From 6ccb5835ff55d85156be91473c598eca9d6cb9a6 Mon Sep 17 00:00:00 2001 From: Elias Fleckenstein Date: Wed, 4 Nov 2020 16:57:41 +0100 Subject: [PATCH] Revert "Make Lint Happy" This reverts commit ad148587dcf5244c2d2011dba339786c765c54c4. --- src/activeobject.h | 60 +- src/ban.cpp | 24 +- src/chat.cpp | 185 +- src/chat.h | 43 +- src/chat_interface.h | 51 +- src/client/camera.cpp | 336 ++- src/client/camera.h | 94 +- src/client/client.cpp | 792 +++--- src/client/client.h | 277 ++- src/client/clientenvironment.cpp | 198 +- src/client/clientenvironment.h | 39 +- src/client/clientlauncher.cpp | 131 +- src/client/clientlauncher.h | 2 +- src/client/clientmap.cpp | 240 +- src/client/clientmap.h | 50 +- src/client/clientmedia.cpp | 193 +- src/client/clientmedia.h | 43 +- src/client/clientobject.cpp | 17 +- src/client/clientobject.h | 27 +- src/client/clouds.cpp | 375 +-- src/client/clouds.h | 42 +- src/client/content_cao.cpp | 798 +++--- src/client/content_cao.h | 97 +- src/client/content_cso.cpp | 36 +- src/client/content_cso.h | 4 +- src/client/content_mapblock.cpp | 975 ++++---- src/client/content_mapblock.h | 61 +- src/client/filecache.cpp | 27 +- src/client/fontengine.cpp | 152 +- src/client/fontengine.h | 54 +- src/client/game.cpp | 1398 +++++------ src/client/game.h | 318 +-- src/client/gameui.cpp | 156 +- src/client/gameui.h | 5 +- src/client/guiscalingfilter.cpp | 68 +- src/client/guiscalingfilter.h | 11 +- src/client/hud.cpp | 644 +++-- src/client/hud.h | 32 +- src/client/imagefilters.cpp | 207 +- src/client/imagefilters.h | 3 +- src/client/inputhandler.h | 22 +- src/client/joystick_controller.cpp | 96 +- src/client/joystick_controller.h | 62 +- src/client/keycode.cpp | 377 +-- src/client/keys.h | 2 +- src/client/localplayer.cpp | 255 +- src/client/localplayer.h | 40 +- src/client/mapblock_mesh.cpp | 659 +++-- src/client/mapblock_mesh.h | 47 +- src/client/mesh.cpp | 934 +++---- src/client/mesh.h | 29 +- src/client/mesh_generator_thread.cpp | 113 +- src/client/minimap.cpp | 353 ++- src/client/minimap.h | 34 +- src/client/particles.cpp | 287 ++- src/client/particles.h | 82 +- src/client/render/core.cpp | 37 +- src/client/render/interlaced.cpp | 4 +- src/client/render/plain.cpp | 4 +- src/client/render/sidebyside.cpp | 7 +- src/client/render/stereo.cpp | 4 +- src/client/renderingengine.cpp | 67 +- src/client/renderingengine.h | 6 +- src/client/shader.cpp | 381 +-- src/client/shader.h | 107 +- src/client/sky.cpp | 551 ++--- src/client/sky.h | 55 +- src/client/sound_openal.cpp | 229 +- src/client/tile.cpp | 1012 ++++---- src/client/tile.h | 96 +- src/client/wieldmesh.cpp | 365 ++- src/clientiface.cpp | 230 +- src/clientiface.h | 156 +- src/collision.cpp | 514 ++-- src/collision.h | 23 +- src/config.h | 33 +- src/content_mapnode.cpp | 88 +- src/content_nodemeta.cpp | 115 +- src/content_nodemeta.h | 5 +- src/convert_json.cpp | 12 +- src/convert_json.h | 4 +- src/craftdef.cpp | 368 ++- src/craftdef.h | 139 +- src/database/database-dummy.cpp | 2 + src/database/database-files.cpp | 9 +- src/database/database-leveldb.cpp | 67 +- src/database/database-postgresql.cpp | 433 ++-- src/database/database-postgresql.h | 36 +- src/database/database-redis.cpp | 85 +- src/database/database-sqlite3.cpp | 377 ++- src/database/database-sqlite3.h | 22 +- src/database/database.cpp | 9 +- src/daynightratio.h | 18 +- src/debug.cpp | 55 +- src/debug.h | 72 +- src/defaultsettings.cpp | 53 +- src/emerge.cpp | 244 +- src/emerge.h | 66 +- src/environment.cpp | 223 +- src/exceptions.h | 104 +- src/face_position_cache.cpp | 63 +- src/face_position_cache.h | 3 +- src/filesys.cpp | 282 +-- src/filesys.h | 10 +- src/gamedef.h | 38 +- src/gettext.cpp | 123 +- src/gettext.h | 28 +- src/gui/StyleSpec.h | 31 +- src/gui/cheatMenu.cpp | 79 +- src/gui/cheatMenu.h | 13 +- src/gui/guiAnimatedImage.cpp | 16 +- src/gui/guiAnimatedImage.h | 9 +- src/gui/guiBackgroundImage.cpp | 15 +- src/gui/guiBackgroundImage.h | 5 +- src/gui/guiBox.cpp | 10 +- src/gui/guiBox.h | 2 +- src/gui/guiButton.cpp | 466 ++-- src/gui/guiButton.h | 251 +- src/gui/guiButtonImage.cpp | 20 +- src/gui/guiButtonImage.h | 4 +- src/gui/guiButtonItemImage.cpp | 11 +- src/gui/guiButtonItemImage.h | 4 +- src/gui/guiChatConsole.cpp | 389 +-- src/gui/guiChatConsole.h | 25 +- src/gui/guiConfirmRegistration.cpp | 24 +- src/gui/guiEditBoxWithScrollbar.cpp | 586 ++--- src/gui/guiEditBoxWithScrollbar.h | 35 +- src/gui/guiEngine.cpp | 208 +- src/gui/guiEngine.h | 79 +- src/gui/guiFormSpecMenu.cpp | 2045 ++++++++-------- src/gui/guiFormSpecMenu.h | 207 +- src/gui/guiHyperText.cpp | 161 +- src/gui/guiHyperText.h | 7 +- src/gui/guiInventoryList.cpp | 108 +- src/gui/guiInventoryList.h | 42 +- src/gui/guiItemImage.cpp | 11 +- src/gui/guiItemImage.h | 9 +- src/gui/guiKeyChangeMenu.cpp | 289 +-- src/gui/guiMainMenu.h | 6 +- src/gui/guiPasswordChange.cpp | 37 +- src/gui/guiPathSelectMenu.cpp | 14 +- src/gui/guiScrollBar.cpp | 17 +- src/gui/guiSkin.cpp | 475 ++-- src/gui/guiSkin.h | 652 ++--- src/gui/guiTable.cpp | 361 +-- src/gui/guiTable.h | 35 +- src/gui/guiVolumeChange.cpp | 58 +- src/gui/guiVolumeChange.h | 5 +- src/gui/intlGUIEditBox.cpp | 1072 ++++---- src/gui/intlGUIEditBox.h | 306 +-- src/gui/mainmenumanager.h | 48 +- src/gui/modalMenu.h | 8 +- src/gui/touchscreengui.cpp | 682 +++--- src/httpfetch.cpp | 226 +- src/hud.cpp | 69 +- src/hud.h | 37 +- src/inventory.cpp | 320 +-- src/inventory.h | 91 +- src/inventorymanager.cpp | 313 +-- src/inventorymanager.h | 77 +- src/irrlicht_changes/CGUITTFont.cpp | 723 +++--- src/irrlicht_changes/CGUITTFont.h | 679 +++--- src/irrlicht_changes/irrUString.h | 2552 +++++++++++--------- src/irrlicht_changes/static_text.cpp | 329 +-- src/irrlicht_changes/static_text.h | 315 +-- src/irrlichttypes.h | 38 +- src/itemdef.cpp | 153 +- src/itemdef.h | 70 +- src/itemstackmetadata.cpp | 7 +- src/light.cpp | 30 +- src/log.cpp | 110 +- src/log.h | 84 +- src/main.cpp | 373 ++- src/map.cpp | 1044 ++++---- src/map.h | 116 +- src/map_settings_manager.cpp | 49 +- src/map_settings_manager.h | 17 +- src/mapblock.cpp | 433 ++-- src/mapblock.h | 239 +- src/mapgen/cavegen.cpp | 432 ++-- src/mapgen/cavegen.h | 25 +- src/mapgen/dungeongen.cpp | 451 ++-- src/mapgen/dungeongen.h | 24 +- src/mapgen/mapgen.cpp | 704 +++--- src/mapgen/mapgen.h | 60 +- src/mapgen/mapgen_carpathian.cpp | 475 ++-- src/mapgen/mapgen_carpathian.h | 35 +- src/mapgen/mapgen_flat.cpp | 207 +- src/mapgen/mapgen_fractal.cpp | 196 +- src/mapgen/mapgen_fractal.h | 4 +- src/mapgen/mapgen_singlenode.cpp | 31 +- src/mapgen/mapgen_v5.cpp | 168 +- src/mapgen/mapgen_v6.cpp | 955 ++++---- src/mapgen/mapgen_v6.h | 26 +- src/mapgen/mapgen_v7.cpp | 447 ++-- src/mapgen/mapgen_v7.h | 16 +- src/mapgen/mapgen_valleys.cpp | 488 ++-- src/mapgen/mapgen_valleys.h | 19 +- src/mapgen/mg_biome.cpp | 181 +- src/mapgen/mg_biome.h | 65 +- src/mapgen/mg_decoration.cpp | 308 +-- src/mapgen/mg_decoration.h | 45 +- src/mapgen/mg_ore.cpp | 423 ++-- src/mapgen/mg_ore.h | 91 +- src/mapgen/mg_schematic.cpp | 221 +- src/mapgen/mg_schematic.h | 55 +- src/mapgen/treegen.cpp | 644 ++--- src/mapgen/treegen.h | 120 +- src/mapnode.cpp | 436 ++-- src/mapnode.h | 80 +- src/mapsector.cpp | 18 +- src/mapsector.h | 16 +- src/metadata.h | 17 +- src/network/address.cpp | 2 +- src/network/clientopcodes.cpp | 414 ++-- src/network/clientopcodes.h | 11 +- src/network/clientpackethandler.cpp | 616 ++--- src/network/connection.cpp | 525 ++-- src/network/connection.h | 392 ++- src/network/connectionthreads.cpp | 779 +++--- src/network/networkpacket.cpp | 132 +- src/network/networkprotocol.h | 151 +- src/network/serveropcodes.cpp | 396 ++- src/network/serveropcodes.h | 11 +- src/network/serverpackethandler.cpp | 745 +++--- src/nodedef.cpp | 544 +++-- src/nodedef.h | 103 +- src/nodemetadata.cpp | 30 +- src/nodemetadata.h | 27 +- src/nodetimer.cpp | 24 +- src/nodetimer.h | 40 +- src/noise.cpp | 277 ++- src/noise.h | 159 +- src/objdef.cpp | 42 +- src/objdef.h | 15 +- src/object_properties.cpp | 26 +- src/particles.cpp | 22 +- src/particles.h | 15 +- src/pathfinder.cpp | 720 +++--- src/pathfinder.h | 22 +- src/player.cpp | 65 +- src/player.h | 68 +- src/porting.cpp | 210 +- src/porting.h | 189 +- src/porting_android.cpp | 136 +- src/porting_android.h | 7 +- src/profiler.h | 14 +- src/raycast.cpp | 56 +- src/raycast.h | 8 +- src/reflowscan.cpp | 63 +- src/reflowscan.h | 3 +- src/remoteplayer.cpp | 85 +- src/rollback.cpp | 627 ++--- src/rollback.h | 82 +- src/rollback_interface.cpp | 81 +- src/rollback_interface.h | 40 +- src/script/common/c_content.cpp | 824 +++---- src/script/common/c_content.h | 188 +- src/script/common/c_converter.cpp | 150 +- src/script/common/c_converter.h | 136 +- src/script/common/c_internal.cpp | 24 +- src/script/common/c_internal.h | 35 +- src/script/common/c_types.cpp | 6 +- src/script/common/c_types.h | 6 +- src/script/cpp_api/s_async.cpp | 44 +- src/script/cpp_api/s_async.h | 14 +- src/script/cpp_api/s_base.cpp | 116 +- src/script/cpp_api/s_base.h | 73 +- src/script/cpp_api/s_client.cpp | 15 +- src/script/cpp_api/s_entity.cpp | 53 +- src/script/cpp_api/s_entity.h | 24 +- src/script/cpp_api/s_env.cpp | 43 +- src/script/cpp_api/s_env.h | 4 +- src/script/cpp_api/s_internal.h | 30 +- src/script/cpp_api/s_inventory.cpp | 84 +- src/script/cpp_api/s_inventory.h | 22 +- src/script/cpp_api/s_item.cpp | 44 +- src/script/cpp_api/s_item.h | 28 +- src/script/cpp_api/s_mainmenu.h | 3 +- src/script/cpp_api/s_node.cpp | 59 +- src/script/cpp_api/s_node.h | 18 +- src/script/cpp_api/s_nodemeta.cpp | 98 +- src/script/cpp_api/s_nodemeta.h | 24 +- src/script/cpp_api/s_player.cpp | 66 +- src/script/cpp_api/s_player.h | 41 +- src/script/cpp_api/s_security.cpp | 360 +-- src/script/cpp_api/s_security.h | 30 +- src/script/cpp_api/s_server.cpp | 27 +- src/script/cpp_api/s_server.h | 20 +- src/script/lua_api/l_areastore.cpp | 55 +- src/script/lua_api/l_base.cpp | 24 +- src/script/lua_api/l_base.h | 39 +- src/script/lua_api/l_client.cpp | 38 +- src/script/lua_api/l_clientobject.cpp | 7 +- src/script/lua_api/l_clientobject.h | 2 +- src/script/lua_api/l_craft.cpp | 188 +- src/script/lua_api/l_craft.h | 13 +- src/script/lua_api/l_env.cpp | 298 ++- src/script/lua_api/l_env.h | 84 +- src/script/lua_api/l_http.cpp | 24 +- src/script/lua_api/l_http.h | 6 +- src/script/lua_api/l_internal.h | 41 +- src/script/lua_api/l_inventory.cpp | 119 +- src/script/lua_api/l_inventory.h | 24 +- src/script/lua_api/l_inventoryaction.cpp | 45 +- src/script/lua_api/l_inventoryaction.h | 34 +- src/script/lua_api/l_item.cpp | 112 +- src/script/lua_api/l_item.h | 20 +- src/script/lua_api/l_itemstackmeta.cpp | 43 +- src/script/lua_api/l_itemstackmeta.h | 10 +- src/script/lua_api/l_localplayer.cpp | 33 +- src/script/lua_api/l_mainmenu.cpp | 349 +-- src/script/lua_api/l_mainmenu.h | 19 +- src/script/lua_api/l_mapgen.cpp | 593 ++--- src/script/lua_api/l_mapgen.h | 2 +- src/script/lua_api/l_metadata.cpp | 14 +- src/script/lua_api/l_minimap.cpp | 40 +- src/script/lua_api/l_nodemeta.cpp | 89 +- src/script/lua_api/l_nodemeta.h | 8 +- src/script/lua_api/l_nodetimer.cpp | 46 +- src/script/lua_api/l_noise.cpp | 120 +- src/script/lua_api/l_object.cpp | 514 ++-- src/script/lua_api/l_object.h | 13 +- src/script/lua_api/l_particles.cpp | 47 +- src/script/lua_api/l_particles.h | 3 +- src/script/lua_api/l_particles_local.cpp | 38 +- src/script/lua_api/l_rollback.cpp | 13 +- src/script/lua_api/l_rollback.h | 3 +- src/script/lua_api/l_server.cpp | 92 +- src/script/lua_api/l_settings.cpp | 105 +- src/script/lua_api/l_sound.cpp | 1 + src/script/lua_api/l_storage.cpp | 43 +- src/script/lua_api/l_util.cpp | 35 +- src/script/lua_api/l_vmanip.cpp | 98 +- src/script/scripting_client.cpp | 3 +- src/script/scripting_client.h | 11 +- src/script/scripting_mainmenu.cpp | 10 +- src/script/scripting_mainmenu.h | 7 +- src/script/scripting_server.cpp | 12 +- src/script/scripting_server.h | 21 +- src/serialization.cpp | 180 +- src/serialization.h | 5 +- src/server.cpp | 1146 +++++---- src/server.h | 221 +- src/server/luaentity_sao.cpp | 198 +- src/server/player_sao.cpp | 123 +- src/server/serveractiveobject.cpp | 11 +- src/server/serveractiveobject.h | 128 +- src/serverenvironment.cpp | 897 ++++--- src/serverenvironment.h | 124 +- src/serverlist.cpp | 79 +- src/serverlist.h | 10 +- src/settings.cpp | 237 +- src/settings.h | 72 +- src/settings_translation_file.cpp | 1014 ++------ src/staticobject.cpp | 27 +- src/staticobject.h | 21 +- src/terminal_chat_console.cpp | 330 +-- src/terminal_chat_console.h | 34 +- src/texture_override.cpp | 42 +- src/threading/event.cpp | 1 + src/threading/semaphore.cpp | 74 +- src/threading/thread.cpp | 86 +- src/threading/thread.h | 25 +- src/tileanimation.cpp | 22 +- src/tileanimation.h | 4 +- src/tool.cpp | 38 +- src/tool.h | 54 +- src/translation.cpp | 16 +- src/unittest/test.cpp | 89 +- src/unittest/test.h | 120 +- src/unittest/test_areastore.cpp | 35 +- src/unittest/test_collision.cpp | 293 +-- src/unittest/test_compression.cpp | 67 +- src/unittest/test_connection.cpp | 59 +- src/unittest/test_filepath.cpp | 117 +- src/unittest/test_inventory.cpp | 88 +- src/unittest/test_keycode.cpp | 6 +- src/unittest/test_map_settings_manager.cpp | 39 +- src/unittest/test_noderesolver.cpp | 47 +- src/unittest/test_noise.cpp | 1293 ++-------- src/unittest/test_random.cpp | 667 +---- src/unittest/test_schematic.cpp | 256 +- src/unittest/test_serialization.cpp | 307 +-- src/unittest/test_settings.cpp | 314 +-- src/unittest/test_socket.cpp | 21 +- src/unittest/test_threading.cpp | 21 +- src/unittest/test_utilities.cpp | 197 +- src/unittest/test_voxelalgorithms.cpp | 25 +- src/unittest/test_voxelmanipulator.cpp | 35 +- src/util/areastore.cpp | 90 +- src/util/areastore.h | 57 +- src/util/auth.cpp | 45 +- src/util/auth.h | 23 +- src/util/base64.cpp | 74 +- src/util/base64.h | 6 +- src/util/basic_macros.h | 15 +- src/util/container.h | 56 +- src/util/directiontables.cpp | 171 +- src/util/directiontables.h | 26 +- src/util/enriched_string.cpp | 15 +- src/util/enriched_string.h | 31 +- src/util/md32_common.h | 461 ++-- src/util/numeric.cpp | 48 +- src/util/numeric.h | 137 +- src/util/pointedthing.cpp | 64 +- src/util/pointedthing.h | 5 +- src/util/pointer.h | 103 +- src/util/quicktune.cpp | 22 +- src/util/quicktune.h | 33 +- src/util/quicktune_shortcutter.h | 26 +- src/util/serialize.cpp | 471 ++-- src/util/serialize.h | 280 +-- src/util/sha1.cpp | 117 +- src/util/srp.cpp | 352 ++- src/util/srp.h | 21 +- src/util/strfnd.h | 16 +- src/util/string.cpp | 419 ++-- src/util/string.h | 149 +- src/util/thread.h | 75 +- src/util/timetaker.cpp | 16 +- src/util/timetaker.h | 11 +- src/version.cpp | 32 +- src/voxel.cpp | 168 +- src/voxel.h | 203 +- src/voxelalgorithms.cpp | 847 +++---- src/voxelalgorithms.h | 27 +- 427 files changed, 35360 insertions(+), 36563 deletions(-) diff --git a/src/activeobject.h b/src/activeobject.h index 50d3525e9..85e160d10 100644 --- a/src/activeobject.h +++ b/src/activeobject.h @@ -23,41 +23,39 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irr_v3d.h" #include -enum ActiveObjectType -{ + +enum ActiveObjectType { ACTIVEOBJECT_TYPE_INVALID = 0, ACTIVEOBJECT_TYPE_TEST = 1, - // Obsolete stuff +// Obsolete stuff ACTIVEOBJECT_TYPE_ITEM = 2, - // ACTIVEOBJECT_TYPE_RAT = 3, - // ACTIVEOBJECT_TYPE_OERKKI1 = 4, - // ACTIVEOBJECT_TYPE_FIREFLY = 5, +// ACTIVEOBJECT_TYPE_RAT = 3, +// ACTIVEOBJECT_TYPE_OERKKI1 = 4, +// ACTIVEOBJECT_TYPE_FIREFLY = 5, ACTIVEOBJECT_TYPE_MOBV2 = 6, - // End obsolete stuff +// End obsolete stuff ACTIVEOBJECT_TYPE_LUAENTITY = 7, - // Special type, not stored as a static object +// Special type, not stored as a static object ACTIVEOBJECT_TYPE_PLAYER = 100, - // Special type, only exists as CAO +// Special type, only exists as CAO ACTIVEOBJECT_TYPE_GENERIC = 101, }; // Other types are defined in content_object.h struct ActiveObjectMessage { - ActiveObjectMessage( - u16 id_, bool reliable_ = true, const std::string &data_ = "") : - id(id_), - reliable(reliable_), datastring(data_) - { - } + ActiveObjectMessage(u16 id_, bool reliable_=true, const std::string &data_ = "") : + id(id_), + reliable(reliable_), + datastring(data_) + {} u16 id; bool reliable; std::string datastring; }; -enum ActiveObjectCommand -{ +enum ActiveObjectCommand { AO_CMD_SET_PROPERTIES, AO_CMD_UPDATE_POSITION, AO_CMD_SET_TEXTURE_MOD, @@ -80,14 +78,24 @@ enum ActiveObjectCommand class ActiveObject { public: - ActiveObject(u16 id) : m_id(id) {} + ActiveObject(u16 id): + m_id(id) + { + } - u16 getId() const { return m_id; } + u16 getId() const + { + return m_id; + } - void setId(u16 id) { m_id = id; } + void setId(u16 id) + { + m_id = id; + } virtual ActiveObjectType getType() const = 0; + /*! * Returns the collision box of the object. * This box is translated by the object's @@ -97,6 +105,7 @@ class ActiveObject */ virtual bool getCollisionBox(aabb3f *toset) const = 0; + /*! * Returns the selection box of the object. * This box is not translated when the @@ -106,21 +115,18 @@ class ActiveObject */ virtual bool getSelectionBox(aabb3f *toset) const = 0; + virtual bool collideWithObjects() const = 0; + virtual void setAttachment(int parent_id, const std::string &bone, v3f position, - v3f rotation) - { - } + v3f rotation) {} virtual void getAttachment(int *parent_id, std::string *bone, v3f *position, - v3f *rotation) const - { - } + v3f *rotation) const {} virtual void clearChildAttachments() {} virtual void clearParentAttachment() {} virtual void addAttachmentChild(int child_id) {} virtual void removeAttachmentChild(int child_id) {} - protected: u16 m_id; // 0 is invalid, "no id" }; diff --git a/src/ban.cpp b/src/ban.cpp index a6623574f..3decc9666 100644 --- a/src/ban.cpp +++ b/src/ban.cpp @@ -28,12 +28,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "filesys.h" -BanManager::BanManager(const std::string &banfilepath) : m_banfilepath(banfilepath) +BanManager::BanManager(const std::string &banfilepath): + m_banfilepath(banfilepath) { try { load(); - } catch (SerializationError &e) { - infostream << "BanManager: creating " << m_banfilepath << std::endl; + } catch(SerializationError &e) { + infostream << "BanManager: creating " + << m_banfilepath << std::endl; } } @@ -45,11 +47,10 @@ BanManager::~BanManager() void BanManager::load() { MutexAutoLock lock(m_mutex); - infostream << "BanManager: loading from " << m_banfilepath << std::endl; + infostream<<"BanManager: loading from "< 0 && del_unformatted < m_unformatted.size()) { + while (count > 0 && del_unformatted < m_unformatted.size()) + { ++del_unformatted; // keep m_formatted in sync - if (del_formatted < m_formatted.size()) { + if (del_formatted < m_formatted.size()) + { sanity_check(m_formatted[del_formatted].first); ++del_formatted; @@ -103,8 +106,7 @@ void ChatBuffer::deleteOldest(u32 count) --count; } - m_unformatted.erase( - m_unformatted.begin(), m_unformatted.begin() + del_unformatted); + m_unformatted.erase(m_unformatted.begin(), m_unformatted.begin() + del_unformatted); m_formatted.erase(m_formatted.begin(), m_formatted.begin() + del_formatted); if (at_bottom) @@ -133,13 +135,16 @@ u32 ChatBuffer::getRows() const void ChatBuffer::reformat(u32 cols, u32 rows) { - if (cols == 0 || rows == 0) { + if (cols == 0 || rows == 0) + { // Clear formatted buffer m_cols = 0; m_rows = 0; m_scroll = 0; m_formatted.clear(); - } else if (cols != m_cols || rows != m_rows) { + } + else if (cols != m_cols || rows != m_rows) + { // TODO: Avoid reformatting ALL lines (even invisible ones) // each time the console size changes. @@ -147,17 +152,21 @@ void ChatBuffer::reformat(u32 cols, u32 rows) u32 restore_scroll_unformatted = 0; u32 restore_scroll_formatted = 0; bool at_bottom = (m_scroll == getBottomScrollPos()); - if (!at_bottom) { - for (s32 i = 0; i < m_scroll; ++i) { + if (!at_bottom) + { + for (s32 i = 0; i < m_scroll; ++i) + { if (m_formatted[i].first) ++restore_scroll_unformatted; } } // If number of columns change, reformat everything - if (cols != m_cols) { + if (cols != m_cols) + { m_formatted.clear(); - for (u32 i = 0; i < m_unformatted.size(); ++i) { + for (u32 i = 0; i < m_unformatted.size(); ++i) + { if (i == restore_scroll_unformatted) restore_scroll_formatted = m_formatted.size(); formatChatLine(m_unformatted[i], cols, m_formatted); @@ -169,18 +178,21 @@ void ChatBuffer::reformat(u32 cols, u32 rows) m_rows = rows; // Restore the scroll position - if (at_bottom) { + if (at_bottom) + { scrollBottom(); - } else { + } + else + { scrollAbsolute(restore_scroll_formatted); } } } -const ChatFormattedLine &ChatBuffer::getFormattedLine(u32 row) const +const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const { - s32 index = m_scroll + (s32)row; - if (index >= 0 && index < (s32)m_formatted.size()) + s32 index = m_scroll + (s32) row; + if (index >= 0 && index < (s32) m_formatted.size()) return m_formatted[index]; return m_empty_formatted_line; @@ -213,8 +225,8 @@ void ChatBuffer::scrollTop() m_scroll = getTopScrollPos(); } -u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, - std::vector &destination) const +u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols, + std::vector& destination) const { u32 num_added = 0; std::vector next_frags; @@ -228,15 +240,15 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, if (!line.name.empty()) { temp_frag.text = L"<"; temp_frag.column = 0; - // temp_frag.bold = 0; + //temp_frag.bold = 0; next_frags.push_back(temp_frag); temp_frag.text = line.name; temp_frag.column = 0; - // temp_frag.bold = 1; + //temp_frag.bold = 1; next_frags.push_back(temp_frag); temp_frag.text = L"> "; temp_frag.column = 0; - // temp_frag.bold = 0; + //temp_frag.bold = 0; next_frags.push_back(temp_frag); } @@ -246,40 +258,46 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, if (line.name.empty()) { // Server messages hanging_indentation = 0; - } else if (name_sanitized.size() + 3 <= cols / 2) { + } else if (name_sanitized.size() + 3 <= cols/2) { // Names shorter than about half the console width hanging_indentation = line.name.size() + 3; } else { // Very long names hanging_indentation = 2; } - // EnrichedString line_text(line.text); + //EnrichedString line_text(line.text); next_line.first = true; bool text_processing = false; // Produce fragments and layout them into lines - while (!next_frags.empty() || in_pos < line.text.size()) { + while (!next_frags.empty() || in_pos < line.text.size()) + { // Layout fragments into lines - while (!next_frags.empty()) { - ChatFormattedFragment &frag = next_frags[0]; - if (frag.text.size() <= cols - out_column) { + while (!next_frags.empty()) + { + ChatFormattedFragment& frag = next_frags[0]; + if (frag.text.size() <= cols - out_column) + { // Fragment fits into current line frag.column = out_column; next_line.fragments.push_back(frag); out_column += frag.text.size(); next_frags.erase(next_frags.begin()); - } else { + } + else + { // Fragment does not fit into current line // So split it up temp_frag.text = frag.text.substr(0, cols - out_column); temp_frag.column = out_column; - // temp_frag.bold = frag.bold; + //temp_frag.bold = frag.bold; next_line.fragments.push_back(temp_frag); frag.text = frag.text.substr(cols - out_column); out_column = cols; } - if (out_column == cols || text_processing) { + if (out_column == cols || text_processing) + { // End the current line destination.push_back(next_line); num_added++; @@ -291,7 +309,8 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, } // Produce fragment - if (in_pos < line.text.size()) { + if (in_pos < line.text.size()) + { u32 remaining_in_input = line.text.size() - in_pos; u32 remaining_in_output = cols - out_column; @@ -300,7 +319,8 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, // on a word boundary. u32 frag_length = 1, space_pos = 0; while (frag_length < remaining_in_input && - frag_length < remaining_in_output) { + frag_length < remaining_in_output) + { if (iswspace(line.text.getString()[in_pos + frag_length])) space_pos = frag_length; ++frag_length; @@ -310,7 +330,7 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, temp_frag.text = line.text.substr(in_pos, frag_length); temp_frag.column = 0; - // temp_frag.bold = 0; + //temp_frag.bold = 0; next_frags.push_back(temp_frag); in_pos += frag_length; text_processing = true; @@ -318,7 +338,8 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, } // End the last line - if (num_added == 0 || !next_line.fragments.empty()) { + if (num_added == 0 || !next_line.fragments.empty()) + { destination.push_back(next_line); num_added++; } @@ -328,8 +349,8 @@ u32 ChatBuffer::formatChatLine(const ChatLine &line, u32 cols, s32 ChatBuffer::getTopScrollPos() const { - s32 formatted_count = (s32)m_formatted.size(); - s32 rows = (s32)m_rows; + s32 formatted_count = (s32) m_formatted.size(); + s32 rows = (s32) m_rows; if (rows == 0) return 0; @@ -341,8 +362,8 @@ s32 ChatBuffer::getTopScrollPos() const s32 ChatBuffer::getBottomScrollPos() const { - s32 formatted_count = (s32)m_formatted.size(); - s32 rows = (s32)m_rows; + s32 formatted_count = (s32) m_formatted.size(); + s32 rows = (s32) m_rows; if (rows == 0) return 0; @@ -356,8 +377,10 @@ void ChatBuffer::resize(u32 scrollback) deleteOldest(m_unformatted.size() - m_scrollback); } -ChatPrompt::ChatPrompt(const std::wstring &prompt, u32 history_limit) : - m_prompt(prompt), m_history_limit(history_limit) + +ChatPrompt::ChatPrompt(const std::wstring &prompt, u32 history_limit): + m_prompt(prompt), + m_history_limit(history_limit) { } @@ -381,10 +404,11 @@ void ChatPrompt::input(const std::wstring &str) void ChatPrompt::addToHistory(const std::wstring &line) { - if (!line.empty() && (m_history.size() == 0 || m_history.back() != line)) { + if (!line.empty() && + (m_history.size() == 0 || m_history.back() != line)) { // Remove all duplicates - m_history.erase(std::remove(m_history.begin(), m_history.end(), line), - m_history.end()); + m_history.erase(std::remove(m_history.begin(), m_history.end(), + line), m_history.end()); // Push unique line m_history.push_back(line); } @@ -405,7 +429,7 @@ void ChatPrompt::clear() std::wstring ChatPrompt::replace(const std::wstring &line) { std::wstring old_line = m_line; - m_line = line; + m_line = line; m_view = m_cursor = line.size(); clampView(); m_nick_completion_start = 0; @@ -415,7 +439,8 @@ std::wstring ChatPrompt::replace(const std::wstring &line) void ChatPrompt::historyPrev() { - if (m_history_index != 0) { + if (m_history_index != 0) + { --m_history_index; replace(m_history[m_history_index]); } @@ -423,16 +448,19 @@ void ChatPrompt::historyPrev() void ChatPrompt::historyNext() { - if (m_history_index + 1 >= m_history.size()) { + if (m_history_index + 1 >= m_history.size()) + { m_history_index = m_history.size(); replace(L""); - } else { + } + else + { ++m_history_index; replace(m_history[m_history_index]); } } -void ChatPrompt::nickCompletion(const std::list &names, bool backwards) +void ChatPrompt::nickCompletion(const std::list& names, bool backwards) { // Two cases: // (a) m_nick_completion_start == m_nick_completion_end == 0 @@ -446,10 +474,11 @@ void ChatPrompt::nickCompletion(const std::list &names, bool backwa u32 prefix_start = m_nick_completion_start; u32 prefix_end = m_nick_completion_end; bool initial = (prefix_end == 0); - if (initial) { + if (initial) + { // no previous nick completion is active prefix_start = prefix_end = m_cursor; - while (prefix_start > 0 && !iswspace(m_line[prefix_start - 1])) + while (prefix_start > 0 && !iswspace(m_line[prefix_start-1])) --prefix_start; while (prefix_end < m_line.size() && !iswspace(m_line[prefix_end])) ++prefix_end; @@ -475,14 +504,17 @@ void ChatPrompt::nickCompletion(const std::list &names, bool backwa // find a replacement string and the word that will be replaced u32 word_end = prefix_end; u32 replacement_index = 0; - if (!initial) { + if (!initial) + { while (word_end < m_line.size() && !iswspace(m_line[word_end])) ++word_end; std::wstring word = m_line.substr(prefix_start, word_end - prefix_start); // cycle through completions - for (u32 i = 0; i < completions.size(); ++i) { - if (str_equal(word, completions[i], true)) { + for (u32 i = 0; i < completions.size(); ++i) + { + if (str_equal(word, completions[i], true)) + { if (backwards) replacement_index = i + completions.size() - 1; else @@ -507,10 +539,13 @@ void ChatPrompt::nickCompletion(const std::list &names, bool backwa void ChatPrompt::reformat(u32 cols) { - if (cols <= m_prompt.size()) { + if (cols <= m_prompt.size()) + { m_cols = 0; m_view = m_cursor; - } else { + } + else + { s32 length = m_line.size(); bool was_at_end = (m_view + m_cols >= length + 1); m_cols = cols - m_prompt.size(); @@ -603,9 +638,12 @@ void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope sco void ChatPrompt::clampView() { s32 length = m_line.size(); - if (length + 1 <= m_cols) { + if (length + 1 <= m_cols) + { m_view = 0; - } else { + } + else + { m_view = MYMIN(m_view, length + 1 - m_cols); m_view = MYMIN(m_view, m_cursor); m_view = MYMAX(m_view, m_cursor - m_cols + 1); @@ -613,8 +651,12 @@ void ChatPrompt::clampView() } } -ChatBackend::ChatBackend() : - m_console_buffer(500), m_recent_buffer(6), m_prompt(L"]", 500) + + +ChatBackend::ChatBackend(): + m_console_buffer(500), + m_recent_buffer(6), + m_prompt(L"]", 500) { } @@ -623,7 +665,8 @@ void ChatBackend::addMessage(const std::wstring &name, std::wstring text) // Note: A message may consist of multiple lines, for example the MOTD. text = translate_string(text); WStrfnd fnd(text); - while (!fnd.at_end()) { + while (!fnd.at_end()) + { std::wstring line = fnd.next(L"\n"); m_console_buffer.addLine(name, line); m_recent_buffer.addLine(name, line); @@ -635,10 +678,13 @@ void ChatBackend::addUnparsedMessage(std::wstring message) // TODO: Remove the need to parse chat messages client-side, by sending // separate name and text fields in TOCLIENT_CHAT_MESSAGE. - if (message.size() >= 2 && message[0] == L'<') { + if (message.size() >= 2 && message[0] == L'<') + { std::size_t closing = message.find_first_of(L'>', 1); - if (closing != std::wstring::npos && closing + 2 <= message.size() && - message[closing + 1] == L' ') { + if (closing != std::wstring::npos && + closing + 2 <= message.size() && + message[closing+1] == L' ') + { std::wstring name = message.substr(1, closing - 1); std::wstring text = message.substr(closing + 2); addMessage(name, text); @@ -650,12 +696,12 @@ void ChatBackend::addUnparsedMessage(std::wstring message) addMessage(L"", message); } -ChatBuffer &ChatBackend::getConsoleBuffer() +ChatBuffer& ChatBackend::getConsoleBuffer() { return m_console_buffer; } -ChatBuffer &ChatBackend::getRecentBuffer() +ChatBuffer& ChatBackend::getRecentBuffer() { return m_recent_buffer; } @@ -664,7 +710,7 @@ EnrichedString ChatBackend::getRecentChat() const { EnrichedString result; for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i) { - const ChatLine &line = m_recent_buffer.getLine(i); + const ChatLine& line = m_recent_buffer.getLine(i); if (i != 0) result += L"\n"; if (!line.name.empty()) { @@ -677,7 +723,7 @@ EnrichedString ChatBackend::getRecentChat() const return result; } -ChatPrompt &ChatBackend::getPrompt() +ChatPrompt& ChatBackend::getPrompt() { return m_prompt; } @@ -697,6 +743,7 @@ void ChatBackend::clearRecentChat() m_recent_buffer.clear(); } + void ChatBackend::applySettings() { u32 recent_lines = g_settings->getU32("recent_chat_messages"); diff --git a/src/chat.h b/src/chat.h index 9fe910cc9..f84ece206 100644 --- a/src/chat.h +++ b/src/chat.h @@ -38,13 +38,15 @@ struct ChatLine // message text EnrichedString text; - ChatLine(const std::wstring &a_name, const std::wstring &a_text) : - name(a_name), text(a_text) + ChatLine(const std::wstring &a_name, const std::wstring &a_text): + name(a_name), + text(a_text) { } - ChatLine(const EnrichedString &a_name, const EnrichedString &a_text) : - name(a_name), text(a_text) + ChatLine(const EnrichedString &a_name, const EnrichedString &a_text): + name(a_name), + text(a_text) { } }; @@ -56,7 +58,7 @@ struct ChatFormattedFragment // starting column u32 column; // formatting - // u8 bold:1; + //u8 bold:1; }; struct ChatFormattedLine @@ -83,7 +85,7 @@ class ChatBuffer // Get number of lines currently in buffer. u32 getLineCount() const; // Get reference to i-th chat line. - const ChatLine &getLine(u32 index) const; + const ChatLine& getLine(u32 index) const; // Increase each chat line's age by dtime. void step(f32 dtime); @@ -100,7 +102,7 @@ class ChatBuffer void reformat(u32 cols, u32 rows); // Get formatted line for a given row (0 is top of screen). // Only valid after reformat has been called at least once - const ChatFormattedLine &getFormattedLine(u32 row) const; + const ChatFormattedLine& getFormattedLine(u32 row) const; // Scrolling in formatted buffer (relative) // positive rows == scroll up, negative rows == scroll down void scroll(s32 rows); @@ -114,11 +116,10 @@ class ChatBuffer // Format a chat line for the given number of columns. // Appends the formatted lines to the destination array and // returns the number of formatted lines. - u32 formatChatLine(const ChatLine &line, u32 cols, - std::vector &destination) const; + u32 formatChatLine(const ChatLine& line, u32 cols, + std::vector& destination) const; void resize(u32 scrollback); - protected: s32 getTopScrollPos() const; s32 getBottomScrollPos() const; @@ -158,10 +159,7 @@ class ChatPrompt std::wstring getLine() const { return m_line; } // Get section of line that is currently selected - std::wstring getSelection() const - { - return m_line.substr(m_cursor, m_cursor_len); - } + std::wstring getSelection() const { return m_line.substr(m_cursor, m_cursor_len); } // Clear the current line void clear(); @@ -175,7 +173,7 @@ class ChatPrompt void historyNext(); // Nick completion - void nickCompletion(const std::list &names, bool backwards); + void nickCompletion(const std::list& names, bool backwards); // Update console size and reformat the visible portion of the prompt void reformat(u32 cols); @@ -187,23 +185,20 @@ class ChatPrompt s32 getCursorLength() const { return m_cursor_len; } // Cursor operations - enum CursorOp - { + enum CursorOp { CURSOROP_MOVE, CURSOROP_SELECT, CURSOROP_DELETE }; // Cursor operation direction - enum CursorOpDir - { + enum CursorOpDir { CURSOROP_DIR_LEFT, CURSOROP_DIR_RIGHT }; // Cursor operation scope - enum CursorOpScope - { + enum CursorOpScope { CURSOROP_SCOPE_CHARACTER, CURSOROP_SCOPE_WORD, CURSOROP_SCOPE_LINE, @@ -266,13 +261,13 @@ class ChatBackend void addUnparsedMessage(std::wstring line); // Get the console buffer - ChatBuffer &getConsoleBuffer(); + ChatBuffer& getConsoleBuffer(); // Get the recent messages buffer - ChatBuffer &getRecentBuffer(); + ChatBuffer& getRecentBuffer(); // Concatenate all recent messages EnrichedString getRecentChat() const; // Get the console prompt - ChatPrompt &getPrompt(); + ChatPrompt& getPrompt(); // Reformat all buffers void reformat(u32 cols, u32 rows); diff --git a/src/chat_interface.h b/src/chat_interface.h index 5cbb8a927..5dc3d3880 100644 --- a/src/chat_interface.h +++ b/src/chat_interface.h @@ -24,59 +24,56 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "irrlichttypes.h" -enum ChatEventType -{ +enum ChatEventType { CET_CHAT, CET_NICK_ADD, CET_NICK_REMOVE, CET_TIME_INFO, }; -class ChatEvent -{ +class ChatEvent { protected: ChatEvent(ChatEventType a_type) { type = a_type; } - public: ChatEventType type; }; -struct ChatEventTimeInfo : public ChatEvent -{ - ChatEventTimeInfo(u64 a_game_time, u32 a_time) : - ChatEvent(CET_TIME_INFO), game_time(a_game_time), time(a_time) - { - } +struct ChatEventTimeInfo : public ChatEvent { + ChatEventTimeInfo( + u64 a_game_time, + u32 a_time) : + ChatEvent(CET_TIME_INFO), + game_time(a_game_time), + time(a_time) + {} u64 game_time; u32 time; }; -struct ChatEventNick : public ChatEvent -{ +struct ChatEventNick : public ChatEvent { ChatEventNick(ChatEventType a_type, - const std::string &a_nick) : - ChatEvent(a_type), // one of CET_NICK_ADD, CET_NICK_REMOVE - nick(a_nick) - { - } + const std::string &a_nick) : + ChatEvent(a_type), // one of CET_NICK_ADD, CET_NICK_REMOVE + nick(a_nick) + {} std::string nick; }; -struct ChatEventChat : public ChatEvent -{ - ChatEventChat(const std::string &a_nick, const std::wstring &an_evt_msg) : - ChatEvent(CET_CHAT), nick(a_nick), evt_msg(an_evt_msg) - { - } +struct ChatEventChat : public ChatEvent { + ChatEventChat(const std::string &a_nick, + const std::wstring &an_evt_msg) : + ChatEvent(CET_CHAT), + nick(a_nick), + evt_msg(an_evt_msg) + {} std::string nick; std::wstring evt_msg; }; -struct ChatInterface -{ - MutexedQueue command_queue; // chat backend --> server +struct ChatInterface { + MutexedQueue command_queue; // chat backend --> server MutexedQueue outgoing_queue; // server --> chat backend }; diff --git a/src/client/camera.cpp b/src/client/camera.cpp index 9d74447d5..c9e8fab6a 100644 --- a/src/client/camera.cpp +++ b/src/client/camera.cpp @@ -22,13 +22,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client.h" #include "config.h" #include "map.h" -#include "clientmap.h" // MapDrawControl +#include "clientmap.h" // MapDrawControl #include "player.h" #include #include "client/renderingengine.h" #include "settings.h" #include "wieldmesh.h" -#include "noise.h" // easeCurve +#include "noise.h" // easeCurve #include "sound.h" #include "event.h" #include "nodedef.h" @@ -43,8 +43,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #define WIELDMESH_AMPLITUDE_X 7.0f #define WIELDMESH_AMPLITUDE_Y 10.0f -Camera::Camera(MapDrawControl &draw_control, Client *client) : - m_draw_control(draw_control), m_client(client) +Camera::Camera(MapDrawControl &draw_control, Client *client): + m_draw_control(draw_control), + m_client(client) { scene::ISceneManager *smgr = RenderingEngine::get_scene_manager(); // note: making the camera node a child of the player node @@ -75,8 +76,8 @@ Camera::Camera(MapDrawControl &draw_control, Client *client) : m_cache_view_bobbing_amount = g_settings->getFloat("view_bobbing_amount"); // 45 degrees is the lowest FOV that doesn't cause the server to treat this // as a zoom FOV and load world beyond the set server limits. - m_cache_fov = std::fmax(g_settings->getFloat("fov"), 45.0f); - m_arm_inertia = g_settings->getBool("arm_inertia"); + m_cache_fov = std::fmax(g_settings->getFloat("fov"), 45.0f); + m_arm_inertia = g_settings->getBool("arm_inertia"); m_nametags.clear(); } @@ -102,8 +103,7 @@ void Camera::notifyFovChange() if (m_fov_transition_active) m_old_fov_degrees = m_curr_fov_degrees; else - m_old_fov_degrees = - m_server_sent_fov ? m_target_fov_degrees : m_cache_fov; + m_old_fov_degrees = m_server_sent_fov ? m_target_fov_degrees : m_cache_fov; /* * Update m_server_sent_fov next - it corresponds to the target FOV of the @@ -118,8 +118,7 @@ void Camera::notifyFovChange() m_target_fov_degrees = m_cache_fov; } else { m_server_sent_fov = true; - m_target_fov_degrees = - spec.is_multiplier ? m_cache_fov * spec.fov : spec.fov; + m_target_fov_degrees = spec.is_multiplier ? m_cache_fov * spec.fov : spec.fov; } if (spec.transition_time > 0.0f) @@ -163,9 +162,10 @@ inline f32 my_modf(f32 x) void Camera::step(f32 dtime) { - if (m_view_bobbing_fall > 0) { + if(m_view_bobbing_fall > 0) + { m_view_bobbing_fall -= 3 * dtime; - if (m_view_bobbing_fall <= 0) + if(m_view_bobbing_fall <= 0) m_view_bobbing_fall = -1; // Mark the effect as finished } @@ -175,8 +175,9 @@ void Camera::step(f32 dtime) if (m_wield_change_timer >= 0 && was_under_zero) m_wieldnode->setItem(m_wield_item_next, m_client); - if (m_view_bobbing_state != 0) { - // f32 offset = dtime * m_view_bobbing_speed * 0.035; + if (m_view_bobbing_state != 0) + { + //f32 offset = dtime * m_view_bobbing_speed * 0.035; f32 offset = dtime * m_view_bobbing_speed * 0.030; if (m_view_bobbing_state == 2) { // Animation is getting turned off @@ -201,15 +202,15 @@ void Camera::step(f32 dtime) m_view_bobbing_anim = 0; m_view_bobbing_state = 0; } - } else { + } + else { float was = m_view_bobbing_anim; m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset); bool step = (was == 0 || (was < 0.5f && m_view_bobbing_anim >= 0.5f) || (was > 0.5f && m_view_bobbing_anim <= 0.5f)); - if (step) { - m_client->getEventManager()->put(new SimpleTriggerEvent( - MtEvent::VIEW_BOBBING_STEP)); + if(step) { + m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::VIEW_BOBBING_STEP)); } } } @@ -218,18 +219,18 @@ void Camera::step(f32 dtime) f32 offset = dtime * 3.5f; float m_digging_anim_was = m_digging_anim; m_digging_anim += offset; - if (m_digging_anim >= 1) { + if (m_digging_anim >= 1) + { m_digging_anim = 0; m_digging_button = -1; } float lim = 0.15; - if (m_digging_anim_was < lim && m_digging_anim >= lim) { + if(m_digging_anim_was < lim && m_digging_anim >= lim) + { if (m_digging_button == 0) { - m_client->getEventManager()->put(new SimpleTriggerEvent( - MtEvent::CAMERA_PUNCH_LEFT)); - } else if (m_digging_button == 1) { - m_client->getEventManager()->put(new SimpleTriggerEvent( - MtEvent::CAMERA_PUNCH_RIGHT)); + m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_LEFT)); + } else if(m_digging_button == 1) { + m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_RIGHT)); } } } @@ -258,9 +259,8 @@ static inline v2f dir(const v2f &pos_dist) void Camera::addArmInertia(f32 player_yaw) { - m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw, -100.0f, 100.0f) / - 0.016f) * - 0.01f; + m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw, + -100.0f, 100.0f) / 0.016f) * 0.01f; m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / 0.016f); f32 gap_X = std::fabs(WIELDMESH_OFFSET_X - m_wieldmesh_offset.X); f32 gap_Y = std::fabs(WIELDMESH_OFFSET_Y - m_wieldmesh_offset.Y); @@ -276,17 +276,14 @@ void Camera::addArmInertia(f32 player_yaw) m_cam_vel_old.X = m_cam_vel.X; f32 acc_X = 0.12f * (m_cam_vel.X - (gap_X * 0.1f)); - m_wieldmesh_offset.X += - m_last_cam_pos.X < player_yaw ? acc_X : -acc_X; + m_wieldmesh_offset.X += m_last_cam_pos.X < player_yaw ? acc_X : -acc_X; if (m_last_cam_pos.X != player_yaw) m_last_cam_pos.X = player_yaw; m_wieldmesh_offset.X = rangelim(m_wieldmesh_offset.X, - WIELDMESH_OFFSET_X - - (WIELDMESH_AMPLITUDE_X * 0.5f), - WIELDMESH_OFFSET_X + - (WIELDMESH_AMPLITUDE_X * 0.5f)); + WIELDMESH_OFFSET_X - (WIELDMESH_AMPLITUDE_X * 0.5f), + WIELDMESH_OFFSET_X + (WIELDMESH_AMPLITUDE_X * 0.5f)); } if (m_cam_vel.Y > 1.0f) { @@ -294,18 +291,15 @@ void Camera::addArmInertia(f32 player_yaw) m_cam_vel_old.Y = m_cam_vel.Y; f32 acc_Y = 0.12f * (m_cam_vel.Y - (gap_Y * 0.1f)); - m_wieldmesh_offset.Y += m_last_cam_pos.Y > m_camera_direction.Y - ? acc_Y - : -acc_Y; + m_wieldmesh_offset.Y += + m_last_cam_pos.Y > m_camera_direction.Y ? acc_Y : -acc_Y; if (m_last_cam_pos.Y != m_camera_direction.Y) m_last_cam_pos.Y = m_camera_direction.Y; m_wieldmesh_offset.Y = rangelim(m_wieldmesh_offset.Y, - WIELDMESH_OFFSET_Y - - (WIELDMESH_AMPLITUDE_Y * 0.5f), - WIELDMESH_OFFSET_Y + - (WIELDMESH_AMPLITUDE_Y * 0.5f)); + WIELDMESH_OFFSET_Y - (WIELDMESH_AMPLITUDE_Y * 0.5f), + WIELDMESH_OFFSET_Y + (WIELDMESH_AMPLITUDE_Y * 0.5f)); } m_arm_dir = dir(m_wieldmesh_offset); @@ -315,34 +309,27 @@ void Camera::addArmInertia(f32 player_yaw) following a vector, with a smooth deceleration factor. */ - f32 dec_X = 0.35f * - (std::min(15.0f, m_cam_vel_old.X) * - (1.0f + (1.0f - m_arm_dir.X))) * - (gap_X / 20.0f); + f32 dec_X = 0.35f * (std::min(15.0f, m_cam_vel_old.X) * (1.0f + + (1.0f - m_arm_dir.X))) * (gap_X / 20.0f); - f32 dec_Y = 0.25f * - (std::min(15.0f, m_cam_vel_old.Y) * - (1.0f + (1.0f - m_arm_dir.Y))) * - (gap_Y / 15.0f); + f32 dec_Y = 0.25f * (std::min(15.0f, m_cam_vel_old.Y) * (1.0f + + (1.0f - m_arm_dir.Y))) * (gap_Y / 15.0f); if (gap_X < 0.1f) m_cam_vel_old.X = 0.0f; - m_wieldmesh_offset.X -= m_wieldmesh_offset.X > WIELDMESH_OFFSET_X - ? dec_X - : -dec_X; + m_wieldmesh_offset.X -= + m_wieldmesh_offset.X > WIELDMESH_OFFSET_X ? dec_X : -dec_X; if (gap_Y < 0.1f) m_cam_vel_old.Y = 0.0f; - m_wieldmesh_offset.Y -= m_wieldmesh_offset.Y > WIELDMESH_OFFSET_Y - ? dec_Y - : -dec_Y; + m_wieldmesh_offset.Y -= + m_wieldmesh_offset.Y > WIELDMESH_OFFSET_Y ? dec_Y : -dec_Y; } } -void Camera::update( - LocalPlayer *player, f32 frametime, f32 busytime, f32 tool_reload_ratio) +void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio) { // Get player position // Smooth the movement when walking up stairs @@ -353,24 +340,19 @@ void Camera::update( // mods expect the player head to be at the parent's position // plus eye height. if (player->getParent()) - player_position = - player->getParent()->getPosition() + - v3f(0, g_settings->getBool("float_above_parent") ? BS : 0, - 0); - - // Smooth the camera movement when the player instantly moves upward due to - // stepheight. To smooth the 'not touching_ground' stepheight, smoothing is - // necessary when jumping or swimming (for when moving from liquid to land). - // Disable smoothing if climbing or flying, to avoid upwards offset of player - // model when seen in 3rd person view. - bool flying = g_settings->getBool("free_move") && - m_client->checkLocalPrivilege("fly"); - if (player_position.Y > old_player_position.Y && !player->is_climbing && - !flying) { + player_position = player->getParent()->getPosition() + v3f(0, g_settings->getBool("float_above_parent") ? BS : 0, 0); + + // Smooth the camera movement when the player instantly moves upward due to stepheight. + // To smooth the 'not touching_ground' stepheight, smoothing is necessary when jumping + // or swimming (for when moving from liquid to land). + // Disable smoothing if climbing or flying, to avoid upwards offset of player model + // when seen in 3rd person view. + bool flying = g_settings->getBool("free_move") && m_client->checkLocalPrivilege("fly"); + if (player_position.Y > old_player_position.Y && !player->is_climbing && !flying) { f32 oldy = old_player_position.Y; f32 newy = player_position.Y; f32 t = std::exp(-23 * frametime); - player_position.Y = oldy * t + newy * (1 - t); + player_position.Y = oldy * t + newy * (1-t); } // Set player node transformation @@ -379,20 +361,19 @@ void Camera::update( m_playernode->updateAbsolutePosition(); // Get camera tilt timer (hurt animation) - float cameratilt = fabs(fabs(player->hurt_tilt_timer - 0.75) - 0.75); + float cameratilt = fabs(fabs(player->hurt_tilt_timer-0.75)-0.75); // Fall bobbing animation float fall_bobbing = 0; - if (player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD) { - if (m_view_bobbing_fall == -1) // Effect took place and has finished + if(player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD) + { + if(m_view_bobbing_fall == -1) // Effect took place and has finished player->camera_impact = m_view_bobbing_fall = 0; - else if (m_view_bobbing_fall == 0) // Initialize effect + else if(m_view_bobbing_fall == 0) // Initialize effect m_view_bobbing_fall = 1; // Convert 0 -> 1 to 0 -> 1 -> 0 - fall_bobbing = m_view_bobbing_fall < 0.5 - ? m_view_bobbing_fall * 2 - : -(m_view_bobbing_fall - 0.5) * 2 + 1; + fall_bobbing = m_view_bobbing_fall < 0.5 ? m_view_bobbing_fall * 2 : -(m_view_bobbing_fall - 0.5) * 2 + 1; // Smoothen and invert the above fall_bobbing = sin(fall_bobbing * 0.5 * M_PI) * -1; // Amplify according to the intensity of the impact @@ -413,56 +394,60 @@ void Camera::update( eye_offset.Y += cameratilt * -player->hurt_tilt_strength + fall_bobbing; m_headnode->setPosition(eye_offset); m_headnode->setRotation(v3f(player->getPitch(), 0, - cameratilt * player->hurt_tilt_strength)); + cameratilt * player->hurt_tilt_strength)); m_headnode->updateAbsolutePosition(); } // Compute relative camera position and target - v3f rel_cam_pos = v3f(0, 0, 0); - v3f rel_cam_target = v3f(0, 0, 1); - v3f rel_cam_up = v3f(0, 1, 0); + v3f rel_cam_pos = v3f(0,0,0); + v3f rel_cam_target = v3f(0,0,1); + v3f rel_cam_up = v3f(0,1,0); if (m_cache_view_bobbing_amount != 0.0f && m_view_bobbing_anim != 0.0f && - m_camera_mode < CAMERA_MODE_THIRD) { + m_camera_mode < CAMERA_MODE_THIRD) { f32 bobfrac = my_modf(m_view_bobbing_anim * 2); f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0; -#if 1 + #if 1 f32 bobknob = 1.2; f32 bobtmp = sin(pow(bobfrac, bobknob) * M_PI); - // f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI); + //f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI); - v3f bobvec = v3f(0.3 * bobdir * sin(bobfrac * M_PI), - -0.28 * bobtmp * bobtmp, 0.); + v3f bobvec = v3f( + 0.3 * bobdir * sin(bobfrac * M_PI), + -0.28 * bobtmp * bobtmp, + 0.); - // rel_cam_pos += 0.2 * bobvec; - // rel_cam_target += 0.03 * bobvec; - // rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI); + //rel_cam_pos += 0.2 * bobvec; + //rel_cam_target += 0.03 * bobvec; + //rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI); float f = 1.0; f *= m_cache_view_bobbing_amount; rel_cam_pos += bobvec * f; - // rel_cam_target += 0.995 * bobvec * f; + //rel_cam_target += 0.995 * bobvec * f; rel_cam_target += bobvec * f; rel_cam_target.Z -= 0.005 * bobvec.Z * f; - // rel_cam_target.X -= 0.005 * bobvec.X * f; - // rel_cam_target.Y -= 0.005 * bobvec.Y * f; + //rel_cam_target.X -= 0.005 * bobvec.X * f; + //rel_cam_target.Y -= 0.005 * bobvec.Y * f; rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * M_PI * f); -#else + #else f32 angle_deg = 1 * bobdir * sin(bobfrac * M_PI); f32 angle_rad = angle_deg * M_PI / 180; f32 r = 0.05; - v3f off = v3f(r * sin(angle_rad), r * (cos(angle_rad) - 1), 0); + v3f off = v3f( + r * sin(angle_rad), + r * (cos(angle_rad) - 1), + 0); rel_cam_pos += off; - // rel_cam_target += off; + //rel_cam_target += off; rel_cam_up.rotateXYBy(angle_deg); -#endif + #endif + } // Compute absolute camera position and target - m_headnode->getAbsoluteTransformation().transformVect( - m_camera_position, rel_cam_pos); - m_headnode->getAbsoluteTransformation().rotateVect( - m_camera_direction, rel_cam_target - rel_cam_pos); + m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos); + m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos); v3f abs_cam_up; m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up); @@ -471,7 +456,8 @@ void Camera::update( v3f my_cp = m_camera_position; // Reposition the camera for third person view - if (m_camera_mode > CAMERA_MODE_FIRST) { + if (m_camera_mode > CAMERA_MODE_FIRST) + { if (m_camera_mode == CAMERA_MODE_THIRD_FRONT) m_camera_direction *= -1; @@ -483,46 +469,41 @@ void Camera::update( my_cp.X = m_camera_position.X + m_camera_direction.X * -i; my_cp.Z = m_camera_position.Z + m_camera_direction.Z * -i; if (i > 12) - my_cp.Y = m_camera_position.Y + - (m_camera_direction.Y * -i); + my_cp.Y = m_camera_position.Y + (m_camera_direction.Y * -i); // Prevent camera positioned inside nodes const NodeDefManager *nodemgr = m_client->ndef(); - MapNode n = m_client->getEnv().getClientMap().getNode( - floatToInt(my_cp, BS)); + MapNode n = m_client->getEnv().getClientMap() + .getNode(floatToInt(my_cp, BS)); - const ContentFeatures &features = nodemgr->get(n); + const ContentFeatures& features = nodemgr->get(n); if (features.walkable) { - my_cp.X += m_camera_direction.X * -1 * -BS / 2; - my_cp.Z += m_camera_direction.Z * -1 * -BS / 2; - my_cp.Y += m_camera_direction.Y * -1 * -BS / 2; + my_cp.X += m_camera_direction.X*-1*-BS/2; + my_cp.Z += m_camera_direction.Z*-1*-BS/2; + my_cp.Y += m_camera_direction.Y*-1*-BS/2; abort = true; break; } } // If node blocks camera position don't move y to heigh - if (abort && my_cp.Y > player_position.Y + BS * 2) - my_cp.Y = player_position.Y + BS * 2; + if (abort && my_cp.Y > player_position.Y+BS*2) + my_cp.Y = player_position.Y+BS*2; } // Update offset if too far away from the center of the map - m_camera_offset.X += - CAMERA_OFFSET_STEP * - (((s16)(my_cp.X / BS) - m_camera_offset.X) / CAMERA_OFFSET_STEP); - m_camera_offset.Y += - CAMERA_OFFSET_STEP * - (((s16)(my_cp.Y / BS) - m_camera_offset.Y) / CAMERA_OFFSET_STEP); - m_camera_offset.Z += - CAMERA_OFFSET_STEP * - (((s16)(my_cp.Z / BS) - m_camera_offset.Z) / CAMERA_OFFSET_STEP); + m_camera_offset.X += CAMERA_OFFSET_STEP* + (((s16)(my_cp.X/BS) - m_camera_offset.X)/CAMERA_OFFSET_STEP); + m_camera_offset.Y += CAMERA_OFFSET_STEP* + (((s16)(my_cp.Y/BS) - m_camera_offset.Y)/CAMERA_OFFSET_STEP); + m_camera_offset.Z += CAMERA_OFFSET_STEP* + (((s16)(my_cp.Z/BS) - m_camera_offset.Z)/CAMERA_OFFSET_STEP); // Set camera node transformation - m_cameranode->setPosition(my_cp - intToFloat(m_camera_offset, BS)); + m_cameranode->setPosition(my_cp-intToFloat(m_camera_offset, BS)); m_cameranode->setUpVector(abs_cam_up); // *100.0 helps in large map coordinates - m_cameranode->setTarget(my_cp - intToFloat(m_camera_offset, BS) + - 100 * m_camera_direction); + m_cameranode->setTarget(my_cp-intToFloat(m_camera_offset, BS) + 100 * m_camera_direction); // update the camera position in third-person mode to render blocks behind player // and correctly apply liquid post FX. @@ -542,9 +523,7 @@ void Camera::update( // Mark transition as complete if target FOV has been reached if ((m_fov_diff > 0.0f && m_curr_fov_degrees >= m_target_fov_degrees) || - (m_fov_diff < 0.0f && - m_curr_fov_degrees <= - m_target_fov_degrees)) { + (m_fov_diff < 0.0f && m_curr_fov_degrees <= m_target_fov_degrees)) { m_fov_transition_active = false; m_curr_fov_degrees = m_target_fov_degrees; } @@ -562,10 +541,10 @@ void Camera::update( // FOV and aspect ratio const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - m_aspect = (f32)window_size.X / (f32)window_size.Y; + m_aspect = (f32) window_size.X / (f32) window_size.Y; m_fov_y = m_curr_fov_degrees * M_PI / 180.0; // Increase vertical FOV on lower aspect ratios (<16:10) - m_fov_y *= core::clamp(sqrt(16. / 10. / m_aspect), 1.0, 1.4); + m_fov_y *= core::clamp(sqrt(16./10. / m_aspect), 1.0, 1.4); m_fov_x = 2 * atan(m_aspect * tan(0.5 * m_fov_y)); m_cameranode->setAspectRatio(m_aspect); m_cameranode->setFOV(m_fov_y); @@ -574,27 +553,29 @@ void Camera::update( addArmInertia(player->getYaw()); // Position the wielded item - // v3f wield_position = v3f(45, -35, 65); + //v3f wield_position = v3f(45, -35, 65); v3f wield_position = v3f(m_wieldmesh_offset.X, m_wieldmesh_offset.Y, 65); - // v3f wield_rotation = v3f(-100, 120, -100); + //v3f wield_rotation = v3f(-100, 120, -100); v3f wield_rotation = v3f(-100, 120, -100); - wield_position.Y += fabs(m_wield_change_timer) * 320 - 40; - if (m_digging_anim < 0.05 || m_digging_anim > 0.5) { + wield_position.Y += fabs(m_wield_change_timer)*320 - 40; + if(m_digging_anim < 0.05 || m_digging_anim > 0.5) + { f32 frac = 1.0; - if (m_digging_anim > 0.5) + if(m_digging_anim > 0.5) frac = 2.0 * (m_digging_anim - 0.5); // This value starts from 1 and settles to 0 f32 ratiothing = std::pow((1.0f - tool_reload_ratio), 0.5f); - // f32 ratiothing2 = pow(ratiothing, 0.5f); - f32 ratiothing2 = (easeCurve(ratiothing * 0.5)) * 2.0; + //f32 ratiothing2 = pow(ratiothing, 0.5f); + f32 ratiothing2 = (easeCurve(ratiothing*0.5))*2.0; wield_position.Y -= frac * 25.0 * pow(ratiothing2, 1.7f); - // wield_position.Z += frac * 5.0 * ratiothing2; + //wield_position.Z += frac * 5.0 * ratiothing2; wield_position.X -= frac * 35.0 * pow(ratiothing2, 1.1f); wield_rotation.Y += frac * 70.0 * pow(ratiothing2, 1.4f); - // wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f); - // wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f); + //wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f); + //wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f); } - if (m_digging_button != -1) { + if (m_digging_button != -1) + { f32 digfrac = m_digging_anim; wield_position.X -= 50 * sin(pow(digfrac, 0.8f) * M_PI); wield_position.Y += 24 * sin(digfrac * 1.8 * M_PI); @@ -609,8 +590,8 @@ void Camera::update( wield_rotation *= core::RADTODEG; } else { f32 bobfrac = my_modf(m_view_bobbing_anim); - wield_position.X -= sin(bobfrac * M_PI * 2.0) * 3.0; - wield_position.Y += sin(my_modf(bobfrac * 2.0) * M_PI) * 3.0; + wield_position.X -= sin(bobfrac*M_PI*2.0) * 3.0; + wield_position.Y += sin(my_modf(bobfrac*2.0)*M_PI) * 3.0; } m_wieldnode->setPosition(wield_position); m_wieldnode->setRotation(wield_rotation); @@ -628,8 +609,7 @@ void Camera::update( const bool movement_Y = fabs(speed.Y) > BS; const bool walking = movement_XZ && player->touching_ground; - const bool swimming = - (movement_XZ || player->swimming_vertical) && player->in_liquid; + const bool swimming = (movement_XZ || player->swimming_vertical) && player->in_liquid; const bool climbing = movement_Y && player->is_climbing; if ((walking || swimming || climbing) && !flying) { // Start animation @@ -648,20 +628,18 @@ void Camera::updateViewingRange() // Ignore near_plane setting on all other platforms to prevent abuse #if ENABLE_GLES - m_cameranode->setNearValue( - rangelim(g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS); + m_cameranode->setNearValue(rangelim( + g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS); #else m_cameranode->setNearValue(0.1f * BS); #endif - m_draw_control.wanted_range = - std::fmin(adjustDist(viewing_range, getFovMax()), 4000); + m_draw_control.wanted_range = std::fmin(adjustDist(viewing_range, getFovMax()), 4000); if (m_draw_control.range_all) { m_cameranode->setFarValue(100000.0); return; } - m_cameranode->setFarValue( - (viewing_range < 2000) ? 2000 * BS : viewing_range * BS); + m_cameranode->setFarValue((viewing_range < 2000) ? 2000 * BS : viewing_range * BS); } void Camera::setDigging(s32 button) @@ -682,23 +660,23 @@ void Camera::wield(const ItemStack &item) } } -void Camera::drawWieldedTool(irr::core::matrix4 *translation) +void Camera::drawWieldedTool(irr::core::matrix4* translation) { // Clear Z buffer so that the wielded tool stays in front of world geometry m_wieldmgr->getVideoDriver()->clearZBuffer(); // Draw the wielded node (in a separate scene manager) - scene::ICameraSceneNode *cam = m_wieldmgr->getActiveCamera(); + scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera(); cam->setAspectRatio(m_cameranode->getAspectRatio()); - cam->setFOV(72.0 * M_PI / 180.0); + cam->setFOV(72.0*M_PI/180.0); cam->setNearValue(10); cam->setFarValue(1000); - if (translation != NULL) { + if (translation != NULL) + { irr::core::matrix4 startMatrix = cam->getAbsoluteTransformation(); - irr::core::vector3df focusPoint = - (cam->getTarget() - cam->getAbsolutePosition()) - .setLength(1) + - cam->getAbsolutePosition(); + irr::core::vector3df focusPoint = (cam->getTarget() + - cam->getAbsolutePosition()).setLength(1) + + cam->getAbsolutePosition(); irr::core::vector3df camera_pos = (startMatrix * *translation).getTranslation(); @@ -713,7 +691,8 @@ void Camera::drawNametags() core::matrix4 trans = m_cameranode->getProjectionMatrix(); trans *= m_cameranode->getViewMatrix(); - for (std::list::const_iterator i = m_nametags.begin(); + for (std::list::const_iterator + i = m_nametags.begin(); i != m_nametags.end(); ++i) { Nametag *nametag = *i; if (nametag->nametag_color.getAlpha() == 0) { @@ -722,34 +701,27 @@ void Camera::drawNametags() // shadow can remain. continue; } - v3f pos = nametag->parent_node->getAbsolutePosition() + - nametag->nametag_pos * BS; - f32 transformed_pos[4] = {pos.X, pos.Y, pos.Z, 1.0f}; + v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->nametag_pos * BS; + f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f }; trans.multiplyWith1x4Matrix(transformed_pos); if (transformed_pos[3] > 0) { - std::wstring nametag_colorless = unescape_translate( - utf8_to_wide(nametag->nametag_text)); + std::wstring nametag_colorless = + unescape_translate(utf8_to_wide(nametag->nametag_text)); core::dimension2d textsize = - g_fontengine->getFont()->getDimension( - nametag_colorless.c_str()); - f32 zDiv = transformed_pos[3] == 0.0f - ? 1.0f - : core::reciprocal(transformed_pos[3]); - v2u32 screensize = RenderingEngine::get_video_driver() - ->getScreenSize(); + g_fontengine->getFont()->getDimension( + nametag_colorless.c_str()); + f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f : + core::reciprocal(transformed_pos[3]); + v2u32 screensize = RenderingEngine::get_video_driver()->getScreenSize(); v2s32 screen_pos; - screen_pos.X = screensize.X * (0.5 * transformed_pos[0] * zDiv + - 0.5) - - textsize.Width / 2; - screen_pos.Y = screensize.Y * (0.5 - transformed_pos[1] * zDiv * - 0.5) - - textsize.Height / 2; + screen_pos.X = screensize.X * + (0.5 * transformed_pos[0] * zDiv + 0.5) - textsize.Width / 2; + screen_pos.Y = screensize.Y * + (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2; core::rect size(0, 0, textsize.Width, textsize.Height); g_fontengine->getFont()->draw( - translate_string( - utf8_to_wide(nametag->nametag_text)) - .c_str(), - size + screen_pos, nametag->nametag_color); + translate_string(utf8_to_wide(nametag->nametag_text)).c_str(), + size + screen_pos, nametag->nametag_color); } } } diff --git a/src/client/camera.h b/src/client/camera.h index bf10329ab..3a59637bc 100644 --- a/src/client/camera.h +++ b/src/client/camera.h @@ -31,13 +31,15 @@ struct MapDrawControl; class Client; class WieldMeshSceneNode; -struct Nametag -{ - Nametag(scene::ISceneNode *a_parent_node, const std::string &a_nametag_text, - const video::SColor &a_nametag_color, const v3f &a_nametag_pos) : - parent_node(a_parent_node), - nametag_text(a_nametag_text), nametag_color(a_nametag_color), - nametag_pos(a_nametag_pos) +struct Nametag { + Nametag(scene::ISceneNode *a_parent_node, + const std::string &a_nametag_text, + const video::SColor &a_nametag_color, + const v3f &a_nametag_pos): + parent_node(a_parent_node), + nametag_text(a_nametag_text), + nametag_color(a_nametag_color), + nametag_pos(a_nametag_pos) { } scene::ISceneNode *parent_node; @@ -46,17 +48,12 @@ struct Nametag v3f nametag_pos; }; -enum CameraMode -{ - CAMERA_MODE_FIRST, - CAMERA_MODE_THIRD, - CAMERA_MODE_THIRD_FRONT -}; +enum CameraMode {CAMERA_MODE_FIRST, CAMERA_MODE_THIRD, CAMERA_MODE_THIRD_FRONT}; /* - Client camera class, manages the player and camera scene nodes, the viewing - distance and performs view bobbing etc. It also displays the wielded tool in front of - the first-person camera. + Client camera class, manages the player and camera scene nodes, the viewing distance + and performs view bobbing etc. It also displays the wielded tool in front of the + first-person camera. */ class Camera { @@ -66,30 +63,54 @@ class Camera // Get camera scene node. // It has the eye transformation, pitch and view bobbing applied. - inline scene::ICameraSceneNode *getCameraNode() const { return m_cameranode; } + inline scene::ICameraSceneNode* getCameraNode() const + { + return m_cameranode; + } // Get the camera position (in absolute scene coordinates). // This has view bobbing applied. - inline v3f getPosition() const { return m_camera_position; } + inline v3f getPosition() const + { + return m_camera_position; + } // Returns the absolute position of the head SceneNode in the world - inline v3f getHeadPosition() const { return m_headnode->getAbsolutePosition(); } + inline v3f getHeadPosition() const + { + return m_headnode->getAbsolutePosition(); + } // Get the camera direction (in absolute camera coordinates). // This has view bobbing applied. - inline v3f getDirection() const { return m_camera_direction; } + inline v3f getDirection() const + { + return m_camera_direction; + } // Get the camera offset - inline v3s16 getOffset() const { return m_camera_offset; } + inline v3s16 getOffset() const + { + return m_camera_offset; + } // Horizontal field of view - inline f32 getFovX() const { return m_fov_x; } + inline f32 getFovX() const + { + return m_fov_x; + } // Vertical field of view - inline f32 getFovY() const { return m_fov_y; } + inline f32 getFovY() const + { + return m_fov_y; + } // Get maximum of getFovX() and getFovY() - inline f32 getFovMax() const { return MYMAX(m_fov_x, m_fov_y); } + inline f32 getFovMax() const + { + return MYMAX(m_fov_x, m_fov_y); + } // Notify about new server-sent FOV and initialize smooth FOV transition void notifyFovChange(); @@ -102,7 +123,7 @@ class Camera // Update the camera from the local player's position. // busytime is used to adjust the viewing range. - void update(LocalPlayer *player, f32 frametime, f32 busytime, + void update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio); // Update render distance @@ -118,11 +139,10 @@ class Camera // Draw the wielded tool. // This has to happen *after* the main scene is drawn. // Warning: This clears the Z buffer. - void drawWieldedTool(irr::core::matrix4 *translation = NULL); + void drawWieldedTool(irr::core::matrix4* translation=NULL); // Toggle the current camera mode - void toggleCameraMode() - { + void toggleCameraMode() { if (m_camera_mode == CAMERA_MODE_FIRST) m_camera_mode = CAMERA_MODE_THIRD; else if (m_camera_mode == CAMERA_MODE_THIRD) @@ -132,14 +152,20 @@ class Camera } // Set the current camera mode - inline void setCameraMode(CameraMode mode) { m_camera_mode = mode; } + inline void setCameraMode(CameraMode mode) + { + m_camera_mode = mode; + } - // read the current camera mode - inline CameraMode getCameraMode() { return m_camera_mode; } + //read the current camera mode + inline CameraMode getCameraMode() + { + return m_camera_mode; + } Nametag *addNametag(scene::ISceneNode *parent_node, - const std::string &nametag_text, video::SColor nametag_color, - const v3f &pos); + const std::string &nametag_text, video::SColor nametag_color, + const v3f &pos); void removeNametag(Nametag *nametag); @@ -159,7 +185,7 @@ class Camera WieldMeshSceneNode *m_wieldnode = nullptr; // draw control - MapDrawControl &m_draw_control; + MapDrawControl& m_draw_control; Client *m_client; diff --git a/src/client/client.cpp b/src/client/client.cpp index 54fbbf8b5..aa3e257ac 100644 --- a/src/client/client.cpp +++ b/src/client/client.cpp @@ -59,7 +59,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "chatmessage.h" #include "translation.h" -extern gui::IGUIEnvironment *guienv; +extern gui::IGUIEnvironment* guienv; /* Utility classes @@ -76,11 +76,10 @@ u32 PacketCounter::sum() const void PacketCounter::print(std::ostream &o) const { for (const auto &it : m_packets) { - auto name = it.first >= TOCLIENT_NUM_MSG_TYPES - ? "?" - : toClientCommandTable[it.first].name; - o << "cmd " << it.first << " (" << name << ") count " << it.second - << std::endl; + auto name = it.first >= TOCLIENT_NUM_MSG_TYPES ? "?" + : toClientCommandTable[it.first].name; + o << "cmd " << it.first << " (" << name << ") count " + << it.second << std::endl; } } @@ -88,23 +87,42 @@ void PacketCounter::print(std::ostream &o) const Client */ -Client::Client(const char *playername, const std::string &password, - const std::string &address_name, MapDrawControl &control, - IWritableTextureSource *tsrc, IWritableShaderSource *shsrc, - IWritableItemDefManager *itemdef, NodeDefManager *nodedef, - ISoundManager *sound, MtEventManager *event, bool ipv6, GameUI *game_ui) : - m_mesh_update_thread(this), - m_tsrc(tsrc), m_shsrc(shsrc), m_itemdef(itemdef), m_nodedef(nodedef), - m_sound(sound), m_event(event), - m_env(new ClientMap(this, control, 666), tsrc, this), - m_particle_manager(&m_env), - m_con(new con::Connection( - PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)), - m_address_name(address_name), m_server_ser_ver(SER_FMT_VER_INVALID), - m_last_chat_message_sent(time(NULL)), m_password(password), - m_chosen_auth_mech(AUTH_MECHANISM_NONE), - m_media_downloader(new ClientMediaDownloader()), m_state(LC_Created), - m_game_ui(game_ui), m_modchannel_mgr(new ModChannelMgr()) +Client::Client( + const char *playername, + const std::string &password, + const std::string &address_name, + MapDrawControl &control, + IWritableTextureSource *tsrc, + IWritableShaderSource *shsrc, + IWritableItemDefManager *itemdef, + NodeDefManager *nodedef, + ISoundManager *sound, + MtEventManager *event, + bool ipv6, + GameUI *game_ui +): + m_mesh_update_thread(this), + m_tsrc(tsrc), + m_shsrc(shsrc), + m_itemdef(itemdef), + m_nodedef(nodedef), + m_sound(sound), + m_event(event), + m_env( + new ClientMap(this, control, 666), + tsrc, this + ), + m_particle_manager(&m_env), + m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)), + m_address_name(address_name), + m_server_ser_ver(SER_FMT_VER_INVALID), + m_last_chat_message_sent(time(NULL)), + m_password(password), + m_chosen_auth_mech(AUTH_MECHANISM_NONE), + m_media_downloader(new ClientMediaDownloader()), + m_state(LC_Created), + m_game_ui(game_ui), + m_modchannel_mgr(new ModChannelMgr()) { // Add local player m_env.setLocalPlayer(new LocalPlayer(this, playername)); @@ -128,8 +146,8 @@ void Client::loadMods() // TODO Delete this code block when server-sent CSM and verifying of builtin are // complete. if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) { - warningstream << "Client-provided mod loading is disabled by server." - << std::endl; + warningstream << "Client-provided mod loading is disabled by server." << + std::endl; return; } @@ -173,8 +191,7 @@ void Client::loadMods() for (const ModSpec &mod : m_mods) { if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) { throw ModError("Error loading mod \"" + mod.name + - "\": Mod name does not follow naming " - "conventions: " + "\": Mod name does not follow naming conventions: " "Only characters [a-z0-9_] are allowed."); } scanModIntoMemory(mod.name, mod.path); @@ -208,14 +225,13 @@ bool Client::checkBuiltinIntegrity() } void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path, - std::string mod_subpath) + std::string mod_subpath) { std::string full_path = mod_path + DIR_DELIM + mod_subpath; std::vector mod = fs::GetDirListing(full_path); for (const fs::DirListNode &j : mod) { if (j.dir) { - scanModSubfolder(mod_name, mod_path, - mod_subpath + j.name + DIR_DELIM); + scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM); continue; } std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/'); @@ -223,12 +239,12 @@ void Client::scanModSubfolder(const std::string &mod_name, const std::string &mo std::string real_path = full_path + j.name; std::string vfs_path = mod_name + ":" + mod_subpath + j.name; infostream << "Client::scanModSubfolder(): Loading \"" << real_path - << "\" as \"" << vfs_path << "\"." << std::endl; + << "\" as \"" << vfs_path << "\"." << std::endl; std::ifstream is(real_path, std::ios::binary | std::ios::ate); - if (!is.good()) { + if(!is.good()) { errorstream << "Client::scanModSubfolder(): Can't read file \"" - << real_path << "\"." << std::endl; + << real_path << "\"." << std::endl; continue; } auto size = is.tellg(); @@ -243,25 +259,23 @@ void Client::scanModSubfolder(const std::string &mod_name, const std::string &mo const std::string &Client::getBuiltinLuaPath() { - static const std::string builtin_dir = - porting::path_share + DIR_DELIM + "builtin"; + static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin"; return builtin_dir; } const std::string &Client::getClientModsLuaPath() { - static const std::string clientmods_dir = - porting::path_share + DIR_DELIM + "clientmods"; + static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods"; return clientmods_dir; } -const std::vector &Client::getMods() const +const std::vector& Client::getMods() const { static std::vector client_modspec_temp; return client_modspec_temp; } -const ModSpec *Client::getModSpec(const std::string &modname) const +const ModSpec* Client::getModSpec(const std::string &modname) const { return NULL; } @@ -271,7 +285,7 @@ void Client::Stop() m_shutdown = true; if (m_mods_loaded) m_script->on_shutdown(); - // request all client managed threads to stop + //request all client managed threads to stop m_mesh_update_thread.stop(); // Save local server map if (m_localdb) { @@ -302,6 +316,7 @@ Client::~Client() delete r.mesh; } + delete m_inventory_from_server; // Delete detached inventories @@ -311,8 +326,7 @@ Client::~Client() // cleanup 3d model meshes on client shutdown while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) { - scene::IAnimatedMesh *mesh = - RenderingEngine::get_mesh_cache()->getMeshByIndex(0); + scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0); if (mesh) RenderingEngine::get_mesh_cache()->removeMesh(mesh); @@ -338,7 +352,7 @@ void Client::step(float dtime) dtime = 2.0; m_animation_time += dtime; - if (m_animation_time > 60.0) + if(m_animation_time > 60.0) m_animation_time -= 60.0; m_time_of_day_update_timer += dtime; @@ -351,14 +365,14 @@ void Client::step(float dtime) { float &counter = m_packetcounter_timer; counter -= dtime; - if (counter <= 0.0f) { + if(counter <= 0.0f) + { counter = 30.0f; u32 sum = m_packetcounter.sum(); float avg = sum / counter; infostream << "Client packetcounter (" << counter << "s): " - << "sum=" << sum << " avg=" << avg << "/s" - << std::endl; + << "sum=" << sum << " avg=" << avg << "/s" << std::endl; m_packetcounter.print(infostream); m_packetcounter.clear(); } @@ -369,19 +383,19 @@ void Client::step(float dtime) static bool initial_step = true; if (initial_step) { initial_step = false; - } else if (m_state == LC_Created) { + } + else if(m_state == LC_Created) { if (m_is_registration_confirmation_state) { // Waiting confirmation return; } float &counter = m_connection_reinit_timer; counter -= dtime; - if (counter <= 0.0) { + if(counter <= 0.0) { counter = 2.0; LocalPlayer *myplayer = m_env.getLocalPlayer(); - FATAL_ERROR_IF(myplayer == NULL, - "Local player not found in environment."); + FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment."); sendInit(myplayer->getName()); } @@ -398,12 +412,12 @@ void Client::step(float dtime) Run Map's timers and unload unused data */ const float map_timer_and_unload_dtime = 5.25; - if (m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) { + if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) { std::vector deleted_blocks; m_env.getMap().timerUpdate(map_timer_and_unload_dtime, - g_settings->getFloat("client_unload_unused_data_timeout"), - g_settings->getS32("client_mapblock_limit"), - &deleted_blocks); + g_settings->getFloat("client_unload_unused_data_timeout"), + g_settings->getS32("client_mapblock_limit"), + &deleted_blocks); /* Send info to server @@ -412,9 +426,9 @@ void Client::step(float dtime) std::vector::iterator i = deleted_blocks.begin(); std::vector sendlist; - for (;;) { - if (sendlist.size() == 255 || i == deleted_blocks.end()) { - if (sendlist.empty()) + for(;;) { + if(sendlist.size() == 255 || i == deleted_blocks.end()) { + if(sendlist.empty()) break; /* [0] u16 command @@ -426,7 +440,7 @@ void Client::step(float dtime) sendDeletedBlocks(sendlist); - if (i == deleted_blocks.end()) + if(i == deleted_blocks.end()) break; sendlist.clear(); @@ -463,8 +477,7 @@ void Client::step(float dtime) if (envEvent.type == CEE_PLAYER_DAMAGE) { u16 damage = envEvent.player_damage.amount; - if (envEvent.player_damage.send_to_server && - !g_settings->getBool("prevent_natural_damage")) + if (envEvent.player_damage.send_to_server && ! g_settings->getBool("prevent_natural_damage")) sendDamage(damage); // Add to ClientEvent queue @@ -480,7 +493,7 @@ void Client::step(float dtime) */ float &counter = m_avg_rtt_timer; counter += dtime; - if (counter >= 10) { + if(counter >= 10) { counter = 0.0; // connectedAndInitialized() is true, peer exists. float avg_rtt = getRTT(); @@ -493,7 +506,8 @@ void Client::step(float dtime) { float &counter = m_playerpos_send_timer; counter += dtime; - if ((m_state == LC_Ready) && (counter >= m_recommended_send_interval)) { + if((m_state == LC_Ready) && (counter >= m_recommended_send_interval)) + { counter = 0.0; sendPlayerPos(); } @@ -505,14 +519,14 @@ void Client::step(float dtime) { int num_processed_meshes = 0; std::vector blocks_to_ack; - while (!m_mesh_update_thread.m_queue_out.empty()) { + while (!m_mesh_update_thread.m_queue_out.empty()) + { num_processed_meshes++; MinimapMapblock *minimap_mapblock = NULL; bool do_mapper_update = true; - MeshUpdateResult r = - m_mesh_update_thread.m_queue_out.pop_frontNoEx(); + MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx(); MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p); if (block) { // Delete the old mesh @@ -526,8 +540,7 @@ void Client::step(float dtime) bool is_empty = true; for (int l = 0; l < MAX_TILE_LAYERS; l++) - if (r.mesh->getMesh(l)->getMeshBufferCount() != - 0) + if (r.mesh->getMesh(l)->getMeshBufferCount() != 0) is_empty = false; if (is_empty) @@ -553,13 +566,12 @@ void Client::step(float dtime) } } if (blocks_to_ack.size() > 0) { - // Acknowledge block(s) - sendGotBlocks(blocks_to_ack); + // Acknowledge block(s) + sendGotBlocks(blocks_to_ack); } if (num_processed_meshes > 0) - g_profiler->graphAdd( - "num_processed_meshes", num_processed_meshes); + g_profiler->graphAdd("num_processed_meshes", num_processed_meshes); } /* @@ -588,8 +600,7 @@ void Client::step(float dtime) if (count_after != count_before) { // Do this every seconds after TOCLIENT_INVENTORY - // Reset the locally changed inventory to the authoritative - // inventory + // Reset the locally changed inventory to the authoritative inventory player->inventory = *m_inventory_from_server; m_update_wielded_item = true; } @@ -613,17 +624,16 @@ void Client::step(float dtime) Handle removed remotely initiated sounds */ m_removed_sounds_check_timer += dtime; - if (m_removed_sounds_check_timer >= 2.32) { + if(m_removed_sounds_check_timer >= 2.32) { m_removed_sounds_check_timer = 0; // Find removed sounds and clear references to them std::vector removed_server_ids; - for (std::unordered_map::iterator i = - m_sounds_server_to_client.begin(); + for (std::unordered_map::iterator i = m_sounds_server_to_client.begin(); i != m_sounds_server_to_client.end();) { s32 server_id = i->first; int client_id = i->second; ++i; - if (!m_sound->soundExists(client_id)) { + if(!m_sound->soundExists(client_id)) { m_sounds_server_to_client.erase(server_id); m_sounds_client_to_server.erase(client_id); m_sounds_to_objects.erase(client_id); @@ -632,47 +642,48 @@ void Client::step(float dtime) } // Sync to server - if (!removed_server_ids.empty()) { + if(!removed_server_ids.empty()) { sendRemovedSounds(removed_server_ids); } } m_mod_storage_save_timer -= dtime; if (m_mod_storage_save_timer <= 0.0f) { - m_mod_storage_save_timer = - g_settings->getFloat("server_map_save_interval"); + m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval"); int n = 0; - for (std::unordered_map::const_iterator it = - m_mod_storages.begin(); - it != m_mod_storages.end(); ++it) { + for (std::unordered_map::const_iterator + it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) { if (it->second->isModified()) { it->second->save(getModStoragePath()); n++; } } if (n > 0) - infostream << "Saved " << n << " modified mod storages." - << std::endl; + infostream << "Saved " << n << " modified mod storages." << std::endl; } // Write server map - if (m_localdb && m_localdb_save_interval.step(dtime, m_cache_save_interval)) { + if (m_localdb && m_localdb_save_interval.step(dtime, + m_cache_save_interval)) { m_localdb->endSave(); m_localdb->beginSave(); } } bool Client::loadMedia(const std::string &data, const std::string &filename, - bool from_media_push) + bool from_media_push) { std::string name; - const char *image_ext[] = {".png", ".jpg", ".bmp", ".tga", ".pcx", ".ppm", ".psd", - ".wal", ".rgb", NULL}; + const char *image_ext[] = { + ".png", ".jpg", ".bmp", ".tga", + ".pcx", ".ppm", ".psd", ".wal", ".rgb", + NULL + }; name = removeStringEnd(filename, image_ext); if (!name.empty()) { TRACESTREAM(<< "Client: Attempting to load image " - << "file \"" << filename << "\"" << std::endl); + << "file \"" << filename << "\"" << std::endl); io::IFileSystem *irrfs = RenderingEngine::get_filesystem(); video::IVideoDriver *vdrv = RenderingEngine::get_video_driver(); @@ -689,8 +700,8 @@ bool Client::loadMedia(const std::string &data, const std::string &filename, // Read image video::IImage *img = vdrv->createImageFromFile(rfile); if (!img) { - errorstream << "Client: Cannot create image from data of " - << "file \"" << filename << "\"" << std::endl; + errorstream<<"Client: Cannot create image from data of " + <<"file \""<drop(); return false; } @@ -701,53 +712,62 @@ bool Client::loadMedia(const std::string &data, const std::string &filename, return true; } - const char *sound_ext[] = {".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg", - ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg", ".ogg", NULL}; + const char *sound_ext[] = { + ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg", + ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg", + ".ogg", NULL + }; name = removeStringEnd(filename, sound_ext); if (!name.empty()) { TRACESTREAM(<< "Client: Attempting to load sound " - << "file \"" << filename << "\"" << std::endl); + << "file \"" << filename << "\"" << std::endl); return m_sound->loadSoundData(name, data); } - const char *model_ext[] = {".x", ".b3d", ".md2", ".obj", NULL}; + const char *model_ext[] = { + ".x", ".b3d", ".md2", ".obj", + NULL + }; name = removeStringEnd(filename, model_ext); if (!name.empty()) { - verbosestream << "Client: Storing model into memory: " - << "\"" << filename << "\"" << std::endl; - if (m_mesh_data.count(filename)) - errorstream << "Multiple models with name \"" << filename.c_str() - << "\" found; replacing previous model" << std::endl; + verbosestream<<"Client: Storing model into memory: " + <<"\""<loadTranslation(data); return true; } - errorstream << "Client: Don't know how to load file \"" << filename << "\"" - << std::endl; + errorstream << "Client: Don't know how to load file \"" + << filename << "\"" << std::endl; return false; } // Virtual methods from con::PeerHandler void Client::peerAdded(con::Peer *peer) { - infostream << "Client::peerAdded(): peer->id=" << peer->id << std::endl; + infostream << "Client::peerAdded(): peer->id=" + << peer->id << std::endl; } void Client::deletingPeer(con::Peer *peer, bool timeout) { infostream << "Client::deletingPeer(): " - "Server Peer is getting deleted " - << "(timeout=" << timeout << ")" << std::endl; + "Server Peer is getting deleted " + << "(timeout=" << timeout << ")" << std::endl; if (timeout) { m_access_denied = true; @@ -769,13 +789,12 @@ void Client::request_media(const std::vector &file_requests) writeU16(os, TOSERVER_REQUEST_MEDIA); size_t file_requests_size = file_requests.size(); - FATAL_ERROR_IF(file_requests_size > 0xFFFF, - "Unsupported number of file requests"); + FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests"); // Packet dynamicly resized NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0); - pkt << (u16)(file_requests_size & 0xFFFF); + pkt << (u16) (file_requests_size & 0xFFFF); for (const std::string &file_request : file_requests) { pkt << file_request; @@ -784,20 +803,23 @@ void Client::request_media(const std::vector &file_requests) Send(&pkt); infostream << "Client: Sending media request list to server (" - << file_requests.size() << " files. packet size)" << std::endl; + << file_requests.size() << " files. packet size)" << std::endl; } -void Client::initLocalMapSaving( - const Address &address, const std::string &hostname, bool is_local_server) +void Client::initLocalMapSaving(const Address &address, + const std::string &hostname, + bool is_local_server) { if (!g_settings->getBool("enable_local_map_saving") || is_local_server) { return; } std::string world_path; -#define set_world_path(hostname) \ - world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + "server_" + \ - hostname + "_" + std::to_string(address.getPort()); +#define set_world_path(hostname) \ + world_path = porting::path_user \ + + DIR_DELIM + "worlds" \ + + DIR_DELIM + "server_" \ + + hostname + "_" + std::to_string(address.getPort()); set_world_path(hostname); if (!fs::IsDir(world_path)) { @@ -810,8 +832,7 @@ void Client::initLocalMapSaving( m_localdb = new MapDatabaseSQLite3(world_path); m_localdb->beginSave(); - actionstream << "Local map saving started, map will be saved at '" << world_path - << "'" << std::endl; + actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl; } void Client::ReceiveAll() @@ -819,13 +840,12 @@ void Client::ReceiveAll() NetworkPacket pkt; u64 start_ms = porting::getTimeMs(); const u64 budget = 100; - for (;;) { + for(;;) { // Limit time even if there would be huge amounts of data to // process if (porting::getTimeMs() > start_ms + budget) { infostream << "Client::ReceiveAll(): " - "Packet processing budget exceeded." - << std::endl; + "Packet processing budget exceeded." << std::endl; break; } @@ -836,15 +856,15 @@ void Client::ReceiveAll() ProcessData(&pkt); } catch (const con::InvalidIncomingDataException &e) { infostream << "Client::ReceiveAll(): " - "InvalidIncomingDataException: what()=" - << e.what() << std::endl; + "InvalidIncomingDataException: what()=" + << e.what() << std::endl; } } } -inline void Client::handleCommand(NetworkPacket *pkt) +inline void Client::handleCommand(NetworkPacket* pkt) { - const ToClientCommandHandler &opHandle = toClientCommandTable[pkt->getCommand()]; + const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()]; (this->*opHandle.handler)(pkt); } @@ -853,10 +873,10 @@ inline void Client::handleCommand(NetworkPacket *pkt) */ void Client::ProcessData(NetworkPacket *pkt) { - ToClientCommand command = (ToClientCommand)pkt->getCommand(); + ToClientCommand command = (ToClientCommand) pkt->getCommand(); u32 sender_peer_id = pkt->getPeerId(); - // infostream<<"Client: received command="< &blocks) { NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size()); - pkt << (u8)blocks.size(); + pkt << (u8) blocks.size(); for (const v3s16 &block : blocks) { pkt << block; @@ -1099,7 +1122,7 @@ void Client::sendDeletedBlocks(std::vector &blocks) void Client::sendGotBlocks(const std::vector &blocks) { NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size()); - pkt << (u8)blocks.size(); + pkt << (u8) blocks.size(); for (const v3s16 &block : blocks) pkt << block; @@ -1113,7 +1136,7 @@ void Client::sendRemovedSounds(std::vector &soundList) NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4); - pkt << (u16)(server_ids & 0xFFFF); + pkt << (u16) (server_ids & 0xFFFF); for (s32 sound_id : soundList) pkt << sound_id; @@ -1121,8 +1144,8 @@ void Client::sendRemovedSounds(std::vector &soundList) Send(&pkt); } -void Client::sendNodemetaFields( - v3s16 p, const std::string &formname, const StringMap &fields) +void Client::sendNodemetaFields(v3s16 p, const std::string &formname, + const StringMap &fields) { size_t fields_size = fields.size(); @@ -1130,7 +1153,7 @@ void Client::sendNodemetaFields( NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0); - pkt << p << formname << (u16)(fields_size & 0xFFFF); + pkt << p << formname << (u16) (fields_size & 0xFFFF); StringMap::const_iterator it; for (it = fields.begin(); it != fields.end(); ++it) { @@ -1143,17 +1166,18 @@ void Client::sendNodemetaFields( Send(&pkt); } -void Client::sendInventoryFields(const std::string &formname, const StringMap &fields) +void Client::sendInventoryFields(const std::string &formname, + const StringMap &fields) { size_t fields_size = fields.size(); FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields"); NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0); - pkt << formname << (u16)(fields_size & 0xFFFF); + pkt << formname << (u16) (fields_size & 0xFFFF); StringMap::const_iterator it; for (it = fields.begin(); it != fields.end(); ++it) { - const std::string &name = it->first; + const std::string &name = it->first; const std::string &value = it->second; pkt << name; pkt.putLongString(value); @@ -1172,7 +1196,7 @@ void Client::sendInventoryAction(InventoryAction *a) std::string s = os.str(); NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size()); - pkt.putRawString(s.c_str(), s.size()); + pkt.putRawString(s.c_str(),s.size()); Send(&pkt); } @@ -1182,9 +1206,8 @@ bool Client::canSendChatMessage() const u32 now = time(NULL); float time_passed = now - m_last_chat_message_sent; - float virt_chat_message_allowance = - m_chat_message_allowance + - time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f); + float virt_chat_message_allowance = m_chat_message_allowance + time_passed * + (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f); if (virt_chat_message_allowance < 1.0f) return false; @@ -1200,26 +1223,22 @@ void Client::sendChatMessage(const std::wstring &message) float time_passed = now - m_last_chat_message_sent; m_last_chat_message_sent = time(NULL); - m_chat_message_allowance += - time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f); + m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f); if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S) m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S; m_chat_message_allowance -= 1.0f; - NetworkPacket pkt( - TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16)); + NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16)); pkt << message; Send(&pkt); - } else if (m_out_chat_queue.size() < (u16)max_queue_size || - max_queue_size == -1) { + } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) { m_out_chat_queue.push(message); } else { - infostream << "Could not queue chat message because maximum out chat " - "queue size (" - << max_queue_size << ") is reached." << std::endl; + infostream << "Could not queue chat message because maximum out chat queue size (" + << max_queue_size << ") is reached." << std::endl; } } @@ -1228,8 +1247,8 @@ void Client::clearOutChatQueue() m_out_chat_queue = std::queue(); } -void Client::sendChangePassword( - const std::string &oldpassword, const std::string &newpassword) +void Client::sendChangePassword(const std::string &oldpassword, + const std::string &newpassword) { LocalPlayer *player = m_env.getLocalPlayer(); if (player == NULL) @@ -1241,6 +1260,7 @@ void Client::sendChangePassword( startAuth(choseAuthMech(m_sudo_auth_methods)); } + void Client::sendDamage(u16 damage) { NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16)); @@ -1259,10 +1279,10 @@ void Client::sendReady() NetworkPacket pkt(TOSERVER_CLIENT_READY, 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2); - pkt << (u8)VERSION_MAJOR << (u8)VERSION_MINOR << (u8)VERSION_PATCH << (u8)0 - << (u16)strlen(g_version_hash); + pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH + << (u8) 0 << (u16) strlen(g_version_hash); - pkt.putRawString(g_version_hash, (u16)strlen(g_version_hash)); + pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash)); pkt << (u16)FORMSPEC_API_VERSION; Send(&pkt); } @@ -1274,31 +1294,32 @@ void Client::sendPlayerPos(v3f pos) return; ClientMap &map = m_env.getClientMap(); - u8 camera_fov = map.getCameraFov(); + u8 camera_fov = map.getCameraFov(); u8 wanted_range = map.getControl().wanted_range; // Save bandwidth by only updating position when // player is not dead and something changed - // FIXME: This part causes breakages in mods like 3d_armor, and has been commented - // for now if (m_activeobjects_received && player->isDead()) + // FIXME: This part causes breakages in mods like 3d_armor, and has been commented for now + // if (m_activeobjects_received && player->isDead()) // return; - if (player->last_position == pos && - player->last_speed == player->getLegitSpeed() && - player->last_pitch == player->getPitch() && - player->last_yaw == player->getYaw() && - player->last_keyPressed == player->keyPressed && - player->last_camera_fov == camera_fov && + if ( + player->last_position == pos && + player->last_speed == player->getLegitSpeed() && + player->last_pitch == player->getPitch() && + player->last_yaw == player->getYaw() && + player->last_keyPressed == player->keyPressed && + player->last_camera_fov == camera_fov && player->last_wanted_range == wanted_range) return; - player->last_position = pos; - player->last_speed = player->getLegitSpeed(); - player->last_pitch = player->getPitch(); - player->last_yaw = player->getYaw(); - player->last_keyPressed = player->keyPressed; - player->last_camera_fov = camera_fov; + player->last_position = pos; + player->last_speed = player->getLegitSpeed(); + player->last_pitch = player->getPitch(); + player->last_yaw = player->getYaw(); + player->last_keyPressed = player->keyPressed; + player->last_camera_fov = camera_fov; player->last_wanted_range = wanted_range; NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1); @@ -1318,11 +1339,12 @@ void Client::sendPlayerPos() void Client::removeNode(v3s16 p) { - std::map modified_blocks; + std::map modified_blocks; try { m_env.getMap().removeNodeAndUpdate(p, modified_blocks); - } catch (InvalidPositionException &e) { + } + catch(InvalidPositionException &e) { } for (const auto &modified_block : modified_blocks) { @@ -1341,7 +1363,7 @@ MapNode Client::CSMGetNode(v3s16 p, bool *is_valid_position) { if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) { v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS); - if ((u32)ppos.getDistanceFrom(p) > m_csm_restriction_noderange) { + if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) { *is_valid_position = false; return {}; } @@ -1367,22 +1389,24 @@ v3s16 Client::CSMClampPos(v3s16 pos) return pos; v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS); const int range = m_csm_restriction_noderange; - return v3s16(core::clamp(pos.X, (int)ppos.X - range, (int)ppos.X + range), - core::clamp(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range), - core::clamp( - pos.Z, (int)ppos.Z - range, (int)ppos.Z + range)); + return v3s16( + core::clamp(pos.X, (int)ppos.X - range, (int)ppos.X + range), + core::clamp(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range), + core::clamp(pos.Z, (int)ppos.Z - range, (int)ppos.Z + range) + ); } void Client::addNode(v3s16 p, MapNode n, bool remove_metadata) { - // TimeTaker timer1("Client::addNode()"); + //TimeTaker timer1("Client::addNode()"); - std::map modified_blocks; + std::map modified_blocks; try { - // TimeTaker timer3("Client::addNode(): addNodeAndUpdate"); + //TimeTaker timer3("Client::addNode(): addNodeAndUpdate"); m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata); - } catch (InvalidPositionException &e) { + } + catch(InvalidPositionException &e) { } for (const auto &modified_block : modified_blocks) { @@ -1426,28 +1450,35 @@ bool Client::updateWieldedItem() return true; } -Inventory *Client::getInventory(const InventoryLocation &loc) +Inventory* Client::getInventory(const InventoryLocation &loc) { - switch (loc.type) { - case InventoryLocation::UNDEFINED: { - } break; + switch(loc.type){ + case InventoryLocation::UNDEFINED: + {} + break; case InventoryLocation::PLAYER: - case InventoryLocation::CURRENT_PLAYER: { + case InventoryLocation::CURRENT_PLAYER: + { LocalPlayer *player = m_env.getLocalPlayer(); assert(player); return &player->inventory; - } break; - case InventoryLocation::NODEMETA: { + } + break; + case InventoryLocation::NODEMETA: + { NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p); - if (!meta) + if(!meta) return NULL; return meta->getInventory(); - } break; - case InventoryLocation::DETACHED: { + } + break; + case InventoryLocation::DETACHED: + { if (m_detached_inventories.count(loc.name) == 0) return NULL; return m_detached_inventories[loc.name]; - } break; + } + break; default: FATAL_ERROR("Invalid inventory location type."); break; @@ -1494,11 +1525,13 @@ void Client::setCrack(int level, v3s16 pos) m_crack_level = level; m_crack_pos = pos; - if (old_crack_level >= 0 && (level < 0 || pos != old_crack_pos)) { + if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos)) + { // remove old crack addUpdateMeshTaskForNode(old_crack_pos, false, true); } - if (level >= 0 && (old_crack_level < 0 || pos != old_crack_pos)) { + if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos)) + { // add new crack addUpdateMeshTaskForNode(pos, false, true); } @@ -1522,20 +1555,20 @@ bool Client::getChatMessage(std::wstring &res) res = L""; switch (chatMessage->type) { - case CHATMESSAGE_TYPE_RAW: - case CHATMESSAGE_TYPE_ANNOUNCE: - case CHATMESSAGE_TYPE_SYSTEM: - res = chatMessage->message; - break; - case CHATMESSAGE_TYPE_NORMAL: { - if (!chatMessage->sender.empty()) - res = L"<" + chatMessage->sender + L"> " + chatMessage->message; - else + case CHATMESSAGE_TYPE_RAW: + case CHATMESSAGE_TYPE_ANNOUNCE: + case CHATMESSAGE_TYPE_SYSTEM: res = chatMessage->message; - break; - } - default: - break; + break; + case CHATMESSAGE_TYPE_NORMAL: { + if (!chatMessage->sender.empty()) + res = L"<" + chatMessage->sender + L"> " + chatMessage->message; + else + res = chatMessage->message; + break; + } + default: + break; } delete chatMessage; @@ -1570,18 +1603,19 @@ void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent) void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent) { - try { + try{ addUpdateMeshTask(blockpos, ack_to_server, urgent); - } catch (InvalidPositionException &e) { } + catch(InvalidPositionException &e){} // Leading edge - for (int i = 0; i < 6; i++) { - try { + for (int i=0;i<6;i++) + { + try{ v3s16 p = blockpos + g_6dirs[i]; addUpdateMeshTask(p, false, urgent); - } catch (InvalidPositionException &e) { } + catch(InvalidPositionException &e){} } } @@ -1589,56 +1623,56 @@ void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool ur { { v3s16 p = nodepos; - infostream << "Client::addUpdateMeshTaskForNode(): " - << "(" << p.X << "," << p.Y << "," << p.Z << ")" << std::endl; + infostream<<"Client::addUpdateMeshTaskForNode(): " + <<"("<getPosition(), BS)); - + v3s16 currentBlock = getNodeBlockPos(floatToInt(m_env.getLocalPlayer()->getPosition(), BS)); + for (s16 X = currentBlock.X - 2; X <= currentBlock.X + 2; X++) - for (s16 Y = currentBlock.Y - 2; Y <= currentBlock.Y + 2; Y++) - for (s16 Z = currentBlock.Z - 2; Z <= currentBlock.Z + 2; Z++) - addUpdateMeshTask(v3s16(X, Y, Z), false, true); - - std::map *sectors = m_env.getMap().getSectorsPtr(); - + for (s16 Y = currentBlock.Y - 2; Y <= currentBlock.Y + 2; Y++) + for (s16 Z = currentBlock.Z - 2; Z <= currentBlock.Z + 2; Z++) + addUpdateMeshTask(v3s16(X, Y, Z), false, true); + + std::map *sectors = m_env.getMap().getSectorsPtr(); + for (auto §or_it : *sectors) { MapSector *sector = sector_it.second; MapBlockVect blocks; @@ -1677,48 +1711,46 @@ float Client::mediaReceiveProgress() return 1.0; // downloader only exists when not yet done } -typedef struct TextureUpdateArgs -{ +typedef struct TextureUpdateArgs { gui::IGUIEnvironment *guienv; u64 last_time_ms; u16 last_percent; - const wchar_t *text_base; + const wchar_t* text_base; ITextureSource *tsrc; } TextureUpdateArgs; void texture_update_progress(void *args, u32 progress, u32 max_progress) { - TextureUpdateArgs *targs = (TextureUpdateArgs *)args; - u16 cur_percent = ceil(progress / (double)max_progress * 100.); - - // update the loading menu -- if neccessary - bool do_draw = false; - u64 time_ms = targs->last_time_ms; - if (cur_percent != targs->last_percent) { - targs->last_percent = cur_percent; - time_ms = porting::getTimeMs(); - // only draw when the user will notice something: - do_draw = (time_ms - targs->last_time_ms > 100); - } + TextureUpdateArgs* targs = (TextureUpdateArgs*) args; + u16 cur_percent = ceil(progress / (double) max_progress * 100.); + + // update the loading menu -- if neccessary + bool do_draw = false; + u64 time_ms = targs->last_time_ms; + if (cur_percent != targs->last_percent) { + targs->last_percent = cur_percent; + time_ms = porting::getTimeMs(); + // only draw when the user will notice something: + do_draw = (time_ms - targs->last_time_ms > 100); + } - if (do_draw) { - targs->last_time_ms = time_ms; - std::basic_stringstream strm; - strm << targs->text_base << " " << targs->last_percent << "%..."; - RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, - 0, 72 + (u16)((18. / 100.) * (double)targs->last_percent), - true); - } + if (do_draw) { + targs->last_time_ms = time_ms; + std::basic_stringstream strm; + strm << targs->text_base << " " << targs->last_percent << "%..."; + RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0, + 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true); + } } void Client::afterContentReceived() { - infostream << "Client::afterContentReceived() started" << std::endl; + infostream<<"Client::afterContentReceived() started"<rebuildImagesAndTextures(); delete[] text; // Rebuild shaders - infostream << "- Rebuilding shaders" << std::endl; + infostream<<"- Rebuilding shaders"<rebuildShaders(); delete[] text; // Update node aliases - infostream << "- Updating node aliases" << std::endl; + infostream<<"- Updating node aliases"<updateAliases(m_itemdef); for (const auto &path : getTextureDirs()) { TextureOverrideSource override_source(path + DIR_DELIM + "override.txt"); m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides()); - m_itemdef->applyTextureOverrides( - override_source.getItemTextureOverrides()); + m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides()); } m_nodedef->setNodeRegistrationStatus(true); m_nodedef->runNodeResolveCallbacks(); delete[] text; // Update node textures and assign shaders to each tile - infostream << "- Updating node textures" << std::endl; + infostream<<"- Updating node textures"<updateTextures(this, texture_update_progress, &tu_args); delete[] tu_args.text_base; // Start mesh update thread after setting up content definitions - infostream << "- Starting mesh update thread" << std::endl; + infostream<<"- Starting mesh update thread"<getPeerStat(PEER_ID_SERVER, con::AVG_RTT); + return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT); } float Client::getCurRate() @@ -1794,7 +1825,7 @@ float Client::getCurRate() void Client::makeScreenshot() { irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver(); - irr::video::IImage *const raw_image = driver->createScreenShot(); + irr::video::IImage* const raw_image = driver->createScreenShot(); if (!raw_image) return; @@ -1810,12 +1841,12 @@ void Client::makeScreenshot() if (fs::IsPathAbsolute(g_settings->get("screenshot_path"))) screenshot_dir = g_settings->get("screenshot_path"); else - screenshot_dir = porting::path_user + DIR_DELIM + - g_settings->get("screenshot_path"); + screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path"); - std::string filename_base = screenshot_dir + DIR_DELIM + - std::string("screenshot_") + - std::string(timetstamp_c); + std::string filename_base = screenshot_dir + + DIR_DELIM + + std::string("screenshot_") + + std::string(timetstamp_c); std::string filename_ext = "." + g_settings->get("screenshot_format"); std::string filename; @@ -1830,20 +1861,18 @@ void Client::makeScreenshot() unsigned serial = 0; while (serial < SCREENSHOT_MAX_SERIAL_TRIES) { - filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + - filename_ext; + filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext; std::ifstream tmp(filename.c_str()); if (!tmp.good()) - break; // File did not apparently exist, we'll go with it + break; // File did not apparently exist, we'll go with it serial++; } if (serial == SCREENSHOT_MAX_SERIAL_TRIES) { - infostream << "Could not find suitable filename for screenshot" - << std::endl; + infostream << "Could not find suitable filename for screenshot" << std::endl; } else { - irr::video::IImage *const image = driver->createImage( - video::ECF_R8G8B8, raw_image->getDimension()); + irr::video::IImage* const image = + driver->createImage(video::ECF_R8G8B8, raw_image->getDimension()); if (image) { raw_image->copyTo(image); @@ -1881,32 +1910,32 @@ void Client::showMinimap(const bool show) // IGameDef interface // Under envlock -IItemDefManager *Client::getItemDefManager() +IItemDefManager* Client::getItemDefManager() { return m_itemdef; } -IWritableItemDefManager *Client::getWritableItemDefManager() +IWritableItemDefManager* Client::getWritableItemDefManager() { return m_itemdef; } -const NodeDefManager *Client::getNodeDefManager() +const NodeDefManager* Client::getNodeDefManager() { return m_nodedef; } -NodeDefManager *Client::getWritableNodeDefManager() +NodeDefManager* Client::getWritableNodeDefManager() { return m_nodedef; } -ICraftDefManager *Client::getCraftDefManager() +ICraftDefManager* Client::getCraftDefManager() { return NULL; - // return m_craftdef; + //return m_craftdef; } -ITextureSource *Client::getTextureSource() +ITextureSource* Client::getTextureSource() { return m_tsrc; } -IWritableShaderSource *Client::getShaderSource() +IWritableShaderSource* Client::getShaderSource() { return m_shsrc; } @@ -1914,39 +1943,39 @@ IWritableShaderSource *Client::getShaderSource() u16 Client::allocateUnknownNodeId(const std::string &name) { errorstream << "Client::allocateUnknownNodeId(): " - << "Client cannot allocate node IDs" << std::endl; + << "Client cannot allocate node IDs" << std::endl; FATAL_ERROR("Client allocated unknown node"); return CONTENT_IGNORE; } -ISoundManager *Client::getSoundManager() +ISoundManager* Client::getSoundManager() { return m_sound; } -MtEventManager *Client::getEventManager() +MtEventManager* Client::getEventManager() { return m_event; } -ParticleManager *Client::getParticleManager() +ParticleManager* Client::getParticleManager() { return &m_particle_manager; } -scene::IAnimatedMesh *Client::getMesh(const std::string &filename, bool cache) +scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache) { StringMap::const_iterator it = m_mesh_data.find(filename); if (it == m_mesh_data.end()) { - errorstream << "Client::getMesh(): Mesh not found: \"" << filename << "\"" - << std::endl; + errorstream << "Client::getMesh(): Mesh not found: \"" << filename + << "\"" << std::endl; return NULL; } - const std::string &data = it->second; + const std::string &data = it->second; // Create the mesh, remove it from cache and return it // This allows unique vertex colors and other properties for each instance Buffer data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht - io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile( + io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile( *data_rw, data_rw.getSize(), filename.c_str()); FATAL_ERROR_IF(!rfile, "Could not create/open RAM file"); @@ -1958,7 +1987,7 @@ scene::IAnimatedMesh *Client::getMesh(const std::string &filename, bool cache) return mesh; } -const std::string *Client::getModFile(std::string filename) +const std::string* Client::getModFile(std::string filename) { // strip dir delimiter from beginning of path auto pos = filename.find_first_of(':'); @@ -1979,7 +2008,7 @@ bool Client::registerModStorage(ModMetadata *storage) { if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) { errorstream << "Unable to register same mod storage twice. Storage name: " - << storage->getModName() << std::endl; + << storage->getModName() << std::endl; return false; } @@ -1990,7 +2019,7 @@ bool Client::registerModStorage(ModMetadata *storage) void Client::unregisterModStorage(const std::string &name) { std::unordered_map::const_iterator it = - m_mod_storages.find(name); + m_mod_storages.find(name); if (it != m_mod_storages.end()) { // Save unconditionaly on unregistration it->second->save(getModStoragePath()); @@ -2040,20 +2069,19 @@ bool Client::sendModChannelMessage(const std::string &channel, const std::string if (message.size() > STRING_MAX_LEN) { warningstream << "ModChannel message too long, dropping before sending " - << " (" << message.size() << " > " << STRING_MAX_LEN - << ", channel: " << channel << ")" << std::endl; + << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: " + << channel << ")" << std::endl; return false; } // @TODO: do some client rate limiting - NetworkPacket pkt( - TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size()); + NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size()); pkt << channel << message; Send(&pkt); return true; } -ModChannel *Client::getModChannel(const std::string &channel) +ModChannel* Client::getModChannel(const std::string &channel) { return m_modchannel_mgr->getModChannel(channel); } diff --git a/src/client/client.h b/src/client/client.h index f00c331ab..7455d78dc 100644 --- a/src/client/client.h +++ b/src/client/client.h @@ -49,7 +49,7 @@ class IWritableTextureSource; class IWritableShaderSource; class ISoundManager; class NodeDefManager; -// class IWritableCraftDefManager; +//class IWritableCraftDefManager; class ClientMediaDownloader; struct MapDrawControl; class ModChannelMgr; @@ -60,13 +60,11 @@ class Minimap; struct MinimapMapblock; class Camera; class NetworkPacket; -namespace con -{ +namespace con { class Connection; } -enum LocalClientState -{ +enum LocalClientState { LC_Created, LC_Init, LC_Ready @@ -90,7 +88,10 @@ class PacketCounter n->second++; } - void clear() { m_packets.clear(); } + void clear() + { + m_packets.clear(); + } u32 sum() const; void print(std::ostream &o) const; @@ -110,21 +111,28 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef NOTE: Nothing is thread-safe here. */ - Client(const char *playername, const std::string &password, - const std::string &address_name, MapDrawControl &control, - IWritableTextureSource *tsrc, IWritableShaderSource *shsrc, - IWritableItemDefManager *itemdef, NodeDefManager *nodedef, - ISoundManager *sound, MtEventManager *event, bool ipv6, - GameUI *game_ui); + Client( + const char *playername, + const std::string &password, + const std::string &address_name, + MapDrawControl &control, + IWritableTextureSource *tsrc, + IWritableShaderSource *shsrc, + IWritableItemDefManager *itemdef, + NodeDefManager *nodedef, + ISoundManager *sound, + MtEventManager *event, + bool ipv6, + GameUI *game_ui + ); ~Client(); DISABLE_CLASS_COPY(Client); // Load local mods into memory void scanModSubfolder(const std::string &mod_name, const std::string &mod_path, - std::string mod_subpath); - inline void scanModIntoMemory( - const std::string &mod_name, const std::string &mod_path) + std::string mod_subpath); + inline void scanModIntoMemory(const std::string &mod_name, const std::string &mod_path) { scanModSubfolder(mod_name, mod_path, ""); } @@ -134,6 +142,7 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef */ void Stop(); + bool isShutdown(); /* @@ -154,58 +163,58 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef * Command Handlers */ - void handleCommand(NetworkPacket *pkt); - - void handleCommand_Null(NetworkPacket *pkt){}; - void handleCommand_Deprecated(NetworkPacket *pkt); - void handleCommand_Hello(NetworkPacket *pkt); - void handleCommand_AuthAccept(NetworkPacket *pkt); - void handleCommand_AcceptSudoMode(NetworkPacket *pkt); - void handleCommand_DenySudoMode(NetworkPacket *pkt); - void handleCommand_AccessDenied(NetworkPacket *pkt); - void handleCommand_RemoveNode(NetworkPacket *pkt); - void handleCommand_AddNode(NetworkPacket *pkt); + void handleCommand(NetworkPacket* pkt); + + void handleCommand_Null(NetworkPacket* pkt) {}; + void handleCommand_Deprecated(NetworkPacket* pkt); + void handleCommand_Hello(NetworkPacket* pkt); + void handleCommand_AuthAccept(NetworkPacket* pkt); + void handleCommand_AcceptSudoMode(NetworkPacket* pkt); + void handleCommand_DenySudoMode(NetworkPacket* pkt); + void handleCommand_AccessDenied(NetworkPacket* pkt); + void handleCommand_RemoveNode(NetworkPacket* pkt); + void handleCommand_AddNode(NetworkPacket* pkt); void handleCommand_NodemetaChanged(NetworkPacket *pkt); - void handleCommand_BlockData(NetworkPacket *pkt); - void handleCommand_Inventory(NetworkPacket *pkt); - void handleCommand_TimeOfDay(NetworkPacket *pkt); + void handleCommand_BlockData(NetworkPacket* pkt); + void handleCommand_Inventory(NetworkPacket* pkt); + void handleCommand_TimeOfDay(NetworkPacket* pkt); void handleCommand_ChatMessage(NetworkPacket *pkt); - void handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt); - void handleCommand_ActiveObjectMessages(NetworkPacket *pkt); - void handleCommand_Movement(NetworkPacket *pkt); + void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt); + void handleCommand_ActiveObjectMessages(NetworkPacket* pkt); + void handleCommand_Movement(NetworkPacket* pkt); void handleCommand_Fov(NetworkPacket *pkt); - void handleCommand_HP(NetworkPacket *pkt); - void handleCommand_Breath(NetworkPacket *pkt); - void handleCommand_MovePlayer(NetworkPacket *pkt); - void handleCommand_DeathScreen(NetworkPacket *pkt); - void handleCommand_AnnounceMedia(NetworkPacket *pkt); - void handleCommand_Media(NetworkPacket *pkt); - void handleCommand_NodeDef(NetworkPacket *pkt); - void handleCommand_ItemDef(NetworkPacket *pkt); - void handleCommand_PlaySound(NetworkPacket *pkt); - void handleCommand_StopSound(NetworkPacket *pkt); + void handleCommand_HP(NetworkPacket* pkt); + void handleCommand_Breath(NetworkPacket* pkt); + void handleCommand_MovePlayer(NetworkPacket* pkt); + void handleCommand_DeathScreen(NetworkPacket* pkt); + void handleCommand_AnnounceMedia(NetworkPacket* pkt); + void handleCommand_Media(NetworkPacket* pkt); + void handleCommand_NodeDef(NetworkPacket* pkt); + void handleCommand_ItemDef(NetworkPacket* pkt); + void handleCommand_PlaySound(NetworkPacket* pkt); + void handleCommand_StopSound(NetworkPacket* pkt); void handleCommand_FadeSound(NetworkPacket *pkt); - void handleCommand_Privileges(NetworkPacket *pkt); - void handleCommand_InventoryFormSpec(NetworkPacket *pkt); - void handleCommand_DetachedInventory(NetworkPacket *pkt); - void handleCommand_ShowFormSpec(NetworkPacket *pkt); - void handleCommand_SpawnParticle(NetworkPacket *pkt); - void handleCommand_AddParticleSpawner(NetworkPacket *pkt); - void handleCommand_DeleteParticleSpawner(NetworkPacket *pkt); - void handleCommand_HudAdd(NetworkPacket *pkt); - void handleCommand_HudRemove(NetworkPacket *pkt); - void handleCommand_HudChange(NetworkPacket *pkt); - void handleCommand_HudSetFlags(NetworkPacket *pkt); - void handleCommand_HudSetParam(NetworkPacket *pkt); - void handleCommand_HudSetSky(NetworkPacket *pkt); - void handleCommand_HudSetSun(NetworkPacket *pkt); - void handleCommand_HudSetMoon(NetworkPacket *pkt); - void handleCommand_HudSetStars(NetworkPacket *pkt); - void handleCommand_CloudParams(NetworkPacket *pkt); - void handleCommand_OverrideDayNightRatio(NetworkPacket *pkt); - void handleCommand_LocalPlayerAnimations(NetworkPacket *pkt); - void handleCommand_EyeOffset(NetworkPacket *pkt); - void handleCommand_UpdatePlayerList(NetworkPacket *pkt); + void handleCommand_Privileges(NetworkPacket* pkt); + void handleCommand_InventoryFormSpec(NetworkPacket* pkt); + void handleCommand_DetachedInventory(NetworkPacket* pkt); + void handleCommand_ShowFormSpec(NetworkPacket* pkt); + void handleCommand_SpawnParticle(NetworkPacket* pkt); + void handleCommand_AddParticleSpawner(NetworkPacket* pkt); + void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt); + void handleCommand_HudAdd(NetworkPacket* pkt); + void handleCommand_HudRemove(NetworkPacket* pkt); + void handleCommand_HudChange(NetworkPacket* pkt); + void handleCommand_HudSetFlags(NetworkPacket* pkt); + void handleCommand_HudSetParam(NetworkPacket* pkt); + void handleCommand_HudSetSky(NetworkPacket* pkt); + void handleCommand_HudSetSun(NetworkPacket* pkt); + void handleCommand_HudSetMoon(NetworkPacket* pkt); + void handleCommand_HudSetStars(NetworkPacket* pkt); + void handleCommand_CloudParams(NetworkPacket* pkt); + void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt); + void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt); + void handleCommand_EyeOffset(NetworkPacket* pkt); + void handleCommand_UpdatePlayerList(NetworkPacket* pkt); void handleCommand_ModChannelMsg(NetworkPacket *pkt); void handleCommand_ModChannelSignal(NetworkPacket *pkt); void handleCommand_SrpBytesSandB(NetworkPacket *pkt); @@ -216,30 +225,31 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef void ProcessData(NetworkPacket *pkt); - void Send(NetworkPacket *pkt); + void Send(NetworkPacket* pkt); void interact(InteractAction action, const PointedThing &pointed); - void sendNodemetaFields( - v3s16 p, const std::string &formname, const StringMap &fields); - void sendInventoryFields(const std::string &formname, const StringMap &fields); + void sendNodemetaFields(v3s16 p, const std::string &formname, + const StringMap &fields); + void sendInventoryFields(const std::string &formname, + const StringMap &fields); void sendInventoryAction(InventoryAction *a); void sendChatMessage(const std::wstring &message); void clearOutChatQueue(); - void sendChangePassword( - const std::string &oldpassword, const std::string &newpassword); + void sendChangePassword(const std::string &oldpassword, + const std::string &newpassword); void sendDamage(u16 damage); void sendRespawn(); void sendReady(); - ClientEnvironment &getEnv() { return m_env; } + ClientEnvironment& getEnv() { return m_env; } ITextureSource *tsrc() { return getTextureSource(); } ISoundManager *sound() { return getSoundManager(); } static const std::string &getBuiltinLuaPath(); static const std::string &getClientModsLuaPath(); const std::vector &getMods() const override; - const ModSpec *getModSpec(const std::string &modname) const override; + const ModSpec* getModSpec(const std::string &modname) const override; // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent) void removeNode(v3s16 p); @@ -258,7 +268,7 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef bool updateWieldedItem(); /* InventoryManager interface */ - Inventory *getInventory(const InventoryLocation &loc) override; + Inventory* getInventory(const InventoryLocation &loc) override; void inventoryAction(InventoryAction *a) override; // Send the item number 'item' as player item to the server @@ -278,40 +288,29 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef u16 getHP(); bool checkPrivilege(const std::string &priv) const - { - return g_settings->getBool("priv_bypass") - ? true - : (m_privileges.count(priv) != 0); - } + { return g_settings->getBool("priv_bypass") ? true : (m_privileges.count(priv) != 0); } const std::unordered_set &getPrivilegeList() const - { - return m_privileges; - } + { return m_privileges; } bool getChatMessage(std::wstring &message); - void typeChatMessage(const std::wstring &message); + void typeChatMessage(const std::wstring& message); - u64 getMapSeed() { return m_map_seed; } + u64 getMapSeed(){ return m_map_seed; } - void addUpdateMeshTask( - v3s16 blockpos, bool ack_to_server = false, bool urgent = false); + void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false); // Including blocks at appropriate edges - void addUpdateMeshTaskWithEdge( - v3s16 blockpos, bool ack_to_server = false, bool urgent = false); - void addUpdateMeshTaskForNode( - v3s16 nodepos, bool ack_to_server = false, bool urgent = false); + void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false); + void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false); void updateAllMapBlocks(); void updateCameraOffset(v3s16 camera_offset) - { - m_mesh_update_thread.m_camera_offset = camera_offset; - } + { m_mesh_update_thread.m_camera_offset = camera_offset; } bool hasClientEvents() const { return !m_client_event_queue.empty(); } // Get event from queue. If queue is empty, it triggers an assertion failure. - ClientEvent *getClientEvent(); + ClientEvent * getClientEvent(); bool accessDenied() const { return m_access_denied; } @@ -327,12 +326,17 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef // disconnect client when CSM failed. const std::string &accessDeniedReason() const { return m_access_denied_reason; } - const bool itemdefReceived() const { return m_itemdef_received; } - const bool nodedefReceived() const { return m_nodedef_received; } - const bool mediaReceived() const { return !m_media_downloader; } - const bool activeObjectsReceived() const { return m_activeobjects_received; } + const bool itemdefReceived() const + { return m_itemdef_received; } + const bool nodedefReceived() const + { return m_nodedef_received; } + const bool mediaReceived() const + { return !m_media_downloader; } + const bool activeObjectsReceived() const + { return m_activeobjects_received; } - u16 getProtoVersion() { return m_proto_ver; } + u16 getProtoVersion() + { return m_proto_ver; } bool connectedToServer(); void confirmRegistration(); @@ -346,29 +350,28 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef float getRTT(); float getCurRate(); - Minimap *getMinimap() { return m_minimap; } - void setCamera(Camera *camera) { m_camera = camera; } + Minimap* getMinimap() { return m_minimap; } + void setCamera(Camera* camera) { m_camera = camera; } - Camera *getCamera() { return m_camera; } + Camera* getCamera () { return m_camera; } bool shouldShowMinimap() const; // IGameDef interface - IItemDefManager *getItemDefManager() override; - IWritableItemDefManager *getWritableItemDefManager() override; - const NodeDefManager *getNodeDefManager() override; - NodeDefManager *getWritableNodeDefManager() override; - ICraftDefManager *getCraftDefManager() override; - ITextureSource *getTextureSource(); - virtual IWritableShaderSource *getShaderSource(); + IItemDefManager* getItemDefManager() override; + IWritableItemDefManager* getWritableItemDefManager() override; + const NodeDefManager* getNodeDefManager() override; + NodeDefManager* getWritableNodeDefManager() override; + ICraftDefManager* getCraftDefManager() override; + ITextureSource* getTextureSource(); + virtual IWritableShaderSource* getShaderSource(); u16 allocateUnknownNodeId(const std::string &name) override; - virtual ISoundManager *getSoundManager(); - MtEventManager *getEventManager(); - virtual ParticleManager *getParticleManager(); - bool checkLocalPrivilege(const std::string &priv) { return checkPrivilege(priv); } - virtual scene::IAnimatedMesh *getMesh( - const std::string &filename, bool cache = false); - const std::string *getModFile(std::string filename); + virtual ISoundManager* getSoundManager(); + MtEventManager* getEventManager(); + virtual ParticleManager* getParticleManager(); + bool checkLocalPrivilege(const std::string &priv){ return checkPrivilege(priv); } + virtual scene::IAnimatedMesh* getMesh(const std::string &filename, bool cache = false); + const std::string* getModFile(std::string filename); std::string getModStoragePath() const override; bool registerModStorage(ModMetadata *meta) override; @@ -377,7 +380,7 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef // The following set of functions is used by ClientMediaDownloader // Insert a media file appropriately into the appropriate manager bool loadMedia(const std::string &data, const std::string &filename, - bool from_media_push = false); + bool from_media_push = false); // Send a request for conventional media transfer void request_media(const std::vector &file_requests); @@ -385,7 +388,10 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef void makeScreenshot(); - inline void pushToChatQueue(ChatMessage *cec) { m_chat_queue.push(cec); } + inline void pushToChatQueue(ChatMessage *cec) + { + m_chat_queue.push(cec); + } ClientScripting *getScript() { return m_script; } const bool modsLoaded() const { return m_mods_loaded; } @@ -396,17 +402,26 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef const Address getServerAddress(); - const std::string &getAddressName() const { return m_address_name; } + const std::string &getAddressName() const + { + return m_address_name; + } - inline u64 getCSMRestrictionFlags() const { return m_csm_restriction_flags; } + inline u64 getCSMRestrictionFlags() const + { + return m_csm_restriction_flags; + } inline bool checkCSMRestrictionFlag(CSMRestrictionFlags flag) const { - // return m_csm_restriction_flags & flag; + //return m_csm_restriction_flags & flag; return false; } - u32 getCSMNodeRangeLimit() const { return m_csm_restriction_noderange; } + u32 getCSMNodeRangeLimit() const + { + return m_csm_restriction_noderange; + } inline std::unordered_map &getHUDTranslationMap() { @@ -415,19 +430,19 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef bool joinModChannel(const std::string &channel) override; bool leaveModChannel(const std::string &channel) override; - bool sendModChannelMessage( - const std::string &channel, const std::string &message) override; + bool sendModChannelMessage(const std::string &channel, + const std::string &message) override; ModChannel *getModChannel(const std::string &channel) override; const std::string &getFormspecPrepend() const { return m_env.getLocalPlayer()->formspec_prepend; } - + void sendPlayerPos(v3f pos); void sendPlayerPos(); MeshUpdateThread m_mesh_update_thread; - + private: void loadMods(); bool checkBuiltinIntegrity(); @@ -436,11 +451,13 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef void peerAdded(con::Peer *peer) override; void deletingPeer(con::Peer *peer, bool timeout) override; - void initLocalMapSaving(const Address &address, const std::string &hostname, + void initLocalMapSaving(const Address &address, + const std::string &hostname, bool is_local_server); void ReceiveAll(); + void deleteAuthData(); // helper method shared with clientpackethandler static AuthMechanism choseAuthMech(const u32 mechs); @@ -453,7 +470,8 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef void sendRemovedSounds(std::vector &soundList); // Helper function - inline std::string getPlayerName() { return m_env.getLocalPlayer()->getName(); } + inline std::string getPlayerName() + { return m_env.getLocalPlayer()->getName(); } bool canSendChatMessage() const; @@ -470,6 +488,7 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef ISoundManager *m_sound; MtEventManager *m_event; + ClientEnvironment m_env; ParticleManager m_particle_manager; std::unique_ptr m_con; @@ -497,8 +516,8 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef int m_crack_level = -1; v3s16 m_crack_pos; // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT - // s32 m_daynight_i; - // u32 m_daynight_ratio; + //s32 m_daynight_i; + //u32 m_daynight_ratio; std::queue m_out_chat_queue; u32 m_last_chat_message_sent; float m_chat_message_allowance = 5.0f; @@ -557,7 +576,7 @@ class Client : public con::PeerHandler, public InventoryManager, public IGameDef // Detached inventories // key = name - std::unordered_map m_detached_inventories; + std::unordered_map m_detached_inventories; // Storage for mesh data for creating multiple instances of the same mesh StringMap m_mesh_data; diff --git a/src/client/clientenvironment.cpp b/src/client/clientenvironment.cpp index 2f95177f3..3f82bd316 100644 --- a/src/client/clientenvironment.cpp +++ b/src/client/clientenvironment.cpp @@ -45,7 +45,9 @@ with this program; if not, write to the Free Software Foundation, Inc., class CAOShaderConstantSetter : public IShaderConstantSetter { public: - CAOShaderConstantSetter() : m_emissive_color_setting("emissiveColor") {} + CAOShaderConstantSetter(): + m_emissive_color_setting("emissiveColor") + {} ~CAOShaderConstantSetter() override = default; @@ -59,15 +61,15 @@ class CAOShaderConstantSetter : public IShaderConstantSetter video::SColorf emissive_color(m_emissive_color); float as_array[4] = { - emissive_color.r, - emissive_color.g, - emissive_color.b, - emissive_color.a, + emissive_color.r, + emissive_color.g, + emissive_color.b, + emissive_color.a, }; m_emissive_color_setting.set(as_array, services); } - void onSetMaterial(const video::SMaterial &material) override + void onSetMaterial(const video::SMaterial& material) override { m_emissive_color = material.EmissiveColor; } @@ -80,19 +82,25 @@ class CAOShaderConstantSetter : public IShaderConstantSetter class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory { public: - CAOShaderConstantSetterFactory() {} + CAOShaderConstantSetterFactory() + {} - virtual IShaderConstantSetter *create() { return new CAOShaderConstantSetter(); } + virtual IShaderConstantSetter* create() + { + return new CAOShaderConstantSetter(); + } }; /* ClientEnvironment */ -ClientEnvironment::ClientEnvironment( - ClientMap *map, ITextureSource *texturesource, Client *client) : - Environment(client), - m_map(map), m_texturesource(texturesource), m_client(client) +ClientEnvironment::ClientEnvironment(ClientMap *map, + ITextureSource *texturesource, Client *client): + Environment(client), + m_map(map), + m_texturesource(texturesource), + m_client(client) { auto *shdrsrc = m_client->getShaderSource(); shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory()); @@ -112,12 +120,12 @@ ClientEnvironment::~ClientEnvironment() delete m_local_player; } -Map &ClientEnvironment::getMap() +Map & ClientEnvironment::getMap() { return *m_map; } -ClientMap &ClientEnvironment::getClientMap() +ClientMap & ClientEnvironment::getClientMap() { return *m_map; } @@ -127,7 +135,8 @@ void ClientEnvironment::setLocalPlayer(LocalPlayer *player) /* It is a failure if already is a local player */ - FATAL_ERROR_IF(m_local_player != NULL, "Local player already allocated"); + FATAL_ERROR_IF(m_local_player != NULL, + "Local player already allocated"); m_local_player = player; } @@ -157,21 +166,21 @@ void ClientEnvironment::step(float dtime) /* Maximum position increment */ - // f32 position_max_increment = 0.05*BS; - f32 position_max_increment = 0.1 * BS; + //f32 position_max_increment = 0.05*BS; + f32 position_max_increment = 0.1*BS; // Maximum time increment (for collision detection etc) // time = distance / speed f32 dtime_max_increment = 1; - if (player_speed > 0.001) + if(player_speed > 0.001) dtime_max_increment = position_max_increment / player_speed; // Maximum time increment is 10ms or lower - if (dtime_max_increment > 0.01) + if(dtime_max_increment > 0.01) dtime_max_increment = 0.01; // Don't allow overly huge dtime - if (dtime > 0.5) + if(dtime > 0.5) dtime = 0.5; f32 dtime_downcount = dtime; @@ -181,19 +190,23 @@ void ClientEnvironment::step(float dtime) */ u32 loopcount = 0; - do { + do + { loopcount++; f32 dtime_part; - if (dtime_downcount > dtime_max_increment) { + if(dtime_downcount > dtime_max_increment) + { dtime_part = dtime_max_increment; dtime_downcount -= dtime_part; - } else { + } + else + { dtime_part = dtime_downcount; /* - Setting this to 0 (no -=dtime_part) disables an infinite - loop when dtime_part is so small that dtime_downcount -= - dtime_part does nothing + Setting this to 0 (no -=dtime_part) disables an infinite loop + when dtime_part is so small that dtime_downcount -= dtime_part + does nothing */ dtime_downcount = 0; } @@ -207,40 +220,33 @@ void ClientEnvironment::step(float dtime) lplayer->applyControl(dtime_part, this); // Apply physics - if (!free_move && !is_climbing && - !g_settings->getBool("freecam")) { + if (!free_move && !is_climbing && ! g_settings->getBool("freecam")) { // Gravity v3f speed = lplayer->getSpeed(); if (!lplayer->in_liquid) speed.Y -= lplayer->movement_gravity * - lplayer->physics_override_gravity * - dtime_part * 2.0f; + lplayer->physics_override_gravity * dtime_part * 2.0f; // Liquid floating / sinking if (lplayer->in_liquid && !lplayer->swimming_vertical && !lplayer->swimming_pitch) - speed.Y -= lplayer->movement_liquid_sink * - dtime_part * 2.0f; + speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f; // Liquid resistance if (lplayer->in_liquid_stable || lplayer->in_liquid) { - // How much the node's viscosity blocks movement, - // ranges between 0 and 1. Should match the scale - // at which viscosity increase affects other - // liquid attributes. + // How much the node's viscosity blocks movement, ranges + // between 0 and 1. Should match the scale at which viscosity + // increase affects other liquid attributes. static const f32 viscosity_factor = 0.3f; - v3f d_wanted = -speed / - lplayer->movement_liquid_fluidity; + v3f d_wanted = -speed / lplayer->movement_liquid_fluidity; f32 dl = d_wanted.getLength(); if (dl > lplayer->movement_liquid_fluidity_smooth) dl = lplayer->movement_liquid_fluidity_smooth; - dl *= (lplayer->liquid_viscosity * - viscosity_factor) + - (1 - viscosity_factor); - v3f d = d_wanted.normalize() * - (dl * dtime_part * 100.0f); + dl *= (lplayer->liquid_viscosity * viscosity_factor) + + (1 - viscosity_factor); + v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f); speed += d; } @@ -252,15 +258,14 @@ void ClientEnvironment::step(float dtime) This also does collision detection. */ lplayer->move(dtime_part, this, position_max_increment, - &player_collisions); + &player_collisions); } } while (dtime_downcount > 0.001); bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal(); for (const CollisionInfo &info : player_collisions) { - v3f speed_diff = info.new_speed - info.old_speed; - ; + v3f speed_diff = info.new_speed - info.old_speed;; // Handle only fall damage // (because otherwise walking against something in fast_move kills you) if (speed_diff.Y < 0 || info.old_speed.Y >= 0) @@ -268,12 +273,12 @@ void ClientEnvironment::step(float dtime) // Get rid of other components speed_diff.X = 0; speed_diff.Z = 0; - f32 pre_factor = 1; // 1 hp per node/s - f32 tolerance = BS * 14; // 5 without damage - f32 post_factor = 1; // 1 hp per node/s + f32 pre_factor = 1; // 1 hp per node/s + f32 tolerance = BS*14; // 5 without damage + f32 post_factor = 1; // 1 hp per node/s if (info.type == COLLISION_NODE) { - const ContentFeatures &f = m_client->ndef()->get( - m_map->getNode(info.node_p)); + const ContentFeatures &f = m_client->ndef()-> + get(m_map->getNode(info.node_p)); // Determine fall damage multiplier int addp = itemgroup_get(f.groups, "fall_damage_add_percent"); pre_factor = 1.0f + (float)addp / 100.0f; @@ -284,8 +289,8 @@ void ClientEnvironment::step(float dtime) u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX); if (damage != 0) { damageLocalPlayer(damage, true); - m_client->getEventManager()->put(new SimpleTriggerEvent( - MtEvent::PLAYER_FALLING_DAMAGE)); + m_client->getEventManager()->put( + new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE)); } } } @@ -314,8 +319,7 @@ void ClientEnvironment::step(float dtime) */ bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21); - auto cb_state = [this, dtime, update_lighting, day_night_ratio]( - ClientActiveObject *cao) { + auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) { // Step object cao->step(dtime, this); @@ -333,10 +337,11 @@ void ClientEnvironment::step(float dtime) ClientSimpleObject *simple = *i; simple->step(dtime); - if (simple->m_to_be_removed) { + if(simple->m_to_be_removed) { delete simple; i = m_simple_objects.erase(i); - } else { + } + else { ++i; } } @@ -347,18 +352,20 @@ void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple) m_simple_objects.push_back(simple); } -GenericCAO *ClientEnvironment::getGenericCAO(u16 id) +GenericCAO* ClientEnvironment::getGenericCAO(u16 id) { ClientActiveObject *obj = getActiveObject(id); if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC) - return (GenericCAO *)obj; + return (GenericCAO*) obj; return NULL; } -bool isFreeClientActiveObjectId(const u16 id, ClientActiveObjectMap &objects) +bool isFreeClientActiveObjectId(const u16 id, + ClientActiveObjectMap &objects) { return id != 0 && objects.find(id) == objects.end(); + } u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects) @@ -366,8 +373,8 @@ u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects) // try to reuse id's as late as possible static u16 last_used_id = 0; u16 startid = last_used_id; - for (;;) { - last_used_id++; + for(;;) { + last_used_id ++; if (isFreeClientActiveObjectId(last_used_id, objects)) return last_used_id; @@ -389,27 +396,33 @@ u16 ClientEnvironment::addActiveObject(ClientActiveObject *object) return object->getId(); } -void ClientEnvironment::addActiveObject(u16 id, u8 type, const std::string &init_data) +void ClientEnvironment::addActiveObject(u16 id, u8 type, + const std::string &init_data) { - ClientActiveObject *obj = ClientActiveObject::create( - (ActiveObjectType)type, m_client, this); - if (obj == NULL) { - infostream << "ClientEnvironment::addActiveObject(): " - << "id=" << id << " type=" << type - << ": Couldn't create object" << std::endl; + ClientActiveObject* obj = + ClientActiveObject::create((ActiveObjectType) type, m_client, this); + if(obj == NULL) + { + infostream<<"ClientEnvironment::addActiveObject(): " + <<"id="<setId(id); - try { + try + { obj->initialize(init_data); - } catch (SerializationError &e) { - errorstream << "ClientEnvironment::addActiveObject():" - << " id=" << id << " type=" << type - << ": SerializationError in initialize(): " << e.what() - << ": init_data=" << serializeJsonString(init_data) - << std::endl; + } + catch(SerializationError &e) + { + errorstream<<"ClientEnvironment::addActiveObject():" + <<" id="<processMessage(data); } catch (SerializationError &e) { - errorstream << "ClientEnvironment::processActiveObjectMessage():" - << " id=" << id << " type=" << obj->getType() - << " SerializationError in processMessage(): " << e.what() - << std::endl; + errorstream<<"ClientEnvironment::processActiveObjectMessage():" + << " id=" << id << " type=" << obj->getType() + << " SerializationError in processMessage(): " << e.what() + << std::endl; } } @@ -499,12 +513,12 @@ ClientEnvEvent ClientEnvironment::getClientEnvEvent() } void ClientEnvironment::getSelectedActiveObjects( - const core::line3d &shootline_on_map, - std::vector &objects) + const core::line3d &shootline_on_map, + std::vector &objects) { std::vector allObjects; - getActiveObjects(shootline_on_map.start, shootline_on_map.getLength() + 10.0f, - allObjects); + getActiveObjects(shootline_on_map.start, + shootline_on_map.getLength() + 10.0f, allObjects); const v3f line_vector = shootline_on_map.getVector(); for (const auto &allObject : allObjects) { @@ -514,17 +528,15 @@ void ClientEnvironment::getSelectedActiveObjects( continue; const v3f &pos = obj->getPosition(); - aabb3f offsetted_box( - selection_box.MinEdge + pos, selection_box.MaxEdge + pos); + aabb3f offsetted_box(selection_box.MinEdge + pos, + selection_box.MaxEdge + pos); v3f current_intersection; v3s16 current_normal; if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector, - ¤t_intersection, ¤t_normal)) { - objects.emplace_back((s16)obj->getId(), current_intersection, - current_normal, - (current_intersection - shootline_on_map.start) - .getLengthSQ()); + ¤t_intersection, ¤t_normal)) { + objects.emplace_back((s16) obj->getId(), current_intersection, current_normal, + (current_intersection - shootline_on_map.start).getLengthSQ()); } } } diff --git a/src/client/clientenvironment.h b/src/client/clientenvironment.h index a24ea209a..52d999c99 100644 --- a/src/client/clientenvironment.h +++ b/src/client/clientenvironment.h @@ -49,27 +49,25 @@ enum ClientEnvEventType struct ClientEnvEvent { ClientEnvEventType type; - union - { - // struct{ + union { + //struct{ //} none; - struct - { + struct{ u16 amount; bool send_to_server; } player_damage; }; }; -typedef std::unordered_map ClientActiveObjectMap; +typedef std::unordered_map ClientActiveObjectMap; class ClientEnvironment : public Environment { public: ClientEnvironment(ClientMap *map, ITextureSource *texturesource, Client *client); ~ClientEnvironment(); - Map &getMap(); - ClientMap &getClientMap(); + Map & getMap(); + ClientMap & getClientMap(); Client *getGameDef() { return m_client; } void setScript(ClientScripting *script) { m_script = script; } @@ -89,13 +87,13 @@ class ClientEnvironment : public Environment ActiveObjects */ - GenericCAO *getGenericCAO(u16 id); - ClientActiveObject *getActiveObject(u16 id) + GenericCAO* getGenericCAO(u16 id); + ClientActiveObject* getActiveObject(u16 id) { return m_ao_manager.getActiveObject(id); } - - std::unordered_map getAllActiveObjects() + + std::unordered_map getAllActiveObjects() { return m_ao_manager.getAllActiveObjects(); } @@ -119,7 +117,7 @@ class ClientEnvironment : public Environment Callbacks for activeobjects */ - void damageLocalPlayer(u16 damage, bool handle_hp = true); + void damageLocalPlayer(u16 damage, bool handle_hp=true); /* Client likes to call these @@ -127,7 +125,7 @@ class ClientEnvironment : public Environment // Get all nearby objects void getActiveObjects(const v3f &origin, f32 max_d, - std::vector &dest) + std::vector &dest) { return m_ao_manager.getActiveObjects(origin, max_d, dest); } @@ -137,18 +135,17 @@ class ClientEnvironment : public Environment // Get event from queue. If queue is empty, it triggers an assertion failure. ClientEnvEvent getClientEnvEvent(); - virtual void getSelectedActiveObjects(const core::line3d &shootline_on_map, - std::vector &objects); + virtual void getSelectedActiveObjects( + const core::line3d &shootline_on_map, + std::vector &objects + ); const std::list &getPlayerNames() { return m_player_names; } void addPlayerName(const std::string &name) { m_player_names.push_back(name); } void removePlayerName(const std::string &name) { m_player_names.remove(name); } void updateCameraOffset(const v3s16 &camera_offset) - { - m_camera_offset = camera_offset; - } + { m_camera_offset = camera_offset; } v3s16 getCameraOffset() const { return m_camera_offset; } - private: ClientMap *m_map; LocalPlayer *m_local_player = nullptr; @@ -156,7 +153,7 @@ class ClientEnvironment : public Environment Client *m_client; ClientScripting *m_script = nullptr; client::ActiveObjectMgr m_ao_manager; - std::vector m_simple_objects; + std::vector m_simple_objects; std::queue m_client_event_queue; IntervalLimiter m_active_object_light_update_interval; std::list m_player_names; diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index b96c7e7f6..ce16797e6 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -36,10 +36,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "network/networkexceptions.h" #if USE_SOUND -#include "sound_openal.h" + #include "sound_openal.h" #endif #ifdef __ANDROID__ -#include "porting.h" + #include "porting.h" #endif /* mainmenumanager.h @@ -87,6 +87,7 @@ ClientLauncher::~ClientLauncher() #endif } + bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) { /* This function is called when a client must be started. @@ -94,7 +95,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) * - Singleplayer (address but map provided) * - Join server (no map but address provided) * - Local server (for main menu only) - */ + */ init_args(start_data, cmd_args); @@ -130,7 +131,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) This changes the minimum allowed number of vertices in a VBO. Default is 500. */ - // driver->setMinHardwareBufferVertexCount(50); + //driver->setMinHardwareBufferVertexCount(50); // Create game callback for menus g_gamecallback = new MainGameCallback(); @@ -139,8 +140,8 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) init_input(); - RenderingEngine::get_scene_manager()->getParameters()->setAttribute( - scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); + RenderingEngine::get_scene_manager()->getParameters()-> + setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); guienv = RenderingEngine::get_gui_env(); skin = RenderingEngine::get_gui_env()->getSkin(); @@ -177,8 +178,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) g_fontengine = new FontEngine(g_settings, guienv); FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed."); -#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || \ - IRRLICHT_VERSION_MAJOR >= 2 +#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 // Irrlicht 1.8 input colours skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128)); skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49)); @@ -186,13 +186,12 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) // Create the menu clouds if (!g_menucloudsmgr) - g_menucloudsmgr = RenderingEngine::get_scene_manager() - ->createNewSceneManager(); + g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager(); if (!g_menuclouds) g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand()); g_menuclouds->setHeight(100.0f); g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255)); - scene::ICameraSceneNode *camera; + scene::ICameraSceneNode* camera; camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100)); camera->setFarValue(10000); @@ -215,17 +214,17 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) bool retval = true; bool *kill = porting::signal_handler_killstatus(); - while (RenderingEngine::run() && !*kill && !g_gamecallback->shutdown_requested) { + while (RenderingEngine::run() && !*kill && + !g_gamecallback->shutdown_requested) { // Set the window caption const wchar_t *text = wgettext("Main Menu"); - RenderingEngine::get_raw_device()->setWindowCaption( - (utf8_to_wide(PROJECT_NAME_C) + L" " + - utf8_to_wide(g_version_hash) + L" [" + - text + L"]") - .c_str()); + RenderingEngine::get_raw_device()-> + setWindowCaption((utf8_to_wide(PROJECT_NAME_C) + + L" " + utf8_to_wide(g_version_hash) + + L" [" + text + L"]").c_str()); delete[] text; - try { // This is used for catching disconnects + try { // This is used for catching disconnects RenderingEngine::get_gui_env()->clear(); @@ -234,11 +233,11 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) custom gui elements directly on the screen. Otherwise they won't be automatically drawn. */ - guiroot = RenderingEngine::get_gui_env()->addStaticText( - L"", core::rect(0, 0, 10000, 10000)); + guiroot = RenderingEngine::get_gui_env()->addStaticText(L"", + core::rect(0, 0, 10000, 10000)); - bool game_has_run = launch_game(error_message, - reconnect_requested, start_data, cmd_args); + bool game_has_run = launch_game(error_message, reconnect_requested, + start_data, cmd_args); // Reset the reconnect_requested flag reconnect_requested = false; @@ -259,23 +258,26 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) // Break out of menu-game loop to shut down cleanly if (!RenderingEngine::get_raw_device()->run() || *kill) { if (!g_settings_path.empty()) - g_settings->updateConfigFile( - g_settings_path.c_str()); + g_settings->updateConfigFile(g_settings_path.c_str()); break; } RenderingEngine::get_video_driver()->setTextureCreationFlag( - video::ETCF_CREATE_MIP_MAPS, - g_settings->getBool("mip_map")); + video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map")); #ifdef HAVE_TOUCHSCREENGUI - receiver->m_touchscreengui = new TouchScreenGUI( - RenderingEngine::get_raw_device(), receiver); + receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver); g_touchscreengui = receiver->m_touchscreengui; #endif - the_game(kill, input, start_data, error_message, chat_backend, - &reconnect_requested); + the_game( + kill, + input, + start_data, + error_message, + chat_backend, + &reconnect_requested + ); RenderingEngine::get_scene_manager()->clear(); #ifdef HAVE_TOUCHSCREENGUI @@ -284,7 +286,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) receiver->m_touchscreengui = NULL; #endif - } // try + } //try catch (con::PeerNotFoundException &e) { error_message = gettext("Connection error (timed out?)"); errorstream << error_message << std::endl; @@ -302,8 +304,8 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) // If no main menu, show error and exit if (skip_main_menu) { if (!error_message.empty()) { - verbosestream << "error_message = " << error_message - << std::endl; + verbosestream << "error_message = " + << error_message << std::endl; retval = false; } break; @@ -337,8 +339,8 @@ void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_ar list_video_modes = cmd_args.getFlag("videomodes"); - random_input = g_settings->getBool("random_input") || - cmd_args.getFlag("random-input"); + random_input = g_settings->getBool("random_input") + || cmd_args.getFlag("random-input"); } bool ClientLauncher::init_engine() @@ -370,14 +372,14 @@ void ClientLauncher::init_input() } input->joystick.onJoystickConnect(joystick_infos); } else { - errorstream << "Could not activate joystick support." - << std::endl; + errorstream << "Could not activate joystick support." << std::endl; } } } -bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requested, - GameStartData &start_data, const Settings &cmd_args) +bool ClientLauncher::launch_game(std::string &error_message, + bool reconnect_requested, GameStartData &start_data, + const Settings &cmd_args) { // Prepare and check the start data to launch a game std::string error_message_lua = error_message; @@ -392,8 +394,8 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ getline(passfile, start_data.password); } else { error_message = gettext("Provided password file " - "failed to open: ") + - cmd_args.get("password-file"); + "failed to open: ") + + cmd_args.get("password-file"); errorstream << error_message << std::endl; return false; } @@ -408,7 +410,7 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ spec.gameid = getWorldGameId(spec.path, true); spec.name = _("[--world parameter]"); - if (spec.gameid.empty()) { // Create new + if (spec.gameid.empty()) { // Create new spec.gameid = g_settings->get("default_game"); spec.name += " [new]"; } @@ -422,11 +424,11 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ // Initialize menu data // TODO: Re-use existing structs (GameStartData) MainMenuData menudata; - menudata.address = start_data.address; - menudata.name = start_data.name; - menudata.password = start_data.password; - menudata.port = itos(start_data.socket_port); - menudata.script_data.errormessage = error_message_lua; + menudata.address = start_data.address; + menudata.name = start_data.name; + menudata.password = start_data.password; + menudata.port = itos(start_data.socket_port); + menudata.script_data.errormessage = error_message_lua; menudata.script_data.reconnect_requested = reconnect_requested; main_menu(&menudata); @@ -436,9 +438,8 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ return false; if (!menudata.script_data.errormessage.empty()) { - /* The calling function will pass this back into this function - * upon the next iteration (if any) causing it to be displayed by - * the GUI + /* The calling function will pass this back into this function upon the + * next iteration (if any) causing it to be displayed by the GUI */ error_message = menudata.script_data.errormessage; return false; @@ -465,7 +466,7 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ server_description = menudata.serverdescription; start_data.local_server = !menudata.simple_singleplayer_mode && - start_data.address.empty(); + start_data.address.empty(); } if (!RenderingEngine::run()) @@ -486,9 +487,9 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ g_settings->set("name", start_data.name); if (!start_data.address.empty()) { ServerListSpec server; - server["name"] = server_name; - server["address"] = start_data.address; - server["port"] = itos(start_data.socket_port); + server["name"] = server_name; + server["address"] = start_data.address; + server["port"] = itos(start_data.socket_port); server["description"] = server_description; ServerList::insert(server); } @@ -502,21 +503,21 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ } auto &worldspec = start_data.world_spec; - infostream << "Selected world: " << worldspec.name << " [" << worldspec.path - << "]" << std::endl; + infostream << "Selected world: " << worldspec.name + << " [" << worldspec.path << "]" << std::endl; if (start_data.address.empty()) { // For singleplayer and local server if (worldspec.path.empty()) { error_message = gettext("No world selected and no address " - "provided. Nothing to do."); + "provided. Nothing to do."); errorstream << error_message << std::endl; return false; } if (!fs::PathExists(worldspec.path)) { - error_message = gettext("Provided world path doesn't exist: ") + - worldspec.path; + error_message = gettext("Provided world path doesn't exist: ") + + worldspec.path; errorstream << error_message << std::endl; return false; } @@ -524,8 +525,8 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ // Load gamespec for required game start_data.game_spec = findWorldSubgame(worldspec.path); if (!start_data.game_spec.isValid()) { - error_message = gettext("Could not find or load game \"") + - worldspec.gameid + "\""; + error_message = gettext("Could not find or load game \"") + + worldspec.gameid + "\""; errorstream << error_message << std::endl; return false; } @@ -600,7 +601,7 @@ void ClientLauncher::speed_tests() for (u32 i = 0; i < ii; i++) { tempstring2 += "asd"; } - for (u32 i = 0; i < ii + 1; i++) { + for (u32 i = 0; i < ii+1; i++) { tempstring += "asd"; if (tempstring == tempstring2) break; @@ -609,7 +610,7 @@ void ClientLauncher::speed_tests() } infostream << "All of the following tests should take around 100ms each." - << std::endl; + << std::endl; { TimeTaker timer("Testing floating-point conversion speed"); @@ -639,7 +640,7 @@ void ClientLauncher::speed_tests() const s16 ii = 300; for (s16 y = 0; y < ii; y++) { for (s16 x = 0; x < ii; x++) { - map1[v2s16(x, y)] = tempf; + map1[v2s16(x, y)] = tempf; tempf += 1; } } @@ -665,7 +666,7 @@ void ClientLauncher::speed_tests() } } // Do at least 10ms - while (timer.getTimerTime() < 10); + while(timer.getTimerTime() < 10); u32 dtime = timer.stop(); u32 per_ms = n / dtime; diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h index 1828272b1..b280d8e6b 100644 --- a/src/client/clientlauncher.h +++ b/src/client/clientlauncher.h @@ -40,7 +40,7 @@ class ClientLauncher void init_input(); bool launch_game(std::string &error_message, bool reconnect_requested, - GameStartData &start_data, const Settings &cmd_args); + GameStartData &start_data, const Settings &cmd_args); void main_menu(MainMenuData *menudata); diff --git a/src/client/clientmap.cpp b/src/client/clientmap.cpp index dea354c96..d41b66741 100644 --- a/src/client/clientmap.cpp +++ b/src/client/clientmap.cpp @@ -26,20 +26,24 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapblock.h" #include "profiler.h" #include "settings.h" -#include "camera.h" // CameraModes +#include "camera.h" // CameraModes #include "util/basic_macros.h" #include #include "client/renderingengine.h" -ClientMap::ClientMap(Client *client, MapDrawControl &control, s32 id) : - Map(dout_client, client), - scene::ISceneNode( - RenderingEngine::get_scene_manager()->getRootSceneNode(), - RenderingEngine::get_scene_manager(), id), - m_client(client), m_control(control) +ClientMap::ClientMap( + Client *client, + MapDrawControl &control, + s32 id +): + Map(dout_client, client), + scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), + RenderingEngine::get_scene_manager(), id), + m_client(client), + m_control(control) { - m_box = aabb3f(-BS * 1000000, -BS * 1000000, -BS * 1000000, BS * 1000000, - BS * 1000000, BS * 1000000); + m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000, + BS*1000000,BS*1000000,BS*1000000); /* TODO: Add a callback function so these can be updated when a setting * changes. At this point in time it doesn't matter (e.g. /set @@ -50,12 +54,13 @@ ClientMap::ClientMap(Client *client, MapDrawControl &control, s32 id) : * (as opposed to the this local caching). This can be addressed in * a later release. */ - m_cache_trilinear_filter = g_settings->getBool("trilinear_filter"); - m_cache_bilinear_filter = g_settings->getBool("bilinear_filter"); + 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"); + } -MapSector *ClientMap::emergeSector(v2s16 p2d) +MapSector * ClientMap::emergeSector(v2s16 p2d) { // Check that it doesn't exist already MapSector *sector = getSectorNoGenerate(p2d); @@ -71,7 +76,8 @@ MapSector *ClientMap::emergeSector(v2s16 p2d) void ClientMap::OnRegisterSceneNode() { - if (IsVisible) { + if(IsVisible) + { SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT); } @@ -79,23 +85,29 @@ void ClientMap::OnRegisterSceneNode() ISceneNode::OnRegisterSceneNode(); } -void ClientMap::getBlocksInViewRange( - v3s16 cam_pos_nodes, v3s16 *p_blocks_min, v3s16 *p_blocks_max) +void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes, + v3s16 *p_blocks_min, v3s16 *p_blocks_max) { v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1); // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d' // can exceed the range of v3s16 when a large view range is used near the // world edges. - v3s32 p_nodes_min(cam_pos_nodes.X - box_nodes_d.X, - cam_pos_nodes.Y - box_nodes_d.Y, cam_pos_nodes.Z - box_nodes_d.Z); - v3s32 p_nodes_max(cam_pos_nodes.X + box_nodes_d.X, - cam_pos_nodes.Y + box_nodes_d.Y, cam_pos_nodes.Z + box_nodes_d.Z); + v3s32 p_nodes_min( + cam_pos_nodes.X - box_nodes_d.X, + cam_pos_nodes.Y - box_nodes_d.Y, + cam_pos_nodes.Z - box_nodes_d.Z); + v3s32 p_nodes_max( + cam_pos_nodes.X + box_nodes_d.X, + cam_pos_nodes.Y + box_nodes_d.Y, + cam_pos_nodes.Z + box_nodes_d.Z); // Take a fair amount as we will be dropping more out later // Umm... these additions are a bit strange but they are needed. - *p_blocks_min = v3s16(p_nodes_min.X / MAP_BLOCKSIZE - 3, + *p_blocks_min = v3s16( + p_nodes_min.X / MAP_BLOCKSIZE - 3, p_nodes_min.Y / MAP_BLOCKSIZE - 3, p_nodes_min.Z / MAP_BLOCKSIZE - 3); - *p_blocks_max = v3s16(p_nodes_max.X / MAP_BLOCKSIZE + 1, + *p_blocks_max = v3s16( + p_nodes_max.X / MAP_BLOCKSIZE + 1, p_nodes_max.Y / MAP_BLOCKSIZE + 1, p_nodes_max.Z / MAP_BLOCKSIZE + 1); } @@ -134,13 +146,14 @@ void ClientMap::updateDrawList() bool occlusion_culling_enabled = true; if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) { MapNode n = getNode(cam_pos_nodes); - if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2) + if (n.getContent() == CONTENT_IGNORE || + m_nodedef->get(n).solidness == 2) occlusion_culling_enabled = false; } // Uncomment to debug occluded blocks in the wireframe mode // TODO: Include this as a flag for an extended debugging setting - // if (occlusion_culling_enabled && m_control.show_wireframe) + //if (occlusion_culling_enabled && m_control.show_wireframe) // occlusion_culling_enabled = porting::getTimeS() & 1; for (const auto §or_it : m_sectors) { @@ -177,9 +190,10 @@ void ClientMap::updateDrawList() float d = 0.0; if (!isBlockInSight(block->getPos(), camera_position, - camera_direction, camera_fov, range, &d)) + camera_direction, camera_fov, range, &d)) continue; + /* Ignore if mesh doesn't exist */ @@ -192,9 +206,7 @@ void ClientMap::updateDrawList() Occlusion culling */ if ((!m_control.range_all && d > m_control.wanted_range * BS) || - (occlusion_culling_enabled && - isBlockOccluded(block, - cam_pos_nodes))) { + (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) { blocks_occlusion_culled++; continue; } @@ -221,7 +233,7 @@ void ClientMap::updateDrawList() struct MeshBufList { video::SMaterial m; - std::vector bufs; + std::vector bufs; }; struct MeshBufListList @@ -245,8 +257,8 @@ struct MeshBufListList std::vector &list = lists[layer]; const video::SMaterial &m = buf->getMaterial(); for (MeshBufList &l : list) { - // comparing a full material is quite expensive so we don't do it - // if not even first texture is equal + // comparing a full material is quite expensive so we don't do it if + // not even first texture is equal if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture) continue; @@ -262,7 +274,7 @@ struct MeshBufListList } }; -void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) +void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) { bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT; @@ -297,7 +309,7 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) // For limiting number of mesh animations per frame u32 mesh_animate_count = 0; - // u32 mesh_animate_count_far = 0; + //u32 mesh_animate_count_far = 0; /* Draw the selected MapBlocks @@ -313,23 +325,22 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) continue; float d = 0.0; - if (!isBlockInSight(block->getPos(), camera_position, camera_direction, - camera_fov, 100000 * BS, &d)) + if (!isBlockInSight(block->getPos(), camera_position, + camera_direction, camera_fov, 100000 * BS, &d)) continue; // Mesh animation if (pass == scene::ESNRP_SOLID) { - // MutexAutoLock lock(block->mesh_mutex); + //MutexAutoLock lock(block->mesh_mutex); MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); // Pretty random but this should work somewhat nicely bool faraway = d >= BS * 50; if (mapBlockMesh->isAnimationForced() || !faraway || - mesh_animate_count < (m_control.range_all ? 200 - : 50)) { + mesh_animate_count < (m_control.range_all ? 200 : 50)) { - bool animated = mapBlockMesh->animate(faraway, - animation_time, crack, daynight_ratio); + bool animated = mapBlockMesh->animate(faraway, animation_time, + crack, daynight_ratio); if (animated) mesh_animate_count++; } else { @@ -341,7 +352,7 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) Get the meshbuffers of the block */ { - // MutexAutoLock lock(block->mesh_mutex); + //MutexAutoLock lock(block->mesh_mutex); MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); @@ -354,30 +365,23 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) for (u32 i = 0; i < c; i++) { scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); - video::SMaterial &material = buf->getMaterial(); - video::IMaterialRenderer *rnd = - driver->getMaterialRenderer( - material.MaterialType); + video::SMaterial& material = buf->getMaterial(); + video::IMaterialRenderer* rnd = + driver->getMaterialRenderer(material.MaterialType); bool transparent = (rnd && rnd->isTransparent()); if (transparent == is_transparent_pass) { 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); + 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); + m_control.show_wireframe); drawbufs.add(buf, layer); } @@ -393,9 +397,8 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) for (MeshBufList &list : lists) { // Check and abort if the machine is swapping a lot if (draw.getTimerTime() > 2000) { - infostream << "ClientMap::renderMap(): Rendering took " - ">2s, " - << "returning." << std::endl; + infostream << "ClientMap::renderMap(): Rendering took >2s, " << + "returning." << std::endl; return; } driver->setMaterial(list.m); @@ -417,9 +420,9 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass) } static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step, - float step_multiplier, float start_distance, float end_distance, - const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d, - int *result, bool *sunlight_seen) + float step_multiplier, float start_distance, float end_distance, + const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d, + int *result, bool *sunlight_seen) { int brightness_sum = 0; int brightness_count = 0; @@ -435,7 +438,7 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step, { v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS); MapNode n = map->getNode(p); - if (ndef->get(n).param_type == CPT_LIGHT && + if(ndef->get(n).param_type == CPT_LIGHT && !ndef->get(n).sunlight_propagates) allow_allowing_non_sunlight_propagates = true; } @@ -443,14 +446,14 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step, { v3s16 p = floatToInt(pf, BS); MapNode n = map->getNode(p); - if (n.getContent() == CONTENT_IGNORE) { - float newd = 2 * BS; - pf = p0 + dir * 2 * newd; + if(n.getContent() == CONTENT_IGNORE){ + float newd = 2*BS; + pf = p0 + dir * 2*newd; distance = newd; sunlight_min_d = 0; } } - for (int i = 0; distance < end_distance; i++) { + for (int i=0; distance < end_distance; i++) { pf += dir * step; distance += step; step *= step_multiplier; @@ -465,10 +468,10 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step, if (ndef->get(n).param_type != CPT_LIGHT || (!ndef->get(n).sunlight_propagates && - !allow_non_sunlight_propagates)) { + !allow_non_sunlight_propagates)){ nonlight_seen = true; noncount++; - if (noncount >= 4) + if(noncount >= 4) break; continue; } @@ -481,7 +484,7 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step, brightness_count++; } *result = 0; - if (brightness_count == 0) + if(brightness_count == 0) return false; *result = brightness_sum / brightness_count; /*std::cerr<<"Sampled "< 35 * BS) - sunlight_min_d = 35 * BS; + float sunlight_min_d = max_d*0.8; + if(sunlight_min_d > 35*BS) + sunlight_min_d = 35*BS; std::vector values; - for (u32 i = 0; i < sizeof(z_directions) / sizeof(*z_directions); i++) { + for(u32 i=0; i a; - a.buildRotateFromTo(v3f(0, 1, 0), z_dir); + a.buildRotateFromTo(v3f(0,1,0), z_dir); v3f dir = m_camera_direction; a.rotateVect(dir); int br = 0; - float step = BS * 1.5; - if (max_d > 35 * BS) + float step = BS*1.5; + if(max_d > 35*BS) step = max_d / 35 * 1.5; float off = step * z_offsets[i]; bool sunlight_seen_now = false; - bool ok = getVisibleBrightness(this, m_camera_position, dir, step, 1.0, - max_d * 0.6 + off, max_d, m_nodedef, daylight_factor, - sunlight_min_d, &br, &sunlight_seen_now); - if (sunlight_seen_now) + bool ok = getVisibleBrightness(this, m_camera_position, dir, + step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor, + sunlight_min_d, + &br, &sunlight_seen_now); + if(sunlight_seen_now) sunlight_seen_count++; - if (!ok) + if(!ok) continue; values.push_back(br); // Don't try too much if being in the sun is clear - if (sunlight_seen_count >= 20) + if(sunlight_seen_count >= 20) break; } int brightness_sum = 0; int brightness_count = 0; std::sort(values.begin(), values.end()); u32 num_values_to_use = values.size(); - if (num_values_to_use >= 10) - num_values_to_use -= num_values_to_use / 2; - else if (num_values_to_use >= 7) - num_values_to_use -= num_values_to_use / 3; + if(num_values_to_use >= 10) + num_values_to_use -= num_values_to_use/2; + else if(num_values_to_use >= 7) + num_values_to_use -= num_values_to_use/3; u32 first_value_i = (values.size() - num_values_to_use) / 2; - for (u32 i = first_value_i; i < first_value_i + num_values_to_use; i++) { + for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) { brightness_sum += values[i]; brightness_count++; } int ret = 0; - if (brightness_count == 0) { + if(brightness_count == 0){ MapNode n = getNode(floatToInt(m_camera_position, BS)); - if (m_nodedef->get(n).param_type == CPT_LIGHT) { + if(m_nodedef->get(n).param_type == CPT_LIGHT){ ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef)); } else { ret = oldvalue; @@ -578,25 +586,27 @@ void ClientMap::renderPostFx(CameraMode cam_mode) // - If the player is in a solid node, make everything black. // - If the player is in liquid, draw a semi-transparent overlay. // - Do not if player is in third person mode - const ContentFeatures &features = m_nodedef->get(n); + const ContentFeatures& features = m_nodedef->get(n); video::SColor post_effect_color = features.post_effect_color; - if (features.solidness == 2 && - !((g_settings->getBool("noclip") || - g_settings->getBool("freecam")) && - m_client->checkLocalPrivilege("noclip")) && - cam_mode == CAMERA_MODE_FIRST) { + if(features.solidness == 2 && !((g_settings->getBool("noclip") || g_settings->getBool("freecam")) && + m_client->checkLocalPrivilege("noclip")) && + cam_mode == CAMERA_MODE_FIRST) + { post_effect_color = video::SColor(255, 0, 0, 0); } - if (post_effect_color.getAlpha() != 0) { + if (post_effect_color.getAlpha() != 0) + { // Draw a full-screen rectangle - video::IVideoDriver *driver = SceneManager->getVideoDriver(); + video::IVideoDriver* driver = SceneManager->getVideoDriver(); v2u32 ss = driver->getScreenSize(); - core::rect rect(0, 0, ss.X, ss.Y); + core::rect rect(0,0, ss.X, ss.Y); driver->draw2DRectangle(post_effect_color, rect); } } void ClientMap::PrintInfo(std::ostream &out) { - out << "ClientMap: "; + out<<"ClientMap: "; } + + diff --git a/src/client/clientmap.h b/src/client/clientmap.h index 23eb561f8..172e3a1d6 100644 --- a/src/client/clientmap.h +++ b/src/client/clientmap.h @@ -47,13 +47,23 @@ class ITextureSource; class ClientMap : public Map, public scene::ISceneNode { public: - ClientMap(Client *client, MapDrawControl &control, s32 id); + ClientMap( + Client *client, + MapDrawControl &control, + s32 id + ); virtual ~ClientMap() = default; - s32 mapType() const { return MAPTYPE_CLIENT; } + s32 mapType() const + { + return MAPTYPE_CLIENT; + } - void drop() { ISceneNode::drop(); } + void drop() + { + ISceneNode::drop(); + } void updateCamera(const v3f &pos, const v3f &dir, f32 fov, const v3s16 &offset) { @@ -66,9 +76,9 @@ class ClientMap : public Map, public scene::ISceneNode /* Forcefully get a sector from somewhere */ - MapSector *emergeSector(v2s16 p); + MapSector * emergeSector(v2s16 p); - // void deSerializeSector(v2s16 p2d, std::istream &is); + //void deSerializeSector(v2s16 p2d, std::istream &is); /* ISceneNode methods @@ -78,43 +88,45 @@ class ClientMap : public Map, public scene::ISceneNode virtual void render() { - video::IVideoDriver *driver = SceneManager->getVideoDriver(); + video::IVideoDriver* driver = SceneManager->getVideoDriver(); driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); renderMap(driver, SceneManager->getSceneNodeRenderPass()); } - virtual const aabb3f &getBoundingBox() const { return m_box; } + virtual const aabb3f &getBoundingBox() const + { + return m_box; + } - void getBlocksInViewRange( - v3s16 cam_pos_nodes, v3s16 *p_blocks_min, v3s16 *p_blocks_max); + void getBlocksInViewRange(v3s16 cam_pos_nodes, + v3s16 *p_blocks_min, v3s16 *p_blocks_max); void updateDrawList(); - void renderMap(video::IVideoDriver *driver, s32 pass); + void renderMap(video::IVideoDriver* driver, s32 pass); - int getBackgroundBrightness(float max_d, u32 daylight_factor, int oldvalue, - bool *sunlight_seen_result); + int getBackgroundBrightness(float max_d, u32 daylight_factor, + int oldvalue, bool *sunlight_seen_result); void renderPostFx(CameraMode cam_mode); // For debug printing virtual void PrintInfo(std::ostream &out); - const MapDrawControl &getControl() const { return m_control; } + const MapDrawControl & getControl() const { return m_control; } f32 getCameraFov() const { return m_camera_fov; } - private: Client *m_client; - aabb3f m_box = aabb3f(-BS * 1000000, -BS * 1000000, -BS * 1000000, BS * 1000000, - BS * 1000000, BS * 1000000); + aabb3f m_box = aabb3f(-BS * 1000000, -BS * 1000000, -BS * 1000000, + BS * 1000000, BS * 1000000, BS * 1000000); MapDrawControl &m_control; - v3f m_camera_position = v3f(0, 0, 0); - v3f m_camera_direction = v3f(0, 0, 1); + v3f m_camera_position = v3f(0,0,0); + v3f m_camera_direction = v3f(0,0,1); f32 m_camera_fov = M_PI; v3s16 m_camera_offset; - std::map m_drawlist; + std::map m_drawlist; std::set m_last_drawn_sectors; diff --git a/src/client/clientmedia.cpp b/src/client/clientmedia.cpp index 1cf18b84b..8cd3b6bcc 100644 --- a/src/client/clientmedia.cpp +++ b/src/client/clientmedia.cpp @@ -48,8 +48,9 @@ bool clientMediaUpdateCache(const std::string &raw_hash, const std::string &file ClientMediaDownloader */ -ClientMediaDownloader::ClientMediaDownloader() : - m_media_cache(getMediaCacheDir()), m_httpfetch_caller(HTTPFETCH_DISCARD) +ClientMediaDownloader::ClientMediaDownloader(): + m_media_cache(getMediaCacheDir()), + m_httpfetch_caller(HTTPFETCH_DISCARD) { } @@ -72,21 +73,24 @@ void ClientMediaDownloader::addFile(const std::string &name, const std::string & // if name was already announced, ignore the new announcement if (m_files.count(name) != 0) { errorstream << "Client: ignoring duplicate media announcement " - << "sent by server: \"" << name << "\"" << std::endl; + << "sent by server: \"" << name << "\"" + << std::endl; return; } // if name is empty or contains illegal characters, ignore the file if (name.empty() || !string_allowed(name, TEXTURENAME_ALLOWED_CHARS)) { errorstream << "Client: ignoring illegal file name " - << "sent by server: \"" << name << "\"" << std::endl; + << "sent by server: \"" << name << "\"" + << std::endl; return; } // length of sha1 must be exactly 20 (160 bits), else ignore the file if (sha1.size() != 20) { errorstream << "Client: ignoring illegal SHA1 sent by server: " - << hex_encode(sha1) << " \"" << name << "\"" << std::endl; + << hex_encode(sha1) << " \"" << name << "\"" + << std::endl; return; } @@ -99,13 +103,13 @@ void ClientMediaDownloader::addFile(const std::string &name, const std::string & void ClientMediaDownloader::addRemoteServer(const std::string &baseurl) { - assert(!m_initial_step_done); // pre-condition + assert(!m_initial_step_done); // pre-condition -#ifdef USE_CURL + #ifdef USE_CURL if (g_settings->getBool("enable_remote_media_server")) { - infostream << "Client: Adding remote server \"" << baseurl - << "\" for media download" << std::endl; + infostream << "Client: Adding remote server \"" + << baseurl << "\" for media download" << std::endl; RemoteServerStatus *remote = new RemoteServerStatus(); remote->baseurl = baseurl; @@ -113,12 +117,13 @@ void ClientMediaDownloader::addRemoteServer(const std::string &baseurl) m_remotes.push_back(remote); } -#else + #else - infostream << "Client: Ignoring remote server \"" << baseurl - << "\" because cURL support is not compiled in" << std::endl; + infostream << "Client: Ignoring remote server \"" + << baseurl << "\" because cURL support is not compiled in" + << std::endl; -#endif + #endif } void ClientMediaDownloader::step(Client *client) @@ -153,10 +158,9 @@ void ClientMediaDownloader::step(Client *client) if (m_httpfetch_active == 0) { if (m_uncached_received_count < m_uncached_count) { infostream << "Client: Failed to remote-fetch " - << (m_uncached_count - - m_uncached_received_count) - << " files. Requesting them" - << " the usual way." << std::endl; + << (m_uncached_count-m_uncached_received_count) + << " files. Requesting them" + << " the usual way." << std::endl; } startConventionalTransfers(client); } @@ -177,8 +181,8 @@ void ClientMediaDownloader::initialStep(Client *client) // If found in cache, try to load it from there if (found_in_cache) { - bool success = checkAndLoad( - name, sha1, tmp_os.str(), true, client); + bool success = checkAndLoad(name, sha1, + tmp_os.str(), true, client); if (success) { filestatus->received = true; m_uncached_count--; @@ -193,8 +197,9 @@ void ClientMediaDownloader::initialStep(Client *client) bool did = fs::CreateAllDirs(getMediaCacheDir()); if (!did) { errorstream << "Client: " - << "Could not create media cache directory: " - << getMediaCacheDir() << std::endl; + << "Could not create media cache directory: " + << getMediaCacheDir() + << std::endl; } } @@ -205,7 +210,8 @@ void ClientMediaDownloader::initialStep(Client *client) // reduce the size of the compiled code if (!USE_CURL || m_uncached_count == 0 || m_remotes.empty()) { startConventionalTransfers(client); - } else { + } + else { // Otherwise start off by requesting each server's sha1 set // This is the first time we use httpfetch, so alloc a caller ID @@ -245,26 +251,27 @@ void ClientMediaDownloader::initialStep(Client *client) RemoteServerStatus *remote = m_remotes[i]; actionstream << "Client: Contacting remote server \"" - << remote->baseurl << "\"" << std::endl; + << remote->baseurl << "\"" << std::endl; HTTPFetchRequest fetch_request; - fetch_request.url = remote->baseurl + MTHASHSET_FILE_NAME; + fetch_request.url = + remote->baseurl + MTHASHSET_FILE_NAME; fetch_request.caller = m_httpfetch_caller; fetch_request.request_id = m_httpfetch_next_id; // == i fetch_request.timeout = m_httpfetch_timeout; fetch_request.connect_timeout = m_httpfetch_timeout; fetch_request.post_data = required_hash_set; fetch_request.extra_headers.emplace_back( - "Content-Type: application/octet-stream"); + "Content-Type: application/octet-stream"); // Encapsulate possible IPv6 plain address in [] std::string addr = client->getAddressName(); if (addr.find(':', 0) != std::string::npos) addr = '[' + addr + ']'; fetch_request.extra_headers.emplace_back( - std::string("Referer: minetest://") + addr + ":" + - std::to_string(client->getServerAddress() - .getPort())); + std::string("Referer: minetest://") + + addr + ":" + + std::to_string(client->getServerAddress().getPort())); httpfetch_async(fetch_request); @@ -275,7 +282,8 @@ void ClientMediaDownloader::initialStep(Client *client) } } -void ClientMediaDownloader::remoteHashSetReceived(const HTTPFetchResult &fetch_result) +void ClientMediaDownloader::remoteHashSetReceived( + const HTTPFetchResult &fetch_result) { u32 remote_id = fetch_result.request_id; assert(remote_id < m_remotes.size()); @@ -295,23 +303,25 @@ void ClientMediaDownloader::remoteHashSetReceived(const HTTPFetchResult &fetch_r // available on this server, add this server // to the available_remotes array - for (std::map::iterator it = - m_files.upper_bound(m_name_bound); + for(std::map::iterator + it = m_files.upper_bound(m_name_bound); it != m_files.end(); ++it) { FileStatus *f = it->second; if (!f->received && sha1_set.count(f->sha1)) f->available_remotes.push_back(remote_id); } - } catch (SerializationError &e) { - infostream << "Client: Remote server \"" << remote->baseurl - << "\" sent invalid hash set: " << e.what() - << std::endl; + } + catch (SerializationError &e) { + infostream << "Client: Remote server \"" + << remote->baseurl << "\" sent invalid hash set: " + << e.what() << std::endl; } } } void ClientMediaDownloader::remoteMediaReceived( - const HTTPFetchResult &fetch_result, Client *client) + const HTTPFetchResult &fetch_result, + Client *client) { // Some remote server sent us a file. // -> decrement number of active fetches @@ -321,7 +331,7 @@ void ClientMediaDownloader::remoteMediaReceived( std::string name; { std::unordered_map::iterator it = - m_remote_file_transfers.find(fetch_result.request_id); + m_remote_file_transfers.find(fetch_result.request_id); assert(it != m_remote_file_transfers.end()); name = it->second; m_remote_file_transfers.erase(it); @@ -341,8 +351,8 @@ void ClientMediaDownloader::remoteMediaReceived( // If fetch succeeded, try to load media file if (fetch_result.succeeded) { - bool success = checkAndLoad( - name, filestatus->sha1, fetch_result.data, false, client); + bool success = checkAndLoad(name, filestatus->sha1, + fetch_result.data, false, client); if (success) { filestatus->received = true; assert(m_uncached_received_count < m_uncached_count); @@ -379,17 +389,19 @@ s32 ClientMediaDownloader::selectRemoteServer(FileStatus *filestatus) } } - filestatus->available_remotes.erase(filestatus->available_remotes.begin() + best); + filestatus->available_remotes.erase( + filestatus->available_remotes.begin() + best); return best_remote_id; + } void ClientMediaDownloader::startRemoteMediaTransfers() { bool changing_name_bound = true; - for (std::map::iterator files_iter = - m_files.upper_bound(m_name_bound); + for (std::map::iterator + files_iter = m_files.upper_bound(m_name_bound); files_iter != m_files.end(); ++files_iter) { // Abort if active fetch limit is exceeded @@ -405,25 +417,28 @@ void ClientMediaDownloader::startRemoteMediaTransfers() s32 remote_id = selectRemoteServer(filestatus); if (remote_id >= 0) { // Found a server, so start fetching - RemoteServerStatus *remote = m_remotes[remote_id]; + RemoteServerStatus *remote = + m_remotes[remote_id]; std::string url = remote->baseurl + - hex_encode(filestatus->sha1); + hex_encode(filestatus->sha1); verbosestream << "Client: " - << "Requesting remote media file " - << "\"" << name << "\" " - << "\"" << url << "\"" << std::endl; + << "Requesting remote media file " + << "\"" << name << "\" " + << "\"" << url << "\"" << std::endl; HTTPFetchRequest fetch_request; fetch_request.url = url; fetch_request.caller = m_httpfetch_caller; fetch_request.request_id = m_httpfetch_next_id; fetch_request.timeout = 0; // no data timeout! - fetch_request.connect_timeout = m_httpfetch_timeout; + fetch_request.connect_timeout = + m_httpfetch_timeout; httpfetch_async(fetch_request); m_remote_file_transfers.insert(std::make_pair( - m_httpfetch_next_id, name)); + m_httpfetch_next_id, + name)); filestatus->current_remote = remote_id; remote->active_count++; @@ -432,21 +447,24 @@ void ClientMediaDownloader::startRemoteMediaTransfers() } } - if (filestatus->received || (filestatus->current_remote < 0 && - !m_outstanding_hash_sets)) { + if (filestatus->received || + (filestatus->current_remote < 0 && + !m_outstanding_hash_sets)) { // If we arrive here, we conclusively know that we // won't fetch this file from a remote server in the // future. So update the name bound if possible. if (changing_name_bound) m_name_bound = name; - } else + } + else changing_name_bound = false; } + } void ClientMediaDownloader::startConventionalTransfers(Client *client) { - assert(m_httpfetch_active == 0); // pre-condition + assert(m_httpfetch_active == 0); // pre-condition if (m_uncached_received_count != m_uncached_count) { // Some media files have not been received yet, use the @@ -456,21 +474,24 @@ void ClientMediaDownloader::startConventionalTransfers(Client *client) if (!file.second->received) file_requests.push_back(file.first); } - assert((s32)file_requests.size() == + assert((s32) file_requests.size() == m_uncached_count - m_uncached_received_count); client->request_media(file_requests); } } void ClientMediaDownloader::conventionalTransferDone( - const std::string &name, const std::string &data, Client *client) + const std::string &name, + const std::string &data, + Client *client) { // Check that file was announced - std::map::iterator file_iter = m_files.find(name); + std::map::iterator + file_iter = m_files.find(name); if (file_iter == m_files.end()) { errorstream << "Client: server sent media file that was" - << "not announced, ignoring it: \"" << name << "\"" - << std::endl; + << "not announced, ignoring it: \"" << name << "\"" + << std::endl; return; } FileStatus *filestatus = file_iter->second; @@ -479,7 +500,8 @@ void ClientMediaDownloader::conventionalTransferDone( // Check that file hasn't already been received if (filestatus->received) { errorstream << "Client: server sent media file that we already" - << "received, ignoring it: \"" << name << "\"" << std::endl; + << "received, ignoring it: \"" << name << "\"" + << std::endl; return; } @@ -495,7 +517,8 @@ void ClientMediaDownloader::conventionalTransferDone( checkAndLoad(name, filestatus->sha1, data, false, client); } -bool ClientMediaDownloader::checkAndLoad(const std::string &name, const std::string &sha1, +bool ClientMediaDownloader::checkAndLoad( + const std::string &name, const std::string &sha1, const std::string &data, bool is_from_cache, Client *client) { const char *cached_or_received = is_from_cache ? "cached" : "received"; @@ -508,16 +531,18 @@ bool ClientMediaDownloader::checkAndLoad(const std::string &name, const std::str SHA1 data_sha1_calculator; data_sha1_calculator.addBytes(data.c_str(), data.size()); unsigned char *data_tmpdigest = data_sha1_calculator.getDigest(); - data_sha1.assign((char *)data_tmpdigest, 20); + data_sha1.assign((char*) data_tmpdigest, 20); free(data_tmpdigest); } // Check that received file matches announced checksum if (data_sha1 != sha1) { std::string data_sha1_hex = hex_encode(data_sha1); - infostream << "Client: " << cached_or_received_uc << " media file " - << sha1_hex << " \"" << name << "\" " - << "mismatches actual checksum " << data_sha1_hex << std::endl; + infostream << "Client: " + << cached_or_received_uc << " media file " + << sha1_hex << " \"" << name << "\" " + << "mismatches actual checksum " << data_sha1_hex + << std::endl; return false; } @@ -525,15 +550,16 @@ bool ClientMediaDownloader::checkAndLoad(const std::string &name, const std::str bool success = client->loadMedia(data, name); if (!success) { infostream << "Client: " - << "Failed to load " << cached_or_received - << " media: " << sha1_hex << " \"" << name << "\"" - << std::endl; + << "Failed to load " << cached_or_received << " media: " + << sha1_hex << " \"" << name << "\"" + << std::endl; return false; } verbosestream << "Client: " - << "Loaded " << cached_or_received << " media: " << sha1_hex - << " \"" << name << "\"" << std::endl; + << "Loaded " << cached_or_received << " media: " + << sha1_hex << " \"" << name << "\"" + << std::endl; // Update cache (unless we just loaded the file from the cache) if (!is_from_cache) @@ -560,15 +586,15 @@ std::string ClientMediaDownloader::serializeRequiredHashSet() std::ostringstream os(std::ios::binary); writeU32(os, MTHASHSET_FILE_SIGNATURE); // signature - writeU16(os, 1); // version + writeU16(os, 1); // version // Write list of hashes of files that have not been // received (found in cache) yet - for (std::map::iterator it = m_files.begin(); + for (std::map::iterator + it = m_files.begin(); it != m_files.end(); ++it) { if (!it->second->received) { - FATAL_ERROR_IF(it->second->sha1.size() != 20, - "Invalid SHA1 size"); + FATAL_ERROR_IF(it->second->sha1.size() != 20, "Invalid SHA1 size"); os << it->second->sha1; } } @@ -576,26 +602,29 @@ std::string ClientMediaDownloader::serializeRequiredHashSet() return os.str(); } -void ClientMediaDownloader::deSerializeHashSet( - const std::string &data, std::set &result) +void ClientMediaDownloader::deSerializeHashSet(const std::string &data, + std::set &result) { if (data.size() < 6 || data.size() % 20 != 6) { - throw SerializationError("ClientMediaDownloader::deSerializeHashSet: " - "invalid hash set file size"); + throw SerializationError( + "ClientMediaDownloader::deSerializeHashSet: " + "invalid hash set file size"); } - const u8 *data_cstr = (const u8 *)data.c_str(); + const u8 *data_cstr = (const u8*) data.c_str(); u32 signature = readU32(&data_cstr[0]); if (signature != MTHASHSET_FILE_SIGNATURE) { - throw SerializationError("ClientMediaDownloader::deSerializeHashSet: " - "invalid hash set file signature"); + throw SerializationError( + "ClientMediaDownloader::deSerializeHashSet: " + "invalid hash set file signature"); } u16 version = readU16(&data_cstr[4]); if (version != 1) { - throw SerializationError("ClientMediaDownloader::deSerializeHashSet: " - "unsupported hash set file version"); + throw SerializationError( + "ClientMediaDownloader::deSerializeHashSet: " + "unsupported hash set file version"); } for (u32 pos = 6; pos < data.size(); pos += 20) { diff --git a/src/client/clientmedia.h b/src/client/clientmedia.h index 6a52c551d..5a918535b 100644 --- a/src/client/clientmedia.h +++ b/src/client/clientmedia.h @@ -35,7 +35,8 @@ struct HTTPFetchResult; // Store file into media cache (unless it exists already) // Validating the hash is responsibility of the caller -bool clientMediaUpdateCache(const std::string &raw_hash, const std::string &filedata); +bool clientMediaUpdateCache(const std::string &raw_hash, + const std::string &filedata); class ClientMediaDownloader { @@ -43,21 +44,22 @@ class ClientMediaDownloader ClientMediaDownloader(); ~ClientMediaDownloader(); - float getProgress() const - { + float getProgress() const { if (m_uncached_count >= 1) - return 1.0f * m_uncached_received_count / m_uncached_count; + return 1.0f * m_uncached_received_count / + m_uncached_count; return 0.0f; } - bool isStarted() const { return m_initial_step_done; } + bool isStarted() const { + return m_initial_step_done; + } // If this returns true, the downloader is done and can be deleted - bool isDone() const - { + bool isDone() const { return m_initial_step_done && - m_uncached_received_count == m_uncached_count; + m_uncached_received_count == m_uncached_count; } // Add a file to the list of required file (but don't fetch it yet) @@ -80,42 +82,44 @@ class ClientMediaDownloader // Must be called for each file received through TOCLIENT_MEDIA void conventionalTransferDone( - const std::string &name, const std::string &data, Client *client); + const std::string &name, + const std::string &data, + Client *client); private: - struct FileStatus - { + struct FileStatus { bool received; std::string sha1; s32 current_remote; std::vector available_remotes; }; - struct RemoteServerStatus - { + struct RemoteServerStatus { std::string baseurl; s32 active_count; }; void initialStep(Client *client); void remoteHashSetReceived(const HTTPFetchResult &fetch_result); - void remoteMediaReceived(const HTTPFetchResult &fetch_result, Client *client); + void remoteMediaReceived(const HTTPFetchResult &fetch_result, + Client *client); s32 selectRemoteServer(FileStatus *filestatus); void startRemoteMediaTransfers(); void startConventionalTransfers(Client *client); bool checkAndLoad(const std::string &name, const std::string &sha1, - const std::string &data, bool is_from_cache, Client *client); + const std::string &data, bool is_from_cache, + Client *client); std::string serializeRequiredHashSet(); - static void deSerializeHashSet( - const std::string &data, std::set &result); + static void deSerializeHashSet(const std::string &data, + std::set &result); // Maps filename to file status - std::map m_files; + std::map m_files; // Array of remote media servers - std::vector m_remotes; + std::vector m_remotes; // Filesystem-based media cache FileCache m_media_cache; @@ -144,4 +148,5 @@ class ClientMediaDownloader // don't need to be looked at again // (use m_files.upper_bound(m_name_bound) to get an iterator) std::string m_name_bound = ""; + }; diff --git a/src/client/clientobject.cpp b/src/client/clientobject.cpp index af8b35da1..f4b69201b 100644 --- a/src/client/clientobject.cpp +++ b/src/client/clientobject.cpp @@ -25,8 +25,11 @@ with this program; if not, write to the Free Software Foundation, Inc., ClientActiveObject */ -ClientActiveObject::ClientActiveObject(u16 id, Client *client, ClientEnvironment *env) : - ActiveObject(id), m_client(client), m_env(env) +ClientActiveObject::ClientActiveObject(u16 id, Client *client, + ClientEnvironment *env): + ActiveObject(id), + m_client(client), + m_env(env) { } @@ -35,15 +38,15 @@ ClientActiveObject::~ClientActiveObject() removeFromScene(true); } -ClientActiveObject *ClientActiveObject::create( - ActiveObjectType type, Client *client, ClientEnvironment *env) +ClientActiveObject* ClientActiveObject::create(ActiveObjectType type, + Client *client, ClientEnvironment *env) { // Find factory function auto n = m_types.find(type); if (n == m_types.end()) { // If factory is not found, just return. - warningstream << "ClientActiveObject: No factory for type=" << (int)type - << std::endl; + warningstream << "ClientActiveObject: No factory for type=" + << (int)type << std::endl; return NULL; } @@ -59,3 +62,5 @@ void ClientActiveObject::registerType(u16 type, Factory f) return; m_types[type] = f; } + + diff --git a/src/client/clientobject.h b/src/client/clientobject.h index 1cde010c7..4a1743d72 100644 --- a/src/client/clientobject.h +++ b/src/client/clientobject.h @@ -29,6 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include + class ClientEnvironment; class ITextureSource; class Client; @@ -52,20 +53,16 @@ class ClientActiveObject : public ActiveObject virtual bool getSelectionBox(aabb3f *toset) const { return false; } virtual bool collideWithObjects() const { return false; } virtual const v3f getPosition() const { return v3f(0.0f); } - virtual scene::ISceneNode *getSceneNode() const { return NULL; } + virtual scene::ISceneNode *getSceneNode() const + { return NULL; } virtual scene::IAnimatedMeshSceneNode *getAnimatedMeshSceneNode() const - { - return NULL; - } + { return NULL; } virtual bool isLocalPlayer() const { return false; } virtual ClientActiveObject *getParent() const { return nullptr; }; virtual const std::unordered_set &getAttachmentChildIds() const - { - static std::unordered_set rv; - return rv; - } - virtual void updateAttachments(){}; + { static std::unordered_set rv; return rv; } + virtual void updateAttachments() {}; virtual bool doShowSelectionBox() { return true; } @@ -85,15 +82,12 @@ class ClientActiveObject : public ActiveObject virtual void initialize(const std::string &data) {} // Create a certain type of ClientActiveObject - static ClientActiveObject *create( - ActiveObjectType type, Client *client, ClientEnvironment *env); + static ClientActiveObject *create(ActiveObjectType type, Client *client, + ClientEnvironment *env); // If returns true, punch will not be sent to the server virtual bool directReportPunch(v3f dir, const ItemStack *punchitem = nullptr, - float time_from_last_punch = 1000000) - { - return false; - } + float time_from_last_punch = 1000000) { return false; } protected: // Used for creating objects based on type @@ -101,7 +95,6 @@ class ClientActiveObject : public ActiveObject static void registerType(u16 type, Factory f); Client *m_client; ClientEnvironment *m_env; - private: // Used for creating objects based on type static std::unordered_map m_types; @@ -118,7 +111,7 @@ class DistanceSortedActiveObject d = a_d; } - bool operator<(const DistanceSortedActiveObject &other) const + bool operator < (const DistanceSortedActiveObject &other) const { return d < other.d; } diff --git a/src/client/clouds.cpp b/src/client/clouds.cpp index e59eb8b4d..887a62f25 100644 --- a/src/client/clouds.cpp +++ b/src/client/clouds.cpp @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include + // Menu clouds are created later class Clouds; Clouds *g_menuclouds = NULL; @@ -39,43 +40,48 @@ static void cloud_3d_setting_changed(const std::string &settingname, void *data) ((Clouds *)data)->readSettings(); } -Clouds::Clouds(scene::ISceneManager *mgr, s32 id, u32 seed) : - scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), m_seed(seed) +Clouds::Clouds(scene::ISceneManager* mgr, + s32 id, + u32 seed +): + scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), + m_seed(seed) { m_material.setFlag(video::EMF_LIGHTING, false); - // m_material.setFlag(video::EMF_BACK_FACE_CULLING, false); + //m_material.setFlag(video::EMF_BACK_FACE_CULLING, false); m_material.setFlag(video::EMF_BACK_FACE_CULLING, true); m_material.setFlag(video::EMF_BILINEAR_FILTER, false); m_material.setFlag(video::EMF_FOG_ENABLE, true); m_material.setFlag(video::EMF_ANTI_ALIASING, true); - // m_material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + //m_material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; m_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; - m_params.height = 120; - m_params.density = 0.4f; - m_params.thickness = 16.0f; - m_params.color_bright = video::SColor(229, 240, 240, 255); + m_params.height = 120; + m_params.density = 0.4f; + m_params.thickness = 16.0f; + m_params.color_bright = video::SColor(229, 240, 240, 255); m_params.color_ambient = video::SColor(255, 0, 0, 0); - m_params.speed = v2f(0.0f, -2.0f); + m_params.speed = v2f(0.0f, -2.0f); readSettings(); - g_settings->registerChangedCallback( - "enable_3d_clouds", &cloud_3d_setting_changed, this); + g_settings->registerChangedCallback("enable_3d_clouds", + &cloud_3d_setting_changed, this); updateBox(); } Clouds::~Clouds() { - g_settings->deregisterChangedCallback( - "enable_3d_clouds", &cloud_3d_setting_changed, this); + g_settings->deregisterChangedCallback("enable_3d_clouds", + &cloud_3d_setting_changed, this); } void Clouds::OnRegisterSceneNode() { - if (IsVisible) { + if(IsVisible) + { SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT); - // SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); + //SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); } ISceneNode::OnRegisterSceneNode(); @@ -87,10 +93,10 @@ void Clouds::render() if (m_params.density <= 0.0f) return; // no need to do anything - video::IVideoDriver *driver = SceneManager->getVideoDriver(); + video::IVideoDriver* driver = SceneManager->getVideoDriver(); - if (SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT) - // if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID) + if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT) + //if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID) return; ScopeProfiler sp(g_profiler, "Clouds::render()", SPT_AVG); @@ -115,14 +121,15 @@ void Clouds::render() v2f center_of_drawing_in_noise_f = -cloud_origin_from_camera_f; // The integer center point of drawing in the noise v2s16 center_of_drawing_in_noise_i( - std::floor(center_of_drawing_in_noise_f.X / cloud_size), - std::floor(center_of_drawing_in_noise_f.Y / cloud_size)); + std::floor(center_of_drawing_in_noise_f.X / cloud_size), + std::floor(center_of_drawing_in_noise_f.Y / cloud_size) + ); // The world position of the integer center point of drawing in the noise - v2f world_center_of_drawing_in_noise_f = - v2f(center_of_drawing_in_noise_i.X * cloud_size, - center_of_drawing_in_noise_i.Y * cloud_size) + - m_origin; + v2f world_center_of_drawing_in_noise_f = v2f( + center_of_drawing_in_noise_i.X * cloud_size, + center_of_drawing_in_noise_i.Y * cloud_size + ) + m_origin; /*video::SColor c_top(128,b*240,b*240,b*255); video::SColor c_side_1(128,b*230,b*230,b*255); @@ -147,185 +154,185 @@ void Clouds::render() video::SColor c_bottom = c_bottom_f.toSColor(); // Get fog parameters for setting them back later - video::SColor fog_color(0, 0, 0, 0); + video::SColor fog_color(0,0,0,0); video::E_FOG_TYPE fog_type = video::EFT_FOG_LINEAR; f32 fog_start = 0; f32 fog_end = 0; f32 fog_density = 0; bool fog_pixelfog = false; bool fog_rangefog = false; - driver->getFog(fog_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog, - fog_rangefog); + driver->getFog(fog_color, fog_type, fog_start, fog_end, fog_density, + fog_pixelfog, fog_rangefog); // Set our own fog driver->setFog(fog_color, fog_type, cloud_full_radius * 0.5, - cloud_full_radius * 1.2, fog_density, fog_pixelfog, fog_rangefog); + cloud_full_radius*1.2, fog_density, fog_pixelfog, fog_rangefog); // Read noise bool *grid = new bool[m_cloud_radius_i * 2 * m_cloud_radius_i * 2]; - for (s16 zi = -m_cloud_radius_i; zi < m_cloud_radius_i; zi++) { - u32 si = (zi + m_cloud_radius_i) * m_cloud_radius_i * 2 + - m_cloud_radius_i; + + for(s16 zi = -m_cloud_radius_i; zi < m_cloud_radius_i; zi++) { + u32 si = (zi + m_cloud_radius_i) * m_cloud_radius_i * 2 + m_cloud_radius_i; for (s16 xi = -m_cloud_radius_i; xi < m_cloud_radius_i; xi++) { u32 i = si + xi; - grid[i] = gridFilled(xi + center_of_drawing_in_noise_i.X, - zi + center_of_drawing_in_noise_i.Y); + grid[i] = gridFilled( + xi + center_of_drawing_in_noise_i.X, + zi + center_of_drawing_in_noise_i.Y + ); } } -#define GETINDEX(x, z, radius) (((z) + (radius)) * (radius)*2 + (x) + (radius)) -#define INAREA(x, z, radius) \ +#define GETINDEX(x, z, radius) (((z)+(radius))*(radius)*2 + (x)+(radius)) +#define INAREA(x, z, radius) \ ((x) >= -(radius) && (x) < (radius) && (z) >= -(radius) && (z) < (radius)) - for (s16 zi0 = -m_cloud_radius_i; zi0 < m_cloud_radius_i; zi0++) - for (s16 xi0 = -m_cloud_radius_i; xi0 < m_cloud_radius_i; xi0++) { - s16 zi = zi0; - s16 xi = xi0; - // Draw from front to back (needed for transparency) - /*if(zi <= 0) - zi = -m_cloud_radius_i - zi; - if(xi <= 0) - xi = -m_cloud_radius_i - xi;*/ - // Draw from back to front - if (zi >= 0) - zi = m_cloud_radius_i - zi - 1; - if (xi >= 0) - xi = m_cloud_radius_i - xi - 1; - - u32 i = GETINDEX(xi, zi, m_cloud_radius_i); - - if (!grid[i]) - continue; - - v2f p0 = v2f(xi, zi) * cloud_size + - world_center_of_drawing_in_noise_f; - - video::S3DVertex v[4] = { - video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 0, 1), - video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 1, 1), - video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 1, 0), - video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 0, 0)}; - - /*if(zi <= 0 && xi <= 0){ - v[0].Color.setBlue(255); - v[1].Color.setBlue(255); - v[2].Color.setBlue(255); - v[3].Color.setBlue(255); - }*/ - - f32 rx = cloud_size / 2.0f; - // if clouds are flat, the top layer should be at the given height - f32 ry = m_enable_3d ? m_params.thickness * BS : 0.0f; - f32 rz = cloud_size / 2; - - for (int i = 0; i < num_faces_to_draw; i++) { - switch (i) { - case 0: // top - for (video::S3DVertex &vertex : v) { - vertex.Normal.set(0, 1, 0); - } - v[0].Pos.set(-rx, ry, -rz); - v[1].Pos.set(-rx, ry, rz); - v[2].Pos.set(rx, ry, rz); - v[3].Pos.set(rx, ry, -rz); - break; - case 1: // back - if (INAREA(xi, zi - 1, m_cloud_radius_i)) { - u32 j = GETINDEX(xi, zi - 1, - m_cloud_radius_i); - if (grid[j]) - continue; - } - for (video::S3DVertex &vertex : v) { - vertex.Color = c_side_1; - vertex.Normal.set(0, 0, -1); - } - v[0].Pos.set(-rx, ry, -rz); - v[1].Pos.set(rx, ry, -rz); - v[2].Pos.set(rx, 0, -rz); - v[3].Pos.set(-rx, 0, -rz); - break; - case 2: // right - if (INAREA(xi + 1, zi, m_cloud_radius_i)) { - u32 j = GETINDEX(xi + 1, zi, - m_cloud_radius_i); - if (grid[j]) - continue; - } - for (video::S3DVertex &vertex : v) { - vertex.Color = c_side_2; - vertex.Normal.set(1, 0, 0); - } - v[0].Pos.set(rx, ry, -rz); - v[1].Pos.set(rx, ry, rz); - v[2].Pos.set(rx, 0, rz); - v[3].Pos.set(rx, 0, -rz); - break; - case 3: // front - if (INAREA(xi, zi + 1, m_cloud_radius_i)) { - u32 j = GETINDEX(xi, zi + 1, - m_cloud_radius_i); - if (grid[j]) - continue; - } - for (video::S3DVertex &vertex : v) { - vertex.Color = c_side_1; - vertex.Normal.set(0, 0, -1); - } - v[0].Pos.set(rx, ry, rz); - v[1].Pos.set(-rx, ry, rz); - v[2].Pos.set(-rx, 0, rz); - v[3].Pos.set(rx, 0, rz); - break; - case 4: // left - if (INAREA(xi - 1, zi, m_cloud_radius_i)) { - u32 j = GETINDEX(xi - 1, zi, - m_cloud_radius_i); - if (grid[j]) - continue; - } - for (video::S3DVertex &vertex : v) { - vertex.Color = c_side_2; - vertex.Normal.set(-1, 0, 0); - } - v[0].Pos.set(-rx, ry, rz); - v[1].Pos.set(-rx, ry, -rz); - v[2].Pos.set(-rx, 0, -rz); - v[3].Pos.set(-rx, 0, rz); - break; - case 5: // bottom - for (video::S3DVertex &vertex : v) { - vertex.Color = c_bottom; - vertex.Normal.set(0, -1, 0); - } - v[0].Pos.set(rx, 0, rz); - v[1].Pos.set(-rx, 0, rz); - v[2].Pos.set(-rx, 0, -rz); - v[3].Pos.set(rx, 0, -rz); - break; + for (s16 zi0= -m_cloud_radius_i; zi0 < m_cloud_radius_i; zi0++) + for (s16 xi0= -m_cloud_radius_i; xi0 < m_cloud_radius_i; xi0++) + { + s16 zi = zi0; + s16 xi = xi0; + // Draw from front to back (needed for transparency) + /*if(zi <= 0) + zi = -m_cloud_radius_i - zi; + if(xi <= 0) + xi = -m_cloud_radius_i - xi;*/ + // Draw from back to front + if(zi >= 0) + zi = m_cloud_radius_i - zi - 1; + if(xi >= 0) + xi = m_cloud_radius_i - xi - 1; + + u32 i = GETINDEX(xi, zi, m_cloud_radius_i); + + if (!grid[i]) + continue; + + v2f p0 = v2f(xi,zi)*cloud_size + world_center_of_drawing_in_noise_f; + + video::S3DVertex v[4] = { + video::S3DVertex(0,0,0, 0,0,0, c_top, 0, 1), + video::S3DVertex(0,0,0, 0,0,0, c_top, 1, 1), + video::S3DVertex(0,0,0, 0,0,0, c_top, 1, 0), + video::S3DVertex(0,0,0, 0,0,0, c_top, 0, 0) + }; + + /*if(zi <= 0 && xi <= 0){ + v[0].Color.setBlue(255); + v[1].Color.setBlue(255); + v[2].Color.setBlue(255); + v[3].Color.setBlue(255); + }*/ + + f32 rx = cloud_size / 2.0f; + // if clouds are flat, the top layer should be at the given height + f32 ry = m_enable_3d ? m_params.thickness * BS : 0.0f; + f32 rz = cloud_size / 2; + + for(int i=0; idrawVertexPrimitiveList(v, 4, indices, 2, - video::EVT_STANDARD, scene::EPT_TRIANGLES, - video::EIT_16BIT); - } + for (video::S3DVertex &vertex : v) + vertex.Pos += pos; + u16 indices[] = {0,1,2,2,3,0}; + driver->drawVertexPrimitiveList(v, 4, indices, 2, + video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT); } + } delete[] grid; // Restore fog settings - driver->setFog(fog_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog, - fog_rangefog); + driver->setFog(fog_color, fog_type, fog_start, fog_end, fog_density, + fog_pixelfog, fog_rangefog); } void Clouds::step(float dtime) @@ -337,17 +344,11 @@ void Clouds::update(const v3f &camera_p, const video::SColorf &color_diffuse) { m_camera_pos = camera_p; m_color.r = MYMIN(MYMAX(color_diffuse.r * m_params.color_bright.getRed(), - m_params.color_ambient.getRed()), - 255) / - 255.0f; + m_params.color_ambient.getRed()), 255) / 255.0f; m_color.g = MYMIN(MYMAX(color_diffuse.g * m_params.color_bright.getGreen(), - m_params.color_ambient.getGreen()), - 255) / - 255.0f; + m_params.color_ambient.getGreen()), 255) / 255.0f; m_color.b = MYMIN(MYMAX(color_diffuse.b * m_params.color_bright.getBlue(), - m_params.color_ambient.getBlue()), - 255) / - 255.0f; + m_params.color_ambient.getBlue()), 255) / 255.0f; m_color.a = m_params.color_bright.getAlpha() / 255.0f; // is the camera inside the cloud mesh? @@ -357,10 +358,8 @@ void Clouds::update(const v3f &camera_p, const video::SColorf &color_diffuse) if (camera_height >= m_box.MinEdge.Y && camera_height <= m_box.MaxEdge.Y) { v2f camera_in_noise; - camera_in_noise.X = floor( - (camera_p.X - m_origin.X) / cloud_size + 0.5); - camera_in_noise.Y = floor( - (camera_p.Z - m_origin.Y) / cloud_size + 0.5); + camera_in_noise.X = floor((camera_p.X - m_origin.X) / cloud_size + 0.5); + camera_in_noise.Y = floor((camera_p.Z - m_origin.Y) / cloud_size + 0.5); bool filled = gridFilled(camera_in_noise.X, camera_in_noise.Y); m_camera_inside_cloud = filled; } @@ -376,8 +375,10 @@ void Clouds::readSettings() bool Clouds::gridFilled(int x, int y) const { float cloud_size_noise = cloud_size / (BS * 200.f); - float noise = noise2d_perlin((float)x * cloud_size_noise, - (float)y * cloud_size_noise, m_seed, 3, 0.5); + float noise = noise2d_perlin( + (float)x * cloud_size_noise, + (float)y * cloud_size_noise, + m_seed, 3, 0.5); // normalize to 0..1 (given 3 octaves) static constexpr const float noise_bound = 1.0f + 0.5f + 0.25f; float density = noise / noise_bound * 0.5f + 0.5f; diff --git a/src/client/clouds.h b/src/client/clouds.h index ba371de7d..a4d810faa 100644 --- a/src/client/clouds.h +++ b/src/client/clouds.h @@ -29,19 +29,16 @@ class Clouds; extern Clouds *g_menuclouds; // Scene manager used for menu clouds -namespace irr -{ -namespace scene -{ -class ISceneManager; -} -} +namespace irr{namespace scene{class ISceneManager;}} extern irr::scene::ISceneManager *g_menucloudsmgr; class Clouds : public scene::ISceneNode { public: - Clouds(scene::ISceneManager *mgr, s32 id, u32 seed); + Clouds(scene::ISceneManager* mgr, + s32 id, + u32 seed + ); ~Clouds(); @@ -53,11 +50,20 @@ class Clouds : public scene::ISceneNode virtual void render(); - virtual const aabb3f &getBoundingBox() const { return m_box; } + virtual const aabb3f &getBoundingBox() const + { + return m_box; + } - virtual u32 getMaterialCount() const { return 1; } + virtual u32 getMaterialCount() const + { + return 1; + } - virtual video::SMaterial &getMaterial(u32 i) { return m_material; } + virtual video::SMaterial& getMaterial(u32 i) + { + return m_material; + } /* Other stuff @@ -97,7 +103,10 @@ class Clouds : public scene::ISceneNode updateBox(); } - void setSpeed(v2f speed) { m_params.speed = speed; } + void setSpeed(v2f speed) + { + m_params.speed = speed; + } void setThickness(float thickness) { @@ -112,12 +121,10 @@ class Clouds : public scene::ISceneNode private: void updateBox() { - float height_bs = m_params.height * BS; + float height_bs = m_params.height * BS; float thickness_bs = m_params.thickness * BS; - m_box = aabb3f(-BS * 1000000.0f, height_bs - BS * m_camera_offset.Y, - -BS * 1000000.0f, BS * 1000000.0f, - height_bs + thickness_bs - BS * m_camera_offset.Y, - BS * 1000000.0f); + m_box = aabb3f(-BS * 1000000.0f, height_bs - BS * m_camera_offset.Y, -BS * 1000000.0f, + BS * 1000000.0f, height_bs + thickness_bs - BS * m_camera_offset.Y, BS * 1000000.0f); } bool gridFilled(int x, int y) const; @@ -133,4 +140,5 @@ class Clouds : public scene::ISceneNode video::SColorf m_color = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); CloudParams m_params; bool m_camera_inside_cloud = false; + }; diff --git a/src/client/content_cao.cpp b/src/client/content_cao.cpp index 36a47d57c..cf671d5ca 100644 --- a/src/client/content_cao.cpp +++ b/src/client/content_cao.cpp @@ -53,7 +53,8 @@ struct ToolCapabilities; std::unordered_map ClientActiveObject::m_types; -template void SmoothTranslator::init(T current) +template +void SmoothTranslator::init(T current) { val_old = current; val_current = current; @@ -63,9 +64,8 @@ template void SmoothTranslator::init(T current) aim_is_end = true; } -template -void SmoothTranslator::update( - T new_target, bool is_end_position, float update_interval) +template +void SmoothTranslator::update(T new_target, bool is_end_position, float update_interval) { aim_is_end = is_end_position; val_old = val_current; @@ -81,7 +81,8 @@ void SmoothTranslator::update( anim_time_counter = 0; } -template void SmoothTranslator::translate(f32 dtime) +template +void SmoothTranslator::translate(f32 dtime) { anim_time_counter = anim_time_counter + dtime; T val_diff = val_target - val_old; @@ -109,7 +110,8 @@ void SmoothTranslatorWrapped::translate(f32 dtime) // Move a bit less than should, to avoid oscillation moveratio = std::min(moveratio * 0.8f, move_end); - wrappedApproachShortest(val_current, val_target, val_diff * moveratio, 360.f); + wrappedApproachShortest(val_current, val_target, + val_diff * moveratio, 360.f); } void SmoothTranslatorWrappedv3f::translate(f32 dtime) @@ -137,26 +139,26 @@ void SmoothTranslatorWrappedv3f::translate(f32 dtime) // Move a bit less than should, to avoid oscillation moveratio = std::min(moveratio * 0.8f, move_end); - wrappedApproachShortest( - val_current.X, val_target.X, val_diff_v3f.X * moveratio, 360.f); + wrappedApproachShortest(val_current.X, val_target.X, + val_diff_v3f.X * moveratio, 360.f); - wrappedApproachShortest( - val_current.Y, val_target.Y, val_diff_v3f.Y * moveratio, 360.f); + wrappedApproachShortest(val_current.Y, val_target.Y, + val_diff_v3f.Y * moveratio, 360.f); - wrappedApproachShortest( - val_current.Z, val_target.Z, val_diff_v3f.Z * moveratio, 360.f); + wrappedApproachShortest(val_current.Z, val_target.Z, + val_diff_v3f.Z * moveratio, 360.f); } /* Other stuff */ -static void setBillboardTextureMatrix( - scene::IBillboardSceneNode *bill, float txs, float tys, int col, int row) +static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill, + float txs, float tys, int col, int row) { - video::SMaterial &material = bill->getMaterial(0); - core::matrix4 &matrix = material.getTextureMatrix(0); - matrix.setTextureTranslate(txs * col, tys * row); + video::SMaterial& material = bill->getMaterial(0); + core::matrix4& matrix = material.getTextureMatrix(0); + matrix.setTextureTranslate(txs*col, tys*row); matrix.setTextureScale(txs, tys); } @@ -179,9 +181,12 @@ class TestCAO : public ClientActiveObject TestCAO(Client *client, ClientEnvironment *env); virtual ~TestCAO() = default; - ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_TEST; } + ActiveObjectType getType() const + { + return ACTIVEOBJECT_TYPE_TEST; + } - static ClientActiveObject *create(Client *client, ClientEnvironment *env); + static ClientActiveObject* create(Client *client, ClientEnvironment *env); void addToScene(ITextureSource *tsrc); void removeFromScene(bool permanent); @@ -193,7 +198,6 @@ class TestCAO : public ClientActiveObject void processMessage(const std::string &data); bool getCollisionBox(aabb3f *toset) const { return false; } - private: scene::IMeshSceneNode *m_node; v3f m_position; @@ -202,38 +206,40 @@ class TestCAO : public ClientActiveObject // Prototype TestCAO proto_TestCAO(NULL, NULL); -TestCAO::TestCAO(Client *client, ClientEnvironment *env) : - ClientActiveObject(0, client, env), m_node(NULL), - m_position(v3f(0, 10 * BS, 0)) +TestCAO::TestCAO(Client *client, ClientEnvironment *env): + ClientActiveObject(0, client, env), + m_node(NULL), + m_position(v3f(0,10*BS,0)) { ClientActiveObject::registerType(getType(), create); } -ClientActiveObject *TestCAO::create(Client *client, ClientEnvironment *env) +ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env) { return new TestCAO(client, env); } void TestCAO::addToScene(ITextureSource *tsrc) { - if (m_node != NULL) + if(m_node != NULL) return; - // video::IVideoDriver* driver = smgr->getVideoDriver(); + //video::IVideoDriver* driver = smgr->getVideoDriver(); scene::SMesh *mesh = new scene::SMesh(); scene::IMeshBuffer *buf = new scene::SMeshBuffer(); - video::SColor c(255, 255, 255, 255); - video::S3DVertex vertices[4] = { - video::S3DVertex(-BS / 2, -BS / 4, 0, 0, 0, 0, c, 0, 1), - video::S3DVertex(BS / 2, -BS / 4, 0, 0, 0, 0, c, 1, 1), - video::S3DVertex(BS / 2, BS / 4, 0, 0, 0, 0, c, 1, 0), - video::S3DVertex(-BS / 2, BS / 4, 0, 0, 0, 0, c, 0, 0), + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0), }; - u16 indices[] = {0, 1, 2, 2, 3, 0}; + u16 indices[] = {0,1,2,2,3,0}; buf->append(vertices, 4, indices, 6); // Set material - buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false + buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png")); buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); @@ -266,14 +272,15 @@ void TestCAO::updateNodePos() return; m_node->setPosition(m_position); - // m_node->setRotation(v3f(0, 45, 0)); + //m_node->setRotation(v3f(0, 45, 0)); } void TestCAO::step(float dtime, ClientEnvironment *env) { - if (m_node) { + if(m_node) + { v3f rot = m_node->getRotation(); - // infostream<<"dtime="<> cmd; - if (cmd == 0) { + is>>cmd; + if(cmd == 0) + { v3f newpos; - is >> newpos.X; - is >> newpos.Y; - is >> newpos.Z; + is>>newpos.X; + is>>newpos.Y; + is>>newpos.Z; m_position = newpos; updateNodePos(); } @@ -301,7 +309,7 @@ void TestCAO::processMessage(const std::string &data) #include "clientobject.h" -GenericCAO::GenericCAO(Client *client, ClientEnvironment *env) : +GenericCAO::GenericCAO(Client *client, ClientEnvironment *env): ClientActiveObject(0, client, env) { if (client == NULL) { @@ -313,8 +321,9 @@ GenericCAO::GenericCAO(Client *client, ClientEnvironment *env) : bool GenericCAO::getCollisionBox(aabb3f *toset) const { - if (m_prop.physical) { - // update collision box + if (m_prop.physical) + { + //update collision box toset->MinEdge = m_prop.collisionbox.MinEdge * BS; toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS; @@ -334,7 +343,7 @@ bool GenericCAO::collideWithObjects() const void GenericCAO::initialize(const std::string &data) { - infostream << "GenericCAO: Got init data" << std::endl; + infostream<<"GenericCAO: Got init data"<getCameraOffset(); return m_matrixnode->getAbsolutePosition() + - intToFloat(camera_offset, BS); + intToFloat(camera_offset, BS); } return m_position; @@ -451,8 +461,7 @@ void GenericCAO::setChildrenVisible(bool toset) } } -void GenericCAO::setAttachment( - int parent_id, const std::string &bone, v3f position, v3f rotation) +void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation) { int old_parent = m_attachment_parent_id; m_attachment_parent_id = parent_id; @@ -470,12 +479,12 @@ void GenericCAO::setAttachment( if (parent) parent->addAttachmentChild(m_id); } - + updateAttachments(); } -void GenericCAO::getAttachment( - int *parent_id, std::string *bone, v3f *position, v3f *rotation) const +void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position, + v3f *rotation) const { *parent_id = m_attachment_parent_id; *bone = m_attachment_bone; @@ -514,10 +523,10 @@ void GenericCAO::removeAttachmentChild(int child_id) m_attachment_child_ids.erase(child_id); } -ClientActiveObject *GenericCAO::getParent() const +ClientActiveObject* GenericCAO::getParent() const { - return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) - : nullptr; + return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) : + nullptr; } void GenericCAO::removeFromScene(bool permanent) @@ -535,7 +544,7 @@ void GenericCAO::removeFromScene(bool permanent) m_meshnode->remove(); m_meshnode->drop(); m_meshnode = nullptr; - } else if (m_animated_meshnode) { + } else if (m_animated_meshnode) { m_animated_meshnode->remove(); m_animated_meshnode->drop(); m_animated_meshnode = nullptr; @@ -581,30 +590,26 @@ void GenericCAO::addToScene(ITextureSource *tsrc) MaterialType material_type; if (m_prop.shaded && m_prop.glow == 0) - material_type = (m_prop.use_texture_alpha) ? TILE_MATERIAL_ALPHA - : TILE_MATERIAL_BASIC; + material_type = (m_prop.use_texture_alpha) ? + TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC; else - material_type = (m_prop.use_texture_alpha) - ? TILE_MATERIAL_PLAIN_ALPHA - : TILE_MATERIAL_PLAIN; + material_type = (m_prop.use_texture_alpha) ? + TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN; - u32 shader_id = shader_source->getShader( - "object_shader", material_type, NDT_NORMAL); + u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL); m_material_type = shader_source->getShaderInfo(shader_id).material; } else { - m_material_type = - (m_prop.use_texture_alpha) - ? video::EMT_TRANSPARENT_ALPHA_CHANNEL - : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + m_material_type = (m_prop.use_texture_alpha) ? + video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; } auto grabMatrixNode = [this] { - m_matrixnode = RenderingEngine::get_scene_manager() - ->addDummyTransformationSceneNode(); + m_matrixnode = RenderingEngine::get_scene_manager()-> + addDummyTransformationSceneNode(); m_matrixnode->grab(); }; - auto setSceneNodeMaterial = [this](scene::ISceneNode *node) { + auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) { node->setMaterialFlag(video::EMF_LIGHTING, false); node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false); node->setMaterialFlag(video::EMF_FOG_ENABLE, true); @@ -618,22 +623,21 @@ void GenericCAO::addToScene(ITextureSource *tsrc) if (m_prop.visual == "sprite") { grabMatrixNode(); - m_spritenode = RenderingEngine::get_scene_manager() - ->addBillboardSceneNode(m_matrixnode, - v2f(1, 1), v3f(0, 0, 0), - -1); + m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode( + m_matrixnode, v2f(1, 1), v3f(0,0,0), -1); m_spritenode->grab(); - m_spritenode->setMaterialTexture( - 0, tsrc->getTextureForMesh("unknown_node.png")); + m_spritenode->setMaterialTexture(0, + tsrc->getTextureForMesh("unknown_node.png")); setSceneNodeMaterial(m_spritenode); - m_spritenode->setSize( - v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS); + m_spritenode->setSize(v2f(m_prop.visual_size.X, + m_prop.visual_size.Y) * BS); { const float txs = 1.0 / 1; const float tys = 1.0 / 1; - setBillboardTextureMatrix(m_spritenode, txs, tys, 0, 0); + setBillboardTextureMatrix(m_spritenode, + txs, tys, 0, 0); } } else if (m_prop.visual == "upright_sprite") { grabMatrixNode(); @@ -645,17 +649,17 @@ void GenericCAO::addToScene(ITextureSource *tsrc) { // Front scene::IMeshBuffer *buf = new scene::SMeshBuffer(); video::S3DVertex vertices[4] = { - video::S3DVertex(-dx, -dy, 0, 0, 0, 1, c, 1, 1), - video::S3DVertex(dx, -dy, 0, 0, 0, 1, c, 0, 1), - video::S3DVertex(dx, dy, 0, 0, 0, 1, c, 0, 0), - video::S3DVertex(-dx, dy, 0, 0, 0, 1, c, 1, 0), + video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1), + video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1), + video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0), + video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0), }; if (m_is_player) { // Move minimal Y position to 0 (feet position) for (video::S3DVertex &vertex : vertices) vertex.Pos.Y += dy; } - u16 indices[] = {0, 1, 2, 2, 3, 0}; + u16 indices[] = {0,1,2,2,3,0}; buf->append(vertices, 4, indices, 6); // Set material buf->getMaterial().setFlag(video::EMF_LIGHTING, false); @@ -665,10 +669,8 @@ void GenericCAO::addToScene(ITextureSource *tsrc) if (m_enable_shaders) { buf->getMaterial().EmissiveColor = c; - buf->getMaterial().setFlag( - video::EMF_GOURAUD_SHADING, false); - buf->getMaterial().setFlag( - video::EMF_NORMALIZE_NORMALS, true); + buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false); + buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true); } // Add to mesh @@ -678,17 +680,17 @@ void GenericCAO::addToScene(ITextureSource *tsrc) { // Back scene::IMeshBuffer *buf = new scene::SMeshBuffer(); video::S3DVertex vertices[4] = { - video::S3DVertex(dx, -dy, 0, 0, 0, -1, c, 1, 1), - video::S3DVertex(-dx, -dy, 0, 0, 0, -1, c, 0, 1), - video::S3DVertex(-dx, dy, 0, 0, 0, -1, c, 0, 0), - video::S3DVertex(dx, dy, 0, 0, 0, -1, c, 1, 0), + video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1), + video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1), + video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0), + video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0), }; if (m_is_player) { // Move minimal Y position to 0 (feet position) for (video::S3DVertex &vertex : vertices) vertex.Pos.Y += dy; } - u16 indices[] = {0, 1, 2, 2, 3, 0}; + u16 indices[] = {0,1,2,2,3,0}; buf->append(vertices, 4, indices, 6); // Set material buf->getMaterial().setFlag(video::EMF_LIGHTING, false); @@ -698,18 +700,16 @@ void GenericCAO::addToScene(ITextureSource *tsrc) if (m_enable_shaders) { buf->getMaterial().EmissiveColor = c; - buf->getMaterial().setFlag( - video::EMF_GOURAUD_SHADING, false); - buf->getMaterial().setFlag( - video::EMF_NORMALIZE_NORMALS, true); + buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false); + buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true); } // Add to mesh mesh->addMeshBuffer(buf); buf->drop(); } - m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode( - mesh, m_matrixnode); + m_meshnode = RenderingEngine::get_scene_manager()-> + addMeshSceneNode(mesh, m_matrixnode); m_meshnode->grab(); mesh->drop(); // Set it to use the materials of the meshbuffers directly. @@ -717,54 +717,47 @@ void GenericCAO::addToScene(ITextureSource *tsrc) m_meshnode->setReadOnlyMaterials(true); } else if (m_prop.visual == "cube") { grabMatrixNode(); - scene::IMesh *mesh = createCubeMesh(v3f(BS, BS, BS)); - m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode( - mesh, m_matrixnode); + scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS)); + m_meshnode = RenderingEngine::get_scene_manager()-> + addMeshSceneNode(mesh, m_matrixnode); m_meshnode->grab(); mesh->drop(); m_meshnode->setScale(m_prop.visual_size); - m_meshnode->setMaterialFlag( - video::EMF_BACK_FACE_CULLING, m_prop.backface_culling); + m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, + m_prop.backface_culling); setSceneNodeMaterial(m_meshnode); } else if (m_prop.visual == "mesh") { grabMatrixNode(); scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true); if (mesh) { - m_animated_meshnode = - RenderingEngine::get_scene_manager() - ->addAnimatedMeshSceneNode(mesh, - m_matrixnode); + m_animated_meshnode = RenderingEngine::get_scene_manager()-> + addAnimatedMeshSceneNode(mesh, m_matrixnode); m_animated_meshnode->grab(); mesh->drop(); // The scene node took hold of it if (!checkMeshNormals(mesh)) { - infostream << "GenericCAO: recalculating normals for " - "mesh " - << m_prop.mesh << std::endl; - m_smgr->getMeshManipulator()->recalculateNormals( - mesh, true, false); + infostream << "GenericCAO: recalculating normals for mesh " + << m_prop.mesh << std::endl; + m_smgr->getMeshManipulator()-> + recalculateNormals(mesh, true, false); } - m_animated_meshnode - ->animateJoints(); // Needed for some animations + m_animated_meshnode->animateJoints(); // Needed for some animations m_animated_meshnode->setScale(m_prop.visual_size); // set vertex colors to ensure alpha is set - setMeshColor(m_animated_meshnode->getMesh(), - video::SColor(0xFFFFFFFF)); + setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF)); - setAnimatedMeshColor( - m_animated_meshnode, video::SColor(0xFFFFFFFF)); + setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF)); setSceneNodeMaterial(m_animated_meshnode); m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, - m_prop.backface_culling); + m_prop.backface_culling); } else - errorstream << "GenericCAO::addToScene(): Could not load mesh " - << m_prop.mesh << std::endl; + errorstream<<"GenericCAO::addToScene(): Could not load mesh "<idef(); item = ItemStack(m_prop.textures[0], 1, 0, idef); } } else { - infostream << "serialized form: " << m_prop.wield_item - << std::endl; + infostream << "serialized form: " << m_prop.wield_item << std::endl; item.deSerialize(m_prop.wield_item, m_client->idef()); } m_wield_meshnode = new WieldMeshSceneNode( - RenderingEngine::get_scene_manager(), -1); - m_wield_meshnode->setItem(item, m_client, (m_prop.visual == "wielditem")); + RenderingEngine::get_scene_manager(), -1); + m_wield_meshnode->setItem(item, m_client, + (m_prop.visual == "wielditem")); m_wield_meshnode->setScale(m_prop.visual_size / 2.0f); m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF)); } else { - infostream << "GenericCAO::addToScene(): \"" << m_prop.visual - << "\" not supported" << std::endl; + infostream<<"GenericCAO::addToScene(): \""<getBool("fullbright")) light_at_pos = 255; - + v3s16 pos[3]; u16 npos = getLightPosition(pos); for (u16 i = 0; i < npos; i++) { bool this_ok; MapNode n = m_env->getMap().getNode(pos[i], &this_ok); if (this_ok) { - u8 this_light = n.getLightBlend( - day_night_ratio, m_client->ndef()); + u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef()); light_at_pos = MYMAX(light_at_pos, this_light); pos_ok = true; } @@ -899,8 +891,7 @@ u16 GenericCAO::getLightPosition(v3s16 *pos) void GenericCAO::updateNametag() { - if (m_is_local_player && - !g_settings->getBool("freecam")) // No nametag for local player + if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player return; if (m_prop.nametag.empty()) { @@ -920,8 +911,8 @@ void GenericCAO::updateNametag() pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f; if (!m_nametag) { // Add nametag - m_nametag = m_client->getCamera()->addNametag( - node, m_prop.nametag, m_prop.nametag_color, pos); + m_nametag = m_client->getCamera()->addNametag(node, + m_prop.nametag, m_prop.nametag_color, pos); } else { // Update nametag m_nametag->nametag_text = m_prop.nametag; @@ -939,11 +930,11 @@ void GenericCAO::updateNodePos() if (node) { v3s16 camera_offset = m_env->getCameraOffset(); - v3f pos = pos_translator.val_current - intToFloat(camera_offset, BS); + v3f pos = pos_translator.val_current - + intToFloat(camera_offset, BS); getPosRotMatrix().setTranslation(pos); if (node != m_spritenode) { // rotate if not a sprite - v3f rot = m_is_local_player ? -m_rotation - : -rot_translator.val_current; + v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current; setPitchYawRoll(getPosRotMatrix(), rot); } } @@ -956,7 +947,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) LocalPlayer *player = m_env->getLocalPlayer(); m_position = player->getLegitPosition(); pos_translator.val_current = m_position; - if (!g_settings->getBool("freecam")) { + if (! g_settings->getBool("freecam")) { m_rotation.Y = wrapDegrees_0_360(player->getYaw()); rot_translator.val_current = m_rotation; } @@ -964,43 +955,39 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) if (m_is_visible) { int old_anim = player->last_animation; float old_anim_speed = player->last_animation_speed; - m_velocity = v3f(0, 0, 0); - m_acceleration = v3f(0, 0, 0); + m_velocity = v3f(0,0,0); + m_acceleration = v3f(0,0,0); const PlayerControl &controls = player->getPlayerControl(); bool walking = false; - if ((controls.up || controls.down || controls.left || - controls.right || - controls.forw_move_joystick_axis != 0.f || - controls.sidew_move_joystick_axis != 0.f) && - !g_settings->getBool("freecam")) + if ((controls.up || controls.down || controls.left || controls.right || + controls.forw_move_joystick_axis != 0.f || + controls.sidew_move_joystick_axis != 0.f) && ! g_settings->getBool("freecam")) walking = true; f32 new_speed = player->local_animation_speed; - v2s32 new_anim = v2s32(0, 0); + v2s32 new_anim = v2s32(0,0); bool allow_update = false; // increase speed if using fast or flying fast - if ((g_settings->getBool("fast_move") && - m_client->checkLocalPrivilege("fast")) && + if((g_settings->getBool("fast_move") && + m_client->checkLocalPrivilege("fast")) && (controls.aux1 || - (!player->touching_ground && - g_settings->getBool( - "free_move") && - m_client->checkLocalPrivilege( - "fly")))) - new_speed *= 1.5; + (!player->touching_ground && + g_settings->getBool("free_move") && + m_client->checkLocalPrivilege("fly")))) + new_speed *= 1.5; // slowdown speed if sneeking - if (controls.sneak && walking && !g_settings->getBool("no_slow")) + if (controls.sneak && walking && ! g_settings->getBool("no_slow")) new_speed /= 2; if (walking && (controls.LMB || controls.RMB)) { new_anim = player->local_animations[3]; player->last_animation = WD_ANIM; - } else if (walking) { + } else if(walking) { new_anim = player->local_animations[1]; player->last_animation = WALK_ANIM; - } else if (controls.LMB || controls.RMB) { + } else if(controls.LMB || controls.RMB) { new_anim = player->local_animations[2]; player->last_animation = DIG_ANIM; } @@ -1023,9 +1010,10 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) // Update local player animations if ((player->last_animation != old_anim || - m_animation_speed != old_anim_speed) && - player->last_animation != NO_ANIM && allow_update) - updateAnimation(); + m_animation_speed != old_anim_speed) && + player->last_animation != NO_ANIM && allow_update) + updateAnimation(); + } } @@ -1038,20 +1026,17 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) ClientActiveObject *obj = m_env->getActiveObject(cao_id); if (obj) { scene::ISceneNode *child_node = obj->getSceneNode(); - // The node's parent is always an - // IDummyTraformationSceneNode, so we need to reparent - // that one instead. + // The node's parent is always an IDummyTraformationSceneNode, + // so we need to reparent that one instead. if (child_node) - child_node->getParent()->setParent( - m_smgr->getRootSceneNode()); + child_node->getParent()->setParent(m_smgr->getRootSceneNode()); } } removeFromScene(false); addToScene(m_client->tsrc()); - // Attachments, part 2: Now that the parent has been refreshed, put its - // attachments back + // Attachments, part 2: Now that the parent has been refreshed, put its attachments back for (u16 cao_id : m_attachment_child_ids) { ClientActiveObject *obj = m_env->getActiveObject(cao_id); if (obj) @@ -1064,31 +1049,31 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) if (node) node->setVisible(m_is_visible); - if (getParent() != - NULL) // Attachments should be glued to their parent by Irrlicht + if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht { // Set these for later m_position = getPosition(); - m_velocity = v3f(0, 0, 0); - m_acceleration = v3f(0, 0, 0); + m_velocity = v3f(0,0,0); + m_acceleration = v3f(0,0,0); pos_translator.val_current = m_position; pos_translator.val_target = m_position; } else { rot_translator.translate(dtime); v3f lastpos = pos_translator.val_current; - if (m_prop.physical) { + if(m_prop.physical) + { aabb3f box = m_prop.collisionbox; box.MinEdge *= BS; box.MaxEdge *= BS; collisionMoveResult moveresult; - f32 pos_max_d = BS * 0.125; // Distance per iteration + f32 pos_max_d = BS*0.125; // Distance per iteration v3f p_pos = m_position; v3f p_velocity = m_velocity; - moveresult = collisionMoveSimple(env, env->getGameDef(), - pos_max_d, box, m_prop.stepheight, dtime, &p_pos, - &p_velocity, m_acceleration, this, - m_prop.collideWithObjects); + moveresult = collisionMoveSimple(env,env->getGameDef(), + pos_max_d, box, m_prop.stepheight, dtime, + &p_pos, &p_velocity, m_acceleration, + this, m_prop.collideWithObjects); // Apply results m_position = p_pos; m_velocity = p_velocity; @@ -1096,8 +1081,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) bool is_end_position = moveresult.collides; pos_translator.update(m_position, is_end_position, dtime); } else { - m_position += dtime * m_velocity + - 0.5 * dtime * dtime * m_acceleration; + m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration; m_velocity += dtime * m_acceleration; pos_translator.update(m_position, pos_translator.aim_is_end, pos_translator.anim_time); @@ -1111,62 +1095,56 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) m_step_distance_counter = 0.0f; if (!m_is_local_player && m_prop.makes_footstep_sound) { const NodeDefManager *ndef = m_client->ndef(); - v3s16 p = floatToInt( - getPosition() + v3f(0.0f, - (m_prop.collisionbox.MinEdge.Y - - 0.5f) * - BS, - 0.0f), - BS); + v3s16 p = floatToInt(getPosition() + + v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS); MapNode n = m_env->getMap().getNode(p); SimpleSoundSpec spec = ndef->get(n).sound_footstep; // Reduce footstep gain, as non-local-player footsteps are // somehow louder. spec.gain *= 0.6f; - m_client->sound()->playSoundAt( - spec, false, getPosition()); + m_client->sound()->playSoundAt(spec, false, getPosition()); } } } m_anim_timer += dtime; - if (m_anim_timer >= m_anim_framelength) { + if(m_anim_timer >= m_anim_framelength) + { m_anim_timer -= m_anim_framelength; m_anim_frame++; - if (m_anim_frame >= m_anim_num_frames) + if(m_anim_frame >= m_anim_num_frames) m_anim_frame = 0; } updateTexturePos(); - if (m_reset_textures_timer >= 0) { + if(m_reset_textures_timer >= 0) + { m_reset_textures_timer -= dtime; - if (m_reset_textures_timer <= 0) { + if(m_reset_textures_timer <= 0) { m_reset_textures_timer = -1; updateTextures(m_previous_texture_modifier); } } if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) { - // This is the child node's rotation. It is only used for - // automatic_rotate. + // This is the child node's rotation. It is only used for automatic_rotate. v3f local_rot = node->getRotation(); - local_rot.Y = modulo360f( - local_rot.Y - - dtime * core::RADTODEG * m_prop.automatic_rotate); + local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG * + m_prop.automatic_rotate); node->setRotation(local_rot); } if (!getParent() && m_prop.automatic_face_movement_dir && (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) { - float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI + - m_prop.automatic_face_movement_dir_offset; + float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI + + m_prop.automatic_face_movement_dir_offset; float max_rotation_per_sec = m_prop.automatic_face_movement_max_rotation_per_sec; if (max_rotation_per_sec > 0) { wrappedApproachShortest(m_rotation.Y, target_yaw, - dtime * max_rotation_per_sec, 360.f); + dtime * max_rotation_per_sec, 360.f); } else { // Negative values of max_rotation_per_sec mean disabled. m_rotation.Y = target_yaw; @@ -1191,13 +1169,14 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) void GenericCAO::updateTexturePos() { - if (m_spritenode) { - scene::ICameraSceneNode *camera = + if(m_spritenode) + { + scene::ICameraSceneNode* camera = m_spritenode->getSceneManager()->getActiveCamera(); - if (!camera) + if(!camera) return; - v3f cam_to_entity = m_spritenode->getAbsolutePosition() - - camera->getAbsolutePosition(); + v3f cam_to_entity = m_spritenode->getAbsolutePosition() + - camera->getAbsolutePosition(); cam_to_entity.normalize(); int row = m_tx_basepos.Y; @@ -1209,17 +1188,17 @@ void GenericCAO::updateTexturePos() else if (cam_to_entity.Y < -0.75) col += 4; else { - float mob_dir = atan2(cam_to_entity.Z, cam_to_entity.X) / - M_PI * 180.; + float mob_dir = + atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.; float dir = mob_dir - m_rotation.Y; dir = wrapDegrees_180(dir); if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f) col += 2; - else if (std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f) + else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f) col += 3; - else if (std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f) + else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f) col += 0; - else if (std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f) + else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f) col += 1; else col += 4; @@ -1256,106 +1235,87 @@ void GenericCAO::updateTextures(std::string mod) texturestring += mod; m_spritenode->getMaterial(0).MaterialType = m_material_type; m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f; - m_spritenode->setMaterialTexture( - 0, tsrc->getTextureForMesh(texturestring)); + m_spritenode->setMaterialTexture(0, + tsrc->getTextureForMesh(texturestring)); - // This allows setting per-material colors. However, until a real - // lighting system is added, the code below will have no effect. - // Once MineTest has directional lighting, it should work - // automatically. + // This allows setting per-material colors. However, until a real lighting + // system is added, the code below will have no effect. Once MineTest + // has directional lighting, it should work automatically. if (!m_prop.colors.empty()) { - m_spritenode->getMaterial(0).AmbientColor = - m_prop.colors[0]; - m_spritenode->getMaterial(0).DiffuseColor = - m_prop.colors[0]; - m_spritenode->getMaterial(0).SpecularColor = - m_prop.colors[0]; + m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0]; + m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0]; + m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0]; } - m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, - use_trilinear_filter); - m_spritenode->getMaterial(0).setFlag( - video::EMF_BILINEAR_FILTER, use_bilinear_filter); - m_spritenode->getMaterial(0).setFlag( - video::EMF_ANISOTROPIC_FILTER, - use_anisotropic_filter); + m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter); + m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter); + m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter); } } if (m_animated_meshnode) { if (m_prop.visual == "mesh") { for (u32 i = 0; i < m_prop.textures.size() && - i < m_animated_meshnode->getMaterialCount(); - ++i) { + i < m_animated_meshnode->getMaterialCount(); ++i) { std::string texturestring = m_prop.textures[i]; if (texturestring.empty()) - continue; // Empty texture string means don't - // modify that material + continue; // Empty texture string means don't modify that material texturestring += mod; - video::ITexture *texture = - tsrc->getTextureForMesh(texturestring); + video::ITexture* texture = tsrc->getTextureForMesh(texturestring); if (!texture) { - errorstream << "GenericCAO::updateTextures(): " - "Could not load texture " - << texturestring << std::endl; + errorstream<<"GenericCAO::updateTextures(): Could not load texture "<getMaterial(i); + video::SMaterial& material = m_animated_meshnode->getMaterial(i); material.MaterialType = m_material_type; material.MaterialTypeParam = 0.5f; material.TextureLayer[0].Texture = texture; material.setFlag(video::EMF_LIGHTING, true); material.setFlag(video::EMF_BILINEAR_FILTER, false); - material.setFlag(video::EMF_BACK_FACE_CULLING, - m_prop.backface_culling); + material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling); // don't filter low-res textures, makes them look blurry // player models have a res of 64 - const core::dimension2d &size = - texture->getOriginalSize(); + const core::dimension2d &size = texture->getOriginalSize(); const u32 res = std::min(size.Height, size.Width); use_trilinear_filter &= res > 64; use_bilinear_filter &= res > 64; - m_animated_meshnode->getMaterial(i).setFlag( - video::EMF_TRILINEAR_FILTER, - use_trilinear_filter); - m_animated_meshnode->getMaterial(i).setFlag( - video::EMF_BILINEAR_FILTER, - use_bilinear_filter); - m_animated_meshnode->getMaterial(i).setFlag( - video::EMF_ANISOTROPIC_FILTER, - use_anisotropic_filter); + m_animated_meshnode->getMaterial(i) + .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter); + m_animated_meshnode->getMaterial(i) + .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter); + m_animated_meshnode->getMaterial(i) + .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter); } for (u32 i = 0; i < m_prop.colors.size() && - i < m_animated_meshnode->getMaterialCount(); - ++i) { - // This allows setting per-material colors. However, until - // a real lighting system is added, the code below will - // have no effect. Once MineTest has directional lighting, - // it should work automatically. - m_animated_meshnode->getMaterial(i).AmbientColor = - m_prop.colors[i]; - m_animated_meshnode->getMaterial(i).DiffuseColor = - m_prop.colors[i]; - m_animated_meshnode->getMaterial(i).SpecularColor = - m_prop.colors[i]; + i < m_animated_meshnode->getMaterialCount(); ++i) + { + // This allows setting per-material colors. However, until a real lighting + // system is added, the code below will have no effect. Once MineTest + // has directional lighting, it should work automatically. + m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i]; + m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i]; + m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i]; } } } - if (m_meshnode) { - if (m_prop.visual == "cube") { - for (u32 i = 0; i < 6; ++i) { + if(m_meshnode) + { + if(m_prop.visual == "cube") + { + for (u32 i = 0; i < 6; ++i) + { std::string texturestring = "unknown_node.png"; - if (m_prop.textures.size() > i) + if(m_prop.textures.size() > i) texturestring = m_prop.textures[i]; texturestring += mod; + // Set material flags and texture - video::SMaterial &material = m_meshnode->getMaterial(i); + video::SMaterial& material = m_meshnode->getMaterial(i); material.MaterialType = m_material_type; material.MaterialTypeParam = 0.5f; material.setFlag(video::EMF_LIGHTING, false); @@ -1364,28 +1324,19 @@ void GenericCAO::updateTextures(std::string mod) tsrc->getTextureForMesh(texturestring)); material.getTextureMatrix(0).makeIdentity(); - // This allows setting per-material colors. However, until - // a real lighting system is added, the code below will - // have no effect. Once MineTest has directional lighting, - // it should work automatically. - if (m_prop.colors.size() > i) { - m_meshnode->getMaterial(i).AmbientColor = - m_prop.colors[i]; - m_meshnode->getMaterial(i).DiffuseColor = - m_prop.colors[i]; - m_meshnode->getMaterial(i).SpecularColor = - m_prop.colors[i]; + // This allows setting per-material colors. However, until a real lighting + // system is added, the code below will have no effect. Once MineTest + // has directional lighting, it should work automatically. + if(m_prop.colors.size() > i) + { + m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i]; + m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i]; + m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i]; } - m_meshnode->getMaterial(i).setFlag( - video::EMF_TRILINEAR_FILTER, - use_trilinear_filter); - m_meshnode->getMaterial(i).setFlag( - video::EMF_BILINEAR_FILTER, - use_bilinear_filter); - m_meshnode->getMaterial(i).setFlag( - video::EMF_ANISOTROPIC_FILTER, - use_anisotropic_filter); + m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter); + m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter); + m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter); } } else if (m_prop.visual == "upright_sprite") { scene::IMesh *mesh = m_meshnode->getMesh(); @@ -1395,28 +1346,21 @@ void GenericCAO::updateTextures(std::string mod) tname = m_prop.textures[0]; tname += mod; scene::IMeshBuffer *buf = mesh->getMeshBuffer(0); - buf->getMaterial().setTexture( - 0, tsrc->getTextureForMesh(tname)); - - // This allows setting per-material colors. However, until - // a real lighting system is added, the code below will - // have no effect. Once MineTest has directional lighting, - // it should work automatically. - if (!m_prop.colors.empty()) { - buf->getMaterial().AmbientColor = - m_prop.colors[0]; - buf->getMaterial().DiffuseColor = - m_prop.colors[0]; - buf->getMaterial().SpecularColor = - m_prop.colors[0]; + buf->getMaterial().setTexture(0, + tsrc->getTextureForMesh(tname)); + + // This allows setting per-material colors. However, until a real lighting + // system is added, the code below will have no effect. Once MineTest + // has directional lighting, it should work automatically. + if(!m_prop.colors.empty()) { + buf->getMaterial().AmbientColor = m_prop.colors[0]; + buf->getMaterial().DiffuseColor = m_prop.colors[0]; + buf->getMaterial().SpecularColor = m_prop.colors[0]; } - buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, - use_trilinear_filter); - buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, - use_bilinear_filter); - buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, - use_anisotropic_filter); + buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter); + buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter); } { std::string tname = "unknown_object.png"; @@ -1426,35 +1370,25 @@ void GenericCAO::updateTextures(std::string mod) tname = m_prop.textures[0]; tname += mod; scene::IMeshBuffer *buf = mesh->getMeshBuffer(1); - buf->getMaterial().setTexture( - 0, tsrc->getTextureForMesh(tname)); + buf->getMaterial().setTexture(0, + tsrc->getTextureForMesh(tname)); - // This allows setting per-material colors. However, until - // a real lighting system is added, the code below will - // have no effect. Once MineTest has directional lighting, - // it should work automatically. + // This allows setting per-material colors. However, until a real lighting + // system is added, the code below will have no effect. Once MineTest + // has directional lighting, it should work automatically. if (m_prop.colors.size() >= 2) { - buf->getMaterial().AmbientColor = - m_prop.colors[1]; - buf->getMaterial().DiffuseColor = - m_prop.colors[1]; - buf->getMaterial().SpecularColor = - m_prop.colors[1]; + buf->getMaterial().AmbientColor = m_prop.colors[1]; + buf->getMaterial().DiffuseColor = m_prop.colors[1]; + buf->getMaterial().SpecularColor = m_prop.colors[1]; } else if (!m_prop.colors.empty()) { - buf->getMaterial().AmbientColor = - m_prop.colors[0]; - buf->getMaterial().DiffuseColor = - m_prop.colors[0]; - buf->getMaterial().SpecularColor = - m_prop.colors[0]; + buf->getMaterial().AmbientColor = m_prop.colors[0]; + buf->getMaterial().DiffuseColor = m_prop.colors[0]; + buf->getMaterial().SpecularColor = m_prop.colors[0]; } - buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, - use_trilinear_filter); - buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, - use_bilinear_filter); - buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, - use_anisotropic_filter); + buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter); + buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter); } // Set mesh color (only if lighting is disabled) if (!m_prop.colors.empty() && m_glow < 0) @@ -1469,15 +1403,13 @@ void GenericCAO::updateAnimation() return; if (m_animated_meshnode->getStartFrame() != m_animation_range.X || - m_animated_meshnode->getEndFrame() != m_animation_range.Y) - m_animated_meshnode->setFrameLoop( - m_animation_range.X, m_animation_range.Y); + m_animated_meshnode->getEndFrame() != m_animation_range.Y) + m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y); if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed) m_animated_meshnode->setAnimationSpeed(m_animation_speed); m_animated_meshnode->setTransitionTime(m_animation_blend); // Requires Irrlicht 1.8 or greater -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || \ - IRRLICHT_VERSION_MAJOR > 1 +#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1 if (m_animated_meshnode->getLoopMode() != m_animation_loop) m_animated_meshnode->setLoopMode(m_animation_loop); #endif @@ -1496,13 +1428,10 @@ void GenericCAO::updateBonePosition() if (m_bone_position.empty() || !m_animated_meshnode) return; - m_animated_meshnode->setJointMode( - irr::scene::EJUOR_CONTROL); // To write positions to the mesh on - // render + m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render for (auto &it : m_bone_position) { std::string bone_name = it.first; - irr::scene::IBoneSceneNode *bone = - m_animated_meshnode->getJointNode(bone_name.c_str()); + irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str()); if (bone) { bone->setPosition(it.second.X); bone->setRotation(it.second.Y); @@ -1515,8 +1444,7 @@ void GenericCAO::updateBonePosition() if (!bone) continue; - // If bone is manually positioned there is no need to perform the bug - // check + //If bone is manually positioned there is no need to perform the bug check bool skip = false; for (auto &it : m_bone_position) { if (it.first == bone->getName()) { @@ -1528,10 +1456,9 @@ void GenericCAO::updateBonePosition() continue; // Workaround for Irrlicht bug - // We check each bone to see if it has been rotated ~180deg from its - // expected position due to a bug in Irricht when using EJUOR_CONTROL - // joint control. If the bug is detected we update the bone to the proper - // position and update the bones transformation. + // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht + // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position + // and update the bones transformation. v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees(); float offset = fabsf(bone_rot.X - bone->getRotation().X); if (offset > 179.9f && offset < 180.1f) { @@ -1577,26 +1504,25 @@ void GenericCAO::updateAttachments() v3f old_pos = getPosition(); m_matrixnode->setParent(m_smgr->getRootSceneNode()); - getPosRotMatrix().setTranslation( - old_pos - intToFloat(camera_offset, BS)); + getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS)); m_matrixnode->updateAbsolutePosition(); } - } else // Attach + } + else // Attach { parent->updateAttachments(); scene::ISceneNode *parent_node = parent->getSceneNode(); scene::IAnimatedMeshSceneNode *parent_animated_mesh_node = parent->getAnimatedMeshSceneNode(); if (parent_animated_mesh_node && !m_attachment_bone.empty()) { - parent_node = parent_animated_mesh_node->getJointNode( - m_attachment_bone.c_str()); + parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str()); } if (m_matrixnode && parent_node) { m_matrixnode->setParent(parent_node); parent_node->updateAbsolutePosition(); getPosRotMatrix().setTranslation(m_attachment_position); - // setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation); + //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation); // use Irrlicht eulers instead getPosRotMatrix().setRotationDegrees(m_attachment_rotation); m_matrixnode->updateAbsolutePosition(); @@ -1616,20 +1542,23 @@ bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const */ bool uses_legacy_texture = new_.wield_item.empty() && - (new_.visual == "wielditem" || new_.visual == "item"); + (new_.visual == "wielditem" || new_.visual == "item"); // Ordered to compare primitive types before std::vectors return old.backface_culling != new_.backface_culling || - old.is_visible != new_.is_visible || old.mesh != new_.mesh || - old.shaded != new_.shaded || - old.use_texture_alpha != new_.use_texture_alpha || - old.visual != new_.visual || old.visual_size != new_.visual_size || - old.wield_item != new_.wield_item || old.colors != new_.colors || - (uses_legacy_texture && old.textures != new_.textures); + old.is_visible != new_.is_visible || + old.mesh != new_.mesh || + old.shaded != new_.shaded || + old.use_texture_alpha != new_.use_texture_alpha || + old.visual != new_.visual || + old.visual_size != new_.visual_size || + old.wield_item != new_.wield_item || + old.colors != new_.colors || + (uses_legacy_texture && old.textures != new_.textures); } void GenericCAO::processMessage(const std::string &data) { - // infostream<<"GenericCAO: Got message"< 0) { m_reset_textures_timer = -1; updateTextures(m_previous_texture_modifier); @@ -1744,7 +1670,9 @@ void GenericCAO::processMessage(const std::string &data) bool sneak_glitch = !readU8(is); bool new_move = !readU8(is); - if (m_is_local_player) { + + if(m_is_local_player) + { LocalPlayer *player = m_env->getLocalPlayer(); player->physics_override_speed = override_speed; player->physics_override_jump = override_jump; @@ -1760,33 +1688,31 @@ void GenericCAO::processMessage(const std::string &data) m_animation_range = v2s32((s32)range.X, (s32)range.Y); m_animation_speed = readF32(is); m_animation_blend = readF32(is); - // these are sent inverted so we get true when the server sends - // nothing + // these are sent inverted so we get true when the server sends nothing m_animation_loop = !readU8(is); updateAnimation(); } else { LocalPlayer *player = m_env->getLocalPlayer(); - if (player->last_animation == NO_ANIM) { + if(player->last_animation == NO_ANIM) + { m_animation_range = v2s32((s32)range.X, (s32)range.Y); m_animation_speed = readF32(is); m_animation_blend = readF32(is); - // these are sent inverted so we get true when the server - // sends nothing + // these are sent inverted so we get true when the server sends nothing m_animation_loop = !readU8(is); } // update animation only if local animations present // and received animation is unknown (except idle animation) bool is_known = false; - for (int i = 1; i < 4; i++) { - if (m_animation_range.Y == player->local_animations[i].Y) + for (int i = 1;i<4;i++) + { + if(m_animation_range.Y == player->local_animations[i].Y) is_known = true; } - if (!is_known || - (player->local_animations[1].Y + - player->local_animations[2] - .Y < - 1)) { - updateAnimation(); + if(!is_known || + (player->local_animations[1].Y + player->local_animations[2].Y < 1)) + { + updateAnimation(); } } } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) { @@ -1821,23 +1747,21 @@ void GenericCAO::processMessage(const std::string &data) if (m_is_local_player) m_env->getLocalPlayer()->hp = m_hp; - if (damage > 0) { - if (m_hp == 0) { + if (damage > 0) + { + if (m_hp == 0) + { // TODO: Execute defined fast response // As there is no definition, make a smoke puff - ClientSimpleObject *simple = createSmokePuff(m_smgr, - m_env, m_position, - v2f(m_prop.visual_size.X, - m_prop.visual_size.Y) * - BS); + ClientSimpleObject *simple = createSmokePuff( + m_smgr, m_env, m_position, + v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS); m_env->addSimpleObject(simple); - } else if (m_reset_textures_timer < 0 && - !m_prop.damage_texture_modifier.empty()) { + } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) { m_reset_textures_timer = 0.05; - if (damage >= 2) + if(damage >= 2) m_reset_textures_timer += 0.05 * damage; - updateTextures(m_current_texture_modifier + - m_prop.damage_texture_modifier); + updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier); } } @@ -1851,7 +1775,8 @@ void GenericCAO::processMessage(const std::string &data) } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) { m_armor_groups.clear(); int armor_groups_size = readU16(is); - for (int i = 0; i < armor_groups_size; i++) { + for(int i=0; igetToolCapabilities(m_client->idef()); PunchDamageResult result = getPunchDamage( - m_armor_groups, toolcap, punchitem, time_from_last_punch); + m_armor_groups, + toolcap, + punchitem, + time_from_last_punch); - if (result.did_punch && result.damage != 0) { - if (result.damage < m_hp) { + if(result.did_punch && result.damage != 0) + { + if(result.damage < m_hp) + { m_hp -= result.damage; } else { m_hp = 0; // TODO: Execute defined fast response // As there is no definition, make a smoke puff - ClientSimpleObject *simple = createSmokePuff(m_smgr, m_env, - m_position, - v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * - BS); + ClientSimpleObject *simple = createSmokePuff( + m_smgr, m_env, m_position, + v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS); m_env->addSimpleObject(simple); } - if (m_reset_textures_timer < 0 && - !m_prop.damage_texture_modifier.empty()) { + if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) { m_reset_textures_timer = 0.05; if (result.damage >= 2) m_reset_textures_timer += 0.05 * result.damage; - updateTextures(m_current_texture_modifier + - m_prop.damage_texture_modifier); + updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier); } } @@ -1911,13 +1838,14 @@ bool GenericCAO::directReportPunch( std::string GenericCAO::debugInfoText() { std::ostringstream os(std::ios::binary); - os << "GenericCAO hp=" << m_hp << "\n"; - os << "armor={"; - for (ItemGroupList::const_iterator i = m_armor_groups.begin(); - i != m_armor_groups.end(); ++i) { - os << i->first << "=" << i->second << ", "; + os<<"GenericCAO hp="<first<<"="<second<<", "; } - os << "}"; + os<<"}"; return os.str(); } diff --git a/src/client/content_cao.h b/src/client/content_cao.h index 9ab5d710d..56ba8e0ec 100644 --- a/src/client/content_cao.h +++ b/src/client/content_cao.h @@ -35,7 +35,8 @@ struct Nametag; SmoothTranslator */ -template struct SmoothTranslator +template +struct SmoothTranslator { T val_old; T val_current; @@ -49,7 +50,7 @@ template struct SmoothTranslator void init(T current); void update(T new_target, bool is_end_position = false, - float update_interval = -1); + float update_interval = -1); void translate(f32 dtime); }; @@ -76,8 +77,7 @@ class GenericCAO : public ClientActiveObject // scene::ISceneManager *m_smgr = nullptr; Client *m_client = nullptr; - aabb3f m_selection_box = - aabb3f(-BS / 3., -BS / 3., -BS / 3., BS / 3., BS / 3., BS / 3.); + aabb3f m_selection_box = aabb3f(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.); scene::IMeshSceneNode *m_meshnode = nullptr; scene::IAnimatedMeshSceneNode *m_animated_meshnode = nullptr; WieldMeshSceneNode *m_wield_meshnode = nullptr; @@ -92,7 +92,7 @@ class GenericCAO : public ClientActiveObject SmoothTranslator pos_translator; SmoothTranslatorWrappedv3f rot_translator; // Spritesheet/animation stuff - v2f m_tx_size = v2f(1, 1); + v2f m_tx_size = v2f(1,1); v2s16 m_tx_basepos; bool m_initial_tx_basepos_set = false; bool m_tx_select_horiz_by_yawpitch = false; @@ -137,13 +137,19 @@ class GenericCAO : public ClientActiveObject ~GenericCAO(); - static ClientActiveObject *create(Client *client, ClientEnvironment *env) + static ClientActiveObject* create(Client *client, ClientEnvironment *env) { return new GenericCAO(client, env); } - inline ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_GENERIC; } - inline const ItemGroupList &getGroups() const { return m_armor_groups; } + inline ActiveObjectType getType() const + { + return ACTIVEOBJECT_TYPE_GENERIC; + } + inline const ItemGroupList &getGroups() const + { + return m_armor_groups; + } void initialize(const std::string &data); void processInitData(const std::string &data); @@ -156,13 +162,22 @@ class GenericCAO : public ClientActiveObject const v3f getPosition() const; - void setPosition(const v3f &pos) { pos_translator.val_current = pos; } + void setPosition(const v3f &pos) + { + pos_translator.val_current = pos; + } inline const v3f &getRotation() const { return m_rotation; } - inline const v3f getAcceleration() const { return m_acceleration; } + inline const v3f getAcceleration() const + { + return m_acceleration; + } - inline const v3f getVelocity() const { return m_velocity; } + inline const v3f getVelocity() const + { + return m_velocity; + } const bool isImmortal(); @@ -190,21 +205,38 @@ class GenericCAO : public ClientActiveObject return &m_matrixnode->getAbsoluteTransformation(); } - inline f32 getStepHeight() const { return m_prop.stepheight; } + inline f32 getStepHeight() const + { + return m_prop.stepheight; + } - inline bool isLocalPlayer() const { return m_is_local_player; } + inline bool isLocalPlayer() const + { + return m_is_local_player; + } - inline std::string getName() const { return m_name; } + inline std::string getName() const + { + return m_name; + } - inline bool isPlayer() const { return m_is_player; } + inline bool isPlayer() const + { + return m_is_player; + } - inline bool isVisible() const { return m_is_visible; } + inline bool isVisible() const + { + return m_is_visible; + } - inline void setVisible(bool toset) { m_is_visible = toset; } + inline void setVisible(bool toset) + { + m_is_visible = toset; + } void setChildrenVisible(bool toset); - void setAttachment(int parent_id, const std::string &bone, v3f position, - v3f rotation); + void setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation); void getAttachment(int *parent_id, std::string *bone, v3f *position, v3f *rotation) const; void clearChildAttachments(); @@ -214,16 +246,17 @@ class GenericCAO : public ClientActiveObject ClientActiveObject *getParent() const; int getParentId() const { return m_attachment_parent_id; } const std::unordered_set &getAttachmentChildIds() const - { - return m_attachment_child_ids; - } + { return m_attachment_child_ids; } void updateAttachments(); void removeFromScene(bool permanent); void addToScene(ITextureSource *tsrc); - inline void expireVisuals() { m_visuals_expired = true; } + inline void expireVisuals() + { + m_visuals_expired = true; + } void updateLight(u32 day_night_ratio); @@ -254,14 +287,20 @@ class GenericCAO : public ClientActiveObject void processMessage(const std::string &data); - bool directReportPunch(v3f dir, const ItemStack *punchitem = NULL, - float time_from_last_punch = 1000000); + bool directReportPunch(v3f dir, const ItemStack *punchitem=NULL, + float time_from_last_punch=1000000); std::string debugInfoText(); - std::string infoText() { return m_prop.infotext; } - + std::string infoText() + { + return m_prop.infotext; + } + float m_waiting_for_reattach; - - ObjectProperties *getProperties() { return &m_prop; } + + ObjectProperties *getProperties() + { + return &m_prop; + } }; diff --git a/src/client/content_cso.cpp b/src/client/content_cso.cpp index f9b02e823..f9641afbe 100644 --- a/src/client/content_cso.cpp +++ b/src/client/content_cso.cpp @@ -24,26 +24,25 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client.h" #include "map.h" -class SmokePuffCSO : public ClientSimpleObject +class SmokePuffCSO: public ClientSimpleObject { float m_age = 0.0f; scene::IBillboardSceneNode *m_spritenode = nullptr; - public: - SmokePuffCSO(scene::ISceneManager *smgr, ClientEnvironment *env, const v3f &pos, - const v2f &size) + SmokePuffCSO(scene::ISceneManager *smgr, + ClientEnvironment *env, const v3f &pos, const v2f &size) { - infostream << "SmokePuffCSO: constructing" << std::endl; - m_spritenode = smgr->addBillboardSceneNode(NULL, v2f(1, 1), pos, -1); - m_spritenode->setMaterialTexture( - 0, env->getGameDef()->tsrc()->getTextureForMesh( - "smoke_puff.png")); + infostream<<"SmokePuffCSO: constructing"<addBillboardSceneNode( + NULL, v2f(1,1), pos, -1); + m_spritenode->setMaterialTexture(0, + env->getGameDef()->tsrc()->getTextureForMesh("smoke_puff.png")); m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false); m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false); - // m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF); + //m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF); m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL); m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true); - m_spritenode->setColor(video::SColor(255, 0, 0, 0)); + m_spritenode->setColor(video::SColor(255,0,0,0)); m_spritenode->setVisible(true); m_spritenode->setSize(size); /* Update brightness */ @@ -51,27 +50,28 @@ class SmokePuffCSO : public ClientSimpleObject bool pos_ok; MapNode n = env->getMap().getNode(floatToInt(pos, BS), &pos_ok); light = pos_ok ? decode_light(n.getLightBlend(env->getDayNightRatio(), - env->getGameDef()->ndef())) - : 64; - video::SColor color(255, light, light, light); + env->getGameDef()->ndef())) + : 64; + video::SColor color(255,light,light,light); m_spritenode->setColor(color); } virtual ~SmokePuffCSO() { - infostream << "SmokePuffCSO: destructing" << std::endl; + infostream<<"SmokePuffCSO: destructing"<remove(); } void step(float dtime) { m_age += dtime; - if (m_age > 1.0) { + if(m_age > 1.0){ m_to_be_removed = true; } } }; -ClientSimpleObject *createSmokePuff( - scene::ISceneManager *smgr, ClientEnvironment *env, v3f pos, v2f size) +ClientSimpleObject* createSmokePuff(scene::ISceneManager *smgr, + ClientEnvironment *env, v3f pos, v2f size) { return new SmokePuffCSO(smgr, env, pos, size); } + diff --git a/src/client/content_cso.h b/src/client/content_cso.h index ccdb00610..cc9213175 100644 --- a/src/client/content_cso.h +++ b/src/client/content_cso.h @@ -22,5 +22,5 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irrlichttypes_extrabloated.h" #include "clientsimpleobject.h" -ClientSimpleObject *createSmokePuff( - scene::ISceneManager *smgr, ClientEnvironment *env, v3f pos, v2f size); +ClientSimpleObject* createSmokePuff(scene::ISceneManager *smgr, + ClientEnvironment *env, v3f pos, v2f size); diff --git a/src/client/content_mapblock.cpp b/src/client/content_mapblock.cpp index c97963ede..3d06584c4 100644 --- a/src/client/content_mapblock.cpp +++ b/src/client/content_mapblock.cpp @@ -45,14 +45,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #define FRAMED_NEIGHBOR_COUNT 18 static const v3s16 light_dirs[8] = { - v3s16(-1, -1, -1), - v3s16(-1, -1, 1), - v3s16(-1, 1, -1), - v3s16(-1, 1, 1), - v3s16(1, -1, -1), - v3s16(1, -1, 1), - v3s16(1, 1, -1), - v3s16(1, 1, 1), + v3s16(-1, -1, -1), + v3s16(-1, -1, 1), + v3s16(-1, 1, -1), + v3s16(-1, 1, 1), + v3s16( 1, -1, -1), + v3s16( 1, -1, 1), + v3s16( 1, 1, -1), + v3s16( 1, 1, 1), }; // Standard index set to make a quad on 4 vertices @@ -62,15 +62,14 @@ const std::string MapblockMeshGenerator::raillike_groupname = "connect_to_railli MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output) { - data = input; + data = input; collector = output; - nodedef = data->m_client->ndef(); + nodedef = data->m_client->ndef(); meshmanip = RenderingEngine::get_scene_manager()->getMeshManipulator(); enable_mesh_cache = g_settings->getBool("enable_mesh_cache") && - !data->m_smooth_lighting; // Mesh cache is not supported with - // smooth lighting + !data->m_smooth_lighting; // Mesh cache is not supported with smooth lighting blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE; } @@ -121,11 +120,11 @@ void MapblockMeshGenerator::getSpecialTile(int index, TileSpec *tile, bool apply top_layer->material_flags |= MATERIAL_FLAG_CRACK; } -void MapblockMeshGenerator::drawQuad( - v3f *coords, const v3s16 &normal, float vertical_tiling) +void MapblockMeshGenerator::drawQuad(v3f *coords, const v3s16 &normal, + float vertical_tiling) { - const v2f tcoords[4] = {v2f(0.0, 0.0), v2f(1.0, 0.0), v2f(1.0, vertical_tiling), - v2f(0.0, vertical_tiling)}; + const v2f tcoords[4] = {v2f(0.0, 0.0), v2f(1.0, 0.0), + v2f(1.0, vertical_tiling), v2f(0.0, vertical_tiling)}; video::S3DVertex vertices[4]; bool shade_face = !f->light_source && (normal != v3s16(0, 0, 0)); v3f normal2(normal.X, normal.Y, normal.Z); @@ -153,8 +152,8 @@ void MapblockMeshGenerator::drawQuad( // should be (2+2)*6=24 values in the list. The order of // the faces in the list is up-down-right-left-back-front // (compatible with ContentFeatures). -void MapblockMeshGenerator::drawCuboid(const aabb3f &box, TileSpec *tiles, int tilecount, - const LightInfo *lights, const f32 *txc) +void MapblockMeshGenerator::drawCuboid(const aabb3f &box, + TileSpec *tiles, int tilecount, const LightInfo *lights, const f32 *txc) { assert(tilecount >= 1 && tilecount <= 6); // pre-condition @@ -177,64 +176,46 @@ void MapblockMeshGenerator::drawCuboid(const aabb3f &box, TileSpec *tiles, int t } video::S3DVertex vertices[24] = { - // top - video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[0], - txc[1]), - video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[2], - txc[1]), - video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[2], - txc[3]), - video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[0], - txc[3]), - // bottom - video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[4], - txc[5]), - video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[6], - txc[5]), - video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[6], - txc[7]), - video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[4], - txc[7]), - // right - video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, colors[2], txc[8], - txc[9]), - video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, colors[2], txc[10], - txc[9]), - video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, colors[2], txc[10], - txc[11]), - video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, colors[2], txc[8], - txc[11]), - // left - video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, colors[3], - txc[12], txc[13]), - video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, colors[3], - txc[14], txc[13]), - video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, colors[3], - txc[14], txc[15]), - video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, colors[3], - txc[12], txc[15]), - // back - video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[16], - txc[17]), - video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[18], - txc[17]), - video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[18], - txc[19]), - video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[16], - txc[19]), - // front - video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, colors[5], - txc[20], txc[21]), - video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, colors[5], - txc[22], txc[21]), - video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, colors[5], - txc[22], txc[23]), - video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, colors[5], - txc[20], txc[23]), + // top + video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[0], txc[1]), + video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[2], txc[1]), + video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[2], txc[3]), + video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[0], txc[3]), + // bottom + video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[4], txc[5]), + video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[6], txc[5]), + video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[6], txc[7]), + video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[4], txc[7]), + // right + video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, colors[2], txc[ 8], txc[9]), + video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, colors[2], txc[10], txc[9]), + video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, colors[2], txc[10], txc[11]), + video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, colors[2], txc[ 8], txc[11]), + // left + video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, colors[3], txc[12], txc[13]), + video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, colors[3], txc[14], txc[13]), + video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, colors[3], txc[14], txc[15]), + video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, colors[3], txc[12], txc[15]), + // back + video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[16], txc[17]), + video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[18], txc[17]), + video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[18], txc[19]), + video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[16], txc[19]), + // front + video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, colors[5], txc[20], txc[21]), + video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, colors[5], txc[22], txc[21]), + video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, colors[5], txc[22], txc[23]), + video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, colors[5], txc[20], txc[23]), }; - static const u8 light_indices[24] = {3, 7, 6, 2, 0, 4, 5, 1, 6, 7, 5, 4, 3, 2, 0, - 1, 7, 3, 1, 5, 2, 6, 4, 0}; + static const u8 light_indices[24] = { + 3, 7, 6, 2, + 0, 4, 5, 1, + 6, 7, 5, 4, + 3, 2, 0, 1, + 7, 3, 1, 5, + 2, 6, 4, 0 + }; for (int face = 0; face < 6; face++) { int tileindex = MYMIN(face, tilecount - 1); @@ -286,9 +267,8 @@ void MapblockMeshGenerator::drawCuboid(const aabb3f &box, TileSpec *tiles, int t for (int j = 0; j < 24; ++j) { video::S3DVertex &vertex = vertices[j]; vertex.Color = encode_light( - lights[light_indices[j]].getPair( - MYMAX(0.0f, vertex.Normal.Y)), - f->light_source); + lights[light_indices[j]].getPair(MYMAX(0.0f, vertex.Normal.Y)), + f->light_source); if (!f->light_source) applyFacesShading(vertex.Color, vertex.Normal); } @@ -307,8 +287,7 @@ void MapblockMeshGenerator::getSmoothLightFrame() for (int k = 0; k < 8; ++k) frame.sunlight[k] = false; for (int k = 0; k < 8; ++k) { - LightPair light(getSmoothLightTransparent( - blockpos_nodes + p, light_dirs[k], data)); + LightPair light(getSmoothLightTransparent(blockpos_nodes + p, light_dirs[k], data)); frame.lightsDay[k] = light.lightDay; frame.lightsNight[k] = light.lightNight; // If there is direct sunlight and no ambient occlusion at some corner, @@ -327,12 +306,9 @@ LightInfo MapblockMeshGenerator::blendLight(const v3f &vertex_pos) // Light levels at (logical) node corners are known. Here, // trilinear interpolation is used to calculate light level // at a given point in the node. - f32 x = core::clamp(vertex_pos.X / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, - 1.0 + SMOOTH_LIGHTING_OVERSIZE); - f32 y = core::clamp(vertex_pos.Y / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, - 1.0 + SMOOTH_LIGHTING_OVERSIZE); - f32 z = core::clamp(vertex_pos.Z / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, - 1.0 + SMOOTH_LIGHTING_OVERSIZE); + f32 x = core::clamp(vertex_pos.X / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); + f32 y = core::clamp(vertex_pos.Y / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); + f32 z = core::clamp(vertex_pos.Z / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); f32 lightDay = 0.0; // daylight f32 lightNight = 0.0; f32 lightBoosted = 0.0; // daylight + direct sunlight, if any @@ -358,12 +334,11 @@ video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos) return encode_light(light.getPair(), f->light_source); } -video::SColor MapblockMeshGenerator::blendLightColor( - const v3f &vertex_pos, const v3f &vertex_normal) +video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos, + const v3f &vertex_normal) { LightInfo light = blendLight(vertex_pos); - video::SColor color = encode_light( - light.getPair(MYMAX(0.0f, vertex_normal.Y)), f->light_source); + video::SColor color = encode_light(light.getPair(MYMAX(0.0f, vertex_normal.Y)), f->light_source); if (!f->light_source) applyFacesShading(color, vertex_normal); return color; @@ -378,19 +353,19 @@ void MapblockMeshGenerator::generateCuboidTextureCoords(const aabb3f &box, f32 * f32 ty2 = (box.MaxEdge.Y / BS) + 0.5; f32 tz2 = (box.MaxEdge.Z / BS) + 0.5; f32 txc[24] = { - tx1, 1 - tz2, tx2, 1 - tz1, // up - tx1, tz1, tx2, tz2, // down - tz1, 1 - ty2, tz2, 1 - ty1, // right - 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1, // left - 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1, // back - tx1, 1 - ty2, tx2, 1 - ty1, // front + tx1, 1 - tz2, tx2, 1 - tz1, // up + tx1, tz1, tx2, tz2, // down + tz1, 1 - ty2, tz2, 1 - ty1, // right + 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1, // left + 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1, // back + tx1, 1 - ty2, tx2, 1 - ty1, // front }; for (int i = 0; i != 24; ++i) coords[i] = txc[i]; } -void MapblockMeshGenerator::drawAutoLightedCuboid( - aabb3f box, const f32 *txc, TileSpec *tiles, int tile_count) +void MapblockMeshGenerator::drawAutoLightedCuboid(aabb3f box, const f32 *txc, + TileSpec *tiles, int tile_count) { bool scale = std::fabs(f->visual_scale - 1.0f) > 1e-3f; f32 texture_coord_buf[24]; @@ -438,16 +413,12 @@ void MapblockMeshGenerator::prepareLiquidNodeDrawing() getSpecialTile(0, &tile_liquid_top); getSpecialTile(1, &tile_liquid); - MapNode ntop = data->m_vmanip.getNodeNoEx( - blockpos_nodes + v3s16(p.X, p.Y + 1, p.Z)); - MapNode nbottom = data->m_vmanip.getNodeNoEx( - blockpos_nodes + v3s16(p.X, p.Y - 1, p.Z)); + MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(p.X, p.Y + 1, p.Z)); + MapNode nbottom = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(p.X, p.Y - 1, p.Z)); c_flowing = f->liquid_alternative_flowing_id; c_source = f->liquid_alternative_source_id; - top_is_same_liquid = (ntop.getContent() == c_flowing) || - (ntop.getContent() == c_source); - draw_liquid_bottom = (nbottom.getContent() != c_flowing) && - (nbottom.getContent() != c_source); + top_is_same_liquid = (ntop.getContent() == c_flowing) || (ntop.getContent() == c_source); + draw_liquid_bottom = (nbottom.getContent() != c_flowing) && (nbottom.getContent() != c_source); if (draw_liquid_bottom) { const ContentFeatures &f2 = nodedef->get(nbottom.getContent()); if (f2.solidness > 1) @@ -461,8 +432,7 @@ void MapblockMeshGenerator::prepareLiquidNodeDrawing() // If this liquid emits light and doesn't contain light, draw // it at what it emits, for an increased effect u8 e = decode_light(f->light_source); - light = LightPair(std::max(e, light.lightDay), - std::max(e, light.lightNight)); + light = LightPair(std::max(e, light.lightDay), std::max(e, light.lightNight)); } else if (nodedef->get(ntop).param_type == CPT_LIGHT) { // Otherwise, use the light of the node on top if possible light = LightPair(getInteriorLight(ntop, 0, nodedef)); @@ -477,47 +447,46 @@ void MapblockMeshGenerator::getLiquidNeighborhood() u8 range = rangelim(nodedef->get(c_flowing).liquid_range, 1, 8); for (int w = -1; w <= 1; w++) - for (int u = -1; u <= 1; u++) { - NeighborData &neighbor = liquid_neighbors[w + 1][u + 1]; - v3s16 p2 = p + v3s16(u, 0, w); - MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); - neighbor.content = n2.getContent(); - neighbor.level = -0.5 * BS; - neighbor.is_same_liquid = false; - neighbor.top_is_same_liquid = false; - - if (neighbor.content == CONTENT_IGNORE) - continue; - - if (neighbor.content == c_source) { - neighbor.is_same_liquid = true; - neighbor.level = 0.5 * BS; - } else if (neighbor.content == c_flowing) { - neighbor.is_same_liquid = true; - u8 liquid_level = (n2.param2 & LIQUID_LEVEL_MASK); - if (liquid_level <= LIQUID_LEVEL_MAX + 1 - range) - liquid_level = 0; - else - liquid_level -= (LIQUID_LEVEL_MAX + 1 - range); - neighbor.level = (-0.5 + (liquid_level + 0.5) / range) * - BS; - } + for (int u = -1; u <= 1; u++) { + NeighborData &neighbor = liquid_neighbors[w + 1][u + 1]; + v3s16 p2 = p + v3s16(u, 0, w); + MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + neighbor.content = n2.getContent(); + neighbor.level = -0.5 * BS; + neighbor.is_same_liquid = false; + neighbor.top_is_same_liquid = false; + + if (neighbor.content == CONTENT_IGNORE) + continue; - // Check node above neighbor. - // NOTE: This doesn't get executed if neighbor - // doesn't exist - p2.Y++; - n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); - if (n2.getContent() == c_source || n2.getContent() == c_flowing) - neighbor.top_is_same_liquid = true; + if (neighbor.content == c_source) { + neighbor.is_same_liquid = true; + neighbor.level = 0.5 * BS; + } else if (neighbor.content == c_flowing) { + neighbor.is_same_liquid = true; + u8 liquid_level = (n2.param2 & LIQUID_LEVEL_MASK); + if (liquid_level <= LIQUID_LEVEL_MAX + 1 - range) + liquid_level = 0; + else + liquid_level -= (LIQUID_LEVEL_MAX + 1 - range); + neighbor.level = (-0.5 + (liquid_level + 0.5) / range) * BS; } + + // Check node above neighbor. + // NOTE: This doesn't get executed if neighbor + // doesn't exist + p2.Y++; + n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + if (n2.getContent() == c_source || n2.getContent() == c_flowing) + neighbor.top_is_same_liquid = true; + } } void MapblockMeshGenerator::calculateCornerLevels() { for (int k = 0; k < 2; k++) - for (int i = 0; i < 2; i++) - corner_levels[k][i] = getCornerLevel(i, k); + for (int i = 0; i < 2; i++) + corner_levels[k][i] = getCornerLevel(i, k); } f32 MapblockMeshGenerator::getCornerLevel(int i, int k) @@ -526,58 +495,59 @@ f32 MapblockMeshGenerator::getCornerLevel(int i, int k) int count = 0; int air_count = 0; for (int dk = 0; dk < 2; dk++) - for (int di = 0; di < 2; di++) { - NeighborData &neighbor_data = liquid_neighbors[k + dk][i + di]; - content_t content = neighbor_data.content; - - // If top is liquid, draw starting from top of node - if (neighbor_data.top_is_same_liquid) - return 0.5 * BS; - - // Source always has the full height - if (content == c_source) - return 0.5 * BS; - - // Flowing liquid has level information - if (content == c_flowing) { - sum += neighbor_data.level; - count++; - } else if (content == CONTENT_AIR) { - air_count++; - if (air_count >= 2) - return -0.5 * BS + 0.2; - } + for (int di = 0; di < 2; di++) { + NeighborData &neighbor_data = liquid_neighbors[k + dk][i + di]; + content_t content = neighbor_data.content; + + // If top is liquid, draw starting from top of node + if (neighbor_data.top_is_same_liquid) + return 0.5 * BS; + + // Source always has the full height + if (content == c_source) + return 0.5 * BS; + + // Flowing liquid has level information + if (content == c_flowing) { + sum += neighbor_data.level; + count++; + } else if (content == CONTENT_AIR) { + air_count++; + if (air_count >= 2) + return -0.5 * BS + 0.2; } + } if (count > 0) return sum / count; return 0; } -namespace -{ -struct LiquidFaceDesc -{ - v3s16 dir; // XZ - v3s16 p[2]; // XZ only; 1 means +, 0 means - -}; -struct UV -{ - int u, v; -}; -static const LiquidFaceDesc liquid_base_faces[4] = { - {v3s16(1, 0, 0), {v3s16(1, 0, 1), v3s16(1, 0, 0)}}, - {v3s16(-1, 0, 0), {v3s16(0, 0, 0), v3s16(0, 0, 1)}}, - {v3s16(0, 0, 1), {v3s16(0, 0, 1), v3s16(1, 0, 1)}}, - {v3s16(0, 0, -1), {v3s16(1, 0, 0), v3s16(0, 0, 0)}}, -}; -static const UV liquid_base_vertices[4] = {{0, 1}, {1, 1}, {1, 0}, {0, 0}}; +namespace { + struct LiquidFaceDesc { + v3s16 dir; // XZ + v3s16 p[2]; // XZ only; 1 means +, 0 means - + }; + struct UV { + int u, v; + }; + static const LiquidFaceDesc liquid_base_faces[4] = { + {v3s16( 1, 0, 0), {v3s16(1, 0, 1), v3s16(1, 0, 0)}}, + {v3s16(-1, 0, 0), {v3s16(0, 0, 0), v3s16(0, 0, 1)}}, + {v3s16( 0, 0, 1), {v3s16(0, 0, 1), v3s16(1, 0, 1)}}, + {v3s16( 0, 0, -1), {v3s16(1, 0, 0), v3s16(0, 0, 0)}}, + }; + static const UV liquid_base_vertices[4] = { + {0, 1}, + {1, 1}, + {1, 0}, + {0, 0} + }; } void MapblockMeshGenerator::drawLiquidSides() { for (const auto &face : liquid_base_faces) { - const NeighborData &neighbor = - liquid_neighbors[face.dir.Z + 1][face.dir.X + 1]; + const NeighborData &neighbor = liquid_neighbors[face.dir.Z + 1][face.dir.X + 1]; // No face between nodes of the same liquid, unless there is node // at the top to which it should be connected. Again, unless the face @@ -604,9 +574,7 @@ void MapblockMeshGenerator::drawLiquidSides() pos.X = (base.X - 0.5f) * BS; pos.Z = (base.Z - 0.5f) * BS; if (vertex.v) { - pos.Y = neighbor.is_same_liquid - ? corner_levels[base.Z][base.X] - : -0.5f * BS; + pos.Y = neighbor.is_same_liquid ? corner_levels[base.Z][base.X] : -0.5f * BS; } else if (top_is_same_liquid) { pos.Y = 0.5f * BS; } else { @@ -617,8 +585,7 @@ void MapblockMeshGenerator::drawLiquidSides() if (data->m_smooth_lighting) color = blendLightColor(pos); pos += origin; - vertices[j] = video::S3DVertex( - pos.X, pos.Y, pos.Z, 0, 0, 0, color, vertex.u, v); + vertices[j] = video::S3DVertex(pos.X, pos.Y, pos.Z, 0, 0, 0, color, vertex.u, v); }; collector->append(tile_liquid, vertices, 4, quad_indices, 6); } @@ -632,14 +599,10 @@ void MapblockMeshGenerator::drawLiquidTop() static const int corner_resolve[4][2] = {{0, 1}, {1, 1}, {1, 0}, {0, 0}}; video::S3DVertex vertices[4] = { - video::S3DVertex(-BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 0, - 1), - video::S3DVertex(BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 1, - 1), - video::S3DVertex(BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 1, - 0), - video::S3DVertex(-BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, - 0, 0), + video::S3DVertex(-BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 0, 1), + video::S3DVertex( BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 1, 1), + video::S3DVertex( BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 1, 0), + video::S3DVertex(-BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 0, 0), }; for (int i = 0; i < 4; i++) { @@ -656,10 +619,10 @@ void MapblockMeshGenerator::drawLiquidTop() // Rotate texture to make animation go in flow direction // Positive if liquid moves towards +Z f32 dz = (corner_levels[0][0] + corner_levels[0][1]) - - (corner_levels[1][0] + corner_levels[1][1]); + (corner_levels[1][0] + corner_levels[1][1]); // Positive if liquid moves towards +X f32 dx = (corner_levels[0][0] + corner_levels[1][0]) - - (corner_levels[0][1] + corner_levels[1][1]); + (corner_levels[0][1] + corner_levels[1][1]); f32 tcoord_angle = atan2(dz, dx) * core::RADTODEG; v2f tcoord_center(0.5, 0.5); v2f tcoord_translate(blockpos_nodes.Z + p.Z, blockpos_nodes.X + p.X); @@ -680,14 +643,10 @@ void MapblockMeshGenerator::drawLiquidTop() void MapblockMeshGenerator::drawLiquidBottom() { video::S3DVertex vertices[4] = { - video::S3DVertex(-BS / 2, -BS / 2, -BS / 2, 0, 0, 0, - color_liquid_top, 0, 0), - video::S3DVertex(BS / 2, -BS / 2, -BS / 2, 0, 0, 0, - color_liquid_top, 1, 0), - video::S3DVertex(BS / 2, -BS / 2, BS / 2, 0, 0, 0, - color_liquid_top, 1, 1), - video::S3DVertex(-BS / 2, -BS / 2, BS / 2, 0, 0, 0, - color_liquid_top, 0, 1), + video::S3DVertex(-BS / 2, -BS / 2, -BS / 2, 0, 0, 0, color_liquid_top, 0, 0), + video::S3DVertex( BS / 2, -BS / 2, -BS / 2, 0, 0, 0, color_liquid_top, 1, 0), + video::S3DVertex( BS / 2, -BS / 2, BS / 2, 0, 0, 0, color_liquid_top, 1, 1), + video::S3DVertex(-BS / 2, -BS / 2, BS / 2, 0, 0, 0, color_liquid_top, 0, 1), }; for (int i = 0; i < 4; i++) { @@ -725,32 +684,26 @@ void MapblockMeshGenerator::drawGlasslikeNode() continue; // Face at Z- v3f vertices[4] = { - v3f(-BS / 2, BS / 2, -BS / 2), - v3f(BS / 2, BS / 2, -BS / 2), - v3f(BS / 2, -BS / 2, -BS / 2), - v3f(-BS / 2, -BS / 2, -BS / 2), + v3f(-BS / 2, BS / 2, -BS / 2), + v3f( BS / 2, BS / 2, -BS / 2), + v3f( BS / 2, -BS / 2, -BS / 2), + v3f(-BS / 2, -BS / 2, -BS / 2), }; for (v3f &vertex : vertices) { switch (face) { - case D6D_ZP: - vertex.rotateXZBy(180); - break; - case D6D_YP: - vertex.rotateYZBy(90); - break; - case D6D_XP: - vertex.rotateXZBy(90); - break; - case D6D_ZN: - vertex.rotateXZBy(0); - break; - case D6D_YN: - vertex.rotateYZBy(-90); - break; - case D6D_XN: - vertex.rotateXZBy(-90); - break; + case D6D_ZP: + vertex.rotateXZBy(180); break; + case D6D_YP: + vertex.rotateYZBy( 90); break; + case D6D_XP: + vertex.rotateXZBy( 90); break; + case D6D_ZN: + vertex.rotateXZBy( 0); break; + case D6D_YN: + vertex.rotateYZBy(-90); break; + case D6D_XN: + vertex.rotateXZBy(-90); break; } } drawQuad(vertices, dir); @@ -780,34 +733,33 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() static const float b = 0.876f * (BS / 2.0f); static const aabb3f frame_edges[FRAMED_EDGE_COUNT] = { - aabb3f(b, b, -a, a, a, a), // y+ - aabb3f(-a, b, -a, -b, a, a), // y+ - aabb3f(b, -a, -a, a, -b, a), // y- - aabb3f(-a, -a, -a, -b, -b, a), // y- - aabb3f(b, -a, b, a, a, a), // x+ - aabb3f(b, -a, -a, a, a, -b), // x+ - aabb3f(-a, -a, b, -b, a, a), // x- - aabb3f(-a, -a, -a, -b, a, -b), // x- - aabb3f(-a, b, b, a, a, a), // z+ - aabb3f(-a, -a, b, a, -b, a), // z+ - aabb3f(-a, -a, -a, a, -b, -b), // z- - aabb3f(-a, b, -a, a, a, -b), // z- + aabb3f( b, b, -a, a, a, a), // y+ + aabb3f(-a, b, -a, -b, a, a), // y+ + aabb3f( b, -a, -a, a, -b, a), // y- + aabb3f(-a, -a, -a, -b, -b, a), // y- + aabb3f( b, -a, b, a, a, a), // x+ + aabb3f( b, -a, -a, a, a, -b), // x+ + aabb3f(-a, -a, b, -b, a, a), // x- + aabb3f(-a, -a, -a, -b, a, -b), // x- + aabb3f(-a, b, b, a, a, a), // z+ + aabb3f(-a, -a, b, a, -b, a), // z+ + aabb3f(-a, -a, -a, a, -b, -b), // z- + aabb3f(-a, b, -a, a, a, -b), // z- }; // tables of neighbour (connect if same type and merge allowed), // checked with g_26dirs // 1 = connect, 0 = face visible - bool nb[FRAMED_NEIGHBOR_COUNT] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + bool nb[FRAMED_NEIGHBOR_COUNT] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // 1 = check - static const bool check_nb_vertical[FRAMED_NEIGHBOR_COUNT] = { - 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - static const bool check_nb_horizontal[FRAMED_NEIGHBOR_COUNT] = { - 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0}; - static const bool check_nb_all[FRAMED_NEIGHBOR_COUNT] = { - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + static const bool check_nb_vertical [FRAMED_NEIGHBOR_COUNT] = + {0,1,0,0,1,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; + static const bool check_nb_horizontal [FRAMED_NEIGHBOR_COUNT] = + {1,0,1,1,0,1, 0,0,0,0, 1,1,1,1, 0,0,0,0}; + static const bool check_nb_all [FRAMED_NEIGHBOR_COUNT] = + {1,1,1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1}; const bool *check_nb = check_nb_all; // neighbours checks for frames visibility @@ -831,29 +783,18 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() // edge visibility static const u8 nb_triplet[FRAMED_EDGE_COUNT][3] = { - {1, 2, 7}, - {1, 5, 6}, - {4, 2, 15}, - {4, 5, 14}, - {2, 0, 11}, - {2, 3, 13}, - {5, 0, 10}, - {5, 3, 12}, - {0, 1, 8}, - {0, 4, 16}, - {3, 4, 17}, - {3, 1, 9}, + {1, 2, 7}, {1, 5, 6}, {4, 2, 15}, {4, 5, 14}, + {2, 0, 11}, {2, 3, 13}, {5, 0, 10}, {5, 3, 12}, + {0, 1, 8}, {0, 4, 16}, {3, 4, 17}, {3, 1, 9}, }; tile = tiles[1]; for (int edge = 0; edge < FRAMED_EDGE_COUNT; edge++) { bool edge_invisible; if (nb[nb_triplet[edge][2]]) - edge_invisible = - nb[nb_triplet[edge][0]] & nb[nb_triplet[edge][1]]; + edge_invisible = nb[nb_triplet[edge][0]] & nb[nb_triplet[edge][1]]; else - edge_invisible = - nb[nb_triplet[edge][0]] ^ nb[nb_triplet[edge][1]]; + edge_invisible = nb[nb_triplet[edge][0]] ^ nb[nb_triplet[edge][1]]; if (edge_invisible) continue; drawAutoLightedCuboid(frame_edges[edge]); @@ -866,32 +807,26 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() tile = glass_tiles[face]; // Face at Z- v3f vertices[4] = { - v3f(-a, a, -g), - v3f(a, a, -g), - v3f(a, -a, -g), - v3f(-a, -a, -g), + v3f(-a, a, -g), + v3f( a, a, -g), + v3f( a, -a, -g), + v3f(-a, -a, -g), }; for (v3f &vertex : vertices) { switch (face) { - case D6D_ZP: - vertex.rotateXZBy(180); - break; - case D6D_YP: - vertex.rotateYZBy(90); - break; - case D6D_XP: - vertex.rotateXZBy(90); - break; - case D6D_ZN: - vertex.rotateXZBy(0); - break; - case D6D_YN: - vertex.rotateYZBy(-90); - break; - case D6D_XN: - vertex.rotateXZBy(-90); - break; + case D6D_ZP: + vertex.rotateXZBy(180); break; + case D6D_YP: + vertex.rotateYZBy( 90); break; + case D6D_XP: + vertex.rotateXZBy( 90); break; + case D6D_ZN: + vertex.rotateXZBy( 0); break; + case D6D_YN: + vertex.rotateYZBy(-90); break; + case D6D_XN: + vertex.rotateXZBy(-90); break; } } v3s16 dir = g_6dirs[face]; @@ -906,9 +841,12 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() // convert it to -0.5 .. 0.5 float vlev = (param2 / 63.0f) * 2.0f - 1.0f; getSpecialTile(0, &tile); - drawAutoLightedCuboid(aabb3f(-(nb[5] ? g : b), -(nb[4] ? g : b), - -(nb[3] ? g : b), (nb[2] ? g : b), (nb[1] ? g : b) * vlev, - (nb[0] ? g : b))); + drawAutoLightedCuboid(aabb3f(-(nb[5] ? g : b), + -(nb[4] ? g : b), + -(nb[3] ? g : b), + (nb[2] ? g : b), + (nb[1] ? g : b) * vlev, + (nb[0] ? g : b))); } } @@ -924,49 +862,44 @@ void MapblockMeshGenerator::drawTorchlikeNode() u8 wall = n.getWallMounted(nodedef); u8 tileindex = 0; switch (wall) { - case DWM_YP: - tileindex = 1; - break; // ceiling - case DWM_YN: - tileindex = 0; - break; // floor - default: - tileindex = 2; // side (or invalid—should we care?) + case DWM_YP: tileindex = 1; break; // ceiling + case DWM_YN: tileindex = 0; break; // floor + default: tileindex = 2; // side (or invalid—should we care?) } useTile(tileindex, MATERIAL_FLAG_CRACK_OVERLAY, MATERIAL_FLAG_BACKFACE_CULLING); float size = BS / 2 * f->visual_scale; v3f vertices[4] = { - v3f(-size, size, 0), - v3f(size, size, 0), - v3f(size, -size, 0), - v3f(-size, -size, 0), + v3f(-size, size, 0), + v3f( size, size, 0), + v3f( size, -size, 0), + v3f(-size, -size, 0), }; for (v3f &vertex : vertices) { switch (wall) { - case DWM_YP: - vertex.Y += -size + BS / 2; - vertex.rotateXZBy(-45); - break; - case DWM_YN: - vertex.Y += size - BS / 2; - vertex.rotateXZBy(45); - break; - case DWM_XP: - vertex.X += -size + BS / 2; - break; - case DWM_XN: - vertex.X += -size + BS / 2; - vertex.rotateXZBy(180); - break; - case DWM_ZP: - vertex.X += -size + BS / 2; - vertex.rotateXZBy(90); - break; - case DWM_ZN: - vertex.X += -size + BS / 2; - vertex.rotateXZBy(-90); + case DWM_YP: + vertex.Y += -size + BS/2; + vertex.rotateXZBy(-45); + break; + case DWM_YN: + vertex.Y += size - BS/2; + vertex.rotateXZBy(45); + break; + case DWM_XP: + vertex.X += -size + BS/2; + break; + case DWM_XN: + vertex.X += -size + BS/2; + vertex.rotateXZBy(180); + break; + case DWM_ZP: + vertex.X += -size + BS/2; + vertex.rotateXZBy(90); + break; + case DWM_ZN: + vertex.X += -size + BS/2; + vertex.rotateXZBy(-90); } } drawQuad(vertices); @@ -980,45 +913,39 @@ void MapblockMeshGenerator::drawSignlikeNode() float size = BS / 2 * f->visual_scale; // Wall at X+ of node v3f vertices[4] = { - v3f(BS / 2 - offset, size, size), - v3f(BS / 2 - offset, size, -size), - v3f(BS / 2 - offset, -size, -size), - v3f(BS / 2 - offset, -size, size), + v3f(BS / 2 - offset, size, size), + v3f(BS / 2 - offset, size, -size), + v3f(BS / 2 - offset, -size, -size), + v3f(BS / 2 - offset, -size, size), }; for (v3f &vertex : vertices) { switch (wall) { - case DWM_YP: - vertex.rotateXYBy(90); - break; - case DWM_YN: - vertex.rotateXYBy(-90); - break; - case DWM_XP: - vertex.rotateXZBy(0); - break; - case DWM_XN: - vertex.rotateXZBy(180); - break; - case DWM_ZP: - vertex.rotateXZBy(90); - break; - case DWM_ZN: - vertex.rotateXZBy(-90); - break; + case DWM_YP: + vertex.rotateXYBy( 90); break; + case DWM_YN: + vertex.rotateXYBy(-90); break; + case DWM_XP: + vertex.rotateXZBy( 0); break; + case DWM_XN: + vertex.rotateXZBy(180); break; + case DWM_ZP: + vertex.rotateXZBy( 90); break; + case DWM_ZN: + vertex.rotateXZBy(-90); break; } } drawQuad(vertices); } -void MapblockMeshGenerator::drawPlantlikeQuad( - float rotation, float quad_offset, bool offset_top_only) +void MapblockMeshGenerator::drawPlantlikeQuad(float rotation, float quad_offset, + bool offset_top_only) { v3f vertices[4] = { - v3f(-scale, -BS / 2 + 2.0 * scale * plant_height, 0), - v3f(scale, -BS / 2 + 2.0 * scale * plant_height, 0), - v3f(scale, -BS / 2, 0), - v3f(-scale, -BS / 2, 0), + v3f(-scale, -BS / 2 + 2.0 * scale * plant_height, 0), + v3f( scale, -BS / 2 + 2.0 * scale * plant_height, 0), + v3f( scale, -BS / 2, 0), + v3f(-scale, -BS / 2, 0), }; if (random_offset_Y) { PseudoRandom yrng(face_num++ | p.X << 16 | p.Z << 8 | p.Y << 24); @@ -1089,15 +1016,15 @@ void MapblockMeshGenerator::drawPlantlike() break; case PLANT_STYLE_HASH: - drawPlantlikeQuad(1, BS / 4); - drawPlantlikeQuad(91, BS / 4); + drawPlantlikeQuad( 1, BS / 4); + drawPlantlikeQuad( 91, BS / 4); drawPlantlikeQuad(181, BS / 4); drawPlantlikeQuad(271, BS / 4); break; case PLANT_STYLE_HASH2: - drawPlantlikeQuad(1, -BS / 2, true); - drawPlantlikeQuad(91, -BS / 2, true); + drawPlantlikeQuad( 1, -BS / 2, true); + drawPlantlikeQuad( 91, -BS / 2, true); drawPlantlikeQuad(181, -BS / 2, true); drawPlantlikeQuad(271, -BS / 2, true); break; @@ -1125,14 +1052,14 @@ void MapblockMeshGenerator::drawPlantlikeRootedNode() p.Y--; } -void MapblockMeshGenerator::drawFirelikeQuad( - float rotation, float opening_angle, float offset_h, float offset_v) +void MapblockMeshGenerator::drawFirelikeQuad(float rotation, float opening_angle, + float offset_h, float offset_v) { v3f vertices[4] = { - v3f(-scale, -BS / 2 + scale * 2, 0), - v3f(scale, -BS / 2 + scale * 2, 0), - v3f(scale, -BS / 2, 0), - v3f(-scale, -BS / 2, 0), + v3f(-scale, -BS / 2 + scale * 2, 0), + v3f( scale, -BS / 2 + scale * 2, 0), + v3f( scale, -BS / 2, 0), + v3f(-scale, -BS / 2, 0), }; for (v3f &vertex : vertices) { @@ -1204,37 +1131,19 @@ void MapblockMeshGenerator::drawFencelikeNode() tile_rot.rotation = 1; static const f32 post_rad = BS / 8; - static const f32 bar_rad = BS / 16; - static const f32 bar_len = BS / 2 - post_rad; + static const f32 bar_rad = BS / 16; + static const f32 bar_len = BS / 2 - post_rad; // The post - always present - static const aabb3f post( - -post_rad, -BS / 2, -post_rad, post_rad, BS / 2, post_rad); + static const aabb3f post(-post_rad, -BS / 2, -post_rad, + post_rad, BS / 2, post_rad); static const f32 postuv[24] = { - 0.375, - 0.375, - 0.625, - 0.625, - 0.375, - 0.375, - 0.625, - 0.625, - 0.000, - 0.000, - 0.250, - 1.000, - 0.250, - 0.000, - 0.500, - 1.000, - 0.500, - 0.000, - 0.750, - 1.000, - 0.750, - 0.000, - 1.000, - 1.000, + 0.375, 0.375, 0.625, 0.625, + 0.375, 0.375, 0.625, 0.625, + 0.000, 0.000, 0.250, 1.000, + 0.250, 0.000, 0.500, 1.000, + 0.500, 0.000, 0.750, 1.000, + 0.750, 0.000, 1.000, 1.000, }; tile = tile_rot; drawAutoLightedCuboid(post, postuv); @@ -1247,35 +1156,17 @@ void MapblockMeshGenerator::drawFencelikeNode() MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); const ContentFeatures *f2 = &nodedef->get(n2); if (f2->drawtype == NDT_FENCELIKE) { - static const aabb3f bar_x1(BS / 2 - bar_len, BS / 4 - bar_rad, -bar_rad, - BS / 2 + bar_len, BS / 4 + bar_rad, bar_rad); + static const aabb3f bar_x1(BS / 2 - bar_len, BS / 4 - bar_rad, -bar_rad, + BS / 2 + bar_len, BS / 4 + bar_rad, bar_rad); static const aabb3f bar_x2(BS / 2 - bar_len, -BS / 4 - bar_rad, -bar_rad, - BS / 2 + bar_len, -BS / 4 + bar_rad, bar_rad); + BS / 2 + bar_len, -BS / 4 + bar_rad, bar_rad); static const f32 xrailuv[24] = { - 0.000, - 0.125, - 1.000, - 0.250, - 0.000, - 0.250, - 1.000, - 0.375, - 0.375, - 0.375, - 0.500, - 0.500, - 0.625, - 0.625, - 0.750, - 0.750, - 0.000, - 0.500, - 1.000, - 0.625, - 0.000, - 0.875, - 1.000, - 1.000, + 0.000, 0.125, 1.000, 0.250, + 0.000, 0.250, 1.000, 0.375, + 0.375, 0.375, 0.500, 0.500, + 0.625, 0.625, 0.750, 0.750, + 0.000, 0.500, 1.000, 0.625, + 0.000, 0.875, 1.000, 1.000, }; drawAutoLightedCuboid(bar_x1, xrailuv); drawAutoLightedCuboid(bar_x2, xrailuv); @@ -1287,35 +1178,17 @@ void MapblockMeshGenerator::drawFencelikeNode() n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); f2 = &nodedef->get(n2); if (f2->drawtype == NDT_FENCELIKE) { - static const aabb3f bar_z1(-bar_rad, BS / 4 - bar_rad, BS / 2 - bar_len, - bar_rad, BS / 4 + bar_rad, BS / 2 + bar_len); + static const aabb3f bar_z1(-bar_rad, BS / 4 - bar_rad, BS / 2 - bar_len, + bar_rad, BS / 4 + bar_rad, BS / 2 + bar_len); static const aabb3f bar_z2(-bar_rad, -BS / 4 - bar_rad, BS / 2 - bar_len, - bar_rad, -BS / 4 + bar_rad, BS / 2 + bar_len); + bar_rad, -BS / 4 + bar_rad, BS / 2 + bar_len); static const f32 zrailuv[24] = { - 0.1875, - 0.0625, - 0.3125, - 0.3125, // cannot rotate; stretch - 0.2500, - 0.0625, - 0.3750, - 0.3125, // for wood texture instead - 0.0000, - 0.5625, - 1.0000, - 0.6875, - 0.0000, - 0.3750, - 1.0000, - 0.5000, - 0.3750, - 0.3750, - 0.5000, - 0.5000, - 0.6250, - 0.6250, - 0.7500, - 0.7500, + 0.1875, 0.0625, 0.3125, 0.3125, // cannot rotate; stretch + 0.2500, 0.0625, 0.3750, 0.3125, // for wood texture instead + 0.0000, 0.5625, 1.0000, 0.6875, + 0.0000, 0.3750, 1.0000, 0.5000, + 0.3750, 0.3750, 0.5000, 0.5000, + 0.6250, 0.6250, 0.7500, 0.7500, }; drawAutoLightedCuboid(bar_z1, zrailuv); drawAutoLightedCuboid(bar_z2, zrailuv); @@ -1329,51 +1202,48 @@ bool MapblockMeshGenerator::isSameRail(v3s16 dir) return true; const ContentFeatures &def2 = nodedef->get(node2); return ((def2.drawtype == NDT_RAILLIKE) && - (def2.getGroup(raillike_groupname) == raillike_group)); + (def2.getGroup(raillike_groupname) == raillike_group)); } -namespace -{ -static const v3s16 rail_direction[4] = { - v3s16(0, 0, 1), - v3s16(0, 0, -1), - v3s16(-1, 0, 0), - v3s16(1, 0, 0), -}; -static const int rail_slope_angle[4] = {0, 180, 90, -90}; +namespace { + static const v3s16 rail_direction[4] = { + v3s16( 0, 0, 1), + v3s16( 0, 0, -1), + v3s16(-1, 0, 0), + v3s16( 1, 0, 0), + }; + static const int rail_slope_angle[4] = {0, 180, 90, -90}; -enum RailTile -{ - straight, - curved, - junction, - cross, -}; -struct RailDesc -{ - int tile_index; - int angle; -}; -static const RailDesc rail_kinds[16] = { - // +x -x -z +z - //------------- - {straight, 0}, // . . . . - {straight, 0}, // . . . +Z - {straight, 0}, // . . -Z . - {straight, 0}, // . . -Z +Z - {straight, 90}, // . -X . . - {curved, 180}, // . -X . +Z - {curved, 270}, // . -X -Z . + enum RailTile { + straight, + curved, + junction, + cross, + }; + struct RailDesc { + int tile_index; + int angle; + }; + static const RailDesc rail_kinds[16] = { + // +x -x -z +z + //------------- + {straight, 0}, // . . . . + {straight, 0}, // . . . +Z + {straight, 0}, // . . -Z . + {straight, 0}, // . . -Z +Z + {straight, 90}, // . -X . . + { curved, 180}, // . -X . +Z + { curved, 270}, // . -X -Z . {junction, 180}, // . -X -Z +Z - {straight, 90}, // +X . . . - {curved, 90}, // +X . . +Z - {curved, 0}, // +X . -Z . - {junction, 0}, // +X . -Z +Z - {straight, 90}, // +X -X . . - {junction, 90}, // +X -X . +Z + {straight, 90}, // +X . . . + { curved, 90}, // +X . . +Z + { curved, 0}, // +X . -Z . + {junction, 0}, // +X . -Z +Z + {straight, 90}, // +X -X . . + {junction, 90}, // +X -X . +Z {junction, 270}, // +X -X -Z . - {cross, 0}, // +X -X -Z +Z -}; + { cross, 0}, // +X -X -Z +Z + }; } void MapblockMeshGenerator::drawRaillikeNode() @@ -1390,7 +1260,8 @@ void MapblockMeshGenerator::drawRaillikeNode() sloped = true; angle = rail_slope_angle[dir]; } - if (rail_above || isSameRail(rail_direction[dir]) || + if (rail_above || + isSameRail(rail_direction[dir]) || isSameRail(rail_direction[dir] + v3s16(0, -1, 0))) code |= 1 << dir; } @@ -1405,13 +1276,13 @@ void MapblockMeshGenerator::drawRaillikeNode() useTile(tile_index, MATERIAL_FLAG_CRACK_OVERLAY, MATERIAL_FLAG_BACKFACE_CULLING); static const float offset = BS / 64; - static const float size = BS / 2; + static const float size = BS / 2; float y2 = sloped ? size : -size; v3f vertices[4] = { - v3f(-size, y2 + offset, size), - v3f(size, y2 + offset, size), - v3f(size, -size + offset, -size), - v3f(-size, -size + offset, -size), + v3f(-size, y2 + offset, size), + v3f( size, y2 + offset, size), + v3f( size, -size + offset, -size), + v3f(-size, -size + offset, -size), }; if (angle) for (v3f &vertex : vertices) @@ -1419,20 +1290,25 @@ void MapblockMeshGenerator::drawRaillikeNode() drawQuad(vertices); } -namespace -{ -static const v3s16 nodebox_tile_dirs[6] = {v3s16(0, 1, 0), v3s16(0, -1, 0), - v3s16(1, 0, 0), v3s16(-1, 0, 0), v3s16(0, 0, 1), v3s16(0, 0, -1)}; - -// we have this order for some reason... -static const v3s16 nodebox_connection_dirs[6] = { - v3s16(0, 1, 0), // top - v3s16(0, -1, 0), // bottom - v3s16(0, 0, -1), // front - v3s16(-1, 0, 0), // left - v3s16(0, 0, 1), // back - v3s16(1, 0, 0), // right -}; +namespace { + static const v3s16 nodebox_tile_dirs[6] = { + v3s16(0, 1, 0), + v3s16(0, -1, 0), + v3s16(1, 0, 0), + v3s16(-1, 0, 0), + v3s16(0, 0, 1), + v3s16(0, 0, -1) + }; + + // we have this order for some reason... + static const v3s16 nodebox_connection_dirs[6] = { + v3s16( 0, 1, 0), // top + v3s16( 0, -1, 0), // bottom + v3s16( 0, 0, -1), // front + v3s16(-1, 0, 0), // left + v3s16( 0, 0, 1), // back + v3s16( 1, 0, 0), // right + }; } void MapblockMeshGenerator::drawNodeboxNode() @@ -1464,10 +1340,11 @@ void MapblockMeshGenerator::drawNodeboxNode() void MapblockMeshGenerator::drawMeshNode() { u8 facedir = 0; - scene::IMesh *mesh; + scene::IMesh* mesh; bool private_mesh; // as a grab/drop pair is not thread-safe - if (f->param_type_2 == CPT2_FACEDIR || f->param_type_2 == CPT2_COLORED_FACEDIR) { + if (f->param_type_2 == CPT2_FACEDIR || + f->param_type_2 == CPT2_COLORED_FACEDIR) { facedir = n.getFaceDir(nodedef); } else if (f->param_type_2 == CPT2_WALLMOUNTED || f->param_type_2 == CPT2_COLORED_WALLMOUNTED) { @@ -1507,14 +1384,14 @@ void MapblockMeshGenerator::drawMeshNode() vertex.Color = blendLightColor(vertex.Pos, vertex.Normal); vertex.Pos += origin; } - collector->append(tile, vertices, vertex_count, buf->getIndices(), - buf->getIndexCount()); + collector->append(tile, vertices, vertex_count, + buf->getIndices(), buf->getIndexCount()); } else { // Don't modify the mesh, it may not be private here. // Instead, let the collector process colors, etc. - collector->append(tile, vertices, vertex_count, buf->getIndices(), - buf->getIndexCount(), origin, color, - f->light_source); + collector->append(tile, vertices, vertex_count, + buf->getIndices(), buf->getIndexCount(), origin, + color, f->light_source); } } if (private_mesh) @@ -1532,12 +1409,12 @@ void MapblockMeshGenerator::drawNode() { // skip some drawtypes early switch (f->drawtype) { - case NDT_NORMAL: // Drawn by MapBlockMesh - case NDT_AIRLIKE: // Not drawn at all - case NDT_LIQUID: // Drawn by MapBlockMesh - return; - default: - break; + case NDT_NORMAL: // Drawn by MapBlockMesh + case NDT_AIRLIKE: // Not drawn at all + case NDT_LIQUID: // Drawn by MapBlockMesh + return; + default: + break; } origin = intToFloat(p, BS); if (data->m_smooth_lighting) @@ -1545,48 +1422,20 @@ void MapblockMeshGenerator::drawNode() else light = LightPair(getInteriorLight(n, 1, nodedef)); switch (f->drawtype) { - case NDT_FLOWINGLIQUID: - drawLiquidNode(); - break; - case NDT_GLASSLIKE: - drawGlasslikeNode(); - break; - case NDT_GLASSLIKE_FRAMED: - drawGlasslikeFramedNode(); - break; - case NDT_ALLFACES: - drawAllfacesNode(); - break; - case NDT_TORCHLIKE: - drawTorchlikeNode(); - break; - case NDT_SIGNLIKE: - drawSignlikeNode(); - break; - case NDT_PLANTLIKE: - drawPlantlikeNode(); - break; - case NDT_PLANTLIKE_ROOTED: - drawPlantlikeRootedNode(); - break; - case NDT_FIRELIKE: - drawFirelikeNode(); - break; - case NDT_FENCELIKE: - drawFencelikeNode(); - break; - case NDT_RAILLIKE: - drawRaillikeNode(); - break; - case NDT_NODEBOX: - drawNodeboxNode(); - break; - case NDT_MESH: - drawMeshNode(); - break; - default: - errorUnknownDrawtype(); - break; + case NDT_FLOWINGLIQUID: drawLiquidNode(); break; + case NDT_GLASSLIKE: drawGlasslikeNode(); break; + case NDT_GLASSLIKE_FRAMED: drawGlasslikeFramedNode(); break; + case NDT_ALLFACES: drawAllfacesNode(); break; + case NDT_TORCHLIKE: drawTorchlikeNode(); break; + case NDT_SIGNLIKE: drawSignlikeNode(); break; + case NDT_PLANTLIKE: drawPlantlikeNode(); break; + case NDT_PLANTLIKE_ROOTED: drawPlantlikeRootedNode(); break; + case NDT_FIRELIKE: drawFirelikeNode(); break; + case NDT_FENCELIKE: drawFencelikeNode(); break; + case NDT_RAILLIKE: drawRaillikeNode(); break; + case NDT_NODEBOX: drawNodeboxNode(); break; + case NDT_MESH: drawMeshNode(); break; + default: errorUnknownDrawtype(); break; } } @@ -1597,12 +1446,12 @@ void MapblockMeshGenerator::drawNode() void MapblockMeshGenerator::generate() { for (p.Z = 0; p.Z < MAP_BLOCKSIZE; p.Z++) - for (p.Y = 0; p.Y < MAP_BLOCKSIZE; p.Y++) - for (p.X = 0; p.X < MAP_BLOCKSIZE; p.X++) { - n = data->m_vmanip.getNodeNoEx(blockpos_nodes + p); - f = &nodedef->get(n); - drawNode(); - } + for (p.Y = 0; p.Y < MAP_BLOCKSIZE; p.Y++) + for (p.X = 0; p.X < MAP_BLOCKSIZE; p.X++) { + n = data->m_vmanip.getNodeNoEx(blockpos_nodes + p); + f = &nodedef->get(n); + drawNode(); + } } void MapblockMeshGenerator::renderSingle(content_t node) diff --git a/src/client/content_mapblock.h b/src/client/content_mapblock.h index 73ff11333..97947cdbe 100644 --- a/src/client/content_mapblock.h +++ b/src/client/content_mapblock.h @@ -25,8 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MeshMakeData; struct MeshCollector; -struct LightPair -{ +struct LightPair { u8 lightDay; u8 lightNight; @@ -34,29 +33,26 @@ struct LightPair explicit LightPair(u16 value) : lightDay(value & 0xff), lightNight(value >> 8) {} LightPair(u8 valueA, u8 valueB) : lightDay(valueA), lightNight(valueB) {} LightPair(float valueA, float valueB) : - lightDay(core::clamp(core::round32(valueA), 0, 255)), - lightNight(core::clamp(core::round32(valueB), 0, 255)) - { - } + lightDay(core::clamp(core::round32(valueA), 0, 255)), + lightNight(core::clamp(core::round32(valueB), 0, 255)) {} operator u16() const { return lightDay | lightNight << 8; } }; -struct LightInfo -{ +struct LightInfo { float light_day; float light_night; float light_boosted; LightPair getPair(float sunlight_boost = 0.0) const { - return LightPair((1 - sunlight_boost) * light_day + - sunlight_boost * light_boosted, - light_night); + return LightPair( + (1 - sunlight_boost) * light_day + + sunlight_boost * light_boosted, + light_night); } }; -struct LightFrame -{ +struct LightFrame { f32 lightsDay[8]; f32 lightsNight[8]; bool sunlight[8]; @@ -71,10 +67,10 @@ class MapblockMeshGenerator const NodeDefManager *nodedef; scene::IMeshManipulator *meshmanip; - // options +// options bool enable_mesh_cache; - // current node +// current node v3s16 blockpos_nodes; v3s16 p; v3f origin; @@ -86,30 +82,30 @@ class MapblockMeshGenerator TileSpec tile; float scale; - // lighting +// lighting void getSmoothLightFrame(); LightInfo blendLight(const v3f &vertex_pos); video::SColor blendLightColor(const v3f &vertex_pos); video::SColor blendLightColor(const v3f &vertex_pos, const v3f &vertex_normal); void useTile(int index = 0, u8 set_flags = MATERIAL_FLAG_CRACK_OVERLAY, - u8 reset_flags = 0, bool special = false); + u8 reset_flags = 0, bool special = false); void getTile(int index, TileSpec *tile); void getTile(v3s16 direction, TileSpec *tile); void getSpecialTile(int index, TileSpec *tile, bool apply_crack = false); - // face drawing +// face drawing void drawQuad(v3f *vertices, const v3s16 &normal = v3s16(0, 0, 0), - float vertical_tiling = 1.0); + float vertical_tiling = 1.0); - // cuboid drawing! +// cuboid drawing! void drawCuboid(const aabb3f &box, TileSpec *tiles, int tilecount, - const LightInfo *lights, const f32 *txc); + const LightInfo *lights , const f32 *txc); void generateCuboidTextureCoords(aabb3f const &box, f32 *coords); void drawAutoLightedCuboid(aabb3f box, const f32 *txc = NULL, - TileSpec *tiles = NULL, int tile_count = 0); + TileSpec *tiles = NULL, int tile_count = 0); - // liquid-specific +// liquid-specific bool top_is_same_liquid; bool draw_liquid_bottom; TileSpec tile_liquid; @@ -117,8 +113,7 @@ class MapblockMeshGenerator content_t c_flowing; content_t c_source; video::SColor color_liquid_top; - struct NeighborData - { + struct NeighborData { f32 level; content_t content; bool is_same_liquid; @@ -135,13 +130,13 @@ class MapblockMeshGenerator void drawLiquidTop(); void drawLiquidBottom(); - // raillike-specific +// raillike-specific // name of the group that enables connecting to raillike nodes of different kind static const std::string raillike_groupname; int raillike_group; bool isSameRail(v3s16 dir); - // plantlike-specific +// plantlike-specific PlantlikeStyle draw_style; v3f offset; int rotate_degree; @@ -150,14 +145,14 @@ class MapblockMeshGenerator float plant_height; void drawPlantlikeQuad(float rotation, float quad_offset = 0, - bool offset_top_only = false); + bool offset_top_only = false); void drawPlantlike(); - // firelike-specific - void drawFirelikeQuad(float rotation, float opening_angle, float offset_h, - float offset_v = 0.0); +// firelike-specific + void drawFirelikeQuad(float rotation, float opening_angle, + float offset_h, float offset_v = 0.0); - // drawtypes +// drawtypes void drawLiquidNode(); void drawGlasslikeNode(); void drawGlasslikeFramedNode(); @@ -172,7 +167,7 @@ class MapblockMeshGenerator void drawNodeboxNode(); void drawMeshNode(); - // common +// common void errorUnknownDrawtype(); void drawNode(); diff --git a/src/client/filecache.cpp b/src/client/filecache.cpp index 0c8f06198..46bbe4059 100644 --- a/src/client/filecache.cpp +++ b/src/client/filecache.cpp @@ -32,28 +32,28 @@ bool FileCache::loadByPath(const std::string &path, std::ostream &os) { std::ifstream fis(path.c_str(), std::ios_base::binary); - if (!fis.good()) { - verbosestream << "FileCache: File not found in cache: " << path - << std::endl; + if(!fis.good()){ + verbosestream<<"FileCache: File not found in cache: " + <getSkin() != NULL); // pre-condition readSettings(); if (m_currentMode == FM_Standard) { - m_settings->registerChangedCallback( - "font_size", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_bold", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_italic", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_path", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_path_bold", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_path_italic", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_path_bolditalic", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_shadow", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "font_shadow_alpha", font_setting_changed, NULL); - } else if (m_currentMode == FM_Fallback) { - m_settings->registerChangedCallback( - "fallback_font_size", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "fallback_font_path", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "fallback_font_shadow", font_setting_changed, NULL); - m_settings->registerChangedCallback( - "fallback_font_shadow_alpha", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_size", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_bold", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_italic", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_path", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL); + m_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL); + } + else if (m_currentMode == FM_Fallback) { + m_settings->registerChangedCallback("fallback_font_size", font_setting_changed, NULL); + m_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL); + m_settings->registerChangedCallback("fallback_font_shadow", font_setting_changed, NULL); + m_settings->registerChangedCallback("fallback_font_shadow_alpha", font_setting_changed, NULL); } m_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL); @@ -118,9 +107,9 @@ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec) 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; + 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; @@ -175,6 +164,7 @@ unsigned int FontEngine::getTextWidth(const std::wstring &text, const FontSpec & return font->getDimension(text.c_str()).Width; } + /** get line height for a specific font (including empty room between lines) */ unsigned int FontEngine::getLineHeight(const FontSpec &spec) { @@ -186,8 +176,8 @@ unsigned int FontEngine::getLineHeight(const FontSpec &spec) } FATAL_ERROR_IF(font == NULL, "Could not get font"); - return font->getDimension(L"Some unimportant example String").Height + - font->getKerningHeight(); + return font->getDimension(L"Some unimportant example String").Height + + font->getKerningHeight(); } /******************************************************************************/ @@ -217,7 +207,7 @@ void FontEngine::readSettings() if (USE_FREETYPE && g_settings->getBool("freetype")) { m_default_size[FM_Standard] = m_settings->getU16("font_size"); m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size"); - m_default_size[FM_Mono] = m_settings->getU16("mono_font_size"); + m_default_size[FM_Mono] = m_settings->getU16("mono_font_size"); /*~ DO NOT TRANSLATE THIS LITERALLY! This is a special string. Put either "no" or "yes" @@ -227,8 +217,8 @@ void FontEngine::readSettings() The fallback font is (normally) required for languages with non-Latin script, like Chinese. When in doubt, test your translation. */ - m_currentMode = is_yes(gettext("needs_fallback_font")) ? FM_Fallback - : FM_Standard; + m_currentMode = is_yes(gettext("needs_fallback_font")) ? + FM_Fallback : FM_Standard; m_default_bold = m_settings->getBool("font_bold"); m_default_italic = m_settings->getBool("font_italic"); @@ -237,8 +227,8 @@ void FontEngine::readSettings() m_currentMode = FM_Simple; } - m_default_size[FM_Simple] = m_settings->getU16("font_size"); - m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size"); + m_default_size[FM_Simple] = m_settings->getU16("font_size"); + m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size"); cleanCache(); updateFontCache(); @@ -253,12 +243,11 @@ void FontEngine::updateSkin() if (font) m_env->getSkin()->setFont(font); else - errorstream << "FontEngine: Default font file: " - << "\n\t\"" << m_settings->get("font_path") << "\"" - << "\n\trequired for current screen configuration was not " - "found" - << " or was invalid file format." - << "\n\tUsing irrlicht default font." << std::endl; + errorstream << "FontEngine: Default font file: " << + "\n\t\"" << m_settings->get("font_path") << "\"" << + "\n\trequired for current screen configuration was not found" << + " or was invalid file format." << + "\n\tUsing irrlicht default font." << std::endl; // If we did fail to create a font our own make irrlicht find a default one font = m_env->getSkin()->getFont(); @@ -285,15 +274,15 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) std::string setting_prefix = ""; switch (spec.mode) { - case FM_Fallback: - setting_prefix = "fallback_"; - break; - case FM_Mono: - case FM_SimpleMono: - setting_prefix = "mono_"; - break; - default: - break; + case FM_Fallback: + setting_prefix = "fallback_"; + break; + case FM_Mono: + case FM_SimpleMono: + setting_prefix = "mono_"; + break; + default: + break; } std::string setting_suffix = ""; @@ -303,26 +292,28 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) setting_suffix.append("_italic"); u32 size = std::floor(RenderingEngine::getDisplayDensity() * - m_settings->getFloat("gui_scaling") * spec.size); + m_settings->getFloat("gui_scaling") * spec.size); if (size == 0) { errorstream << "FontEngine: attempt to use font size 0" << std::endl; - errorstream << " display density: " - << RenderingEngine::getDisplayDensity() << std::endl; + errorstream << " display density: " << RenderingEngine::getDisplayDensity() << std::endl; abort(); } - u16 font_shadow = 0; + u16 font_shadow = 0; u16 font_shadow_alpha = 0; g_settings->getU16NoEx(setting_prefix + "font_shadow", font_shadow); - g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha", font_shadow_alpha); + g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha", + font_shadow_alpha); std::string wanted_font_path; wanted_font_path = g_settings->get(setting_prefix + "font_path" + setting_suffix); - std::string fallback_settings[] = {wanted_font_path, - m_settings->get("fallback_font_path"), - m_settings->getDefault(setting_prefix + "font_path")}; + std::string fallback_settings[] = { + wanted_font_path, + m_settings->get("fallback_font_path"), + m_settings->getDefault(setting_prefix + "font_path") + }; #if USE_FREETYPE for (const std::string &font_path : fallback_settings) { @@ -333,19 +324,18 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) if (font) return font; - errorstream << "FontEngine: Cannot load '" << font_path - << "'. Trying to fall back to another path." << std::endl; + errorstream << "FontEngine: Cannot load '" << font_path << + "'. Trying to fall back to another path." << std::endl; } + // give up errorstream << "minetest can not continue without a valid font. " - "Please correct the 'font_path' setting or install the font " - "file in the proper location" - << std::endl; + "Please correct the 'font_path' setting or install the font " + "file in the proper location" << std::endl; #else errorstream << "FontEngine: Tried to load freetype fonts but Minetest was" - " not compiled with that library." - << std::endl; + " not compiled with that library." << std::endl; #endif abort(); } @@ -365,18 +355,20 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec) if (ending == ".ttf") { errorstream << "FontEngine: Found font \"" << font_path - << "\" but freetype is not available." << std::endl; + << "\" 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() * - m_settings->getFloat("gui_scaling") * spec.size); + u32 size = std::floor( + RenderingEngine::getDisplayDensity() * + m_settings->getFloat("gui_scaling") * + spec.size); irr::gui::IGUIFont *font = nullptr; - std::string font_extensions[] = {".png", ".xml"}; + 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 @@ -397,8 +389,7 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec) font = m_env->getFont(path.str().c_str()); if (font) { - verbosestream << "FontEngine: found font: " << path.str() - << std::endl; + verbosestream << "FontEngine: found font: " << path.str() << std::endl; break; } } @@ -412,8 +403,7 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec) if (fs::PathExists(font_path)) { font = m_env->getFont(font_path.c_str()); if (font) - verbosestream << "FontEngine: found font: " << font_path - << std::endl; + verbosestream << "FontEngine: found font: " << font_path << std::endl; } } diff --git a/src/client/fontengine.h b/src/client/fontengine.h index a9d7a13c2..865b2d3ff 100644 --- a/src/client/fontengine.h +++ b/src/client/fontengine.h @@ -29,8 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #define FONT_SIZE_UNSPECIFIED 0xFFFFFFFF -enum FontMode : u8 -{ +enum FontMode : u8 { FM_Standard = 0, FM_Mono, FM_Fallback, @@ -40,15 +39,18 @@ enum FontMode : u8 FM_Unspecified }; -struct FontSpec -{ +struct FontSpec { FontSpec(unsigned int font_size, FontMode mode, bool bold, bool italic) : - size(font_size), mode(mode), bold(bold), italic(italic) + size(font_size), + mode(mode), + bold(bold), + italic(italic) {} + + u16 getHash() { + return (mode << 2) | (bold << 1) | italic; } - u16 getHash() { return (mode << 2) | (bold << 1) | italic; } - unsigned int size; FontMode mode; bool bold; @@ -58,15 +60,16 @@ struct FontSpec class FontEngine { public: - FontEngine(Settings *main_settings, gui::IGUIEnvironment *env); + + FontEngine(Settings* main_settings, gui::IGUIEnvironment* env); ~FontEngine(); // Get best possible font specified by FontSpec irr::gui::IGUIFont *getFont(FontSpec spec); - irr::gui::IGUIFont *getFont(unsigned int font_size = FONT_SIZE_UNSPECIFIED, - FontMode mode = FM_Unspecified) + irr::gui::IGUIFont *getFont(unsigned int font_size=FONT_SIZE_UNSPECIFIED, + FontMode mode=FM_Unspecified) { FontSpec spec(font_size, mode, m_default_bold, m_default_italic); return getFont(spec); @@ -76,8 +79,9 @@ class FontEngine unsigned int getTextHeight(const FontSpec &spec); /** get text width if a text for a specific font */ - unsigned int getTextHeight(unsigned int font_size = FONT_SIZE_UNSPECIFIED, - FontMode mode = FM_Unspecified) + unsigned int getTextHeight( + unsigned int font_size=FONT_SIZE_UNSPECIFIED, + FontMode mode=FM_Unspecified) { FontSpec spec(font_size, mode, m_default_bold, m_default_italic); return getTextHeight(spec); @@ -86,9 +90,9 @@ class FontEngine unsigned int getTextWidth(const std::wstring &text, const FontSpec &spec); /** get text width if a text for a specific font */ - unsigned int getTextWidth(const std::wstring &text, - unsigned int font_size = FONT_SIZE_UNSPECIFIED, - FontMode mode = FM_Unspecified) + unsigned int getTextWidth(const std::wstring& text, + unsigned int font_size=FONT_SIZE_UNSPECIFIED, + FontMode mode=FM_Unspecified) { FontSpec spec(font_size, mode, m_default_bold, m_default_italic); return getTextWidth(text, spec); @@ -99,9 +103,9 @@ class FontEngine return getTextWidth(utf8_to_wide(text), spec); } - unsigned int getTextWidth(const std::string &text, - unsigned int font_size = FONT_SIZE_UNSPECIFIED, - FontMode mode = FM_Unspecified) + unsigned int getTextWidth(const std::string& text, + unsigned int font_size=FONT_SIZE_UNSPECIFIED, + FontMode mode=FM_Unspecified) { FontSpec spec(font_size, mode, m_default_bold, m_default_italic); return getTextWidth(utf8_to_wide(text), spec); @@ -110,8 +114,8 @@ class FontEngine /** get line height for a specific font (including empty room between lines) */ unsigned int getLineHeight(const FontSpec &spec); - unsigned int getLineHeight(unsigned int font_size = FONT_SIZE_UNSPECIFIED, - FontMode mode = FM_Unspecified) + unsigned int getLineHeight(unsigned int font_size=FONT_SIZE_UNSPECIFIED, + FontMode mode=FM_Unspecified) { FontSpec spec(font_size, mode, m_default_bold, m_default_italic); return getLineHeight(spec); @@ -124,7 +128,7 @@ class FontEngine unsigned int getFontSize(FontMode mode); /** initialize font engine */ - void initialize(Settings *main_settings, gui::IGUIEnvironment *env); + void initialize(Settings* main_settings, gui::IGUIEnvironment* env); /** update internal parameters from settings */ void readSettings(); @@ -146,13 +150,13 @@ class FontEngine void cleanCache(); /** pointer to settings for registering callbacks or reading config */ - Settings *m_settings = nullptr; + Settings* m_settings = nullptr; /** pointer to irrlicht gui environment */ - gui::IGUIEnvironment *m_env = nullptr; + gui::IGUIEnvironment* m_env = nullptr; /** internal storage for caching fonts of different size */ - std::map m_font_cache[FM_MaxMode << 2]; + std::map m_font_cache[FM_MaxMode << 2]; /** default font size to use */ unsigned int m_default_size[FM_MaxMode]; @@ -168,4 +172,4 @@ class FontEngine }; /** interface to access main font engine*/ -extern FontEngine *g_fontengine; +extern FontEngine* g_fontengine; diff --git a/src/client/game.cpp b/src/client/game.cpp index e56101436..479484ae9 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/clientevent.h" #include "client/gameui.h" #include "client/inputhandler.h" -#include "client/tile.h" // For TextureSource +#include "client/tile.h" // For TextureSource #include "client/keys.h" #include "client/joystick_controller.h" #include "clientmap.h" @@ -52,7 +52,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gui/profilergraph.h" #include "mapblock.h" #include "minimap.h" -#include "nodedef.h" // Needed for determining pointing to nodes +#include "nodedef.h" // Needed for determining pointing to nodes #include "nodemetadata.h" #include "particles.h" #include "porting.h" @@ -73,49 +73,60 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "hud.h" #if USE_SOUND -#include "client/sound_openal.h" + #include "client/sound_openal.h" #else -#include "client/sound.h" + #include "client/sound.h" #endif -Game::Game() : m_chat_log_buf(g_logger), m_game_ui(new GameUI()) -{ - g_settings->registerChangedCallback( - "doubletap_jump", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "enable_clouds", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "doubletap_joysticks", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "enable_particles", &settingChangedCallback, this); - g_settings->registerChangedCallback("enable_fog", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "mouse_sensitivity", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "joystick_frustum_sensitivity", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "repeat_rightclick_time", &settingChangedCallback, this); - g_settings->registerChangedCallback("noclip", &settingChangedCallback, this); - g_settings->registerChangedCallback("free_move", &settingChangedCallback, this); - g_settings->registerChangedCallback("cinematic", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "cinematic_camera_smoothing", &settingChangedCallback, this); - g_settings->registerChangedCallback( - "camera_smoothing", &settingChangedCallback, this); - g_settings->registerChangedCallback("freecam", &freecamChangedCallback, this); - g_settings->registerChangedCallback("xray", &updateAllMapBlocksCallback, this); - g_settings->registerChangedCallback( - "xray_nodes", &updateAllMapBlocksCallback, this); - g_settings->registerChangedCallback( - "fullbright", &updateAllMapBlocksCallback, this); - +Game::Game() : + m_chat_log_buf(g_logger), + m_game_ui(new GameUI()) +{ + g_settings->registerChangedCallback("doubletap_jump", + &settingChangedCallback, this); + g_settings->registerChangedCallback("enable_clouds", + &settingChangedCallback, this); + g_settings->registerChangedCallback("doubletap_joysticks", + &settingChangedCallback, this); + g_settings->registerChangedCallback("enable_particles", + &settingChangedCallback, this); + g_settings->registerChangedCallback("enable_fog", + &settingChangedCallback, this); + g_settings->registerChangedCallback("mouse_sensitivity", + &settingChangedCallback, this); + g_settings->registerChangedCallback("joystick_frustum_sensitivity", + &settingChangedCallback, this); + g_settings->registerChangedCallback("repeat_rightclick_time", + &settingChangedCallback, this); + g_settings->registerChangedCallback("noclip", + &settingChangedCallback, this); + g_settings->registerChangedCallback("free_move", + &settingChangedCallback, this); + g_settings->registerChangedCallback("cinematic", + &settingChangedCallback, this); + g_settings->registerChangedCallback("cinematic_camera_smoothing", + &settingChangedCallback, this); + g_settings->registerChangedCallback("camera_smoothing", + &settingChangedCallback, this); + g_settings->registerChangedCallback("freecam", + &freecamChangedCallback, this); + g_settings->registerChangedCallback("xray", + &updateAllMapBlocksCallback, this); + g_settings->registerChangedCallback("xray_nodes", + &updateAllMapBlocksCallback, this); + g_settings->registerChangedCallback("fullbright", + &updateAllMapBlocksCallback, this); + readSettings(); #ifdef __ANDROID__ - m_cache_hold_aux1 = false; // This is initialised properly later + m_cache_hold_aux1 = false; // This is initialised properly later #endif + } + + /**************************************************************************** MinetestApp Public ****************************************************************************/ @@ -141,44 +152,53 @@ Game::~Game() extendedResourceCleanup(); - g_settings->deregisterChangedCallback( - "doubletap_jump", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "enable_clouds", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "enable_particles", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "enable_fog", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "mouse_sensitivity", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "repeat_rightclick_time", &settingChangedCallback, this); - g_settings->deregisterChangedCallback("noclip", &settingChangedCallback, this); - g_settings->deregisterChangedCallback("free_move", &settingChangedCallback, this); - g_settings->deregisterChangedCallback("cinematic", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "cinematic_camera_smoothing", &settingChangedCallback, this); - g_settings->deregisterChangedCallback( - "camera_smoothing", &settingChangedCallback, this); - g_settings->deregisterChangedCallback("freecam", &freecamChangedCallback, this); - g_settings->deregisterChangedCallback("xray", &updateAllMapBlocksCallback, this); - g_settings->deregisterChangedCallback( - "xray_nodes", &updateAllMapBlocksCallback, this); - g_settings->deregisterChangedCallback( - "fullbright", &updateAllMapBlocksCallback, this); -} - -bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_data, - std::string &error_message, bool *reconnect, ChatBackend *chat_backend) + g_settings->deregisterChangedCallback("doubletap_jump", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("enable_clouds", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("enable_particles", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("enable_fog", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("mouse_sensitivity", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("repeat_rightclick_time", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("noclip", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("free_move", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("cinematic", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("cinematic_camera_smoothing", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("camera_smoothing", + &settingChangedCallback, this); + g_settings->deregisterChangedCallback("freecam", + &freecamChangedCallback, this); + g_settings->deregisterChangedCallback("xray", + &updateAllMapBlocksCallback, this); + g_settings->deregisterChangedCallback("xray_nodes", + &updateAllMapBlocksCallback, this); + g_settings->deregisterChangedCallback("fullbright", + &updateAllMapBlocksCallback, this); +} + +bool Game::startup(bool *kill, + InputHandler *input, + const GameStartData &start_data, + std::string &error_message, + bool *reconnect, + ChatBackend *chat_backend) { // "cache" - this->device = RenderingEngine::get_raw_device(); - this->kill = kill; - this->error_message = &error_message; + this->device = RenderingEngine::get_raw_device(); + this->kill = kill; + this->error_message = &error_message; this->reconnect_requested = reconnect; - this->input = input; - this->chat_backend = chat_backend; + this->input = input; + this->chat_backend = chat_backend; this->simple_singleplayer_mode = start_data.isSinglePlayer(); input->keycache.populate(); @@ -186,8 +206,8 @@ bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_d driver = device->getVideoDriver(); smgr = RenderingEngine::get_scene_manager(); - RenderingEngine::get_scene_manager()->getParameters()->setAttribute( - scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); + RenderingEngine::get_scene_manager()->getParameters()-> + setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); // Reinit runData runData = GameRunData(); @@ -201,8 +221,8 @@ bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_d g_client_translations->clear(); // address can change if simple_singleplayer_mode - if (!init(start_data.world_spec.path, start_data.address, start_data.socket_port, - start_data.game_spec)) + if (!init(start_data.world_spec.path, start_data.address, + start_data.socket_port, start_data.game_spec)) return false; if (!createClient(start_data)) @@ -213,13 +233,14 @@ bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_d return true; } + void Game::run() { ProfilerGraph graph; - RunStats stats = {0}; - FpsControl draw_times = {0}; + RunStats stats = { 0 }; + FpsControl draw_times = { 0 }; f32 dtime; // in seconds - + /* Clear the profiler */ Profiler::GraphValues dummyvalues; g_profiler->graphGet(dummyvalues); @@ -229,25 +250,24 @@ void Game::run() set_light_table(g_settings->getFloat("display_gamma")); #ifdef __ANDROID__ - m_cache_hold_aux1 = g_settings->getBool("fast_move") && - client->checkPrivilege("fast"); + m_cache_hold_aux1 = g_settings->getBool("fast_move") + && client->checkPrivilege("fast"); #endif - irr::core::dimension2d previous_screen_size( - g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); + irr::core::dimension2d previous_screen_size(g_settings->getU16("screen_w"), + g_settings->getU16("screen_h")); - while (RenderingEngine::run() && - !(*kill || g_gamecallback->shutdown_requested || - (server && server->isShutdownRequested()))) { + while (RenderingEngine::run() + && !(*kill || g_gamecallback->shutdown_requested + || (server && server->isShutdownRequested()))) { const irr::core::dimension2d ¤t_screen_size = - RenderingEngine::get_video_driver()->getScreenSize(); + RenderingEngine::get_video_driver()->getScreenSize(); // Verify if window size has changed and save it if it's the case // Ensure evaluating settings->getBool after verifying screensize // First condition is cheaper if (previous_screen_size != current_screen_size && - current_screen_size != - irr::core::dimension2d(0, 0) && + current_screen_size != irr::core::dimension2d(0,0) && g_settings->getBool("autosave_screensize")) { g_settings->setU16("screen_w", current_screen_size.Width); g_settings->setU16("screen_h", current_screen_size.Height); @@ -278,32 +298,30 @@ void Game::run() processUserInput(dtime); // Update camera before player movement to avoid camera lag of one frame updateCameraDirection(&cam_view_target, dtime); - cam_view.camera_yaw += - (cam_view_target.camera_yaw - cam_view.camera_yaw) * - m_cache_cam_smoothing; - cam_view.camera_pitch += - (cam_view_target.camera_pitch - cam_view.camera_pitch) * - m_cache_cam_smoothing; + cam_view.camera_yaw += (cam_view_target.camera_yaw - + cam_view.camera_yaw) * m_cache_cam_smoothing; + cam_view.camera_pitch += (cam_view_target.camera_pitch - + cam_view.camera_pitch) * m_cache_cam_smoothing; updatePlayerControl(cam_view); step(&dtime); processClientEvents(&cam_view_target); updateCamera(draw_times.busy_time, dtime); updateSound(dtime); processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud, - m_game_ui->m_flags.show_debug); + m_game_ui->m_flags.show_debug); updateFrame(&graph, &stats, dtime, cam_view); updateProfilerGraphs(&graph); // Update if minimap has been disabled by the server m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap(); - if (m_does_lost_focus_pause_game && !device->isWindowFocused() && - !isMenuActive()) { + if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) { showPauseMenu(); } } } + void Game::shutdown() { RenderingEngine::finalize(); @@ -358,13 +376,17 @@ void Game::shutdown() } } + /****************************************************************************/ /**************************************************************************** Startup ****************************************************************************/ /****************************************************************************/ -bool Game::init(const std::string &map_dir, const std::string &address, u16 port, +bool Game::init( + const std::string &map_dir, + const std::string &address, + u16 port, const SubgameSpec &gamespec) { texture_src = createTextureSource(); @@ -379,8 +401,8 @@ bool Game::init(const std::string &map_dir, const std::string &address, u16 port eventmgr = new EventManager(); quicktune = new QuicktuneShortcutter(); - if (!(texture_src && shader_src && itemdef_manager && nodedef_manager && - eventmgr && quicktune)) + if (!(texture_src && shader_src && itemdef_manager && nodedef_manager + && eventmgr && quicktune)) return false; if (!initSound()) @@ -400,8 +422,7 @@ bool Game::initSound() #if USE_SOUND if (g_settings->getBool("enable_sound") && g_sound_manager_singleton.get()) { infostream << "Attempting to use OpenAL audio" << std::endl; - sound = createOpenALSoundManager( - g_sound_manager_singleton.get(), &soundfetcher); + sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher); if (!sound) infostream << "Failed to initialize OpenAL audio" << std::endl; } else @@ -423,8 +444,8 @@ bool Game::initSound() return true; } -bool Game::createSingleplayerServer( - const std::string &map_dir, const SubgameSpec &gamespec, u16 port) +bool Game::createSingleplayerServer(const std::string &map_dir, + const SubgameSpec &gamespec, u16 port) { showOverlayMessage(N_("Creating server..."), 0, 5); @@ -432,7 +453,7 @@ bool Game::createSingleplayerServer( Address bind_addr(0, 0, 0, 0, port); if (g_settings->getBool("ipv6_server")) { - bind_addr.setAddress((IPv6AddressBytes *)NULL); + bind_addr.setAddress((IPv6AddressBytes *) NULL); } try { @@ -444,14 +465,14 @@ bool Game::createSingleplayerServer( } if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) { - *error_message = "Unable to listen on " + bind_addr.serializeString() + - " because IPv6 is disabled"; + *error_message = "Unable to listen on " + + bind_addr.serializeString() + + " because IPv6 is disabled"; errorstream << *error_message << std::endl; return false; } - server = new Server( - map_dir, gamespec, simple_singleplayer_mode, bind_addr, false); + server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false); server->start(); return true; @@ -493,9 +514,8 @@ bool Game::createClient(const GameStartData &start_data) return false; } - GameGlobalShaderConstantSetterFactory *scsf = - new GameGlobalShaderConstantSetterFactory(&m_flags.force_fog_off, - &runData.fog_range, client); + GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory( + &m_flags.force_fog_off, &runData.fog_range, client); shader_src->addShaderConstantSetterFactory(scsf); // Update cached textures, meshes and materials @@ -523,7 +543,7 @@ bool Game::createClient(const GameStartData &start_data) */ sky = new Sky(-1, texture_src); scsf->setSky(sky); - skybox = NULL; // This is used/set later on in the main run loop + skybox = NULL; // This is used/set later on in the main run loop if (!sky) { *error_message = "Memory allocation error sky"; @@ -587,15 +607,15 @@ bool Game::initGui() chat_backend->applySettings(); // Chat backend and console - gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, - chat_backend, client, &g_menumgr); + gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), + -1, chat_backend, client, &g_menumgr); if (!gui_chat_console) { *error_message = "Could not allocate memory for chat console"; errorstream << *error_message << std::endl; return false; } - + m_cheat_menu = new CheatMenu(client); if (!m_cheat_menu) { @@ -614,10 +634,10 @@ bool Game::initGui() return true; } -bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, - bool *connection_aborted) +bool Game::connectToServer(const GameStartData &start_data, + bool *connect_ok, bool *connection_aborted) { - *connect_ok = false; // Let's not be overly optimistic + *connect_ok = false; // Let's not be overly optimistic *connection_aborted = false; bool local_server_mode = false; @@ -629,7 +649,7 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, connect_address.Resolve(start_data.address.c_str()); if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY - // connect_address.Resolve("localhost"); + //connect_address.Resolve("localhost"); if (connect_address.isIPv6()) { IPv6AddressBytes addr_bytes; addr_bytes.bytes[15] = 1; @@ -647,14 +667,15 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) { *error_message = "Unable to connect to " + - connect_address.serializeString() + - " because IPv6 is disabled"; + connect_address.serializeString() + + " because IPv6 is disabled"; errorstream << *error_message << std::endl; return false; } - client = new Client(start_data.name.c_str(), start_data.password, - start_data.address, *draw_control, texture_src, shader_src, + client = new Client(start_data.name.c_str(), + start_data.password, start_data.address, + *draw_control, texture_src, shader_src, itemdef_manager, nodedef_manager, sound, eventmgr, connect_address.isIPv6(), m_game_ui.get()); @@ -667,7 +688,8 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, connect_address.print(&infostream); infostream << std::endl; - client->connect(connect_address, simple_singleplayer_mode || local_server_mode); + client->connect(connect_address, + simple_singleplayer_mode || local_server_mode); /* Wait for server to accept connection @@ -676,7 +698,7 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, try { input->clear(); - FpsControl fps_control = {0}; + FpsControl fps_control = { 0 }; f32 dtime; f32 wait_time = 0; // in seconds @@ -703,8 +725,8 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, break; if (client->accessDenied()) { - *error_message = "Access denied. Reason: " + - client->accessDeniedReason(); + *error_message = "Access denied. Reason: " + + client->accessDeniedReason(); *reconnect_requested = client->reconnectRequested(); errorstream << *error_message << std::endl; break; @@ -719,22 +741,16 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, if (client->m_is_registration_confirmation_state) { if (registration_confirmation_shown) { // Keep drawing the GUI - RenderingEngine::draw_menu_scene( - guienv, dtime, true); + RenderingEngine::draw_menu_scene(guienv, dtime, true); } else { registration_confirmation_shown = true; - (new GUIConfirmRegistration(guienv, - guienv->getRootGUIElement(), -1, - &g_menumgr, client, - start_data.name, - start_data.password, - connection_aborted, texture_src)) - ->drop(); + (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1, + &g_menumgr, client, start_data.name, start_data.password, + connection_aborted, texture_src))->drop(); } } else { wait_time += dtime; - // Only time out if we aren't waiting for the server we - // started + // Only time out if we aren't waiting for the server we started if (!start_data.isSinglePlayer() && wait_time > 10) { *error_message = "Connection timed out."; errorstream << *error_message << std::endl; @@ -742,8 +758,7 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok, } // Update status - showOverlayMessage( - N_("Connecting to server..."), dtime, 20); + showOverlayMessage(N_("Connecting to server..."), dtime, 20); } } } catch (con::PeerNotFoundException &e) { @@ -759,7 +774,7 @@ bool Game::getServerContent(bool *aborted) { input->clear(); - FpsControl fps_control = {0}; + FpsControl fps_control = { 0 }; f32 dtime; // in seconds fps_control.last_time = RenderingEngine::get_timer_time(); @@ -802,26 +817,24 @@ bool Game::getServerContent(bool *aborted) if (!client->itemdefReceived()) { const wchar_t *text = wgettext("Item definitions..."); progress = 25; - RenderingEngine::draw_load_screen( - text, guienv, texture_src, dtime, progress); + RenderingEngine::draw_load_screen(text, guienv, texture_src, + dtime, progress); delete[] text; } else if (!client->nodedefReceived()) { const wchar_t *text = wgettext("Node definitions..."); progress = 30; - RenderingEngine::draw_load_screen( - text, guienv, texture_src, dtime, progress); + RenderingEngine::draw_load_screen(text, guienv, texture_src, + dtime, progress); delete[] text; } else { std::stringstream message; std::fixed(message); message.precision(0); - message << gettext("Media...") << " " - << (client->mediaReceiveProgress() * 100) << "%"; + message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%"; message.precision(2); if ((USE_CURL == 0) || - (!g_settings->getBool( - "enable_remote_media_server"))) { + (!g_settings->getBool("enable_remote_media_server"))) { float cur = client->getCurRate(); std::string cur_unit = gettext("KiB/s"); @@ -834,14 +847,15 @@ bool Game::getServerContent(bool *aborted) } progress = 30 + client->mediaReceiveProgress() * 35 + 0.5; - RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), - guienv, texture_src, dtime, progress); + RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv, + texture_src, dtime, progress); } } return true; } + /****************************************************************************/ /**************************************************************************** Run @@ -859,12 +873,14 @@ inline void Game::updateInteractTimers(f32 dtime) runData.time_from_last_punch += dtime; } + /* returns false if game should exit, otherwise true */ inline bool Game::checkConnection() { if (client->accessDenied()) { - *error_message = "Access denied. Reason: " + client->accessDeniedReason(); + *error_message = "Access denied. Reason: " + + client->accessDeniedReason(); *reconnect_requested = client->reconnectRequested(); errorstream << *error_message << std::endl; return false; @@ -873,6 +889,7 @@ inline bool Game::checkConnection() return true; } + /* returns false if game should exit, otherwise true */ inline bool Game::handleCallbacks() @@ -883,21 +900,20 @@ inline bool Game::handleCallbacks() } if (g_gamecallback->changepassword_requested) { - (new GUIPasswordChange( - guienv, guiroot, -1, &g_menumgr, client, texture_src)) - ->drop(); + (new GUIPasswordChange(guienv, guiroot, -1, + &g_menumgr, client, texture_src))->drop(); g_gamecallback->changepassword_requested = false; } if (g_gamecallback->changevolume_requested) { - (new GUIVolumeChange(guienv, guiroot, -1, &g_menumgr, texture_src)) - ->drop(); + (new GUIVolumeChange(guienv, guiroot, -1, + &g_menumgr, texture_src))->drop(); g_gamecallback->changevolume_requested = false; } if (g_gamecallback->keyconfig_requested) { - (new GUIKeyChangeMenu(guienv, guiroot, -1, &g_menumgr, texture_src)) - ->drop(); + (new GUIKeyChangeMenu(guienv, guiroot, -1, + &g_menumgr, texture_src))->drop(); g_gamecallback->keyconfig_requested = false; } @@ -909,6 +925,7 @@ inline bool Game::handleCallbacks() return true; } + void Game::processQueues() { texture_src->processQueue(); @@ -916,9 +933,12 @@ void Game::processQueues() shader_src->processQueue(); } -void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime) + +void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, + f32 dtime) { - float profiler_print_interval = g_settings->getFloat("profiler_print_interval"); + float profiler_print_interval = + g_settings->getFloat("profiler_print_interval"); bool print_to_log = true; if (profiler_print_interval == 0) { @@ -937,14 +957,15 @@ void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, } // Update update graphs - g_profiler->graphAdd( - "Time non-rendering [ms]", draw_times.busy_time - stats.drawtime); + g_profiler->graphAdd("Time non-rendering [ms]", + draw_times.busy_time - stats.drawtime); g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time); g_profiler->graphAdd("FPS", 1.0f / dtime); } -void Game::updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime) +void Game::updateStats(RunStats *stats, const FpsControl &draw_times, + f32 dtime) { f32 jitter; @@ -992,6 +1013,8 @@ void Game::updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime) } } + + /**************************************************************************** Input handling ****************************************************************************/ @@ -999,8 +1022,7 @@ void Game::updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime) void Game::processUserInput(f32 dtime) { // Reset input if window not active or some menu is active - if (!device->isWindowActive() || isMenuActive() || - guienv->hasFocus(gui_chat_console)) { + if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) { input->clear(); #ifdef HAVE_TOUCHSCREENGUI g_touchscreengui->hide(); @@ -1037,6 +1059,7 @@ void Game::processUserInput(f32 dtime) processItemSelection(&runData.new_playeritem); } + void Game::processKeyInput() { if (wasKeyDown(KeyType::DROP)) { @@ -1065,11 +1088,9 @@ void Game::processKeyInput() if (client->modsLoaded()) openConsole(0.2, L"."); else - m_game_ui->showStatusText( - wgettext("Client side scripting is disabled")); + m_game_ui->showStatusText(wgettext("Client side scripting is disabled")); } else if (wasKeyDown(KeyType::CONSOLE)) { - openConsole(core::clamp( - g_settings->getFloat("console_height"), 0.1f, 1.0f)); + openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f)); } else if (wasKeyDown(KeyType::FREEMOVE)) { toggleFreeMove(); } else if (wasKeyDown(KeyType::JUMP)) { @@ -1112,14 +1133,11 @@ void Game::processKeyInput() } } else if (wasKeyDown(KeyType::INC_VOLUME)) { if (g_settings->getBool("enable_sound")) { - float new_volume = rangelim( - g_settings->getFloat("sound_volume") + 0.1f, 0.0f, - 1.0f); + float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f); wchar_t buf[100]; g_settings->setFloat("sound_volume", new_volume); const wchar_t *str = wgettext("Volume changed to %d%%"); - swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, - myround(new_volume * 100)); + swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100)); delete[] str; m_game_ui->showStatusText(buf); } else { @@ -1127,24 +1145,20 @@ void Game::processKeyInput() } } else if (wasKeyDown(KeyType::DEC_VOLUME)) { if (g_settings->getBool("enable_sound")) { - float new_volume = rangelim( - g_settings->getFloat("sound_volume") - 0.1f, 0.0f, - 1.0f); + float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f); wchar_t buf[100]; g_settings->setFloat("sound_volume", new_volume); const wchar_t *str = wgettext("Volume changed to %d%%"); - swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, - myround(new_volume * 100)); + swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100)); delete[] str; m_game_ui->showStatusText(buf); } else { m_game_ui->showTranslatedStatusText("Sound system is disabled"); } #else - } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME) || - wasKeyDown(KeyType::DEC_VOLUME)) { - m_game_ui->showTranslatedStatusText( - "Sound system is not supported on this build"); + } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME) + || wasKeyDown(KeyType::DEC_VOLUME)) { + m_game_ui->showTranslatedStatusText("Sound system is not supported on this build"); #endif } else if (wasKeyDown(KeyType::CINEMATIC)) { toggleCinematic(); @@ -1203,7 +1217,8 @@ void Game::processItemSelection(u16 *new_playeritem) *new_playeritem = player->getWieldIndex(); s32 wheel = input->getMouseWheel(); - u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1, player->hud_hotbar_itemcount - 1); + u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1, + player->hud_hotbar_itemcount - 1); s32 dir = wheel; @@ -1226,13 +1241,14 @@ void Game::processItemSelection(u16 *new_playeritem) /* Item selection using hotbar slot keys */ for (u16 i = 0; i <= max_item; i++) { - if (wasKeyDown((GameKeyType)(KeyType::SLOT_1 + i))) { + if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) { *new_playeritem = i; break; } } } + void Game::dropSelectedItem(bool single_item) { IDropAction *a = new IDropAction(); @@ -1243,6 +1259,7 @@ void Game::dropSelectedItem(bool single_item) client->inventoryAction(a); } + void Game::openInventory() { /* @@ -1261,13 +1278,12 @@ void Game::openInventory() InventoryLocation inventoryloc; inventoryloc.setCurrentPlayer(); - if (!client->modsLoaded() || - !client->getScript()->on_inventory_open( - fs_src->m_client->getInventory(inventoryloc))) { + if (!client->modsLoaded() + || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) { TextDest *txt_dst = new TextDestPlayerInventory(client); auto *&formspec = m_game_ui->updateFormspec(""); GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, - txt_dst, client->getFormspecPrepend()); + txt_dst, client->getFormspecPrepend()); formspec->setFormSpec(fs_src->getForm(), inventoryloc); } @@ -1285,6 +1301,7 @@ void Game::openEnderchest() client->getScript()->open_enderchest(); } + void Game::openConsole(float scale, const wchar_t *line) { assert(scale > 0.0f && scale <= 1.0f); @@ -1314,6 +1331,7 @@ void Game::handleAndroidChatInput() } #endif + void Game::toggleFreeMove() { bool free_move = !g_settings->getBool("free_move"); @@ -1323,8 +1341,7 @@ void Game::toggleFreeMove() if (client->checkPrivilege("fly")) { m_game_ui->showTranslatedStatusText("Fly mode enabled"); } else { - m_game_ui->showTranslatedStatusText( - "Fly mode enabled (note: no 'fly' privilege)"); + m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)"); } } else { m_game_ui->showTranslatedStatusText("Fly mode disabled"); @@ -1339,6 +1356,7 @@ void Game::toggleFreeMoveAlt() runData.reset_jump_timer = true; } + void Game::togglePitchMove() { bool pitch_move = !g_settings->getBool("pitch_move"); @@ -1351,6 +1369,7 @@ void Game::togglePitchMove() } } + void Game::toggleFast() { bool fast_move = !g_settings->getBool("fast_move"); @@ -1361,8 +1380,7 @@ void Game::toggleFast() if (has_fast_privs) { m_game_ui->showTranslatedStatusText("Fast mode enabled"); } else { - m_game_ui->showTranslatedStatusText( - "Fast mode enabled (note: no 'fast' privilege)"); + m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)"); } } else { m_game_ui->showTranslatedStatusText("Fast mode disabled"); @@ -1373,6 +1391,7 @@ void Game::toggleFast() #endif } + void Game::toggleNoClip() { bool noclip = !g_settings->getBool("noclip"); @@ -1382,8 +1401,7 @@ void Game::toggleNoClip() if (client->checkPrivilege("noclip")) { m_game_ui->showTranslatedStatusText("Noclip mode enabled"); } else { - m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: " - "no 'noclip' privilege)"); + m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)"); } } else { m_game_ui->showTranslatedStatusText("Noclip mode disabled"); @@ -1392,7 +1410,7 @@ void Game::toggleNoClip() void Game::toggleKillaura() { - bool killaura = !g_settings->getBool("killaura"); + bool killaura = ! g_settings->getBool("killaura"); g_settings->set("killaura", bool_to_cstr(killaura)); if (killaura) { @@ -1404,7 +1422,7 @@ void Game::toggleKillaura() void Game::toggleFreecam() { - bool freecam = !g_settings->getBool("freecam"); + bool freecam = ! g_settings->getBool("freecam"); g_settings->set("freecam", bool_to_cstr(freecam)); if (freecam) { @@ -1416,7 +1434,7 @@ void Game::toggleFreecam() void Game::toggleScaffold() { - bool scaffold = !g_settings->getBool("scaffold"); + bool scaffold = ! g_settings->getBool("scaffold"); g_settings->set("scaffold", bool_to_cstr(scaffold)); if (scaffold) { @@ -1428,7 +1446,7 @@ void Game::toggleScaffold() void Game::toggleNextItem() { - bool next_item = !g_settings->getBool("next_item"); + bool next_item = ! g_settings->getBool("next_item"); g_settings->set("next_item", bool_to_cstr(next_item)); if (next_item) { @@ -1463,8 +1481,7 @@ void Game::toggleAutoforward() void Game::toggleMinimap(bool shift_pressed) { - if (!mapper || !m_game_ui->m_flags.show_hud || - !g_settings->getBool("enable_minimap")) + if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap")) return; if (shift_pressed) { @@ -1485,32 +1502,31 @@ void Game::toggleMinimap(bool shift_pressed) m_game_ui->m_flags.show_minimap = true; switch (mode) { - case MINIMAP_MODE_SURFACEx1: - m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1"); - break; - case MINIMAP_MODE_SURFACEx2: - m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2"); - break; - case MINIMAP_MODE_SURFACEx4: - m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4"); - break; - case MINIMAP_MODE_RADARx1: - m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1"); - break; - case MINIMAP_MODE_RADARx2: - m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2"); - break; - case MINIMAP_MODE_RADARx4: - m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4"); - break; - default: - mode = MINIMAP_MODE_OFF; - m_game_ui->m_flags.show_minimap = false; - if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) - m_game_ui->showTranslatedStatusText("Minimap hidden"); - else - m_game_ui->showTranslatedStatusText( - "Minimap currently disabled by game or mod"); + case MINIMAP_MODE_SURFACEx1: + m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1"); + break; + case MINIMAP_MODE_SURFACEx2: + m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2"); + break; + case MINIMAP_MODE_SURFACEx4: + m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4"); + break; + case MINIMAP_MODE_RADARx1: + m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1"); + break; + case MINIMAP_MODE_RADARx2: + m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2"); + break; + case MINIMAP_MODE_RADARx4: + m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4"); + break; + default: + mode = MINIMAP_MODE_OFF; + m_game_ui->m_flags.show_minimap = false; + if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) + m_game_ui->showTranslatedStatusText("Minimap hidden"); + else + m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod"); } mapper->setMinimapMode(mode); @@ -1526,6 +1542,7 @@ void Game::toggleFog() m_game_ui->showTranslatedStatusText("Fog enabled"); } + void Game::toggleDebug() { // Initial / 4x toggle: Chat only @@ -1537,8 +1554,7 @@ void Game::toggleDebug() m_game_ui->m_flags.show_profiler_graph = false; draw_control->show_wireframe = false; m_game_ui->showTranslatedStatusText("Debug info shown"); - } else if (!m_game_ui->m_flags.show_profiler_graph && - !draw_control->show_wireframe) { + } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) { m_game_ui->m_flags.show_profiler_graph = true; m_game_ui->showTranslatedStatusText("Profiler graph shown"); } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) { @@ -1550,15 +1566,14 @@ void Game::toggleDebug() m_game_ui->m_flags.show_profiler_graph = false; draw_control->show_wireframe = false; if (client->checkPrivilege("debug")) { - m_game_ui->showTranslatedStatusText("Debug info, profiler graph, " - "and wireframe hidden"); + m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden"); } else { - m_game_ui->showTranslatedStatusText( - "Debug info and profiler graph hidden"); + m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden"); } } } + void Game::toggleUpdateCamera() { if (g_settings->getBool("freecam")) @@ -1570,6 +1585,7 @@ void Game::toggleUpdateCamera() m_game_ui->showTranslatedStatusText("Camera update enabled"); } + void Game::increaseViewRange() { s16 range = g_settings->getS16("viewing_range"); @@ -1593,6 +1609,7 @@ void Game::increaseViewRange() g_settings->set("viewing_range", itos(range_new)); } + void Game::decreaseViewRange() { s16 range = g_settings->getS16("viewing_range"); @@ -1615,6 +1632,7 @@ void Game::decreaseViewRange() g_settings->set("viewing_range", itos(range_new)); } + void Game::toggleFullViewRange() { draw_control->range_all = !draw_control->range_all; @@ -1624,18 +1642,19 @@ void Game::toggleFullViewRange() m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range"); } + void Game::checkZoomEnabled() { LocalPlayer *player = client->getEnv().getLocalPlayer(); if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f) - m_game_ui->showTranslatedStatusText( - "Zoom currently disabled by game or mod"); + m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod"); } + void Game::updateCameraDirection(CameraOrientation *cam, float dtime) { - if ((device->isWindowActive() && device->isWindowFocused() && !isMenuActive()) || - input->isRandom()) { + if ((device->isWindowActive() && device->isWindowFocused() + && !isMenuActive()) || input->isRandom()) { #ifndef __ANDROID__ if (!input->isRandom()) { @@ -1649,7 +1668,7 @@ void Game::updateCameraDirection(CameraOrientation *cam, float dtime) m_first_loop_after_window_activation = false; input->setMousePos(driver->getScreenSize().Width / 2, - driver->getScreenSize().Height / 2); + driver->getScreenSize().Height / 2); } else { updateCameraOrientation(cam, dtime); } @@ -1663,6 +1682,7 @@ void Game::updateCameraDirection(CameraOrientation *cam, float dtime) #endif m_first_loop_after_window_activation = true; + } } @@ -1670,20 +1690,18 @@ void Game::updateCameraOrientation(CameraOrientation *cam, float dtime) { #ifdef HAVE_TOUCHSCREENGUI if (g_touchscreengui) { - cam->camera_yaw += g_touchscreengui->getYawChange(); - cam->camera_pitch = g_touchscreengui->getPitch(); + cam->camera_yaw += g_touchscreengui->getYawChange(); + cam->camera_pitch = g_touchscreengui->getPitch(); } else { #endif - v2s32 center(driver->getScreenSize().Width / 2, - driver->getScreenSize().Height / 2); + v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2); v2s32 dist = input->getMousePos() - center; - if (m_invert_mouse || - camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) { + if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) { dist.Y = -dist.Y; } - cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity; + cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity; cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity; if (dist.X != 0 || dist.Y != 0) @@ -1694,45 +1712,51 @@ void Game::updateCameraOrientation(CameraOrientation *cam, float dtime) if (m_cache_enable_joysticks) { f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime; - cam->camera_yaw -= input->joystick.getAxisWithoutDead( - JA_FRUSTUM_HORIZONTAL) * - c; - cam->camera_pitch += - input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * - c; + cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c; + cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c; } cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5); } + void Game::updatePlayerControl(const CameraOrientation &cam) { - // TimeTaker tt("update player control", NULL, PRECISION_NANO); + //TimeTaker tt("update player control", NULL, PRECISION_NANO); // DO NOT use the isKeyDown method for the forward, backward, left, right // buttons, as the code that uses the controls needs to be able to // distinguish between the two in order to know when to use joysticks. - PlayerControl control(input->isKeyDown(KeyType::FORWARD), - input->isKeyDown(KeyType::BACKWARD), - input->isKeyDown(KeyType::LEFT), input->isKeyDown(KeyType::RIGHT), - isKeyDown(KeyType::JUMP), isKeyDown(KeyType::SPECIAL1), - isKeyDown(KeyType::SNEAK), isKeyDown(KeyType::ZOOM), - input->getLeftState(), input->getRightState(), cam.camera_pitch, - cam.camera_yaw, - input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE), - input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)); - - u32 keypress_bits = (((u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) | - ((u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) | - ((u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) | - ((u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) | - ((u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) | - ((u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) | - ((u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) | - ((u32)(input->getLeftState() & 0x1) << 7) | - ((u32)(input->getRightState() & 0x1) << 8) | - ((u32)(isKeyDown(KeyType::ZOOM) & 0x1) << 9)); + PlayerControl control( + input->isKeyDown(KeyType::FORWARD), + input->isKeyDown(KeyType::BACKWARD), + input->isKeyDown(KeyType::LEFT), + input->isKeyDown(KeyType::RIGHT), + isKeyDown(KeyType::JUMP), + isKeyDown(KeyType::SPECIAL1), + isKeyDown(KeyType::SNEAK), + isKeyDown(KeyType::ZOOM), + input->getLeftState(), + input->getRightState(), + cam.camera_pitch, + cam.camera_yaw, + input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE), + input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE) + ); + + u32 keypress_bits = ( + ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) | + ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) | + ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) | + ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) | + ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) | + ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) | + ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) | + ( (u32)(input->getLeftState() & 0x1) << 7) | + ( (u32)(input->getRightState() & 0x1) << 8) | + ( (u32)(isKeyDown(KeyType::ZOOM) & 0x1) << 9) + ); #ifdef ANDROID /* For Android, simulate holding down AUX1 (fast move) if the user has @@ -1764,15 +1788,17 @@ void Game::updatePlayerControl(const CameraOrientation &cam) client->setPlayerControl(control); player->keyPressed = keypress_bits; - // tt.stop(); + //tt.stop(); } + inline void Game::step(f32 *dtime) { - bool can_be_and_is_paused = (simple_singleplayer_mode && g_menumgr.pausesGame()); + bool can_be_and_is_paused = + (simple_singleplayer_mode && g_menumgr.pausesGame()); if (can_be_and_is_paused) { // This is for a singleplayer server - *dtime = 0; // No time passes + *dtime = 0; // No time passes } else { if (server) server->step(*dtime); @@ -1782,24 +1808,24 @@ inline void Game::step(f32 *dtime) } const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = { - {&Game::handleClientEvent_None}, - {&Game::handleClientEvent_PlayerDamage}, - {&Game::handleClientEvent_PlayerForceMove}, - {&Game::handleClientEvent_Deathscreen}, - {&Game::handleClientEvent_ShowFormSpec}, - {&Game::handleClientEvent_ShowLocalFormSpec}, - {&Game::handleClientEvent_HandleParticleEvent}, - {&Game::handleClientEvent_HandleParticleEvent}, - {&Game::handleClientEvent_HandleParticleEvent}, - {&Game::handleClientEvent_HudAdd}, - {&Game::handleClientEvent_HudRemove}, - {&Game::handleClientEvent_HudChange}, - {&Game::handleClientEvent_SetSky}, - {&Game::handleClientEvent_SetSun}, - {&Game::handleClientEvent_SetMoon}, - {&Game::handleClientEvent_SetStars}, - {&Game::handleClientEvent_OverrideDayNigthRatio}, - {&Game::handleClientEvent_CloudParams}, + {&Game::handleClientEvent_None}, + {&Game::handleClientEvent_PlayerDamage}, + {&Game::handleClientEvent_PlayerForceMove}, + {&Game::handleClientEvent_Deathscreen}, + {&Game::handleClientEvent_ShowFormSpec}, + {&Game::handleClientEvent_ShowLocalFormSpec}, + {&Game::handleClientEvent_HandleParticleEvent}, + {&Game::handleClientEvent_HandleParticleEvent}, + {&Game::handleClientEvent_HandleParticleEvent}, + {&Game::handleClientEvent_HudAdd}, + {&Game::handleClientEvent_HudRemove}, + {&Game::handleClientEvent_HudChange}, + {&Game::handleClientEvent_SetSky}, + {&Game::handleClientEvent_SetSun}, + {&Game::handleClientEvent_SetMoon}, + {&Game::handleClientEvent_SetStars}, + {&Game::handleClientEvent_OverrideDayNigthRatio}, + {&Game::handleClientEvent_CloudParams}, }; void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam) @@ -1821,7 +1847,7 @@ void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation player->hurt_tilt_timer = 1.5f; player->hurt_tilt_strength = - rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f); + rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f); } // Play damage sound @@ -1854,21 +1880,19 @@ void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation { if (event->show_formspec.formspec->empty()) { auto formspec = m_game_ui->getFormspecGUI(); - if (formspec && (event->show_formspec.formname->empty() || - *(event->show_formspec.formname) == - m_game_ui->getFormspecName())) { + if (formspec && (event->show_formspec.formname->empty() + || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) { formspec->quitMenu(); } } else { FormspecFormSource *fs_src = - new FormspecFormSource(*(event->show_formspec.formspec)); - TextDestPlayerInventory *txt_dst = new TextDestPlayerInventory( - client, *(event->show_formspec.formname)); + new FormspecFormSource(*(event->show_formspec.formspec)); + TextDestPlayerInventory *txt_dst = + new TextDestPlayerInventory(client, *(event->show_formspec.formname)); - auto *&formspec = m_game_ui->updateFormspec( - *(event->show_formspec.formname)); - GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, - txt_dst, client->getFormspecPrepend()); + auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname)); + GUIFormSpecMenu::create(formspec, client, &input->joystick, + fs_src, txt_dst, client->getFormspecPrepend()); } delete event->show_formspec.formspec; @@ -1877,10 +1901,9 @@ void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam) { - FormspecFormSource *fs_src = - new FormspecFormSource(*event->show_formspec.formspec); + FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec); LocalFormspecHandler *txt_dst = - new LocalFormspecHandler(*event->show_formspec.formname, client); + new LocalFormspecHandler(*event->show_formspec.formname, client); GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick, fs_src, txt_dst, client->getFormspecPrepend()); @@ -1888,8 +1911,8 @@ void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrienta delete event->show_formspec.formname; } -void Game::handleClientEvent_HandleParticleEvent( - ClientEvent *event, CameraOrientation *cam) +void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event, + CameraOrientation *cam) { LocalPlayer *player = client->getEnv().getLocalPlayer(); client->getParticleManager()->handleParticleEvent(event, client, player); @@ -1917,20 +1940,20 @@ void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam) } HudElement *e = new HudElement; - e->type = (HudElementType)event->hudadd.type; - e->pos = *event->hudadd.pos; - e->name = *event->hudadd.name; - e->scale = *event->hudadd.scale; - e->text = *event->hudadd.text; + e->type = (HudElementType)event->hudadd.type; + e->pos = *event->hudadd.pos; + e->name = *event->hudadd.name; + e->scale = *event->hudadd.scale; + e->text = *event->hudadd.text; e->number = event->hudadd.number; - e->item = event->hudadd.item; - e->dir = event->hudadd.dir; - e->align = *event->hudadd.align; + e->item = event->hudadd.item; + e->dir = event->hudadd.dir; + e->align = *event->hudadd.align; e->offset = *event->hudadd.offset; e->world_pos = *event->hudadd.world_pos; e->size = *event->hudadd.size; e->z_index = event->hudadd.z_index; - e->text2 = *event->hudadd.text2; + e->text2 = *event->hudadd.text2; hud_server_to_client[server_id] = player->addHud(e); delete event->hudadd.pos; @@ -1967,57 +1990,57 @@ void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *ca } switch (event->hudchange.stat) { - case HUD_STAT_POS: - e->pos = *event->hudchange.v2fdata; - break; + case HUD_STAT_POS: + e->pos = *event->hudchange.v2fdata; + break; - case HUD_STAT_NAME: - e->name = *event->hudchange.sdata; - break; + case HUD_STAT_NAME: + e->name = *event->hudchange.sdata; + break; - case HUD_STAT_SCALE: - e->scale = *event->hudchange.v2fdata; - break; + case HUD_STAT_SCALE: + e->scale = *event->hudchange.v2fdata; + break; - case HUD_STAT_TEXT: - e->text = *event->hudchange.sdata; - break; + case HUD_STAT_TEXT: + e->text = *event->hudchange.sdata; + break; - case HUD_STAT_NUMBER: - e->number = event->hudchange.data; - break; + case HUD_STAT_NUMBER: + e->number = event->hudchange.data; + break; - case HUD_STAT_ITEM: - e->item = event->hudchange.data; - break; + case HUD_STAT_ITEM: + e->item = event->hudchange.data; + break; - case HUD_STAT_DIR: - e->dir = event->hudchange.data; - break; + case HUD_STAT_DIR: + e->dir = event->hudchange.data; + break; - case HUD_STAT_ALIGN: - e->align = *event->hudchange.v2fdata; - break; + case HUD_STAT_ALIGN: + e->align = *event->hudchange.v2fdata; + break; - case HUD_STAT_OFFSET: - e->offset = *event->hudchange.v2fdata; - break; + case HUD_STAT_OFFSET: + e->offset = *event->hudchange.v2fdata; + break; - case HUD_STAT_WORLD_POS: - e->world_pos = *event->hudchange.v3fdata; - break; + case HUD_STAT_WORLD_POS: + e->world_pos = *event->hudchange.v3fdata; + break; - case HUD_STAT_SIZE: - e->size = *event->hudchange.v2s32data; - break; + case HUD_STAT_SIZE: + e->size = *event->hudchange.v2s32data; + break; - case HUD_STAT_Z_INDEX: - e->z_index = event->hudchange.data; - break; + case HUD_STAT_Z_INDEX: + e->z_index = event->hudchange.data; + break; - case HUD_STAT_TEXT2: - e->text2 = *event->hudchange.sdata; - break; + case HUD_STAT_TEXT2: + e->text2 = *event->hudchange.sdata; + break; } delete event->hudchange.v3fdata; @@ -2044,9 +2067,11 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam) sky->setVisible(true); // Update mesh based skybox colours if applicable. sky->setSkyColors(event->set_sky->sky_color); - sky->setHorizonTint(event->set_sky->fog_sun_tint, - event->set_sky->fog_moon_tint, - event->set_sky->fog_tint_type); + sky->setHorizonTint( + event->set_sky->fog_sun_tint, + event->set_sky->fog_moon_tint, + event->set_sky->fog_tint_type + ); } else if (event->set_sky->type == "skybox" && event->set_sky->textures.size() == 6) { // Disable the dyanmic mesh skybox: @@ -2054,23 +2079,27 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam) // Set fog colors: sky->setFallbackBgColor(event->set_sky->bgcolor); // Set sunrise and sunset fog tinting: - sky->setHorizonTint(event->set_sky->fog_sun_tint, - event->set_sky->fog_moon_tint, - event->set_sky->fog_tint_type); + sky->setHorizonTint( + event->set_sky->fog_sun_tint, + event->set_sky->fog_moon_tint, + event->set_sky->fog_tint_type + ); // Add textures to skybox. for (int i = 0; i < 6; i++) - sky->addTextureToSkybox( - event->set_sky->textures[i], i, texture_src); + sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src); } else { // Handle everything else as plain color. if (event->set_sky->type != "plain") - infostream << "Unknown sky type: " << (event->set_sky->type) - << std::endl; + infostream << "Unknown sky type: " + << (event->set_sky->type) << std::endl; sky->setVisible(false); sky->setFallbackBgColor(event->set_sky->bgcolor); // Disable directional sun/moon tinting on plain or invalid skyboxes. - sky->setHorizonTint(event->set_sky->bgcolor, event->set_sky->bgcolor, - "custom"); + sky->setHorizonTint( + event->set_sky->bgcolor, + event->set_sky->bgcolor, + "custom" + ); } delete event->set_sky; } @@ -2078,8 +2107,8 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam) void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam) { sky->setSunVisible(event->sun_params->visible); - sky->setSunTexture(event->sun_params->texture, event->sun_params->tonemap, - texture_src); + sky->setSunTexture(event->sun_params->texture, + event->sun_params->tonemap, texture_src); sky->setSunScale(event->sun_params->scale); sky->setSunriseVisible(event->sun_params->sunrise_visible); sky->setSunriseTexture(event->sun_params->sunrise, texture_src); @@ -2089,8 +2118,8 @@ void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam) void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam) { sky->setMoonVisible(event->moon_params->visible); - sky->setMoonTexture(event->moon_params->texture, event->moon_params->tonemap, - texture_src); + sky->setMoonTexture(event->moon_params->texture, + event->moon_params->tonemap, texture_src); sky->setMoonScale(event->moon_params->scale); delete event->moon_params; } @@ -2104,12 +2133,12 @@ void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam delete event->star_params; } -void Game::handleClientEvent_OverrideDayNigthRatio( - ClientEvent *event, CameraOrientation *cam) +void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event, + CameraOrientation *cam) { client->getEnv().setDayNightRatioOverride( - event->override_day_night_ratio.do_override, - event->override_day_night_ratio.ratio_f * 1000.0f); + event->override_day_night_ratio.do_override, + event->override_day_night_ratio.ratio_f * 1000.0f); } void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam) @@ -2129,9 +2158,8 @@ void Game::processClientEvents(CameraOrientation *cam) { while (client->hasClientEvents()) { std::unique_ptr event(client->getClientEvent()); - FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, - "Invalid clientevent type"); - const ClientEventHandler &evHandler = clientEventHandler[event->type]; + FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type"); + const ClientEventHandler& evHandler = clientEventHandler[event->type]; (this->*evHandler.handler)(event.get(), cam); } } @@ -2153,7 +2181,7 @@ void Game::updateChat(f32 dtime, const v2u32 &screensize) // Display all messages in a static text element m_game_ui->setChatText(chat_backend->getRecentChat(), - chat_backend->getRecentBuffer().getLineCount()); + chat_backend->getRecentBuffer().getLineCount()); } void Game::updateCamera(u32 busy_time, f32 dtime) @@ -2173,11 +2201,11 @@ void Game::updateCamera(u32 busy_time, f32 dtime) } ToolCapabilities playeritem_toolcap = - playeritem.getToolCapabilities(itemdef_manager); + playeritem.getToolCapabilities(itemdef_manager); v3s16 old_camera_offset = camera->getOffset(); - if (wasKeyDown(KeyType::CAMERA_MODE) && !g_settings->getBool("freecam")) { + if (wasKeyDown(KeyType::CAMERA_MODE) && ! g_settings->getBool("freecam")) { camera->toggleCameraMode(); updatePlayerCAOVisibility(); } @@ -2216,20 +2244,18 @@ void Game::updatePlayerCAOVisibility() GenericCAO *playercao = player->getCAO(); if (!playercao) return; - playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST || - g_settings->getBool("freecam")); - playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST || - g_settings->getBool("freecam")); + playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST || g_settings->getBool("freecam")); + playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST || g_settings->getBool("freecam")); } void Game::updateSound(f32 dtime) { // Update sound listener v3s16 camera_offset = camera->getOffset(); - sound->updateListener(camera->getCameraNode()->getPosition() + - intToFloat(camera_offset, BS), - v3f(0, 0, 0), // velocity - camera->getDirection(), camera->getCameraNode()->getUpVector()); + sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS), + v3f(0, 0, 0), // velocity + camera->getDirection(), + camera->getCameraNode()->getUpVector()); bool mute_sound = g_settings->getBool("mute_sound"); if (mute_sound) { @@ -2259,12 +2285,13 @@ void Game::updateSound(f32 dtime) soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep; } + void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) { LocalPlayer *player = client->getEnv().getLocalPlayer(); const v3f camera_direction = camera->getDirection(); - const v3s16 camera_offset = camera->getOffset(); + const v3s16 camera_offset = camera->getOffset(); /* Calculate what block is the crosshair pointing to @@ -2275,7 +2302,7 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager); f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager)); - + if (g_settings->getBool("increase_tool_range")) d += 2; if (g_settings->getBool("increase_tool_range_plus")) @@ -2305,17 +2332,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) { shootline = g_touchscreengui->getShootline(); // Scale shootline to the acual distance the player can reach - shootline.end = shootline.start + - shootline.getVector().normalize() * BS * d; + shootline.end = shootline.start + + shootline.getVector().normalize() * BS * d; shootline.start += intToFloat(camera_offset, BS); shootline.end += intToFloat(camera_offset, BS); } #endif - PointedThing pointed = - updatePointedThing(shootline, selected_def.liquids_pointable, - !runData.ldown_for_dig, camera_offset); + PointedThing pointed = updatePointedThing(shootline, + selected_def.liquids_pointable, + !runData.ldown_for_dig, + camera_offset); if (pointed != runData.pointed_old) { infostream << "Pointing at " << pointed.dump() << std::endl; @@ -2335,19 +2363,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) if (runData.digging) { if (input->getLeftReleased()) { infostream << "Left button released" - << " (stopped digging)" << std::endl; + << " (stopped digging)" << std::endl; runData.digging = false; } else if (pointed != runData.pointed_old) { - if (pointed.type == POINTEDTHING_NODE && - runData.pointed_old.type == POINTEDTHING_NODE && - pointed.node_undersurface == - runData.pointed_old - .node_undersurface) { + if (pointed.type == POINTEDTHING_NODE + && runData.pointed_old.type == POINTEDTHING_NODE + && pointed.node_undersurface + == runData.pointed_old.node_undersurface) { // Still pointing to the same node, but a different face. // Don't reset. } else { infostream << "Pointing away from node" - << " (stopped digging)" << std::endl; + << " (stopped digging)" << std::endl; runData.digging = false; hud->updateSelectionMesh(camera_offset); } @@ -2373,22 +2400,19 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) soundmaker->m_player_leftpunch_sound.name = ""; // Prepare for repeating, unless we're not supposed to - if ((input->getRightState() || g_settings->getBool("autoplace")) && - !g_settings->getBool("safe_dig_and_place")) + if ((input->getRightState() || g_settings->getBool("autoplace")) && !g_settings->getBool("safe_dig_and_place")) runData.repeat_rightclick_timer += dtime; else runData.repeat_rightclick_timer = 0; if (selected_def.usable && input->getLeftState()) { - if (input->getLeftClicked() && - (!client->modsLoaded() || - !client->getScript()->on_item_use( - selected_item, pointed))) + if (input->getLeftClicked() && (!client->modsLoaded() + || !client->getScript()->on_item_use(selected_item, pointed))) client->interact(INTERACT_USE, pointed); } else if (pointed.type == POINTEDTHING_NODE) { handlePointingAtNode(pointed, selected_item, hand_item, dtime); } else if (pointed.type == POINTEDTHING_OBJECT) { - v3f player_position = player->getPosition(); + v3f player_position = player->getPosition(); handlePointingAtObject(pointed, tool_item, player_position, show_debug); } else if (input->getLeftState()) { // When button is held down in air, show continuous animation @@ -2412,14 +2436,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) input->resetRightReleased(); } -PointedThing Game::updatePointedThing(const core::line3d &shootline, - bool liquids_pointable, bool look_for_object, const v3s16 &camera_offset) + +PointedThing Game::updatePointedThing( + const core::line3d &shootline, + bool liquids_pointable, + bool look_for_object, + const v3s16 &camera_offset) { std::vector *selectionboxes = hud->getSelectionBoxes(); selectionboxes->clear(); hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0)); - static thread_local const bool show_entity_selectionbox = - g_settings->getBool("show_entity_selectionbox"); + static thread_local const bool show_entity_selectionbox = g_settings->getBool( + "show_entity_selectionbox"); ClientEnvironment &env = client->getEnv(); ClientMap &map = env.getClientMap(); @@ -2427,20 +2455,16 @@ PointedThing Game::updatePointedThing(const core::line3d &shootline, runData.selected_object = NULL; hud->pointing_at_object = false; - RaycastState s(shootline, look_for_object, liquids_pointable, - !g_settings->getBool("dont_point_nodes")); + RaycastState s(shootline, look_for_object, liquids_pointable, ! g_settings->getBool("dont_point_nodes")); PointedThing result; env.continueRaycast(&s, &result); if (result.type == POINTEDTHING_OBJECT) { hud->pointing_at_object = true; - runData.selected_object = - client->getEnv().getActiveObject(result.object_id); + runData.selected_object = client->getEnv().getActiveObject(result.object_id); aabb3f selection_box; - if (show_entity_selectionbox && - runData.selected_object->doShowSelectionBox() && - runData.selected_object->getSelectionBox( - &selection_box)) { + if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() && + runData.selected_object->getSelectionBox(&selection_box)) { v3f pos = runData.selected_object->getPosition(); selectionboxes->push_back(aabb3f(selection_box)); hud->setSelectionPos(pos, camera_offset); @@ -2450,21 +2474,22 @@ PointedThing Game::updatePointedThing(const core::line3d &shootline, MapNode n = map.getNode(result.node_undersurface); std::vector boxes; n.getSelectionBoxes(nodedef, &boxes, - n.getNeighbors(result.node_undersurface, &map)); + n.getNeighbors(result.node_undersurface, &map)); f32 d = 0.002 * BS; for (std::vector::const_iterator i = boxes.begin(); - i != boxes.end(); ++i) { + i != boxes.end(); ++i) { aabb3f box = *i; box.MinEdge -= v3f(d, d, d); box.MaxEdge += v3f(d, d, d); selectionboxes->push_back(box); } - hud->setSelectionPos( - intToFloat(result.node_undersurface, BS), camera_offset); - hud->setSelectedFaceNormal(v3f(result.intersection_normal.X, - result.intersection_normal.Y, - result.intersection_normal.Z)); + hud->setSelectionPos(intToFloat(result.node_undersurface, BS), + camera_offset); + hud->setSelectedFaceNormal(v3f( + result.intersection_normal.X, + result.intersection_normal.Y, + result.intersection_normal.Z)); } // Update selection mesh light level and vertex colors @@ -2490,15 +2515,13 @@ PointedThing Game::updatePointedThing(const core::line3d &shootline, // Modify final color a bit with time u32 timer = porting::getTimeMs() % 5000; - float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5)); + float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5)); float sin_r = 0.08f * std::sin(timerf); float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f); float sin_b = 0.08f * std::sin(timerf + irr::core::PI); c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255)); - c.setGreen(core::clamp( - core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255)); - c.setBlue(core::clamp( - core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255)); + c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255)); + c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255)); // Set mesh final color hud->setSelectionMeshColor(c); @@ -2514,8 +2537,9 @@ void Game::handlePointingAtNothing(const ItemStack &playerItem) client->interact(INTERACT_ACTIVATE, fauxPointed); } + void Game::handlePointingAtNode(const PointedThing &pointed, - const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime) + const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime) { v3s16 nodepos = pointed.node_undersurface; v3s16 neighbourpos = pointed.node_abovesurface; @@ -2526,10 +2550,10 @@ void Game::handlePointingAtNode(const PointedThing &pointed, ClientMap &map = client->getEnv().getClientMap(); - if (((runData.nodig_delay_timer <= 0.0 || g_settings->getBool("fastdig")) && - (input->getLeftState() || g_settings->getBool("autodig")) && - !runData.digging_blocked && - client->checkPrivilege("interact"))) { + if (((runData.nodig_delay_timer <= 0.0 || g_settings->getBool("fastdig")) && (input->getLeftState() || g_settings->getBool("autodig")) + && !runData.digging_blocked + && client->checkPrivilege("interact")) + ) { handleDigging(pointed, nodepos, selected_item, hand_item, dtime); } @@ -2537,30 +2561,25 @@ void Game::handlePointingAtNode(const PointedThing &pointed, NodeMetadata *meta = map.getNodeMetadata(nodepos); if (meta) { - m_game_ui->setInfoText(unescape_translate( - utf8_to_wide(meta->getString("infotext")))); + m_game_ui->setInfoText(unescape_translate(utf8_to_wide( + meta->getString("infotext")))); } else { MapNode n = map.getNode(nodepos); if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") { - m_game_ui->setInfoText( - L"Unknown node: " + - utf8_to_wide(nodedef_manager->get(n).name)); + m_game_ui->setInfoText(L"Unknown node: " + + utf8_to_wide(nodedef_manager->get(n).name)); } } - if ((input->getRightState() || g_settings->getBool("autoplace")) && + if ((input->getRightState() || g_settings->getBool("autoplace")) && (input->getRightClicked() || - (runData.repeat_rightclick_timer >= - (g_settings->getBool("fastplace") - ? 0 - : m_repeat_right_click_time))) && + (runData.repeat_rightclick_timer >= (g_settings->getBool("fastplace") ? 0 : m_repeat_right_click_time))) && client->checkPrivilege("interact")) { runData.repeat_rightclick_timer = 0; infostream << "Ground right-clicked" << std::endl; - camera->setDigging( - 1); // right click animation (always shown for feedback) + camera->setDigging(1); // right click animation (always shown for feedback) soundmaker->m_player_rightpunch_sound = SimpleSoundSpec(); @@ -2569,8 +2588,8 @@ void Game::handlePointingAtNode(const PointedThing &pointed, // And also set the sound and send the interact // But first check for meta formspec and rightclickable auto &def = selected_item.getDefinition(itemdef_manager); - bool placed = nodePlacement( - def, selected_item, nodepos, neighbourpos, pointed, meta); + bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos, + pointed, meta); if (placed && client->modsLoaded()) client->getScript()->on_placenode(pointed, def); @@ -2578,9 +2597,8 @@ void Game::handlePointingAtNode(const PointedThing &pointed, } bool Game::nodePlacement(const ItemDefinition &selected_def, - const ItemStack &selected_item, const v3s16 &nodepos, - const v3s16 &neighbourpos, const PointedThing &pointed, - const NodeMetadata *meta) + const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos, + const PointedThing &pointed, const NodeMetadata *meta) { std::string prediction = selected_def.node_placement_prediction; const NodeDefManager *nodedef = client->ndef(); @@ -2595,8 +2613,8 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, } // formspec in meta - if (meta && !meta->getString("formspec").empty() && !input->isRandom() && - !isKeyDown(KeyType::SNEAK)) { + if (meta && !meta->getString("formspec").empty() && !input->isRandom() + && !isKeyDown(KeyType::SNEAK)) { // on_rightclick callbacks are called anyway if (nodedef_manager->get(map.getNode(nodepos)).rightclickable) client->interact(INTERACT_PLACE, pointed); @@ -2607,12 +2625,12 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, inventoryloc.setNodeMeta(nodepos); NodeMetadataFormSource *fs_src = new NodeMetadataFormSource( - &client->getEnv().getClientMap(), nodepos); + &client->getEnv().getClientMap(), nodepos); TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client); auto *&formspec = m_game_ui->updateFormspec(""); GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, - txt_dst, client->getFormspecPrepend()); + txt_dst, client->getFormspecPrepend()); formspec->setFormSpec(meta->getString("formspec"), inventoryloc); return false; @@ -2620,14 +2638,15 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, // on_rightclick callback if (prediction.empty() || (nodedef->get(node).rightclickable && - !isKeyDown(KeyType::SNEAK))) { + !isKeyDown(KeyType::SNEAK))) { // Report to server client->interact(INTERACT_PLACE, pointed); return false; } - verbosestream << "Node placement prediction for " << selected_def.name << " is " - << prediction << std::endl; + verbosestream << "Node placement prediction for " + << selected_def.name << " is " + << prediction << std::endl; v3s16 p = neighbourpos; // Place inside node itself if buildable_to @@ -2651,8 +2670,9 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, if (!found) { errorstream << "Node placement prediction failed for " - << selected_def.name << " (places " << prediction - << ") - Name not known" << std::endl; + << selected_def.name << " (places " + << prediction + << ") - Name not known" << std::endl; // Handle this as if prediction was empty // Report to server client->interact(INTERACT_PLACE, pointed); @@ -2679,9 +2699,7 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, if (predicted_f.param_type_2 == CPT2_FACEDIR || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) { - v3s16 dir = nodepos - - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), - BS); + v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS); if (abs(dir.X) > abs(dir.Z)) { param2 = dir.X < 0 ? 3 : 1; @@ -2692,15 +2710,15 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, assert(param2 <= 5); - // Check attachment if node is in group attached_node - if (((ItemGroupList)predicted_f.groups)["attached_node"] != 0) { + //Check attachment if node is in group attached_node + if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) { static v3s16 wallmounted_dirs[8] = { - v3s16(0, 1, 0), - v3s16(0, -1, 0), - v3s16(1, 0, 0), - v3s16(-1, 0, 0), - v3s16(0, 0, 1), - v3s16(0, 0, -1), + v3s16(0, 1, 0), + v3s16(0, -1, 0), + v3s16(1, 0, 0), + v3s16(-1, 0, 0), + v3s16(0, 0, 1), + v3s16(0, 0, -1), }; v3s16 pp; @@ -2718,11 +2736,11 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, } // Apply color - if ((predicted_f.param_type_2 == CPT2_COLOR || - predicted_f.param_type_2 == CPT2_COLORED_FACEDIR || - predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) { - const std::string &indexstr = - selected_item.metadata.getString("palette_index", 0); + if ((predicted_f.param_type_2 == CPT2_COLOR + || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR + || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) { + const std::string &indexstr = selected_item.metadata.getString( + "palette_index", 0); if (!indexstr.empty()) { s32 index = mystoi(indexstr); if (predicted_f.param_type_2 == CPT2_COLOR) { @@ -2747,13 +2765,10 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, // NOTE: This is to be eventually implemented by a mod as client-side Lua if (!nodedef->get(n).walkable || g_settings->getBool("enable_build_where_you_stand") || - (client->checkPrivilege("noclip") && - g_settings->getBool("noclip")) || + (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) || (nodedef->get(n).walkable && - neighbourpos != player->getStandingNodePos() + - v3s16(0, 1, 0) && - neighbourpos != player->getStandingNodePos() + - v3s16(0, 2, 0))) { + neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) && + neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) { // This triggers the required mesh update too client->addNode(p, n); // Report to server @@ -2762,24 +2777,24 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, soundmaker->m_player_rightpunch_sound = selected_def.sound_place; return true; } else { - soundmaker->m_player_rightpunch_sound = - selected_def.sound_place_failed; + soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed; return false; } } catch (InvalidPositionException &e) { errorstream << "Node placement prediction failed for " - << selected_def.name << " (places " << prediction - << ") - Position not loaded" << std::endl; + << selected_def.name << " (places " + << prediction + << ") - Position not loaded" << std::endl; soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed; return false; } } -void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &tool_item, - const v3f &player_position, bool show_debug) +void Game::handlePointingAtObject(const PointedThing &pointed, + const ItemStack &tool_item, const v3f &player_position, bool show_debug) { std::wstring infotext = unescape_translate( - utf8_to_wide(runData.selected_object->infoText())); + utf8_to_wide(runData.selected_object->infoText())); if (show_debug) { if (!infotext.empty()) { @@ -2794,8 +2809,7 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack & bool do_punch = false; bool do_punch_damage = false; - if (runData.object_hit_delay_timer <= 0.0 || - g_settings->getBool("spamclick")) { + if (runData.object_hit_delay_timer <= 0.0 || g_settings->getBool("spamclick")) { do_punch = true; do_punch_damage = true; runData.object_hit_delay_timer = object_hit_delay; @@ -2824,10 +2838,11 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack & } } else if (input->getRightClicked()) { infostream << "Right-clicked object" << std::endl; - client->interact(INTERACT_PLACE, pointed); // place + client->interact(INTERACT_PLACE, pointed); // place } } + void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime) { @@ -2855,14 +2870,13 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, runData.dig_time_complete = params.time; if (m_cache_enable_particles) { - const ContentFeatures &features = - client->getNodeDefManager()->get(n); - client->getParticleManager()->addNodeParticle( - client, player, nodepos, n, features); + const ContentFeatures &features = client->getNodeDefManager()->get(n); + client->getParticleManager()->addNodeParticle(client, + player, nodepos, n, features); } } - - if (g_settings->getBool("instant_break")) { + + if(g_settings->getBool("instant_break")) { runData.dig_time_complete = 0; runData.dig_instantly = true; } @@ -2877,8 +2891,9 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, } if (!runData.dig_instantly) { - runData.dig_index = (float)crack_animation_length * runData.dig_time / - runData.dig_time_complete; + runData.dig_index = (float)crack_animation_length + * runData.dig_time + / runData.dig_time_complete; } else { // This is for e.g. torches runData.dig_index = crack_animation_length; @@ -2902,8 +2917,8 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, // Don't show cracks if not diggable if (runData.dig_time_complete >= 100000.0) { } else if (runData.dig_index < crack_animation_length) { - // TimeTaker timer("client.setTempMod"); - // infostream<<"dig_index="<modsLoaded() && client->getScript()->on_dignode( - nodepos, wasnode)) { + if (client->modsLoaded() && + client->getScript()->on_dignode(nodepos, wasnode)) { return; } @@ -2938,8 +2953,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, client->removeNode(nodepos); } else if (!f.node_dig_prediction.empty()) { content_t id; - bool found = client->ndef()->getId( - f.node_dig_prediction, id); + bool found = client->ndef()->getId(f.node_dig_prediction, id); if (found) client->addNode(nodepos, id, true); } @@ -2950,11 +2964,12 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, if (m_cache_enable_particles) { const ContentFeatures &features = - client->getNodeDefManager()->get(wasnode); - client->getParticleManager()->addDiggingParticles( - client, player, nodepos, wasnode, features); + client->getNodeDefManager()->get(wasnode); + client->getParticleManager()->addDiggingParticles(client, + player, nodepos, wasnode, features); } + // Send event to trigger sound client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode)); } @@ -2966,9 +2981,10 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, client->setCrack(-1, nodepos); } - camera->setDigging(0); // left click animation + camera->setDigging(0); // left click animation } + void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, const CameraOrientation &cam) { @@ -2998,13 +3014,10 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, sunlight_seen = true; } else { float old_brightness = sky->getBrightness(); - direct_brightness = - client->getEnv().getClientMap().getBackgroundBrightness( - MYMIN(runData.fog_range * 1.2, 60 * BS), - daynight_ratio, - (int)(old_brightness * 255.5), - &sunlight_seen) / - 255.0; + direct_brightness = client->getEnv().getClientMap() + .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS), + daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen) + / 255.0; } float time_of_day_smooth = runData.time_of_day_smooth; @@ -3019,16 +3032,17 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, time_of_day_smooth = time_of_day; if (time_of_day_smooth > 0.8 && time_of_day < 0.2) - time_of_day_smooth = time_of_day_smooth * (1.0 - todsm) + - (time_of_day + 1.0) * todsm; + time_of_day_smooth = time_of_day_smooth * (1.0 - todsm) + + (time_of_day + 1.0) * todsm; else - time_of_day_smooth = - time_of_day_smooth * (1.0 - todsm) + time_of_day * todsm; + time_of_day_smooth = time_of_day_smooth * (1.0 - todsm) + + time_of_day * todsm; runData.time_of_day_smooth = time_of_day_smooth; - sky->update(time_of_day_smooth, time_brightness, direct_brightness, sunlight_seen, - camera->getCameraMode(), player->getYaw(), player->getPitch()); + sky->update(time_of_day_smooth, time_brightness, direct_brightness, + sunlight_seen, camera->getCameraMode(), player->getYaw(), + player->getPitch()); /* Update clouds @@ -3039,26 +3053,20 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, clouds->step(dtime); // camera->getPosition is not enough for 3rd person views v3f camera_node_position = camera->getCameraNode()->getPosition(); - v3s16 camera_offset = camera->getOffset(); - camera_node_position.X = - camera_node_position.X + camera_offset.X * BS; - camera_node_position.Y = - camera_node_position.Y + camera_offset.Y * BS; - camera_node_position.Z = - camera_node_position.Z + camera_offset.Z * BS; - clouds->update(camera_node_position, sky->getCloudColor()); + v3s16 camera_offset = camera->getOffset(); + camera_node_position.X = camera_node_position.X + camera_offset.X * BS; + camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS; + camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS; + clouds->update(camera_node_position, + sky->getCloudColor()); if (clouds->isCameraInsideCloud() && m_cache_enable_fog) { // if inside clouds, and fog enabled, use that as sky // color(s) - video::SColor clouds_dark = - clouds->getColor().getInterpolated( - video::SColor(255, 0, 0, - 0), - 0.9); + video::SColor clouds_dark = clouds->getColor() + .getInterpolated(video::SColor(255, 0, 0, 0), 0.9); sky->overrideColors(clouds_dark, clouds->getColor()); sky->setInClouds(true); - runData.fog_range = std::fmin( - runData.fog_range * 0.5f, 32.0f * BS); + runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS); // do not draw clouds after all clouds->setVisible(false); } @@ -3077,17 +3085,24 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, */ if (m_cache_enable_fog) { - driver->setFog(sky->getBgColor(), video::EFT_FOG_LINEAR, + driver->setFog( + sky->getBgColor(), + video::EFT_FOG_LINEAR, runData.fog_range * m_cache_fog_start, - runData.fog_range * 1.0, 0.01, + runData.fog_range * 1.0, + 0.01, false, // pixel fog - true // range fog + true // range fog ); } else { - driver->setFog(sky->getBgColor(), video::EFT_FOG_LINEAR, 100000 * BS, - 110000 * BS, 0.01f, + driver->setFog( + sky->getBgColor(), + video::EFT_FOG_LINEAR, + 100000 * BS, + 110000 * BS, + 0.01f, false, // pixel fog - false // range fog + false // range fog ); } @@ -3120,17 +3135,15 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, runData.update_draw_list_timer += dtime; v3f camera_direction = camera->getDirection(); - if (runData.update_draw_list_timer >= 0.2 || - runData.update_draw_list_last_cam_dir.getDistanceFrom( - camera_direction) > 0.2 || - m_camera_offset_changed) { + if (runData.update_draw_list_timer >= 0.2 + || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 + || m_camera_offset_changed) { runData.update_draw_list_timer = 0; client->getEnv().getClientMap().updateDrawList(); runData.update_draw_list_last_cam_dir = camera_direction; } - m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, - gui_chat_console, dtime); + m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime); /* make sure menu is on top @@ -3149,9 +3162,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, auto &loc = formspec->getFormspecLocation(); if (loc.type == InventoryLocation::NODEMETA) { - NodeMetadata *meta = - client->getEnv().getClientMap().getNodeMetadata( - loc.p); + NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p); if (!meta || meta->getString("formspec").empty()) { formspec->quitMenu(); break; @@ -3171,10 +3182,11 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, driver->beginScene(true, true, skycolor); bool draw_wield_tool = (m_game_ui->m_flags.show_hud && - (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) && - (camera->getCameraMode() == CAMERA_MODE_FIRST)); - bool draw_crosshair = ((player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) && - (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT)); + (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) && + (camera->getCameraMode() == CAMERA_MODE_FIRST)); + bool draw_crosshair = ( + (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) && + (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT)); #ifdef HAVE_TOUCHSCREENGUI try { draw_crosshair = !g_settings->getBool("touchtarget"); @@ -3182,9 +3194,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, } #endif RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud, - m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair, - g_settings->getBool("enable_tracers"), - g_settings->getBool("enable_esp")); + m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair, g_settings->getBool("enable_tracers"), g_settings->getBool("enable_esp")); /* Profiler graph @@ -3196,7 +3206,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, Cheat menu */ - if (!gui_chat_console->isOpen()) { + if (! gui_chat_console->isOpen()) { if (m_game_ui->m_flags.show_cheat_menu) m_cheat_menu->draw(driver, m_game_ui->m_flags.show_debug); if (g_settings->getBool("cheat_hud")) @@ -3207,10 +3217,8 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, */ if (runData.damage_flash > 0.0f) { video::SColor color(runData.damage_flash, 180, 0, 0); - if (!g_settings->getBool("no_hurt_cam")) - driver->draw2DRectangle(color, - core::rect(0, 0, screensize.X, screensize.Y), - NULL); + if (! g_settings->getBool("no_hurt_cam")) + driver->draw2DRectangle(color, core::rect(0, 0, screensize.X, screensize.Y), NULL); runData.damage_flash -= 384.0f * dtime; } @@ -3236,7 +3244,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, /* End scene */ - + driver->endScene(); stats->drawtime = tt_draw.stop(true); @@ -3252,6 +3260,8 @@ inline void Game::updateProfilerGraphs(ProfilerGraph *graph) graph->put(values); } + + /**************************************************************************** Misc ****************************************************************************/ @@ -3265,15 +3275,14 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime) u32 time = device->getTimer()->getTime(); u32 last_time = fps_timings->last_time; - if (time > last_time) // Make sure time hasn't overflowed + if (time > last_time) // Make sure time hasn't overflowed fps_timings->busy_time = time - last_time; else fps_timings->busy_time = 0; - u32 frametime_min = - 1000 / - (g_menumgr.pausesGame() ? g_settings->getFloat("pause_fps_max") - : g_settings->getFloat("fps_max")); + u32 frametime_min = 1000 / (g_menumgr.pausesGame() + ? g_settings->getFloat("pause_fps_max") + : g_settings->getFloat("fps_max")); if (fps_timings->busy_time < frametime_min) { fps_timings->sleep_time = frametime_min - fps_timings->busy_time; @@ -3291,7 +3300,7 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime) device->getTimer()->tick(); // Update device timer time = device->getTimer()->getTime(); - if (time > last_time) // Make sure last_time hasn't overflowed + if (time > last_time) // Make sure last_time hasn't overflowed *dtime = (time - last_time) / 1000.0; else *dtime = 0; @@ -3302,8 +3311,8 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime) void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds) { const wchar_t *wmsg = wgettext(msg); - RenderingEngine::draw_load_screen( - wmsg, guienv, texture_src, dtime, percent, draw_clouds); + RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent, + draw_clouds); delete[] wmsg; } @@ -3314,12 +3323,12 @@ void Game::settingChangedCallback(const std::string &setting_name, void *data) void Game::updateAllMapBlocksCallback(const std::string &setting_name, void *data) { - ((Game *)data)->client->updateAllMapBlocks(); + ((Game *) data)->client->updateAllMapBlocks(); } void Game::freecamChangedCallback(const std::string &setting_name, void *data) { - Game *game = (Game *)data; + Game *game = (Game *) data; LocalPlayer *player = game->client->getEnv().getLocalPlayer(); if (g_settings->getBool("freecam")) { game->camera->setCameraMode(CAMERA_MODE_FIRST); @@ -3332,25 +3341,23 @@ void Game::freecamChangedCallback(const std::string &setting_name, void *data) void Game::readSettings() { - m_cache_doubletap_jump = g_settings->getBool("doubletap_jump"); - m_cache_enable_clouds = g_settings->getBool("enable_clouds"); - m_cache_enable_joysticks = g_settings->getBool("enable_joysticks"); - m_cache_enable_particles = g_settings->getBool("enable_particles"); - m_cache_enable_fog = g_settings->getBool("enable_fog"); - m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity"); - m_cache_joystick_frustum_sensitivity = - g_settings->getFloat("joystick_frustum_sensitivity"); - m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time"); + m_cache_doubletap_jump = g_settings->getBool("doubletap_jump"); + m_cache_enable_clouds = g_settings->getBool("enable_clouds"); + m_cache_enable_joysticks = g_settings->getBool("enable_joysticks"); + m_cache_enable_particles = g_settings->getBool("enable_particles"); + m_cache_enable_fog = g_settings->getBool("enable_fog"); + m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity"); + m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity"); + m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time"); - m_cache_enable_noclip = g_settings->getBool("noclip"); - m_cache_enable_free_move = g_settings->getBool("free_move"); + m_cache_enable_noclip = g_settings->getBool("noclip"); + m_cache_enable_free_move = g_settings->getBool("free_move"); - m_cache_fog_start = g_settings->getFloat("fog_start"); + m_cache_fog_start = g_settings->getFloat("fog_start"); m_cache_cam_smoothing = 0; if (g_settings->getBool("cinematic")) - m_cache_cam_smoothing = - 1 - g_settings->getFloat("cinematic_camera_smoothing"); + m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing"); else m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing"); @@ -3372,40 +3379,41 @@ void Game::extendedResourceCleanup() // Extended resource accounting infostream << "Irrlicht resources after cleanup:" << std::endl; infostream << "\tRemaining meshes : " - << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl; - infostream << "\tRemaining textures : " << driver->getTextureCount() << std::endl; + << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl; + infostream << "\tRemaining textures : " + << driver->getTextureCount() << std::endl; for (unsigned int i = 0; i < driver->getTextureCount(); i++) { irr::video::ITexture *texture = driver->getTextureByIndex(i); infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str() - << std::endl; + << std::endl; } clearTextureNameCache(); - infostream << "\tRemaining materials: " << driver->getMaterialRendererCount() - << " (note: irrlicht doesn't support removing renderers)" << std::endl; + infostream << "\tRemaining materials: " + << driver-> getMaterialRendererCount() + << " (note: irrlicht doesn't support removing renderers)" << std::endl; } void Game::showDeathFormspec() { - static std::string formspec_str = std::string("formspec_version[1]") + - SIZE_TAG "bgcolor[#320000b4;true]" - "label[4.85,1.35;" + - gettext("You died") + - "]" - "button_exit[4,3;3,0.5;btn_respawn;" + - gettext("Respawn") + "]"; + static std::string formspec_str = + std::string("formspec_version[1]") + + SIZE_TAG + "bgcolor[#320000b4;true]" + "label[4.85,1.35;" + gettext("You died") + "]" + "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]" + ; /* Create menu */ /* Note: FormspecFormSource and LocalFormspecHandler * * are deleted by guiFormSpecMenu */ FormspecFormSource *fs_src = new FormspecFormSource(formspec_str); - LocalFormspecHandler *txt_dst = - new LocalFormspecHandler("MT_DEATH_SCREEN", client); + LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client); auto *&formspec = m_game_ui->getFormspecGUI(); - GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, txt_dst, - client->getFormspecPrepend()); + GUIFormSpecMenu::create(formspec, client, &input->joystick, + fs_src, txt_dst, client->getFormspecPrepend()); formspec->setFocus("btn_respawn"); } @@ -3413,53 +3421,59 @@ void Game::showDeathFormspec() void Game::showPauseMenu() { #ifdef __ANDROID__ - static const std::string control_text = - strgettext("Default Controls:\n" - "No menu visible:\n" - "- single tap: button activate\n" - "- double tap: place/use\n" - "- slide finger: look around\n" - "Menu/Inventory visible:\n" - "- double tap (outside):\n" - " -->close\n" - "- touch stack, touch slot:\n" - " --> move stack\n" - "- touch&drag, tap 2nd finger\n" - " --> place single item to slot\n"); + static const std::string control_text = strgettext("Default Controls:\n" + "No menu visible:\n" + "- single tap: button activate\n" + "- double tap: place/use\n" + "- slide finger: look around\n" + "Menu/Inventory visible:\n" + "- double tap (outside):\n" + " -->close\n" + "- touch stack, touch slot:\n" + " --> move stack\n" + "- touch&drag, tap 2nd finger\n" + " --> place single item to slot\n" + ); #else - static const std::string control_text_template = - strgettext("Controls:\n" - "- %s: move forwards\n" - "- %s: move backwards\n" - "- %s: move left\n" - "- %s: move right\n" - "- %s: jump/climb\n" - "- %s: sneak/go down\n" - "- %s: drop item\n" - "- %s: inventory\n" - "- %s: enderchest\n" - "- Mouse: turn/look\n" - "- Mouse left: dig/punch\n" - "- Mouse right: place/use\n" - "- Mouse wheel: select item\n" - "- %s: chat\n" - "- %s: Killaura\n" - "- %s: Freecam\n" - "- %s: Scaffold\n" - "- %s: NextItem\n"); - - char control_text_buf[600]; - - porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), - control_text_template.c_str(), GET_KEY_NAME(keymap_forward), - GET_KEY_NAME(keymap_backward), GET_KEY_NAME(keymap_left), - GET_KEY_NAME(keymap_right), GET_KEY_NAME(keymap_jump), - GET_KEY_NAME(keymap_sneak), GET_KEY_NAME(keymap_drop), - GET_KEY_NAME(keymap_inventory), GET_KEY_NAME(keymap_enderchest), - GET_KEY_NAME(keymap_chat), GET_KEY_NAME(keymap_toggle_killaura), + static const std::string control_text_template = strgettext("Controls:\n" + "- %s: move forwards\n" + "- %s: move backwards\n" + "- %s: move left\n" + "- %s: move right\n" + "- %s: jump/climb\n" + "- %s: sneak/go down\n" + "- %s: drop item\n" + "- %s: inventory\n" + "- %s: enderchest\n" + "- Mouse: turn/look\n" + "- Mouse left: dig/punch\n" + "- Mouse right: place/use\n" + "- Mouse wheel: select item\n" + "- %s: chat\n" + "- %s: Killaura\n" + "- %s: Freecam\n" + "- %s: Scaffold\n" + "- %s: NextItem\n" + ); + + char control_text_buf[600]; + + porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(), + GET_KEY_NAME(keymap_forward), + GET_KEY_NAME(keymap_backward), + GET_KEY_NAME(keymap_left), + GET_KEY_NAME(keymap_right), + GET_KEY_NAME(keymap_jump), + GET_KEY_NAME(keymap_sneak), + GET_KEY_NAME(keymap_drop), + GET_KEY_NAME(keymap_inventory), + GET_KEY_NAME(keymap_enderchest), + GET_KEY_NAME(keymap_chat), + GET_KEY_NAME(keymap_toggle_killaura), GET_KEY_NAME(keymap_toggle_freecam), GET_KEY_NAME(keymap_toggle_scaffold), - GET_KEY_NAME(keymap_toggle_next_item)); + GET_KEY_NAME(keymap_toggle_next_item) + ); std::string control_text = std::string(control_text_buf); str_formspec_escape(control_text); @@ -3468,12 +3482,13 @@ void Game::showPauseMenu() float ypos = simple_singleplayer_mode ? 0.7f : 0.1f; std::ostringstream os; - os << "formspec_version[1]" << SIZE_TAG << "button_exit[4," << (ypos++) - << ";3,0.5;btn_continue;" << strgettext("Continue") << "]"; + os << "formspec_version[1]" << SIZE_TAG + << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;" + << strgettext("Continue") << "]"; if (!simple_singleplayer_mode) { os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;" - << strgettext("Change Password") << "]"; + << strgettext("Change Password") << "]"; } else { os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]"; } @@ -3482,27 +3497,27 @@ void Game::showPauseMenu() #if USE_SOUND if (g_settings->getBool("enable_sound")) { os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;" - << strgettext("Sound Volume") << "]"; + << strgettext("Sound Volume") << "]"; } #endif - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;" - << strgettext("Change Keys") << "]"; + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;" + << strgettext("Change Keys") << "]"; #endif - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;" - << strgettext("Exit to Menu") << "]"; - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;" - << strgettext("Exit to OS") << "]" - << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]" - << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n" - << "\n" - << strgettext("Game info:") << "\n"; + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;" + << strgettext("Exit to Menu") << "]"; + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;" + << strgettext("Exit to OS") << "]" + << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]" + << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n" + << "\n" + << strgettext("Game info:") << "\n"; const std::string &address = client->getAddressName(); static const std::string mode = strgettext("- Mode: "); if (!simple_singleplayer_mode) { Address serverAddress = client->getServerAddress(); if (!address.empty()) { os << mode << strgettext("Remote server") << "\n" - << strgettext("- Address: ") << address; + << strgettext("- Address: ") << address; } else { os << mode << strgettext("Hosting server"); } @@ -3513,24 +3528,21 @@ void Game::showPauseMenu() if (simple_singleplayer_mode || address.empty()) { static const std::string on = strgettext("On"); static const std::string off = strgettext("Off"); - const std::string &damage = - g_settings->getBool("enable_damage") ? on : off; - const std::string &creative = - g_settings->getBool("creative_mode") ? on : off; - const std::string &announced = - g_settings->getBool("server_announce") ? on : off; + const std::string &damage = g_settings->getBool("enable_damage") ? on : off; + const std::string &creative = g_settings->getBool("creative_mode") ? on : off; + const std::string &announced = g_settings->getBool("server_announce") ? on : off; os << strgettext("- Damage: ") << damage << "\n" - << strgettext("- Creative Mode: ") << creative << "\n"; + << strgettext("- Creative Mode: ") << creative << "\n"; if (!simple_singleplayer_mode) { - const std::string &pvp = - g_settings->getBool("enable_pvp") ? on : off; + const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off; //~ PvP = Player versus Player os << strgettext("- PvP: ") << pvp << "\n" - << strgettext("- Public: ") << announced << "\n"; + << strgettext("- Public: ") << announced << "\n"; std::string server_name = g_settings->get("server_name"); str_formspec_escape(server_name); if (announced == on && !server_name.empty()) os << strgettext("- Server Name: ") << server_name; + } } os << ";]"; @@ -3542,8 +3554,8 @@ void Game::showPauseMenu() LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU"); auto *&formspec = m_game_ui->getFormspecGUI(); - GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, txt_dst, - client->getFormspecPrepend()); + GUIFormSpecMenu::create(formspec, client, &input->joystick, + fs_src, txt_dst, client->getFormspecPrepend()); formspec->setFocus("btn_continue"); formspec->doPause = true; } @@ -3556,12 +3568,15 @@ void Game::showPauseMenu() Game *g_game; -void the_game(bool *kill, InputHandler *input, const GameStartData &start_data, - std::string &error_message, ChatBackend &chat_backend, +void the_game(bool *kill, + InputHandler *input, + const GameStartData &start_data, + std::string &error_message, + ChatBackend &chat_backend, bool *reconnect_requested) // Used for local game { Game game; - + g_game = &game; /* Make a copy of the server address because if a local singleplayer server @@ -3572,14 +3587,13 @@ void the_game(bool *kill, InputHandler *input, const GameStartData &start_data, try { if (game.startup(kill, input, start_data, error_message, - reconnect_requested, &chat_backend)) { + reconnect_requested, &chat_backend)) { game.run(); } } catch (SerializationError &e) { - error_message = std::string("A serialization error occurred:\n") + - e.what() + - "\n\nThe server is probably " + error_message = std::string("A serialization error occurred:\n") + + e.what() + "\n\nThe server is probably " " running a different version of " PROJECT_NAME_C "."; errorstream << error_message << std::endl; } catch (ServerError &e) { diff --git a/src/client/game.h b/src/client/game.h index 70286ba85..51accc679 100644 --- a/src/client/game.h +++ b/src/client/game.h @@ -28,7 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., //#include "client/gameui.h" #include "client/inputhandler.h" #include "client/sound.h" -#include "client/tile.h" // For TextureSource +#include "client/tile.h" // For TextureSource #include "client/keys.h" #include "client/joystick_controller.h" #include "clientmap.h" @@ -52,7 +52,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gui/profilergraph.h" #include "mapblock.h" #include "minimap.h" -#include "nodedef.h" // Needed for determining pointing to nodes +#include "nodedef.h" // Needed for determining pointing to nodes #include "nodemetadata.h" #include "particles.h" #include "porting.h" @@ -75,26 +75,23 @@ with this program; if not, write to the Free Software Foundation, Inc., #include class InputHandler; -class ChatBackend; /* to avoid having to include chat.h */ +class ChatBackend; /* to avoid having to include chat.h */ struct SubgameSpec; struct GameStartData; -struct Jitter -{ +struct Jitter { f32 max, min, avg, counter, max_sample, min_sample, max_fraction; }; -struct RunStats -{ +struct RunStats { u32 drawtime; Jitter dtime_jitter, busy_time_jitter; }; -struct CameraOrientation -{ - f32 camera_yaw; // "right/left" - f32 camera_pitch; // "up/down" +struct CameraOrientation { + f32 camera_yaw; // "right/left" + f32 camera_pitch; // "up/down" }; /* @@ -149,10 +146,13 @@ struct TextDestPlayerInventory : public TextDest struct LocalFormspecHandler : public TextDest { - LocalFormspecHandler(const std::string &formname) { m_formname = formname; } + LocalFormspecHandler(const std::string &formname) + { + m_formname = formname; + } - LocalFormspecHandler(const std::string &formname, Client *client) : - m_client(client) + LocalFormspecHandler(const std::string &formname, Client *client): + m_client(client) { m_formname = formname; } @@ -212,10 +212,14 @@ struct LocalFormspecHandler : public TextDest /* Form update callback */ -class NodeMetadataFormSource : public IFormSource +class NodeMetadataFormSource: public IFormSource { public: - NodeMetadataFormSource(ClientMap *map, v3s16 p) : m_map(map), m_p(p) {} + NodeMetadataFormSource(ClientMap *map, v3s16 p): + m_map(map), + m_p(p) + { + } const std::string &getForm() const { static const std::string empty_string = ""; @@ -241,10 +245,13 @@ class NodeMetadataFormSource : public IFormSource v3s16 m_p; }; -class PlayerInventoryFormSource : public IFormSource +class PlayerInventoryFormSource: public IFormSource { public: - PlayerInventoryFormSource(Client *client) : m_client(client) {} + PlayerInventoryFormSource(Client *client): + m_client(client) + { + } const std::string &getForm() const { @@ -255,21 +262,26 @@ class PlayerInventoryFormSource : public IFormSource Client *m_client; }; -class NodeDugEvent : public MtEvent +class NodeDugEvent: public MtEvent { public: v3s16 p; MapNode n; - NodeDugEvent(v3s16 p, MapNode n) : p(p), n(n) {} - MtEvent::Type getType() const { return MtEvent::NODE_DUG; } + NodeDugEvent(v3s16 p, MapNode n): + p(p), + n(n) + {} + MtEvent::Type getType() const + { + return MtEvent::NODE_DUG; + } }; class SoundMaker { ISoundManager *m_sound; const NodeDefManager *m_ndef; - public: bool makes_footstep_sound; float m_player_step_timer; @@ -279,9 +291,12 @@ class SoundMaker SimpleSoundSpec m_player_leftpunch_sound; SimpleSoundSpec m_player_rightpunch_sound; - SoundMaker(ISoundManager *sound, const NodeDefManager *ndef) : - m_sound(sound), m_ndef(ndef), makes_footstep_sound(true), - m_player_step_timer(0), m_player_jump_timer(0.0f) + SoundMaker(ISoundManager *sound, const NodeDefManager *ndef): + m_sound(sound), + m_ndef(ndef), + makes_footstep_sound(true), + m_player_step_timer(0), + m_player_jump_timer(0.0f) { } @@ -348,22 +363,19 @@ class SoundMaker static void playerFallingDamage(MtEvent *e, void *data) { SoundMaker *sm = (SoundMaker *)data; - sm->m_sound->playSound( - SimpleSoundSpec("player_falling_damage", 0.5), false); + sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false); } void registerReceiver(MtEventManager *mgr) { mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this); - mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, - this); + mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this); mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this); mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this); mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this); mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this); mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this); - mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, - this); + mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this); } void step(float dtime) @@ -374,40 +386,30 @@ class SoundMaker }; // Locally stored sounds don't need to be preloaded because of this -class GameOnDemandSoundFetcher : public OnDemandSoundFetcher +class GameOnDemandSoundFetcher: public OnDemandSoundFetcher { std::set m_fetched; - private: - void paths_insert(std::set &dst_paths, const std::string &base, - const std::string &name) + void paths_insert(std::set &dst_paths, + const std::string &base, + const std::string &name) { dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".0.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".1.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".2.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".3.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".4.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".5.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".6.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".7.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".8.ogg"); - dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + - ".9.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg"); + dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg"); } - public: - void fetchSounds(const std::string &name, std::set &dst_paths, - std::set &dst_datas) + void fetchSounds(const std::string &name, + std::set &dst_paths, + std::set &dst_datas) { if (m_fetched.count(name)) return; @@ -415,10 +417,11 @@ class GameOnDemandSoundFetcher : public OnDemandSoundFetcher m_fetched.insert(name); paths_insert(dst_paths, porting::path_share, name); - paths_insert(dst_paths, porting::path_user, name); + paths_insert(dst_paths, porting::path_user, name); } }; + // before 1.8 there isn't a "integer interface", only float #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) typedef f32 SamplerLayer_t; @@ -426,6 +429,7 @@ typedef f32 SamplerLayer_t; typedef s32 SamplerLayer_t; #endif + class GameGlobalShaderConstantSetter : public IShaderConstantSetter { Sky *m_sky; @@ -456,25 +460,30 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter static void settingsCallback(const std::string &name, void *userdata) { - reinterpret_cast(userdata) - ->onSettingsChange(name); + reinterpret_cast(userdata)->onSettingsChange(name); } void setSky(Sky *sky) { m_sky = sky; } - GameGlobalShaderConstantSetter( - Sky *sky, bool *force_fog_off, f32 *fog_range, Client *client) : - m_sky(sky), - m_force_fog_off(force_fog_off), m_fog_range(fog_range), - m_sky_bg_color("skyBgColor"), m_fog_distance("fogDistance"), - m_animation_timer_vertex("animationTimer"), - m_animation_timer_pixel("animationTimer"), - m_day_light("dayLight"), m_eye_position_pixel("eyePosition"), - m_eye_position_vertex("eyePosition"), m_minimap_yaw("yawVec"), - m_camera_offset_pixel("cameraOffset"), - m_camera_offset_vertex("cameraOffset"), - m_base_texture("baseTexture"), m_normal_texture("normalTexture"), - m_texture_flags("textureFlags"), m_client(client) + GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off, + f32 *fog_range, Client *client) : + m_sky(sky), + m_force_fog_off(force_fog_off), + m_fog_range(fog_range), + m_sky_bg_color("skyBgColor"), + m_fog_distance("fogDistance"), + m_animation_timer_vertex("animationTimer"), + m_animation_timer_pixel("animationTimer"), + m_day_light("dayLight"), + m_eye_position_pixel("eyePosition"), + m_eye_position_vertex("eyePosition"), + m_minimap_yaw("yawVec"), + m_camera_offset_pixel("cameraOffset"), + m_camera_offset_vertex("cameraOffset"), + m_base_texture("baseTexture"), + m_normal_texture("normalTexture"), + m_texture_flags("textureFlags"), + m_client(client) { g_settings->registerChangedCallback("enable_fog", settingsCallback, this); m_fog_enabled = g_settings->getBool("enable_fog"); @@ -482,12 +491,11 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter ~GameGlobalShaderConstantSetter() { - g_settings->deregisterChangedCallback( - "enable_fog", settingsCallback, this); + g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this); } - virtual void onSetConstants( - video::IMaterialRendererServices *services, bool is_highlevel) + virtual void onSetConstants(video::IMaterialRendererServices *services, + bool is_highlevel) { if (!is_highlevel) return; @@ -496,10 +504,10 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter video::SColor bgcolor = m_sky->getBgColor(); video::SColorf bgcolorf(bgcolor); float bgcolorfa[4] = { - bgcolorf.r, - bgcolorf.g, - bgcolorf.b, - bgcolorf.a, + bgcolorf.r, + bgcolorf.g, + bgcolorf.b, + bgcolorf.a, }; m_sky_bg_color.set(bgcolorfa, services); @@ -514,7 +522,10 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio(); video::SColorf sunlight; get_sunlight_color(&sunlight, daynight_ratio); - float dnc[3] = {sunlight.r, sunlight.g, sunlight.b}; + float dnc[3] = { + sunlight.r, + sunlight.g, + sunlight.b }; m_day_light.set(dnc, services); u32 animation_timer = porting::getTimeMs() % 1000000; @@ -559,13 +570,16 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter m_camera_offset_pixel.set(camera_offset_array, services); m_camera_offset_vertex.set(camera_offset_array, services); - SamplerLayer_t base_tex = 0, normal_tex = 1, flags_tex = 2; + SamplerLayer_t base_tex = 0, + normal_tex = 1, + flags_tex = 2; m_base_texture.set(&base_tex, services); m_normal_texture.set(&normal_tex, services); m_texture_flags.set(&flags_tex, services); } }; + class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory { Sky *m_sky; @@ -573,18 +587,16 @@ class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactor f32 *m_fog_range; Client *m_client; std::vector created_nosky; - public: - GameGlobalShaderConstantSetterFactory( - bool *force_fog_off, f32 *fog_range, Client *client) : - m_sky(NULL), - m_force_fog_off(force_fog_off), m_fog_range(fog_range), - m_client(client) - { - } - - void setSky(Sky *sky) - { + GameGlobalShaderConstantSetterFactory(bool *force_fog_off, + f32 *fog_range, Client *client) : + m_sky(NULL), + m_force_fog_off(force_fog_off), + m_fog_range(fog_range), + m_client(client) + {} + + void setSky(Sky *sky) { m_sky = sky; for (GameGlobalShaderConstantSetter *ggscs : created_nosky) { ggscs->setSky(m_sky); @@ -592,7 +604,7 @@ class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactor created_nosky.clear(); } - virtual IShaderConstantSetter *create() + virtual IShaderConstantSetter* create() { GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter( m_sky, m_force_fog_off, m_fog_range, m_client); @@ -614,19 +626,18 @@ class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactor const float object_hit_delay = 0.2; -struct FpsControl -{ +struct FpsControl { u32 last_time, busy_time, sleep_time; }; + /* The reason the following structs are not anonymous structs within the * class is that they are not used by the majority of member functions and * many functions that do require objects of thse types do not modify them * (so they can be passed as a const qualified parameter) */ -struct GameRunData -{ +struct GameRunData { u16 dig_index; u16 new_playeritem; PointedThing pointed_old; @@ -662,24 +673,27 @@ struct ClientEventHandler void (Game::*handler)(ClientEvent *, CameraOrientation *); }; -class Game -{ +class Game { public: Game(); ~Game(); - bool startup(bool *kill, InputHandler *input, const GameStartData &game_params, - std::string &error_message, bool *reconnect, + bool startup(bool *kill, + InputHandler *input, + const GameStartData &game_params, + std::string &error_message, + bool *reconnect, ChatBackend *chat_backend); + void run(); void shutdown(); void extendedResourceCleanup(); // Basic initialisation - bool init(const std::string &map_dir, const std::string &address, u16 port, - const SubgameSpec &gamespec); + bool init(const std::string &map_dir, const std::string &address, + u16 port, const SubgameSpec &gamespec); bool initSound(); bool createSingleplayerServer(const std::string &map_dir, const SubgameSpec &gamespec, u16 port); @@ -689,8 +703,8 @@ class Game bool initGui(); // Client connection - bool connectToServer( - const GameStartData &start_data, bool *connect_ok, bool *aborted); + bool connectToServer(const GameStartData &start_data, + bool *connect_ok, bool *aborted); bool getServerContent(bool *aborted); // Main loop @@ -699,8 +713,7 @@ class Game bool checkConnection(); bool handleCallbacks(); void processQueues(); - void updateProfilers( - const RunStats &stats, const FpsControl &draw_times, f32 dtime); + void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime); void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime); void updateProfilerGraphs(ProfilerGraph *graph); @@ -712,7 +725,7 @@ class Game void dropSelectedItem(bool single_item = false); void openInventory(); void openEnderchest(); - void openConsole(float scale, const wchar_t *line = NULL); + void openConsole(float scale, const wchar_t *line=NULL); void toggleFreeMove(); void toggleFreeMoveAlt(); void togglePitchMove(); @@ -757,19 +770,16 @@ class Game * @param[out] selected_object the selected object or * NULL if not found */ - PointedThing updatePointedThing(const core::line3d &shootline, - bool liquids_pointable, bool look_for_object, - const v3s16 &camera_offset); + PointedThing updatePointedThing( + const core::line3d &shootline, bool liquids_pointable, + bool look_for_object, const v3s16 &camera_offset); void handlePointingAtNothing(const ItemStack &playerItem); void handlePointingAtNode(const PointedThing &pointed, - const ItemStack &selected_item, const ItemStack &hand_item, - f32 dtime); - void handlePointingAtObject(const PointedThing &pointed, - const ItemStack &playeritem, const v3f &player_position, - bool show_debug); + const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime); + void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem, + const v3f &player_position, bool show_debug); void handleDigging(const PointedThing &pointed, const v3s16 &nodepos, - const ItemStack &selected_item, const ItemStack &hand_item, - f32 dtime); + const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime); void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, const CameraOrientation &cam); @@ -781,19 +791,23 @@ class Game static void freecamChangedCallback(const std::string &setting_name, void *data); static void settingChangedCallback(const std::string &setting_name, void *data); - static void updateAllMapBlocksCallback( - const std::string &setting_name, void *data); + static void updateAllMapBlocksCallback(const std::string &setting_name, void *data); void readSettings(); - inline bool isKeyDown(GameKeyType k) { return input->isKeyDown(k); } - inline bool wasKeyDown(GameKeyType k) { return input->wasKeyDown(k); } + inline bool isKeyDown(GameKeyType k) + { + return input->isKeyDown(k); + } + inline bool wasKeyDown(GameKeyType k) + { + return input->wasKeyDown(k); + } #ifdef __ANDROID__ void handleAndroidChatInput(); #endif - struct Flags - { + struct Flags { bool force_fog_off = false; bool disable_camera_update = false; }; @@ -804,14 +818,12 @@ class Game // ClientEvent handlers void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam); - void handleClientEvent_PlayerForceMove( - ClientEvent *event, CameraOrientation *cam); + void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam); - void handleClientEvent_ShowLocalFormSpec( - ClientEvent *event, CameraOrientation *cam); - void handleClientEvent_HandleParticleEvent( - ClientEvent *event, CameraOrientation *cam); + void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam); + void handleClientEvent_HandleParticleEvent(ClientEvent *event, + CameraOrientation *cam); void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam); @@ -819,16 +831,15 @@ class Game void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam); - void handleClientEvent_OverrideDayNigthRatio( - ClientEvent *event, CameraOrientation *cam); + void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event, + CameraOrientation *cam); void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam); void updateChat(f32 dtime, const v2u32 &screensize); - bool nodePlacement(const ItemDefinition &selected_def, - const ItemStack &selected_item, const v3s16 &nodepos, - const v3s16 &neighbourpos, const PointedThing &pointed, - const NodeMetadata *meta); + bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item, + const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed, + const NodeMetadata *meta); static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX]; InputHandler *input = nullptr; @@ -847,10 +858,10 @@ class Game ISoundManager *sound = nullptr; bool sound_is_dummy = false; SoundMaker *soundmaker = nullptr; - + ChatBackend *chat_backend = nullptr; LogOutputBuffer m_chat_log_buf; - + EventManager *eventmgr = nullptr; QuicktuneShortcutter *quicktune = nullptr; bool registration_confirmation_shown = false; @@ -860,8 +871,8 @@ class Game CheatMenu *m_cheat_menu = nullptr; MapDrawControl *draw_control = nullptr; Camera *camera = nullptr; - Clouds *clouds = nullptr; // Free using ->Drop() - Sky *sky = nullptr; // Free using ->Drop() + Clouds *clouds = nullptr; // Free using ->Drop() + Sky *sky = nullptr; // Free using ->Drop() Hud *hud = nullptr; Minimap *mapper = nullptr; @@ -903,11 +914,11 @@ class Game bool m_cache_enable_fog; bool m_cache_enable_noclip; bool m_cache_enable_free_move; - f32 m_cache_mouse_sensitivity; - f32 m_cache_joystick_frustum_sensitivity; - f32 m_repeat_right_click_time; - f32 m_cache_cam_smoothing; - f32 m_cache_fog_start; + f32 m_cache_mouse_sensitivity; + f32 m_cache_joystick_frustum_sensitivity; + f32 m_repeat_right_click_time; + f32 m_cache_cam_smoothing; + f32 m_cache_fog_start; bool m_invert_mouse = false; bool m_first_loop_after_window_activation = false; @@ -915,8 +926,8 @@ class Game bool m_does_lost_focus_pause_game = false; - CameraOrientation cam_view_target = {0}; - CameraOrientation cam_view = {0}; + CameraOrientation cam_view_target = { 0 }; + CameraOrientation cam_view = { 0 }; #ifdef __ANDROID__ bool m_cache_hold_aux1; @@ -925,6 +936,9 @@ class Game }; extern Game *g_game; -void the_game(bool *kill, InputHandler *input, const GameStartData &start_data, - std::string &error_message, ChatBackend &chat_backend, +void the_game(bool *kill, + InputHandler *input, + const GameStartData &start_data, + std::string &error_message, + ChatBackend &chat_backend, bool *reconnect_requested); diff --git a/src/client/gameui.cpp b/src/client/gameui.cpp index b72fcd999..a9057052e 100644 --- a/src/client/gameui.cpp +++ b/src/client/gameui.cpp @@ -34,7 +34,8 @@ with this program; if not, write to the Free Software Foundation, Inc., inline static const char *yawToDirectionString(int yaw) { - static const char *direction[4] = {"North +Z", "West -X", "South -Z", "East +X"}; + static const char *direction[4] = + {"North +Z", "West -X", "South -Z", "East +X"}; yaw = wrapDegrees_0_360(yaw); yaw = (yaw + 45) % 360 / 90; @@ -45,58 +46,56 @@ inline static const char *yawToDirectionString(int yaw) GameUI::GameUI() { if (guienv && guienv->getSkin()) - m_statustext_initial_color = - guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT); + m_statustext_initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT); else m_statustext_initial_color = video::SColor(255, 0, 0, 0); + } void GameUI::init() { - m_guitext_coords = gui::StaticText::add( - guienv, L"", core::rect(0, 0, 0, 0), false, false, guiroot); - + m_guitext_coords = gui::StaticText::add(guienv, L"", core::rect(0, 0, 0, 0), false, + false, guiroot); + // First line of debug text m_guitext = gui::StaticText::add(guienv, utf8_to_wide(PROJECT_NAME_C).c_str(), - core::rect(0, 0, 0, 0), false, false, guiroot); + core::rect(0, 0, 0, 0), false, false, guiroot); // Second line of debug text - m_guitext2 = gui::StaticText::add( - guienv, L"", core::rect(0, 0, 0, 0), false, false, guiroot); + m_guitext2 = gui::StaticText::add(guienv, L"", core::rect(0, 0, 0, 0), false, + false, guiroot); // At the middle of the screen // Object infos are shown in this m_guitext_info = gui::StaticText::add(guienv, L"", - core::rect(0, 0, 400, - g_fontengine->getTextHeight() * 5 + 5) + - v2s32(100, 200), - false, true, guiroot); + core::rect(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + + v2s32(100, 200), false, true, guiroot); // Status text (displays info when showing and hiding GUI stuff, etc.) m_guitext_status = gui::StaticText::add(guienv, L"", - core::rect(0, 0, 0, 0), false, false, guiroot); + core::rect(0, 0, 0, 0), false, false, guiroot); m_guitext_status->setVisible(false); // Chat text m_guitext_chat = gui::StaticText::add(guienv, L"", core::rect(0, 0, 0, 0), - // false, false); // Disable word wrap as of now - false, true, guiroot); + //false, false); // Disable word wrap as of now + false, true, guiroot); u16 chat_font_size = g_settings->getU16("chat_font_size"); if (chat_font_size != 0) { - m_guitext_chat->setOverrideFont( - g_fontengine->getFont(chat_font_size, FM_Unspecified)); + m_guitext_chat->setOverrideFont(g_fontengine->getFont( + chat_font_size, FM_Unspecified)); } // Profiler text (size is updated when text is updated) m_guitext_profiler = gui::StaticText::add(guienv, L"", - core::rect(0, 0, 0, 0), false, false, guiroot); + core::rect(0, 0, 0, 0), false, false, guiroot); m_guitext_profiler->setOverrideFont(g_fontengine->getFont( - g_fontengine->getDefaultFontSize() * 0.9f, FM_Mono)); + g_fontengine->getDefaultFontSize() * 0.9f, FM_Mono)); m_guitext_profiler->setVisible(false); } void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_control, - const CameraOrientation &cam, const PointedThing &pointed_old, - const GUIChatConsole *chat_console, float dtime) + const CameraOrientation &cam, const PointedThing &pointed_old, + const GUIChatConsole *chat_console, float dtime) { LocalPlayer *player = client->getEnv().getLocalPlayer(); v3f player_position = player->getPosition(); @@ -106,15 +105,14 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_ if (show_coords) { std::ostringstream os(std::ios_base::binary); - os << std::setprecision(1) << std::fixed << (player_position.X / BS) - << ", " << (player_position.Y / BS) << ", " - << (player_position.Z / BS); + os << std::setprecision(1) << std::fixed + << (player_position.X / BS) + << ", " << (player_position.Y / BS) + << ", " << (player_position.Z / BS); setStaticText(m_guitext_coords, utf8_to_wide(os.str()).c_str()); - m_guitext_coords->setRelativePosition(core::rect(5, - screensize.Y - 5 - g_fontengine->getTextHeight(), - screensize.X, screensize.Y)); + m_guitext_coords->setRelativePosition(core::rect(5, screensize.Y - 5 - g_fontengine->getTextHeight(), screensize.X, screensize.Y)); } - + m_guitext_coords->setVisible(show_coords); if (m_flags.show_debug) { @@ -123,17 +121,23 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_ u16 fps = 1.0 / stats.dtime_jitter.avg; std::ostringstream os(std::ios_base::binary); - os << std::fixed << PROJECT_NAME_C " " << g_version_hash - << " | FPS: " << fps << std::setprecision(0) - << " | drawtime: " << drawtime_avg << "ms" << std::setprecision(1) - << " | dtime jitter: " << (stats.dtime_jitter.max_fraction * 100.0) - << "%" << std::setprecision(1) << " | view range: " - << (draw_control->range_all ? "All" : itos(draw_control->wanted_range)) - << std::setprecision(3) << " | RTT: " << client->getRTT() << "s"; + os << std::fixed + << PROJECT_NAME_C " " << g_version_hash + << " | FPS: " << fps + << std::setprecision(0) + << " | drawtime: " << drawtime_avg << "ms" + << std::setprecision(1) + << " | dtime jitter: " + << (stats.dtime_jitter.max_fraction * 100.0) << "%" + << std::setprecision(1) + << " | view range: " + << (draw_control->range_all ? "All" : itos(draw_control->wanted_range)) + << std::setprecision(3) + << " | RTT: " << client->getRTT() << "s"; setStaticText(m_guitext, utf8_to_wide(os.str()).c_str()); - m_guitext->setRelativePosition(core::rect( - 5, 5, screensize.X, 5 + g_fontengine->getTextHeight())); + m_guitext->setRelativePosition(core::rect(5, 5, screensize.X, + 5 + g_fontengine->getTextHeight())); } // Finally set the guitext visible depending on the flag @@ -141,31 +145,32 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_ if (m_flags.show_debug) { std::ostringstream os(std::ios_base::binary); - os << std::setprecision(1) << std::fixed << "pos: (" - << (player_position.X / BS) << ", " << (player_position.Y / BS) << ", " - << (player_position.Z / BS) - << ") | yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "\xC2\xB0 " - << yawToDirectionString(cam.camera_yaw) - << " | pitch: " << (-wrapDegrees_180(cam.camera_pitch)) << "\xC2\xB0" - << " | seed: " << ((u64)client->getMapSeed()); + os << std::setprecision(1) << std::fixed + << "pos: (" << (player_position.X / BS) + << ", " << (player_position.Y / BS) + << ", " << (player_position.Z / BS) + << ") | yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "\xC2\xB0 " + << yawToDirectionString(cam.camera_yaw) + << " | pitch: " << (-wrapDegrees_180(cam.camera_pitch)) << "\xC2\xB0" + << " | seed: " << ((u64)client->getMapSeed()); if (pointed_old.type == POINTEDTHING_NODE) { ClientMap &map = client->getEnv().getClientMap(); const NodeDefManager *nodedef = client->getNodeDefManager(); MapNode n = map.getNode(pointed_old.node_undersurface); - if (n.getContent() != CONTENT_IGNORE && - nodedef->get(n).name != "unknown") { + if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") { os << ", pointed: " << nodedef->get(n).name - << ", param2: " << (u64)n.getParam2(); + << ", param2: " << (u64) n.getParam2(); } } setStaticText(m_guitext2, utf8_to_wide(os.str()).c_str()); m_guitext2->setRelativePosition(core::rect(5, - 5 + g_fontengine->getTextHeight(), screensize.X, - 5 + g_fontengine->getTextHeight() * 2)); + 5 + g_fontengine->getTextHeight(), screensize.X, + 5 + g_fontengine->getTextHeight() * 2 + )); } m_guitext2->setVisible(m_flags.show_debug); @@ -188,22 +193,19 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_ m_guitext_status->setVisible(!m_statustext.empty()); if (!m_statustext.empty()) { - s32 status_width = m_guitext_status->getTextWidth(); + s32 status_width = m_guitext_status->getTextWidth(); s32 status_height = m_guitext_status->getTextHeight(); s32 status_y = screensize.Y - 150; s32 status_x = (screensize.X - status_width) / 2; - m_guitext_status->setRelativePosition( - core::rect(status_x, status_y - status_height, - status_x + status_width, status_y)); + m_guitext_status->setRelativePosition(core::rect(status_x , + status_y - status_height, status_x + status_width, status_y)); // Fade out video::SColor final_color = m_statustext_initial_color; final_color.setAlpha(0); - video::SColor fade_color = - m_statustext_initial_color.getInterpolated_quadratic( - m_statustext_initial_color, final_color, - m_statustext_time / statustext_time_max); + video::SColor fade_color = m_statustext_initial_color.getInterpolated_quadratic( + m_statustext_initial_color, final_color, m_statustext_time / statustext_time_max); m_guitext_status->setOverrideColor(fade_color); m_guitext_status->enableOverrideColor(true); } @@ -233,17 +235,18 @@ void GameUI::setChatText(const EnrichedString &chat_text, u32 recent_chat_count) { // Update gui element size and position - + const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - + s32 chat_y = window_size.Y - 150 - m_guitext_chat->getTextHeight(); if (m_flags.show_debug) chat_y += 2 * g_fontengine->getLineHeight(); - core::rect chat_size(10, chat_y, window_size.X - 20, 0); - chat_size.LowerRightCorner.Y = std::min( - (s32)window_size.Y, m_guitext_chat->getTextHeight() + chat_y); + core::rect chat_size(10, chat_y, + window_size.X - 20, 0); + chat_size.LowerRightCorner.Y = std::min((s32)window_size.Y, + m_guitext_chat->getTextHeight() + chat_y); m_guitext_chat->setRelativePosition(chat_size); setStaticText(m_guitext_chat, chat_text); @@ -255,27 +258,24 @@ void GameUI::updateProfiler() { if (m_profiler_current_page != 0) { std::ostringstream os(std::ios_base::binary); - os << " Profiler page " << (int)m_profiler_current_page - << ", elapsed: " << g_profiler->getElapsedMs() << " ms)" << std::endl; + os << " Profiler page " << (int)m_profiler_current_page << + ", elapsed: " << g_profiler->getElapsedMs() << " ms)" << std::endl; - int lines = g_profiler->print( - os, m_profiler_current_page, m_profiler_max_page); + int lines = g_profiler->print(os, m_profiler_current_page, m_profiler_max_page); ++lines; EnrichedString str(utf8_to_wide(os.str())); str.setBackground(video::SColor(120, 0, 0, 0)); setStaticText(m_guitext_profiler, str); - core::dimension2d size = - m_guitext_profiler->getOverrideFont()->getDimension( - str.c_str()); + core::dimension2d size = m_guitext_profiler->getOverrideFont()-> + getDimension(str.c_str()); core::position2di upper_left(6, 50); core::position2di lower_right = upper_left; lower_right.X += size.Width + 10; - lower_right.Y += size.Height; + lower_right.Y += size.Height; - m_guitext_profiler->setRelativePosition( - core::rect(upper_left, lower_right)); + m_guitext_profiler->setRelativePosition(core::rect(upper_left, lower_right)); } m_guitext_profiler->setVisible(m_profiler_current_page != 0); @@ -310,17 +310,16 @@ void GameUI::toggleHud() void GameUI::toggleProfiler() { - m_profiler_current_page = - (m_profiler_current_page + 1) % (m_profiler_max_page + 1); + m_profiler_current_page = (m_profiler_current_page + 1) % (m_profiler_max_page + 1); // FIXME: This updates the profiler with incomplete values updateProfiler(); if (m_profiler_current_page != 0) { wchar_t buf[255]; - const wchar_t *str = wgettext("Profiler shown (page %d of %d)"); - swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, m_profiler_current_page, - m_profiler_max_page); + const wchar_t* str = wgettext("Profiler shown (page %d of %d)"); + swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, + m_profiler_current_page, m_profiler_max_page); delete[] str; showStatusText(buf); } else { @@ -328,6 +327,7 @@ void GameUI::toggleProfiler() } } + void GameUI::deleteFormspec() { if (m_formspec) { diff --git a/src/client/gameui.h b/src/client/gameui.h index 2278ad1d6..8a1b5650d 100644 --- a/src/client/gameui.h +++ b/src/client/gameui.h @@ -85,8 +85,7 @@ class GameUI const bool isChatVisible() { - return m_flags.show_chat && m_recent_chat_count != 0 && - m_profiler_current_page == 0; + return m_flags.show_chat && m_recent_chat_count != 0 && m_profiler_current_page == 0; } void setChatText(const EnrichedString &chat_text, u32 recent_chat_count); @@ -113,7 +112,7 @@ class GameUI gui::IGUIStaticText *m_guitext = nullptr; // First line of debug text gui::IGUIStaticText *m_guitext2 = nullptr; // Second line of debug text gui::IGUIStaticText *m_guitext_coords = nullptr; - + gui::IGUIStaticText *m_guitext_info = nullptr; // At the middle of the screen std::wstring m_infotext; diff --git a/src/client/guiscalingfilter.cpp b/src/client/guiscalingfilter.cpp index 6b426fdf4..4262331bd 100644 --- a/src/client/guiscalingfilter.cpp +++ b/src/client/guiscalingfilter.cpp @@ -40,13 +40,12 @@ std::map g_txrCache; /* Manually insert an image into the cache, useful to avoid texture-to-image * conversion whenever we can intercept it. */ -void guiScalingCache( - const io::path &key, video::IVideoDriver *driver, video::IImage *value) +void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value) { if (!g_settings->getBool("gui_scaling_filter")) return; - video::IImage *copied = driver->createImage( - value->getColorFormat(), value->getDimension()); + video::IImage *copied = driver->createImage(value->getColorFormat(), + value->getDimension()); value->copyTo(copied); g_imgCache[key] = copied; } @@ -70,8 +69,9 @@ void guiScalingCacheClear() * texture is not already cached, attempt to create it. Returns a pre-scaled texture, * or the original texture if unable to pre-scale it. */ -video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITexture *src, - const core::rect &srcrect, const core::rect &destrect) +video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, + video::ITexture *src, const core::rect &srcrect, + const core::rect &destrect) { if (src == NULL) return src; @@ -81,9 +81,12 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex // Calculate scaled texture name. char rectstr[200]; porting::mt_snprintf(rectstr, sizeof(rectstr), "%d:%d:%d:%d:%d:%d", - srcrect.UpperLeftCorner.X, srcrect.UpperLeftCorner.Y, - srcrect.getWidth(), srcrect.getHeight(), destrect.getWidth(), - destrect.getHeight()); + srcrect.UpperLeftCorner.X, + srcrect.UpperLeftCorner.Y, + srcrect.getWidth(), + srcrect.getHeight(), + destrect.getWidth(), + destrect.getHeight()); io::path origname = src->getName().getPath(); io::path scalename = origname + "@guiScalingFilter:" + rectstr; @@ -94,12 +97,12 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex // Try to find the texture converted to an image in the cache. // If the image was not found, try to extract it from the texture. - video::IImage *srcimg = g_imgCache[origname]; + video::IImage* srcimg = g_imgCache[origname]; if (srcimg == NULL) { if (!g_settings->getBool("gui_scaling_filter_txr2img")) return src; srcimg = driver->createImageFromData(src->getColorFormat(), - src->getSize(), src->lock(), false); + src->getSize(), src->lock(), false); src->unlock(); g_imgCache[origname] = srcimg; } @@ -108,7 +111,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex imageCleanTransparent(srcimg, 0); video::IImage *destimg = driver->createImage(src->getColorFormat(), core::dimension2d((u32)destrect.getWidth(), - (u32)destrect.getHeight())); + (u32)destrect.getHeight())); imageScaleNNAA(srcimg, srcrect, destimg); #if ENABLE_GLES @@ -117,7 +120,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex if (!hasNPotSupport()) { video::IImage *po2img = driver->createImage(src->getColorFormat(), core::dimension2d(npot2((u32)destrect.getWidth()), - npot2((u32)destrect.getHeight()))); + npot2((u32)destrect.getHeight()))); po2img->fill(video::SColor(0, 0, 0, 0)); destimg->copyTo(po2img); destimg->drop(); @@ -136,15 +139,14 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex /* Convenience wrapper for guiScalingResizeCached that accepts parameters that * are available at GUI imagebutton creation time. */ -video::ITexture *guiScalingImageButton( - video::IVideoDriver *driver, video::ITexture *src, s32 width, s32 height) +video::ITexture *guiScalingImageButton(video::IVideoDriver *driver, + video::ITexture *src, s32 width, s32 height) { if (src == NULL) return src; return guiScalingResizeCached(driver, src, - core::rect(0, 0, src->getSize().Width, - src->getSize().Height), - core::rect(0, 0, width, height)); + core::rect(0, 0, src->getSize().Width, src->getSize().Height), + core::rect(0, 0, width, height)); } /* Replacement for driver->draw2DImage() that uses the high-quality pre-scaled @@ -161,10 +163,9 @@ void draw2DImageFilterScaled(video::IVideoDriver *driver, video::ITexture *txr, return; // Correct source rect based on scaled image. - const core::rect mysrcrect = - (scaled != txr) ? core::rect(0, 0, destrect.getWidth(), - destrect.getHeight()) - : srcrect; + const core::rect mysrcrect = (scaled != txr) + ? core::rect(0, 0, destrect.getWidth(), destrect.getHeight()) + : srcrect; driver->draw2DImage(scaled, destrect, mysrcrect, cliprect, colors, usealpha); } @@ -173,13 +174,11 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture, const core::rect &rect, const core::rect &middle, const core::rect *cliprect) { - const video::SColor color(255, 255, 255, 255); - const video::SColor colors[] = {color, color, color, color}; + const video::SColor color(255,255,255,255); + const video::SColor colors[] = {color,color,color,color}; auto originalSize = texture->getOriginalSize(); - core::vector2di lowerRightOffset = - core::vector2di(originalSize.Width, originalSize.Height) - - middle.LowerRightCorner; + core::vector2di lowerRightOffset = core::vector2di(originalSize.Width, originalSize.Height) - middle.LowerRightCorner; for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { @@ -188,8 +187,7 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture, switch (x) { case 0: - dest.LowerRightCorner.X = rect.UpperLeftCorner.X + - middle.UpperLeftCorner.X; + dest.LowerRightCorner.X = rect.UpperLeftCorner.X + middle.UpperLeftCorner.X; src.LowerRightCorner.X = middle.UpperLeftCorner.X; break; @@ -201,16 +199,14 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture, break; case 2: - dest.UpperLeftCorner.X = rect.LowerRightCorner.X - - lowerRightOffset.X; + dest.UpperLeftCorner.X = rect.LowerRightCorner.X - lowerRightOffset.X; src.UpperLeftCorner.X = middle.LowerRightCorner.X; break; } switch (y) { case 0: - dest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + - middle.UpperLeftCorner.Y; + dest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + middle.UpperLeftCorner.Y; src.LowerRightCorner.Y = middle.UpperLeftCorner.Y; break; @@ -222,14 +218,12 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture, break; case 2: - dest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - - lowerRightOffset.Y; + dest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - lowerRightOffset.Y; src.UpperLeftCorner.Y = middle.LowerRightCorner.Y; break; } - draw2DImageFilterScaled(driver, texture, dest, src, cliprect, - colors, true); + draw2DImageFilterScaled(driver, texture, dest, src, cliprect, colors, true); } } } diff --git a/src/client/guiscalingfilter.h b/src/client/guiscalingfilter.h index 703cbfb93..b703d91f0 100644 --- a/src/client/guiscalingfilter.h +++ b/src/client/guiscalingfilter.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Manually insert an image into the cache, useful to avoid texture-to-image * conversion whenever we can intercept it. */ -void guiScalingCache( - const io::path &key, video::IVideoDriver *driver, video::IImage *value); +void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value); // Manually clear the cache, e.g. when switching to different worlds. void guiScalingCacheClear(); @@ -39,16 +38,16 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex /* Convenience wrapper for guiScalingResizeCached that accepts parameters that * are available at GUI imagebutton creation time. */ -video::ITexture *guiScalingImageButton( - video::IVideoDriver *driver, video::ITexture *src, s32 width, s32 height); +video::ITexture *guiScalingImageButton(video::IVideoDriver *driver, video::ITexture *src, + s32 width, s32 height); /* Replacement for driver->draw2DImage() that uses the high-quality pre-scaled * texture, if configured. */ void draw2DImageFilterScaled(video::IVideoDriver *driver, video::ITexture *txr, const core::rect &destrect, const core::rect &srcrect, - const core::rect *cliprect = 0, - const video::SColor *const colors = 0, bool usealpha = false); + const core::rect *cliprect = 0, const video::SColor *const colors = 0, + bool usealpha = false); /* * 9-slice / segment drawing diff --git a/src/client/hud.cpp b/src/client/hud.cpp index db5c5ef9f..2b347c1e0 100644 --- a/src/client/hud.cpp +++ b/src/client/hud.cpp @@ -47,16 +47,16 @@ with this program; if not, write to the Free Software Foundation, Inc., Hud::Hud(gui::IGUIEnvironment *guienv, Client *client, LocalPlayer *player, Inventory *inventory) { - driver = RenderingEngine::get_video_driver(); - this->guienv = guienv; - this->client = client; - this->player = player; - this->inventory = inventory; - - m_hud_scaling = g_settings->getFloat("hud_scaling"); - m_scale_factor = m_hud_scaling * RenderingEngine::getDisplayDensity(); - m_hotbar_imagesize = std::floor( - HOTBAR_IMAGE_SIZE * RenderingEngine::getDisplayDensity() + 0.5f); + driver = RenderingEngine::get_video_driver(); + this->guienv = guienv; + this->client = client; + this->player = player; + this->inventory = inventory; + + m_hud_scaling = g_settings->getFloat("hud_scaling"); + m_scale_factor = m_hud_scaling * RenderingEngine::getDisplayDensity(); + m_hotbar_imagesize = std::floor(HOTBAR_IMAGE_SIZE * + RenderingEngine::getDisplayDensity() + 0.5f); m_hotbar_imagesize *= m_hud_scaling; m_padding = m_hotbar_imagesize / 12; @@ -98,19 +98,16 @@ Hud::Hud(gui::IGUIEnvironment *guienv, Client *client, LocalPlayer *player, if (g_settings->getBool("enable_shaders")) { IShaderSource *shdrsrc = client->getShaderSource(); - u16 shader_id = shdrsrc->getShader(m_mode == HIGHLIGHT_HALO - ? "selection_shader" - : "default_shader", - 1, 1); - m_selection_material.MaterialType = - shdrsrc->getShaderInfo(shader_id).material; + u16 shader_id = shdrsrc->getShader( + m_mode == HIGHLIGHT_HALO ? "selection_shader" : "default_shader", 1, 1); + m_selection_material.MaterialType = shdrsrc->getShaderInfo(shader_id).material; } else { m_selection_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; } if (m_mode == HIGHLIGHT_BOX) { m_selection_material.Thickness = - rangelim(g_settings->getS16("selectionbox_width"), 1, 5); + rangelim(g_settings->getS16("selectionbox_width"), 1, 5); } else if (m_mode == HIGHLIGHT_HALO) { m_selection_material.setTexture(0, tsrc->getTextureForMesh("halo.png")); m_selection_material.setFlag(video::EMF_BACK_FACE_CULLING, true); @@ -125,50 +122,51 @@ Hud::~Hud() m_selection_mesh->drop(); } -void Hud::drawItem(const ItemStack &item, const core::rect &rect, bool selected) +void Hud::drawItem(const ItemStack &item, const core::rect& rect, + bool selected) { if (selected) { /* draw hihlighting around selected item */ if (use_hotbar_selected_image) { core::rect imgrect2 = rect; - imgrect2.UpperLeftCorner.X -= (m_padding * 2); - imgrect2.UpperLeftCorner.Y -= (m_padding * 2); - imgrect2.LowerRightCorner.X += (m_padding * 2); - imgrect2.LowerRightCorner.Y += (m_padding * 2); - video::ITexture *texture = - tsrc->getTexture(hotbar_selected_image); - core::dimension2di imgsize(texture->getOriginalSize()); + imgrect2.UpperLeftCorner.X -= (m_padding*2); + imgrect2.UpperLeftCorner.Y -= (m_padding*2); + imgrect2.LowerRightCorner.X += (m_padding*2); + imgrect2.LowerRightCorner.Y += (m_padding*2); + video::ITexture *texture = tsrc->getTexture(hotbar_selected_image); + core::dimension2di imgsize(texture->getOriginalSize()); draw2DImageFilterScaled(driver, texture, imgrect2, - core::rect(core::position2d(0, 0), - imgsize), + core::rect(core::position2d(0,0), imgsize), NULL, hbar_colors, true); } else { - video::SColor c_outside(255, 255, 0, 0); - // video::SColor c_outside(255,0,0,0); - // video::SColor c_inside(255,192,192,192); + video::SColor c_outside(255,255,0,0); + //video::SColor c_outside(255,0,0,0); + //video::SColor c_inside(255,192,192,192); s32 x1 = rect.UpperLeftCorner.X; s32 y1 = rect.UpperLeftCorner.Y; s32 x2 = rect.LowerRightCorner.X; s32 y2 = rect.LowerRightCorner.Y; // Black base borders driver->draw2DRectangle(c_outside, - core::rect(v2s32(x1 - m_padding, - y1 - m_padding), - v2s32(x2 + m_padding, y1)), - NULL); + core::rect( + v2s32(x1 - m_padding, y1 - m_padding), + v2s32(x2 + m_padding, y1) + ), NULL); driver->draw2DRectangle(c_outside, - core::rect(v2s32(x1 - m_padding, y2), - v2s32(x2 + m_padding, - y2 + m_padding)), - NULL); + core::rect( + v2s32(x1 - m_padding, y2), + v2s32(x2 + m_padding, y2 + m_padding) + ), NULL); driver->draw2DRectangle(c_outside, - core::rect(v2s32(x1 - m_padding, y1), - v2s32(x1, y2)), - NULL); + core::rect( + v2s32(x1 - m_padding, y1), + v2s32(x1, y2) + ), NULL); driver->draw2DRectangle(c_outside, - core::rect(v2s32(x2, y1), - v2s32(x2 + m_padding, y2)), - NULL); + core::rect( + v2s32(x2, y1), + v2s32(x2 + m_padding, y2) + ), NULL); /*// Light inside borders driver->draw2DRectangle(c_inside, core::rect( @@ -197,11 +195,11 @@ void Hud::drawItem(const ItemStack &item, const core::rect &rect, bool sele video::SColor bgcolor2(128, 0, 0, 0); if (!use_hotbar_image) driver->draw2DRectangle(bgcolor2, rect, NULL); - drawItemStack(driver, g_fontengine->getFont(), item, rect, NULL, client, - selected ? IT_ROT_SELECTED : IT_ROT_NONE); + drawItemStack(driver, g_fontengine->getFont(), item, rect, NULL, + client, selected ? IT_ROT_SELECTED : IT_ROT_NONE); } -// NOTE: selectitem = 0 -> no selected; selectitem 1-based +//NOTE: selectitem = 0 -> no selected; selectitem 1-based void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, s32 inv_offset, InventoryList *mainlist, u16 selectitem, u16 direction) { @@ -210,8 +208,8 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, g_touchscreengui->resetHud(); #endif - s32 height = m_hotbar_imagesize + m_padding * 2; - s32 width = (itemcount - inv_offset) * (m_hotbar_imagesize + m_padding * 2); + s32 height = m_hotbar_imagesize + m_padding * 2; + s32 width = (itemcount - inv_offset) * (m_hotbar_imagesize + m_padding * 2); if (direction == HUD_DIR_TOP_BOTTOM || direction == HUD_DIR_BOTTOM_TOP) { s32 tmp = height; @@ -237,14 +235,14 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, // draw customized item background if (use_hotbar_image) { - core::rect imgrect2(-m_padding / 2, -m_padding / 2, - width + m_padding / 2, height + m_padding / 2); + core::rect imgrect2(-m_padding/2, -m_padding/2, + width+m_padding/2, height+m_padding/2); core::rect rect2 = imgrect2 + pos; video::ITexture *texture = tsrc->getTexture(hotbar_image); core::dimension2di imgsize(texture->getOriginalSize()); draw2DImageFilterScaled(driver, texture, rect2, - core::rect(core::position2d(0, 0), imgsize), - NULL, hbar_colors, true); + core::rect(core::position2d(0,0), imgsize), + NULL, hbar_colors, true); } // Draw items @@ -255,25 +253,20 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, v2s32 steppos; switch (direction) { case HUD_DIR_RIGHT_LEFT: - steppos = v2s32(-(m_padding + (i - inv_offset) * fullimglen), - m_padding); + steppos = v2s32(-(m_padding + (i - inv_offset) * fullimglen), m_padding); break; case HUD_DIR_TOP_BOTTOM: - steppos = v2s32(m_padding, - m_padding + (i - inv_offset) * fullimglen); + steppos = v2s32(m_padding, m_padding + (i - inv_offset) * fullimglen); break; case HUD_DIR_BOTTOM_TOP: - steppos = v2s32(m_padding, - -(m_padding + (i - inv_offset) * fullimglen)); + steppos = v2s32(m_padding, -(m_padding + (i - inv_offset) * fullimglen)); break; default: - steppos = v2s32(m_padding + (i - inv_offset) * fullimglen, - m_padding); + steppos = v2s32(m_padding + (i - inv_offset) * fullimglen, m_padding); break; } - drawItem(mainlist->getItem(i), (imgrect + pos + steppos), - (i + 1) == selectitem); + drawItem(mainlist->getItem(i), (imgrect + pos + steppos), (i + 1) == selectitem); #ifdef HAVE_TOUCHSCREENGUI if (g_touchscreengui) @@ -282,22 +275,21 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, } } -// Calculates screen position of waypoint. Returns true if waypoint is visible (in front -// of the player), else false. +// Calculates screen position of waypoint. Returns true if waypoint is visible (in front of the player), else false. bool Hud::calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *pos) { v3f w_pos = e->world_pos * BS; - scene::ICameraSceneNode *camera = - RenderingEngine::get_scene_manager()->getActiveCamera(); + scene::ICameraSceneNode* camera = + RenderingEngine::get_scene_manager()->getActiveCamera(); w_pos -= intToFloat(camera_offset, BS); core::matrix4 trans = camera->getProjectionMatrix(); trans *= camera->getViewMatrix(); - f32 transformed_pos[4] = {w_pos.X, w_pos.Y, w_pos.Z, 1.0f}; + f32 transformed_pos[4] = { w_pos.X, w_pos.Y, w_pos.Z, 1.0f }; trans.multiplyWith1x4Matrix(transformed_pos); if (transformed_pos[3] < 0) return false; - f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f - : core::reciprocal(transformed_pos[3]); + f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f : + core::reciprocal(transformed_pos[3]); pos->X = m_screensize.X * (0.5 * transformed_pos[0] * zDiv + 0.5); pos->Y = m_screensize.Y * (0.5 - transformed_pos[1] * zDiv * 0.5); return true; @@ -306,7 +298,7 @@ bool Hud::calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *p void Hud::drawLuaElements(const v3s16 &camera_offset) { u32 text_height = g_fontengine->getTextHeight(); - irr::gui::IGUIFont *font = g_fontengine->getFont(); + irr::gui::IGUIFont* font = g_fontengine->getFont(); // Reorder elements by z_index std::vector ids; @@ -326,150 +318,122 @@ void Hud::drawLuaElements(const v3s16 &camera_offset) for (size_t i : ids) { HudElement *e = player->getHud(i); - v2s32 pos(floor(e->pos.X * (float)m_screensize.X + 0.5), - floor(e->pos.Y * (float)m_screensize.Y + 0.5)); + v2s32 pos(floor(e->pos.X * (float) m_screensize.X + 0.5), + floor(e->pos.Y * (float) m_screensize.Y + 0.5)); switch (e->type) { - case HUD_ELEM_TEXT: { - irr::gui::IGUIFont *textfont = font; - unsigned int font_size = g_fontengine->getDefaultFontSize(); + case HUD_ELEM_TEXT: { + irr::gui::IGUIFont *textfont = font; + unsigned int font_size = g_fontengine->getDefaultFontSize(); - if (e->size.X > 0) - font_size *= e->size.X; + if (e->size.X > 0) + font_size *= e->size.X; - if (font_size != g_fontengine->getDefaultFontSize()) - textfont = g_fontengine->getFont(font_size); + if (font_size != g_fontengine->getDefaultFontSize()) + textfont = g_fontengine->getFont(font_size); - video::SColor color(255, (e->number >> 16) & 0xFF, - (e->number >> 8) & 0xFF, (e->number >> 0) & 0xFF); - std::wstring text = unescape_translate(utf8_to_wide(e->text)); - core::dimension2d textsize = - textfont->getDimension(text.c_str()); + video::SColor color(255, (e->number >> 16) & 0xFF, + (e->number >> 8) & 0xFF, + (e->number >> 0) & 0xFF); + std::wstring text = unescape_translate(utf8_to_wide(e->text)); + core::dimension2d textsize = textfont->getDimension(text.c_str()); #ifdef __ANDROID__ - // The text size on Android is not proportional with the actual - // scaling - irr::gui::IGUIFont *font_scaled = - font_size <= 3 ? textfont - : g_fontengine->getFont( - font_size - 3); - if (e->offset.X < -20) - textsize = font_scaled->getDimension(text.c_str()); + // The text size on Android is not proportional with the actual scaling + irr::gui::IGUIFont *font_scaled = font_size <= 3 ? + textfont : g_fontengine->getFont(font_size - 3); + if (e->offset.X < -20) + textsize = font_scaled->getDimension(text.c_str()); #endif - v2s32 offset((e->align.X - 1.0) * (textsize.Width / 2), - (e->align.Y - 1.0) * (textsize.Height / 2)); - core::rect size(0, 0, e->scale.X * m_scale_factor, - text_height * e->scale.Y * m_scale_factor); - v2s32 offs(e->offset.X * m_scale_factor, - e->offset.Y * m_scale_factor); + v2s32 offset((e->align.X - 1.0) * (textsize.Width / 2), + (e->align.Y - 1.0) * (textsize.Height / 2)); + core::rect size(0, 0, e->scale.X * m_scale_factor, + text_height * e->scale.Y * m_scale_factor); + v2s32 offs(e->offset.X * m_scale_factor, + e->offset.Y * m_scale_factor); #ifdef __ANDROID__ - if (e->offset.X < -20) - font_scaled->draw(text.c_str(), - size + pos + offset + offs, color); - else + if (e->offset.X < -20) + font_scaled->draw(text.c_str(), size + pos + offset + offs, color); + else #endif - { - textfont->draw(text.c_str(), size + pos + offset + offs, - color); - } - break; - } - case HUD_ELEM_STATBAR: { - v2s32 offs(e->offset.X, e->offset.Y); - drawStatbar(pos, HUD_CORNER_UPPER, e->dir, e->text, e->text2, + { + textfont->draw(text.c_str(), size + pos + offset + offs, color); + } + break; } + case HUD_ELEM_STATBAR: { + v2s32 offs(e->offset.X, e->offset.Y); + drawStatbar(pos, HUD_CORNER_UPPER, e->dir, e->text, e->text2, e->number, e->item, offs, e->size); - break; - } - case HUD_ELEM_INVENTORY: { - InventoryList *inv = inventory->getList(e->text); - drawItems(pos, v2s32(e->offset.X, e->offset.Y), e->number, 0, inv, - e->item, e->dir); - break; - } - case HUD_ELEM_WAYPOINT: { - if (!calculateScreenPos(camera_offset, e, &pos)) - break; - v3f p_pos = player->getPosition() / BS; - pos += v2s32(e->offset.X, e->offset.Y); - video::SColor color(255, (e->number >> 16) & 0xFF, - (e->number >> 8) & 0xFF, (e->number >> 0) & 0xFF); - std::wstring text = unescape_translate(utf8_to_wide(e->name)); - const std::string &unit = e->text; - // waypoints reuse the item field to store precision, item = - // precision + 1 - u32 item = e->item; - float precision = (item == 0) ? 10.0f : (item - 1.f); - bool draw_precision = precision > 0; - - core::rect bounds(0, 0, - font->getDimension(text.c_str()).Width, - (draw_precision ? 2 : 1) * text_height); - pos.Y += (e->align.Y - 1.0) * bounds.getHeight() / 2; - bounds += pos; - font->draw(text.c_str(), - bounds + v2s32((e->align.X - 1.0) * bounds.getWidth() / - 2, - 0), - color); - if (draw_precision) { - std::ostringstream os; - float distance = - std::floor(precision * - p_pos.getDistanceFrom( - e->world_pos)) / - precision; - os << distance << unit; - text = unescape_translate(utf8_to_wide(os.str())); - bounds.LowerRightCorner.X = - bounds.UpperLeftCorner.X + - font->getDimension(text.c_str()).Width; - font->draw(text.c_str(), - bounds + v2s32((e->align.X - 1.0f) * bounds.getWidth() / - 2, - text_height), - color); + break; } + case HUD_ELEM_INVENTORY: { + InventoryList *inv = inventory->getList(e->text); + drawItems(pos, v2s32(e->offset.X, e->offset.Y), e->number, 0, + inv, e->item, e->dir); + break; } + case HUD_ELEM_WAYPOINT: { + if (!calculateScreenPos(camera_offset, e, &pos)) + break; + v3f p_pos = player->getPosition() / BS; + pos += v2s32(e->offset.X, e->offset.Y); + video::SColor color(255, (e->number >> 16) & 0xFF, + (e->number >> 8) & 0xFF, + (e->number >> 0) & 0xFF); + std::wstring text = unescape_translate(utf8_to_wide(e->name)); + const std::string &unit = e->text; + // waypoints reuse the item field to store precision, item = precision + 1 + u32 item = e->item; + float precision = (item == 0) ? 10.0f : (item - 1.f); + bool draw_precision = precision > 0; + + core::rect bounds(0, 0, font->getDimension(text.c_str()).Width, (draw_precision ? 2:1) * text_height); + pos.Y += (e->align.Y - 1.0) * bounds.getHeight() / 2; + bounds += pos; + font->draw(text.c_str(), bounds + v2s32((e->align.X - 1.0) * bounds.getWidth() / 2, 0), color); + if (draw_precision) { + std::ostringstream os; + float distance = std::floor(precision * p_pos.getDistanceFrom(e->world_pos)) / precision; + os << distance << unit; + text = unescape_translate(utf8_to_wide(os.str())); + bounds.LowerRightCorner.X = bounds.UpperLeftCorner.X + font->getDimension(text.c_str()).Width; + font->draw(text.c_str(), bounds + v2s32((e->align.X - 1.0f) * bounds.getWidth() / 2, text_height), color); + } + break; } + case HUD_ELEM_IMAGE_WAYPOINT: { + if (!calculateScreenPos(camera_offset, e, &pos)) + break; } - break; - } - case HUD_ELEM_IMAGE_WAYPOINT: { - if (!calculateScreenPos(camera_offset, e, &pos)) - break; - } - case HUD_ELEM_IMAGE: { - video::ITexture *texture = tsrc->getTexture(e->text); - if (!texture) - continue; - - const video::SColor color(255, 255, 255, 255); - const video::SColor colors[] = {color, color, color, color}; - core::dimension2di imgsize(texture->getOriginalSize()); - v2s32 dstsize(imgsize.Width * e->scale.X * m_scale_factor, - imgsize.Height * e->scale.Y * m_scale_factor); - if (e->scale.X < 0) - dstsize.X = m_screensize.X * (e->scale.X * -0.01); - if (e->scale.Y < 0) - dstsize.Y = m_screensize.Y * (e->scale.Y * -0.01); - v2s32 offset((e->align.X - 1.0) * dstsize.X / 2, - (e->align.Y - 1.0) * dstsize.Y / 2); - core::rect rect(0, 0, dstsize.X, dstsize.Y); - rect += pos + offset + - v2s32(e->offset.X * m_scale_factor, - e->offset.Y * m_scale_factor); - draw2DImageFilterScaled(driver, texture, rect, - core::rect(core::position2d(0, 0), - imgsize), + case HUD_ELEM_IMAGE: { + video::ITexture *texture = tsrc->getTexture(e->text); + if (!texture) + continue; + + const video::SColor color(255, 255, 255, 255); + const video::SColor colors[] = {color, color, color, color}; + core::dimension2di imgsize(texture->getOriginalSize()); + v2s32 dstsize(imgsize.Width * e->scale.X * m_scale_factor, + imgsize.Height * e->scale.Y * m_scale_factor); + if (e->scale.X < 0) + dstsize.X = m_screensize.X * (e->scale.X * -0.01); + if (e->scale.Y < 0) + dstsize.Y = m_screensize.Y * (e->scale.Y * -0.01); + v2s32 offset((e->align.X - 1.0) * dstsize.X / 2, + (e->align.Y - 1.0) * dstsize.Y / 2); + core::rect rect(0, 0, dstsize.X, dstsize.Y); + rect += pos + offset + v2s32(e->offset.X * m_scale_factor, + e->offset.Y * m_scale_factor); + draw2DImageFilterScaled(driver, texture, rect, + core::rect(core::position2d(0,0), imgsize), NULL, colors, true); - break; - } - default: - infostream << "Hud::drawLuaElements: ignoring drawform " - << e->type << " of hud element ID " << i - << " due to unrecognized type" << std::endl; + break; } + default: + infostream << "Hud::drawLuaElements: ignoring drawform " << e->type << + " of hud element ID " << i << " due to unrecognized type" << std::endl; } } } -void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &texture, - const std::string &bgtexture, s32 count, s32 maxcount, v2s32 offset, - v2s32 size) + +void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, + const std::string &texture, const std::string &bgtexture, + s32 count, s32 maxcount, v2s32 offset, v2s32 size) { const video::SColor color(255, 255, 255, 255); const video::SColor colors[] = {color, color, color, color}; @@ -488,12 +452,12 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex if (size == v2s32()) { dstd = srcd; dstd.Height *= m_scale_factor; - dstd.Width *= m_scale_factor; + dstd.Width *= m_scale_factor; offset.X *= m_scale_factor; offset.Y *= m_scale_factor; } else { dstd.Height = size.Y * m_scale_factor; - dstd.Width = size.X * m_scale_factor; + dstd.Width = size.X * m_scale_factor; offset.X *= m_scale_factor; offset.Y *= m_scale_factor; } @@ -506,27 +470,29 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex v2s32 steppos; switch (drawdir) { - case HUD_DIR_RIGHT_LEFT: - steppos = v2s32(-1, 0); - break; - case HUD_DIR_TOP_BOTTOM: - steppos = v2s32(0, 1); - break; - case HUD_DIR_BOTTOM_TOP: - steppos = v2s32(0, -1); - break; - default: - // From left to right - steppos = v2s32(1, 0); - break; + case HUD_DIR_RIGHT_LEFT: + steppos = v2s32(-1, 0); + break; + case HUD_DIR_TOP_BOTTOM: + steppos = v2s32(0, 1); + break; + case HUD_DIR_BOTTOM_TOP: + steppos = v2s32(0, -1); + break; + default: + // From left to right + steppos = v2s32(1, 0); + break; } - auto calculate_clipping_rect = [](core::dimension2di src, - v2s32 steppos) -> core::rect { + auto calculate_clipping_rect = [] (core::dimension2di src, + v2s32 steppos) -> core::rect { + // Create basic rectangle core::rect rect(0, 0, - src.Width - std::abs(steppos.X) * src.Width / 2, - src.Height - std::abs(steppos.Y) * src.Height / 2); + src.Width - std::abs(steppos.X) * src.Width / 2, + src.Height - std::abs(steppos.Y) * src.Height / 2 + ); // Move rectangle left or down if (steppos.X == -1) rect += v2s32(src.Width / 2, 0); @@ -541,8 +507,8 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex if (count % 2 == 1) { // Need to draw halves: Calculate rectangles - srchalfrect = calculate_clipping_rect(srcd, steppos); - dsthalfrect = calculate_clipping_rect(dstd, steppos); + srchalfrect = calculate_clipping_rect(srcd, steppos); + dsthalfrect = calculate_clipping_rect(dstd, steppos); srchalfrect2 = calculate_clipping_rect(srcd, steppos * -1); dsthalfrect2 = calculate_clipping_rect(dstd, steppos * -1); } @@ -556,19 +522,20 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex core::rect dstrect(0, 0, dstd.Width, dstd.Height); dstrect += p; - draw2DImageFilterScaled(driver, stat_texture, dstrect, srcrect, NULL, - colors, true); + draw2DImageFilterScaled(driver, stat_texture, + dstrect, srcrect, NULL, colors, true); p += steppos; } if (count % 2 == 1) { // Draw half a texture - draw2DImageFilterScaled(driver, stat_texture, dsthalfrect + p, - srchalfrect, NULL, colors, true); + draw2DImageFilterScaled(driver, stat_texture, + dsthalfrect + p, srchalfrect, NULL, colors, true); if (stat_texture_bg && maxcount > count) { - draw2DImageFilterScaled(driver, stat_texture_bg, dsthalfrect2 + p, - srchalfrect2, NULL, colors, true); + draw2DImageFilterScaled(driver, stat_texture_bg, + dsthalfrect2 + p, srchalfrect2, + NULL, colors, true); p += steppos; } } @@ -585,26 +552,28 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex core::rect dstrect(0, 0, dstd.Width, dstd.Height); dstrect += p; - draw2DImageFilterScaled(driver, stat_texture_bg, dstrect, srcrect, + draw2DImageFilterScaled(driver, stat_texture_bg, + dstrect, srcrect, NULL, colors, true); p += steppos; } if (maxcount % 2 == 1) { - draw2DImageFilterScaled(driver, stat_texture_bg, dsthalfrect + p, - srchalfrect, NULL, colors, true); + draw2DImageFilterScaled(driver, stat_texture_bg, + dsthalfrect + p, srchalfrect, + NULL, colors, true); } } } -void Hud::drawHotbar(u16 playeritem) -{ + +void Hud::drawHotbar(u16 playeritem) { v2s32 centerlowerpos(m_displaycenter.X, m_screensize.Y); InventoryList *mainlist = inventory->getList("main"); if (mainlist == NULL) { - // silently ignore this we may not be initialized completely + //silently ignore this we may not be initialized completely return; } @@ -613,57 +582,49 @@ void Hud::drawHotbar(u16 playeritem) v2s32 pos = centerlowerpos - v2s32(width / 2, m_hotbar_imagesize + m_padding * 3); const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - if ((float)width / (float)window_size.X <= + if ((float) width / (float) window_size.X <= g_settings->getFloat("hud_hotbar_max_width")) { if (player->hud_flags & HUD_FLAG_HOTBAR_VISIBLE) { - drawItems(pos, v2s32(0, 0), hotbar_itemcount, 0, mainlist, - playeritem + 1, 0); + drawItems(pos, v2s32(0, 0), hotbar_itemcount, 0, mainlist, playeritem + 1, 0); } } else { - pos.X += width / 4; + pos.X += width/4; v2s32 secondpos = pos; pos = pos - v2s32(0, m_hotbar_imagesize + m_padding); if (player->hud_flags & HUD_FLAG_HOTBAR_VISIBLE) { - drawItems(pos, v2s32(0, 0), hotbar_itemcount / 2, 0, mainlist, - playeritem + 1, 0); + drawItems(pos, v2s32(0, 0), hotbar_itemcount / 2, 0, + mainlist, playeritem + 1, 0); drawItems(secondpos, v2s32(0, 0), hotbar_itemcount, - hotbar_itemcount / 2, mainlist, playeritem + 1, - 0); + hotbar_itemcount / 2, mainlist, playeritem + 1, 0); } } } + void Hud::drawCrosshair() { if (pointing_at_object) { if (use_object_crosshair_image) { - video::ITexture *object_crosshair = - tsrc->getTexture("object_crosshair.png"); - v2u32 size = object_crosshair->getOriginalSize(); + video::ITexture *object_crosshair = tsrc->getTexture("object_crosshair.png"); + v2u32 size = object_crosshair->getOriginalSize(); v2s32 lsize = v2s32(m_displaycenter.X - (size.X / 2), m_displaycenter.Y - (size.Y / 2)); driver->draw2DImage(object_crosshair, lsize, - core::rect(0, 0, size.X, size.Y), nullptr, - crosshair_argb, true); + core::rect(0, 0, size.X, size.Y), + nullptr, crosshair_argb, true); } else { driver->draw2DLine( - m_displaycenter - - v2s32(OBJECT_CROSSHAIR_LINE_SIZE, - OBJECT_CROSSHAIR_LINE_SIZE), - m_displaycenter + - v2s32(OBJECT_CROSSHAIR_LINE_SIZE, - OBJECT_CROSSHAIR_LINE_SIZE), - crosshair_argb); + m_displaycenter - v2s32(OBJECT_CROSSHAIR_LINE_SIZE, + OBJECT_CROSSHAIR_LINE_SIZE), + m_displaycenter + v2s32(OBJECT_CROSSHAIR_LINE_SIZE, + OBJECT_CROSSHAIR_LINE_SIZE), crosshair_argb); driver->draw2DLine( - m_displaycenter + - v2s32(OBJECT_CROSSHAIR_LINE_SIZE, - -OBJECT_CROSSHAIR_LINE_SIZE), - m_displaycenter + - v2s32(-OBJECT_CROSSHAIR_LINE_SIZE, - OBJECT_CROSSHAIR_LINE_SIZE), - crosshair_argb); + m_displaycenter + v2s32(OBJECT_CROSSHAIR_LINE_SIZE, + -OBJECT_CROSSHAIR_LINE_SIZE), + m_displaycenter + v2s32(-OBJECT_CROSSHAIR_LINE_SIZE, + OBJECT_CROSSHAIR_LINE_SIZE), crosshair_argb); } return; @@ -671,19 +632,17 @@ void Hud::drawCrosshair() if (use_crosshair_image) { video::ITexture *crosshair = tsrc->getTexture("crosshair.png"); - v2u32 size = crosshair->getOriginalSize(); + v2u32 size = crosshair->getOriginalSize(); v2s32 lsize = v2s32(m_displaycenter.X - (size.X / 2), m_displaycenter.Y - (size.Y / 2)); driver->draw2DImage(crosshair, lsize, - core::rect(0, 0, size.X, size.Y), nullptr, - crosshair_argb, true); + core::rect(0, 0, size.X, size.Y), + nullptr, crosshair_argb, true); } else { driver->draw2DLine(m_displaycenter - v2s32(CROSSHAIR_LINE_SIZE, 0), - m_displaycenter + v2s32(CROSSHAIR_LINE_SIZE, 0), - crosshair_argb); + m_displaycenter + v2s32(CROSSHAIR_LINE_SIZE, 0), crosshair_argb); driver->draw2DLine(m_displaycenter - v2s32(0, CROSSHAIR_LINE_SIZE), - m_displaycenter + v2s32(0, CROSSHAIR_LINE_SIZE), - crosshair_argb); + m_displaycenter + v2s32(0, CROSSHAIR_LINE_SIZE), crosshair_argb); } } @@ -700,11 +659,10 @@ void Hud::drawSelectionMesh() // Draw 3D selection boxes video::SMaterial oldmaterial = driver->getMaterial2D(); driver->setMaterial(m_selection_material); - for (auto &selection_box : m_selection_boxes) { - aabb3f box = aabb3f(selection_box.MinEdge + - m_selection_pos_with_offset, - selection_box.MaxEdge + - m_selection_pos_with_offset); + for (auto & selection_box : m_selection_boxes) { + aabb3f box = aabb3f( + selection_box.MinEdge + m_selection_pos_with_offset, + selection_box.MaxEdge + m_selection_pos_with_offset); u32 r = (selectionbox_argb.getRed() * m_selection_mesh_color.getRed() / 255); @@ -721,12 +679,12 @@ void Hud::drawSelectionMesh() driver->setMaterial(m_selection_material); setMeshColor(m_selection_mesh, m_selection_mesh_color); video::SColor face_color(0, - MYMIN(255, m_selection_mesh_color.getRed() * 1.5), - MYMIN(255, m_selection_mesh_color.getGreen() * 1.5), - MYMIN(255, m_selection_mesh_color.getBlue() * 1.5)); - setMeshColorByNormal( - m_selection_mesh, m_selected_face_normal, face_color); - scene::IMesh *mesh = cloneMesh(m_selection_mesh); + MYMIN(255, m_selection_mesh_color.getRed() * 1.5), + MYMIN(255, m_selection_mesh_color.getGreen() * 1.5), + MYMIN(255, m_selection_mesh_color.getBlue() * 1.5)); + setMeshColorByNormal(m_selection_mesh, m_selected_face_normal, + face_color); + scene::IMesh* mesh = cloneMesh(m_selection_mesh); translateMesh(mesh, m_selection_pos_with_offset); u32 mc = m_selection_mesh->getMeshBufferCount(); for (u32 i = 0; i < mc; i++) { @@ -757,8 +715,14 @@ void Hud::updateSelectionMesh(const v3s16 &camera_offset) // New pointed object, create new mesh. // Texture UV coordinates for selection boxes - static f32 texture_uv[24] = {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, - 1, 1, 0, 0, 1, 1}; + static f32 texture_uv[24] = { + 0,0,1,1, + 0,0,1,1, + 0,0,1,1, + 0,0,1,1, + 0,0,1,1, + 0,0,1,1 + }; // Use single halo box instead of multiple overlapping boxes. // Temporary solution - problem can be solved with multiple @@ -773,34 +737,37 @@ void Hud::updateSelectionMesh(const v3s16 &camera_offset) } m_halo_boxes.push_back(halo_box); - m_selection_mesh = convertNodeboxesToMesh(m_halo_boxes, texture_uv, 0.5); + m_selection_mesh = convertNodeboxesToMesh( + m_halo_boxes, texture_uv, 0.5); } -void Hud::resizeHotbar() -{ +void Hud::resizeHotbar() { const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); if (m_screensize != window_size) { - m_hotbar_imagesize = floor( - HOTBAR_IMAGE_SIZE * RenderingEngine::getDisplayDensity() + - 0.5); + m_hotbar_imagesize = floor(HOTBAR_IMAGE_SIZE * + RenderingEngine::getDisplayDensity() + 0.5); m_hotbar_imagesize *= m_hud_scaling; m_padding = m_hotbar_imagesize / 12; m_screensize = window_size; - m_displaycenter = v2s32(m_screensize.X / 2, m_screensize.Y / 2); + m_displaycenter = v2s32(m_screensize.X/2,m_screensize.Y/2); } } -struct MeshTimeInfo -{ +struct MeshTimeInfo { u64 time; scene::IMesh *mesh = nullptr; }; -void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, - const ItemStack &item, const core::rect &rect, - const core::rect *clip, Client *client, - ItemRotationKind rotation_kind, const v3s16 &angle, +void drawItemStack( + video::IVideoDriver *driver, + gui::IGUIFont *font, + const ItemStack &item, + const core::rect &rect, + const core::rect *clip, + Client *client, + ItemRotationKind rotation_kind, + const v3s16 &angle, const v3s16 &rotation_speed) { static MeshTimeInfo rotation_time_infos[IT_ROT_NONE]; @@ -825,9 +792,7 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, ti.mesh = mesh; ti.time = porting::getTimeMs(); } else { - delta = porting::getDeltaMs( - ti.time, porting::getTimeMs()) % - 100000; + delta = porting::getDeltaMs(ti.time, porting::getTimeMs()) % 100000; } } core::rect oldViewPort = driver->getViewPort(); @@ -842,26 +807,18 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, core::matrix4 ViewMatrix; ViewMatrix.buildProjectionMatrixOrthoLH( - 2.0f * viewrect.getWidth() / rect.getWidth(), - 2.0f * viewrect.getHeight() / rect.getHeight(), -1.0f, - 100.0f); + 2.0f * viewrect.getWidth() / rect.getWidth(), + 2.0f * viewrect.getHeight() / rect.getHeight(), + -1.0f, + 100.0f); ViewMatrix.setTranslation(core::vector3df( - 1.0f * - (rect.LowerRightCorner.X + - rect.UpperLeftCorner.X - - viewrect.LowerRightCorner - .X - - viewrect.UpperLeftCorner - .X) / - viewrect.getWidth(), - 1.0f * - (viewrect.LowerRightCorner.Y + - viewrect.UpperLeftCorner - .Y - - rect.LowerRightCorner.Y - - rect.UpperLeftCorner.Y) / - viewrect.getHeight(), - 0.0f)); + 1.0f * (rect.LowerRightCorner.X + rect.UpperLeftCorner.X - + viewrect.LowerRightCorner.X - viewrect.UpperLeftCorner.X) / + viewrect.getWidth(), + 1.0f * (viewrect.LowerRightCorner.Y + viewrect.UpperLeftCorner.Y - + rect.LowerRightCorner.Y - rect.UpperLeftCorner.Y) / + viewrect.getHeight(), + 0.0f)); driver->setTransform(video::ETS_PROJECTION, ProjMatrix); driver->setTransform(video::ETS_VIEW, ViewMatrix); @@ -870,20 +827,22 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, matrix.makeIdentity(); static thread_local bool enable_animations = - g_settings->getBool("inventory_items_animations"); + g_settings->getBool("inventory_items_animations"); if (enable_animations) { - float timer_f = (float)delta / 5000.f; + float timer_f = (float) delta / 5000.f; matrix.setRotationDegrees(v3f( - angle.X + rotation_speed.X * 3.60f * timer_f, - angle.Y + rotation_speed.Y * 3.60f * timer_f, - angle.Z + rotation_speed.Z * 3.60f * timer_f)); + angle.X + rotation_speed.X * 3.60f * timer_f, + angle.Y + rotation_speed.Y * 3.60f * timer_f, + angle.Z + rotation_speed.Z * 3.60f * timer_f) + ); } driver->setTransform(video::ETS_WORLD, matrix); driver->setViewPort(viewrect); - video::SColor basecolor = client->idef()->getItemstackColor(item, client); + video::SColor basecolor = + client->idef()->getItemstackColor(item, client); u32 mc = mesh->getMeshBufferCount(); for (u32 j = 0; j < mc; ++j) { @@ -919,13 +878,10 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, if (def.type == ITEM_NODE && def.inventory_image.empty() && !def.inventory_overlay.empty()) { ITextureSource *tsrc = client->getTextureSource(); - video::ITexture *overlay_texture = - tsrc->getTexture(def.inventory_overlay); - core::dimension2d dimens = - overlay_texture->getOriginalSize(); + video::ITexture *overlay_texture = tsrc->getTexture(def.inventory_overlay); + core::dimension2d dimens = overlay_texture->getOriginalSize(); core::rect srcrect(0, 0, dimens.Width, dimens.Height); - draw2DImageFilterScaled(driver, overlay_texture, rect, srcrect, - clip, 0, true); + draw2DImageFilterScaled(driver, overlay_texture, rect, srcrect, clip, 0, true); } } @@ -935,15 +891,17 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, float barpad_x = rect.getWidth() / 16; float barpad_y = rect.getHeight() / 16; - core::rect progressrect(rect.UpperLeftCorner.X + barpad_x, - rect.LowerRightCorner.Y - barpad_y - barheight, - rect.LowerRightCorner.X - barpad_x, - rect.LowerRightCorner.Y - barpad_y); + core::rect progressrect( + rect.UpperLeftCorner.X + barpad_x, + rect.LowerRightCorner.Y - barpad_y - barheight, + rect.LowerRightCorner.X - barpad_x, + rect.LowerRightCorner.Y - barpad_y); // Shrink progressrect by amount of tool damage float wear = item.wear / 65535.0f; - int progressmid = wear * progressrect.UpperLeftCorner.X + - (1 - wear) * progressrect.LowerRightCorner.X; + int progressmid = + wear * progressrect.UpperLeftCorner.X + + (1 - wear) * progressrect.LowerRightCorner.X; // Compute progressbar color // wear = 0.0: green @@ -975,9 +933,11 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, v2s32 sdim(dim.X, dim.Y); core::rect rect2( - /*rect.UpperLeftCorner, - core::dimension2d(rect.getWidth(), 15)*/ - rect.LowerRightCorner - sdim, sdim); + /*rect.UpperLeftCorner, + core::dimension2d(rect.getWidth(), 15)*/ + rect.LowerRightCorner - sdim, + sdim + ); video::SColor bgcolor(128, 0, 0, 0); driver->draw2DRectangle(bgcolor, rect2, clip); @@ -987,11 +947,15 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, } } -void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, - const ItemStack &item, const core::rect &rect, - const core::rect *clip, Client *client, +void drawItemStack( + video::IVideoDriver *driver, + gui::IGUIFont *font, + const ItemStack &item, + const core::rect &rect, + const core::rect *clip, + Client *client, ItemRotationKind rotation_kind) { drawItemStack(driver, font, item, rect, clip, client, rotation_kind, - v3s16(0, 0, 0), v3s16(0, 100, 0)); + v3s16(0, 0, 0), v3s16(0, 100, 0)); } diff --git a/src/client/hud.h b/src/client/hud.h index 818e3dea3..ba34d479d 100644 --- a/src/client/hud.h +++ b/src/client/hud.h @@ -85,9 +85,9 @@ class Hud private: bool calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *pos); - void drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &texture, - const std::string &bgtexture, s32 count, s32 maxcount, - v2s32 offset, v2s32 size = v2s32()); + void drawStatbar(v2s32 pos, u16 corner, u16 drawdir, + const std::string &texture, const std::string& bgtexture, + s32 count, s32 maxcount, v2s32 offset, v2s32 size = v2s32()); void drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, s32 inv_offset, InventoryList *mainlist, u16 selectitem, @@ -100,8 +100,7 @@ class Hud v3s16 m_camera_offset; v2u32 m_screensize; v2s32 m_displaycenter; - s32 m_hotbar_imagesize; // Takes hud_scaling into account, updated by - // resizeHotbar() + s32 m_hotbar_imagesize; // Takes hud_scaling into account, updated by resizeHotbar() s32 m_padding; // Takes hud_scaling into account, updated by resizeHotbar() video::SColor hbar_colors[4]; @@ -133,13 +132,22 @@ enum ItemRotationKind IT_ROT_NONE, // Must be last, also serves as number }; -void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, - const ItemStack &item, const core::rect &rect, - const core::rect *clip, Client *client, +void drawItemStack(video::IVideoDriver *driver, + gui::IGUIFont *font, + const ItemStack &item, + const core::rect &rect, + const core::rect *clip, + Client *client, ItemRotationKind rotation_kind); -void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font, - const ItemStack &item, const core::rect &rect, - const core::rect *clip, Client *client, - ItemRotationKind rotation_kind, const v3s16 &angle, +void drawItemStack( + video::IVideoDriver *driver, + gui::IGUIFont *font, + const ItemStack &item, + const core::rect &rect, + const core::rect *clip, + Client *client, + ItemRotationKind rotation_kind, + const v3s16 &angle, const v3s16 &rotation_speed); + diff --git a/src/client/imagefilters.cpp b/src/client/imagefilters.cpp index a75e7f8d6..0fa501410 100644 --- a/src/client/imagefilters.cpp +++ b/src/client/imagefilters.cpp @@ -38,45 +38,44 @@ void imageCleanTransparent(video::IImage *src, u32 threshold) // Walk each pixel looking for fully transparent ones. // Note: loop y around x for better cache locality. for (u32 ctry = 0; ctry < dim.Height; ctry++) - for (u32 ctrx = 0; ctrx < dim.Width; ctrx++) { + for (u32 ctrx = 0; ctrx < dim.Width; ctrx++) { - // Ignore opaque pixels. - irr::video::SColor c = src->getPixel(ctrx, ctry); - if (c.getAlpha() > threshold) + // Ignore opaque pixels. + irr::video::SColor c = src->getPixel(ctrx, ctry); + if (c.getAlpha() > threshold) + continue; + + // Sample size and total weighted r, g, b values. + u32 ss = 0, sr = 0, sg = 0, sb = 0; + + // Walk each neighbor pixel (clipped to image bounds). + for (u32 sy = (ctry < 1) ? 0 : (ctry - 1); + sy <= (ctry + 1) && sy < dim.Height; sy++) + for (u32 sx = (ctrx < 1) ? 0 : (ctrx - 1); + sx <= (ctrx + 1) && sx < dim.Width; sx++) { + + // Ignore transparent pixels. + irr::video::SColor d = src->getPixel(sx, sy); + if (d.getAlpha() <= threshold) continue; - // Sample size and total weighted r, g, b values. - u32 ss = 0, sr = 0, sg = 0, sb = 0; - - // Walk each neighbor pixel (clipped to image bounds). - for (u32 sy = (ctry < 1) ? 0 : (ctry - 1); - sy <= (ctry + 1) && sy < dim.Height; sy++) - for (u32 sx = (ctrx < 1) ? 0 : (ctrx - 1); - sx <= (ctrx + 1) && sx < dim.Width; - sx++) { - - // Ignore transparent pixels. - irr::video::SColor d = src->getPixel(sx, sy); - if (d.getAlpha() <= threshold) - continue; - - // Add RGB values weighted by alpha. - u32 a = d.getAlpha(); - ss += a; - sr += a * d.getRed(); - sg += a * d.getGreen(); - sb += a * d.getBlue(); - } - - // If we found any neighbor RGB data, set pixel to average - // weighted by alpha. - if (ss > 0) { - c.setRed(sr / ss); - c.setGreen(sg / ss); - c.setBlue(sb / ss); - src->setPixel(ctrx, ctry, c); - } + // Add RGB values weighted by alpha. + u32 a = d.getAlpha(); + ss += a; + sr += a * d.getRed(); + sg += a * d.getGreen(); + sb += a * d.getBlue(); } + + // If we found any neighbor RGB data, set pixel to average + // weighted by alpha. + if (ss > 0) { + c.setRed(sr / ss); + c.setGreen(sg / ss); + c.setBlue(sb / ss); + src->setPixel(ctrx, ctry, c); + } + } } /* Scale a region of an image into another image, using nearest-neighbor with @@ -86,8 +85,7 @@ void imageCleanTransparent(video::IImage *src, u32 threshold) * filter is designed to produce the most accurate results for both upscaling * and downscaling. */ -void imageScaleNNAA( - video::IImage *src, const core::rect &srcrect, video::IImage *dest) +void imageScaleNNAA(video::IImage *src, const core::rect &srcrect, video::IImage *dest) { double sx, sy, minsx, maxsx, minsy, maxsy, area, ra, ga, ba, aa, pw, ph, pa; u32 dy, dx; @@ -103,73 +101,72 @@ void imageScaleNNAA( // Note: loop y around x for better cache locality. core::dimension2d dim = dest->getDimension(); for (dy = 0; dy < dim.Height; dy++) - for (dx = 0; dx < dim.Width; dx++) { - - // Calculate floating-point source rectangle bounds. - // Do some basic clipping, and for mirrored/flipped rects, - // make sure min/max are in the right order. - minsx = sox + (dx * sw / dim.Width); - minsx = rangelim(minsx, 0, sox + sw); - maxsx = minsx + sw / dim.Width; - maxsx = rangelim(maxsx, 0, sox + sw); - if (minsx > maxsx) - SWAP(double, minsx, maxsx); - minsy = soy + (dy * sh / dim.Height); - minsy = rangelim(minsy, 0, soy + sh); - maxsy = minsy + sh / dim.Height; - maxsy = rangelim(maxsy, 0, soy + sh); - if (minsy > maxsy) - SWAP(double, minsy, maxsy); - - // Total area, and integral of r, g, b values over that area, - // initialized to zero, to be summed up in next loops. - area = 0; - ra = 0; - ga = 0; - ba = 0; - aa = 0; - - // Loop over the integral pixel positions described by those - // bounds. - for (sy = floor(minsy); sy < maxsy; sy++) - for (sx = floor(minsx); sx < maxsx; sx++) { - - // Calculate width, height, then area of dest - // pixel that's covered by this source pixel. - pw = 1; - if (minsx > sx) - pw += sx - minsx; - if (maxsx < (sx + 1)) - pw += maxsx - sx - 1; - ph = 1; - if (minsy > sy) - ph += sy - minsy; - if (maxsy < (sy + 1)) - ph += maxsy - sy - 1; - pa = pw * ph; - - // Get source pixel and add it to totals, weighted - // by covered area and alpha. - pxl = src->getPixel((u32)sx, (u32)sy); - area += pa; - ra += pa * pxl.getRed(); - ga += pa * pxl.getGreen(); - ba += pa * pxl.getBlue(); - aa += pa * pxl.getAlpha(); - } - - // Set the destination image pixel to the average color. - if (area > 0) { - pxl.setRed(ra / area + 0.5); - pxl.setGreen(ga / area + 0.5); - pxl.setBlue(ba / area + 0.5); - pxl.setAlpha(aa / area + 0.5); - } else { - pxl.setRed(0); - pxl.setGreen(0); - pxl.setBlue(0); - pxl.setAlpha(0); - } - dest->setPixel(dx, dy, pxl); + for (dx = 0; dx < dim.Width; dx++) { + + // Calculate floating-point source rectangle bounds. + // Do some basic clipping, and for mirrored/flipped rects, + // make sure min/max are in the right order. + minsx = sox + (dx * sw / dim.Width); + minsx = rangelim(minsx, 0, sox + sw); + maxsx = minsx + sw / dim.Width; + maxsx = rangelim(maxsx, 0, sox + sw); + if (minsx > maxsx) + SWAP(double, minsx, maxsx); + minsy = soy + (dy * sh / dim.Height); + minsy = rangelim(minsy, 0, soy + sh); + maxsy = minsy + sh / dim.Height; + maxsy = rangelim(maxsy, 0, soy + sh); + if (minsy > maxsy) + SWAP(double, minsy, maxsy); + + // Total area, and integral of r, g, b values over that area, + // initialized to zero, to be summed up in next loops. + area = 0; + ra = 0; + ga = 0; + ba = 0; + aa = 0; + + // Loop over the integral pixel positions described by those bounds. + for (sy = floor(minsy); sy < maxsy; sy++) + for (sx = floor(minsx); sx < maxsx; sx++) { + + // Calculate width, height, then area of dest pixel + // that's covered by this source pixel. + pw = 1; + if (minsx > sx) + pw += sx - minsx; + if (maxsx < (sx + 1)) + pw += maxsx - sx - 1; + ph = 1; + if (minsy > sy) + ph += sy - minsy; + if (maxsy < (sy + 1)) + ph += maxsy - sy - 1; + pa = pw * ph; + + // Get source pixel and add it to totals, weighted + // by covered area and alpha. + pxl = src->getPixel((u32)sx, (u32)sy); + area += pa; + ra += pa * pxl.getRed(); + ga += pa * pxl.getGreen(); + ba += pa * pxl.getBlue(); + aa += pa * pxl.getAlpha(); + } + + // Set the destination image pixel to the average color. + if (area > 0) { + pxl.setRed(ra / area + 0.5); + pxl.setGreen(ga / area + 0.5); + pxl.setBlue(ba / area + 0.5); + pxl.setAlpha(aa / area + 0.5); + } else { + pxl.setRed(0); + pxl.setGreen(0); + pxl.setBlue(0); + pxl.setAlpha(0); } + dest->setPixel(dx, dy, pxl); + } } diff --git a/src/client/imagefilters.h b/src/client/imagefilters.h index 67f031890..5676faf85 100644 --- a/src/client/imagefilters.h +++ b/src/client/imagefilters.h @@ -40,5 +40,4 @@ void imageCleanTransparent(video::IImage *src, u32 threshold); * filter is designed to produce the most accurate results for both upscaling * and downscaling. */ -void imageScaleNNAA( - video::IImage *src, const core::rect &srcrect, video::IImage *dest); +void imageScaleNNAA(video::IImage *src, const core::rect &srcrect, video::IImage *dest); diff --git a/src/client/inputhandler.h b/src/client/inputhandler.h index ef5f6fb32..e006affb2 100644 --- a/src/client/inputhandler.h +++ b/src/client/inputhandler.h @@ -218,7 +218,10 @@ class InputHandler virtual ~InputHandler() = default; - virtual bool isRandom() const { return false; } + virtual bool isRandom() const + { + return false; + } virtual bool isKeyDown(GameKeyType k) = 0; virtual void setKeypress(const KeyPress &keyCode) = 0; @@ -374,7 +377,7 @@ class RealInputHandler : public InputHandler m_receiver->clearInput(); } -private: + private: MyEventReceiver *m_receiver = nullptr; v2s32 m_mousepos; }; @@ -384,11 +387,20 @@ class RandomInputHandler : public InputHandler public: RandomInputHandler() = default; - bool isRandom() const { return true; } + bool isRandom() const + { + return true; + } virtual bool isKeyDown(GameKeyType k) { return keydown[keycache.key[k]]; } - virtual void setKeypress(const KeyPress &keyCode) { keydown.set(keyCode); } - virtual void unsetKeypress(const KeyPress &keyCode) { keydown.unset(keyCode); } + virtual void setKeypress(const KeyPress &keyCode) + { + keydown.set(keyCode); + } + virtual void unsetKeypress(const KeyPress &keyCode) + { + keydown.unset(keyCode); + } virtual bool wasKeyDown(GameKeyType k) { return false; } virtual bool cancelPressed() { return false; } virtual v2s32 getMousePos() { return mousepos; } diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp index 5bff6fbba..c29e8b639 100644 --- a/src/client/joystick_controller.cpp +++ b/src/client/joystick_controller.cpp @@ -41,7 +41,7 @@ bool JoystickAxisCmb::isTriggered(const irr::SEvent::SJoystickEvent &ev) const } // spares many characters -#define JLO_B_PB(A, B, C) jlo.button_keys.emplace_back(A, B, C) +#define JLO_B_PB(A, B, C) jlo.button_keys.emplace_back(A, B, C) #define JLO_A_PB(A, B, C, D) jlo.axis_keys.emplace_back(A, B, C, D) JoystickLayout create_default_layout() @@ -51,41 +51,41 @@ JoystickLayout create_default_layout() jlo.axes_dead_border = 1024; const JoystickAxisLayout axes[JA_COUNT] = { - {0, 1}, // JA_SIDEWARD_MOVE - {1, 1}, // JA_FORWARD_MOVE - {3, 1}, // JA_FRUSTUM_HORIZONTAL - {4, 1}, // JA_FRUSTUM_VERTICAL + {0, 1}, // JA_SIDEWARD_MOVE + {1, 1}, // JA_FORWARD_MOVE + {3, 1}, // JA_FRUSTUM_HORIZONTAL + {4, 1}, // JA_FRUSTUM_VERTICAL }; memcpy(jlo.axes, axes, sizeof(jlo.axes)); - u32 sb = 1 << 7; // START button mask - u32 fb = 1 << 3; // FOUR button mask + u32 sb = 1 << 7; // START button mask + u32 fb = 1 << 3; // FOUR button mask u32 bm = sb | fb; // Mask for Both Modifiers // The back button means "ESC". - JLO_B_PB(KeyType::ESC, 1 << 6, 1 << 6); + JLO_B_PB(KeyType::ESC, 1 << 6, 1 << 6); // The start button counts as modifier as well as use key. // JLO_B_PB(KeyType::USE, sb, sb)); // Accessible without start modifier button pressed // regardless whether four is pressed or not - JLO_B_PB(KeyType::SNEAK, sb | 1 << 2, 1 << 2); + JLO_B_PB(KeyType::SNEAK, sb | 1 << 2, 1 << 2); // Accessible without four modifier button pressed // regardless whether start is pressed or not - JLO_B_PB(KeyType::MOUSE_L, fb | 1 << 4, 1 << 4); - JLO_B_PB(KeyType::MOUSE_R, fb | 1 << 5, 1 << 5); + JLO_B_PB(KeyType::MOUSE_L, fb | 1 << 4, 1 << 4); + JLO_B_PB(KeyType::MOUSE_R, fb | 1 << 5, 1 << 5); // Accessible without any modifier pressed - JLO_B_PB(KeyType::JUMP, bm | 1 << 0, 1 << 0); - JLO_B_PB(KeyType::SPECIAL1, bm | 1 << 1, 1 << 1); + JLO_B_PB(KeyType::JUMP, bm | 1 << 0, 1 << 0); + JLO_B_PB(KeyType::SPECIAL1, bm | 1 << 1, 1 << 1); // Accessible with start button not pressed, but four pressed // TODO find usage for button 0 - JLO_B_PB(KeyType::DROP, bm | 1 << 1, fb | 1 << 1); - JLO_B_PB(KeyType::SCROLL_UP, bm | 1 << 4, fb | 1 << 4); - JLO_B_PB(KeyType::SCROLL_DOWN, bm | 1 << 5, fb | 1 << 5); + JLO_B_PB(KeyType::DROP, bm | 1 << 1, fb | 1 << 1); + JLO_B_PB(KeyType::SCROLL_UP, bm | 1 << 4, fb | 1 << 4); + JLO_B_PB(KeyType::SCROLL_DOWN,bm | 1 << 5, fb | 1 << 5); // Accessible with start button and four pressed // TODO find usage for buttons 0, 1 and 4, 5 @@ -93,13 +93,13 @@ JoystickLayout create_default_layout() // Now about the buttons simulated by the axes // Movement buttons, important for vessels - JLO_A_PB(KeyType::FORWARD, 1, 1, 1024); + JLO_A_PB(KeyType::FORWARD, 1, 1, 1024); JLO_A_PB(KeyType::BACKWARD, 1, -1, 1024); - JLO_A_PB(KeyType::LEFT, 0, 1, 1024); - JLO_A_PB(KeyType::RIGHT, 0, -1, 1024); + JLO_A_PB(KeyType::LEFT, 0, 1, 1024); + JLO_A_PB(KeyType::RIGHT, 0, -1, 1024); // Scroll buttons - JLO_A_PB(KeyType::SCROLL_UP, 2, -1, 1024); + JLO_A_PB(KeyType::SCROLL_UP, 2, -1, 1024); JLO_A_PB(KeyType::SCROLL_DOWN, 5, -1, 1024); return jlo; @@ -112,44 +112,44 @@ JoystickLayout create_xbox_layout() jlo.axes_dead_border = 7000; const JoystickAxisLayout axes[JA_COUNT] = { - {0, 1}, // JA_SIDEWARD_MOVE - {1, 1}, // JA_FORWARD_MOVE - {2, 1}, // JA_FRUSTUM_HORIZONTAL - {3, 1}, // JA_FRUSTUM_VERTICAL + {0, 1}, // JA_SIDEWARD_MOVE + {1, 1}, // JA_FORWARD_MOVE + {2, 1}, // JA_FRUSTUM_HORIZONTAL + {3, 1}, // JA_FRUSTUM_VERTICAL }; memcpy(jlo.axes, axes, sizeof(jlo.axes)); // The back button means "ESC". - JLO_B_PB(KeyType::ESC, 1 << 8, 1 << 8); // back - JLO_B_PB(KeyType::ESC, 1 << 9, 1 << 9); // start + JLO_B_PB(KeyType::ESC, 1 << 8, 1 << 8); // back + JLO_B_PB(KeyType::ESC, 1 << 9, 1 << 9); // start // 4 Buttons - JLO_B_PB(KeyType::JUMP, 1 << 0, 1 << 0); // A/green - JLO_B_PB(KeyType::ESC, 1 << 1, 1 << 1); // B/red - JLO_B_PB(KeyType::SPECIAL1, 1 << 2, 1 << 2); // X/blue - JLO_B_PB(KeyType::INVENTORY, 1 << 3, 1 << 3); // Y/yellow + JLO_B_PB(KeyType::JUMP, 1 << 0, 1 << 0); // A/green + JLO_B_PB(KeyType::ESC, 1 << 1, 1 << 1); // B/red + JLO_B_PB(KeyType::SPECIAL1, 1 << 2, 1 << 2); // X/blue + JLO_B_PB(KeyType::INVENTORY, 1 << 3, 1 << 3); // Y/yellow // Analog Sticks - JLO_B_PB(KeyType::SPECIAL1, 1 << 11, 1 << 11); // left - JLO_B_PB(KeyType::SNEAK, 1 << 12, 1 << 12); // right + JLO_B_PB(KeyType::SPECIAL1, 1 << 11, 1 << 11); // left + JLO_B_PB(KeyType::SNEAK, 1 << 12, 1 << 12); // right // Triggers - JLO_B_PB(KeyType::MOUSE_L, 1 << 6, 1 << 6); // lt - JLO_B_PB(KeyType::MOUSE_R, 1 << 7, 1 << 7); // rt - JLO_B_PB(KeyType::SCROLL_UP, 1 << 4, 1 << 4); // lb - JLO_B_PB(KeyType::SCROLL_DOWN, 1 << 5, 1 << 5); // rb + JLO_B_PB(KeyType::MOUSE_L, 1 << 6, 1 << 6); // lt + JLO_B_PB(KeyType::MOUSE_R, 1 << 7, 1 << 7); // rt + JLO_B_PB(KeyType::SCROLL_UP, 1 << 4, 1 << 4); // lb + JLO_B_PB(KeyType::SCROLL_DOWN, 1 << 5, 1 << 5); // rb // D-PAD - JLO_B_PB(KeyType::ZOOM, 1 << 15, 1 << 15); // up - JLO_B_PB(KeyType::DROP, 1 << 13, 1 << 13); // left - JLO_B_PB(KeyType::SCREENSHOT, 1 << 14, 1 << 14); // right - JLO_B_PB(KeyType::FREEMOVE, 1 << 16, 1 << 16); // down + JLO_B_PB(KeyType::ZOOM, 1 << 15, 1 << 15); // up + JLO_B_PB(KeyType::DROP, 1 << 13, 1 << 13); // left + JLO_B_PB(KeyType::SCREENSHOT, 1 << 14, 1 << 14); // right + JLO_B_PB(KeyType::FREEMOVE, 1 << 16, 1 << 16); // down // Movement buttons, important for vessels - JLO_A_PB(KeyType::FORWARD, 1, 1, 1024); + JLO_A_PB(KeyType::FORWARD, 1, 1, 1024); JLO_A_PB(KeyType::BACKWARD, 1, -1, 1024); - JLO_A_PB(KeyType::LEFT, 0, 1, 1024); - JLO_A_PB(KeyType::RIGHT, 0, -1, 1024); + JLO_A_PB(KeyType::LEFT, 0, 1, 1024); + JLO_A_PB(KeyType::RIGHT, 0, -1, 1024); return jlo; } @@ -163,10 +163,9 @@ JoystickController::JoystickController() : clear(); } -void JoystickController::onJoystickConnect( - const std::vector &joystick_infos) +void JoystickController::onJoystickConnect(const std::vector &joystick_infos) { - s32 id = g_settings->getS32("joystick_id"); + s32 id = g_settings->getS32("joystick_id"); std::string layout = g_settings->get("joystick_type"); if (id < 0 || (u16)id >= joystick_infos.size()) { @@ -221,9 +220,7 @@ bool JoystickController::handleEvent(const irr::SEvent::SJoystickEvent &ev) for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) { if (keys_pressed[i]) { if (!m_past_pressed_keys[i] && - m_past_pressed_time[i] < - m_internal_time - - doubling_dtime) { + m_past_pressed_time[i] < m_internal_time - doubling_dtime) { m_past_pressed_keys[i] = true; m_past_pressed_time[i] = m_internal_time; } @@ -239,6 +236,7 @@ bool JoystickController::handleEvent(const irr::SEvent::SJoystickEvent &ev) m_axes_vals[i] = ax_la.invert * ev.Axis[ax_la.axis_id]; } + return true; } diff --git a/src/client/joystick_controller.h b/src/client/joystick_controller.h index ea0833561..7baacd81b 100644 --- a/src/client/joystick_controller.h +++ b/src/client/joystick_controller.h @@ -24,8 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -enum JoystickAxis -{ +enum JoystickAxis { JA_SIDEWARD_MOVE, JA_FORWARD_MOVE, @@ -36,28 +35,27 @@ enum JoystickAxis JA_COUNT, }; -struct JoystickAxisLayout -{ +struct JoystickAxisLayout { u16 axis_id; // -1 if to invert, 1 if to keep it. int invert; }; -struct JoystickCombination -{ - virtual bool isTriggered(const irr::SEvent::SJoystickEvent &ev) const = 0; +struct JoystickCombination { + + virtual bool isTriggered(const irr::SEvent::SJoystickEvent &ev) const=0; GameKeyType key; }; -struct JoystickButtonCmb : public JoystickCombination -{ +struct JoystickButtonCmb : public JoystickCombination { JoystickButtonCmb() = default; JoystickButtonCmb(GameKeyType key, u32 filter_mask, u32 compare_mask) : - filter_mask(filter_mask), compare_mask(compare_mask) + filter_mask(filter_mask), + compare_mask(compare_mask) { this->key = key; } @@ -70,14 +68,14 @@ struct JoystickButtonCmb : public JoystickCombination u32 compare_mask; }; -struct JoystickAxisCmb : public JoystickCombination -{ +struct JoystickAxisCmb : public JoystickCombination { JoystickAxisCmb() = default; JoystickAxisCmb(GameKeyType key, u16 axis_to_compare, int direction, s16 thresh) : - axis_to_compare(axis_to_compare), direction(direction), - thresh(thresh) + axis_to_compare(axis_to_compare), + direction(direction), + thresh(thresh) { this->key = key; } @@ -94,16 +92,14 @@ struct JoystickAxisCmb : public JoystickCombination s16 thresh; }; -struct JoystickLayout -{ +struct JoystickLayout { std::vector button_keys; std::vector axis_keys; JoystickAxisLayout axes[JA_COUNT]; s16 axes_dead_border; }; -class JoystickController -{ +class JoystickController { public: JoystickController(); @@ -119,8 +115,14 @@ class JoystickController m_past_pressed_keys[b] = false; return r; } - bool getWasKeyDown(GameKeyType b) { return m_past_pressed_keys[b]; } - void clearWasKeyDown(GameKeyType b) { m_past_pressed_keys[b] = false; } + bool getWasKeyDown(GameKeyType b) + { + return m_past_pressed_keys[b]; + } + void clearWasKeyDown(GameKeyType b) + { + m_past_pressed_keys[b] = false; + } bool wasKeyReleased(GameKeyType b) { @@ -128,12 +130,24 @@ class JoystickController m_past_released_keys[b] = false; return r; } - bool getWasKeyReleased(GameKeyType b) { return m_past_pressed_keys[b]; } - void clearWasKeyReleased(GameKeyType b) { m_past_pressed_keys[b] = false; } + bool getWasKeyReleased(GameKeyType b) + { + return m_past_pressed_keys[b]; + } + void clearWasKeyReleased(GameKeyType b) + { + m_past_pressed_keys[b] = false; + } - bool isKeyDown(GameKeyType b) { return m_pressed_keys[b]; } + bool isKeyDown(GameKeyType b) + { + return m_pressed_keys[b]; + } - s16 getAxis(JoystickAxis axis) { return m_axes_vals[axis]; } + s16 getAxis(JoystickAxis axis) + { + return m_axes_vals[axis]; + } s16 getAxisWithoutDead(JoystickAxis axis); diff --git a/src/client/keycode.cpp b/src/client/keycode.cpp index bbd269e81..6a0e9f569 100644 --- a/src/client/keycode.cpp +++ b/src/client/keycode.cpp @@ -29,182 +29,224 @@ with this program; if not, write to the Free Software Foundation, Inc., class UnknownKeycode : public BaseException { public: - UnknownKeycode(const char *s) : BaseException(s){}; + UnknownKeycode(const char *s) : + BaseException(s) {}; }; -struct table_key -{ +struct table_key { const char *Name; irr::EKEY_CODE Key; - wchar_t Char; // L'\0' means no character assigned + wchar_t Char; // L'\0' means no character assigned const char *LangName; // NULL means it doesn't have a human description }; -#define DEFINEKEY1(x, lang) /* Irrlicht key without character */ \ - {#x, irr::x, L'\0', lang}, -#define DEFINEKEY2(x, ch, lang) /* Irrlicht key with character */ {#x, irr::x, ch, lang}, -#define DEFINEKEY3(ch) /* single Irrlicht key (e.g. KEY_KEY_X) */ \ - {"KEY_KEY_" TOSTRING(ch), irr::KEY_KEY_##ch, (wchar_t)*TOSTRING(ch), \ - TOSTRING(ch)}, -#define DEFINEKEY4(ch) /* single Irrlicht function key (e.g. KEY_F3) */ \ - {"KEY_F" TOSTRING(ch), irr::KEY_F##ch, L'\0', "F" TOSTRING(ch)}, -#define DEFINEKEY5(ch) /* key without Irrlicht keycode */ \ - {ch, irr::KEY_KEY_CODES_COUNT, (wchar_t)*ch, ch}, +#define DEFINEKEY1(x, lang) /* Irrlicht key without character */ \ + { #x, irr::x, L'\0', lang }, +#define DEFINEKEY2(x, ch, lang) /* Irrlicht key with character */ \ + { #x, irr::x, ch, lang }, +#define DEFINEKEY3(ch) /* single Irrlicht key (e.g. KEY_KEY_X) */ \ + { "KEY_KEY_" TOSTRING(ch), irr::KEY_KEY_ ## ch, (wchar_t) *TOSTRING(ch), TOSTRING(ch) }, +#define DEFINEKEY4(ch) /* single Irrlicht function key (e.g. KEY_F3) */ \ + { "KEY_F" TOSTRING(ch), irr::KEY_F ## ch, L'\0', "F" TOSTRING(ch) }, +#define DEFINEKEY5(ch) /* key without Irrlicht keycode */ \ + { ch, irr::KEY_KEY_CODES_COUNT, (wchar_t) *ch, ch }, #define N_(text) text static const struct table_key table[] = { - // Keys that can be reliably mapped between Char and Key - DEFINEKEY3(0) DEFINEKEY3(1) DEFINEKEY3(2) DEFINEKEY3(3) DEFINEKEY3(4) DEFINEKEY3(5) DEFINEKEY3( - 6) DEFINEKEY3(7) DEFINEKEY3(8) DEFINEKEY3(9) DEFINEKEY3(A) DEFINEKEY3(B) DEFINEKEY3(C) - DEFINEKEY3(D) DEFINEKEY3(E) DEFINEKEY3(F) DEFINEKEY3(G) DEFINEKEY3(H) DEFINEKEY3( - I) DEFINEKEY3(J) DEFINEKEY3(K) DEFINEKEY3(L) DEFINEKEY3(M) - DEFINEKEY3(N) DEFINEKEY3(O) DEFINEKEY3(P) DEFINEKEY3(Q) DEFINEKEY3( - R) DEFINEKEY3(S) DEFINEKEY3(T) DEFINEKEY3(U) - DEFINEKEY3(V) DEFINEKEY3(W) DEFINEKEY3(X) DEFINEKEY3( - Y) DEFINEKEY3(Z) DEFINEKEY2(KEY_PLUS, - L'+', - "+") DEFINEKEY2(KEY_COMMA, - L',', - ",") DEFINEKEY2(KEY_MINUS, - L'-', - "-") DEFINEKEY2(KEY_PERIOD, - L'.', ".") - - // Keys without a Char - DEFINEKEY1(KEY_LBUTTON, N_("Left Button")) DEFINEKEY1( - KEY_RBUTTON, N_("Right Button")) DEFINEKEY1(KEY_CANCEL, - N_("Cancel")) DEFINEKEY1(KEY_MBUTTON, - N_("Middle Button")) DEFINEKEY1(KEY_XBUTTON1, - N_("X Button 1")) DEFINEKEY1(KEY_XBUTTON2, - N_("X Button 2")) DEFINEKEY1(KEY_BACK, - N_("Backspace")) DEFINEKEY1(KEY_TAB, - N_("Tab")) DEFINEKEY1(KEY_CLEAR, N_("Clear")) - DEFINEKEY1(KEY_RETURN, N_("Return")) DEFINEKEY1( - KEY_SHIFT, N_("Shift")) - DEFINEKEY1(KEY_CONTROL, N_("Control")) - //~ Key name, common on Windows keyboards - DEFINEKEY1(KEY_MENU, N_("Menu")) DEFINEKEY1( - KEY_PAUSE, N_("Pause")) DEFINEKEY1(KEY_CAPITAL, - N_("Caps Lock")) DEFINEKEY1(KEY_SPACE, - N_("Space")) DEFINEKEY1(KEY_PRIOR, N_("Page up")) - DEFINEKEY1(KEY_NEXT, N_("Page down")) DEFINEKEY1( - KEY_END, N_("End")) DEFINEKEY1(KEY_HOME, - N_("Home")) DEFINEKEY1(KEY_LEFT, - N_("Left")) DEFINEKEY1(KEY_UP, - N_("Up")) DEFINEKEY1(KEY_RIGHT, - N_("Right")) - DEFINEKEY1(KEY_DOWN, N_("Down")) - //~ Key name - DEFINEKEY1(KEY_SELECT, N_("Select")) - //~ "Print screen" key - DEFINEKEY1(KEY_PRINT, N_("Print")) DEFINEKEY1( - KEY_EXECUT, N_("Execute")) DEFINEKEY1(KEY_SNAPSHOT, - N_("Snapshot")) DEFINEKEY1(KEY_INSERT, - N_("Insert")) DEFINEKEY1(KEY_DELETE, - N_("Delete")) DEFINEKEY1(KEY_HELP, - N_("Help")) DEFINEKEY1(KEY_LWIN, - N_("Left Windows")) DEFINEKEY1(KEY_RWIN, - N_("Right Windows")) DEFINEKEY1(KEY_NUMPAD0, - N_("Numpad 0")) // These are not assigned to a char - DEFINEKEY1(KEY_NUMPAD1, N_("Numpad 1")) // to prevent interference with - // KEY_KEY_[0-9]. - DEFINEKEY1(KEY_NUMPAD2, N_("Numpad 2")) DEFINEKEY1( - KEY_NUMPAD3, N_("Numpad 3")) DEFINEKEY1(KEY_NUMPAD4, - N_("Numpad 4")) DEFINEKEY1(KEY_NUMPAD5, - N_("Numpad 5")) DEFINEKEY1(KEY_NUMPAD6, - N_("Numpad 6")) DEFINEKEY1(KEY_NUMPAD7, - N_("Numpad 7")) DEFINEKEY1(KEY_NUMPAD8, - N_("Numpad 8")) DEFINEKEY1(KEY_NUMPAD9, - N_("Numpad 9")) DEFINEKEY1(KEY_MULTIPLY, - N_("Numpad *")) DEFINEKEY1(KEY_ADD, - N_("Numpad +")) DEFINEKEY1(KEY_SEPARATOR, - N_("Numpad .")) DEFINEKEY1(KEY_SUBTRACT, - N_("Numpad -")) DEFINEKEY1(KEY_DECIMAL, - NULL) DEFINEKEY1(KEY_DIVIDE, - N_("Numpad /")) DEFINEKEY4(1) DEFINEKEY4(2) DEFINEKEY4(3) DEFINEKEY4(4) - DEFINEKEY4(5) DEFINEKEY4(6) DEFINEKEY4(7) DEFINEKEY4(8) DEFINEKEY4(9) DEFINEKEY4( - 10) DEFINEKEY4(11) DEFINEKEY4(12) DEFINEKEY4(13) DEFINEKEY4(14) - DEFINEKEY4(15) DEFINEKEY4(16) DEFINEKEY4(17) DEFINEKEY4( - 18) DEFINEKEY4(19) DEFINEKEY4(20) DEFINEKEY4(21) - DEFINEKEY4(22) DEFINEKEY4(23) DEFINEKEY4( - 24) DEFINEKEY1(KEY_NUMLOCK, - N_("Num " - "Loc" - "k")) DEFINEKEY1(KEY_SCROLL, - N_("Scrol" - "l " - "Loc" - "k")) DEFINEKEY1(KEY_LSHIFT, - N_("Left " - "Shif" - "t")) DEFINEKEY1(KEY_RSHIFT, - N_("Right" - " Shif" - "t")) DEFINEKEY1(KEY_LCONTROL, - N_("Left " - "Contr" - "ol")) DEFINEKEY1(KEY_RCONTROL, - N_("Right" - " Cont" - "rol")) DEFINEKEY1(KEY_LMENU, - N_("Left " - "Men" - "u")) DEFINEKEY1(KEY_RMENU, - N_("Right" - " Men" - "u")) - - // Rare/weird keys - DEFINEKEY1(KEY_KANA, "Kana") DEFINEKEY1(KEY_HANGUEL, "Hangul") DEFINEKEY1( - KEY_HANGUL, "Hangul") DEFINEKEY1(KEY_JUNJA, - "Junja") DEFINEKEY1(KEY_FINAL, - "Final") DEFINEKEY1(KEY_KANJI, - "Kanji") DEFINEKEY1(KEY_HANJA, - "Hanja") DEFINEKEY1(KEY_ESCAPE, - N_("IME Escape")) DEFINEKEY1(KEY_CONVERT, - N_("IME Convert")) DEFINEKEY1(KEY_NONCONVERT, - N_("IME Nonconvert")) DEFINEKEY1(KEY_ACCEPT, - N_("IME Accept")) DEFINEKEY1(KEY_MODECHANGE, - N_("IME Mode Change")) DEFINEKEY1(KEY_APPS, - N_("Apps")) DEFINEKEY1(KEY_SLEEP, N_("Sleep")) -#if !(IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 7 && \ - IRRLICHT_VERSION_REVISION < 3) - DEFINEKEY1(KEY_OEM_1, - "OEM 1") // KEY_OEM_[0-9] and KEY_OEM_102 - // are assigned to multiple - DEFINEKEY1(KEY_OEM_2, "OEM 2") // different chars (on different platforms - // too) and thus w/o char - DEFINEKEY1(KEY_OEM_3, "OEM 3") DEFINEKEY1(KEY_OEM_4, "OEM 4") DEFINEKEY1( - KEY_OEM_5, "OEM 5") DEFINEKEY1(KEY_OEM_6, - "OEM 6") DEFINEKEY1(KEY_OEM_7, - "OEM 7") DEFINEKEY1(KEY_OEM_8, - "OEM 8") DEFINEKEY1(KEY_OEM_AX, - "OEM AX") DEFINEKEY1(KEY_OEM_102, "OEM 102") + // Keys that can be reliably mapped between Char and Key + DEFINEKEY3(0) + DEFINEKEY3(1) + DEFINEKEY3(2) + DEFINEKEY3(3) + DEFINEKEY3(4) + DEFINEKEY3(5) + DEFINEKEY3(6) + DEFINEKEY3(7) + DEFINEKEY3(8) + DEFINEKEY3(9) + DEFINEKEY3(A) + DEFINEKEY3(B) + DEFINEKEY3(C) + DEFINEKEY3(D) + DEFINEKEY3(E) + DEFINEKEY3(F) + DEFINEKEY3(G) + DEFINEKEY3(H) + DEFINEKEY3(I) + DEFINEKEY3(J) + DEFINEKEY3(K) + DEFINEKEY3(L) + DEFINEKEY3(M) + DEFINEKEY3(N) + DEFINEKEY3(O) + DEFINEKEY3(P) + DEFINEKEY3(Q) + DEFINEKEY3(R) + DEFINEKEY3(S) + DEFINEKEY3(T) + DEFINEKEY3(U) + DEFINEKEY3(V) + DEFINEKEY3(W) + DEFINEKEY3(X) + DEFINEKEY3(Y) + DEFINEKEY3(Z) + DEFINEKEY2(KEY_PLUS, L'+', "+") + DEFINEKEY2(KEY_COMMA, L',', ",") + DEFINEKEY2(KEY_MINUS, L'-', "-") + DEFINEKEY2(KEY_PERIOD, L'.', ".") + + // Keys without a Char + DEFINEKEY1(KEY_LBUTTON, N_("Left Button")) + DEFINEKEY1(KEY_RBUTTON, N_("Right Button")) + DEFINEKEY1(KEY_CANCEL, N_("Cancel")) + DEFINEKEY1(KEY_MBUTTON, N_("Middle Button")) + DEFINEKEY1(KEY_XBUTTON1, N_("X Button 1")) + DEFINEKEY1(KEY_XBUTTON2, N_("X Button 2")) + DEFINEKEY1(KEY_BACK, N_("Backspace")) + DEFINEKEY1(KEY_TAB, N_("Tab")) + DEFINEKEY1(KEY_CLEAR, N_("Clear")) + DEFINEKEY1(KEY_RETURN, N_("Return")) + DEFINEKEY1(KEY_SHIFT, N_("Shift")) + DEFINEKEY1(KEY_CONTROL, N_("Control")) + //~ Key name, common on Windows keyboards + DEFINEKEY1(KEY_MENU, N_("Menu")) + DEFINEKEY1(KEY_PAUSE, N_("Pause")) + DEFINEKEY1(KEY_CAPITAL, N_("Caps Lock")) + DEFINEKEY1(KEY_SPACE, N_("Space")) + DEFINEKEY1(KEY_PRIOR, N_("Page up")) + DEFINEKEY1(KEY_NEXT, N_("Page down")) + DEFINEKEY1(KEY_END, N_("End")) + DEFINEKEY1(KEY_HOME, N_("Home")) + DEFINEKEY1(KEY_LEFT, N_("Left")) + DEFINEKEY1(KEY_UP, N_("Up")) + DEFINEKEY1(KEY_RIGHT, N_("Right")) + DEFINEKEY1(KEY_DOWN, N_("Down")) + //~ Key name + DEFINEKEY1(KEY_SELECT, N_("Select")) + //~ "Print screen" key + DEFINEKEY1(KEY_PRINT, N_("Print")) + DEFINEKEY1(KEY_EXECUT, N_("Execute")) + DEFINEKEY1(KEY_SNAPSHOT, N_("Snapshot")) + DEFINEKEY1(KEY_INSERT, N_("Insert")) + DEFINEKEY1(KEY_DELETE, N_("Delete")) + DEFINEKEY1(KEY_HELP, N_("Help")) + DEFINEKEY1(KEY_LWIN, N_("Left Windows")) + DEFINEKEY1(KEY_RWIN, N_("Right Windows")) + DEFINEKEY1(KEY_NUMPAD0, N_("Numpad 0")) // These are not assigned to a char + DEFINEKEY1(KEY_NUMPAD1, N_("Numpad 1")) // to prevent interference with KEY_KEY_[0-9]. + DEFINEKEY1(KEY_NUMPAD2, N_("Numpad 2")) + DEFINEKEY1(KEY_NUMPAD3, N_("Numpad 3")) + DEFINEKEY1(KEY_NUMPAD4, N_("Numpad 4")) + DEFINEKEY1(KEY_NUMPAD5, N_("Numpad 5")) + DEFINEKEY1(KEY_NUMPAD6, N_("Numpad 6")) + DEFINEKEY1(KEY_NUMPAD7, N_("Numpad 7")) + DEFINEKEY1(KEY_NUMPAD8, N_("Numpad 8")) + DEFINEKEY1(KEY_NUMPAD9, N_("Numpad 9")) + DEFINEKEY1(KEY_MULTIPLY, N_("Numpad *")) + DEFINEKEY1(KEY_ADD, N_("Numpad +")) + DEFINEKEY1(KEY_SEPARATOR, N_("Numpad .")) + DEFINEKEY1(KEY_SUBTRACT, N_("Numpad -")) + DEFINEKEY1(KEY_DECIMAL, NULL) + DEFINEKEY1(KEY_DIVIDE, N_("Numpad /")) + DEFINEKEY4(1) + DEFINEKEY4(2) + DEFINEKEY4(3) + DEFINEKEY4(4) + DEFINEKEY4(5) + DEFINEKEY4(6) + DEFINEKEY4(7) + DEFINEKEY4(8) + DEFINEKEY4(9) + DEFINEKEY4(10) + DEFINEKEY4(11) + DEFINEKEY4(12) + DEFINEKEY4(13) + DEFINEKEY4(14) + DEFINEKEY4(15) + DEFINEKEY4(16) + DEFINEKEY4(17) + DEFINEKEY4(18) + DEFINEKEY4(19) + DEFINEKEY4(20) + DEFINEKEY4(21) + DEFINEKEY4(22) + DEFINEKEY4(23) + DEFINEKEY4(24) + DEFINEKEY1(KEY_NUMLOCK, N_("Num Lock")) + DEFINEKEY1(KEY_SCROLL, N_("Scroll Lock")) + DEFINEKEY1(KEY_LSHIFT, N_("Left Shift")) + DEFINEKEY1(KEY_RSHIFT, N_("Right Shift")) + DEFINEKEY1(KEY_LCONTROL, N_("Left Control")) + DEFINEKEY1(KEY_RCONTROL, N_("Right Control")) + DEFINEKEY1(KEY_LMENU, N_("Left Menu")) + DEFINEKEY1(KEY_RMENU, N_("Right Menu")) + + // Rare/weird keys + DEFINEKEY1(KEY_KANA, "Kana") + DEFINEKEY1(KEY_HANGUEL, "Hangul") + DEFINEKEY1(KEY_HANGUL, "Hangul") + DEFINEKEY1(KEY_JUNJA, "Junja") + DEFINEKEY1(KEY_FINAL, "Final") + DEFINEKEY1(KEY_KANJI, "Kanji") + DEFINEKEY1(KEY_HANJA, "Hanja") + DEFINEKEY1(KEY_ESCAPE, N_("IME Escape")) + DEFINEKEY1(KEY_CONVERT, N_("IME Convert")) + DEFINEKEY1(KEY_NONCONVERT, N_("IME Nonconvert")) + DEFINEKEY1(KEY_ACCEPT, N_("IME Accept")) + DEFINEKEY1(KEY_MODECHANGE, N_("IME Mode Change")) + DEFINEKEY1(KEY_APPS, N_("Apps")) + DEFINEKEY1(KEY_SLEEP, N_("Sleep")) +#if !(IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 7 && IRRLICHT_VERSION_REVISION < 3) + DEFINEKEY1(KEY_OEM_1, "OEM 1") // KEY_OEM_[0-9] and KEY_OEM_102 are assigned to multiple + DEFINEKEY1(KEY_OEM_2, "OEM 2") // different chars (on different platforms too) and thus w/o char + DEFINEKEY1(KEY_OEM_3, "OEM 3") + DEFINEKEY1(KEY_OEM_4, "OEM 4") + DEFINEKEY1(KEY_OEM_5, "OEM 5") + DEFINEKEY1(KEY_OEM_6, "OEM 6") + DEFINEKEY1(KEY_OEM_7, "OEM 7") + DEFINEKEY1(KEY_OEM_8, "OEM 8") + DEFINEKEY1(KEY_OEM_AX, "OEM AX") + DEFINEKEY1(KEY_OEM_102, "OEM 102") #endif - DEFINEKEY1(KEY_ATTN, "Attn") DEFINEKEY1( - KEY_CRSEL, "CrSel") DEFINEKEY1(KEY_EXSEL, - "ExSel") DEFINEKEY1(KEY_EREOF, - N_("Erase EOF")) DEFINEKEY1(KEY_PLAY, - N_("Play")) DEFINEKEY1(KEY_ZOOM, - N_("Zoom")) DEFINEKEY1(KEY_PA1, "PA1") - DEFINEKEY1(KEY_OEM_CLEAR, N_("OEM Clear")) - - // Keys without Irrlicht keycode - DEFINEKEY5("!") DEFINEKEY5("\"") DEFINEKEY5("#") DEFINEKEY5( - "$") DEFINEKEY5("%") DEFINEKEY5("&") DEFINEKEY5("'") - DEFINEKEY5("(") DEFINEKEY5(")") DEFINEKEY5( - "*") DEFINEKEY5("/") DEFINEKEY5(":") - DEFINEKEY5(";") DEFINEKEY5("<") DEFINEKEY5( - "=") DEFINEKEY5(">") - DEFINEKEY5("?") DEFINEKEY5("@") DEFINEKEY5( - "[") DEFINEKEY5("\\") - DEFINEKEY5("]") DEFINEKEY5( - "^") - DEFINEKEY5("_")}; + DEFINEKEY1(KEY_ATTN, "Attn") + DEFINEKEY1(KEY_CRSEL, "CrSel") + DEFINEKEY1(KEY_EXSEL, "ExSel") + DEFINEKEY1(KEY_EREOF, N_("Erase EOF")) + DEFINEKEY1(KEY_PLAY, N_("Play")) + DEFINEKEY1(KEY_ZOOM, N_("Zoom")) + DEFINEKEY1(KEY_PA1, "PA1") + DEFINEKEY1(KEY_OEM_CLEAR, N_("OEM Clear")) + + // Keys without Irrlicht keycode + DEFINEKEY5("!") + DEFINEKEY5("\"") + DEFINEKEY5("#") + DEFINEKEY5("$") + DEFINEKEY5("%") + DEFINEKEY5("&") + DEFINEKEY5("'") + DEFINEKEY5("(") + DEFINEKEY5(")") + DEFINEKEY5("*") + DEFINEKEY5("/") + DEFINEKEY5(":") + DEFINEKEY5(";") + DEFINEKEY5("<") + DEFINEKEY5("=") + DEFINEKEY5(">") + DEFINEKEY5("?") + DEFINEKEY5("@") + DEFINEKEY5("[") + DEFINEKEY5("\\") + DEFINEKEY5("]") + DEFINEKEY5("^") + DEFINEKEY5("_") +}; #undef N_ + struct table_key lookup_keyname(const char *name) { for (const auto &table_key : table) { @@ -223,7 +265,7 @@ struct table_key lookup_keykey(irr::EKEY_CODE key) } std::ostringstream os; - os << ""; + os << ""; throw UnknownKeycode(os.str().c_str()); } @@ -235,7 +277,7 @@ struct table_key lookup_keychar(wchar_t Char) } std::ostringstream os; - os << ""; + os << ""; throw UnknownKeycode(os.str().c_str()); } @@ -257,8 +299,7 @@ KeyPress::KeyPress(const char *name) m_name = k.Name; Key = k.Key; return; - } catch (UnknownKeycode &e) { - }; + } catch (UnknownKeycode &e) {}; } else { // Lookup by name m_name = name; @@ -267,8 +308,7 @@ KeyPress::KeyPress(const char *name) Key = k.Key; Char = k.Char; return; - } catch (UnknownKeycode &e) { - }; + } catch (UnknownKeycode &e) {}; } // It's not a known key, complain and try to do something @@ -276,8 +316,7 @@ KeyPress::KeyPress(const char *name) int chars_read = mbtowc(&Char, name, 1); FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character"); m_name = ""; - warningstream << "KeyPress: Unknown key '" << name - << "', falling back to first char."; + warningstream << "KeyPress: Unknown key '" << name << "', falling back to first char."; } KeyPress::KeyPress(const irr::SEvent::SKeyInput &in, bool prefer_character) diff --git a/src/client/keys.h b/src/client/keys.h index e288ecda0..43a032a7b 100644 --- a/src/client/keys.h +++ b/src/client/keys.h @@ -79,7 +79,7 @@ class KeyType SELECT_LEFT, SELECT_RIGHT, SELECT_CONFIRM, - + QUICKTUNE_NEXT, QUICKTUNE_PREV, QUICKTUNE_INC, diff --git a/src/client/localplayer.cpp b/src/client/localplayer.cpp index 324055796..00195cd02 100644 --- a/src/client/localplayer.cpp +++ b/src/client/localplayer.cpp @@ -34,8 +34,9 @@ with this program; if not, write to the Free Software Foundation, Inc., LocalPlayer */ -LocalPlayer::LocalPlayer(Client *client, const char *name) : - Player(name, client->idef()), m_client(client) +LocalPlayer::LocalPlayer(Client *client, const char *name): + Player(name, client->idef()), + m_client(client) { } @@ -56,11 +57,20 @@ static aabb3f getNodeBoundingBox(const std::vector &nodeboxes) return b_max; } -bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &sneak_max) +bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, + const v3f &sneak_max) { - static const v3s16 dir9_center[9] = {v3s16(0, 0, 0), v3s16(1, 0, 0), - v3s16(-1, 0, 0), v3s16(0, 0, 1), v3s16(0, 0, -1), v3s16(1, 0, 1), - v3s16(-1, 0, 1), v3s16(1, 0, -1), v3s16(-1, 0, -1)}; + static const v3s16 dir9_center[9] = { + v3s16( 0, 0, 0), + v3s16( 1, 0, 0), + v3s16(-1, 0, 0), + v3s16( 0, 0, 1), + v3s16( 0, 0, -1), + v3s16( 1, 0, 1), + v3s16(-1, 0, 1), + v3s16( 1, 0, -1), + v3s16(-1, 0, -1) + }; const NodeDefManager *nodemgr = m_client->ndef(); MapNode node; @@ -73,8 +83,7 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea position_y_mod = m_sneak_node_bb_top.MaxEdge.Y - position_y_mod; // Get position of current standing node - const v3s16 current_node = - floatToInt(position - v3f(0.0f, position_y_mod, 0.0f), BS); + const v3s16 current_node = floatToInt(position - v3f(0.0f, position_y_mod, 0.0f), BS); if (current_node != m_sneak_node) { new_sneak_node_exists = false; @@ -103,19 +112,18 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea fabs(diff.Y) > (0.5f + 0.1f) * BS + sneak_max.Z) continue; + // The node to be sneaked on has to be walkable node = map->getNode(p, &is_valid_position); - if (!is_valid_position || !nodemgr->get(node).walkable) + if (!is_valid_position || ! nodemgr->get(node).walkable) continue; // And the node(s) above have to be nonwalkable bool ok = true; if (!physics_override_sneak_glitch) { - u16 height = ceilf((m_collisionbox.MaxEdge.Y - - m_collisionbox.MinEdge.Y) / - BS); + u16 height = + ceilf((m_collisionbox.MaxEdge.Y - m_collisionbox.MinEdge.Y) / BS); for (u16 y = 1; y <= height; y++) { - node = map->getNode( - p + v3s16(0, y, 0), &is_valid_position); + node = map->getNode(p + v3s16(0, y, 0), &is_valid_position); if (!is_valid_position || nodemgr->get(node).walkable) { ok = false; break; @@ -124,7 +132,7 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea } else { // legacy behaviour: check just one node node = map->getNode(p + v3s16(0, 1, 0), &is_valid_position); - ok = is_valid_position && !nodemgr->get(node).walkable; + ok = is_valid_position && ! nodemgr->get(node).walkable; } if (!ok) continue; @@ -146,13 +154,14 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea if (physics_override_sneak_glitch) { // Detect sneak ladder: // Node two meters above sneak node must be solid - node = map->getNode(m_sneak_node + v3s16(0, 2, 0), &is_valid_position); + node = map->getNode(m_sneak_node + v3s16(0, 2, 0), + &is_valid_position); if (is_valid_position && nodemgr->get(node).walkable) { // Node three meters above: must be non-solid node = map->getNode(m_sneak_node + v3s16(0, 3, 0), - &is_valid_position); - m_sneak_ladder_detected = - is_valid_position && !nodemgr->get(node).walkable; + &is_valid_position); + m_sneak_ladder_detected = is_valid_position && + ! nodemgr->get(node).walkable; } } return true; @@ -163,7 +172,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, { if (m_cao && m_cao->m_waiting_for_reattach > 0) m_cao->m_waiting_for_reattach -= dtime; - + // Node at feet position, update each ClientEnvironment::step() if (!collision_info || collision_info->empty()) m_standing_node = floatToInt(m_position, BS); @@ -218,13 +227,13 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, */ // If in liquid, the threshold of coming out is at higher y - if (in_liquid) { + if (in_liquid) + { pp = floatToInt(position + v3f(0.0f, BS * 0.1f, 0.0f), BS); node = map->getNode(pp, &is_valid_position); if (is_valid_position) { in_liquid = nodemgr->get(node.getContent()).isLiquid(); - liquid_viscosity = - nodemgr->get(node.getContent()).liquid_viscosity; + liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity; } else { in_liquid = false; } @@ -235,13 +244,13 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, node = map->getNode(pp, &is_valid_position); if (is_valid_position) { in_liquid = nodemgr->get(node.getContent()).isLiquid(); - liquid_viscosity = - nodemgr->get(node.getContent()).liquid_viscosity; + liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity; } else { in_liquid = false; } } + /* Check if player is in liquid (the stable value) */ @@ -267,16 +276,14 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, is_climbing = false; } else { is_climbing = (nodemgr->get(node.getContent()).climbable || - nodemgr->get(node2.getContent()) - .climbable) && - !free_move; + nodemgr->get(node2.getContent()).climbable) && !free_move; } /* Collision uncertainty radius Make it a bit larger than the maximum distance of movement */ - // f32 d = pos_max_d * 1.1; + //f32 d = pos_max_d * 1.1; // A fairly large value in here makes moving smoother f32 d = 0.15f * BS; @@ -285,21 +292,19 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, // Player object property step height is multiplied by BS in // /src/script/common/c_content.cpp and /src/content_sao.cpp - float player_stepheight = - (m_cao == nullptr) ? 0.0f - : (touching_ground ? m_cao->getStepHeight() - : (0.2f * BS)); + float player_stepheight = (m_cao == nullptr) ? 0.0f : + (touching_ground ? m_cao->getStepHeight() : (0.2f * BS)); v3f accel_f; const v3f initial_position = position; const v3f initial_speed = m_speed; - collisionMoveResult result = collisionMoveSimple(env, m_client, pos_max_d, - m_collisionbox, player_stepheight, dtime, &position, &m_speed, - accel_f, NULL, true, true); + collisionMoveResult result = collisionMoveSimple(env, m_client, + pos_max_d, m_collisionbox, player_stepheight, dtime, + &position, &m_speed, accel_f, NULL, true, true); - bool could_sneak = control.sneak && !free_move && !in_liquid && !is_climbing && - physics_override_sneak; + bool could_sneak = control.sneak && !free_move && !in_liquid && + !is_climbing && physics_override_sneak; // Add new collisions to the vector if (collision_info && !free_move) { @@ -362,10 +367,10 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, // (BS * 0.6f) is the basic stepheight while standing on ground if (y_diff < BS * 0.6f) { // Only center player when they're on the node - position.X = rangelim(position.X, bmin.X - sneak_max.X, - bmax.X + sneak_max.X); - position.Z = rangelim(position.Z, bmin.Z - sneak_max.Z, - bmax.Z + sneak_max.Z); + position.X = rangelim(position.X, + bmin.X - sneak_max.X, bmax.X + sneak_max.X); + position.Z = rangelim(position.Z, + bmin.Z - sneak_max.Z, bmax.Z + sneak_max.Z); if (position.X != old_pos.X) m_speed.X = 0.0f; @@ -388,7 +393,8 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, if (m_speed.Y == 0.0f || m_sneak_ladder_detected) sneak_can_jump = true; - if (collision_info && m_speed.Y - old_speed.Y > BS) { + if (collision_info && + m_speed.Y - old_speed.Y > BS) { // Collide with sneak node, report fall damage CollisionInfo sn_info; sn_info.node_p = m_sneak_node; @@ -417,8 +423,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, */ if (!result.standing_on_object && !touching_ground_was && touching_ground) { - m_client->getEventManager()->put( - new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); + m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); // Set camera impact value to be used for view bobbing camera_impact = getSpeed().Y * -1; @@ -438,18 +443,16 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, Check properties of the node on which the player is standing */ const ContentFeatures &f = nodemgr->get(map->getNode(m_standing_node)); - const ContentFeatures &f1 = - nodemgr->get(map->getNode(m_standing_node + v3s16(0, 1, 0))); + const ContentFeatures &f1 = nodemgr->get(map->getNode(m_standing_node + v3s16(0, 1, 0))); // Determine if jumping is possible m_disable_jump = itemgroup_get(f.groups, "disable_jump") || - itemgroup_get(f1.groups, "disable_jump"); - m_can_jump = ((touching_ground && !is_climbing) || sneak_can_jump) && - !m_disable_jump; + itemgroup_get(f1.groups, "disable_jump"); + m_can_jump = ((touching_ground && !is_climbing) || sneak_can_jump) && !m_disable_jump; // Jump key pressed while jumping off from a bouncy block if (m_can_jump && control.jump && itemgroup_get(f.groups, "bouncy") && - m_speed.Y >= -0.5f * BS) { + m_speed.Y >= -0.5f * BS) { float jumpspeed = movement_speed_jump * physics_override_jump; if (m_speed.Y > 1.0f) { // Reduce boost when speed already is high @@ -458,7 +461,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, m_speed.Y += jumpspeed; } setSpeed(m_speed); - if (!m_freecam) + if (! m_freecam) m_legit_speed = m_speed; m_can_jump = false; } @@ -500,8 +503,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env) bool free_move = fly_allowed && player_settings.free_move; bool fast_move = fast_allowed && player_settings.fast_move; bool pitch_move = (free_move || in_liquid) && player_settings.pitch_move; - // When aux1_descends is enabled the fast key is used to go down, so fast isn't - // possible + // When aux1_descends is enabled the fast key is used to go down, so fast isn't possible bool fast_climb = fast_move && control.aux1 && !player_settings.aux1_descends; bool always_fly_fast = player_settings.always_fly_fast; @@ -578,8 +580,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env) speedH -= v3f(0.0f, 0.0f, 1.0f); if (!control.up && !control.down) - speedH -= v3f(0.0f, 0.0f, 1.0f) * - (control.forw_move_joystick_axis / 32767.f); + speedH -= v3f(0.0f, 0.0f, 1.0f) * (control.forw_move_joystick_axis / 32767.f); if (control.left) speedH += v3f(-1.0f, 0.0f, 0.0f); @@ -588,8 +589,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env) speedH += v3f(1.0f, 0.0f, 0.0f); if (!control.left && !control.right) - speedH += v3f(1.0f, 0.0f, 0.0f) * - (control.sidew_move_joystick_axis / 32767.f); + speedH += v3f(1.0f, 0.0f, 0.0f) * (control.sidew_move_joystick_axis / 32767.f); if (m_autojump) { // release autojump after a given time @@ -621,8 +621,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env) if (speedJ.Y >= -0.5f * BS) { speedJ.Y = movement_speed_jump * physics_override_jump; setSpeed(speedJ); - m_client->getEventManager()->put(new SimpleTriggerEvent( - MtEvent::PLAYER_JUMP)); + m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_JUMP)); } } else if (in_liquid && !m_disable_jump) { if (fast_climb) @@ -642,8 +641,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env) if (superspeed || (is_climbing && fast_climb) || ((in_liquid || in_liquid_stable) && fast_climb)) speedH = speedH.normalize() * movement_speed_fast; - else if (control.sneak && !free_move && !in_liquid && !in_liquid_stable && - !g_settings->getBool("no_slow")) + else if (control.sneak && !free_move && !in_liquid && !in_liquid_stable && !g_settings->getBool("no_slow")) speedH = speedH.normalize() * movement_speed_crouch; else speedH = speedH.normalize() * movement_speed_walk; @@ -679,8 +677,8 @@ void LocalPlayer::applyControl(float dtime, Environment *env) // Accelerate to target speed with maximum increment accelerate((speedH + speedV) * physics_override_speed, - incH * physics_override_speed * slip_factor, - incV * physics_override_speed, pitch_move); + incH * physics_override_speed * slip_factor, incV * physics_override_speed, + pitch_move); } v3s16 LocalPlayer::getStandingNodePos() @@ -715,15 +713,13 @@ v3s16 LocalPlayer::getLightPosition() const v3f LocalPlayer::getEyeOffset() const { - float eye_height = - camera_barely_in_ceiling ? m_eye_height - 0.125f : m_eye_height; + float eye_height = camera_barely_in_ceiling ? m_eye_height - 0.125f : m_eye_height; return v3f(0.0f, BS * eye_height, 0.0f); } ClientActiveObject *LocalPlayer::getParent() const { - return (m_cao && !g_settings->getBool("entity_speed")) ? m_cao->getParent() - : nullptr; + return (m_cao && ! g_settings->getBool("entity_speed")) ? m_cao->getParent() : nullptr; } bool LocalPlayer::isDead() const @@ -741,19 +737,17 @@ void LocalPlayer::tryReattach(int id) bool LocalPlayer::isWaitingForReattach() const { - return g_settings->getBool("entity_speed") && m_cao && !m_cao->getParent() && - m_cao->m_waiting_for_reattach > 0; + return g_settings->getBool("entity_speed") && m_cao && ! m_cao->getParent() && m_cao->m_waiting_for_reattach > 0; } // 3D acceleration void LocalPlayer::accelerate(const v3f &target_speed, const f32 max_increase_H, - const f32 max_increase_V, const bool use_pitch) + const f32 max_increase_V, const bool use_pitch) { const f32 yaw = getYaw(); const f32 pitch = getPitch(); v3f flat_speed = m_speed; - // Rotate speed vector by -yaw and -pitch to make it relative to the player's yaw - // and pitch + // Rotate speed vector by -yaw and -pitch to make it relative to the player's yaw and pitch flat_speed.rotateXZBy(-yaw); if (use_pitch) flat_speed.rotateYZBy(-pitch); @@ -790,7 +784,7 @@ void LocalPlayer::accelerate(const v3f &target_speed, const f32 max_increase_H, // Temporary option for old move code void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, - std::vector *collision_info) + std::vector *collision_info) { Map *map = &env->getMap(); const NodeDefManager *nodemgr = m_client->ndef(); @@ -840,8 +834,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, node = map->getNode(pp, &is_valid_position); if (is_valid_position) { in_liquid = nodemgr->get(node.getContent()).isLiquid(); - liquid_viscosity = - nodemgr->get(node.getContent()).liquid_viscosity; + liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity; } else { in_liquid = false; } @@ -851,8 +844,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, node = map->getNode(pp, &is_valid_position); if (is_valid_position) { in_liquid = nodemgr->get(node.getContent()).isLiquid(); - liquid_viscosity = - nodemgr->get(node.getContent()).liquid_viscosity; + liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity; } else { in_liquid = false; } @@ -881,15 +873,13 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, is_climbing = false; else is_climbing = (nodemgr->get(node.getContent()).climbable || - nodemgr->get(node2.getContent()) - .climbable) && - !free_move; + nodemgr->get(node2.getContent()).climbable) && !free_move; /* Collision uncertainty radius Make it a bit larger than the maximum distance of movement */ - // f32 d = pos_max_d * 1.1; + //f32 d = pos_max_d * 1.1; // A fairly large value in here makes moving smoother f32 d = 0.15f * BS; // This should always apply, otherwise there are glitches @@ -917,8 +907,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, /* Collision seems broken, since player is sinking when sneaking over the edges of current sneaking_node. - TODO (when fixed): Set Y-speed only to 0 when position.Y < - new_y. + TODO (when fixed): Set Y-speed only to 0 when position.Y < new_y. */ if (m_speed.Y < 0.0f) m_speed.Y = 0.0f; @@ -932,9 +921,9 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, const v3f initial_position = position; const v3f initial_speed = m_speed; - collisionMoveResult result = collisionMoveSimple(env, m_client, pos_max_d, - m_collisionbox, player_stepheight, dtime, &position, &m_speed, - accel_f, NULL, true, true); + collisionMoveResult result = collisionMoveSimple(env, m_client, + pos_max_d, m_collisionbox, player_stepheight, dtime, + &position, &m_speed, accel_f, NULL, true, true); // Positition was slightly changed; update standing node pos if (touching_ground) @@ -951,7 +940,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, bool touching_ground_was = touching_ground; touching_ground = result.touching_ground; - // bool standing_on_unloaded = result.standing_on_unloaded; + //bool standing_on_unloaded = result.standing_on_unloaded; /* Check the nodes under the player to see from which node the @@ -977,51 +966,44 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, if (m_need_to_get_new_sneak_node && physics_override_sneak) { m_sneak_node_bb_ymax = 0.0f; - v3s16 pos_i_bottom = floatToInt( - position - v3f(0.0f, position_y_mod, 0.0f), BS); + v3s16 pos_i_bottom = floatToInt(position - v3f(0.0f, position_y_mod, 0.0f), BS); v2f player_p2df(position.X, position.Z); f32 min_distance_f = 100000.0f * BS; // If already seeking from some node, compare to it. v3s16 new_sneak_node = m_sneak_node; - for (s16 x = -1; x <= 1; x++) - for (s16 z = -1; z <= 1; z++) { - v3s16 p = pos_i_bottom + v3s16(x, 0, z); - v3f pf = intToFloat(p, BS); - v2f node_p2df(pf.X, pf.Z); - f32 distance_f = player_p2df.getDistanceFrom(node_p2df); - f32 max_axis_distance_f = MYMAX( - std::fabs(player_p2df.X - node_p2df.X), - std::fabs(player_p2df.Y - node_p2df.Y)); - - if (distance_f > min_distance_f || - max_axis_distance_f > - 0.5f * BS + sneak_max + - 0.1f * BS) - continue; + for (s16 x= -1; x <= 1; x++) + for (s16 z= -1; z <= 1; z++) { + v3s16 p = pos_i_bottom + v3s16(x, 0, z); + v3f pf = intToFloat(p, BS); + v2f node_p2df(pf.X, pf.Z); + f32 distance_f = player_p2df.getDistanceFrom(node_p2df); + f32 max_axis_distance_f = MYMAX( + std::fabs(player_p2df.X - node_p2df.X), + std::fabs(player_p2df.Y - node_p2df.Y)); + + if (distance_f > min_distance_f || + max_axis_distance_f > 0.5f * BS + sneak_max + 0.1f * BS) + continue; - // The node to be sneaked on has to be walkable - node = map->getNode(p, &is_valid_position); - if (!is_valid_position || !nodemgr->get(node).walkable) - continue; - // And the node above it has to be nonwalkable - node = map->getNode( - p + v3s16(0, 1, 0), &is_valid_position); + // The node to be sneaked on has to be walkable + node = map->getNode(p, &is_valid_position); + if (!is_valid_position || !nodemgr->get(node).walkable) + continue; + // And the node above it has to be nonwalkable + node = map->getNode(p + v3s16(0, 1, 0), &is_valid_position); + if (!is_valid_position || nodemgr->get(node).walkable) + continue; + // If not 'sneak_glitch' the node 2 nodes above it has to be nonwalkable + if (!physics_override_sneak_glitch) { + node = map->getNode(p + v3s16(0, 2, 0), &is_valid_position); if (!is_valid_position || nodemgr->get(node).walkable) continue; - // If not 'sneak_glitch' the node 2 nodes above it has to - // be nonwalkable - if (!physics_override_sneak_glitch) { - node = map->getNode(p + v3s16(0, 2, 0), - &is_valid_position); - if (!is_valid_position || - nodemgr->get(node).walkable) - continue; - } - - min_distance_f = distance_f; - new_sneak_node = p; } + min_distance_f = distance_f; + new_sneak_node = p; + } + bool sneak_node_found = (min_distance_f < 100000.0f * BS * 0.9f); m_sneak_node = new_sneak_node; @@ -1065,8 +1047,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d, } if (!result.standing_on_object && !touching_ground_was && touching_ground) { - m_client->getEventManager()->put( - new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); + m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); // Set camera impact value to be used for view bobbing camera_impact = getSpeed().Y * -1.0f; } @@ -1134,8 +1115,8 @@ float LocalPlayer::getSlipFactor(Environment *env, const v3f &speedH) } void LocalPlayer::handleAutojump(f32 dtime, Environment *env, - const collisionMoveResult &result, const v3f &initial_position, - const v3f &initial_speed, f32 pos_max_d) + const collisionMoveResult &result, const v3f &initial_position, + const v3f &initial_speed, f32 pos_max_d) { PlayerSettings &player_settings = getPlayerSettings(); if (!player_settings.autojump) @@ -1145,11 +1126,11 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env, return; bool control_forward = control.up || - (!control.up && !control.down && - control.forw_move_joystick_axis < -0.05f); + (!control.up && !control.down && + control.forw_move_joystick_axis < -0.05f); bool could_autojump = - m_can_jump && !control.jump && !control.sneak && control_forward; + m_can_jump && !control.jump && !control.sneak && control_forward; if (!could_autojump) return; @@ -1176,14 +1157,12 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env, bool is_position_valid; for (s16 z = ceilpos_min.Z; z <= ceilpos_max.Z; ++z) { for (s16 x = ceilpos_min.X; x <= ceilpos_max.X; ++x) { - MapNode n = env->getMap().getNode( - v3s16(x, ceilpos_max.Y, z), &is_position_valid); + MapNode n = env->getMap().getNode(v3s16(x, ceilpos_max.Y, z), &is_position_valid); if (!is_position_valid) - break; // won't collide with the void outside + break; // won't collide with the void outside if (n.getContent() == CONTENT_IGNORE) - return; // players collide with ignore blocks -> same as - // walkable + return; // players collide with ignore blocks -> same as walkable const ContentFeatures &f = ndef->get(n); if (f.walkable) return; // would bump head, don't jump @@ -1196,8 +1175,7 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env, // try at peak of jump, zero step height collisionMoveResult jump_result = collisionMoveSimple(env, m_client, pos_max_d, - m_collisionbox, 0.0f, dtime, &jump_pos, &jump_speed, v3f(0.0f), - NULL, true, true); + m_collisionbox, 0.0f, dtime, &jump_pos, &jump_speed, v3f(0.0f), NULL, true, true); // see if we can get a little bit farther horizontally if we had // jumped @@ -1210,3 +1188,4 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env, m_autojump_time = 0.1f; } } + diff --git a/src/client/localplayer.h b/src/client/localplayer.h index 8b2d932ab..0e071d2b4 100644 --- a/src/client/localplayer.h +++ b/src/client/localplayer.h @@ -132,7 +132,7 @@ class LocalPlayer : public Player inline void setPosition(const v3f &position) { m_position = position; - if (!m_freecam) + if (! m_freecam) m_legit_position = position; m_sneak_node_exists = false; } @@ -140,7 +140,7 @@ class LocalPlayer : public Player v3f getPosition() const { return m_position; } v3f getLegitPosition() const { return m_legit_position; } - + v3f getLegitSpeed() const { return m_legit_speed; } inline void setLegitPosition(const v3f &position) @@ -151,15 +151,18 @@ class LocalPlayer : public Player setPosition(position); } - inline void freecamEnable() { m_freecam = true; } - - inline void freecamDisable() + inline void freecamEnable() + { + m_freecam = true; + } + + inline void freecamDisable() { m_freecam = false; setPosition(m_legit_position); setSpeed(m_legit_speed); } - + // Non-transformed eye offset getters // For accurate positions, use the Camera functions v3f getEyePosition() const { return m_position + getEyeOffset(); } @@ -168,7 +171,7 @@ class LocalPlayer : public Player void setCollisionbox(const aabb3f &box) { m_collisionbox = box; } - const aabb3f &getCollisionbox() const { return m_collisionbox; } + const aabb3f& getCollisionbox() const { return m_collisionbox; } float getZoomFOV() const { return m_zoom_fov; } void setZoomFOV(float zoom_fov) { m_zoom_fov = zoom_fov; } @@ -177,23 +180,26 @@ class LocalPlayer : public Player bool isDead() const; - inline void addVelocity(const v3f &vel) { added_velocity += vel; } - + inline void addVelocity(const v3f &vel) + { + added_velocity += vel; + } + void tryReattach(int id); - + bool isWaitingForReattach() const; - + bool canWalkOn(const ContentFeatures &f); - + private: void accelerate(const v3f &target_speed, const f32 max_increase_H, - const f32 max_increase_V, const bool use_pitch); + const f32 max_increase_V, const bool use_pitch); bool updateSneakNode(Map *map, const v3f &position, const v3f &sneak_max); float getSlipFactor(Environment *env, const v3f &speedH); void handleAutojump(f32 dtime, Environment *env, - const collisionMoveResult &result, - const v3f &position_before_move, const v3f &speed_before_move, - f32 pos_max_d); + const collisionMoveResult &result, + const v3f &position_before_move, const v3f &speed_before_move, + f32 pos_max_d); bool m_freecam = false; v3f m_position; @@ -228,7 +234,7 @@ class LocalPlayer : public Player f32 m_pitch = 0.0f; bool camera_barely_in_ceiling = false; aabb3f m_collisionbox = aabb3f(-BS * 0.30f, 0.0f, -BS * 0.30f, BS * 0.30f, - BS * 1.75f, BS * 0.30f); + BS * 1.75f, BS * 0.30f); float m_eye_height = 1.625f; float m_zoom_fov = 0.0f; bool m_autojump = false; diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 9487eae22..fbd7e2ab7 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -35,40 +35,40 @@ with this program; if not, write to the Free Software Foundation, Inc., MeshMakeData */ -MeshMakeData::MeshMakeData(Client *client, bool use_shaders, bool use_tangent_vertices) : - m_client(client), m_use_shaders(use_shaders), - m_use_tangent_vertices(use_tangent_vertices) -{ -} +MeshMakeData::MeshMakeData(Client *client, bool use_shaders, + bool use_tangent_vertices): + m_client(client), + m_use_shaders(use_shaders), + m_use_tangent_vertices(use_tangent_vertices) +{} void MeshMakeData::fillBlockDataBegin(const v3s16 &blockpos) { m_blockpos = blockpos; - v3s16 blockpos_nodes = m_blockpos * MAP_BLOCKSIZE; + v3s16 blockpos_nodes = m_blockpos*MAP_BLOCKSIZE; m_vmanip.clear(); - VoxelArea voxel_area(blockpos_nodes - v3s16(1, 1, 1) * MAP_BLOCKSIZE, - blockpos_nodes + v3s16(1, 1, 1) * MAP_BLOCKSIZE * 2 - - v3s16(1, 1, 1)); + VoxelArea voxel_area(blockpos_nodes - v3s16(1,1,1) * MAP_BLOCKSIZE, + blockpos_nodes + v3s16(1,1,1) * MAP_BLOCKSIZE*2-v3s16(1,1,1)); m_vmanip.addArea(voxel_area); } void MeshMakeData::fillBlockData(const v3s16 &block_offset, MapNode *data) { v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); - VoxelArea data_area(v3s16(0, 0, 0), data_size - v3s16(1, 1, 1)); + VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1)); v3s16 bp = m_blockpos + block_offset; v3s16 blockpos_nodes = bp * MAP_BLOCKSIZE; - m_vmanip.copyFrom(data, data_area, v3s16(0, 0, 0), blockpos_nodes, data_size); + m_vmanip.copyFrom(data, data_area, v3s16(0,0,0), blockpos_nodes, data_size); } void MeshMakeData::fill(MapBlock *block) { fillBlockDataBegin(block->getPos()); - fillBlockData(v3s16(0, 0, 0), block->getData()); + fillBlockData(v3s16(0,0,0), block->getData()); // Get map for reading neighbor blocks Map *map = block->getParent(); @@ -76,21 +76,20 @@ void MeshMakeData::fill(MapBlock *block) for (const v3s16 &dir : g_26dirs) { v3s16 bp = m_blockpos + dir; MapBlock *b = map->getBlockNoCreateNoEx(bp); - if (b) + if(b) fillBlockData(dir, b->getData()); } } void MeshMakeData::fillSingleNode(MapNode *node) { - m_blockpos = v3s16(0, 0, 0); + m_blockpos = v3s16(0,0,0); - v3s16 blockpos_nodes = v3s16(0, 0, 0); - VoxelArea area(blockpos_nodes - v3s16(1, 1, 1) * MAP_BLOCKSIZE, - blockpos_nodes + v3s16(1, 1, 1) * MAP_BLOCKSIZE * 2 - - v3s16(1, 1, 1)); + v3s16 blockpos_nodes = v3s16(0,0,0); + VoxelArea area(blockpos_nodes-v3s16(1,1,1)*MAP_BLOCKSIZE, + blockpos_nodes+v3s16(1,1,1)*MAP_BLOCKSIZE*2-v3s16(1,1,1)); s32 volume = area.getVolume(); - s32 our_node_index = area.index(1, 1, 1); + s32 our_node_index = area.index(1,1,1); // Allocate this block + neighbors m_vmanip.clear(); @@ -98,7 +97,8 @@ void MeshMakeData::fillSingleNode(MapNode *node) // Fill in data MapNode *data = new MapNode[volume]; - for (s32 i = 0; i < volume; i++) { + for(s32 i = 0; i < volume; i++) + { if (i == our_node_index) data[i] = *node; else @@ -111,12 +111,12 @@ void MeshMakeData::fillSingleNode(MapNode *node) void MeshMakeData::setCrack(int crack_level, v3s16 crack_pos) { if (crack_level >= 0) - m_crack_pos_relative = crack_pos - m_blockpos * MAP_BLOCKSIZE; + m_crack_pos_relative = crack_pos - m_blockpos*MAP_BLOCKSIZE; } void MeshMakeData::setSmoothLighting(bool smooth_lighting) { - m_smooth_lighting = smooth_lighting && !g_settings->getBool("fullbright"); + m_smooth_lighting = smooth_lighting && ! g_settings->getBool("fullbright"); } /* @@ -127,13 +127,13 @@ void MeshMakeData::setSmoothLighting(bool smooth_lighting) Calculate non-smooth lighting at interior of node. Single light bank. */ -static u8 getInteriorLight( - enum LightBank bank, MapNode n, s32 increment, const NodeDefManager *ndef) +static u8 getInteriorLight(enum LightBank bank, MapNode n, s32 increment, + const NodeDefManager *ndef) { u8 light = n.getLight(bank, ndef); if (light > 0) light = rangelim(light + increment, 0, LIGHT_SUN); - if (g_settings->getBool("fullbright")) + if(g_settings->getBool("fullbright")) return 255; return decode_light(light); } @@ -153,22 +153,23 @@ u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef) Calculate non-smooth lighting at face of node. Single light bank. */ -static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2, v3s16 face_dir, - const NodeDefManager *ndef) +static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2, + v3s16 face_dir, const NodeDefManager *ndef) { u8 light; u8 l1 = n.getLight(bank, ndef); u8 l2 = n2.getLight(bank, ndef); - if (l1 > l2) + if(l1 > l2) light = l1; else light = l2; // Boost light level for light sources - u8 light_source = MYMAX(ndef->get(n).light_source, ndef->get(n2).light_source); - if (light_source > light) + u8 light_source = MYMAX(ndef->get(n).light_source, + ndef->get(n2).light_source); + if(light_source > light) light = light_source; - if (g_settings->getBool("fullbright")) + if(g_settings->getBool("fullbright")) return 255; return decode_light(light); } @@ -177,7 +178,8 @@ static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2, v3s16 face_di Calculate non-smooth lighting at face of node. Both light banks. */ -u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir, const NodeDefManager *ndef) +u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir, + const NodeDefManager *ndef) { u16 day = getFaceLight(LIGHTBANK_DAY, n, n2, face_dir, ndef); u16 night = getFaceLight(LIGHTBANK_NIGHT, n, n2, face_dir, ndef); @@ -188,8 +190,8 @@ u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir, const NodeDefMana Calculate smooth lighting at the XYZ- corner of p. Both light banks */ -static u16 getSmoothLightCombined( - const v3s16 &p, const std::array &dirs, MeshMakeData *data) +static u16 getSmoothLightCombined(const v3s16 &p, + const std::array &dirs, MeshMakeData *data) { const NodeDefManager *ndef = data->m_client->ndef(); @@ -200,7 +202,7 @@ static u16 getSmoothLightCombined( u16 light_night = 0; bool direct_sunlight = false; - auto add_node = [&](u8 i, bool obstructed = false) -> bool { + auto add_node = [&] (u8 i, bool obstructed = false) -> bool { if (obstructed) { ambient_occlusion++; return false; @@ -226,7 +228,7 @@ static u16 getSmoothLightCombined( return f.light_propagates; }; - bool obstructed[4] = {true, true, true, true}; + bool obstructed[4] = { true, true, true, true }; add_node(0); bool opaque1 = !add_node(1); bool opaque2 = !add_node(2); @@ -262,34 +264,31 @@ static u16 getSmoothLightCombined( } bool skip_ambient_occlusion_night = false; - if (decode_light(light_source_max) >= light_night) { + if(decode_light(light_source_max) >= light_night) { light_night = decode_light(light_source_max); skip_ambient_occlusion_night = true; } if (ambient_occlusion > 4) { - static thread_local const float ao_gamma = - rangelim(g_settings->getFloat("ambient_occlusion_gamma"), - 0.25, 4.0); + static thread_local const float ao_gamma = rangelim( + g_settings->getFloat("ambient_occlusion_gamma"), 0.25, 4.0); // Table of gamma space multiply factors. static thread_local const float light_amount[3] = { - powf(0.75, 1.0 / ao_gamma), powf(0.5, 1.0 / ao_gamma), - powf(0.25, 1.0 / ao_gamma)}; + powf(0.75, 1.0 / ao_gamma), + powf(0.5, 1.0 / ao_gamma), + powf(0.25, 1.0 / ao_gamma) + }; - // calculate table index for gamma space multiplier + //calculate table index for gamma space multiplier ambient_occlusion -= 5; if (!skip_ambient_occlusion_day) - light_day = rangelim( - core::round32(light_day * - light_amount[ambient_occlusion]), - 0, 255); + light_day = rangelim(core::round32( + light_day * light_amount[ambient_occlusion]), 0, 255); if (!skip_ambient_occlusion_night) - light_night = rangelim( - core::round32(light_night * - light_amount[ambient_occlusion]), - 0, 255); + light_night = rangelim(core::round32( + light_night * light_amount[ambient_occlusion]), 0, 255); } return light_day | (light_night << 8); @@ -300,8 +299,7 @@ static u16 getSmoothLightCombined( Both light banks. Node at p is solid, and thus the lighting is face-dependent. */ -u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, - MeshMakeData *data) +u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data) { return getSmoothLightTransparent(p + face_dir, corner - 2 * face_dir, data); } @@ -313,19 +311,23 @@ u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corn */ u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data) { - const std::array dirs = {{// Always shine light - v3s16(0, 0, 0), v3s16(corner.X, 0, 0), v3s16(0, corner.Y, 0), - v3s16(0, 0, corner.Z), - - // Can be obstructed - v3s16(corner.X, corner.Y, 0), v3s16(corner.X, 0, corner.Z), - v3s16(0, corner.Y, corner.Z), - v3s16(corner.X, corner.Y, corner.Z)}}; + const std::array dirs = {{ + // Always shine light + v3s16(0,0,0), + v3s16(corner.X,0,0), + v3s16(0,corner.Y,0), + v3s16(0,0,corner.Z), + + // Can be obstructed + v3s16(corner.X,corner.Y,0), + v3s16(corner.X,0,corner.Z), + v3s16(0,corner.Y,corner.Z), + v3s16(corner.X,corner.Y,corner.Z) + }}; return getSmoothLightCombined(p, dirs, data); } -void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio) -{ +void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio){ f32 rg = daynight_ratio / 1000.0f - 0.04f; f32 b = (0.98f * daynight_ratio) / 1000.0f + 0.078f; sunlight->r = rg; @@ -333,15 +335,17 @@ void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio) sunlight->b = b; } -void final_color_blend(video::SColor *result, u16 light, u32 daynight_ratio) +void final_color_blend(video::SColor *result, + u16 light, u32 daynight_ratio) { video::SColorf dayLight; get_sunlight_color(&dayLight, daynight_ratio); - final_color_blend(result, encode_light(light, 0), dayLight); + final_color_blend(result, + encode_light(light, 0), dayLight); } -void final_color_blend(video::SColor *result, const video::SColor &data, - const video::SColorf &dayLight) +void final_color_blend(video::SColor *result, + const video::SColor &data, const video::SColorf &dayLight) { static const video::SColorf artificialColor(1.04f, 1.04f, 1.04f); @@ -355,48 +359,16 @@ void final_color_blend(video::SColor *result, const video::SColor &data, // Emphase blue a bit in darker places // Each entry of this array represents a range of 8 blue levels static const u8 emphase_blue_when_dark[32] = { - 1, - 4, - 6, - 6, - 6, - 5, - 4, - 3, - 2, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, + 1, 4, 6, 6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; - b += emphase_blue_when_dark[irr::core::clamp((s32)((r + g + b) / 3 * 255), 0, - 255) / - 8] / - 255.0f; + b += emphase_blue_when_dark[irr::core::clamp((s32) ((r + g + b) / 3 * 255), + 0, 255) / 8] / 255.0f; - result->setRed(core::clamp((s32)(r * 255.0f), 0, 255)); - result->setGreen(core::clamp((s32)(g * 255.0f), 0, 255)); - result->setBlue(core::clamp((s32)(b * 255.0f), 0, 255)); + result->setRed(core::clamp((s32) (r * 255.0f), 0, 255)); + result->setGreen(core::clamp((s32) (g * 255.0f), 0, 255)); + result->setBlue(core::clamp((s32) (b * 255.0f), 0, 255)); } /* @@ -407,20 +379,27 @@ void final_color_blend(video::SColor *result, const video::SColor &data, // a mutex to initialize this table at runtime right in the hot path. // For details search the internet for "cxa_guard_acquire". static const v3s16 vertex_dirs_table[] = { - // ( 1, 0, 0) - v3s16(1, -1, 1), v3s16(1, -1, -1), v3s16(1, 1, -1), v3s16(1, 1, 1), - // ( 0, 1, 0) - v3s16(1, 1, -1), v3s16(-1, 1, -1), v3s16(-1, 1, 1), v3s16(1, 1, 1), - // ( 0, 0, 1) - v3s16(-1, -1, 1), v3s16(1, -1, 1), v3s16(1, 1, 1), v3s16(-1, 1, 1), - // invalid - v3s16(), v3s16(), v3s16(), v3s16(), - // ( 0, 0,-1) - v3s16(1, -1, -1), v3s16(-1, -1, -1), v3s16(-1, 1, -1), v3s16(1, 1, -1), - // ( 0,-1, 0) - v3s16(1, -1, 1), v3s16(-1, -1, 1), v3s16(-1, -1, -1), v3s16(1, -1, -1), - // (-1, 0, 0) - v3s16(-1, -1, -1), v3s16(-1, -1, 1), v3s16(-1, 1, 1), v3s16(-1, 1, -1)}; + // ( 1, 0, 0) + v3s16( 1,-1, 1), v3s16( 1,-1,-1), + v3s16( 1, 1,-1), v3s16( 1, 1, 1), + // ( 0, 1, 0) + v3s16( 1, 1,-1), v3s16(-1, 1,-1), + v3s16(-1, 1, 1), v3s16( 1, 1, 1), + // ( 0, 0, 1) + v3s16(-1,-1, 1), v3s16( 1,-1, 1), + v3s16( 1, 1, 1), v3s16(-1, 1, 1), + // invalid + v3s16(), v3s16(), v3s16(), v3s16(), + // ( 0, 0,-1) + v3s16( 1,-1,-1), v3s16(-1,-1,-1), + v3s16(-1, 1,-1), v3s16( 1, 1,-1), + // ( 0,-1, 0) + v3s16( 1,-1, 1), v3s16(-1,-1, 1), + v3s16(-1,-1,-1), v3s16( 1,-1,-1), + // (-1, 0, 0) + v3s16(-1,-1,-1), v3s16(-1,-1, 1), + v3s16(-1, 1, 1), v3s16(-1, 1,-1) +}; /* vertex_dirs: v3s16[4] @@ -446,27 +425,26 @@ static void getNodeVertexDirs(const v3s16 &dir, v3s16 *vertex_dirs) memcpy(vertex_dirs, &vertex_dirs_table[idx], 4 * sizeof(v3s16)); } -static void getNodeTextureCoords( - v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v) +static void getNodeTextureCoords(v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v) { if (dir.X > 0 || dir.Y > 0 || dir.Z < 0) base -= scale; - if (dir == v3s16(0, 0, 1)) { + if (dir == v3s16(0,0,1)) { *u = -base.X - 1; *v = -base.Y - 1; - } else if (dir == v3s16(0, 0, -1)) { + } else if (dir == v3s16(0,0,-1)) { *u = base.X + 1; *v = -base.Y - 2; - } else if (dir == v3s16(1, 0, 0)) { + } else if (dir == v3s16(1,0,0)) { *u = base.Z + 1; *v = -base.Y - 2; - } else if (dir == v3s16(-1, 0, 0)) { + } else if (dir == v3s16(-1,0,0)) { *u = -base.Z - 1; *v = -base.Y - 1; - } else if (dir == v3s16(0, 1, 0)) { + } else if (dir == v3s16(0,1,0)) { *u = base.X + 1; *v = -base.Z - 2; - } else if (dir == v3s16(0, -1, 0)) { + } else if (dir == v3s16(0,-1,0)) { *u = base.X; *v = base.Z; } @@ -485,8 +463,7 @@ struct FastFace }; static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li3, - const v3f &tp, const v3f &p, const v3s16 &dir, const v3f &scale, - std::vector &dest) + const v3f &tp, const v3f &p, const v3s16 &dir, const v3f &scale, std::vector &dest) { // Position is at the center of the cube. v3f pos = p * BS; @@ -507,51 +484,51 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li switch (tile.rotation) { case 0: break; - case 1: // R90 + case 1: //R90 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[3]; vertex_dirs[3] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[1]; vertex_dirs[1] = t; - t1 = li0; + t1 = li0; li0 = li3; li3 = li2; li2 = li1; li1 = t1; break; - case 2: // R180 + case 2: //R180 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[2]; vertex_dirs[2] = t; t = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[3]; vertex_dirs[3] = t; - t1 = li0; + t1 = li0; li0 = li2; li2 = t1; - t1 = li1; + t1 = li1; li1 = li3; li3 = t1; break; - case 3: // R270 + case 3: //R270 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[3]; vertex_dirs[3] = t; - t1 = li0; + t1 = li0; li0 = li1; li1 = li2; li2 = li3; li3 = t1; break; - case 4: // FXR90 + case 4: //FXR90 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[3]; vertex_dirs[3] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[1]; vertex_dirs[1] = t; - t1 = li0; + t1 = li0; li0 = li3; li3 = li2; li2 = li1; @@ -559,13 +536,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li y0 += h; h *= -1; break; - case 5: // FXR270 + case 5: //FXR270 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[3]; vertex_dirs[3] = t; - t1 = li0; + t1 = li0; li0 = li1; li1 = li2; li2 = li3; @@ -573,13 +550,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li y0 += h; h *= -1; break; - case 6: // FYR90 + case 6: //FYR90 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[3]; vertex_dirs[3] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[1]; vertex_dirs[1] = t; - t1 = li0; + t1 = li0; li0 = li3; li3 = li2; li2 = li1; @@ -587,13 +564,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li x0 += w; w *= -1; break; - case 7: // FYR270 + case 7: //FYR270 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[3]; vertex_dirs[3] = t; - t1 = li0; + t1 = li0; li0 = li1; li1 = li2; li2 = li3; @@ -601,11 +578,11 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li x0 += w; w *= -1; break; - case 8: // FX + case 8: //FX y0 += h; h *= -1; break; - case 9: // FY + case 9: //FY x0 += w; w *= -1; break; @@ -614,8 +591,11 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li } for (u16 i = 0; i < 4; i++) { - vertex_pos[i] = v3f(BS / 2 * vertex_dirs[i].X, BS / 2 * vertex_dirs[i].Y, - BS / 2 * vertex_dirs[i].Z); + vertex_pos[i] = v3f( + BS / 2 * vertex_dirs[i].X, + BS / 2 * vertex_dirs[i].Y, + BS / 2 * vertex_dirs[i].Z + ); } for (v3f &vpos : vertex_pos) { @@ -626,16 +606,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li } f32 abs_scale = 1.0f; - if (scale.X < 0.999f || scale.X > 1.001f) - abs_scale = scale.X; - else if (scale.Y < 0.999f || scale.Y > 1.001f) - abs_scale = scale.Y; - else if (scale.Z < 0.999f || scale.Z > 1.001f) - abs_scale = scale.Z; + if (scale.X < 0.999f || scale.X > 1.001f) abs_scale = scale.X; + else if (scale.Y < 0.999f || scale.Y > 1.001f) abs_scale = scale.Y; + else if (scale.Z < 0.999f || scale.Z > 1.001f) abs_scale = scale.Z; v3f normal(dir.X, dir.Y, dir.Z); - u16 li[4] = {li0, li1, li2, li3}; + u16 li[4] = { li0, li1, li2, li3 }; u16 day[4]; u16 night[4]; @@ -644,16 +621,18 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li night[i] = li[i] & 0xFF; } - bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2]) < - abs(day[1] - day[3]) + abs(night[1] - night[3]); + bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2]) + < abs(day[1] - day[3]) + abs(night[1] - night[3]); - v2f32 f[4] = {core::vector2d(x0 + w * abs_scale, y0 + h), - core::vector2d(x0, y0 + h), core::vector2d(x0, y0), - core::vector2d(x0 + w * abs_scale, y0)}; + v2f32 f[4] = { + core::vector2d(x0 + w * abs_scale, y0 + h), + core::vector2d(x0, y0 + h), + core::vector2d(x0, y0), + core::vector2d(x0 + w * abs_scale, y0) }; // equivalent to dest.push_back(FastFace()) but faster dest.emplace_back(); - FastFace &face = *dest.rbegin(); + FastFace& face = *dest.rbegin(); for (u8 i = 0; i < 4; i++) { video::SColor c = encode_light(li[i], tile.emissive_light); @@ -682,8 +661,8 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li TODO: Add 3: Both faces drawn with backface culling, remove equivalent */ -static u8 face_contents( - content_t m1, content_t m2, bool *equivalent, const NodeDefManager *ndef) +static u8 face_contents(content_t m1, content_t m2, bool *equivalent, + const NodeDefManager *ndef) { *equivalent = false; @@ -700,6 +679,7 @@ static u8 face_contents( u8 c1 = f1.solidness; u8 c2 = f2.solidness; + if (c1 == c2) return 0; @@ -708,6 +688,7 @@ static u8 face_contents( else if (c2 == 0) c2 = f2.visual_solidness; + if (c1 == c2) { *equivalent = true; // If same solidness, liquid takes precense @@ -726,8 +707,7 @@ static u8 face_contents( /* Gets nth node tile (0 <= n <= 5). */ -void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, - TileSpec &tile) +void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile) { const NodeDefManager *ndef = data->m_client->ndef(); const ContentFeatures &f = ndef->get(mn); @@ -747,8 +727,7 @@ void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, /* Gets node tile given a face direction. */ -void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, - TileSpec &tile) +void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile) { const NodeDefManager *ndef = data->m_client->ndef(); @@ -770,43 +749,38 @@ void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *dat // Get rotation for things like chests u8 facedir = mn.getFaceDir(ndef, true); - static const u16 dir_to_tile[24 * 16] = {// 0 +X +Y +Z -Z -Y - // -X -> value=tile,rotation - 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 5, 0, 1, 0, 3, - 0, // rotate around y+ 0 - 3 - 0, 0, 4, 0, 0, 3, 3, 0, 0, 0, 2, 0, 1, 1, 5, 0, 0, 0, 3, 0, 0, 2, - 5, 0, 0, 0, 4, 0, 1, 2, 2, 0, 0, 0, 5, 0, 0, 1, 2, 0, 0, 0, 3, 0, - 1, 3, 4, 0, - - 0, 0, 2, 3, 5, 0, 0, 2, 0, 0, 1, 0, 4, 2, 3, - 1, // rotate around z+ 4 - 7 - 0, 0, 4, 3, 2, 0, 0, 1, 0, 0, 1, 1, 3, 2, 5, 1, 0, 0, 3, 3, 4, 0, - 0, 0, 0, 0, 1, 2, 5, 2, 2, 1, 0, 0, 5, 3, 3, 0, 0, 3, 0, 0, 1, 3, - 2, 2, 4, 1, - - 0, 0, 2, 1, 4, 2, 1, 2, 0, 0, 0, 0, 5, 0, 3, - 3, // rotate around z- 8 - 11 - 0, 0, 4, 1, 3, 2, 1, 3, 0, 0, 0, 3, 2, 0, 5, 3, 0, 0, 3, 1, 5, 2, - 1, 0, 0, 0, 0, 2, 4, 0, 2, 3, 0, 0, 5, 1, 2, 2, 1, 1, 0, 0, 0, 1, - 3, 0, 4, 3, - - 0, 0, 0, 3, 3, 3, 4, 1, 0, 0, 5, 3, 2, 3, 1, - 3, // rotate around x+ 12 - 15 - 0, 0, 0, 2, 5, 3, 3, 1, 0, 0, 2, 3, 4, 3, 1, 0, 0, 0, 0, 1, 2, 3, - 5, 1, 0, 0, 4, 3, 3, 3, 1, 1, 0, 0, 0, 0, 4, 3, 2, 1, 0, 0, 3, 3, - 5, 3, 1, 2, - - 0, 0, 1, 1, 2, 1, 4, 3, 0, 0, 5, 1, 3, 1, 0, - 1, // rotate around x- 16 - 19 - 0, 0, 1, 2, 4, 1, 3, 3, 0, 0, 2, 1, 5, 1, 0, 0, 0, 0, 1, 3, 3, 1, - 5, 3, 0, 0, 4, 1, 2, 1, 0, 3, 0, 0, 1, 0, 5, 1, 2, 3, 0, 0, 3, 1, - 4, 1, 0, 2, - - 0, 0, 3, 2, 1, 2, 4, 2, 0, 0, 5, 2, 0, 2, 2, - 2, // rotate around y- 20 - 23 - 0, 0, 5, 2, 1, 3, 3, 2, 0, 0, 2, 2, 0, 1, 4, 2, 0, 0, 2, 2, 1, 0, - 5, 2, 0, 0, 4, 2, 0, 0, 3, 2, 0, 0, 4, 2, 1, 1, 2, 2, 0, 0, 3, 2, - 0, 3, 5, 2 + static const u16 dir_to_tile[24 * 16] = + { + // 0 +X +Y +Z -Z -Y -X -> value=tile,rotation + 0,0, 2,0 , 0,0 , 4,0 , 0,0, 5,0 , 1,0 , 3,0 , // rotate around y+ 0 - 3 + 0,0, 4,0 , 0,3 , 3,0 , 0,0, 2,0 , 1,1 , 5,0 , + 0,0, 3,0 , 0,2 , 5,0 , 0,0, 4,0 , 1,2 , 2,0 , + 0,0, 5,0 , 0,1 , 2,0 , 0,0, 3,0 , 1,3 , 4,0 , + + 0,0, 2,3 , 5,0 , 0,2 , 0,0, 1,0 , 4,2 , 3,1 , // rotate around z+ 4 - 7 + 0,0, 4,3 , 2,0 , 0,1 , 0,0, 1,1 , 3,2 , 5,1 , + 0,0, 3,3 , 4,0 , 0,0 , 0,0, 1,2 , 5,2 , 2,1 , + 0,0, 5,3 , 3,0 , 0,3 , 0,0, 1,3 , 2,2 , 4,1 , + + 0,0, 2,1 , 4,2 , 1,2 , 0,0, 0,0 , 5,0 , 3,3 , // rotate around z- 8 - 11 + 0,0, 4,1 , 3,2 , 1,3 , 0,0, 0,3 , 2,0 , 5,3 , + 0,0, 3,1 , 5,2 , 1,0 , 0,0, 0,2 , 4,0 , 2,3 , + 0,0, 5,1 , 2,2 , 1,1 , 0,0, 0,1 , 3,0 , 4,3 , + + 0,0, 0,3 , 3,3 , 4,1 , 0,0, 5,3 , 2,3 , 1,3 , // rotate around x+ 12 - 15 + 0,0, 0,2 , 5,3 , 3,1 , 0,0, 2,3 , 4,3 , 1,0 , + 0,0, 0,1 , 2,3 , 5,1 , 0,0, 4,3 , 3,3 , 1,1 , + 0,0, 0,0 , 4,3 , 2,1 , 0,0, 3,3 , 5,3 , 1,2 , + + 0,0, 1,1 , 2,1 , 4,3 , 0,0, 5,1 , 3,1 , 0,1 , // rotate around x- 16 - 19 + 0,0, 1,2 , 4,1 , 3,3 , 0,0, 2,1 , 5,1 , 0,0 , + 0,0, 1,3 , 3,1 , 5,3 , 0,0, 4,1 , 2,1 , 0,3 , + 0,0, 1,0 , 5,1 , 2,3 , 0,0, 3,1 , 4,1 , 0,2 , + + 0,0, 3,2 , 1,2 , 4,2 , 0,0, 5,2 , 0,2 , 2,2 , // rotate around y- 20 - 23 + 0,0, 5,2 , 1,3 , 3,2 , 0,0, 2,2 , 0,1 , 4,2 , + 0,0, 2,2 , 1,0 , 5,2 , 0,0, 4,2 , 0,0 , 3,2 , + 0,0, 4,2 , 1,1 , 2,2 , 0,0, 3,2 , 0,3 , 5,2 }; u16 tile_index = facedir * 16 + dir_i; @@ -821,7 +795,7 @@ std::set splitToContentT(std::string str, const NodeDefManager *ndef) std::string buf; for (char c : str) { if (c == ',' || c == '\n') { - if (!buf.empty()) { + if (! buf.empty()) { dat.insert(ndef->getId(buf)); } buf.clear(); @@ -834,16 +808,24 @@ std::set splitToContentT(std::string str, const NodeDefManager *ndef) static void getTileInfo( // Input: - MeshMakeData *data, const v3s16 &p, const v3s16 &face_dir, + MeshMakeData *data, + const v3s16 &p, + const v3s16 &face_dir, // Output: - bool &makes_face, v3s16 &p_corrected, v3s16 &face_dir_corrected, - u16 *lights, u8 &waving, TileSpec &tile, bool xray, - std::set xraySet) + bool &makes_face, + v3s16 &p_corrected, + v3s16 &face_dir_corrected, + u16 *lights, + u8 &waving, + TileSpec &tile, + bool xray, + std::set xraySet + ) { VoxelManipulator &vmanip = data->m_vmanip; const NodeDefManager *ndef = data->m_client->ndef(); v3s16 blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE; - + const MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p); content_t c0 = n0.getContent(); @@ -856,8 +838,7 @@ static void getTileInfo( return; } - const MapNode &n1 = - vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir); + const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir); content_t c1 = n1.getContent(); if (xray && xraySet.find(c1) != xraySet.end()) @@ -870,7 +851,8 @@ static void getTileInfo( // This is hackish bool equivalent = false; - u8 mf = face_contents(c0, c1, &equivalent, ndef); + u8 mf = face_contents(c0, c1, + &equivalent, ndef); if (mf == 0) { makes_face = false; @@ -910,8 +892,7 @@ static void getTileInfo( v3s16 light_p = blockpos_nodes + p_corrected; for (u16 i = 0; i < 4; i++) - lights[i] = getSmoothLightSolid(light_p, face_dir_corrected, - vertex_dirs[i], data); + lights[i] = getSmoothLightSolid(light_p, face_dir_corrected, vertex_dirs[i], data); } } @@ -920,13 +901,19 @@ static void getTileInfo( translate_dir: unit vector with only one of x, y or z face_dir: unit vector with only one of x, y or z */ -static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos, - v3s16 translate_dir, const v3f &&translate_dir_f, const v3s16 &&face_dir, - std::vector &dest, bool xray, std::set xraySet) +static void updateFastFaceRow( + MeshMakeData *data, + const v3s16 &&startpos, + v3s16 translate_dir, + const v3f &&translate_dir_f, + const v3s16 &&face_dir, + std::vector &dest, + bool xray, + std::set xraySet) { static thread_local const bool waving_liquids = - g_settings->getBool("enable_shaders") && - g_settings->getBool("enable_waving_water"); + g_settings->getBool("enable_shaders") && + g_settings->getBool("enable_waving_water"); v3s16 p = startpos; @@ -940,7 +927,8 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos, TileSpec tile; // Get info of first tile - getTileInfo(data, p, face_dir, makes_face, p_corrected, face_dir_corrected, + getTileInfo(data, p, face_dir, + makes_face, p_corrected, face_dir_corrected, lights, waving, tile, xray, xraySet); // Unroll this variable which has a significant build cost @@ -959,17 +947,21 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos, if (j != MAP_BLOCKSIZE - 1) { p += translate_dir; - getTileInfo(data, p, face_dir, next_makes_face, next_p_corrected, - next_face_dir_corrected, next_lights, waving, - next_tile, xray, xraySet); - - if (next_makes_face == makes_face && - next_p_corrected == p_corrected + translate_dir && - next_face_dir_corrected == face_dir_corrected && - memcmp(next_lights, lights, sizeof(lights)) == 0 + getTileInfo(data, p, face_dir, + next_makes_face, next_p_corrected, + next_face_dir_corrected, next_lights, + waving, + next_tile, + xray, + xraySet); + + if (next_makes_face == makes_face + && next_p_corrected == p_corrected + translate_dir + && next_face_dir_corrected == face_dir_corrected + && memcmp(next_lights, lights, sizeof(lights)) == 0 // Don't apply fast faces to waving water. - && (waving != 3 || !waving_liquids) && - next_tile.isTileable(tile)) { + && (waving != 3 || !waving_liquids) + && next_tile.isTileable(tile)) { next_is_different = false; continuous_tiles_count++; } @@ -982,9 +974,8 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos, // Floating point conversion of the position vector v3f pf(p_corrected.X, p_corrected.Y, p_corrected.Z); // Center point of face (kind of) - v3f sp = pf - - ((f32)continuous_tiles_count * 0.5f - 0.5f) * - translate_dir_f; + v3f sp = pf - ((f32)continuous_tiles_count * 0.5f - 0.5f) + * translate_dir_f; v3f scale(1, 1, 1); if (translate_dir.X != 0) @@ -994,11 +985,9 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos, if (translate_dir.Z != 0) scale.Z = continuous_tiles_count; - makeFastFace(tile, lights[0], lights[1], lights[2], - lights[3], pf, sp, face_dir_corrected, - scale, dest); - g_profiler->avg("Meshgen: Tiles per face [#]", - continuous_tiles_count); + makeFastFace(tile, lights[0], lights[1], lights[2], lights[3], + pf, sp, face_dir_corrected, scale, dest); + g_profiler->avg("Meshgen: Tiles per face [#]", continuous_tiles_count); } continuous_tiles_count = 1; @@ -1013,35 +1002,50 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos, } } -static void updateAllFastFaceRows(MeshMakeData *data, std::vector &dest, - bool xray, std::set xraySet) +static void updateAllFastFaceRows(MeshMakeData *data, + std::vector &dest, bool xray, std::set xraySet) { /* Go through every y,z and get top(y+) faces in rows of x+ */ for (s16 y = 0; y < MAP_BLOCKSIZE; y++) - for (s16 z = 0; z < MAP_BLOCKSIZE; z++) - updateFastFaceRow(data, v3s16(0, y, z), v3s16(1, 0, 0), // dir - v3f(1, 0, 0), v3s16(0, 1, 0), // face dir - dest, xray, xraySet); + for (s16 z = 0; z < MAP_BLOCKSIZE; z++) + updateFastFaceRow(data, + v3s16(0, y, z), + v3s16(1, 0, 0), //dir + v3f (1, 0, 0), + v3s16(0, 1, 0), //face dir + dest, + xray, + xraySet); /* Go through every x,y and get right(x+) faces in rows of z+ */ for (s16 x = 0; x < MAP_BLOCKSIZE; x++) - for (s16 y = 0; y < MAP_BLOCKSIZE; y++) - updateFastFaceRow(data, v3s16(x, y, 0), v3s16(0, 0, 1), // dir - v3f(0, 0, 1), v3s16(1, 0, 0), // face dir - dest, xray, xraySet); + for (s16 y = 0; y < MAP_BLOCKSIZE; y++) + updateFastFaceRow(data, + v3s16(x, y, 0), + v3s16(0, 0, 1), //dir + v3f (0, 0, 1), + v3s16(1, 0, 0), //face dir + dest, + xray, + xraySet); /* Go through every y,z and get back(z+) faces in rows of x+ */ for (s16 z = 0; z < MAP_BLOCKSIZE; z++) - for (s16 y = 0; y < MAP_BLOCKSIZE; y++) - updateFastFaceRow(data, v3s16(0, y, z), v3s16(1, 0, 0), // dir - v3f(1, 0, 0), v3s16(0, 0, 1), // face dir - dest, xray, xraySet); + for (s16 y = 0; y < MAP_BLOCKSIZE; y++) + updateFastFaceRow(data, + v3s16(0, y, z), + v3s16(1, 0, 0), //dir + v3f (1, 0, 0), + v3s16(0, 0, 1), //face dir + dest, + xray, + xraySet); } static void applyTileColor(PreMeshBuffer &pmb) @@ -1051,9 +1055,10 @@ static void applyTileColor(PreMeshBuffer &pmb) return; for (video::S3DVertex &vertex : pmb.vertices) { video::SColor *c = &vertex.Color; - c->set(c->getAlpha(), c->getRed() * tc.getRed() / 255, - c->getGreen() * tc.getGreen() / 255, - c->getBlue() * tc.getBlue() / 255); + c->set(c->getAlpha(), + c->getRed() * tc.getRed() / 255, + c->getGreen() * tc.getGreen() / 255, + c->getBlue() * tc.getBlue() / 255); } } @@ -1061,11 +1066,13 @@ static void applyTileColor(PreMeshBuffer &pmb) MapBlockMesh */ -MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : - m_minimap_mapblock(NULL), m_tsrc(data->m_client->getTextureSource()), - m_shdrsrc(data->m_client->getShaderSource()), - m_animation_force_timer(0), // force initial animation - m_last_crack(-1), m_last_daynight_ratio((u32)-1) +MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): + m_minimap_mapblock(NULL), + m_tsrc(data->m_client->getTextureSource()), + m_shdrsrc(data->m_client->getShaderSource()), + m_animation_force_timer(0), // force initial animation + m_last_crack(-1), + m_last_daynight_ratio((u32) -1) { for (auto &m : m_mesh) m = new scene::SMesh(); @@ -1076,12 +1083,12 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : if (g_settings->getBool("enable_minimap")) { m_minimap_mapblock = new MinimapMapblock; m_minimap_mapblock->getMinimapNodes( - &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE); + &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE); } // 4-21ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated) // 24-155ms for MAP_BLOCKSIZE=32 (NOTE: probably outdated) - // TimeTaker timer1("MapBlockMesh()"); + //TimeTaker timer1("MapBlockMesh()"); std::vector fastfaces_new; fastfaces_new.reserve(512); @@ -1091,19 +1098,18 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : bool xray = g_settings->getBool("xray"); std::set xraySet; if (xray) - xraySet = splitToContentT( - g_settings->get("xray_nodes"), data->m_client->ndef()); - + xraySet = splitToContentT(g_settings->get("xray_nodes"), data->m_client->ndef()); + /* We are including the faces of the trailing edges of the block. This means that when something changes, the caller must also update the meshes of the blocks at the leading edges. NOTE: This is the slowest part of this method. - */ + */ { // 4-23ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated) - // TimeTaker timer2("updateAllFastFaceRows()"); + //TimeTaker timer2("updateAllFastFaceRows()"); updateAllFastFaceRows(data, fastfaces_new, xray, xraySet); } // End of slow part @@ -1117,13 +1123,13 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : { // avg 0ms (100ms spikes when loading textures the first time) // (NOTE: probably outdated) - // TimeTaker timer2("MeshCollector building"); + //TimeTaker timer2("MeshCollector building"); for (const FastFace &f : fastfaces_new) { static const u16 indices[] = {0, 1, 2, 2, 3, 0}; static const u16 indices_alternate[] = {0, 1, 3, 2, 3, 1}; - const u16 *indices_p = f.vertex_0_2_connected ? indices - : indices_alternate; + const u16 *indices_p = + f.vertex_0_2_connected ? indices : indices_alternate; collector.append(f.tile, f.vertices, 4, indices_p, 6); } } @@ -1146,7 +1152,8 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : */ for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { - for (u32 i = 0; i < collector.prebuffers[layer].size(); i++) { + for(u32 i = 0; i < collector.prebuffers[layer].size(); i++) + { PreMeshBuffer &p = collector.prebuffers[layer][i]; applyTileColor(p); @@ -1156,10 +1163,9 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : if (p.layer.material_flags & MATERIAL_FLAG_CRACK) { // Find the texture name plus ^[crack:N: std::ostringstream os(std::ios::binary); - os << m_tsrc->getTextureName(p.layer.texture_id) - << "^[crack"; + os << m_tsrc->getTextureName(p.layer.texture_id) << "^[crack"; if (p.layer.material_flags & MATERIAL_FLAG_CRACK_OVERLAY) - os << "o"; // use ^[cracko + os << "o"; // use ^[cracko u8 tiles = p.layer.scale; if (tiles > 1) os << ":" << (u32)tiles; @@ -1168,27 +1174,24 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : std::pair(layer, i), os.str())); // Replace tile texture with the cracked one p.layer.texture = m_tsrc->getTextureForMesh( - os.str() + "0", &p.layer.texture_id); + os.str() + "0", + &p.layer.texture_id); } // - Texture animation if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) { // Add to MapBlockMesh in order to animate these tiles m_animation_tiles[std::pair(layer, i)] = p.layer; m_animation_frames[std::pair(layer, i)] = 0; - if (g_settings->getBool("desynchronize_mapblock_texture_" - "animation")) { + if (g_settings->getBool( + "desynchronize_mapblock_texture_animation")) { // Get starting position from noise - m_animation_frame_offsets[std::pair( - layer, i)] = - 100000 * - (2.0 + noise3d(data->m_blockpos.X, - data->m_blockpos.Y, - data->m_blockpos.Z, - 0)); + m_animation_frame_offsets[std::pair(layer, i)] = + 100000 * (2.0 + noise3d( + data->m_blockpos.X, data->m_blockpos.Y, + data->m_blockpos.Z, 0)); } else { // Play all synchronized - m_animation_frame_offsets[std::pair( - layer, i)] = 0; + m_animation_frame_offsets[std::pair(layer, i)] = 0; } // Replace tile texture with the first animation frame p.layer.texture = (*p.layer.frames)[0].texture; @@ -1203,14 +1206,10 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : for (u32 j = 0; j < vertex_count; j++) { video::SColor *vc = &p.vertices[j].Color; video::SColor copy = *vc; - if (vc->getAlpha() == 0) // No sunlight - no need - // to animate - final_color_blend(vc, copy, - sunlight); // Finalize - // color + if (vc->getAlpha() == 0) // No sunlight - no need to animate + final_color_blend(vc, copy, sunlight); // Finalize color else // Record color to animate - m_daynight_diffs[std::pair( - layer, i)][j] = copy; + m_daynight_diffs[std::pair(layer, i)][j] = copy; // The sunlight ratio has been stored, // delete alpha (for the final rendering). @@ -1227,9 +1226,8 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : material.setTexture(0, p.layer.texture); if (m_enable_shaders) { - material.MaterialType = - m_shdrsrc->getShaderInfo(p.layer.shader_id) - .material; + material.MaterialType = m_shdrsrc->getShaderInfo( + p.layer.shader_id).material; p.layer.applyMaterialOptionsWithShaders(material); if (p.layer.normal_texture) material.setTexture(1, p.layer.normal_texture); @@ -1247,10 +1245,9 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : buf->Material = material; buf->Vertices.reallocate(p.vertices.size()); buf->Indices.reallocate(p.indices.size()); - for (const video::S3DVertex &v : p.vertices) - buf->Vertices.push_back(video::S3DVertexTangents( - v.Pos, v.Color, v.TCoords)); - for (u16 i : p.indices) + for (const video::S3DVertex &v: p.vertices) + buf->Vertices.push_back(video::S3DVertexTangents(v.Pos, v.Color, v.TCoords)); + for (u16 i: p.indices) buf->Indices.push_back(i); buf->recalculateBoundingBox(); mesh->addMeshBuffer(buf); @@ -1259,7 +1256,7 @@ 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()); + &p.indices[0], p.indices.size()); mesh->addMeshBuffer(buf); buf->drop(); } @@ -1270,14 +1267,11 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : */ m_camera_offset = camera_offset; translateMesh(m_mesh[layer], - intToFloat(data->m_blockpos * MAP_BLOCKSIZE - - camera_offset, - BS)); + intToFloat(data->m_blockpos * MAP_BLOCKSIZE - camera_offset, BS)); if (m_use_tangent_vertices) { - scene::IMeshManipulator *meshmanip = - RenderingEngine::get_scene_manager() - ->getMeshManipulator(); + scene::IMeshManipulator* meshmanip = + RenderingEngine::get_scene_manager()->getMeshManipulator(); meshmanip->recalculateTangents(m_mesh[layer], true, false, false); } @@ -1295,11 +1289,13 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) : } } - // std::cout<<"added "<getMeshBufferCount(); i++) { scene::IMeshBuffer *buf = m->getMeshBuffer(i); - RenderingEngine::get_video_driver()->removeHardwareBuffer( - buf); + RenderingEngine::get_video_driver()->removeHardwareBuffer(buf); } m->drop(); m = NULL; @@ -1317,7 +1312,8 @@ MapBlockMesh::~MapBlockMesh() delete m_minimap_mapblock; } -bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_ratio) +bool MapBlockMesh::animate(bool faraway, float time, int crack, + u32 daynight_ratio) { if (!m_has_animation) { m_animation_force_timer = 100000; @@ -1329,17 +1325,16 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat // Cracks if (crack != m_last_crack) { for (auto &crack_material : m_crack_materials) { - scene::IMeshBuffer *buf = - m_mesh[crack_material.first.first]->getMeshBuffer( - crack_material.first.second); + scene::IMeshBuffer *buf = m_mesh[crack_material.first.first]-> + getMeshBuffer(crack_material.first.second); std::string basename = crack_material.second; // Create new texture name from original std::ostringstream os; os << basename << crack; u32 new_texture_id = 0; - video::ITexture *new_texture = m_tsrc->getTextureForMesh( - os.str(), &new_texture_id); + video::ITexture *new_texture = + m_tsrc->getTextureForMesh(os.str(), &new_texture_id); buf->getMaterial().setTexture(0, new_texture); // If the current material is also animated, @@ -1362,25 +1357,23 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat const TileLayer &tile = animation_tile.second; // Figure out current frame int frameoffset = m_animation_frame_offsets[animation_tile.first]; - int frame = (int)(time * 1000 / tile.animation_frame_length_ms + - frameoffset) % - tile.animation_frame_count; + int frame = (int)(time * 1000 / tile.animation_frame_length_ms + + frameoffset) % tile.animation_frame_count; // If frame doesn't change, skip if (frame == m_animation_frames[animation_tile.first]) continue; m_animation_frames[animation_tile.first] = frame; - scene::IMeshBuffer *buf = - m_mesh[animation_tile.first.first]->getMeshBuffer( - animation_tile.first.second); + scene::IMeshBuffer *buf = m_mesh[animation_tile.first.first]-> + getMeshBuffer(animation_tile.first.second); const FrameSpec &animation_frame = (*tile.frames)[frame]; buf->getMaterial().setTexture(0, animation_frame.texture); if (m_enable_shaders) { if (animation_frame.normal_texture) - buf->getMaterial().setTexture( - 1, animation_frame.normal_texture); + buf->getMaterial().setTexture(1, + animation_frame.normal_texture); buf->getMaterial().setTexture(2, animation_frame.flags_texture); } } @@ -1395,11 +1388,9 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat get_sunlight_color(&day_color, daynight_ratio); for (auto &daynight_diff : m_daynight_diffs) { - scene::IMeshBuffer *buf = - m_mesh[daynight_diff.first.first]->getMeshBuffer( - daynight_diff.first.second); - video::S3DVertex *vertices = - (video::S3DVertex *)buf->getVertices(); + scene::IMeshBuffer *buf = m_mesh[daynight_diff.first.first]-> + getMeshBuffer(daynight_diff.first.second); + video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); for (const auto &j : daynight_diff.second) final_color_blend(&(vertices[j.first].Color), j.second, day_color); @@ -1415,7 +1406,7 @@ void MapBlockMesh::updateCameraOffset(v3s16 camera_offset) if (camera_offset != m_camera_offset) { for (scene::IMesh *layer : m_mesh) { translateMesh(layer, - intToFloat(m_camera_offset - camera_offset, BS)); + intToFloat(m_camera_offset - camera_offset, BS)); if (m_enable_vbo) layer->setDirty(); } diff --git a/src/client/mapblock_mesh.h b/src/client/mapblock_mesh.h index dd08433a1..6af23a656 100644 --- a/src/client/mapblock_mesh.h +++ b/src/client/mapblock_mesh.h @@ -32,21 +32,23 @@ class IShaderSource; Mesh making stuff */ + class MapBlock; struct MinimapMapblock; struct MeshMakeData { VoxelManipulator m_vmanip; - v3s16 m_blockpos = v3s16(-1337, -1337, -1337); - v3s16 m_crack_pos_relative = v3s16(-1337, -1337, -1337); + v3s16 m_blockpos = v3s16(-1337,-1337,-1337); + v3s16 m_crack_pos_relative = v3s16(-1337,-1337,-1337); bool m_smooth_lighting = false; Client *m_client; bool m_use_shaders; bool m_use_tangent_vertices; - MeshMakeData(Client *client, bool use_shaders, bool use_tangent_vertices = false); + MeshMakeData(Client *client, bool use_shaders, + bool use_tangent_vertices = false); /* Copy block data manually (to allow optimizations by the caller) @@ -102,9 +104,15 @@ class MapBlockMesh // Returns true if anything has been changed. bool animate(bool faraway, float time, int crack, u32 daynight_ratio); - scene::IMesh *getMesh() { return m_mesh[0]; } + scene::IMesh *getMesh() + { + return m_mesh[0]; + } - scene::IMesh *getMesh(u8 layer) { return m_mesh[layer]; } + scene::IMesh *getMesh(u8 layer) + { + return m_mesh[layer]; + } MinimapMapblock *moveMinimapMapblock() { @@ -113,11 +121,14 @@ class MapBlockMesh return p; } - bool isAnimationForced() const { return m_animation_force_timer == 0; } + bool isAnimationForced() const + { + return m_animation_force_timer == 0; + } void decreaseAnimationForceTimer() { - if (m_animation_force_timer > 0) + if(m_animation_force_timer > 0) m_animation_force_timer--; } @@ -156,7 +167,7 @@ class MapBlockMesh // For each mesh and mesh buffer, stores pre-baked colors // of sunlit vertices // Keys are pairs of (mesh index, buffer index in the mesh) - std::map, std::map> m_daynight_diffs; + std::map, std::map > m_daynight_diffs; // Camera offset info -> do we have to translate the mesh? v3s16 m_camera_offset; @@ -178,10 +189,9 @@ video::SColor encode_light(u16 light, u8 emissive_light); // Compute light at node u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef); -u16 getFaceLight( - MapNode n, MapNode n2, const v3s16 &face_dir, const NodeDefManager *ndef); -u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, - MeshMakeData *data); +u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir, + const NodeDefManager *ndef); +u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data); u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data); /*! @@ -197,7 +207,8 @@ void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio); * \param light first 8 bits are day light, second 8 bits are * night light */ -void final_color_blend(video::SColor *result, u16 light, u32 daynight_ratio); +void final_color_blend(video::SColor *result, + u16 light, u32 daynight_ratio); /*! * Gives the final SColor shown on screen. @@ -206,14 +217,12 @@ void final_color_blend(video::SColor *result, u16 light, u32 daynight_ratio); * \param data the half-baked vertex color * \param dayLight color of the sunlight */ -void final_color_blend(video::SColor *result, const video::SColor &data, - const video::SColorf &dayLight); +void final_color_blend(video::SColor *result, + const video::SColor &data, const video::SColorf &dayLight); // Retrieves the TileSpec of a face of a node // Adds MATERIAL_FLAG_CRACK if the node is cracked // TileSpec should be passed as reference due to the underlying TileFrame and its vector // TileFrame vector copy cost very much to client -void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, - TileSpec &tile); -void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, - TileSpec &tile); +void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile); +void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile); diff --git a/src/client/mesh.cpp b/src/client/mesh.cpp index 312d4e7f6..e1ec22068 100644 --- a/src/client/mesh.cpp +++ b/src/client/mesh.cpp @@ -35,11 +35,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MY_ETLM_READ_ONLY video::ETLM_READ_ONLY #endif -inline static void applyShadeFactor(video::SColor &color, float factor) +inline static void applyShadeFactor(video::SColor& color, float factor) { - color.setRed(core::clamp(core::round32(color.getRed() * factor), 0, 255)); - color.setGreen(core::clamp(core::round32(color.getGreen() * factor), 0, 255)); - color.setBlue(core::clamp(core::round32(color.getBlue() * factor), 0, 255)); + color.setRed(core::clamp(core::round32(color.getRed()*factor), 0, 255)); + color.setGreen(core::clamp(core::round32(color.getGreen()*factor), 0, 255)); + color.setBlue(core::clamp(core::round32(color.getBlue()*factor), 0, 255)); } void applyFacesShading(video::SColor &color, const v3f &normal) @@ -62,53 +62,54 @@ void applyFacesShading(video::SColor &color, const v3f &normal) applyShadeFactor(color, 0.670820f * x2 + 1.000000f * y2 + 0.836660f * z2); } -scene::IAnimatedMesh *createCubeMesh(v3f scale) +scene::IAnimatedMesh* createCubeMesh(v3f scale) { - video::SColor c(255, 255, 255, 255); - video::S3DVertex vertices[24] = { - // Up - video::S3DVertex(-0.5, +0.5, -0.5, 0, 1, 0, c, 0, 1), - video::S3DVertex(-0.5, +0.5, +0.5, 0, 1, 0, c, 0, 0), - video::S3DVertex(+0.5, +0.5, +0.5, 0, 1, 0, c, 1, 0), - video::S3DVertex(+0.5, +0.5, -0.5, 0, 1, 0, c, 1, 1), - // Down - video::S3DVertex(-0.5, -0.5, -0.5, 0, -1, 0, c, 0, 0), - video::S3DVertex(+0.5, -0.5, -0.5, 0, -1, 0, c, 1, 0), - video::S3DVertex(+0.5, -0.5, +0.5, 0, -1, 0, c, 1, 1), - video::S3DVertex(-0.5, -0.5, +0.5, 0, -1, 0, c, 0, 1), - // Right - video::S3DVertex(+0.5, -0.5, -0.5, 1, 0, 0, c, 0, 1), - video::S3DVertex(+0.5, +0.5, -0.5, 1, 0, 0, c, 0, 0), - video::S3DVertex(+0.5, +0.5, +0.5, 1, 0, 0, c, 1, 0), - video::S3DVertex(+0.5, -0.5, +0.5, 1, 0, 0, c, 1, 1), - // Left - video::S3DVertex(-0.5, -0.5, -0.5, -1, 0, 0, c, 1, 1), - video::S3DVertex(-0.5, -0.5, +0.5, -1, 0, 0, c, 0, 1), - video::S3DVertex(-0.5, +0.5, +0.5, -1, 0, 0, c, 0, 0), - video::S3DVertex(-0.5, +0.5, -0.5, -1, 0, 0, c, 1, 0), - // Back - video::S3DVertex(-0.5, -0.5, +0.5, 0, 0, 1, c, 1, 1), - video::S3DVertex(+0.5, -0.5, +0.5, 0, 0, 1, c, 0, 1), - video::S3DVertex(+0.5, +0.5, +0.5, 0, 0, 1, c, 0, 0), - video::S3DVertex(-0.5, +0.5, +0.5, 0, 0, 1, c, 1, 0), - // Front - video::S3DVertex(-0.5, -0.5, -0.5, 0, 0, -1, c, 0, 1), - video::S3DVertex(-0.5, +0.5, -0.5, 0, 0, -1, c, 0, 0), - video::S3DVertex(+0.5, +0.5, -0.5, 0, 0, -1, c, 1, 0), - video::S3DVertex(+0.5, -0.5, -0.5, 0, 0, -1, c, 1, 1), + video::SColor c(255,255,255,255); + video::S3DVertex vertices[24] = + { + // Up + video::S3DVertex(-0.5,+0.5,-0.5, 0,1,0, c, 0,1), + video::S3DVertex(-0.5,+0.5,+0.5, 0,1,0, c, 0,0), + video::S3DVertex(+0.5,+0.5,+0.5, 0,1,0, c, 1,0), + video::S3DVertex(+0.5,+0.5,-0.5, 0,1,0, c, 1,1), + // Down + video::S3DVertex(-0.5,-0.5,-0.5, 0,-1,0, c, 0,0), + video::S3DVertex(+0.5,-0.5,-0.5, 0,-1,0, c, 1,0), + video::S3DVertex(+0.5,-0.5,+0.5, 0,-1,0, c, 1,1), + video::S3DVertex(-0.5,-0.5,+0.5, 0,-1,0, c, 0,1), + // Right + video::S3DVertex(+0.5,-0.5,-0.5, 1,0,0, c, 0,1), + video::S3DVertex(+0.5,+0.5,-0.5, 1,0,0, c, 0,0), + video::S3DVertex(+0.5,+0.5,+0.5, 1,0,0, c, 1,0), + video::S3DVertex(+0.5,-0.5,+0.5, 1,0,0, c, 1,1), + // Left + video::S3DVertex(-0.5,-0.5,-0.5, -1,0,0, c, 1,1), + video::S3DVertex(-0.5,-0.5,+0.5, -1,0,0, c, 0,1), + video::S3DVertex(-0.5,+0.5,+0.5, -1,0,0, c, 0,0), + video::S3DVertex(-0.5,+0.5,-0.5, -1,0,0, c, 1,0), + // Back + video::S3DVertex(-0.5,-0.5,+0.5, 0,0,1, c, 1,1), + video::S3DVertex(+0.5,-0.5,+0.5, 0,0,1, c, 0,1), + video::S3DVertex(+0.5,+0.5,+0.5, 0,0,1, c, 0,0), + video::S3DVertex(-0.5,+0.5,+0.5, 0,0,1, c, 1,0), + // Front + video::S3DVertex(-0.5,-0.5,-0.5, 0,0,-1, c, 0,1), + video::S3DVertex(-0.5,+0.5,-0.5, 0,0,-1, c, 0,0), + video::S3DVertex(+0.5,+0.5,-0.5, 0,0,-1, c, 1,0), + video::S3DVertex(+0.5,-0.5,-0.5, 0,0,-1, c, 1,1), }; - u16 indices[6] = {0, 1, 2, 2, 3, 0}; + u16 indices[6] = {0,1,2,2,3,0}; scene::SMesh *mesh = new scene::SMesh(); - for (u32 i = 0; i < 6; ++i) { + for (u32 i=0; i<6; ++i) + { scene::IMeshBuffer *buf = new scene::SMeshBuffer(); buf->append(vertices + 4 * i, 4, indices, 6); // Set default material buf->getMaterial().setFlag(video::EMF_LIGHTING, false); buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); - buf->getMaterial().MaterialType = - video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; // Add mesh buffer to mesh mesh->addMeshBuffer(buf); buf->drop(); @@ -116,7 +117,7 @@ scene::IAnimatedMesh *createCubeMesh(v3f scale) scene::SAnimatedMesh *anim_mesh = new scene::SAnimatedMesh(mesh); mesh->drop(); - scaleMesh(anim_mesh, scale); // also recalculates bounding box + scaleMesh(anim_mesh, scale); // also recalculates bounding box return anim_mesh; } @@ -180,9 +181,9 @@ void setMeshBufferColor(scene::IMeshBuffer *buf, const video::SColor &color) { const u32 stride = getVertexPitchFromType(buf->getVertexType()); u32 vertex_count = buf->getVertexCount(); - u8 *vertices = (u8 *)buf->getVertices(); + u8 *vertices = (u8 *) buf->getVertices(); for (u32 i = 0; i < vertex_count; i++) - ((video::S3DVertex *)(vertices + i * stride))->Color = color; + ((video::S3DVertex *) (vertices + i * stride))->Color = color; } void setAnimatedMeshColor(scene::IAnimatedMeshSceneNode *node, const video::SColor &color) @@ -202,7 +203,8 @@ void setMeshColor(scene::IMesh *mesh, const video::SColor &color) setMeshBufferColor(mesh->getMeshBuffer(j), color); } -template static void applyToMesh(scene::IMesh *mesh, const F &fn) +template +static void applyToMesh(scene::IMesh *mesh, const F &fn) { u16 mc = mesh->getMeshBufferCount(); for (u16 j = 0; j < mc; j++) { @@ -219,9 +221,9 @@ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolo { const u32 stride = getVertexPitchFromType(buf->getVertexType()); u32 vertex_count = buf->getVertexCount(); - u8 *vertices = (u8 *)buf->getVertices(); + u8 *vertices = (u8 *) buf->getVertices(); for (u32 i = 0; i < vertex_count; i++) { - video::S3DVertex *vertex = (video::S3DVertex *)(vertices + i * stride); + video::S3DVertex *vertex = (video::S3DVertex *) (vertices + i * stride); video::SColor *vc = &(vertex->Color); // Reset color *vc = *buffercolor; @@ -230,12 +232,14 @@ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolo } } -void setMeshColorByNormalXYZ(scene::IMesh *mesh, const video::SColor &colorX, - const video::SColor &colorY, const video::SColor &colorZ) +void setMeshColorByNormalXYZ(scene::IMesh *mesh, + const video::SColor &colorX, + const video::SColor &colorY, + const video::SColor &colorZ) { if (!mesh) return; - auto colorizator = [=](video::S3DVertex *vertex) { + auto colorizator = [=] (video::S3DVertex *vertex) { f32 x = fabs(vertex->Normal.X); f32 y = fabs(vertex->Normal.Y); f32 z = fabs(vertex->Normal.Z); @@ -249,12 +253,12 @@ void setMeshColorByNormalXYZ(scene::IMesh *mesh, const video::SColor &colorX, applyToMesh(mesh, colorizator); } -void setMeshColorByNormal( - scene::IMesh *mesh, const v3f &normal, const video::SColor &color) +void setMeshColorByNormal(scene::IMesh *mesh, const v3f &normal, + const video::SColor &color) { if (!mesh) return; - auto colorizator = [normal, color](video::S3DVertex *vertex) { + auto colorizator = [normal, color] (video::S3DVertex *vertex) { if (vertex->Normal == normal) vertex->Color = color; }; @@ -267,7 +271,7 @@ static void rotateMesh(scene::IMesh *mesh, float degrees) degrees *= M_PI / 180.0f; float c = std::cos(degrees); float s = std::sin(degrees); - auto rotator = [c, s](video::S3DVertex *vertex) { + auto rotator = [c, s] (video::S3DVertex *vertex) { float u = vertex->Pos.*U; float v = vertex->Pos.*V; vertex->Pos.*U = c * u - s * v; @@ -296,39 +300,23 @@ void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir) int axisdir = facedir >> 2; facedir &= 0x03; switch (facedir) { - case 1: - rotateMeshXZby(mesh, -90); - break; - case 2: - rotateMeshXZby(mesh, 180); - break; - case 3: - rotateMeshXZby(mesh, 90); - break; + case 1: rotateMeshXZby(mesh, -90); break; + case 2: rotateMeshXZby(mesh, 180); break; + case 3: rotateMeshXZby(mesh, 90); break; } switch (axisdir) { - case 1: - rotateMeshYZby(mesh, 90); - break; // z+ - case 2: - rotateMeshYZby(mesh, -90); - break; // z- - case 3: - rotateMeshXYby(mesh, -90); - break; // x+ - case 4: - rotateMeshXYby(mesh, 90); - break; // x- - case 5: - rotateMeshXYby(mesh, -180); - break; + case 1: rotateMeshYZby(mesh, 90); break; // z+ + case 2: rotateMeshYZby(mesh, -90); break; // z- + case 3: rotateMeshXYby(mesh, -90); break; // x+ + case 4: rotateMeshXYby(mesh, 90); break; // x- + case 5: rotateMeshXYby(mesh, -180); break; } } void recalculateBoundingBox(scene::IMesh *src_mesh) { aabb3f bbox; - bbox.reset(0, 0, 0); + bbox.reset(0,0,0); for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) { scene::IMeshBuffer *buf = src_mesh->getMeshBuffer(j); buf->recalculateBoundingBox(); @@ -360,35 +348,35 @@ bool checkMeshNormals(scene::IMesh *mesh) return true; } -scene::IMeshBuffer *cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) +scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) { switch (mesh_buffer->getVertexType()) { case video::EVT_STANDARD: { - video::S3DVertex *v = (video::S3DVertex *)mesh_buffer->getVertices(); + video::S3DVertex *v = (video::S3DVertex *) mesh_buffer->getVertices(); u16 *indices = mesh_buffer->getIndices(); scene::SMeshBuffer *cloned_buffer = new scene::SMeshBuffer(); cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices, - mesh_buffer->getIndexCount()); + mesh_buffer->getIndexCount()); return cloned_buffer; } case video::EVT_2TCOORDS: { video::S3DVertex2TCoords *v = - (video::S3DVertex2TCoords *)mesh_buffer->getVertices(); + (video::S3DVertex2TCoords *) mesh_buffer->getVertices(); u16 *indices = mesh_buffer->getIndices(); scene::SMeshBufferLightMap *cloned_buffer = - new scene::SMeshBufferLightMap(); + new scene::SMeshBufferLightMap(); cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices, - mesh_buffer->getIndexCount()); + mesh_buffer->getIndexCount()); return cloned_buffer; } case video::EVT_TANGENTS: { video::S3DVertexTangents *v = - (video::S3DVertexTangents *)mesh_buffer->getVertices(); + (video::S3DVertexTangents *) mesh_buffer->getVertices(); u16 *indices = mesh_buffer->getIndices(); scene::SMeshBufferTangents *cloned_buffer = - new scene::SMeshBufferTangents(); + new scene::SMeshBufferTangents(); cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices, - mesh_buffer->getIndexCount()); + mesh_buffer->getIndexCount()); return cloned_buffer; } } @@ -397,24 +385,26 @@ scene::IMeshBuffer *cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) return NULL; } -scene::SMesh *cloneMesh(scene::IMesh *src_mesh) +scene::SMesh* cloneMesh(scene::IMesh *src_mesh) { - scene::SMesh *dst_mesh = new scene::SMesh(); + scene::SMesh* dst_mesh = new scene::SMesh(); for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) { - scene::IMeshBuffer *temp_buf = - cloneMeshBuffer(src_mesh->getMeshBuffer(j)); + scene::IMeshBuffer *temp_buf = cloneMeshBuffer( + src_mesh->getMeshBuffer(j)); dst_mesh->addMeshBuffer(temp_buf); temp_buf->drop(); + } return dst_mesh; } -scene::IMesh *convertNodeboxesToMesh( - const std::vector &boxes, const f32 *uv_coords, float expand) +scene::IMesh* convertNodeboxesToMesh(const std::vector &boxes, + const f32 *uv_coords, float expand) { - scene::SMesh *dst_mesh = new scene::SMesh(); + scene::SMesh* dst_mesh = new scene::SMesh(); - for (u16 j = 0; j < 6; j++) { + for (u16 j = 0; j < 6; j++) + { scene::IMeshBuffer *buf = new scene::SMeshBuffer(); buf->getMaterial().setFlag(video::EMF_LIGHTING, false); buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); @@ -422,7 +412,7 @@ scene::IMesh *convertNodeboxesToMesh( buf->drop(); } - video::SColor c(255, 255, 255, 255); + video::SColor c(255,255,255,255); for (aabb3f box : boxes) { box.repair(); @@ -443,36 +433,18 @@ scene::IMesh *convertNodeboxesToMesh( f32 tz2 = (box.MaxEdge.Z / BS) + 0.5; f32 txc_default[24] = { - // up - tx1, - 1 - tz2, - tx2, - 1 - tz1, - // down - tx1, - tz1, - tx2, - tz2, - // right - tz1, - 1 - ty2, - tz2, - 1 - ty1, - // left - 1 - tz2, - 1 - ty2, - 1 - tz1, - 1 - ty1, - // back - 1 - tx2, - 1 - ty2, - 1 - tx1, - 1 - ty1, - // front - tx1, - 1 - ty2, - tx2, - 1 - ty1, + // up + tx1, 1 - tz2, tx2, 1 - tz1, + // down + tx1, tz1, tx2, tz2, + // right + tz1, 1 - ty2, tz2, 1 - ty1, + // left + 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1, + // back + 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1, + // front + tx1, 1 - ty2, tx2, 1 - ty1, }; // use default texture UV mapping if not provided @@ -481,66 +453,44 @@ scene::IMesh *convertNodeboxesToMesh( v3f min = box.MinEdge; v3f max = box.MaxEdge; - video::S3DVertex vertices[24] = { - // up - video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, c, txc[0], - txc[1]), - video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, c, txc[2], - txc[1]), - video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, c, txc[2], - txc[3]), - video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, c, txc[0], - txc[3]), - // down - video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, c, txc[4], - txc[5]), - video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, c, txc[6], - txc[5]), - video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, c, txc[6], - txc[7]), - video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, c, txc[4], - txc[7]), - // right - video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, c, txc[8], - txc[9]), - video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, c, txc[10], - txc[9]), - video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, c, txc[10], - txc[11]), - video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, c, txc[8], - txc[11]), - // left - video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, c, - txc[12], txc[13]), - video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, c, - txc[14], txc[13]), - video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, c, - txc[14], txc[15]), - video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, c, - txc[12], txc[15]), - // back - video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, c, txc[16], - txc[17]), - video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, c, txc[18], - txc[17]), - video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, c, txc[18], - txc[19]), - video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, c, txc[16], - txc[19]), - // front - video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, c, - txc[20], txc[21]), - video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, c, - txc[22], txc[21]), - video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, c, - txc[22], txc[23]), - video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, c, - txc[20], txc[23]), + video::S3DVertex vertices[24] = + { + // up + video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c, txc[0],txc[1]), + video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c, txc[2],txc[1]), + video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c, txc[2],txc[3]), + video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c, txc[0],txc[3]), + // down + video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c, txc[4],txc[5]), + video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c, txc[6],txc[5]), + video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c, txc[6],txc[7]), + video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c, txc[4],txc[7]), + // right + video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c, txc[ 8],txc[9]), + video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c, txc[10],txc[9]), + video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c, txc[10],txc[11]), + video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c, txc[ 8],txc[11]), + // left + video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c, txc[12],txc[13]), + video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c, txc[14],txc[13]), + video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c, txc[14],txc[15]), + video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c, txc[12],txc[15]), + // back + video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c, txc[16],txc[17]), + video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c, txc[18],txc[17]), + video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c, txc[18],txc[19]), + video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c, txc[16],txc[19]), + // front + video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c, txc[20],txc[21]), + video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c, txc[22],txc[21]), + video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c, txc[22],txc[23]), + video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c, txc[20],txc[23]), }; - u16 indices[] = {0, 1, 2, 2, 3, 0}; + u16 indices[] = {0,1,2,2,3,0}; - for (u16 j = 0; j < 24; j += 4) { + for(u16 j = 0; j < 24; j += 4) + { scene::IMeshBuffer *buf = dst_mesh->getMeshBuffer(j / 4); buf->append(vertices + j, 4, indices, 6); } @@ -573,21 +523,28 @@ float FindVertexScore(vcache *v) const float ValenceBoostPower = 0.5f; const float MaxSizeVertexCache = 32.0f; - if (v->NumActiveTris == 0) { + if (v->NumActiveTris == 0) + { // No tri needs this vertex! return -1.0f; } float Score = 0.0f; int CachePosition = v->cachepos; - if (CachePosition < 0) { + if (CachePosition < 0) + { // Vertex is not in FIFO cache - no score. - } else { - if (CachePosition < 3) { + } + else + { + if (CachePosition < 3) + { // This vertex was used in the last triangle, // so it has a fixed score. Score = LastTriScore; - } else { + } + else + { // Points for being high in the cache. const float Scaler = 1.0f / (MaxSizeVertexCache - 3); Score = 1.0f - (CachePosition - 3) * Scaler; @@ -597,7 +554,8 @@ float FindVertexScore(vcache *v) // Bonus points for having a low number of tris still to // use the vert, so we get rid of lone verts quickly. - float ValenceBoost = powf(v->NumActiveTris, -ValenceBoostPower); + float ValenceBoost = powf(v->NumActiveTris, + -ValenceBoostPower); Score += ValenceBoostScale * ValenceBoost; return Score; @@ -611,7 +569,7 @@ class f_lru { public: - f_lru(vcache *v, tcache *t) : vc(v), tc(t) + f_lru(vcache *v, tcache *t): vc(v), tc(t) { for (int &i : cache) { i = -1; @@ -624,10 +582,13 @@ class f_lru bool found = false; // Mark existing pos as empty - for (u16 i = 0; i < cachesize; i++) { - if (cache[i] == vert) { + for (u16 i = 0; i < cachesize; i++) + { + if (cache[i] == vert) + { // Move everything down - for (u16 j = i; j; j--) { + for (u16 j = i; j; j--) + { cache[j] = cache[j - 1]; } @@ -636,12 +597,14 @@ class f_lru } } - if (!found) { - if (cache[cachesize - 1] != -1) - vc[cache[cachesize - 1]].cachepos = -1; + if (!found) + { + if (cache[cachesize-1] != -1) + vc[cache[cachesize-1]].cachepos = -1; // Move everything down - for (u16 i = cachesize - 1; i; i--) { + for (u16 i = cachesize - 1; i; i--) + { cache[i] = cache[i - 1]; } } @@ -651,9 +614,11 @@ class f_lru u32 highest = 0; float hiscore = 0; - if (updatetris) { + if (updatetris) + { // Update cache positions - for (u16 i = 0; i < cachesize; i++) { + for (u16 i = 0; i < cachesize; i++) + { if (cache[i] == -1) break; @@ -667,14 +632,17 @@ class f_lru break; const u16 trisize = vc[i].tris.size(); - for (u16 t = 0; t < trisize; t++) { + for (u16 t = 0; t < trisize; t++) + { tcache *tri = &tc[vc[i].tris[t]]; - tri->score = vc[tri->ind[0]].score + - vc[tri->ind[1]].score + - vc[tri->ind[2]].score; + tri->score = + vc[tri->ind[0]].score + + vc[tri->ind[1]].score + + vc[tri->ind[2]].score; - if (tri->score > hiscore) { + if (tri->score > hiscore) + { hiscore = tri->score; highest = vc[i].tris[t]; } @@ -698,7 +666,7 @@ Vertex cache optimization according to the Forsyth paper: The function is thread-safe (read: you can optimize several meshes in different threads) \param mesh Source mesh for the operation. */ -scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh) +scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh) { if (!mesh) return 0; @@ -708,12 +676,13 @@ scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh) const u32 mbcount = mesh->getMeshBufferCount(); - for (u32 b = 0; b < mbcount; ++b) { + for (u32 b = 0; b < mbcount; ++b) + { const scene::IMeshBuffer *mb = mesh->getMeshBuffer(b); - if (mb->getIndexType() != video::EIT_16BIT) { - // os::Printer::log("Cannot optimize a mesh with 32bit indices", - // ELL_ERROR); + if (mb->getIndexType() != video::EIT_16BIT) + { + //os::Printer::log("Cannot optimize a mesh with 32bit indices", ELL_ERROR); newmesh->drop(); return 0; } @@ -729,26 +698,29 @@ scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh) f_lru lru(vc, tc); // init - for (u16 i = 0; i < vcount; i++) { + for (u16 i = 0; i < vcount; i++) + { vc[i].score = 0; vc[i].cachepos = -1; vc[i].NumActiveTris = 0; } // First pass: count how many times a vert is used - for (u32 i = 0; i < icount; i += 3) { + for (u32 i = 0; i < icount; i += 3) + { vc[ind[i]].NumActiveTris++; vc[ind[i + 1]].NumActiveTris++; vc[ind[i + 2]].NumActiveTris++; - const u32 tri_ind = i / 3; + const u32 tri_ind = i/3; tc[tri_ind].ind[0] = ind[i]; tc[tri_ind].ind[1] = ind[i + 1]; tc[tri_ind].ind[2] = ind[i + 2]; } // Second pass: list of each triangle - for (u32 i = 0; i < tcount; i++) { + for (u32 i = 0; i < tcount; i++) + { vc[tc[i].ind[0]].tris.push_back(i); vc[tc[i].ind[1]].tris.push_back(i); vc[tc[i].ind[2]].tris.push_back(i); @@ -757,308 +729,358 @@ scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh) } // Give initial scores - for (u16 i = 0; i < vcount; i++) { + for (u16 i = 0; i < vcount; i++) + { vc[i].score = FindVertexScore(&vc[i]); } - for (u32 i = 0; i < tcount; i++) { - tc[i].score = vc[tc[i].ind[0]].score + vc[tc[i].ind[1]].score + - vc[tc[i].ind[2]].score; + for (u32 i = 0; i < tcount; i++) + { + tc[i].score = + vc[tc[i].ind[0]].score + + vc[tc[i].ind[1]].score + + vc[tc[i].ind[2]].score; } - switch (mb->getVertexType()) { - case video::EVT_STANDARD: { - video::S3DVertex *v = (video::S3DVertex *)mb->getVertices(); - - scene::SMeshBuffer *buf = new scene::SMeshBuffer(); - buf->Material = mb->getMaterial(); - - buf->Vertices.reallocate(vcount); - buf->Indices.reallocate(icount); - - core::map - sind; // search index for fast operation - typedef core::map::Node snode; - - // Main algorithm - u32 highest = 0; - u32 drawcalls = 0; - for (;;) { - if (tc[highest].drawn) { - bool found = false; - float hiscore = 0; - for (u32 t = 0; t < tcount; t++) { - if (!tc[t].drawn) { - if (tc[t].score > hiscore) { - highest = t; - hiscore = tc[t].score; - found = true; + switch(mb->getVertexType()) + { + case video::EVT_STANDARD: + { + video::S3DVertex *v = (video::S3DVertex *) mb->getVertices(); + + scene::SMeshBuffer *buf = new scene::SMeshBuffer(); + buf->Material = mb->getMaterial(); + + buf->Vertices.reallocate(vcount); + buf->Indices.reallocate(icount); + + core::map sind; // search index for fast operation + typedef core::map::Node snode; + + // Main algorithm + u32 highest = 0; + u32 drawcalls = 0; + for (;;) + { + if (tc[highest].drawn) + { + bool found = false; + float hiscore = 0; + for (u32 t = 0; t < tcount; t++) + { + if (!tc[t].drawn) + { + if (tc[t].score > hiscore) + { + highest = t; + hiscore = tc[t].score; + found = true; + } } } + if (!found) + break; } - if (!found) - break; - } - // Output the best triangle - u16 newind = buf->Vertices.size(); + // Output the best triangle + u16 newind = buf->Vertices.size(); - snode *s = sind.find(v[tc[highest].ind[0]]); + snode *s = sind.find(v[tc[highest].ind[0]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[0]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[0]], newind); - newind++; - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[0]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[0]], newind); + newind++; + } + else + { + buf->Indices.push_back(s->getValue()); + } - s = sind.find(v[tc[highest].ind[1]]); + s = sind.find(v[tc[highest].ind[1]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[1]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[1]], newind); - newind++; - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[1]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[1]], newind); + newind++; + } + else + { + buf->Indices.push_back(s->getValue()); + } - s = sind.find(v[tc[highest].ind[2]]); + s = sind.find(v[tc[highest].ind[2]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[2]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[2]], newind); - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[2]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[2]], newind); + } + else + { + buf->Indices.push_back(s->getValue()); + } - vc[tc[highest].ind[0]].NumActiveTris--; - vc[tc[highest].ind[1]].NumActiveTris--; - vc[tc[highest].ind[2]].NumActiveTris--; + vc[tc[highest].ind[0]].NumActiveTris--; + vc[tc[highest].ind[1]].NumActiveTris--; + vc[tc[highest].ind[2]].NumActiveTris--; - tc[highest].drawn = true; + tc[highest].drawn = true; - for (u16 j : tc[highest].ind) { - vcache *vert = &vc[j]; - for (u16 t = 0; t < vert->tris.size(); t++) { - if (highest == vert->tris[t]) { - vert->tris.erase(t); - break; + for (u16 j : tc[highest].ind) { + vcache *vert = &vc[j]; + for (u16 t = 0; t < vert->tris.size(); t++) + { + if (highest == vert->tris[t]) + { + vert->tris.erase(t); + break; + } } } + + lru.add(tc[highest].ind[0]); + lru.add(tc[highest].ind[1]); + highest = lru.add(tc[highest].ind[2], true); + drawcalls++; } - lru.add(tc[highest].ind[0]); - lru.add(tc[highest].ind[1]); - highest = lru.add(tc[highest].ind[2], true); - drawcalls++; + buf->setBoundingBox(mb->getBoundingBox()); + newmesh->addMeshBuffer(buf); + buf->drop(); } - - buf->setBoundingBox(mb->getBoundingBox()); - newmesh->addMeshBuffer(buf); - buf->drop(); - } break; - case video::EVT_2TCOORDS: { - video::S3DVertex2TCoords *v = - (video::S3DVertex2TCoords *)mb->getVertices(); - - scene::SMeshBufferLightMap *buf = - new scene::SMeshBufferLightMap(); - buf->Material = mb->getMaterial(); - - buf->Vertices.reallocate(vcount); - buf->Indices.reallocate(icount); - - core::map - sind; // search index for fast operation - typedef core::map::Node - snode; - - // Main algorithm - u32 highest = 0; - u32 drawcalls = 0; - for (;;) { - if (tc[highest].drawn) { - bool found = false; - float hiscore = 0; - for (u32 t = 0; t < tcount; t++) { - if (!tc[t].drawn) { - if (tc[t].score > hiscore) { - highest = t; - hiscore = tc[t].score; - found = true; + break; + case video::EVT_2TCOORDS: + { + video::S3DVertex2TCoords *v = (video::S3DVertex2TCoords *) mb->getVertices(); + + scene::SMeshBufferLightMap *buf = new scene::SMeshBufferLightMap(); + buf->Material = mb->getMaterial(); + + buf->Vertices.reallocate(vcount); + buf->Indices.reallocate(icount); + + core::map sind; // search index for fast operation + typedef core::map::Node snode; + + // Main algorithm + u32 highest = 0; + u32 drawcalls = 0; + for (;;) + { + if (tc[highest].drawn) + { + bool found = false; + float hiscore = 0; + for (u32 t = 0; t < tcount; t++) + { + if (!tc[t].drawn) + { + if (tc[t].score > hiscore) + { + highest = t; + hiscore = tc[t].score; + found = true; + } } } + if (!found) + break; } - if (!found) - break; - } - // Output the best triangle - u16 newind = buf->Vertices.size(); + // Output the best triangle + u16 newind = buf->Vertices.size(); - snode *s = sind.find(v[tc[highest].ind[0]]); + snode *s = sind.find(v[tc[highest].ind[0]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[0]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[0]], newind); - newind++; - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[0]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[0]], newind); + newind++; + } + else + { + buf->Indices.push_back(s->getValue()); + } - s = sind.find(v[tc[highest].ind[1]]); + s = sind.find(v[tc[highest].ind[1]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[1]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[1]], newind); - newind++; - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[1]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[1]], newind); + newind++; + } + else + { + buf->Indices.push_back(s->getValue()); + } - s = sind.find(v[tc[highest].ind[2]]); + s = sind.find(v[tc[highest].ind[2]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[2]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[2]], newind); - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[2]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[2]], newind); + } + else + { + buf->Indices.push_back(s->getValue()); + } - vc[tc[highest].ind[0]].NumActiveTris--; - vc[tc[highest].ind[1]].NumActiveTris--; - vc[tc[highest].ind[2]].NumActiveTris--; + vc[tc[highest].ind[0]].NumActiveTris--; + vc[tc[highest].ind[1]].NumActiveTris--; + vc[tc[highest].ind[2]].NumActiveTris--; - tc[highest].drawn = true; + tc[highest].drawn = true; - for (u16 j : tc[highest].ind) { - vcache *vert = &vc[j]; - for (u16 t = 0; t < vert->tris.size(); t++) { - if (highest == vert->tris[t]) { - vert->tris.erase(t); - break; + for (u16 j : tc[highest].ind) { + vcache *vert = &vc[j]; + for (u16 t = 0; t < vert->tris.size(); t++) + { + if (highest == vert->tris[t]) + { + vert->tris.erase(t); + break; + } } } + + lru.add(tc[highest].ind[0]); + lru.add(tc[highest].ind[1]); + highest = lru.add(tc[highest].ind[2]); + drawcalls++; } - lru.add(tc[highest].ind[0]); - lru.add(tc[highest].ind[1]); - highest = lru.add(tc[highest].ind[2]); - drawcalls++; - } + buf->setBoundingBox(mb->getBoundingBox()); + newmesh->addMeshBuffer(buf); + buf->drop(); - buf->setBoundingBox(mb->getBoundingBox()); - newmesh->addMeshBuffer(buf); - buf->drop(); - - } break; - case video::EVT_TANGENTS: { - video::S3DVertexTangents *v = - (video::S3DVertexTangents *)mb->getVertices(); - - scene::SMeshBufferTangents *buf = - new scene::SMeshBufferTangents(); - buf->Material = mb->getMaterial(); - - buf->Vertices.reallocate(vcount); - buf->Indices.reallocate(icount); - - core::map - sind; // search index for fast operation - typedef core::map::Node - snode; - - // Main algorithm - u32 highest = 0; - u32 drawcalls = 0; - for (;;) { - if (tc[highest].drawn) { - bool found = false; - float hiscore = 0; - for (u32 t = 0; t < tcount; t++) { - if (!tc[t].drawn) { - if (tc[t].score > hiscore) { - highest = t; - hiscore = tc[t].score; - found = true; + } + break; + case video::EVT_TANGENTS: + { + video::S3DVertexTangents *v = (video::S3DVertexTangents *) mb->getVertices(); + + scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents(); + buf->Material = mb->getMaterial(); + + buf->Vertices.reallocate(vcount); + buf->Indices.reallocate(icount); + + core::map sind; // search index for fast operation + typedef core::map::Node snode; + + // Main algorithm + u32 highest = 0; + u32 drawcalls = 0; + for (;;) + { + if (tc[highest].drawn) + { + bool found = false; + float hiscore = 0; + for (u32 t = 0; t < tcount; t++) + { + if (!tc[t].drawn) + { + if (tc[t].score > hiscore) + { + highest = t; + hiscore = tc[t].score; + found = true; + } } } + if (!found) + break; } - if (!found) - break; - } - // Output the best triangle - u16 newind = buf->Vertices.size(); + // Output the best triangle + u16 newind = buf->Vertices.size(); - snode *s = sind.find(v[tc[highest].ind[0]]); + snode *s = sind.find(v[tc[highest].ind[0]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[0]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[0]], newind); - newind++; - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[0]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[0]], newind); + newind++; + } + else + { + buf->Indices.push_back(s->getValue()); + } - s = sind.find(v[tc[highest].ind[1]]); + s = sind.find(v[tc[highest].ind[1]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[1]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[1]], newind); - newind++; - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[1]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[1]], newind); + newind++; + } + else + { + buf->Indices.push_back(s->getValue()); + } - s = sind.find(v[tc[highest].ind[2]]); + s = sind.find(v[tc[highest].ind[2]]); - if (!s) { - buf->Vertices.push_back(v[tc[highest].ind[2]]); - buf->Indices.push_back(newind); - sind.insert(v[tc[highest].ind[2]], newind); - } else { - buf->Indices.push_back(s->getValue()); - } + if (!s) + { + buf->Vertices.push_back(v[tc[highest].ind[2]]); + buf->Indices.push_back(newind); + sind.insert(v[tc[highest].ind[2]], newind); + } + else + { + buf->Indices.push_back(s->getValue()); + } - vc[tc[highest].ind[0]].NumActiveTris--; - vc[tc[highest].ind[1]].NumActiveTris--; - vc[tc[highest].ind[2]].NumActiveTris--; + vc[tc[highest].ind[0]].NumActiveTris--; + vc[tc[highest].ind[1]].NumActiveTris--; + vc[tc[highest].ind[2]].NumActiveTris--; - tc[highest].drawn = true; + tc[highest].drawn = true; - for (u16 j : tc[highest].ind) { - vcache *vert = &vc[j]; - for (u16 t = 0; t < vert->tris.size(); t++) { - if (highest == vert->tris[t]) { - vert->tris.erase(t); - break; + for (u16 j : tc[highest].ind) { + vcache *vert = &vc[j]; + for (u16 t = 0; t < vert->tris.size(); t++) + { + if (highest == vert->tris[t]) + { + vert->tris.erase(t); + break; + } } } + + lru.add(tc[highest].ind[0]); + lru.add(tc[highest].ind[1]); + highest = lru.add(tc[highest].ind[2]); + drawcalls++; } - lru.add(tc[highest].ind[0]); - lru.add(tc[highest].ind[1]); - highest = lru.add(tc[highest].ind[2]); - drawcalls++; + buf->setBoundingBox(mb->getBoundingBox()); + newmesh->addMeshBuffer(buf); + buf->drop(); } - - buf->setBoundingBox(mb->getBoundingBox()); - newmesh->addMeshBuffer(buf); - buf->drop(); - } break; + break; } - delete[] vc; - delete[] tc; + delete [] vc; + delete [] tc; } // for each meshbuffer diff --git a/src/client/mesh.h b/src/client/mesh.h index 1698026e8..103c61e45 100644 --- a/src/client/mesh.h +++ b/src/client/mesh.h @@ -35,7 +35,7 @@ void applyFacesShading(video::SColor &color, const v3f &normal); The resulting mesh has 6 materials (up, down, right, left, back, front) which must be defined by the caller. */ -scene::IAnimatedMesh *createCubeMesh(v3f scale); +scene::IAnimatedMesh* createCubeMesh(v3f scale); /* Multiplies each vertex coordinate by the specified scaling factors @@ -61,8 +61,7 @@ void setMeshColor(scene::IMesh *mesh, const video::SColor &color); /* Set a constant color for an animated mesh */ -void setAnimatedMeshColor( - scene::IAnimatedMeshSceneNode *node, const video::SColor &color); +void setAnimatedMeshColor(scene::IAnimatedMeshSceneNode *node, const video::SColor &color); /*! * Overwrites the color of a mesh buffer. @@ -76,11 +75,13 @@ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolo the normal vector, and choose one of colorX, colorY or colorZ accordingly. */ -void setMeshColorByNormalXYZ(scene::IMesh *mesh, const video::SColor &colorX, - const video::SColor &colorY, const video::SColor &colorZ); +void setMeshColorByNormalXYZ(scene::IMesh *mesh, + const video::SColor &colorX, + const video::SColor &colorY, + const video::SColor &colorZ); -void setMeshColorByNormal( - scene::IMesh *mesh, const v3f &normal, const video::SColor &color); +void setMeshColorByNormal(scene::IMesh *mesh, const v3f &normal, + const video::SColor &color); /* Rotate the mesh by 6d facedir value. @@ -91,20 +92,20 @@ void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir); /* Rotate the mesh around the axis and given angle in degrees. */ -void rotateMeshXYby(scene::IMesh *mesh, f64 degrees); -void rotateMeshXZby(scene::IMesh *mesh, f64 degrees); -void rotateMeshYZby(scene::IMesh *mesh, f64 degrees); +void rotateMeshXYby (scene::IMesh *mesh, f64 degrees); +void rotateMeshXZby (scene::IMesh *mesh, f64 degrees); +void rotateMeshYZby (scene::IMesh *mesh, f64 degrees); /* * Clone the mesh buffer. * The returned pointer should be dropped. */ -scene::IMeshBuffer *cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer); +scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer); /* Clone the mesh. */ -scene::SMesh *cloneMesh(scene::IMesh *src_mesh); +scene::SMesh* cloneMesh(scene::IMesh *src_mesh); /* Convert nodeboxes to mesh. Each tile goes into a different buffer. @@ -112,7 +113,7 @@ scene::SMesh *cloneMesh(scene::IMesh *src_mesh); uv_coords[24] - table of texture uv coords for each cuboid face expand - factor by which cuboids will be resized */ -scene::IMesh *convertNodeboxesToMesh(const std::vector &boxes, +scene::IMesh* convertNodeboxesToMesh(const std::vector &boxes, const f32 *uv_coords = NULL, float expand = 0); /* @@ -131,4 +132,4 @@ bool checkMeshNormals(scene::IMesh *mesh); http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html Ported from irrlicht 1.8 */ -scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh); +scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh); diff --git a/src/client/mesh_generator_thread.cpp b/src/client/mesh_generator_thread.cpp index 69d61d5e6..53b980eeb 100644 --- a/src/client/mesh_generator_thread.cpp +++ b/src/client/mesh_generator_thread.cpp @@ -48,13 +48,13 @@ QueuedMeshUpdate::~QueuedMeshUpdate() MeshUpdateQueue */ -MeshUpdateQueue::MeshUpdateQueue(Client *client) : m_client(client) +MeshUpdateQueue::MeshUpdateQueue(Client *client): + m_client(client) { m_cache_enable_shaders = g_settings->getBool("enable_shaders"); - m_cache_use_tangent_vertices = - m_cache_enable_shaders && - (g_settings->getBool("enable_bumpmapping") || - g_settings->getBool("enable_parallax_occlusion")); + m_cache_use_tangent_vertices = m_cache_enable_shaders && ( + g_settings->getBool("enable_bumpmapping") || + g_settings->getBool("enable_parallax_occlusion")); m_cache_smooth_lighting = g_settings->getBool("smooth_lighting"); m_meshgen_block_cache_size = g_settings->getS32("meshgen_block_cache_size"); } @@ -82,23 +82,22 @@ void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool Cache the block data (force-update the center block, don't update the neighbors but get them if they aren't already cached) */ - std::vector cached_blocks; + std::vector cached_blocks; size_t cache_hit_counter = 0; - cached_blocks.reserve(3 * 3 * 3); + 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); - } + 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); + } g_profiler->avg("MeshUpdateQueue: MapBlocks from cache [%]", 100.0f * cache_hit_counter / cached_blocks.size()); @@ -116,7 +115,7 @@ void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool if (q->p == p) { // NOTE: We are not adding a new position to the queue, thus // refcount_from_queue stays the same. - if (ack_block_to_server) + if(ack_block_to_server) q->ack_block_to_server = true; q->crack_level = m_client->getCrackLevel(); q->crack_pos = m_client->getCrackPos(); @@ -147,10 +146,10 @@ QueuedMeshUpdate *MeshUpdateQueue::pop() MutexAutoLock lock(m_mutex); bool must_be_urgent = !m_urgents.empty(); - for (std::vector::iterator i = m_queue.begin(); + for (std::vector::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { QueuedMeshUpdate *q = *i; - if (must_be_urgent && m_urgents.count(q->p) == 0) + if(must_be_urgent && m_urgents.count(q->p) == 0) continue; m_queue.erase(i); m_urgents.erase(q->p); @@ -160,11 +159,12 @@ QueuedMeshUpdate *MeshUpdateQueue::pop() return NULL; } -CachedMapBlockData *MeshUpdateQueue::cacheBlock( - Map *map, v3s16 p, UpdateMode mode, size_t *cache_hit_counter) +CachedMapBlockData* MeshUpdateQueue::cacheBlock(Map *map, v3s16 p, UpdateMode mode, + size_t *cache_hit_counter) { CachedMapBlockData *cached_block = nullptr; - std::map::iterator it = m_cache.find(p); + std::map::iterator it = + m_cache.find(p); if (it != m_cache.end()) { cached_block = it->second; @@ -185,11 +185,10 @@ CachedMapBlockData *MeshUpdateQueue::cacheBlock( MapBlock *b = map->getBlockNoCreateNoEx(p); if (b) { if (!cached_block->data) - cached_block->data = new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE * - MAP_BLOCKSIZE]; + cached_block->data = + new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE]; memcpy(cached_block->data, b->getData(), - MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * - sizeof(MapNode)); + MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * sizeof(MapNode)); } else { delete[] cached_block->data; cached_block->data = nullptr; @@ -197,9 +196,9 @@ CachedMapBlockData *MeshUpdateQueue::cacheBlock( return cached_block; } -CachedMapBlockData *MeshUpdateQueue::getCachedBlock(const v3s16 &p) +CachedMapBlockData* MeshUpdateQueue::getCachedBlock(const v3s16 &p) { - std::map::iterator it = m_cache.find(p); + std::map::iterator it = m_cache.find(p); if (it != m_cache.end()) { return it->second; } @@ -208,8 +207,8 @@ CachedMapBlockData *MeshUpdateQueue::getCachedBlock(const v3s16 &p) void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q) { - MeshMakeData *data = new MeshMakeData( - m_client, m_cache_enable_shaders, m_cache_use_tangent_vertices); + MeshMakeData *data = new MeshMakeData(m_client, m_cache_enable_shaders, + m_cache_use_tangent_vertices); q->data = data; data->fillBlockDataBegin(q->p); @@ -219,18 +218,17 @@ void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q) // 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++) { - v3s16 p = q->p + dp; - CachedMapBlockData *cached_block = getCachedBlock(p); - if (cached_block) { - cached_block->refcount_from_queue--; - cached_block->last_used_timestamp = t_now; - if (cached_block->data) - data->fillBlockData( - dp, cached_block->data); - } - } + for (dp.Y = -1; dp.Y <= 1; dp.Y++) + for (dp.Z = -1; dp.Z <= 1; dp.Z++) { + v3s16 p = q->p + dp; + CachedMapBlockData *cached_block = getCachedBlock(p); + if (cached_block) { + cached_block->refcount_from_queue--; + cached_block->last_used_timestamp = t_now; + if (cached_block->data) + data->fillBlockData(dp, cached_block->data); + } + } data->setCrack(q->crack_level, q->crack_pos); data->setSmoothLighting(m_cache_smooth_lighting); @@ -239,7 +237,7 @@ void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q) void MeshUpdateQueue::cleanupCache() { const int mapblock_kB = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * - sizeof(MapNode) / 1000; + sizeof(MapNode) / 1000; g_profiler->avg("MeshUpdateQueue MapBlock cache size kB", mapblock_kB * m_cache.size()); @@ -247,20 +245,16 @@ void MeshUpdateQueue::cleanupCache() // anything get older than cache_seconds_max or deleted before 2 seconds. const int cache_seconds_max = 10; const int cache_soft_max_size = m_meshgen_block_cache_size * 1000 / mapblock_kB; - int cache_seconds = MYMAX(2, - cache_seconds_max - - m_cache.size() / - (cache_soft_max_size / - cache_seconds_max)); + int cache_seconds = MYMAX(2, cache_seconds_max - + m_cache.size() / (cache_soft_max_size / cache_seconds_max)); int t_now = time(0); - for (std::map::iterator it = m_cache.begin(); - it != m_cache.end();) { + for (std::map::iterator it = m_cache.begin(); + it != m_cache.end(); ) { CachedMapBlockData *cached_block = it->second; if (cached_block->refcount_from_queue == 0 && - cached_block->last_used_timestamp < - t_now - cache_seconds) { + cached_block->last_used_timestamp < t_now - cache_seconds) { m_cache.erase(it++); delete cached_block; } else { @@ -273,15 +267,16 @@ void MeshUpdateQueue::cleanupCache() MeshUpdateThread */ -MeshUpdateThread::MeshUpdateThread(Client *client) : - UpdateThread("Mesh"), m_queue_in(client) +MeshUpdateThread::MeshUpdateThread(Client *client): + UpdateThread("Mesh"), + m_queue_in(client) { m_generation_interval = g_settings->getU16("mesh_generation_interval"); m_generation_interval = rangelim(m_generation_interval, 0, 50); } -void MeshUpdateThread::updateBlock( - Map *map, v3s16 p, bool ack_block_to_server, bool urgent) +void MeshUpdateThread::updateBlock(Map *map, v3s16 p, bool ack_block_to_server, + bool urgent) { // Allow the MeshUpdateQueue to do whatever it wants m_queue_in.addBlock(map, p, ack_block_to_server, urgent); diff --git a/src/client/minimap.cpp b/src/client/minimap.cpp index e321aaae5..68770ec19 100644 --- a/src/client/minimap.cpp +++ b/src/client/minimap.cpp @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapblock.h" #include "client/renderingengine.h" + //// //// MinimapUpdateThread //// @@ -57,7 +58,7 @@ bool MinimapUpdateThread::pushBlockUpdate(v3s16 pos, MinimapMapblock *data) // Add the block QueuedMinimapUpdate q; - q.pos = pos; + q.pos = pos; q.data = data; m_update_queue.push_back(q); @@ -83,6 +84,7 @@ void MinimapUpdateThread::enqueueBlock(v3s16 pos, MinimapMapblock *data) deferUpdate(); } + void MinimapUpdateThread::doUpdate() { QueuedMinimapUpdate update; @@ -90,9 +92,8 @@ void MinimapUpdateThread::doUpdate() while (popBlockUpdate(&update)) { if (update.data) { // Swap two values in the map using single lookup - std::pair::iterator, bool> - result = m_blocks_cache.insert(std::make_pair( - update.pos, update.data)); + std::pair::iterator, bool> + result = m_blocks_cache.insert(std::make_pair(update.pos, update.data)); if (!result.second) { delete result.first->second; result.first->second = update.data; @@ -120,60 +121,51 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height) v3s16 blockpos_min = getNodeBlockPos(pos_min); v3s16 blockpos_max = getNodeBlockPos(pos_max); - // clear the map +// clear the map for (int z = 0; z < size; z++) - for (int x = 0; x < size; x++) { - MinimapPixel &mmpixel = data->minimap_scan[x + z * size]; - mmpixel.air_count = 0; - mmpixel.height = 0; - mmpixel.n = MapNode(CONTENT_AIR); - } + for (int x = 0; x < size; x++) { + MinimapPixel &mmpixel = data->minimap_scan[x + z * size]; + mmpixel.air_count = 0; + mmpixel.height = 0; + mmpixel.n = MapNode(CONTENT_AIR); + } - // draw the map +// draw the map v3s16 blockpos; for (blockpos.Z = blockpos_min.Z; blockpos.Z <= blockpos_max.Z; ++blockpos.Z) - for (blockpos.Y = blockpos_min.Y; blockpos.Y <= blockpos_max.Y; - ++blockpos.Y) - for (blockpos.X = blockpos_min.X; blockpos.X <= blockpos_max.X; - ++blockpos.X) { - std::map::const_iterator - pblock = m_blocks_cache.find(blockpos); - if (pblock == m_blocks_cache.end()) - continue; - const MinimapMapblock &block = *pblock->second; - - v3s16 block_node_min(blockpos * MAP_BLOCKSIZE); - v3s16 block_node_max(block_node_min + MAP_BLOCKSIZE - 1); - // clip - v3s16 range_min = componentwise_max( - block_node_min, pos_min); - v3s16 range_max = componentwise_min( - block_node_max, pos_max); - - v3s16 pos; - pos.Y = range_min.Y; - for (pos.Z = range_min.Z; pos.Z <= range_max.Z; ++pos.Z) - for (pos.X = range_min.X; pos.X <= range_max.X; - ++pos.X) { - v3s16 inblock_pos = pos - block_node_min; - const MinimapPixel &in_pixel = - block.data[inblock_pos.Z * MAP_BLOCKSIZE + - inblock_pos.X]; - - v3s16 inmap_pos = pos - pos_min; - MinimapPixel &out_pixel = - data->minimap_scan[inmap_pos.X + - inmap_pos.Z * size]; - - out_pixel.air_count += in_pixel.air_count; - if (in_pixel.n.param0 != CONTENT_AIR) { - out_pixel.n = in_pixel.n; - out_pixel.height = - inmap_pos.Y + - in_pixel.height; - } - } + for (blockpos.Y = blockpos_min.Y; blockpos.Y <= blockpos_max.Y; ++blockpos.Y) + for (blockpos.X = blockpos_min.X; blockpos.X <= blockpos_max.X; ++blockpos.X) { + std::map::const_iterator pblock = + m_blocks_cache.find(blockpos); + if (pblock == m_blocks_cache.end()) + continue; + const MinimapMapblock &block = *pblock->second; + + v3s16 block_node_min(blockpos * MAP_BLOCKSIZE); + v3s16 block_node_max(block_node_min + MAP_BLOCKSIZE - 1); + // clip + v3s16 range_min = componentwise_max(block_node_min, pos_min); + v3s16 range_max = componentwise_min(block_node_max, pos_max); + + v3s16 pos; + pos.Y = range_min.Y; + for (pos.Z = range_min.Z; pos.Z <= range_max.Z; ++pos.Z) + for (pos.X = range_min.X; pos.X <= range_max.X; ++pos.X) { + v3s16 inblock_pos = pos - block_node_min; + const MinimapPixel &in_pixel = + block.data[inblock_pos.Z * MAP_BLOCKSIZE + inblock_pos.X]; + + v3s16 inmap_pos = pos - pos_min; + MinimapPixel &out_pixel = + data->minimap_scan[inmap_pos.X + inmap_pos.Z * size]; + + out_pixel.air_count += in_pixel.air_count; + if (in_pixel.n.param0 != CONTENT_AIR) { + out_pixel.n = in_pixel.n; + out_pixel.height = inmap_pos.Y + in_pixel.height; } + } + } } //// @@ -182,40 +174,40 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height) Minimap::Minimap(Client *client) { - this->client = client; - this->driver = RenderingEngine::get_video_driver(); - this->m_tsrc = client->getTextureSource(); + this->client = client; + this->driver = RenderingEngine::get_video_driver(); + this->m_tsrc = client->getTextureSource(); this->m_shdrsrc = client->getShaderSource(); - this->m_ndef = client->getNodeDefManager(); + this->m_ndef = client->getNodeDefManager(); m_angle = 0.f; // Initialize static settings m_enable_shaders = g_settings->getBool("enable_shaders"); m_surface_mode_scan_height = - g_settings->getBool("minimap_double_scan_height") ? 256 : 128; + g_settings->getBool("minimap_double_scan_height") ? 256 : 128; // Initialize minimap data data = new MinimapData; - data->mode = MINIMAP_MODE_OFF; - data->is_radar = false; - data->map_invalidated = true; - data->texture = NULL; + data->mode = MINIMAP_MODE_OFF; + data->is_radar = false; + data->map_invalidated = true; + data->texture = NULL; data->heightmap_texture = NULL; data->minimap_shape_round = g_settings->getBool("minimap_shape_round"); // Get round minimap textures data->minimap_mask_round = driver->createImage( - m_tsrc->getTexture("minimap_mask_round.png"), - core::position2d(0, 0), - core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); + m_tsrc->getTexture("minimap_mask_round.png"), + core::position2d(0, 0), + core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); data->minimap_overlay_round = m_tsrc->getTexture("minimap_overlay_round.png"); // Get square minimap textures data->minimap_mask_square = driver->createImage( - m_tsrc->getTexture("minimap_mask_square.png"), - core::position2d(0, 0), - core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); + m_tsrc->getTexture("minimap_mask_square.png"), + core::position2d(0, 0), + core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); data->minimap_overlay_square = m_tsrc->getTexture("minimap_overlay_square.png"); // Create player marker texture @@ -290,21 +282,25 @@ MinimapShape Minimap::getMinimapShape() void Minimap::setMinimapMode(MinimapMode mode) { - static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = {{false, 0, 0}, - {false, m_surface_mode_scan_height, 256}, - {false, m_surface_mode_scan_height, 128}, - {false, m_surface_mode_scan_height, 64}, {true, 32, 128}, - {true, 32, 64}, {true, 32, 32}}; + static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = { + {false, 0, 0}, + {false, m_surface_mode_scan_height, 256}, + {false, m_surface_mode_scan_height, 128}, + {false, m_surface_mode_scan_height, 64}, + {true, 32, 128}, + {true, 32, 64}, + {true, 32, 32} + }; if (mode >= MINIMAP_MODE_COUNT) return; MutexAutoLock lock(m_mutex); - data->is_radar = modedefs[mode].is_radar; + data->is_radar = modedefs[mode].is_radar; data->scan_height = modedefs[mode].scan_height; - data->map_size = modedefs[mode].map_size; - data->mode = mode; + data->map_size = modedefs[mode].map_size; + data->mode = mode; m_minimap_update_thread->deferUpdate(); } @@ -336,55 +332,47 @@ void Minimap::blitMinimapPixelsToImageRadar(video::IImage *map_image) { video::SColor c(240, 0, 0, 0); for (s16 x = 0; x < data->map_size; x++) - for (s16 z = 0; z < data->map_size; z++) { - MinimapPixel *mmpixel = - &data->minimap_scan[x + z * data->map_size]; - - if (mmpixel->air_count > 0) - c.setGreen(core::clamp( - core::round32(32 + - mmpixel->air_count * 8), - 0, 255)); - else - c.setGreen(0); - - map_image->setPixel(x, data->map_size - z - 1, c); - } + for (s16 z = 0; z < data->map_size; z++) { + MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size]; + + if (mmpixel->air_count > 0) + c.setGreen(core::clamp(core::round32(32 + mmpixel->air_count * 8), 0, 255)); + else + c.setGreen(0); + + map_image->setPixel(x, data->map_size - z - 1, c); + } } void Minimap::blitMinimapPixelsToImageSurface( - video::IImage *map_image, video::IImage *heightmap_image) + video::IImage *map_image, video::IImage *heightmap_image) { // This variable creation/destruction has a 1% cost on rendering minimap video::SColor tilecolor; for (s16 x = 0; x < data->map_size; x++) - for (s16 z = 0; z < data->map_size; z++) { - MinimapPixel *mmpixel = - &data->minimap_scan[x + z * data->map_size]; - - const ContentFeatures &f = m_ndef->get(mmpixel->n); - const TileDef *tile = &f.tiledef[0]; - - // Color of the 0th tile (mostly this is the topmost) - if (tile->has_color) - tilecolor = tile->color; - else - mmpixel->n.getColor(f, &tilecolor); - - tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() / - 255); - tilecolor.setGreen(tilecolor.getGreen() * - f.minimap_color.getGreen() / 255); - tilecolor.setBlue(tilecolor.getBlue() * - f.minimap_color.getBlue() / 255); - tilecolor.setAlpha(240); - - map_image->setPixel(x, data->map_size - z - 1, tilecolor); - - u32 h = mmpixel->height; - heightmap_image->setPixel(x, data->map_size - z - 1, - video::SColor(255, h, h, h)); - } + for (s16 z = 0; z < data->map_size; z++) { + MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size]; + + const ContentFeatures &f = m_ndef->get(mmpixel->n); + const TileDef *tile = &f.tiledef[0]; + + // Color of the 0th tile (mostly this is the topmost) + if(tile->has_color) + tilecolor = tile->color; + else + mmpixel->n.getColor(f, &tilecolor); + + tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() / 255); + tilecolor.setGreen(tilecolor.getGreen() * f.minimap_color.getGreen() / 255); + tilecolor.setBlue(tilecolor.getBlue() * f.minimap_color.getBlue() / 255); + tilecolor.setAlpha(240); + + map_image->setPixel(x, data->map_size - z - 1, tilecolor); + + u32 h = mmpixel->height; + heightmap_image->setPixel(x,data->map_size - z - 1, + video::SColor(255, h, h, h)); + } } video::ITexture *Minimap::getMinimapTexture() @@ -395,10 +383,10 @@ video::ITexture *Minimap::getMinimapTexture() // create minimap and heightmap images in memory core::dimension2d dim(data->map_size, data->map_size); - video::IImage *map_image = driver->createImage(video::ECF_A8R8G8B8, dim); + video::IImage *map_image = driver->createImage(video::ECF_A8R8G8B8, dim); video::IImage *heightmap_image = driver->createImage(video::ECF_A8R8G8B8, dim); - video::IImage *minimap_image = driver->createImage(video::ECF_A8R8G8B8, - core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); + video::IImage *minimap_image = driver->createImage(video::ECF_A8R8G8B8, + core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); // Blit MinimapPixels to images if (data->is_radar) @@ -409,19 +397,16 @@ video::ITexture *Minimap::getMinimapTexture() map_image->copyToScaling(minimap_image); map_image->drop(); - video::IImage *minimap_mask = data->minimap_shape_round - ? data->minimap_mask_round - : data->minimap_mask_square; + video::IImage *minimap_mask = data->minimap_shape_round ? + data->minimap_mask_round : data->minimap_mask_square; if (minimap_mask) { for (s16 y = 0; y < MINIMAP_MAX_SY; y++) - for (s16 x = 0; x < MINIMAP_MAX_SX; x++) { - const video::SColor &mask_col = - minimap_mask->getPixel(x, y); - if (!mask_col.getAlpha()) - minimap_image->setPixel( - x, y, video::SColor(0, 0, 0, 0)); - } + for (s16 x = 0; x < MINIMAP_MAX_SX; x++) { + const video::SColor &mask_col = minimap_mask->getPixel(x, y); + if (!mask_col.getAlpha()) + minimap_image->setPixel(x, y, video::SColor(0,0,0,0)); + } } if (data->texture) @@ -431,7 +416,7 @@ video::ITexture *Minimap::getMinimapTexture() data->texture = driver->addTexture("minimap__", minimap_image); data->heightmap_texture = - driver->addTexture("minimap_heightmap__", heightmap_image); + driver->addTexture("minimap_heightmap__", heightmap_image); minimap_image->drop(); heightmap_image->drop(); @@ -443,8 +428,10 @@ video::ITexture *Minimap::getMinimapTexture() v3f Minimap::getYawVec() { if (data->minimap_shape_round) { - return v3f(std::cos(m_angle * core::DEGTORAD), - std::sin(m_angle * core::DEGTORAD), 1.0); + return v3f( + std::cos(m_angle * core::DEGTORAD), + std::sin(m_angle * core::DEGTORAD), + 1.0); } return v3f(1.0, 0.0, 1.0); @@ -458,9 +445,9 @@ scene::SMeshBuffer *Minimap::getMinimapMeshBuffer() static const video::SColor c(255, 255, 255, 255); buf->Vertices[0] = video::S3DVertex(-1, -1, 0, 0, 0, 1, c, 0, 1); - buf->Vertices[1] = video::S3DVertex(-1, 1, 0, 0, 0, 1, c, 0, 0); - buf->Vertices[2] = video::S3DVertex(1, 1, 0, 0, 0, 1, c, 1, 0); - buf->Vertices[3] = video::S3DVertex(1, -1, 0, 0, 0, 1, c, 1, 1); + buf->Vertices[1] = video::S3DVertex(-1, 1, 0, 0, 0, 1, c, 0, 0); + buf->Vertices[2] = video::S3DVertex( 1, 1, 0, 0, 0, 1, c, 1, 0); + buf->Vertices[3] = video::S3DVertex( 1, -1, 0, 0, 0, 1, c, 1, 1); buf->Indices[0] = 0; buf->Indices[1] = 1; @@ -487,7 +474,8 @@ void Minimap::drawMinimap() core::matrix4 oldViewMat = driver->getTransform(video::ETS_VIEW); driver->setViewPort(core::rect( - screensize.X - size - 10, 10, screensize.X - 10, size + 10)); + screensize.X - size - 10, 10, + screensize.X - 10, size + 10)); driver->setTransform(video::ETS_PROJECTION, core::matrix4()); driver->setTransform(video::ETS_VIEW, core::matrix4()); @@ -516,9 +504,8 @@ void Minimap::drawMinimap() driver->drawMeshBuffer(m_meshbuffer); // Draw overlay - video::ITexture *minimap_overlay = data->minimap_shape_round - ? data->minimap_overlay_round - : data->minimap_overlay_square; + video::ITexture *minimap_overlay = data->minimap_shape_round ? + data->minimap_overlay_round : data->minimap_overlay_square; material.TextureLayer[0].Texture = minimap_overlay; material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; driver->setMaterial(material); @@ -549,8 +536,9 @@ void Minimap::drawMinimap() static const video::SColor c[4] = {col, col, col, col}; f32 sin_angle = std::sin(m_angle * core::DEGTORAD); f32 cos_angle = std::cos(m_angle * core::DEGTORAD); - s32 marker_size2 = 0.025 * (float)size; - for (std::list::const_iterator i = m_active_markers.begin(); + s32 marker_size2 = 0.025 * (float)size; + for (std::list::const_iterator + i = m_active_markers.begin(); i != m_active_markers.end(); ++i) { v2f posf = *i; if (data->minimap_shape_round) { @@ -561,36 +549,34 @@ void Minimap::drawMinimap() } posf.X = (posf.X + 0.5) * (float)size; posf.Y = (posf.Y + 0.5) * (float)size; - core::rect dest_rect(s_pos.X + posf.X - marker_size2, - s_pos.Y + posf.Y - marker_size2, - s_pos.X + posf.X + marker_size2, - s_pos.Y + posf.Y + marker_size2); - driver->draw2DImage(data->object_marker_red, dest_rect, img_rect, - &dest_rect, &c[0], true); + core::rect dest_rect( + s_pos.X + posf.X - marker_size2, + s_pos.Y + posf.Y - marker_size2, + s_pos.X + posf.X + marker_size2, + s_pos.Y + posf.Y + marker_size2); + driver->draw2DImage(data->object_marker_red, dest_rect, + img_rect, &dest_rect, &c[0], true); } } void Minimap::updateActiveMarkers() { - video::IImage *minimap_mask = data->minimap_shape_round - ? data->minimap_mask_round - : data->minimap_mask_square; + video::IImage *minimap_mask = data->minimap_shape_round ? + data->minimap_mask_round : data->minimap_mask_square; const std::list &nametags = client->getCamera()->getNametags(); m_active_markers.clear(); for (Nametag *nametag : nametags) { - v3s16 pos = floatToInt( - nametag->parent_node->getAbsolutePosition() + - intToFloat(client->getCamera()->getOffset(), - BS), - BS); - pos -= data->pos - v3s16(data->map_size / 2, data->scan_height / 2, - data->map_size / 2); - if (pos.X < 0 || pos.X > data->map_size || pos.Y < 0 || - pos.Y > data->scan_height || pos.Z < 0 || - pos.Z > data->map_size) { + v3s16 pos = floatToInt(nametag->parent_node->getAbsolutePosition() + + intToFloat(client->getCamera()->getOffset(), BS), BS); + pos -= data->pos - v3s16(data->map_size / 2, + data->scan_height / 2, + data->map_size / 2); + if (pos.X < 0 || pos.X > data->map_size || + pos.Y < 0 || pos.Y > data->scan_height || + pos.Z < 0 || pos.Z > data->map_size) { continue; } pos.X = ((float)pos.X / data->map_size) * MINIMAP_MAX_SX; @@ -600,9 +586,8 @@ void Minimap::updateActiveMarkers() continue; } - m_active_markers.emplace_back( - ((float)pos.X / (float)MINIMAP_MAX_SX) - 0.5, - (1.0 - (float)pos.Z / (float)MINIMAP_MAX_SY) - 0.5); + m_active_markers.emplace_back(((float)pos.X / (float)MINIMAP_MAX_SX) - 0.5, + (1.0 - (float)pos.Z / (float)MINIMAP_MAX_SY) - 0.5); } } @@ -614,26 +599,26 @@ void MinimapMapblock::getMinimapNodes(VoxelManipulator *vmanip, const v3s16 &pos { for (s16 x = 0; x < MAP_BLOCKSIZE; x++) - for (s16 z = 0; z < MAP_BLOCKSIZE; z++) { - s16 air_count = 0; - bool surface_found = false; - MinimapPixel *mmpixel = &data[z * MAP_BLOCKSIZE + x]; - - for (s16 y = MAP_BLOCKSIZE - 1; y >= 0; y--) { - v3s16 p(x, y, z); - MapNode n = vmanip->getNodeNoEx(pos + p); - if (!surface_found && n.getContent() != CONTENT_AIR) { - mmpixel->height = y; - mmpixel->n = n; - surface_found = true; - } else if (n.getContent() == CONTENT_AIR) { - air_count++; - } + for (s16 z = 0; z < MAP_BLOCKSIZE; z++) { + s16 air_count = 0; + bool surface_found = false; + MinimapPixel *mmpixel = &data[z * MAP_BLOCKSIZE + x]; + + for (s16 y = MAP_BLOCKSIZE -1; y >= 0; y--) { + v3s16 p(x, y, z); + MapNode n = vmanip->getNodeNoEx(pos + p); + if (!surface_found && n.getContent() != CONTENT_AIR) { + mmpixel->height = y; + mmpixel->n = n; + surface_found = true; + } else if (n.getContent() == CONTENT_AIR) { + air_count++; } + } - if (!surface_found) - mmpixel->n = MapNode(CONTENT_AIR); + if (!surface_found) + mmpixel->n = MapNode(CONTENT_AIR); - mmpixel->air_count = air_count; - } + mmpixel->air_count = air_count; + } } diff --git a/src/client/minimap.h b/src/client/minimap.h index dc4db514a..258d5330d 100644 --- a/src/client/minimap.h +++ b/src/client/minimap.h @@ -33,8 +33,7 @@ class IShaderSource; #define MINIMAP_MAX_SX 512 #define MINIMAP_MAX_SY 512 -enum MinimapMode -{ +enum MinimapMode { MINIMAP_MODE_OFF, MINIMAP_MODE_SURFACEx1, MINIMAP_MODE_SURFACEx2, @@ -45,36 +44,31 @@ enum MinimapMode MINIMAP_MODE_COUNT, }; -enum MinimapShape -{ +enum MinimapShape { MINIMAP_SHAPE_SQUARE, MINIMAP_SHAPE_ROUND, }; -struct MinimapModeDef -{ +struct MinimapModeDef { bool is_radar; u16 scan_height; u16 map_size; }; -struct MinimapPixel -{ +struct MinimapPixel { //! The topmost node that the minimap displays. MapNode n; u16 height; u16 air_count; }; -struct MinimapMapblock -{ +struct MinimapMapblock { void getMinimapNodes(VoxelManipulator *vmanip, const v3s16 &pos); MinimapPixel data[MAP_BLOCKSIZE * MAP_BLOCKSIZE]; }; -struct MinimapData -{ +struct MinimapData { bool is_radar; MinimapMode mode; v3s16 pos; @@ -94,14 +88,12 @@ struct MinimapData video::ITexture *object_marker_red = nullptr; }; -struct QueuedMinimapUpdate -{ +struct QueuedMinimapUpdate { v3s16 pos; MinimapMapblock *data = nullptr; }; -class MinimapUpdateThread : public UpdateThread -{ +class MinimapUpdateThread : public UpdateThread { public: MinimapUpdateThread() : UpdateThread("Minimap") {} virtual ~MinimapUpdateThread(); @@ -122,8 +114,7 @@ class MinimapUpdateThread : public UpdateThread std::map m_blocks_cache; }; -class Minimap -{ +class Minimap { public: Minimap(Client *client); ~Minimap(); @@ -142,11 +133,12 @@ class Minimap void setMinimapShape(MinimapShape shape); MinimapShape getMinimapShape(); + video::ITexture *getMinimapTexture(); void blitMinimapPixelsToImageRadar(video::IImage *map_image); - void blitMinimapPixelsToImageSurface( - video::IImage *map_image, video::IImage *heightmap_image); + void blitMinimapPixelsToImageSurface(video::IImage *map_image, + video::IImage *heightmap_image); scene::SMeshBuffer *getMinimapMeshBuffer(); @@ -154,7 +146,7 @@ class Minimap void drawMinimap(); video::IVideoDriver *driver; - Client *client; + Client* client; MinimapData *data; private: diff --git a/src/client/particles.cpp b/src/client/particles.cpp index 5885987fc..7acd996dc 100644 --- a/src/client/particles.cpp +++ b/src/client/particles.cpp @@ -44,20 +44,28 @@ static f32 random_f32(f32 min, f32 max) static v3f random_v3f(v3f min, v3f max) { - return v3f(random_f32(min.X, max.X), random_f32(min.Y, max.Y), - random_f32(min.Z, max.Z)); + return v3f( + random_f32(min.X, max.X), + random_f32(min.Y, max.Y), + random_f32(min.Z, max.Z)); } /* Particle */ -Particle::Particle(IGameDef *gamedef, LocalPlayer *player, ClientEnvironment *env, - const ParticleParameters &p, video::ITexture *texture, v2f texpos, - v2f texsize, video::SColor color) : - scene::ISceneNode( - RenderingEngine::get_scene_manager()->getRootSceneNode(), - RenderingEngine::get_scene_manager()) +Particle::Particle( + IGameDef *gamedef, + LocalPlayer *player, + ClientEnvironment *env, + const ParticleParameters &p, + video::ITexture *texture, + v2f texpos, + v2f texsize, + video::SColor color +): + scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), + RenderingEngine::get_scene_manager()) { // Misc m_gamedef = gamedef; @@ -106,8 +114,7 @@ Particle::Particle(IGameDef *gamedef, LocalPlayer *player, ClientEnvironment *en void Particle::OnRegisterSceneNode() { if (IsVisible) - SceneManager->registerNodeForRendering( - this, scene::ESNRP_TRANSPARENT_EFFECT); + SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT_EFFECT); ISceneNode::OnRegisterSceneNode(); } @@ -118,8 +125,9 @@ void Particle::render() driver->setMaterial(m_material); driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); - u16 indices[] = {0, 1, 2, 2, 3, 0}; - driver->drawVertexPrimitiveList(m_vertices, 4, indices, 2, video::EVT_STANDARD, + u16 indices[] = {0,1,2, 2,3,0}; + driver->drawVertexPrimitiveList(m_vertices, 4, + indices, 2, video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT); } @@ -131,8 +139,8 @@ void Particle::step(float dtime) v3f p_pos = m_pos * BS; v3f p_velocity = m_velocity * BS; collisionMoveResult r = collisionMoveSimple(m_env, m_gamedef, BS * 0.5f, - box, 0.0f, dtime, &p_pos, &p_velocity, - m_acceleration * BS, nullptr, m_object_collision); + box, 0.0f, dtime, &p_pos, &p_velocity, m_acceleration * BS, nullptr, + m_object_collision); if (m_collision_removal && r.collides) { // force expiration of the particle m_expiration = -1.0; @@ -147,7 +155,8 @@ void Particle::step(float dtime) if (m_animation.type != TAT_NONE) { m_animation_time += dtime; int frame_length_i, frame_count; - m_animation.determineParams(m_material.getTexture(0)->getSize(), + m_animation.determineParams( + m_material.getTexture(0)->getSize(), &frame_count, &frame_length_i, NULL); float frame_length = frame_length_i / 1000.0; while (m_animation_time > frame_length) { @@ -168,7 +177,11 @@ void Particle::updateLight() u8 light = 0; bool pos_ok; - v3s16 p = v3s16(floor(m_pos.X + 0.5), floor(m_pos.Y + 0.5), floor(m_pos.Z + 0.5)); + v3s16 p = v3s16( + floor(m_pos.X+0.5), + floor(m_pos.Y+0.5), + floor(m_pos.Z+0.5) + ); MapNode n = m_env->getClientMap().getNode(p, &pos_ok); if (pos_ok) light = n.getLightBlend(m_env->getDayNightRatio(), m_gamedef->ndef()); @@ -176,9 +189,10 @@ void Particle::updateLight() light = blend_light(m_env->getDayNightRatio(), LIGHT_SUN, 0); u8 m_light = decode_light(light + m_glow); - m_color.set(255, m_light * m_base_color.getRed() / 255, - m_light * m_base_color.getGreen() / 255, - m_light * m_base_color.getBlue() / 255); + m_color.set(255, + m_light * m_base_color.getRed() / 255, + m_light * m_base_color.getGreen() / 255, + m_light * m_base_color.getBlue() / 255); } void Particle::updateVertices() @@ -191,8 +205,7 @@ void Particle::updateVertices() v2u32 framesize; texcoord = m_animation.getTextureCoords(texsize, m_animation_frame); m_animation.determineParams(texsize, NULL, NULL, &framesize); - framesize_f = v2f(framesize.X / (float)texsize.X, - framesize.Y / (float)texsize.Y); + framesize_f = v2f(framesize.X / (float) texsize.X, framesize.Y / (float) texsize.Y); tx0 = m_texpos.X + texcoord.X; tx1 = m_texpos.X + texcoord.X + framesize_f.X * m_texsize.X; @@ -205,29 +218,27 @@ void Particle::updateVertices() ty1 = m_texpos.Y + m_texsize.Y; } - m_vertices[0] = video::S3DVertex( - -m_size / 2, -m_size / 2, 0, 0, 0, 0, m_color, tx0, ty1); - m_vertices[1] = video::S3DVertex( - m_size / 2, -m_size / 2, 0, 0, 0, 0, m_color, tx1, ty1); - m_vertices[2] = video::S3DVertex( - m_size / 2, m_size / 2, 0, 0, 0, 0, m_color, tx1, ty0); - m_vertices[3] = video::S3DVertex( - -m_size / 2, m_size / 2, 0, 0, 0, 0, m_color, tx0, ty0); + m_vertices[0] = video::S3DVertex(-m_size / 2, -m_size / 2, + 0, 0, 0, 0, m_color, tx0, ty1); + m_vertices[1] = video::S3DVertex(m_size / 2, -m_size / 2, + 0, 0, 0, 0, m_color, tx1, ty1); + m_vertices[2] = video::S3DVertex(m_size / 2, m_size / 2, + 0, 0, 0, 0, m_color, tx1, ty0); + m_vertices[3] = video::S3DVertex(-m_size / 2, m_size / 2, + 0, 0, 0, 0, m_color, tx0, ty0); v3s16 camera_offset = m_env->getCameraOffset(); for (video::S3DVertex &vertex : m_vertices) { if (m_vertical) { - v3f ppos = m_player->getPosition() / BS; - vertex.Pos.rotateXZBy( - std::atan2(ppos.Z - m_pos.Z, ppos.X - m_pos.X) / - core::DEGTORAD + - 90); + v3f ppos = m_player->getPosition()/BS; + vertex.Pos.rotateXZBy(std::atan2(ppos.Z - m_pos.Z, ppos.X - m_pos.X) / + core::DEGTORAD + 90); } else { vertex.Pos.rotateYZBy(m_player->getPitch()); vertex.Pos.rotateXZBy(m_player->getYaw()); } m_box.addInternalPoint(vertex.Pos); - vertex.Pos += m_pos * BS - intToFloat(camera_offset, BS); + vertex.Pos += m_pos*BS - intToFloat(camera_offset, BS); } } @@ -235,11 +246,15 @@ void Particle::updateVertices() ParticleSpawner */ -ParticleSpawner::ParticleSpawner(IGameDef *gamedef, LocalPlayer *player, - const ParticleSpawnerParameters &p, u16 attached_id, - video::ITexture *texture, ParticleManager *p_manager) : - m_particlemanager(p_manager), - p(p) +ParticleSpawner::ParticleSpawner( + IGameDef *gamedef, + LocalPlayer *player, + const ParticleSpawnerParameters &p, + u16 attached_id, + video::ITexture *texture, + ParticleManager *p_manager +): + m_particlemanager(p_manager), p(p) { m_gamedef = gamedef; m_player = player; @@ -255,7 +270,7 @@ ParticleSpawner::ParticleSpawner(IGameDef *gamedef, LocalPlayer *player, } void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius, - const core::matrix4 *attached_absolute_pos_rot_matrix) + const core::matrix4 *attached_absolute_pos_rot_matrix) { v3f ppos = m_player->getPosition() / BS; v3f pos = random_v3f(p.minpos, p.maxpos); @@ -297,10 +312,9 @@ void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius, if (p.node.getContent() != CONTENT_IGNORE) { const ContentFeatures &f = - m_particlemanager->m_env->getGameDef()->ndef()->get( - p.node); + m_particlemanager->m_env->getGameDef()->ndef()->get(p.node); if (!ParticleManager::getNodeParticleParams(p.node, f, pp, &texture, - texpos, texsize, &color, p.node_tile)) + texpos, texsize, &color, p.node_tile)) return; } else { texture = m_texture; @@ -313,7 +327,15 @@ void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius, pp.size = random_f32(p.minsize, p.maxsize); m_particlemanager->addParticle(new Particle( - m_gamedef, m_player, env, pp, texture, texpos, texsize, color)); + m_gamedef, + m_player, + env, + pp, + texture, + texpos, + texsize, + color + )); } void ParticleSpawner::step(float dtime, ClientEnvironment *env) @@ -326,10 +348,8 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env) bool unloaded = false; const core::matrix4 *attached_absolute_pos_rot_matrix = nullptr; if (m_attached_id) { - if (GenericCAO *attached = dynamic_cast( - env->getActiveObject(m_attached_id))) { - attached_absolute_pos_rot_matrix = - attached->getAbsolutePosRotMatrix(); + if (GenericCAO *attached = dynamic_cast(env->getActiveObject(m_attached_id))) { + attached_absolute_pos_rot_matrix = attached->getAbsolutePosRotMatrix(); } else { unloaded = true; } @@ -337,16 +357,14 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env) if (p.time != 0) { // Spawner exists for a predefined timespan - for (auto i = m_spawntimes.begin(); i != m_spawntimes.end();) { + for (auto i = m_spawntimes.begin(); i != m_spawntimes.end(); ) { if ((*i) <= m_time && p.amount > 0) { --p.amount; - // Pretend to, but don't actually spawn a particle if it - // is attached to an unloaded object or distant from - // player. + // Pretend to, but don't actually spawn a particle if it is + // attached to an unloaded object or distant from player. if (!unloaded) - spawnParticle(env, radius, - attached_absolute_pos_rot_matrix); + spawnParticle(env, radius, attached_absolute_pos_rot_matrix); i = m_spawntimes.erase(i); } else { @@ -362,8 +380,7 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env) for (int i = 0; i <= p.amount; i++) { if (rand() / (float)RAND_MAX < dtime) - spawnParticle(env, radius, - attached_absolute_pos_rot_matrix); + spawnParticle(env, radius, attached_absolute_pos_rot_matrix); } } } @@ -372,9 +389,9 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env) ParticleManager */ -ParticleManager::ParticleManager(ClientEnvironment *env) : m_env(env) -{ -} +ParticleManager::ParticleManager(ClientEnvironment *env) : + m_env(env) +{} ParticleManager::~ParticleManager() { @@ -383,8 +400,8 @@ ParticleManager::~ParticleManager() void ParticleManager::step(float dtime) { - stepParticles(dtime); - stepSpawners(dtime); + stepParticles (dtime); + stepSpawners (dtime); } void ParticleManager::stepSpawners(float dtime) @@ -425,80 +442,83 @@ void ParticleManager::clearAll() m_particle_spawners.erase(i++); } - for (auto i = m_particles.begin(); i != m_particles.end();) { + for(auto i = m_particles.begin(); i != m_particles.end();) + { (*i)->remove(); delete *i; i = m_particles.erase(i); } } -void ParticleManager::handleParticleEvent( - ClientEvent *event, Client *client, LocalPlayer *player) +void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client, + LocalPlayer *player) { switch (event->type) { - case CE_DELETE_PARTICLESPAWNER: { - deleteParticleSpawner(event->delete_particlespawner.id); - // no allocated memory in delete event - break; - } - case CE_ADD_PARTICLESPAWNER: { - deleteParticleSpawner(event->add_particlespawner.id); + case CE_DELETE_PARTICLESPAWNER: { + deleteParticleSpawner(event->delete_particlespawner.id); + // no allocated memory in delete event + break; + } + case CE_ADD_PARTICLESPAWNER: { + deleteParticleSpawner(event->add_particlespawner.id); - const ParticleSpawnerParameters &p = *event->add_particlespawner.p; + const ParticleSpawnerParameters &p = *event->add_particlespawner.p; - video::ITexture *texture = client->tsrc()->getTextureForMesh(p.texture); + video::ITexture *texture = + client->tsrc()->getTextureForMesh(p.texture); - auto toadd = new ParticleSpawner(client, player, p, - event->add_particlespawner.attached_id, texture, this); + auto toadd = new ParticleSpawner(client, player, + p, + event->add_particlespawner.attached_id, + texture, + this); - addParticleSpawner(event->add_particlespawner.id, toadd); + addParticleSpawner(event->add_particlespawner.id, toadd); - delete event->add_particlespawner.p; - break; - } - case CE_SPAWN_PARTICLE: { - ParticleParameters &p = *event->spawn_particle; + delete event->add_particlespawner.p; + break; + } + case CE_SPAWN_PARTICLE: { + ParticleParameters &p = *event->spawn_particle; - video::ITexture *texture; - v2f texpos, texsize; - video::SColor color(0xFFFFFFFF); + video::ITexture *texture; + v2f texpos, texsize; + video::SColor color(0xFFFFFFFF); - f32 oldsize = p.size; + f32 oldsize = p.size; - if (p.node.getContent() != CONTENT_IGNORE) { - const ContentFeatures &f = - m_env->getGameDef()->ndef()->get(p.node); - if (!getNodeParticleParams(p.node, f, p, &texture, texpos, - texsize, &color, p.node_tile)) - texture = nullptr; - } else { - texture = client->tsrc()->getTextureForMesh(p.texture); - texpos = v2f(0.0f, 0.0f); - texsize = v2f(1.0f, 1.0f); - } + if (p.node.getContent() != CONTENT_IGNORE) { + const ContentFeatures &f = m_env->getGameDef()->ndef()->get(p.node); + if (!getNodeParticleParams(p.node, f, p, &texture, texpos, + texsize, &color, p.node_tile)) + texture = nullptr; + } else { + texture = client->tsrc()->getTextureForMesh(p.texture); + texpos = v2f(0.0f, 0.0f); + texsize = v2f(1.0f, 1.0f); + } - // Allow keeping default random size - if (oldsize > 0.0f) - p.size = oldsize; + // Allow keeping default random size + if (oldsize > 0.0f) + p.size = oldsize; - if (texture) { - Particle *toadd = new Particle(client, player, m_env, p, texture, - texpos, texsize, color); + if (texture) { + Particle *toadd = new Particle(client, player, m_env, + p, texture, texpos, texsize, color); - addParticle(toadd); - } + addParticle(toadd); + } - delete event->spawn_particle; - break; - } - default: - break; + delete event->spawn_particle; + break; + } + default: break; } } -bool ParticleManager::getNodeParticleParams(const MapNode &n, const ContentFeatures &f, - ParticleParameters &p, video::ITexture **texture, v2f &texpos, - v2f &texsize, video::SColor *color, u8 tilenum) +bool ParticleManager::getNodeParticleParams(const MapNode &n, + const ContentFeatures &f, ParticleParameters &p, video::ITexture **texture, + v2f &texpos, v2f &texsize, video::SColor *color, u8 tilenum) { // No particles for "airlike" nodes if (f.drawtype == NDT_AIRLIKE) @@ -538,8 +558,8 @@ bool ParticleManager::getNodeParticleParams(const MapNode &n, const ContentFeatu // The final burst of particles when a node is finally dug, *not* particles // spawned during the digging of a node. -void ParticleManager::addDiggingParticles(IGameDef *gamedef, LocalPlayer *player, - v3s16 pos, const MapNode &n, const ContentFeatures &f) +void ParticleManager::addDiggingParticles(IGameDef *gamedef, + LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f) { // No particles for "airlike" nodes if (f.drawtype == NDT_AIRLIKE) @@ -553,8 +573,8 @@ void ParticleManager::addDiggingParticles(IGameDef *gamedef, LocalPlayer *player // During the digging of a node particles are spawned individually by this // function, called from Game::handleDigging() in game.cpp. -void ParticleManager::addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3s16 pos, - const MapNode &n, const ContentFeatures &f) +void ParticleManager::addNodeParticle(IGameDef *gamedef, + LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f) { ParticleParameters p; video::ITexture *texture; @@ -567,17 +587,31 @@ void ParticleManager::addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3 p.expirationtime = (rand() % 100) / 100.0f; // Physics - p.vel = v3f((rand() % 150) / 50.0f - 1.5f, (rand() % 150) / 50.0f, - (rand() % 150) / 50.0f - 1.5f); - p.acc = v3f(0.0f, - -player->movement_gravity * player->physics_override_gravity / BS, - 0.0f); - p.pos = v3f((f32)pos.X + (rand() % 100) / 200.0f - 0.25f, - (f32)pos.Y + (rand() % 100) / 200.0f - 0.25f, - (f32)pos.Z + (rand() % 100) / 200.0f - 0.25f); + p.vel = v3f( + (rand() % 150) / 50.0f - 1.5f, + (rand() % 150) / 50.0f, + (rand() % 150) / 50.0f - 1.5f + ); + p.acc = v3f( + 0.0f, + -player->movement_gravity * player->physics_override_gravity / BS, + 0.0f + ); + p.pos = v3f( + (f32)pos.X + (rand() % 100) / 200.0f - 0.25f, + (f32)pos.Y + (rand() % 100) / 200.0f - 0.25f, + (f32)pos.Z + (rand() % 100) / 200.0f - 0.25f + ); Particle *toadd = new Particle( - gamedef, player, m_env, p, texture, texpos, texsize, color); + gamedef, + player, + m_env, + p, + texture, + texpos, + texsize, + color); addParticle(toadd); } @@ -588,6 +622,7 @@ void ParticleManager::addParticle(Particle *toadd) m_particles.push_back(toadd); } + void ParticleManager::addParticleSpawner(u64 id, ParticleSpawner *toadd) { MutexAutoLock lock(m_spawner_list_lock); diff --git a/src/client/particles.h b/src/client/particles.h index b3a1f1156..2011f0262 100644 --- a/src/client/particles.h +++ b/src/client/particles.h @@ -33,24 +33,41 @@ struct ContentFeatures; class Particle : public scene::ISceneNode { -public: - Particle(IGameDef *gamedef, LocalPlayer *player, ClientEnvironment *env, - const ParticleParameters &p, video::ITexture *texture, v2f texpos, - v2f texsize, video::SColor color); + public: + Particle( + IGameDef* gamedef, + LocalPlayer *player, + ClientEnvironment *env, + const ParticleParameters &p, + video::ITexture *texture, + v2f texpos, + v2f texsize, + video::SColor color + ); ~Particle() = default; - virtual const aabb3f &getBoundingBox() const { return m_box; } + virtual const aabb3f &getBoundingBox() const + { + return m_box; + } - virtual u32 getMaterialCount() const { return 1; } + virtual u32 getMaterialCount() const + { + return 1; + } - virtual video::SMaterial &getMaterial(u32 i) { return m_material; } + virtual video::SMaterial& getMaterial(u32 i) + { + return m_material; + } virtual void OnRegisterSceneNode(); virtual void render(); void step(float dtime); - bool get_expired() { return m_expiration < m_time; } + bool get_expired () + { return m_expiration < m_time; } private: void updateLight(); @@ -90,19 +107,23 @@ class Particle : public scene::ISceneNode class ParticleSpawner { public: - ParticleSpawner(IGameDef *gamedef, LocalPlayer *player, - const ParticleSpawnerParameters &p, u16 attached_id, - video::ITexture *texture, ParticleManager *p_manager); + ParticleSpawner(IGameDef* gamedef, + LocalPlayer *player, + const ParticleSpawnerParameters &p, + u16 attached_id, + video::ITexture *texture, + ParticleManager* p_manager); ~ParticleSpawner() = default; void step(float dtime, ClientEnvironment *env); - bool get_expired() { return p.amount <= 0 && p.time != 0; } + bool get_expired () + { return p.amount <= 0 && p.time != 0; } private: void spawnParticle(ClientEnvironment *env, float radius, - const core::matrix4 *attached_absolute_pos_rot_matrix); + const core::matrix4 *attached_absolute_pos_rot_matrix); ParticleManager *m_particlemanager; float m_time; @@ -119,21 +140,21 @@ class ParticleSpawner */ class ParticleManager { - friend class ParticleSpawner; - +friend class ParticleSpawner; public: - ParticleManager(ClientEnvironment *env); + ParticleManager(ClientEnvironment* env); ~ParticleManager(); - void step(float dtime); + void step (float dtime); - void handleParticleEvent(ClientEvent *event, Client *client, LocalPlayer *player); + void handleParticleEvent(ClientEvent *event, Client *client, + LocalPlayer *player); void addDiggingParticles(IGameDef *gamedef, LocalPlayer *player, v3s16 pos, - const MapNode &n, const ContentFeatures &f); + const MapNode &n, const ContentFeatures &f); void addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3s16 pos, - const MapNode &n, const ContentFeatures &f); + const MapNode &n, const ContentFeatures &f); /** * This function is only used by client particle spawners @@ -142,14 +163,17 @@ class ParticleManager * never overlap (u64) * @return new id */ - u64 generateSpawnerId() { return m_next_particle_spawner_id++; } + u64 generateSpawnerId() + { + return m_next_particle_spawner_id++; + } protected: static bool getNodeParticleParams(const MapNode &n, const ContentFeatures &f, - ParticleParameters &p, video::ITexture **texture, v2f &texpos, - v2f &texsize, video::SColor *color, u8 tilenum = 0); + ParticleParameters &p, video::ITexture **texture, v2f &texpos, + v2f &texsize, video::SColor *color, u8 tilenum = 0); - void addParticle(Particle *toadd); + void addParticle(Particle* toadd); private: void addParticleSpawner(u64 id, ParticleSpawner *toadd); @@ -160,13 +184,13 @@ class ParticleManager void clearAll(); - std::vector m_particles; - std::unordered_map m_particle_spawners; - // Start the particle spawner ids generated from here after u32_max. lower values - // are for server sent spawners. + std::vector m_particles; + std::unordered_map m_particle_spawners; + // Start the particle spawner ids generated from here after u32_max. lower values are + // for server sent spawners. u64 m_next_particle_spawner_id = U32_MAX + 1; - ClientEnvironment *m_env; + ClientEnvironment* m_env; std::mutex m_particle_list_lock; std::mutex m_spawner_list_lock; }; diff --git a/src/client/render/core.cpp b/src/client/render/core.cpp index a7644681e..223af5142 100644 --- a/src/client/render/core.cpp +++ b/src/client/render/core.cpp @@ -27,11 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/minimap.h" #include "client/content_cao.h" -RenderingCore::RenderingCore(IrrlichtDevice *_device, Client *_client, Hud *_hud) : - device(_device), driver(device->getVideoDriver()), - smgr(device->getSceneManager()), guienv(device->getGUIEnvironment()), - client(_client), camera(client->getCamera()), - mapper(client->getMinimap()), hud(_hud) +RenderingCore::RenderingCore(IrrlichtDevice *_device, Client *_client, Hud *_hud) + : device(_device), driver(device->getVideoDriver()), smgr(device->getSceneManager()), + guienv(device->getGUIEnvironment()), client(_client), camera(client->getCamera()), + mapper(client->getMinimap()), hud(_hud) { screensize = driver->getScreenSize(); virtual_size = screensize; @@ -56,8 +55,7 @@ void RenderingCore::updateScreenSize() } void RenderingCore::draw(video::SColor _skycolor, bool _show_hud, bool _show_minimap, - bool _draw_wield_tool, bool _draw_crosshair, bool _draw_tracers, - bool _draw_esp) + bool _draw_wield_tool, bool _draw_crosshair, bool _draw_tracers, bool _draw_esp) { v2u32 ss = driver->getScreenSize(); if (screensize != ss) { @@ -71,7 +69,7 @@ void RenderingCore::draw(video::SColor _skycolor, bool _show_hud, bool _show_min draw_crosshair = _draw_crosshair; draw_tracers = _draw_tracers; draw_esp = _draw_esp; - + beforeDraw(); drawAll(); } @@ -80,29 +78,29 @@ void RenderingCore::drawTracersAndESP() { ClientEnvironment &env = client->getEnv(); Camera *camera = client->getCamera(); - + v3f camera_offset = intToFloat(camera->getOffset(), BS); - + v3f eye_pos = (camera->getPosition() + camera->getDirection() - camera_offset); - - video::SMaterial material, oldmaterial; - oldmaterial = driver->getMaterial2D(); + + video::SMaterial material, oldmaterial; + oldmaterial = driver->getMaterial2D(); material.setFlag(video::EMF_LIGHTING, false); material.setFlag(video::EMF_BILINEAR_FILTER, false); material.setFlag(video::EMF_ZBUFFER, false); material.setFlag(video::EMF_ZWRITE_ENABLE, false); driver->setMaterial(material); - + auto allObjects = env.getAllActiveObjects(); for (auto &it : allObjects) { ClientActiveObject *cao = it.second; if (cao->isLocalPlayer() || cao->getParent()) continue; GenericCAO *obj = dynamic_cast(cao); - if (!obj) + if (! obj) continue; aabb3f box; - if (!obj->getSelectionBox(&box)) + if (! obj->getSelectionBox(&box)) continue; v3f pos = obj->getPosition(); pos -= camera_offset; @@ -112,10 +110,9 @@ void RenderingCore::drawTracersAndESP() if (draw_esp) driver->draw3DBox(box, video::SColor(255, 255, 255, 255)); if (draw_tracers) - driver->draw3DLine( - eye_pos, pos, video::SColor(255, 255, 255, 255)); + driver->draw3DLine(eye_pos, pos, video::SColor(255, 255, 255, 255)); } - + driver->setMaterial(oldmaterial); } @@ -137,7 +134,7 @@ void RenderingCore::drawHUD() if (show_hud) { if (draw_crosshair) hud->drawCrosshair(); - + hud->drawHotbar(client->getEnv().getLocalPlayer()->getWieldIndex()); hud->drawLuaElements(camera->getOffset()); camera->drawNametags(); diff --git a/src/client/render/interlaced.cpp b/src/client/render/interlaced.cpp index c5d9c9c24..2aadadc17 100644 --- a/src/client/render/interlaced.cpp +++ b/src/client/render/interlaced.cpp @@ -24,8 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/tile.h" RenderingCoreInterlaced::RenderingCoreInterlaced( - IrrlichtDevice *_device, Client *_client, Hud *_hud) : - RenderingCoreStereo(_device, _client, _hud) + IrrlichtDevice *_device, Client *_client, Hud *_hud) + : RenderingCoreStereo(_device, _client, _hud) { initMaterial(); } diff --git a/src/client/render/plain.cpp b/src/client/render/plain.cpp index 8ac5e106b..a130a14eb 100644 --- a/src/client/render/plain.cpp +++ b/src/client/render/plain.cpp @@ -27,8 +27,8 @@ inline u32 scaledown(u32 coef, u32 size) } RenderingCorePlain::RenderingCorePlain( - IrrlichtDevice *_device, Client *_client, Hud *_hud) : - RenderingCore(_device, _client, _hud) + IrrlichtDevice *_device, Client *_client, Hud *_hud) + : RenderingCore(_device, _client, _hud) { scale = g_settings->getU16("undersampling"); } diff --git a/src/client/render/sidebyside.cpp b/src/client/render/sidebyside.cpp index 89e4b5e80..ed08810db 100644 --- a/src/client/render/sidebyside.cpp +++ b/src/client/render/sidebyside.cpp @@ -22,10 +22,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "client/hud.h" -RenderingCoreSideBySide::RenderingCoreSideBySide(IrrlichtDevice *_device, Client *_client, - Hud *_hud, bool _horizontal, bool _flipped) : - RenderingCoreStereo(_device, _client, _hud), - horizontal(_horizontal), flipped(_flipped) +RenderingCoreSideBySide::RenderingCoreSideBySide( + IrrlichtDevice *_device, Client *_client, Hud *_hud, bool _horizontal, bool _flipped) + : RenderingCoreStereo(_device, _client, _hud), horizontal(_horizontal), flipped(_flipped) { } diff --git a/src/client/render/stereo.cpp b/src/client/render/stereo.cpp index 99997c967..967b5a78f 100644 --- a/src/client/render/stereo.cpp +++ b/src/client/render/stereo.cpp @@ -24,8 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" RenderingCoreStereo::RenderingCoreStereo( - IrrlichtDevice *_device, Client *_client, Hud *_hud) : - RenderingCore(_device, _client, _hud) + IrrlichtDevice *_device, Client *_client, Hud *_hud) + : RenderingCore(_device, _client, _hud) { eye_offset = BS * g_settings->getFloat("3d_paralax_strength"); } diff --git a/src/client/renderingengine.cpp b/src/client/renderingengine.cpp index 0b7a242fa..1534289d4 100644 --- a/src/client/renderingengine.cpp +++ b/src/client/renderingengine.cpp @@ -37,7 +37,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gettext.h" #include "../gui/guiSkin.h" -#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \ +#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \ !defined(SERVER) && !defined(__HAIKU__) #define XORG_USED #endif @@ -58,6 +58,7 @@ with this program; if not, write to the Free Software Foundation, Inc., RenderingEngine *RenderingEngine::s_singleton = nullptr; + static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment, gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver) { @@ -66,7 +67,7 @@ static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment, gui::IGUIFont *builtinfont = environment->getBuiltInFont(); gui::IGUIFontBitmap *bitfont = nullptr; if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP) - bitfont = (gui::IGUIFontBitmap *)builtinfont; + bitfont = (gui::IGUIFontBitmap*)builtinfont; gui::IGUISpriteBank *bank = 0; skin->setFont(builtinfont); @@ -79,6 +80,7 @@ static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment, return skin; } + RenderingEngine::RenderingEngine(IEventReceiver *receiver) { sanity_check(!s_singleton); @@ -104,7 +106,7 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver) u32 i; for (i = 0; i != drivers.size(); i++) { if (!strcasecmp(driverstring.c_str(), - RenderingEngine::getVideoDriverName(drivers[i]))) { + RenderingEngine::getVideoDriverName(drivers[i]))) { driverType = drivers[i]; break; } @@ -132,10 +134,9 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver) #endif #if ENABLE_GLES // there is no standardized path for these on desktop - std::string rel_path = std::string("client") + DIR_DELIM + "shaders" + DIR_DELIM + - "Irrlicht"; - params.OGLES2ShaderPath = - (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str(); + std::string rel_path = std::string("client") + DIR_DELIM + + "shaders" + DIR_DELIM + "Irrlicht"; + params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str(); #endif m_device = createDeviceEx(params); @@ -143,8 +144,8 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver) s_singleton = this; - auto skin = createSkin(m_device->getGUIEnvironment(), gui::EGST_WINDOWS_METALLIC, - driver); + auto skin = createSkin(m_device->getGUIEnvironment(), + gui::EGST_WINDOWS_METALLIC, driver); m_device->getGUIEnvironment()->setSkin(skin); skin->drop(); } @@ -233,7 +234,8 @@ bool RenderingEngine::setupTopLevelWindow(const std::string &name) /* Setting general properties for the top level window */ verbosestream << "Client: Configuring general top level" - << " window properties" << std::endl; + << " window properties" + << std::endl; bool result = setWindowIcon(); return result; @@ -244,16 +246,17 @@ void RenderingEngine::setupTopLevelXorgWindow(const std::string &name) #ifdef XORG_USED const video::SExposedVideoData exposedData = driver->getExposedVideoData(); - Display *x11_dpl = - reinterpret_cast(exposedData.OpenGLLinux.X11Display); + Display *x11_dpl = reinterpret_cast(exposedData.OpenGLLinux.X11Display); if (x11_dpl == NULL) { warningstream << "Client: Could not find X11 Display in ExposedVideoData" - << std::endl; + << std::endl; return; } verbosestream << "Client: Configuring X11-specific top level" - << " window properties" << std::endl; + << " window properties" + << std::endl; + Window x11_win = reinterpret_cast(exposedData.OpenGLLinux.X11Window); @@ -281,35 +284,38 @@ void RenderingEngine::setupTopLevelXorgWindow(const std::string &name) // more, using gtk/gdk as the model it would seem that not using a FQDN is // not an issue for modern Xorg window managers. - verbosestream << "Client: Setting Xorg window manager Properties" << std::endl; + verbosestream << "Client: Setting Xorg window manager Properties" + << std::endl; - XSetWMProperties(x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL); + XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL); // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to // force a shutdown of an application if it doesn't respond to the destroy // window message. - verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager " - "property" - << std::endl; + verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property" + << std::endl; Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false); pid_t pid = getpid(); - XChangeProperty(x11_dpl, x11_win, NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, - reinterpret_cast(&pid), 1); + XChangeProperty(x11_dpl, x11_win, NET_WM_PID, + XA_CARDINAL, 32, PropModeReplace, + reinterpret_cast(&pid),1); // Set the WM_CLIENT_LEADER window property here. Minetest has only one // window and that window will always be the leader. - verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property" << std::endl; + verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property" + << std::endl; Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false); - XChangeProperty(x11_dpl, x11_win, WM_CLIENT_LEADER, XA_WINDOW, 32, - PropModeReplace, reinterpret_cast(&x11_win), 1); + XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER, + XA_WINDOW, 32, PropModeReplace, + reinterpret_cast(&x11_win), 1); #endif } @@ -537,8 +543,8 @@ void RenderingEngine::_draw_load_screen(const std::wstring &text, /* Draws the menu scene including (optional) cloud background. */ -void RenderingEngine::_draw_menu_scene( - gui::IGUIEnvironment *guienv, float dtime, bool clouds) +void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv, + float dtime, bool clouds) { bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); if (cloud_menu_background) { @@ -598,11 +604,9 @@ void RenderingEngine::_finalize() } void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud, - bool show_minimap, bool draw_wield_tool, bool draw_crosshair, - bool draw_tracers, bool draw_esp) + bool show_minimap, bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, bool draw_esp) { - core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair, - draw_tracers, draw_esp); + core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair, draw_tracers, draw_esp); } const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type) @@ -675,6 +679,7 @@ float RenderingEngine::getDisplayDensity() #elif defined(_WIN32) + static float calcDisplayDensity(irr::video::IVideoDriver *driver) { HWND hWnd; @@ -720,7 +725,7 @@ v2u32 RenderingEngine::getDisplaySize() return deskres; } -#else // __ANDROID__ +#else // __ANDROID__ float RenderingEngine::getDisplayDensity() { return porting::getDisplayDensity(); diff --git a/src/client/renderingengine.h b/src/client/renderingengine.h index c9f7d9223..c5fa8918b 100644 --- a/src/client/renderingengine.h +++ b/src/client/renderingengine.h @@ -118,8 +118,7 @@ class RenderingEngine } inline static void draw_scene(video::SColor skycolor, bool show_hud, - bool show_minimap, bool draw_wield_tool, bool draw_crosshair, - bool draw_tracers, bool draw_esp) + bool show_minimap, bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, bool draw_esp) { s_singleton->_draw_scene(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair, draw_tracers, draw_esp); @@ -150,8 +149,7 @@ class RenderingEngine bool clouds = true); void _draw_scene(video::SColor skycolor, bool show_hud, bool show_minimap, - bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, - bool draw_esp); + bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, bool draw_esp); void _initialize(Client *client, Hud *hud); diff --git a/src/client/shader.cpp b/src/client/shader.cpp index 9e0b73696..ee6079f7a 100644 --- a/src/client/shader.cpp +++ b/src/client/shader.cpp @@ -52,7 +52,8 @@ MutexedMap g_shadername_to_path_cache; Utilizes a thread-safe cache. */ -std::string getShaderPath(const std::string &name_of_shader, const std::string &filename) +std::string getShaderPath(const std::string &name_of_shader, + const std::string &filename) { std::string combined = name_of_shader + DIR_DELIM + filename; std::string fullpath; @@ -60,7 +61,7 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string & Check from cache */ bool incache = g_shadername_to_path_cache.get(combined, &fullpath); - if (incache) + if(incache) return fullpath; /* @@ -69,7 +70,7 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string & std::string shader_path = g_settings->get("shader_path"); if (!shader_path.empty()) { std::string testpath = shader_path + DIR_DELIM + combined; - if (fs::PathExists(testpath)) + if(fs::PathExists(testpath)) fullpath = testpath; } @@ -77,10 +78,12 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string & Check from default data directory */ if (fullpath.empty()) { - std::string rel_path = std::string("client") + DIR_DELIM + "shaders" + - DIR_DELIM + name_of_shader + DIR_DELIM + filename; + std::string rel_path = std::string("client") + DIR_DELIM + + "shaders" + DIR_DELIM + + name_of_shader + DIR_DELIM + + filename; std::string testpath = porting::path_share + DIR_DELIM + rel_path; - if (fs::PathExists(testpath)) + if(fs::PathExists(testpath)) fullpath = testpath; } @@ -99,13 +102,13 @@ class SourceShaderCache { public: void insert(const std::string &name_of_shader, const std::string &filename, - const std::string &program, bool prefer_local) + const std::string &program, bool prefer_local) { std::string combined = name_of_shader + DIR_DELIM + filename; // Try to use local shader instead if asked to - if (prefer_local) { + if(prefer_local){ std::string path = getShaderPath(name_of_shader, filename); - if (!path.empty()) { + if(!path.empty()){ std::string p = readFile(path); if (!p.empty()) { m_programs[combined] = p; @@ -116,7 +119,8 @@ class SourceShaderCache m_programs[combined] = program; } - std::string get(const std::string &name_of_shader, const std::string &filename) + std::string get(const std::string &name_of_shader, + const std::string &filename) { std::string combined = name_of_shader + DIR_DELIM + filename; StringMap::iterator n = m_programs.find(combined); @@ -126,8 +130,8 @@ class SourceShaderCache } // Primarily fetches from cache, secondarily tries to read from filesystem - std::string getOrLoad( - const std::string &name_of_shader, const std::string &filename) + std::string getOrLoad(const std::string &name_of_shader, + const std::string &filename) { std::string combined = name_of_shader + DIR_DELIM + filename; StringMap::iterator n = m_programs.find(combined); @@ -135,13 +139,12 @@ class SourceShaderCache return n->second; std::string path = getShaderPath(name_of_shader, filename); if (path.empty()) { - infostream << "SourceShaderCache::getOrLoad(): No path found for " - "\"" - << combined << "\"" << std::endl; + infostream << "SourceShaderCache::getOrLoad(): No path found for \"" + << combined << "\"" << std::endl; return ""; } - infostream << "SourceShaderCache::getOrLoad(): Loading path \"" << path - << "\"" << std::endl; + infostream << "SourceShaderCache::getOrLoad(): Loading path \"" + << path << "\"" << std::endl; std::string p = readFile(path); if (!p.empty()) { m_programs[combined] = p; @@ -149,14 +152,13 @@ class SourceShaderCache } return ""; } - private: StringMap m_programs; std::string readFile(const std::string &path) { std::ifstream is(path.c_str(), std::ios::binary); - if (!is.is_open()) + if(!is.is_open()) return ""; std::ostringstream tmp_os; tmp_os << is.rdbuf(); @@ -164,13 +166,14 @@ class SourceShaderCache } }; + /* ShaderCallback: Sets constants that can be used in shaders */ class ShaderCallback : public video::IShaderConstantSetCallBack { - std::vector m_setters; + std::vector m_setters; public: ShaderCallback(const std::vector &factories) @@ -185,8 +188,7 @@ class ShaderCallback : public video::IShaderConstantSetCallBack delete setter; } - virtual void OnSetConstants( - video::IMaterialRendererServices *services, s32 userData) override + virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override { video::IVideoDriver *driver = services->getVideoDriver(); sanity_check(driver != NULL); @@ -197,13 +199,14 @@ class ShaderCallback : public video::IShaderConstantSetCallBack setter->onSetConstants(services, is_highlevel); } - virtual void OnSetMaterial(const video::SMaterial &material) override + virtual void OnSetMaterial(const video::SMaterial& material) override { for (IShaderConstantSetter *setter : m_setters) setter->onSetMaterial(material); } }; + /* MainShaderConstantSetter: Set basic constants required for almost everything */ @@ -215,13 +218,13 @@ class MainShaderConstantSetter : public IShaderConstantSetter public: MainShaderConstantSetter() : - m_world_view_proj("mWorldViewProj"), m_world("mWorld") - { - } + m_world_view_proj("mWorldViewProj"), + m_world("mWorld") + {} ~MainShaderConstantSetter() = default; - virtual void onSetConstants( - video::IMaterialRendererServices *services, bool is_highlevel) + virtual void onSetConstants(video::IMaterialRendererServices *services, + bool is_highlevel) { video::IVideoDriver *driver = services->getVideoDriver(); sanity_check(driver); @@ -232,28 +235,29 @@ class MainShaderConstantSetter : public IShaderConstantSetter worldViewProj *= driver->getTransform(video::ETS_VIEW); worldViewProj *= driver->getTransform(video::ETS_WORLD); if (is_highlevel) - m_world_view_proj.set(*reinterpret_cast( - worldViewProj.pointer()), - services); + m_world_view_proj.set(*reinterpret_cast(worldViewProj.pointer()), services); else services->setVertexShaderConstant(worldViewProj.pointer(), 0, 4); // Set world matrix core::matrix4 world = driver->getTransform(video::ETS_WORLD); if (is_highlevel) - m_world.set(*reinterpret_cast(world.pointer()), - services); + m_world.set(*reinterpret_cast(world.pointer()), services); else services->setVertexShaderConstant(world.pointer(), 4, 4); + } }; + class MainShaderConstantSetterFactory : public IShaderConstantSetterFactory { public: - virtual IShaderConstantSetter *create() { return new MainShaderConstantSetter(); } + virtual IShaderConstantSetter* create() + { return new MainShaderConstantSetter(); } }; + /* ShaderSource */ @@ -271,8 +275,8 @@ class ShaderSource : public IWritableShaderSource The id 0 points to a null shader. Its material is EMT_SOLID. */ - u32 getShaderIdDirect(const std::string &name, const u8 material_type, - const u8 drawtype); + u32 getShaderIdDirect(const std::string &name, + const u8 material_type, const u8 drawtype); /* If shader specified by the name pointed by the id doesn't @@ -283,7 +287,8 @@ class ShaderSource : public IWritableShaderSource for processing. */ - u32 getShader(const std::string &name, const u8 material_type, const u8 drawtype); + u32 getShader(const std::string &name, + const u8 material_type, const u8 drawtype); ShaderInfo getShaderInfo(u32 id); @@ -294,7 +299,7 @@ class ShaderSource : public IWritableShaderSource // Insert a shader program into the cache without touching the // filesystem. Shall be called from the main thread. void insertSourceShader(const std::string &name_of_shader, - const std::string &filename, const std::string &program); + const std::string &filename, const std::string &program); // Rebuild shaders from the current set of source shaders // Shall be called from the main thread. @@ -306,6 +311,7 @@ class ShaderSource : public IWritableShaderSource } private: + // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; @@ -337,8 +343,8 @@ IWritableShaderSource *createShaderSource() /* Generate shader given the shader name. */ -ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype, - std::vector &callbacks, +ShaderInfo generate_shader(const std::string &name, + u8 material_type, u8 drawtype, std::vector &callbacks, const std::vector &setter_factories, SourceShaderCache *sourcecache); @@ -371,8 +377,8 @@ ShaderSource::~ShaderSource() } } -u32 ShaderSource::getShader( - const std::string &name, const u8 material_type, const u8 drawtype) +u32 ShaderSource::getShader(const std::string &name, + const u8 material_type, const u8 drawtype) { /* Get shader @@ -394,15 +400,15 @@ u32 ShaderSource::getShader( /* infostream<<"Waiting for shader from main thread, name=\"" < result = result_queue.pop_frontNoEx(); + while(true) { + GetResult + result = result_queue.pop_frontNoEx(); if (result.key == name) { return result.item; } - errorstream << "Got shader with invalid name: " << result.key - << std::endl; + errorstream << "Got shader with invalid name: " << result.key << std::endl; } infostream << "getShader(): Failed" << std::endl; @@ -413,22 +419,22 @@ u32 ShaderSource::getShader( /* This method generates all the shaders */ -u32 ShaderSource::getShaderIdDirect( - const std::string &name, const u8 material_type, const u8 drawtype) +u32 ShaderSource::getShaderIdDirect(const std::string &name, + const u8 material_type, const u8 drawtype) { - // infostream<<"getShaderIdDirect(): name=\""<name == name && info->material_type == material_type && - info->drawtype == drawtype) + if(info->name == name && info->material_type == material_type && + info->drawtype == drawtype) return i; } @@ -436,14 +442,13 @@ u32 ShaderSource::getShaderIdDirect( Calling only allowed from main thread */ if (std::this_thread::get_id() != m_main_thread) { - errorstream << "ShaderSource::getShaderIdDirect() " - "called not from main thread" - << std::endl; + errorstream<<"ShaderSource::getShaderIdDirect() " + "called not from main thread"<= m_shaderinfo_cache.size()) + if(id >= m_shaderinfo_cache.size()) return ShaderInfo(); return m_shaderinfo_cache[id]; @@ -473,6 +478,8 @@ ShaderInfo ShaderSource::getShaderInfo(u32 id) void ShaderSource::processQueue() { + + } void ShaderSource::insertSourceShader(const std::string &name_of_shader, @@ -506,12 +513,13 @@ void ShaderSource::rebuildShaders() ShaderInfo *info = &i; if (!info->name.empty()) { *info = generate_shader(info->name, info->material_type, - info->drawtype, m_callbacks, m_setter_factories, - &m_sourcecache); + info->drawtype, m_callbacks, + m_setter_factories, &m_sourcecache); } } } + ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype, std::vector &callbacks, const std::vector &setter_factories, @@ -550,13 +558,11 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices(); - if (!gpu) { - errorstream << "generate_shader(): " - "failed to generate \"" - << name - << "\", " - "GPU programming not supported." - << std::endl; + if(!gpu){ + errorstream<<"generate_shader(): " + "failed to generate \""<getDriverType(), enable_shaders, - vertex_program, pixel_program, geometry_program, is_highlevel); + load_shaders(name, sourcecache, driver->getDriverType(), + enable_shaders, vertex_program, pixel_program, + geometry_program, is_highlevel); // Check hardware/driver support if (!vertex_program.empty() && !driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) && - !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1)) { - infostream << "generate_shader(): vertex shaders disabled " - "because of missing driver/hardware support." - << std::endl; + !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1)){ + infostream<<"generate_shader(): vertex shaders disabled " + "because of missing driver/hardware support." + <queryFeature(video::EVDF_PIXEL_SHADER_1_1) && - !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1)) { - infostream << "generate_shader(): pixel shaders disabled " - "because of missing driver/hardware support." - << std::endl; + !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1)){ + infostream<<"generate_shader(): pixel shaders disabled " + "because of missing driver/hardware support." + <queryFeature(video::EVDF_GEOMETRY_SHADER)) { - infostream << "generate_shader(): geometry shaders disabled " - "because of missing driver/hardware support." - << std::endl; + !driver->queryFeature(video::EVDF_GEOMETRY_SHADER)){ + infostream<<"generate_shader(): geometry shaders disabled " + "because of missing driver/hardware support." + <getFloat("normalmaps_smooth"); - switch (smooth) { + switch (smooth){ case 0: sample_step = 0.0078125; // 1.0 / 128.0 break; @@ -689,7 +696,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp if (g_settings->getBool("enable_bumpmapping")) shaders_header += "#define ENABLE_BUMPMAPPING\n"; - if (g_settings->getBool("enable_parallax_occlusion")) { + if (g_settings->getBool("enable_parallax_occlusion")){ int mode = g_settings->getFloat("parallax_occlusion_mode"); float scale = g_settings->getFloat("parallax_occlusion_scale"); float bias = g_settings->getFloat("parallax_occlusion_bias"); @@ -710,13 +717,12 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp } shaders_header += "#define USE_NORMALMAPS "; - if (g_settings->getBool("enable_bumpmapping") || - g_settings->getBool("enable_parallax_occlusion")) + if (g_settings->getBool("enable_bumpmapping") || g_settings->getBool("enable_parallax_occlusion")) shaders_header += "1\n"; else shaders_header += "0\n"; - if (g_settings->getBool("enable_waving_water")) { + if (g_settings->getBool("enable_waving_water")){ shaders_header += "#define ENABLE_WAVING_WATER 1\n"; shaders_header += "#define WATER_WAVE_HEIGHT "; shaders_header += ftos(g_settings->getFloat("water_wave_height")); @@ -727,7 +733,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp shaders_header += "#define WATER_WAVE_SPEED "; shaders_header += ftos(g_settings->getFloat("water_wave_speed")); shaders_header += "\n"; - } else { + } else{ shaders_header += "#define ENABLE_WAVING_WATER 0\n"; } @@ -751,9 +757,9 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp shaders_header += "\n"; // Call addHighLevelShaderMaterial() or addShaderMaterial() - const c8 *vertex_program_ptr = 0; - const c8 *pixel_program_ptr = 0; - const c8 *geometry_program_ptr = 0; + const c8* vertex_program_ptr = 0; + const c8* pixel_program_ptr = 0; + const c8* geometry_program_ptr = 0; if (!vertex_program.empty()) { vertex_program = shaders_header + vertex_program; vertex_program_ptr = vertex_program.c_str(); @@ -768,57 +774,54 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp } ShaderCallback *cb = new ShaderCallback(setter_factories); s32 shadermat = -1; - if (is_highlevel) { - infostream << "Compiling high level shaders for " << name << std::endl; + if(is_highlevel){ + infostream<<"Compiling high level shaders for "<addHighLevelShaderMaterial( - vertex_program_ptr, // Vertex shader program - "vertexMain", // Vertex shader entry point - video::EVST_VS_1_1, // Vertex shader version - pixel_program_ptr, // Pixel shader program - "pixelMain", // Pixel shader entry point - video::EPST_PS_1_2, // Pixel shader version - geometry_program_ptr, // Geometry shader program - "geometryMain", // Geometry shader entry point - video::EGST_GS_4_0, // Geometry shader version - scene::EPT_TRIANGLES, // Geometry shader input - scene::EPT_TRIANGLE_STRIP, // Geometry shader output - 0, // Support maximum number of vertices - cb, // Set-constant callback - shaderinfo.base_material, // Base material - 1 // Userdata passed to callback - ); - if (shadermat == -1) { - errorstream << "generate_shader(): " - "failed to generate \"" - << name - << "\", " - "addHighLevelShaderMaterial failed." - << std::endl; + vertex_program_ptr, // Vertex shader program + "vertexMain", // Vertex shader entry point + video::EVST_VS_1_1, // Vertex shader version + pixel_program_ptr, // Pixel shader program + "pixelMain", // Pixel shader entry point + video::EPST_PS_1_2, // Pixel shader version + geometry_program_ptr, // Geometry shader program + "geometryMain", // Geometry shader entry point + video::EGST_GS_4_0, // Geometry shader version + scene::EPT_TRIANGLES, // Geometry shader input + scene::EPT_TRIANGLE_STRIP, // Geometry shader output + 0, // Support maximum number of vertices + cb, // Set-constant callback + shaderinfo.base_material, // Base material + 1 // Userdata passed to callback + ); + if(shadermat == -1){ + errorstream<<"generate_shader(): " + "failed to generate \""<addShaderMaterial( - vertex_program_ptr, // Vertex shader program - pixel_program_ptr, // Pixel shader program - cb, // Set-constant callback - shaderinfo.base_material, // Base material - 0 // Userdata passed to callback - ); - - if (shadermat == -1) { - errorstream << "generate_shader(): " - "failed to generate \"" - << name - << "\", " - "addShaderMaterial failed." - << std::endl; + vertex_program_ptr, // Vertex shader program + pixel_program_ptr, // Pixel shader program + cb, // Set-constant callback + shaderinfo.base_material, // Base material + 0 // Userdata passed to callback + ); + + if(shadermat == -1){ + errorstream<<"generate_shader(): " + "failed to generate \""<getMaterialRenderer(shadermat)->grab(); // Apply the newly created material type - shaderinfo.material = (video::E_MATERIAL_TYPE)shadermat; + shaderinfo.material = (video::E_MATERIAL_TYPE) shadermat; return shaderinfo; } @@ -844,45 +847,43 @@ void load_shaders(const std::string &name, SourceShaderCache *sourcecache, geometry_program = ""; is_highlevel = false; - if (enable_shaders) { + if(enable_shaders){ // Look for high level shaders - if (drivertype == video::EDT_DIRECT3D9) { + if(drivertype == video::EDT_DIRECT3D9){ // Direct3D 9: HLSL // (All shaders in one file) vertex_program = sourcecache->getOrLoad(name, "d3d9.hlsl"); pixel_program = vertex_program; geometry_program = vertex_program; - } else if (drivertype == video::EDT_OPENGL) { + } + else if(drivertype == video::EDT_OPENGL){ // OpenGL: GLSL - vertex_program = sourcecache->getOrLoad( - name, "opengl_vertex.glsl"); - pixel_program = sourcecache->getOrLoad( - name, "opengl_fragment.glsl"); - geometry_program = sourcecache->getOrLoad( - name, "opengl_geometry.glsl"); + vertex_program = sourcecache->getOrLoad(name, "opengl_vertex.glsl"); + pixel_program = sourcecache->getOrLoad(name, "opengl_fragment.glsl"); + geometry_program = sourcecache->getOrLoad(name, "opengl_geometry.glsl"); } - if (!vertex_program.empty() || !pixel_program.empty() || - !geometry_program.empty()) { + if (!vertex_program.empty() || !pixel_program.empty() || !geometry_program.empty()){ is_highlevel = true; return; } } + } -void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type, - const std::string &program) +void dumpShaderProgram(std::ostream &output_stream, + const std::string &program_type, const std::string &program) { - output_stream << program_type << " shader program:" << std::endl - << "----------------------------------" << std::endl; + output_stream << program_type << " shader program:" << std::endl << + "----------------------------------" << std::endl; size_t pos = 0; size_t prev = 0; s16 line = 1; while ((pos = program.find('\n', prev)) != std::string::npos) { - output_stream << line++ << ": " << program.substr(prev, pos - prev) - << std::endl; + output_stream << line++ << ": "<< program.substr(prev, pos - prev) << + std::endl; prev = pos + 1; } - output_stream << line << ": " << program.substr(prev) << std::endl - << "End of " << program_type << " shader program." << std::endl - << " " << std::endl; + output_stream << line << ": " << program.substr(prev) << std::endl << + "End of " << program_type << " shader program." << std::endl << + " " << std::endl; } diff --git a/src/client/shader.h b/src/client/shader.h index 4d1578df0..109d39336 100644 --- a/src/client/shader.h +++ b/src/client/shader.h @@ -39,10 +39,10 @@ class IGameDef; Utilizes a thread-safe cache. */ -std::string getShaderPath(const std::string &name_of_shader, const std::string &filename); +std::string getShaderPath(const std::string &name_of_shader, + const std::string &filename); -struct ShaderInfo -{ +struct ShaderInfo { std::string name = ""; video::E_MATERIAL_TYPE base_material = video::EMT_SOLID; video::E_MATERIAL_TYPE material = video::EMT_SOLID; @@ -57,43 +57,38 @@ struct ShaderInfo Setter of constants for shaders */ -namespace irr -{ -namespace video -{ -class IMaterialRendererServices; -} -} +namespace irr { namespace video { + class IMaterialRendererServices; +} } -class IShaderConstantSetter -{ + +class IShaderConstantSetter { public: virtual ~IShaderConstantSetter() = default; virtual void onSetConstants(video::IMaterialRendererServices *services, bool is_highlevel) = 0; - virtual void onSetMaterial(const video::SMaterial &material) {} + virtual void onSetMaterial(const video::SMaterial& material) + { } }; -class IShaderConstantSetterFactory -{ + +class IShaderConstantSetterFactory { public: virtual ~IShaderConstantSetterFactory() = default; - virtual IShaderConstantSetter *create() = 0; + virtual IShaderConstantSetter* create() = 0; }; -template class CachedShaderSetting -{ + +template +class CachedShaderSetting { const char *m_name; T m_sent[count]; bool has_been_set = false; bool is_pixel; - protected: CachedShaderSetting(const char *name, bool is_pixel) : - m_name(name), is_pixel(is_pixel) - { - } - + m_name(name), is_pixel(is_pixel) + {} public: void set(const T value[count], video::IMaterialRendererServices *services) { @@ -109,75 +104,55 @@ template class CachedShaderSetting }; template -class CachedPixelShaderSetting : public CachedShaderSetting -{ +class CachedPixelShaderSetting : public CachedShaderSetting { public: CachedPixelShaderSetting(const char *name) : - CachedShaderSetting(name, true) - { - } + CachedShaderSetting(name, true){} }; template -class CachedVertexShaderSetting : public CachedShaderSetting -{ +class CachedVertexShaderSetting : public CachedShaderSetting { public: CachedVertexShaderSetting(const char *name) : - CachedShaderSetting(name, false) - { - } + CachedShaderSetting(name, false){} }; + /* ShaderSource creates and caches shaders. */ -class IShaderSource -{ +class IShaderSource { public: IShaderSource() = default; virtual ~IShaderSource() = default; - virtual u32 getShaderIdDirect(const std::string &name, const u8 material_type, - const u8 drawtype) - { - return 0; - } - virtual ShaderInfo getShaderInfo(u32 id) { return ShaderInfo(); } - virtual u32 getShader(const std::string &name, const u8 material_type, - const u8 drawtype) - { - return 0; - } + virtual u32 getShaderIdDirect(const std::string &name, + const u8 material_type, const u8 drawtype){return 0;} + virtual ShaderInfo getShaderInfo(u32 id){return ShaderInfo();} + virtual u32 getShader(const std::string &name, + const u8 material_type, const u8 drawtype){return 0;} }; -class IWritableShaderSource : public IShaderSource -{ +class IWritableShaderSource : public IShaderSource { public: IWritableShaderSource() = default; virtual ~IWritableShaderSource() = default; - virtual u32 getShaderIdDirect(const std::string &name, const u8 material_type, - const u8 drawtype) - { - return 0; - } - virtual ShaderInfo getShaderInfo(u32 id) { return ShaderInfo(); } - virtual u32 getShader(const std::string &name, const u8 material_type, - const u8 drawtype) - { - return 0; - } + virtual u32 getShaderIdDirect(const std::string &name, + const u8 material_type, const u8 drawtype){return 0;} + virtual ShaderInfo getShaderInfo(u32 id){return ShaderInfo();} + virtual u32 getShader(const std::string &name, + const u8 material_type, const u8 drawtype){return 0;} - virtual void processQueue() = 0; + virtual void processQueue()=0; virtual void insertSourceShader(const std::string &name_of_shader, - const std::string &filename, const std::string &program) = 0; - virtual void rebuildShaders() = 0; - virtual void addShaderConstantSetterFactory( - IShaderConstantSetterFactory *setter) = 0; + const std::string &filename, const std::string &program)=0; + virtual void rebuildShaders()=0; + virtual void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) = 0; }; IWritableShaderSource *createShaderSource(); -void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type, - const std::string &program); +void dumpShaderProgram(std::ostream &output_stream, + const std::string &program_type, const std::string &program); diff --git a/src/client/sky.cpp b/src/client/sky.cpp index fa36f623e..2e0cbca86 100644 --- a/src/client/sky.cpp +++ b/src/client/sky.cpp @@ -35,9 +35,8 @@ with this program; if not, write to the Free Software Foundation, Inc., using namespace irr::core; Sky::Sky(s32 id, ITextureSource *tsrc) : - scene::ISceneNode( - RenderingEngine::get_scene_manager()->getRootSceneNode(), - RenderingEngine::get_scene_manager(), id) + scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), + RenderingEngine::get_scene_manager(), id) { setAutomaticCulling(scene::EAC_OFF); m_box.MaxEdge.set(0, 0, 0); @@ -61,40 +60,33 @@ Sky::Sky(s32 id, ITextureSource *tsrc) : m_materials[0] = mat; m_materials[1] = mat; - // m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + //m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; m_materials[2] = mat; m_materials[2].setTexture(0, tsrc->getTextureForMesh("sunrisebg.png")); m_materials[2].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; - // m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR; + //m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR; // Ensures that sun and moon textures and tonemaps are correct. setSkyDefaults(); - m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture) - ? tsrc->getTextureForMesh(m_sun_params.texture) - : NULL; - m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture) - ? tsrc->getTextureForMesh(m_moon_params.texture) - : NULL; - m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) - ? tsrc->getTexture(m_sun_params.tonemap) - : NULL; - m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) - ? tsrc->getTexture(m_moon_params.tonemap) - : NULL; + m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture) ? + tsrc->getTextureForMesh(m_sun_params.texture) : NULL; + m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture) ? + tsrc->getTextureForMesh(m_moon_params.texture) : NULL; + m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ? + tsrc->getTexture(m_sun_params.tonemap) : NULL; + m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ? + tsrc->getTexture(m_moon_params.tonemap) : NULL; if (m_sun_texture) { m_materials[3] = mat; m_materials[3].setTexture(0, m_sun_texture); m_materials[3].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; // Disables texture filtering - m_materials[3].setFlag( - video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false); - m_materials[3].setFlag( - video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false); - m_materials[3].setFlag( - video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false); + m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false); + m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false); + m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false); // Use tonemaps if available if (m_sun_tonemap) m_materials[3].Lighting = true; @@ -104,12 +96,9 @@ Sky::Sky(s32 id, ITextureSource *tsrc) : m_materials[4].setTexture(0, m_moon_texture); m_materials[4].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; // Disables texture filtering - m_materials[4].setFlag( - video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false); - m_materials[4].setFlag( - video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false); - m_materials[4].setFlag( - video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false); + m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false); + m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false); + m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false); // Use tonemaps if available if (m_moon_tonemap) m_materials[4].Lighting = true; @@ -157,9 +146,9 @@ void Sky::render() if (m_sunlight_seen) { float sunsize = 0.07; video::SColorf suncolor_f(1, 1, 0, 1); - // suncolor_f.r = 1; - // suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5)); - // suncolor_f.b = MYMAX(0.0, m_brightness * 0.95); + //suncolor_f.r = 1; + //suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5)); + //suncolor_f.b = MYMAX(0.0, m_brightness * 0.95); video::SColorf suncolor2_f(1, 1, 1, 1); // The values below were probably meant to be suncolor2_f instead of a // reassignment of suncolor_f. However, the resulting colour was chosen @@ -177,8 +166,7 @@ void Sky::render() float wn = nightlength / 2; float wicked_time_of_day = 0; if (m_time_of_day > wn && m_time_of_day < 1.0 - wn) - wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + - 0.25; + wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + 0.25; else if (m_time_of_day < 0.5) wicked_time_of_day = m_time_of_day / wn * 0.25; else @@ -192,25 +180,22 @@ void Sky::render() video::SColor mooncolor2 = mooncolor2_f.toSColor(); // Calculate offset normalized to the X dimension of a 512x1 px tonemap - float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * - 511; + float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * 511; if (m_sun_tonemap) { - u8 *texels = (u8 *)m_sun_tonemap->lock(); - video::SColor *texel = - (video::SColor *)(texels + (u32)offset * 4); - video::SColor texel_color(255, texel->getRed(), texel->getGreen(), - texel->getBlue()); + u8 * texels = (u8 *)m_sun_tonemap->lock(); + video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4); + video::SColor texel_color (255, texel->getRed(), + texel->getGreen(), texel->getBlue()); m_sun_tonemap->unlock(); m_materials[3].EmissiveColor = texel_color; } if (m_moon_tonemap) { - u8 *texels = (u8 *)m_moon_tonemap->lock(); - video::SColor *texel = - (video::SColor *)(texels + (u32)offset * 4); - video::SColor texel_color(255, texel->getRed(), texel->getGreen(), - texel->getBlue()); + u8 * texels = (u8 *)m_moon_tonemap->lock(); + video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4); + video::SColor texel_color (255, texel->getRed(), + texel->getGreen(), texel->getBlue()); m_moon_tonemap->unlock(); m_materials[4].EmissiveColor = texel_color; } @@ -236,14 +221,10 @@ void Sky::render() driver->setMaterial(m_materials[j]); // Use 1.05 rather than 1.0 to avoid colliding with the // sun, moon and stars, as this is a background skybox. - vertices[0] = video::S3DVertex( - -1.05, -1.05, -1.05, 0, 0, 1, c, t, t); - vertices[1] = video::S3DVertex( - 1.05, -1.05, -1.05, 0, 0, 1, c, o, t); - vertices[2] = video::S3DVertex( - 1.05, 1.05, -1.05, 0, 0, 1, c, o, o); - vertices[3] = video::S3DVertex( - -1.05, 1.05, -1.05, 0, 0, 1, c, t, o); + vertices[0] = video::S3DVertex(-1.05, -1.05, -1.05, 0, 0, 1, c, t, t); + vertices[1] = video::S3DVertex( 1.05, -1.05, -1.05, 0, 0, 1, c, o, t); + vertices[2] = video::S3DVertex( 1.05, 1.05, -1.05, 0, 0, 1, c, o, o); + vertices[3] = video::S3DVertex(-1.05, 1.05, -1.05, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { if (j == 5) { // Top texture vertex.Pos.rotateYZBy(90); @@ -256,16 +237,14 @@ void Sky::render() } else if (j == 8) { // Right texture vertex.Pos.rotateXZBy(-90); } else if (j == 9) { // Front texture, do nothing - // Irrlicht doesn't like it when vertexes - // are left alone and not rotated for some - // reason. + // Irrlicht doesn't like it when vertexes are left + // alone and not rotated for some reason. vertex.Pos.rotateXZBy(0); - } else { // Back texture + } else {// Back texture vertex.Pos.rotateXZBy(180); } } - driver->drawIndexedTriangleFan( - &vertices[0], 4, indices, 2); + driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } } @@ -273,19 +252,15 @@ void Sky::render() if (m_visible) { driver->setMaterial(m_materials[1]); for (u32 j = 0; j < 4; j++) { - vertices[0] = video::S3DVertex( - -1, -0.02, -1, 0, 0, 1, m_bgcolor, t, t); - vertices[1] = video::S3DVertex( - 1, -0.02, -1, 0, 0, 1, m_bgcolor, o, t); - vertices[2] = video::S3DVertex( - 1, 0.45, -1, 0, 0, 1, m_skycolor, o, o); - vertices[3] = video::S3DVertex( - -1, 0.45, -1, 0, 0, 1, m_skycolor, t, o); + vertices[0] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, m_bgcolor, t, t); + vertices[1] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, m_bgcolor, o, t); + vertices[2] = video::S3DVertex( 1, 0.45, -1, 0, 0, 1, m_skycolor, o, o); + vertices[3] = video::S3DVertex(-1, 0.45, -1, 0, 0, 1, m_skycolor, t, o); for (video::S3DVertex &vertex : vertices) { if (j == 0) - // Don't switch - { - } else if (j == 1) + // Don't switch + {} + else if (j == 1) // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); else if (j == 2) @@ -295,8 +270,7 @@ void Sky::render() // Switch from -Z (south) to +Z (north) vertex.Pos.rotateXZBy(-180); } - driver->drawIndexedTriangleFan( - &vertices[0], 4, indices, 2); + driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } } @@ -312,15 +286,13 @@ void Sky::render() float mid = wicked_time_of_day < 0.5 ? mid1 : (1.0 - mid1); float a_ = 1.0f - std::fabs(wicked_time_of_day - mid) * 35.0f; float a = easeCurve(MYMAX(0, MYMIN(1, a_))); - // std::cerr<<"a_="<getTextureForMesh( + sunglow_texture.empty() ? "sunrisebg.png" : sunglow_texture) + ); } -void Sky::setMoonTexture( - std::string moon_texture, std::string moon_tonemap, ITextureSource *tsrc) +void Sky::setMoonTexture(std::string moon_texture, + std::string moon_tonemap, ITextureSource *tsrc) { // Ignore matching textures (with modifiers) entirely, // but lets at least update the tonemap before hand. m_moon_params.tonemap = moon_tonemap; - m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) - ? tsrc->getTexture(m_moon_params.tonemap) - : NULL; + m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ? + tsrc->getTexture(m_moon_params.tonemap) : NULL; m_materials[4].Lighting = !!m_moon_tonemap; if (m_moon_params.texture == moon_texture) @@ -945,18 +872,15 @@ void Sky::setMoonTexture( if (m_moon_texture) { m_materials[4] = m_materials[0]; m_materials[4].setTexture(0, m_moon_texture); - m_materials[4].MaterialType = - video::EMT_TRANSPARENT_ALPHA_CHANNEL; + m_materials[4].MaterialType = video:: + EMT_TRANSPARENT_ALPHA_CHANNEL; // Disables texture filtering m_materials[4].setFlag( - video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, - false); + video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false); m_materials[4].setFlag( - video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, - false); + video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false); m_materials[4].setFlag( - video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, - false); + video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false); } } else { m_moon_texture = nullptr; @@ -971,9 +895,11 @@ void Sky::setStarCount(u16 star_count, bool force_update) m_stars.clear(); // Rebuild the stars surrounding the camera for (u16 i = 0; i < star_count; i++) { - v3f star = v3f(myrand_range(-10000, 10000), - myrand_range(-10000, 10000), - myrand_range(-10000, 10000)); + v3f star = v3f( + myrand_range(-10000, 10000), + myrand_range(-10000, 10000), + myrand_range(-10000, 10000) + ); star.normalize(); m_stars.emplace_back(star); @@ -986,8 +912,8 @@ void Sky::setSkyColors(const SkyColor &sky_color) m_sky_params.sky_color = sky_color; } -void Sky::setHorizonTint( - video::SColor sun_tint, video::SColor moon_tint, std::string use_sun_tint) +void Sky::setHorizonTint(video::SColor sun_tint, video::SColor moon_tint, + std::string use_sun_tint) { // Change sun and moon tinting: m_sky_params.fog_sun_tint = sun_tint; @@ -1001,7 +927,8 @@ void Sky::setHorizonTint( m_default_tint = true; } -void Sky::addTextureToSkybox(std::string texture, int material_id, ITextureSource *tsrc) +void Sky::addTextureToSkybox(std::string texture, int material_id, + ITextureSource *tsrc) { // Sanity check for more than six textures. if (material_id + 5 >= SKY_MATERIAL_COUNT) @@ -1009,9 +936,9 @@ void Sky::addTextureToSkybox(std::string texture, int material_id, ITextureSourc // Keep a list of texture names handy. m_sky_params.textures.emplace_back(texture); video::ITexture *result = tsrc->getTextureForMesh(texture); - m_materials[material_id + 5] = m_materials[0]; - m_materials[material_id + 5].setTexture(0, result); - m_materials[material_id + 5].MaterialType = video::EMT_SOLID; + m_materials[material_id+5] = m_materials[0]; + m_materials[material_id+5].setTexture(0, result); + m_materials[material_id+5].MaterialType = video::EMT_SOLID; } // To be called once at game init to setup default values. diff --git a/src/client/sky.h b/src/client/sky.h index 8983c3775..3227e8f59 100644 --- a/src/client/sky.h +++ b/src/client/sky.h @@ -63,29 +63,20 @@ class Sky : public scene::ISceneNode } void setSunVisible(bool sun_visible) { m_sun_params.visible = sun_visible; } - void setSunTexture(std::string sun_texture, std::string sun_tonemap, - ITextureSource *tsrc); + void setSunTexture(std::string sun_texture, + std::string sun_tonemap, ITextureSource *tsrc); void setSunScale(f32 sun_scale) { m_sun_params.scale = sun_scale; } - void setSunriseVisible(bool glow_visible) - { - m_sun_params.sunrise_visible = glow_visible; - } - void setSunriseTexture(std::string sunglow_texture, ITextureSource *tsrc); + void setSunriseVisible(bool glow_visible) { m_sun_params.sunrise_visible = glow_visible; } + void setSunriseTexture(std::string sunglow_texture, ITextureSource* tsrc); void setMoonVisible(bool moon_visible) { m_moon_params.visible = moon_visible; } - void setMoonTexture(std::string moon_texture, std::string moon_tonemap, - ITextureSource *tsrc); + void setMoonTexture(std::string moon_texture, + std::string moon_tonemap, ITextureSource *tsrc); void setMoonScale(f32 moon_scale) { m_moon_params.scale = moon_scale; } - void setStarsVisible(bool stars_visible) - { - m_star_params.visible = stars_visible; - } + void setStarsVisible(bool stars_visible) { m_star_params.visible = stars_visible; } void setStarCount(u16 star_count, bool force_update); - void setStarColor(video::SColor star_color) - { - m_star_params.starcolor = star_color; - } + void setStarColor(video::SColor star_color) { m_star_params.starcolor = star_color; } void setStarScale(f32 star_scale) { m_star_params.scale = star_scale; } bool getCloudsVisible() const { return m_clouds_visible && m_clouds_enabled; } @@ -105,12 +96,11 @@ class Sky : public scene::ISceneNode } void setSkyColors(const SkyColor &sky_color); void setHorizonTint(video::SColor sun_tint, video::SColor moon_tint, - std::string use_sun_tint); + std::string use_sun_tint); void setInClouds(bool clouds) { m_in_clouds = clouds; } void clearSkyboxTextures() { m_sky_params.textures.clear(); } - void addTextureToSkybox( - std::string texture, int material_id, ITextureSource *tsrc); - + void addTextureToSkybox(std::string texture, int material_id, + ITextureSource *tsrc); private: aabb3f m_box; video::SMaterial m_materials[SKY_MATERIAL_COUNT]; @@ -175,8 +165,11 @@ class Sky : public scene::ISceneNode // pure white: becomes "diffuse light component" for clouds video::SColorf m_cloudcolor_day_f = video::SColorf(1, 1, 1, 1); // dawn-factoring version of pure white (note: R is above 1.0) - video::SColorf m_cloudcolor_dawn_f = - video::SColorf(255.0f / 240.0f, 223.0f / 240.0f, 191.0f / 255.0f); + video::SColorf m_cloudcolor_dawn_f = video::SColorf( + 255.0f/240.0f, + 223.0f/240.0f, + 191.0f/255.0f + ); SkyboxParams m_sky_params; SunParams m_sun_params; @@ -192,16 +185,14 @@ class Sky : public scene::ISceneNode video::ITexture *m_sun_tonemap; video::ITexture *m_moon_tonemap; - void draw_sun(video::IVideoDriver *driver, float sunsize, - const video::SColor &suncolor, const video::SColor &suncolor2, - float wicked_time_of_day); - void draw_moon(video::IVideoDriver *driver, float moonsize, - const video::SColor &mooncolor, const video::SColor &mooncolor2, - float wicked_time_of_day); - void draw_sky_body(std::array &vertices, float pos_1, - float pos_2, const video::SColor &c); + void draw_sun(video::IVideoDriver *driver, float sunsize, const video::SColor &suncolor, + const video::SColor &suncolor2, float wicked_time_of_day); + void draw_moon(video::IVideoDriver *driver, float moonsize, const video::SColor &mooncolor, + const video::SColor &mooncolor2, float wicked_time_of_day); + void draw_sky_body(std::array &vertices, + float pos_1, float pos_2, const video::SColor &c); void draw_stars(video::IVideoDriver *driver, float wicked_time_of_day); void place_sky_body(std::array &vertices, - float horizon_position, float day_position); + float horizon_position, float day_position); void setSkyDefaults(); }; diff --git a/src/client/sound_openal.cpp b/src/client/sound_openal.cpp index 7cc16d8d7..20a651c1d 100644 --- a/src/client/sound_openal.cpp +++ b/src/client/sound_openal.cpp @@ -24,17 +24,17 @@ with this program; ifnot, write to the Free Software Foundation, Inc., #include "sound_openal.h" #if defined(_WIN32) -#include -#include -//#include + #include + #include + //#include #elif defined(__APPLE__) -#include -#include -//#include + #include + #include + //#include #else -#include -#include -#include + #include + #include + #include #endif #include #include @@ -52,7 +52,7 @@ with this program; ifnot, write to the Free Software Foundation, Inc., std::shared_ptr g_sound_manager_singleton; typedef std::unique_ptr unique_ptr_alcdevice; -typedef std::unique_ptr unique_ptr_alccontext; +typedef std::unique_ptr unique_ptr_alccontext; static void delete_alcdevice(ALCdevice *p) { @@ -90,9 +90,9 @@ static const char *alErrorString(ALenum err) static ALenum warn_if_error(ALenum err, const char *desc) { - if (err == AL_NO_ERROR) + if(err == AL_NO_ERROR) return err; - warningstream << desc << ": " << alErrorString(err) << std::endl; + warningstream< buffer; }; -SoundBuffer *load_opened_ogg_file( - OggVorbis_File *oggFile, const std::string &filename_for_logging) +SoundBuffer *load_opened_ogg_file(OggVorbis_File *oggFile, + const std::string &filename_for_logging) { int endian = 0; // 0 for Little-Endian, 1 for Big-Endian int bitStream; @@ -126,7 +126,7 @@ SoundBuffer *load_opened_ogg_file( pInfo = ov_info(oggFile, -1); // Check the number of channels... always use 16-bit samples - if (pInfo->channels == 1) + if(pInfo->channels == 1) snd->format = AL_FORMAT_MONO16; else snd->format = AL_FORMAT_STEREO16; @@ -135,14 +135,16 @@ SoundBuffer *load_opened_ogg_file( snd->freq = pInfo->rate; // Keep reading until all is read - do { + do + { // Read up to a buffer's worth of decoded sound data bytes = ov_read(oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream); - if (bytes < 0) { + if(bytes < 0) + { ov_clear(oggFile); - infostream << "Audio: Error decoding " << filename_for_logging - << std::endl; + infostream << "Audio: Error decoding " + << filename_for_logging << std::endl; delete snd; return nullptr; } @@ -152,17 +154,18 @@ SoundBuffer *load_opened_ogg_file( } while (bytes > 0); alGenBuffers(1, &snd->buffer_id); - alBufferData(snd->buffer_id, snd->format, &(snd->buffer[0]), snd->buffer.size(), + alBufferData(snd->buffer_id, snd->format, + &(snd->buffer[0]), snd->buffer.size(), snd->freq); ALenum error = alGetError(); - if (error != AL_NO_ERROR) { + if(error != AL_NO_ERROR){ infostream << "Audio: OpenAL error: " << alErrorString(error) - << "preparing sound buffer" << std::endl; + << "preparing sound buffer" << std::endl; } - // infostream << "Audio file " + //infostream << "Audio file " // << filename_for_logging << " loaded" << std::endl; // Clean up! @@ -179,16 +182,15 @@ SoundBuffer *load_ogg_from_file(const std::string &path) // This requires libvorbis >= 1.3.2, as // previous versions expect a non-const char * if (ov_fopen(path.c_str(), &oggFile) != 0) { - infostream << "Audio: Error opening " << path << " for decoding" - << std::endl; + infostream << "Audio: Error opening " << path + << " for decoding" << std::endl; return nullptr; } return load_opened_ogg_file(&oggFile, path); } -struct BufferSource -{ +struct BufferSource { const char *buf; size_t cur_offset; size_t len; @@ -214,8 +216,8 @@ int buffer_sound_seek_func(void *datasource, ogg_int64_t offset, int whence) s->cur_offset = offset; return 0; } else if (whence == SEEK_CUR) { - if ((size_t)MYMIN(-offset, 0) > s->cur_offset || - s->cur_offset + offset > s->len) { + if ((size_t)MYMIN(-offset, 0) > s->cur_offset + || s->cur_offset + offset > s->len) { // offset out of bounds return -1; } @@ -232,8 +234,12 @@ long BufferSourceell_func(void *datasource) return s->cur_offset; } -static ov_callbacks g_buffer_ov_callbacks = {&buffer_sound_read_func, - &buffer_sound_seek_func, nullptr, &BufferSourceell_func}; +static ov_callbacks g_buffer_ov_callbacks = { + &buffer_sound_read_func, + &buffer_sound_seek_func, + nullptr, + &BufferSourceell_func +}; SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_for_log) { @@ -245,8 +251,8 @@ SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_ s.len = buf.size(); if (ov_open_callbacks(&s, &oggFile, nullptr, 0, g_buffer_ov_callbacks) != 0) { - infostream << "Audio: Error opening " << id_for_log << " for decoding" - << std::endl; + infostream << "Audio: Error opening " << id_for_log + << " for decoding" << std::endl; return nullptr; } @@ -262,54 +268,43 @@ struct PlayingSound class SoundManagerSingleton { public: - unique_ptr_alcdevice m_device; + unique_ptr_alcdevice m_device; unique_ptr_alccontext m_context; - public: SoundManagerSingleton() : - m_device(nullptr, delete_alcdevice), - m_context(nullptr, delete_alccontext) + m_device(nullptr, delete_alcdevice), + m_context(nullptr, delete_alccontext) { } bool init() { - if (!(m_device = unique_ptr_alcdevice( - alcOpenDevice(nullptr), delete_alcdevice))) { - errorstream << "Audio: Global Initialization: Failed to open " - "device" - << std::endl; + if (!(m_device = unique_ptr_alcdevice(alcOpenDevice(nullptr), delete_alcdevice))) { + errorstream << "Audio: Global Initialization: Failed to open device" << std::endl; return false; } if (!(m_context = unique_ptr_alccontext( - alcCreateContext(m_device.get(), nullptr), - delete_alccontext))) { - errorstream << "Audio: Global Initialization: Failed to create " - "context" - << std::endl; + alcCreateContext(m_device.get(), nullptr), delete_alccontext))) { + errorstream << "Audio: Global Initialization: Failed to create context" << std::endl; return false; } if (!alcMakeContextCurrent(m_context.get())) { - errorstream << "Audio: Global Initialization: Failed to make " - "current context" - << std::endl; + errorstream << "Audio: Global Initialization: Failed to make current context" << std::endl; return false; } alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); if (alGetError() != AL_NO_ERROR) { - errorstream << "Audio: Global Initialization: OpenAL Error " - << alGetError() << std::endl; + errorstream << "Audio: Global Initialization: OpenAL Error " << alGetError() << std::endl; return false; } - infostream << "Audio: Global Initialized: OpenAL " - << alGetString(AL_VERSION) << ", using " - << alcGetString(m_device.get(), ALC_DEVICE_SPECIFIER) - << std::endl; + infostream << "Audio: Global Initialized: OpenAL " << alGetString(AL_VERSION) + << ", using " << alcGetString(m_device.get(), ALC_DEVICE_SPECIFIER) + << std::endl; return true; } @@ -320,24 +315,22 @@ class SoundManagerSingleton } }; -class OpenALSoundManager : public ISoundManager +class OpenALSoundManager: public ISoundManager { private: OnDemandSoundFetcher *m_fetcher; ALCdevice *m_device; ALCcontext *m_context; int m_next_id; - std::unordered_map> m_buffers; - std::unordered_map m_sounds_playing; - struct FadeState - { + std::unordered_map> m_buffers; + std::unordered_map m_sounds_playing; + struct FadeState { FadeState() = default; - FadeState(float step, float current_gain, float target_gain) : - step(step), current_gain(current_gain), - target_gain(target_gain) - { - } + FadeState(float step, float current_gain, float target_gain): + step(step), + current_gain(current_gain), + target_gain(target_gain) {} float step; float current_gain; float target_gain; @@ -345,11 +338,13 @@ class OpenALSoundManager : public ISoundManager std::unordered_map m_sounds_fading; float m_fade_delay; - public: - OpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher) : - m_fetcher(fetcher), m_device(smg->m_device.get()), - m_context(smg->m_context.get()), m_next_id(1), m_fade_delay(0) + OpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher): + m_fetcher(fetcher), + m_device(smg->m_device.get()), + m_context(smg->m_context.get()), + m_next_id(1), + m_fade_delay(0) { infostream << "Audio: Initialized: OpenAL " << std::endl; } @@ -377,34 +372,37 @@ class OpenALSoundManager : public ISoundManager infostream << "Audio: Deinitialized." << std::endl; } - void step(float dtime) { doFades(dtime); } + void step(float dtime) + { + doFades(dtime); + } void addBuffer(const std::string &name, SoundBuffer *buf) { - std::unordered_map>::iterator i = + std::unordered_map>::iterator i = m_buffers.find(name); - if (i != m_buffers.end()) { + if(i != m_buffers.end()){ i->second.push_back(buf); return; } - std::vector bufs; + std::vector bufs; bufs.push_back(buf); m_buffers[name] = bufs; } - SoundBuffer *getBuffer(const std::string &name) + SoundBuffer* getBuffer(const std::string &name) { - std::unordered_map>::iterator i = + std::unordered_map>::iterator i = m_buffers.find(name); - if (i == m_buffers.end()) + if(i == m_buffers.end()) return nullptr; - std::vector &bufs = i->second; + std::vector &bufs = i->second; int j = myrand() % bufs.size(); return bufs[j]; } - PlayingSound *createPlayingSound( - SoundBuffer *buf, bool loop, float volume, float pitch) + PlayingSound* createPlayingSound(SoundBuffer *buf, bool loop, + float volume, float pitch) { infostream << "OpenALSoundManager: Creating playing sound" << std::endl; assert(buf); @@ -425,11 +423,11 @@ class OpenALSoundManager : public ISoundManager return sound; } - PlayingSound *createPlayingSoundAt( - SoundBuffer *buf, bool loop, float volume, v3f pos, float pitch) + PlayingSound* createPlayingSoundAt(SoundBuffer *buf, bool loop, + float volume, v3f pos, float pitch) { infostream << "OpenALSoundManager: Creating positional playing sound" - << std::endl; + << std::endl; assert(buf); PlayingSound *sound = new PlayingSound; assert(sound); @@ -458,7 +456,7 @@ class OpenALSoundManager : public ISoundManager { assert(buf); PlayingSound *sound = createPlayingSound(buf, loop, volume, pitch); - if (!sound) + if(!sound) return -1; int id = m_next_id++; m_sounds_playing[id] = sound; @@ -470,7 +468,7 @@ class OpenALSoundManager : public ISoundManager { assert(buf); PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos, pitch); - if (!sound) + if(!sound) return -1; int id = m_next_id++; m_sounds_playing[id] = sound; @@ -479,9 +477,8 @@ class OpenALSoundManager : public ISoundManager void deleteSound(int id) { - std::unordered_map::iterator i = - m_sounds_playing.find(id); - if (i == m_sounds_playing.end()) + std::unordered_map::iterator i = m_sounds_playing.find(id); + if(i == m_sounds_playing.end()) return; PlayingSound *sound = i->second; @@ -492,12 +489,12 @@ class OpenALSoundManager : public ISoundManager } /* If buffer does not exist, consult the fetcher */ - SoundBuffer *getFetchBuffer(const std::string &name) + SoundBuffer* getFetchBuffer(const std::string &name) { SoundBuffer *buf = getBuffer(name); - if (buf) + if(buf) return buf; - if (!m_fetcher) + if(!m_fetcher) return nullptr; std::set paths; std::set datas; @@ -516,9 +513,8 @@ class OpenALSoundManager : public ISoundManager { if (!m_sounds_playing.empty()) { verbosestream << "OpenALSoundManager::maintain(): " - << m_sounds_playing.size() << " playing sounds, " - << m_buffers.size() << " sound names loaded" - << std::endl; + << m_sounds_playing.size() <<" playing sounds, " + << m_buffers.size() <<" sound names loaded"< del_list; for (const auto &sp : m_sounds_playing) { @@ -528,15 +524,14 @@ class OpenALSoundManager : public ISoundManager { ALint state; alGetSourcei(sound->source_id, AL_SOURCE_STATE, &state); - if (state != AL_PLAYING) { + if(state != AL_PLAYING){ del_list.insert(id); } } } - if (!del_list.empty()) - verbosestream << "OpenALSoundManager::maintain(): deleting " - << del_list.size() << " playing sounds" - << std::endl; + if(!del_list.empty()) + verbosestream<<"OpenALSoundManager::maintain(): deleting " + <second.step < 0.f) chkGain = -(i->second.current_gain); else @@ -637,8 +636,7 @@ class OpenALSoundManager : public ISoundManager if (chkGain < i->second.target_gain) { i->second.current_gain += (i->second.step * m_fade_delay); - i->second.current_gain = - rangelim(i->second.current_gain, 0, 1); + i->second.current_gain = rangelim(i->second.current_gain, 0, 1); updateSoundGain(i->first, i->second.current_gain); ++i; @@ -704,8 +702,7 @@ std::shared_ptr createSoundManagerSingleton() return smg; } -ISoundManager *createOpenALSoundManager( - SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher) +ISoundManager *createOpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher) { return new OpenALSoundManager(smg, fetcher); }; diff --git a/src/client/tile.cpp b/src/client/tile.cpp index dd159e909..d03588b2b 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -34,6 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiscalingfilter.h" #include "renderingengine.h" + #if ENABLE_GLES #ifdef _IRR_COMPILE_WITH_OGLES1_ #include @@ -61,8 +62,10 @@ static bool replace_ext(std::string &path, const char *ext) return false; // Find place of last dot, fail if \ or / found. s32 last_dot_i = -1; - for (s32 i = path.size() - 1; i >= 0; i--) { - if (path[i] == '.') { + for (s32 i=path.size()-1; i>=0; i--) + { + if (path[i] == '.') + { last_dot_i = i; break; } @@ -74,7 +77,7 @@ static bool replace_ext(std::string &path, const char *ext) if (last_dot_i == -1) return false; // Else make the new path - path = path.substr(0, last_dot_i + 1) + ext; + path = path.substr(0, last_dot_i+1) + ext; return true; } @@ -87,20 +90,24 @@ static bool replace_ext(std::string &path, const char *ext) std::string getImagePath(std::string path) { // A NULL-ended list of possible image extensions - const char *extensions[] = {"png", "jpg", "bmp", "tga", "pcx", "ppm", "psd", - "wal", "rgb", NULL}; + const char *extensions[] = { + "png", "jpg", "bmp", "tga", + "pcx", "ppm", "psd", "wal", "rgb", + NULL + }; // If there is no extension, add one if (removeStringEnd(path, extensions).empty()) path = path + ".png"; // Check paths until something is found to exist const char **ext = extensions; - do { + do{ bool r = replace_ext(path, *ext); if (!r) return ""; if (fs::PathExists(path)) return path; - } while ((++ext) != NULL); + } + while((++ext) != NULL); return ""; } @@ -145,9 +152,10 @@ std::string getTexturePath(const std::string &filename, bool *is_base_pack) /* Check from default data directory */ - if (fullpath.empty()) { - std::string base_path = porting::path_share + DIR_DELIM + "textures" + - DIR_DELIM + "base" + DIR_DELIM + "pack"; + if (fullpath.empty()) + { + std::string base_path = porting::path_share + DIR_DELIM + "textures" + + DIR_DELIM + "base" + DIR_DELIM + "pack"; std::string testpath = base_path + DIR_DELIM + filename; // Check all filename extensions. Returns "" if not found. fullpath = getImagePath(testpath); @@ -176,8 +184,12 @@ struct TextureInfo std::string name; video::ITexture *texture; - TextureInfo(const std::string &name_, video::ITexture *texture_ = NULL) : - name(name_), texture(texture_) + TextureInfo( + const std::string &name_, + video::ITexture *texture_=NULL + ): + name(name_), + texture(texture_) { } }; @@ -189,8 +201,7 @@ struct TextureInfo class SourceImageCache { public: - ~SourceImageCache() - { + ~SourceImageCache() { for (auto &m_image : m_images) { m_image.second->drop(); } @@ -200,14 +211,14 @@ class SourceImageCache { assert(img); // Pre-condition // Remove old image - std::map::iterator n; + std::map::iterator n; n = m_images.find(name); - if (n != m_images.end()) { + if (n != m_images.end()){ if (n->second) n->second->drop(); } - video::IImage *toadd = img; + video::IImage* toadd = img; bool need_to_grab = true; // Try to use local texture instead if asked to @@ -216,11 +227,9 @@ class SourceImageCache std::string path = getTexturePath(name, &is_base_pack); // Ignore base pack if (!path.empty() && !is_base_pack) { - video::IImage *img2 = - RenderingEngine::get_video_driver() - ->createImageFromFile( - path.c_str()); - if (img2) { + video::IImage *img2 = RenderingEngine::get_video_driver()-> + createImageFromFile(path.c_str()); + if (img2){ toadd = img2; need_to_grab = false; } @@ -231,9 +240,9 @@ class SourceImageCache toadd->grab(); m_images[name] = toadd; } - video::IImage *get(const std::string &name) + video::IImage* get(const std::string &name) { - std::map::iterator n; + std::map::iterator n; n = m_images.find(name); if (n != m_images.end()) return n->second; @@ -242,33 +251,31 @@ class SourceImageCache // Primarily fetches from cache, secondarily tries to read from filesystem video::IImage *getOrLoad(const std::string &name) { - std::map::iterator n; + std::map::iterator n; n = m_images.find(name); - if (n != m_images.end()) { + if (n != m_images.end()){ n->second->grab(); // Grab for caller return n->second; } video::IVideoDriver *driver = RenderingEngine::get_video_driver(); std::string path = getTexturePath(name); if (path.empty()) { - infostream << "SourceImageCache::getOrLoad(): No path found for " - "\"" - << name << "\"" << std::endl; + infostream<<"SourceImageCache::getOrLoad(): No path found for \"" + <createImageFromFile(path.c_str()); - if (img) { + if (img){ m_images[name] = img; img->grab(); // Grab for caller } return img; } - private: - std::map m_images; + std::map m_images; }; /* @@ -333,9 +340,9 @@ class TextureSource : public IWritableTextureSource and not found in cache, the call is queued to the main thread for processing. */ - video::ITexture *getTexture(u32 id); + video::ITexture* getTexture(u32 id); - video::ITexture *getTexture(const std::string &name, u32 *id = NULL); + video::ITexture* getTexture(const std::string &name, u32 *id = NULL); /* Get a texture specifically intended for mesh @@ -343,9 +350,9 @@ class TextureSource : public IWritableTextureSource use. This texture may be a different size and may have had additional filters applied. */ - video::ITexture *getTextureForMesh(const std::string &name, u32 *id); + video::ITexture* getTextureForMesh(const std::string &name, u32 *id); - virtual Palette *getPalette(const std::string &name); + virtual Palette* getPalette(const std::string &name); bool isKnownSourceImage(const std::string &name) { @@ -371,11 +378,12 @@ class TextureSource : public IWritableTextureSource // Shall be called from the main thread. void rebuildImagesAndTextures(); - video::ITexture *getNormalTexture(const std::string &name); + video::ITexture* getNormalTexture(const std::string &name); video::SColor getTextureAverageColor(const std::string &name); video::ITexture *getShaderFlagsTexture(bool normamap_present); private: + // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; @@ -388,14 +396,14 @@ class TextureSource : public IWritableTextureSource // Generate image based on a string like "stone.png" or "[crack:1:0". // if baseimg is NULL, it is created. Otherwise stuff is made on it. - bool generateImagePart(std::string part_of_name, video::IImage *&baseimg); + bool generateImagePart(std::string part_of_name, video::IImage *& baseimg); /*! Generates an image from a full string like * "stone.png^mineral_coal.png^[crack:1:0". * Shall be called from the main thread. * The returned Image should be dropped. */ - video::IImage *generateImage(const std::string &name); + video::IImage* generateImage(const std::string &name); // Thread-safe cache of what source images are known (true = known) MutexedMap m_source_image_existence; @@ -413,7 +421,7 @@ class TextureSource : public IWritableTextureSource // Textures that have been overwritten with other ones // but can't be deleted because the ITexture* might still be used - std::vector m_texture_trash; + std::vector m_texture_trash; // Maps image file names to loaded palettes. std::unordered_map m_palettes; @@ -452,24 +460,24 @@ TextureSource::~TextureSource() unsigned int textures_before = driver->getTextureCount(); for (const auto &iter : m_textureinfo_cache) { - // cleanup texture + //cleanup texture if (iter.texture) driver->removeTexture(iter.texture); } m_textureinfo_cache.clear(); for (auto t : m_texture_trash) { - // cleanup trashed texture + //cleanup trashed texture driver->removeTexture(t); } - infostream << "~TextureSource() before cleanup: " << textures_before - << " after: " << driver->getTextureCount() << std::endl; + infostream << "~TextureSource() before cleanup: "<< textures_before + << " after: " << driver->getTextureCount() << std::endl; } u32 TextureSource::getTextureId(const std::string &name) { - // infostream<<"getTextureId(): \""<::iterator n; n = m_name_to_id.find(name); - if (n != m_name_to_id.end()) { + if (n != m_name_to_id.end()) + { return n->second; } } @@ -490,7 +499,8 @@ u32 TextureSource::getTextureId(const std::string &name) return generateTexture(name); } - infostream << "getTextureId(): Queued: name=\"" << name << "\"" << std::endl; + + infostream<<"getTextureId(): Queued: name=\""< result_queue; @@ -499,18 +509,17 @@ u32 TextureSource::getTextureId(const std::string &name) m_get_texture_queue.add(name, 0, 0, &result_queue); try { - while (true) { + while(true) { // Wait result for a second - GetResult result = - result_queue.pop_front(1000); + GetResult + result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } - } catch (ItemNotFoundException &e) { - errorstream << "Waiting for texture " << name << " timed out." - << std::endl; + } catch(ItemNotFoundException &e) { + errorstream << "Waiting for texture " << name << " timed out." << std::endl; return 0; } @@ -521,13 +530,13 @@ u32 TextureSource::getTextureId(const std::string &name) // Draw an image on top of an another one, using the alpha channel of the // source image -static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos, - v2s32 dst_pos, v2u32 size); +static void blit_with_alpha(video::IImage *src, video::IImage *dst, + v2s32 src_pos, v2s32 dst_pos, v2u32 size); // Like blit_with_alpha, but only modifies destination pixels that // are fully opaque -static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, - v2s32 dst_pos, v2u32 size); +static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, + v2s32 src_pos, v2s32 dst_pos, v2u32 size); // Apply a color to an image. Uses an int (0-255) to calculate the ratio. // If the ratio is 255 or -1 and keep_alpha is true, then it multiples the @@ -541,18 +550,18 @@ static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color); // Apply a mask to an image -static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos, - v2s32 dst_pos, v2u32 size); +static void apply_mask(video::IImage *mask, video::IImage *dst, + v2s32 mask_pos, v2s32 dst_pos, v2u32 size); // Draw or overlay a crack -static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay, - s32 frame_count, s32 progression, video::IVideoDriver *driver, - u8 tiles = 1); +static void draw_crack(video::IImage *crack, video::IImage *dst, + bool use_overlay, s32 frame_count, s32 progression, + video::IVideoDriver *driver, u8 tiles = 1); // Brighten image void brighten(video::IImage *image); // Parse a transform name -u32 parseImageTransform(const std::string &s); +u32 parseImageTransform(const std::string& s); // Apply transform to image dimension core::dimension2d imageTransformDimension(u32 transform, core::dimension2d dim); // Apply transform to image data @@ -563,11 +572,11 @@ void imageTransform(u32 transform, video::IImage *src, video::IImage *dst); */ u32 TextureSource::generateTexture(const std::string &name) { - // infostream << "generateTexture(): name=\"" << name << "\"" << std::endl; + //infostream << "generateTexture(): name=\"" << name << "\"" << std::endl; // Empty name means texture 0 if (name.empty()) { - infostream << "generateTexture(): name is empty" << std::endl; + infostream<<"generateTexture(): name is empty"<= m_textureinfo_cache.size()) { - errorstream << "TextureSource::getTextureName(): id=" << id - << " >= m_textureinfo_cache.size()=" - << m_textureinfo_cache.size() << std::endl; + if (id >= m_textureinfo_cache.size()) + { + errorstream<<"TextureSource::getTextureName(): id="<= m_textureinfo_cache.size()=" + <getBool("texture_clean_transparent") || - ((m_setting_trilinear_filter || m_setting_bilinear_filter) && - g_settings->getS32("texture_min_size") > 1); + g_settings->getBool("texture_clean_transparent") || + ((m_setting_trilinear_filter || m_setting_bilinear_filter) && + g_settings->getS32("texture_min_size") > 1); // Avoid duplicating texture if it won't actually change if (filter_needed) return getTexture(name + "^[applyfiltersformesh", id); return getTexture(name, id); } -Palette *TextureSource::getPalette(const std::string &name) +Palette* TextureSource::getPalette(const std::string &name) { // Only the main thread may load images sanity_check(std::this_thread::get_id() == m_main_thread); @@ -683,7 +692,7 @@ Palette *TextureSource::getPalette(const std::string &name) video::IImage *img = generateImage(name); if (!img) { warningstream << "TextureSource::getPalette(): palette \"" << name - << "\" could not be loaded." << std::endl; + << "\" could not be loaded." << std::endl; return NULL; } Palette new_palette; @@ -695,15 +704,13 @@ Palette *TextureSource::getPalette(const std::string &name) return NULL; if (area > 256) { warningstream << "TextureSource::getPalette(): the specified" - << " palette image \"" << name - << "\" is larger than 256" - << " pixels, using the first 256." << std::endl; + << " palette image \"" << name << "\" is larger than 256" + << " pixels, using the first 256." << std::endl; area = 256; } else if (256 % area != 0) warningstream << "TextureSource::getPalette(): the " - << "specified palette image \"" << name - << "\" does not " - << "contain power of two pixels." << std::endl; + << "specified palette image \"" << name << "\" does not " + << "contain power of two pixels." << std::endl; // We stretch the palette so it will fit 256 values // This many param2 values will have the same color u32 step = 256 / area; @@ -731,9 +738,11 @@ void TextureSource::processQueue() /* Fetch textures */ - // NOTE this is only thread safe for ONE consumer thread! - if (!m_get_texture_queue.empty()) { - GetRequest request = m_get_texture_queue.pop(); + //NOTE this is only thread safe for ONE consumer thread! + if (!m_get_texture_queue.empty()) + { + GetRequest + request = m_get_texture_queue.pop(); /*infostream<<"TextureSource::processQueue(): " <<"got texture request with " @@ -746,7 +755,7 @@ void TextureSource::processQueue() void TextureSource::insertSourceImage(const std::string &name, video::IImage *img) { - // infostream<<"TextureSource::insertSourceImage(): name="<getDimension(); core::dimension2du size_left = left->getDimension(); core::dimension2du size_right = right->getDimension(); u32 size = npot2(std::max({ - size_top.Width, - size_top.Height, - size_left.Width, - size_left.Height, - size_right.Width, - size_right.Height, + size_top.Width, size_top.Height, + size_left.Width, size_left.Height, + size_right.Width, size_right.Height, })); // It must be divisible by 4, to let everything work correctly. @@ -822,14 +828,12 @@ static video::IImage *createInventoryCubeImage( video::IVideoDriver *driver = RenderingEngine::get_video_driver(); - auto lock_image = [size, driver](video::IImage *&image) -> const u32 * { + auto lock_image = [size, driver] (video::IImage *&image) -> const u32 * { image->grab(); core::dimension2du dim = image->getDimension(); video::ECOLOR_FORMAT format = image->getColorFormat(); - if (dim.Width != size || dim.Height != size || - format != video::ECF_A8R8G8B8) { - video::IImage *scaled = driver->createImage( - video::ECF_A8R8G8B8, {size, size}); + if (dim.Width != size || dim.Height != size || format != video::ECF_A8R8G8B8) { + video::IImage *scaled = driver->createImage(video::ECF_A8R8G8B8, {size, size}); image->copyToScaling(scaled); image->drop(); image = scaled; @@ -837,13 +841,12 @@ static video::IImage *createInventoryCubeImage( sanity_check(image->getPitch() == 4 * size); return reinterpret_cast(image->lock()); }; - auto free_image = [](video::IImage *image) -> void { + auto free_image = [] (video::IImage *image) -> void { image->unlock(); image->drop(); }; - video::IImage *result = - driver->createImage(video::ECF_A8R8G8B8, {cube_size, cube_size}); + video::IImage *result = driver->createImage(video::ECF_A8R8G8B8, {cube_size, cube_size}); sanity_check(result->getPitch() == 4 * cube_size); result->fill(video::SColor(0x00000000u)); u32 *target = reinterpret_cast(result->lock()); @@ -852,9 +855,10 @@ static video::IImage *createInventoryCubeImage( // `shade_factor` is face brightness, in range [0.0, 1.0] // (xu, xv, x1; yu, yv, y1) form coordinate transformation matrix // `offsets` list pixels to be drawn for single source pixel - auto draw_image = [=](video::IImage *image, float shade_factor, s16 xu, s16 xv, - s16 x1, s16 yu, s16 yv, s16 y1, - std::initializer_list offsets) -> void { + auto draw_image = [=] (video::IImage *image, float shade_factor, + s16 xu, s16 xv, s16 x1, + s16 yu, s16 yv, s16 y1, + std::initializer_list offsets) -> void { u32 brightness = core::clamp(256 * shade_factor, 0, 256); const u32 *source = lock_image(image); for (u16 v = 0; v < size; v++) { @@ -864,87 +868,51 @@ static video::IImage *createInventoryCubeImage( s16 x = xu * u + xv * v + x1; s16 y = yu * u + yv * v + y1; for (const auto &off : offsets) - target[(y + off.Y) * cube_size + (x + off.X) + - offset] = pixel.color; + target[(y + off.Y) * cube_size + (x + off.X) + offset] = pixel.color; source++; } } free_image(image); }; - draw_image(top, 1.000000f, 4, -4, 4 * (size - 1), 2, 2, 0, + draw_image(top, 1.000000f, + 4, -4, 4 * (size - 1), + 2, 2, 0, { - {2, 0}, - {3, 0}, - {4, 0}, - {5, 0}, - {0, 1}, - {1, 1}, - {2, 1}, - {3, 1}, - {4, 1}, - {5, 1}, - {6, 1}, - {7, 1}, - {2, 2}, - {3, 2}, - {4, 2}, - {5, 2}, + {2, 0}, {3, 0}, {4, 0}, {5, 0}, + {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1}, {7, 1}, + {2, 2}, {3, 2}, {4, 2}, {5, 2}, }); - draw_image(left, 0.836660f, 4, 0, 0, 2, 5, 2 * size, + draw_image(left, 0.836660f, + 4, 0, 0, + 2, 5, 2 * size, { - {0, 0}, - {1, 0}, - {0, 1}, - {1, 1}, - {2, 1}, - {3, 1}, - {0, 2}, - {1, 2}, - {2, 2}, - {3, 2}, - {0, 3}, - {1, 3}, - {2, 3}, - {3, 3}, - {0, 4}, - {1, 4}, - {2, 4}, - {3, 4}, - {2, 5}, - {3, 5}, + {0, 0}, {1, 0}, + {0, 1}, {1, 1}, {2, 1}, {3, 1}, + {0, 2}, {1, 2}, {2, 2}, {3, 2}, + {0, 3}, {1, 3}, {2, 3}, {3, 3}, + {0, 4}, {1, 4}, {2, 4}, {3, 4}, + {2, 5}, {3, 5}, }); - draw_image(right, 0.670820f, 4, 0, 4 * size, -2, 5, 4 * size - 2, + draw_image(right, 0.670820f, + 4, 0, 4 * size, + -2, 5, 4 * size - 2, { - {2, 0}, - {3, 0}, - {0, 1}, - {1, 1}, - {2, 1}, - {3, 1}, - {0, 2}, - {1, 2}, - {2, 2}, - {3, 2}, - {0, 3}, - {1, 3}, - {2, 3}, - {3, 3}, - {0, 4}, - {1, 4}, - {2, 4}, - {3, 4}, - {0, 5}, - {1, 5}, + {2, 0}, {3, 0}, + {0, 1}, {1, 1}, {2, 1}, {3, 1}, + {0, 2}, {1, 2}, {2, 2}, {3, 2}, + {0, 3}, {1, 3}, {2, 3}, {3, 3}, + {0, 4}, {1, 4}, {2, 4}, {3, 4}, + {0, 5}, {1, 5}, }); result->unlock(); return result; } -video::IImage *TextureSource::generateImage(const std::string &name) +video::IImage* TextureSource::generateImage(const std::string &name) { // Get the base image @@ -957,7 +925,7 @@ video::IImage *TextureSource::generateImage(const std::string &name) s32 last_separator_pos = -1; u8 paren_bal = 0; for (s32 i = name.size() - 1; i >= 0; i--) { - if (i > 0 && name[i - 1] == escape) + if (i > 0 && name[i-1] == escape) continue; switch (name[i]) { case separator: @@ -969,9 +937,8 @@ video::IImage *TextureSource::generateImage(const std::string &name) case paren_open: if (paren_bal == 0) { errorstream << "generateImage(): unbalanced parentheses" - << "(extranous '(') while generating texture " - "\"" - << name << "\"" << std::endl; + << "(extranous '(') while generating texture \"" + << name << "\"" << std::endl; return NULL; } paren_bal--; @@ -985,11 +952,12 @@ video::IImage *TextureSource::generateImage(const std::string &name) } if (paren_bal > 0) { errorstream << "generateImage(): unbalanced parentheses" - << "(missing matching '(') while generating texture \"" - << name << "\"" << std::endl; + << "(missing matching '(') while generating texture \"" + << name << "\"" << std::endl; return NULL; } + video::IImage *baseimg = NULL; /* @@ -1011,15 +979,15 @@ video::IImage *TextureSource::generateImage(const std::string &name) If this name is enclosed in parentheses, generate it and blit it onto the base image */ - if (last_part_of_name[0] == paren_open && - last_part_of_name[last_part_of_name.size() - 1] == paren_close) { - std::string name2 = - last_part_of_name.substr(1, last_part_of_name.size() - 2); + if (last_part_of_name[0] == paren_open + && last_part_of_name[last_part_of_name.size() - 1] == paren_close) { + std::string name2 = last_part_of_name.substr(1, + last_part_of_name.size() - 2); video::IImage *tmp = generateImage(name2); if (!tmp) { errorstream << "generateImage(): " - "Failed to generate \"" - << name2 << "\"" << std::endl; + "Failed to generate \"" << name2 << "\"" + << std::endl; return NULL; } core::dimension2d dim = tmp->getDimension(); @@ -1032,15 +1000,14 @@ video::IImage *TextureSource::generateImage(const std::string &name) } else if (!generateImagePart(last_part_of_name, baseimg)) { // Generate image according to part of name errorstream << "generateImage(): " - "Failed to generate \"" - << last_part_of_name << "\"" << std::endl; + "Failed to generate \"" << last_part_of_name << "\"" + << std::endl; } // If no resulting image, print a warning if (baseimg == NULL) { errorstream << "generateImage(): baseimg is NULL (attempted to" - " create texture \"" - << name << "\")" << std::endl; + " create texture \"" << name << "\")" << std::endl; } return baseimg; @@ -1048,10 +1015,11 @@ video::IImage *TextureSource::generateImage(const std::string &name) #if ENABLE_GLES + static inline u16 get_GL_major_version() { const GLubyte *gl_version = glGetString(GL_VERSION); - return (u16)(gl_version[0] - '0'); + return (u16) (gl_version[0] - '0'); } /** @@ -1063,9 +1031,9 @@ bool hasNPotSupport() { // Only GLES2 is trusted to correctly report npot support // Note: we cache the boolean result, the GL context will never change. - static const bool supported = - get_GL_major_version() > 1 && glGetString(GL_EXTENSIONS) && - strstr((char *)glGetString(GL_EXTENSIONS), "GL_OES_texture_npot"); + static const bool supported = get_GL_major_version() > 1 && + glGetString(GL_EXTENSIONS) && + strstr((char *)glGetString(GL_EXTENSIONS), "GL_OES_texture_npot"); return supported; } @@ -1076,7 +1044,8 @@ bool hasNPotSupport() * @return image or copy of image aligned to npot2 */ -video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver) +video::IImage * Align2Npot2(video::IImage * image, + video::IVideoDriver* driver) { if (image == NULL) return image; @@ -1086,7 +1055,7 @@ video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver) core::dimension2d dim = image->getDimension(); unsigned int height = npot2(dim.Height); - unsigned int width = npot2(dim.Width); + unsigned int width = npot2(dim.Width); if (dim.Height == height && dim.Width == width) return image; @@ -1096,8 +1065,9 @@ video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver) if (dim.Width > width) width *= 2; - video::IImage *targetimage = driver->createImage( - video::ECF_A8R8G8B8, core::dimension2d(width, height)); + video::IImage *targetimage = + driver->createImage(video::ECF_A8R8G8B8, + core::dimension2d(width, height)); if (targetimage != NULL) image->copyToScaling(targetimage); @@ -1124,7 +1094,8 @@ static std::string unescape_string(const std::string &str, const char esc = '\\' return out; } -bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&baseimg) +bool TextureSource::generateImagePart(std::string part_of_name, + video::IImage *& baseimg) { const char escape = '\\'; // same as in generateImage() video::IVideoDriver *driver = RenderingEngine::get_video_driver(); @@ -1140,34 +1111,28 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& if (!part_of_name.empty()) { // Do not create normalmap dummies - if (part_of_name.find("_normal.png") != - std::string::npos) { - warningstream << "generateImage(): Could not " - "load normal map \"" - << part_of_name << "\"" - << std::endl; + if (part_of_name.find("_normal.png") != std::string::npos) { + warningstream << "generateImage(): Could not load normal map \"" + << part_of_name << "\"" << std::endl; return true; } errorstream << "generateImage(): Could not load image \"" - << part_of_name - << "\" while building texture; " - "Creating a dummy image" - << std::endl; + << part_of_name << "\" while building texture; " + "Creating a dummy image" << std::endl; } // Just create a dummy image - // core::dimension2d dim(2,2); - core::dimension2d dim(1, 1); + //core::dimension2d dim(2,2); + core::dimension2d dim(1,1); image = driver->createImage(video::ECF_A8R8G8B8, dim); sanity_check(image != NULL); /*image->setPixel(0,0, video::SColor(255,255,0,0)); image->setPixel(1,0, video::SColor(255,0,255,0)); image->setPixel(0,1, video::SColor(255,0,0,255)); image->setPixel(1,1, video::SColor(255,255,0,255));*/ - image->setPixel(0, 0, - video::SColor(255, myrand() % 256, myrand() % 256, - myrand() % 256)); + image->setPixel(0,0, video::SColor(255,myrand()%256, + myrand()%256,myrand()%256)); /*image->setPixel(1,0, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); image->setPixel(0,1, video::SColor(255,myrand()%256, @@ -1177,8 +1142,9 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& } // If base image is NULL, load as base. - if (baseimg == NULL) { - // infostream<<"Setting "<copyTo(baseimg); } // Else blit on base. - else { - // infostream<<"Blitting "< dim = image->getDimension(); - // core::dimension2d dim(16,16); + //core::dimension2d dim(16,16); // Position to copy the blitted to in the base image - core::position2d pos_to(0, 0); + core::position2d pos_to(0,0); // Position to copy the blitted from in the blitted image - core::position2d pos_from(0, 0); + core::position2d pos_from(0,0); // Blit /*image->copyToWithAlpha(baseimg, pos_to, core::rect(pos_from, dim), @@ -1207,23 +1174,18 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& core::dimension2d dim_dst = baseimg->getDimension(); if (dim == dim_dst) { blit_with_alpha(image, baseimg, pos_from, pos_to, dim); - } else if (dim.Width * dim.Height < - dim_dst.Width * dim_dst.Height) { + } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) { // Upscale overlying image - video::IImage *scaled_image = - RenderingEngine::get_video_driver()->createImage( - video::ECF_A8R8G8B8, - dim_dst); + video::IImage *scaled_image = RenderingEngine::get_video_driver()-> + createImage(video::ECF_A8R8G8B8, dim_dst); image->copyToScaling(scaled_image); - blit_with_alpha(scaled_image, baseimg, pos_from, pos_to, - dim_dst); + blit_with_alpha(scaled_image, baseimg, pos_from, pos_to, dim_dst); scaled_image->drop(); } else { // Upscale base image - video::IImage *scaled_base = - RenderingEngine::get_video_driver()->createImage( - video::ECF_A8R8G8B8, dim); + video::IImage *scaled_base = RenderingEngine::get_video_driver()-> + createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(scaled_base); baseimg->drop(); baseimg = scaled_base; @@ -1231,9 +1193,11 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& blit_with_alpha(image, baseimg, pos_from, pos_to, dim); } } - // cleanup + //cleanup image->drop(); - } else { + } + else + { // A special texture modification /*infostream<<"generateImage(): generating special " @@ -1246,11 +1210,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& Adds a cracking texture N = animation frame count, P = crack progression */ - if (str_starts_with(part_of_name, "[crack")) { + if (str_starts_with(part_of_name, "[crack")) + { if (baseimg == NULL) { - errorstream << "generateImagePart(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + errorstream<<"generateImagePart(): baseimg == NULL " + <<"for part_of_name=\""<drop(); } } @@ -1294,55 +1259,53 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& [combine:WxH:X,Y=filename:X,Y=filename2 Creates a bigger texture from any amount of smaller ones */ - else if (str_starts_with(part_of_name, "[combine")) { + else if (str_starts_with(part_of_name, "[combine")) + { Strfnd sf(part_of_name); sf.next(":"); u32 w0 = stoi(sf.next("x")); u32 h0 = stoi(sf.next(":")); - core::dimension2d dim(w0, h0); + core::dimension2d dim(w0,h0); if (baseimg == NULL) { baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); - baseimg->fill(video::SColor(0, 0, 0, 0)); + baseimg->fill(video::SColor(0,0,0,0)); } while (!sf.at_end()) { u32 x = stoi(sf.next(",")); u32 y = stoi(sf.next("=")); - std::string filename = unescape_string( - sf.next_esc(":", escape), escape); - infostream << "Adding \"" << filename - << "\" to combined (" << x << "," << y << ")" - << std::endl; + std::string filename = unescape_string(sf.next_esc(":", escape), escape); + infostream<<"Adding \""< dim = img->getDimension(); core::position2d pos_base(x, y); - video::IImage *img2 = driver->createImage( - video::ECF_A8R8G8B8, dim); + video::IImage *img2 = + driver->createImage(video::ECF_A8R8G8B8, dim); img->copyTo(img2); img->drop(); /*img2->copyToWithAlpha(baseimg, pos_base, core::rect(v2s32(0,0), dim), video::SColor(255,255,255,255), NULL);*/ - blit_with_alpha(img2, baseimg, v2s32(0, 0), - pos_base, dim); + blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim); img2->drop(); } else { - errorstream << "generateImagePart(): Failed to " - "load image \"" - << filename << "\" for [combine" - << std::endl; + errorstream << "generateImagePart(): Failed to load image \"" + << filename << "\" for [combine" << std::endl; } } } /* [brighten */ - else if (str_starts_with(part_of_name, "[brighten")) { + else if (str_starts_with(part_of_name, "[brighten")) + { if (baseimg == NULL) { - errorstream << "generateImagePart(): baseimg==NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + errorstream<<"generateImagePart(): baseimg==NULL " + <<"for part_of_name=\""< dim = baseimg->getDimension(); // Set alpha to full - for (u32 y = 0; y < dim.Height; y++) - for (u32 x = 0; x < dim.Width; x++) { - video::SColor c = baseimg->getPixel(x, y); - c.setAlpha(255); - baseimg->setPixel(x, y, c); - } + for (u32 y=0; ygetPixel(x,y); + c.setAlpha(255); + baseimg->setPixel(x,y,c); + } } /* [makealpha:R,G,B Convert one color to transparent. */ - else if (str_starts_with(part_of_name, "[makealpha:")) { + else if (str_starts_with(part_of_name, "[makealpha:")) + { if (baseimg == NULL) { - errorstream << "generateImagePart(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + errorstream<<"generateImagePart(): baseimg == NULL " + <<"for part_of_name=\""<drop();*/ // Set alpha to full - for (u32 y = 0; y < dim.Height; y++) - for (u32 x = 0; x < dim.Width; x++) { - video::SColor c = baseimg->getPixel(x, y); - u32 r = c.getRed(); - u32 g = c.getGreen(); - u32 b = c.getBlue(); - if (!(r == r1 && g == g1 && b == b1)) - continue; - c.setAlpha(0); - baseimg->setPixel(x, y, c); - } + for (u32 y=0; ygetPixel(x,y); + u32 r = c.getRed(); + u32 g = c.getGreen(); + u32 b = c.getBlue(); + if (!(r == r1 && g == g1 && b == b1)) + continue; + c.setAlpha(0); + baseimg->setPixel(x,y,c); + } } /* [transformN @@ -1430,11 +1397,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& The resulting transform will be equivalent to one of the eight existing ones, though (see: dihedral group). */ - else if (str_starts_with(part_of_name, "[transform")) { + else if (str_starts_with(part_of_name, "[transform")) + { if (baseimg == NULL) { - errorstream << "generateImagePart(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + errorstream<<"generateImagePart(): baseimg == NULL " + <<"for part_of_name=\""<createImage( - video::ECF_A8R8G8B8, v2u32(16, 16)); + baseimg = driver->createImage(video::ECF_A8R8G8B8, v2u32(16,16)); video::IImage *img = generateImage(filename); - if (img) { + if (img) + { core::dimension2d dim = img->getDimension(); core::position2d pos_base(0, 0); - video::IImage *img2 = driver->createImage( - video::ECF_A8R8G8B8, dim); + video::IImage *img2 = + driver->createImage(video::ECF_A8R8G8B8, dim); img->copyTo(img2); img->drop(); core::position2d clippos(0, 0); - clippos.Y = dim.Height * (100 - percent) / 100; + clippos.Y = dim.Height * (100-percent) / 100; core::dimension2d clipdim = dim; clipdim.Height = clipdim.Height * percent / 100 + 1; core::rect cliprect(clippos, clipdim); img2->copyToWithAlpha(baseimg, pos_base, - core::rect(v2s32(0, 0), dim), - video::SColor(255, 255, 255, 255), + core::rect(v2s32(0,0), dim), + video::SColor(255,255,255,255), &cliprect); img2->drop(); } @@ -1533,41 +1501,42 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& Crops a frame of a vertical animation. N = frame count, I = frame index */ - else if (str_starts_with(part_of_name, "[verticalframe:")) { + else if (str_starts_with(part_of_name, "[verticalframe:")) + { Strfnd sf(part_of_name); sf.next(":"); u32 frame_count = stoi(sf.next(":")); u32 frame_index = stoi(sf.next(":")); - if (baseimg == NULL) { - errorstream << "generateImagePart(): baseimg != NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + if (baseimg == NULL){ + errorstream<<"generateImagePart(): baseimg != NULL " + <<"for part_of_name=\""<getDimension(); frame_size.Y /= frame_count; - video::IImage *img = driver->createImage( - video::ECF_A8R8G8B8, frame_size); - if (!img) { - errorstream << "generateImagePart(): Could not create " - "image " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + video::IImage *img = driver->createImage(video::ECF_A8R8G8B8, + frame_size); + if (!img){ + errorstream<<"generateImagePart(): Could not create image " + <<"for part_of_name=\""<fill(video::SColor(0, 0, 0, 0)); + img->fill(video::SColor(0,0,0,0)); core::dimension2d dim = frame_size; core::position2d pos_dst(0, 0); core::position2d pos_src(0, frame_index * frame_size.Y); baseimg->copyToWithAlpha(img, pos_dst, core::rect(pos_src, dim), - video::SColor(255, 255, 255, 255), NULL); + video::SColor(255,255,255,255), + NULL); // Replace baseimg baseimg->drop(); baseimg = img; @@ -1576,17 +1545,17 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& [mask:filename Applies a mask to an image */ - else if (str_starts_with(part_of_name, "[mask:")) { + else if (str_starts_with(part_of_name, "[mask:")) + { if (baseimg == NULL) { errorstream << "generateImage(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); - std::string filename = - unescape_string(sf.next_esc(":", escape), escape); + std::string filename = unescape_string(sf.next_esc(":", escape), escape); video::IImage *img = generateImage(filename); if (img) { @@ -1595,7 +1564,7 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& img->drop(); } else { errorstream << "generateImage(): Failed to load \"" - << filename << "\"."; + << filename << "\"."; } } /* @@ -1610,8 +1579,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } @@ -1620,15 +1589,15 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& if (!parseColorString(color_str, color, false)) return false; - apply_multiplication(baseimg, v2u32(0, 0), - baseimg->getDimension(), color); + apply_multiplication(baseimg, v2u32(0, 0), baseimg->getDimension(), color); } /* [colorize:color Overlays image with given color color = color as ColorString */ - else if (str_starts_with(part_of_name, "[colorize:")) { + else if (str_starts_with(part_of_name, "[colorize:")) + { Strfnd sf(part_of_name); sf.next(":"); std::string color_str = sf.next(":"); @@ -1636,8 +1605,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } @@ -1653,14 +1622,14 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& else if (ratio_str == "alpha") keep_alpha = true; - apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), - color, ratio, keep_alpha); + apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), color, ratio, keep_alpha); } /* [applyfiltersformesh Internal modifier */ - else if (str_starts_with(part_of_name, "[applyfiltersformesh")) { + else if (str_starts_with(part_of_name, "[applyfiltersformesh")) + { /* IMPORTANT: When changing this, getTextureForMesh() needs to be * updated too. */ @@ -1668,33 +1637,25 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& if (g_settings->getBool("texture_clean_transparent")) imageCleanTransparent(baseimg, 127); - /* Upscale textures to user's requested minimum size. This is a - * trick to make filters look as good on low-res textures as on - * high-res ones, by making low-res textures BECOME high-res ones. - * This is helpful for worlds that mix high- and low-res textures, - * or for mods with least-common-denominator textures that don't - * have the resources to offer high-res alternatives. + /* Upscale textures to user's requested minimum size. This is a trick to make + * filters look as good on low-res textures as on high-res ones, by making + * low-res textures BECOME high-res ones. This is helpful for worlds that + * mix high- and low-res textures, or for mods with least-common-denominator + * textures that don't have the resources to offer high-res alternatives. */ - const bool filter = m_setting_trilinear_filter || - m_setting_bilinear_filter; - const s32 scaleto = - filter ? g_settings->getS32("texture_min_size") - : 1; + const bool filter = m_setting_trilinear_filter || m_setting_bilinear_filter; + const s32 scaleto = filter ? g_settings->getS32("texture_min_size") : 1; if (scaleto > 1) { - const core::dimension2d dim = - baseimg->getDimension(); + const core::dimension2d dim = baseimg->getDimension(); - /* Calculate scaling needed to make the shortest texture - * dimension equal to the target minimum. If e.g. this is - * a vertical frames animation, the short dimension will - * be the real size. + /* Calculate scaling needed to make the shortest texture dimension + * equal to the target minimum. If e.g. this is a vertical frames + * animation, the short dimension will be the real size. */ if ((dim.Width == 0) || (dim.Height == 0)) { - errorstream << "generateImagePart(): Illegal 0 " - "dimension " - << "for part_of_name=\"" - << part_of_name << "\", cancelling." - << std::endl; + errorstream << "generateImagePart(): Illegal 0 dimension " + << "for part_of_name=\""<< part_of_name + << "\", cancelling." << std::endl; return false; } u32 xscale = scaleto / dim.Width; @@ -1705,11 +1666,9 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& if (scale > 1) { u32 w = scale * dim.Width; u32 h = scale * dim.Height; - const core::dimension2d newdim = - core::dimension2d(w, h); + const core::dimension2d newdim = core::dimension2d(w, h); video::IImage *newimg = driver->createImage( - baseimg->getColorFormat(), - newdim); + baseimg->getColorFormat(), newdim); baseimg->copyToScaling(newimg); baseimg->drop(); baseimg = newimg; @@ -1720,11 +1679,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& [resize:WxH Resizes the base image to the given dimensions */ - else if (str_starts_with(part_of_name, "[resize")) { + else if (str_starts_with(part_of_name, "[resize")) + { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\""<< part_of_name + << "\", cancelling." << std::endl; return false; } @@ -1734,9 +1694,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& u32 height = stoi(sf.next("")); core::dimension2d dim(width, height); - video::IImage *image = - RenderingEngine::get_video_driver()->createImage( - video::ECF_A8R8G8B8, dim); + video::IImage *image = RenderingEngine::get_video_driver()-> + createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(image); baseimg->drop(); baseimg = image; @@ -1751,8 +1710,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& else if (str_starts_with(part_of_name, "[opacity:")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } @@ -1764,12 +1723,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& core::dimension2d dim = baseimg->getDimension(); for (u32 y = 0; y < dim.Height; y++) - for (u32 x = 0; x < dim.Width; x++) { - video::SColor c = baseimg->getPixel(x, y); - c.setAlpha(floor((c.getAlpha() * ratio) / 255 + - 0.5)); - baseimg->setPixel(x, y, c); - } + for (u32 x = 0; x < dim.Width; x++) + { + video::SColor c = baseimg->getPixel(x, y); + c.setAlpha(floor((c.getAlpha() * ratio) / 255 + 0.5)); + baseimg->setPixel(x, y, c); + } } /* [invert:mode @@ -1781,8 +1740,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& else if (str_starts_with(part_of_name, "[invert:")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } @@ -1803,11 +1762,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& core::dimension2d dim = baseimg->getDimension(); for (u32 y = 0; y < dim.Height; y++) - for (u32 x = 0; x < dim.Width; x++) { - video::SColor c = baseimg->getPixel(x, y); - c.color ^= mask; - baseimg->setPixel(x, y, c); - } + for (u32 x = 0; x < dim.Width; x++) + { + video::SColor c = baseimg->getPixel(x, y); + c.color ^= mask; + baseimg->setPixel(x, y, c); + } } /* [sheet:WxH:X,Y @@ -1815,11 +1775,11 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& from the base image it assumes to be a tilesheet with dimensions W,H (in tiles). */ - else if (part_of_name.substr(0, 7) == "[sheet:") { + else if (part_of_name.substr(0,7) == "[sheet:") { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } @@ -1836,26 +1796,26 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& video::IImage *img = driver->createImage( video::ECF_A8R8G8B8, tile_dim); if (!img) { - errorstream << "generateImagePart(): Could not create " - "image " - << "for part_of_name=\"" << part_of_name - << "\", cancelling." << std::endl; + errorstream << "generateImagePart(): Could not create image " + << "for part_of_name=\"" << part_of_name + << "\", cancelling." << std::endl; return false; } - img->fill(video::SColor(0, 0, 0, 0)); + img->fill(video::SColor(0,0,0,0)); v2u32 vdim(tile_dim); core::rect rect(v2s32(x0 * vdim.X, y0 * vdim.Y), tile_dim); baseimg->copyToWithAlpha(img, v2s32(0), rect, - video::SColor(255, 255, 255, 255), NULL); + video::SColor(255,255,255,255), NULL); // Replace baseimg baseimg->drop(); baseimg = img; - } else { + } + else + { errorstream << "generateImagePart(): Invalid " - " modification: \"" - << part_of_name << "\"" << std::endl; + " modification: \"" << part_of_name << "\"" << std::endl; } } @@ -1870,14 +1830,13 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& pixel with alpha=64 drawn atop a pixel with alpha=128 should yield a pixel with alpha=160, while getInterpolated would yield alpha=96. */ -static inline video::SColor blitPixel( - const video::SColor &src_c, const video::SColor &dst_c, u32 ratio) +static inline video::SColor blitPixel(const video::SColor &src_c, const video::SColor &dst_c, u32 ratio) { if (dst_c.getAlpha() == 0) return src_c; video::SColor out_c = src_c.getInterpolated(dst_c, (float)ratio / 255.0f); - out_c.setAlpha(dst_c.getAlpha() + (255 - dst_c.getAlpha()) * src_c.getAlpha() * - ratio / (255 * 255)); + out_c.setAlpha(dst_c.getAlpha() + (255 - dst_c.getAlpha()) * + src_c.getAlpha() * ratio / (255 * 255)); return out_c; } @@ -1888,42 +1847,45 @@ static inline video::SColor blitPixel( This exists because IImage::copyToWithAlpha() doesn't seem to always work. */ -static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos, - v2s32 dst_pos, v2u32 size) +static void blit_with_alpha(video::IImage *src, video::IImage *dst, + v2s32 src_pos, v2s32 dst_pos, v2u32 size) { - for (u32 y0 = 0; y0 < size.Y; y0++) - for (u32 x0 = 0; x0 < size.X; x0++) { - s32 src_x = src_pos.X + x0; - s32 src_y = src_pos.Y + y0; - s32 dst_x = dst_pos.X + x0; - s32 dst_y = dst_pos.Y + y0; - video::SColor src_c = src->getPixel(src_x, src_y); - video::SColor dst_c = dst->getPixel(dst_x, dst_y); - dst_c = blitPixel(src_c, dst_c, src_c.getAlpha()); - dst->setPixel(dst_x, dst_y, dst_c); - } + for (u32 y0=0; y0getPixel(src_x, src_y); + video::SColor dst_c = dst->getPixel(dst_x, dst_y); + dst_c = blitPixel(src_c, dst_c, src_c.getAlpha()); + dst->setPixel(dst_x, dst_y, dst_c); + } } /* Draw an image on top of an another one, using the alpha channel of the source image; only modify fully opaque pixels in destinaion */ -static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, - v2s32 dst_pos, v2u32 size) +static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, + v2s32 src_pos, v2s32 dst_pos, v2u32 size) { - for (u32 y0 = 0; y0 < size.Y; y0++) - for (u32 x0 = 0; x0 < size.X; x0++) { - s32 src_x = src_pos.X + x0; - s32 src_y = src_pos.Y + y0; - s32 dst_x = dst_pos.X + x0; - s32 dst_y = dst_pos.Y + y0; - video::SColor src_c = src->getPixel(src_x, src_y); - video::SColor dst_c = dst->getPixel(dst_x, dst_y); - if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0) { - dst_c = blitPixel(src_c, dst_c, src_c.getAlpha()); - dst->setPixel(dst_x, dst_y, dst_c); - } + for (u32 y0=0; y0getPixel(src_x, src_y); + video::SColor dst_c = dst->getPixel(dst_x, dst_y); + if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0) + { + dst_c = blitPixel(src_c, dst_c, src_c.getAlpha()); + dst->setPixel(dst_x, dst_y, dst_c); } + } } // This function has been disabled because it is currently unused. @@ -1966,60 +1928,61 @@ static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size, u32 alpha = color.getAlpha(); video::SColor dst_c; if ((ratio == -1 && alpha == 255) || ratio == 255) { // full replacement of color - if (keep_alpha) { // replace the color with alpha = dest alpha * color - // alpha + if (keep_alpha) { // replace the color with alpha = dest alpha * color alpha dst_c = color; for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) - for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { - u32 dst_alpha = dst->getPixel(x, y).getAlpha(); - if (dst_alpha > 0) { - dst_c.setAlpha(dst_alpha * alpha / 255); - dst->setPixel(x, y, dst_c); - } + for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { + u32 dst_alpha = dst->getPixel(x, y).getAlpha(); + if (dst_alpha > 0) { + dst_c.setAlpha(dst_alpha * alpha / 255); + dst->setPixel(x, y, dst_c); } + } } else { // replace the color including the alpha for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) - for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) - if (dst->getPixel(x, y).getAlpha() > 0) - dst->setPixel(x, y, color); + for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) + if (dst->getPixel(x, y).getAlpha() > 0) + dst->setPixel(x, y, color); } - } else { // interpolate between the color and destination + } else { // interpolate between the color and destination float interp = (ratio == -1 ? color.getAlpha() / 255.0f : ratio / 255.0f); for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) - for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { - dst_c = dst->getPixel(x, y); - if (dst_c.getAlpha() > 0) { - dst_c = color.getInterpolated(dst_c, interp); - dst->setPixel(x, y, dst_c); - } + for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { + dst_c = dst->getPixel(x, y); + if (dst_c.getAlpha() > 0) { + dst_c = color.getInterpolated(dst_c, interp); + dst->setPixel(x, y, dst_c); } + } } } /* Apply color to destination */ -static void apply_multiplication( - video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color) +static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size, + const video::SColor &color) { video::SColor dst_c; for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) - for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { - dst_c = dst->getPixel(x, y); - dst_c.set(dst_c.getAlpha(), - (dst_c.getRed() * color.getRed()) / 255, - (dst_c.getGreen() * color.getGreen()) / 255, - (dst_c.getBlue() * color.getBlue()) / 255); - dst->setPixel(x, y, dst_c); - } + for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { + dst_c = dst->getPixel(x, y); + dst_c.set( + dst_c.getAlpha(), + (dst_c.getRed() * color.getRed()) / 255, + (dst_c.getGreen() * color.getGreen()) / 255, + (dst_c.getBlue() * color.getBlue()) / 255 + ); + dst->setPixel(x, y, dst_c); + } } /* Apply mask to destination */ -static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos, - v2s32 dst_pos, v2u32 size) +static void apply_mask(video::IImage *mask, video::IImage *dst, + v2s32 mask_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0 = 0; y0 < size.Y; y0++) { for (u32 x0 = 0; x0 < size.X; x0++) { @@ -2047,15 +2010,14 @@ video::IImage *create_crack_image(video::IImage *crack, s32 frame_index, core::rect frame(v2s32(0, frame_index * frame_size.Height), frame_size); video::IImage *result = nullptr; - // extract crack frame +// extract crack frame video::IImage *crack_tile = driver->createImage(video::ECF_A8R8G8B8, tile_size); if (!crack_tile) return nullptr; if (tile_size == frame_size) { crack->copyTo(crack_tile, v2s32(0, 0), frame); } else { - video::IImage *crack_frame = - driver->createImage(video::ECF_A8R8G8B8, frame_size); + video::IImage *crack_frame = driver->createImage(video::ECF_A8R8G8B8, frame_size); if (!crack_frame) goto exit__has_tile; crack->copyTo(crack_frame, v2s32(0, 0), frame); @@ -2065,43 +2027,46 @@ video::IImage *create_crack_image(video::IImage *crack, s32 frame_index, if (tiles == 1) return crack_tile; - // tile it +// tile it result = driver->createImage(video::ECF_A8R8G8B8, size); if (!result) goto exit__has_tile; result->fill({}); for (u8 i = 0; i < tiles; i++) for (u8 j = 0; j < tiles; j++) - crack_tile->copyTo(result, - v2s32(i * tile_size.Width, j * tile_size.Height)); + crack_tile->copyTo(result, v2s32(i * tile_size.Width, j * tile_size.Height)); exit__has_tile: crack_tile->drop(); return result; } -static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay, - s32 frame_count, s32 progression, video::IVideoDriver *driver, u8 tiles) +static void draw_crack(video::IImage *crack, video::IImage *dst, + bool use_overlay, s32 frame_count, s32 progression, + video::IVideoDriver *driver, u8 tiles) { // Dimension of destination image core::dimension2d dim_dst = dst->getDimension(); // Limit frame_count - if (frame_count > (s32)dim_dst.Height) + if (frame_count > (s32) dim_dst.Height) frame_count = dim_dst.Height; if (frame_count < 1) frame_count = 1; // Dimension of the scaled crack stage, // which is the same as the dimension of a single destination frame - core::dimension2d frame_size(dim_dst.Width, dim_dst.Height / frame_count); - video::IImage *crack_scaled = - create_crack_image(crack, progression, frame_size, tiles, driver); + core::dimension2d frame_size( + dim_dst.Width, + dim_dst.Height / frame_count + ); + video::IImage *crack_scaled = create_crack_image(crack, progression, + frame_size, tiles, driver); if (!crack_scaled) return; auto blit = use_overlay ? blit_with_alpha_overlay : blit_with_alpha; for (s32 i = 0; i < frame_count; ++i) { v2s32 dst_pos(0, frame_size.Height * i); - blit(crack_scaled, dst, v2s32(0, 0), dst_pos, frame_size); + blit(crack_scaled, dst, v2s32(0,0), dst_pos, frame_size); } crack_scaled->drop(); @@ -2114,17 +2079,18 @@ void brighten(video::IImage *image) core::dimension2d dim = image->getDimension(); - for (u32 y = 0; y < dim.Height; y++) - for (u32 x = 0; x < dim.Width; x++) { - video::SColor c = image->getPixel(x, y); - c.setRed(0.5 * 255 + 0.5 * (float)c.getRed()); - c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen()); - c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue()); - image->setPixel(x, y, c); - } + for (u32 y=0; ygetPixel(x,y); + c.setRed(0.5 * 255 + 0.5 * (float)c.getRed()); + c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen()); + c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue()); + image->setPixel(x,y,c); + } } -u32 parseImageTransform(const std::string &s) +u32 parseImageTransform(const std::string& s) { int total_transform = 0; @@ -2137,20 +2103,21 @@ u32 parseImageTransform(const std::string &s) transform_names[6] = "fy"; std::size_t pos = 0; - while (pos < s.size()) { + while(pos < s.size()) + { int transform = -1; - for (int i = 0; i <= 7; ++i) { + for (int i = 0; i <= 7; ++i) + { const std::string &name_i = transform_names[i]; - if (s[pos] == ('0' + i)) { + if (s[pos] == ('0' + i)) + { transform = i; pos++; break; } - if (!(name_i.empty()) && - lowercase(s.substr(pos, name_i.size())) == - name_i) { + if (!(name_i.empty()) && lowercase(s.substr(pos, name_i.size())) == name_i) { transform = i; pos += name_i.size(); break; @@ -2198,35 +2165,35 @@ void imageTransform(u32 transform, video::IImage *src, video::IImage *dst) */ int sxn = 0; int syn = 2; - if (transform == 0) // identity - sxn = 0, syn = 2; // sx = dx, sy = dy - else if (transform == 1) // rotate by 90 degrees ccw - sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx - else if (transform == 2) // rotate by 180 degrees - sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy - else if (transform == 3) // rotate by 270 degrees ccw - sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx - else if (transform == 4) // flip x - sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy - else if (transform == 5) // flip x then rotate by 90 degrees ccw - sxn = 2, syn = 0; // sx = dy, sy = dx - else if (transform == 6) // flip y - sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy - else if (transform == 7) // flip y then rotate by 90 degrees ccw - sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx - - for (u32 dy = 0; dy < dstdim.Height; dy++) - for (u32 dx = 0; dx < dstdim.Width; dx++) { - u32 entries[4] = {dx, dstdim.Width - 1 - dx, dy, - dstdim.Height - 1 - dy}; - u32 sx = entries[sxn]; - u32 sy = entries[syn]; - video::SColor c = src->getPixel(sx, sy); - dst->setPixel(dx, dy, c); - } + if (transform == 0) // identity + sxn = 0, syn = 2; // sx = dx, sy = dy + else if (transform == 1) // rotate by 90 degrees ccw + sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx + else if (transform == 2) // rotate by 180 degrees + sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy + else if (transform == 3) // rotate by 270 degrees ccw + sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx + else if (transform == 4) // flip x + sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy + else if (transform == 5) // flip x then rotate by 90 degrees ccw + sxn = 2, syn = 0; // sx = dy, sy = dx + else if (transform == 6) // flip y + sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy + else if (transform == 7) // flip y then rotate by 90 degrees ccw + sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx + + for (u32 dy=0; dygetPixel(sx,sy); + dst->setPixel(dx,dy,c); + } } -video::ITexture *TextureSource::getNormalTexture(const std::string &name) +video::ITexture* TextureSource::getNormalTexture(const std::string &name) { if (isKnownSourceImage("override_normal.png")) return getTexture("override_normal.png"); @@ -2252,8 +2219,9 @@ video::SColor TextureSource::getTextureAverageColor(const std::string &name) video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::SColor c(0, 0, 0, 0); video::ITexture *texture = getTexture(name); - video::IImage *image = driver->createImage( - texture, core::position2d(0, 0), texture->getOriginalSize()); + video::IImage *image = driver->createImage(texture, + core::position2d(0, 0), + texture->getOriginalSize()); u32 total = 0; u32 tR = 0; u32 tG = 0; @@ -2264,7 +2232,7 @@ video::SColor TextureSource::getTextureAverageColor(const std::string &name) step = dim.Width / 16; for (u16 x = 0; x < dim.Width; x += step) { for (u16 y = 0; y < dim.Width; y += step) { - c = image->getPixel(x, y); + c = image->getPixel(x,y); if (c.getAlpha() > 0) { total++; tR += c.getRed(); @@ -2283,6 +2251,7 @@ video::SColor TextureSource::getTextureAverageColor(const std::string &name) return c; } + video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present) { std::string tname = "__shaderFlagsTexture"; @@ -2294,13 +2263,14 @@ video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present) video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IImage *flags_image = driver->createImage( - video::ECF_A8R8G8B8, core::dimension2d(1, 1)); + video::ECF_A8R8G8B8, core::dimension2d(1, 1)); sanity_check(flags_image != NULL); video::SColor c(255, normalmap_present ? 255 : 0, 0, 0); flags_image->setPixel(0, 0, c); insertSourceImage(tname, flags_image); flags_image->drop(); return getTexture(tname); + } std::vector getTextureDirs() diff --git a/src/client/tile.h b/src/client/tile.h index 695bcdeac..49c46f749 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -78,7 +78,7 @@ class ISimpleTextureSource virtual ~ISimpleTextureSource() = default; - virtual video::ITexture *getTexture( + virtual video::ITexture* getTexture( const std::string &name, u32 *id = nullptr) = 0; }; @@ -89,12 +89,12 @@ class ITextureSource : public ISimpleTextureSource virtual ~ITextureSource() = default; - virtual u32 getTextureId(const std::string &name) = 0; - virtual std::string getTextureName(u32 id) = 0; - virtual video::ITexture *getTexture(u32 id) = 0; - virtual video::ITexture *getTexture( - const std::string &name, u32 *id = nullptr) = 0; - virtual video::ITexture *getTextureForMesh( + virtual u32 getTextureId(const std::string &name)=0; + virtual std::string getTextureName(u32 id)=0; + virtual video::ITexture* getTexture(u32 id)=0; + virtual video::ITexture* getTexture( + const std::string &name, u32 *id = nullptr)=0; + virtual video::ITexture* getTextureForMesh( const std::string &name, u32 *id = nullptr) = 0; /*! * Returns a palette from the given texture name. @@ -102,11 +102,11 @@ class ITextureSource : public ISimpleTextureSource * destructed. * Should be called from the main thread. */ - virtual Palette *getPalette(const std::string &name) = 0; - virtual bool isKnownSourceImage(const std::string &name) = 0; - virtual video::ITexture *getNormalTexture(const std::string &name) = 0; - virtual video::SColor getTextureAverageColor(const std::string &name) = 0; - virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present) = 0; + virtual Palette* getPalette(const std::string &name) = 0; + virtual bool isKnownSourceImage(const std::string &name)=0; + virtual video::ITexture* getNormalTexture(const std::string &name)=0; + virtual video::SColor getTextureAverageColor(const std::string &name)=0; + virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0; }; class IWritableTextureSource : public ITextureSource @@ -116,30 +116,29 @@ class IWritableTextureSource : public ITextureSource virtual ~IWritableTextureSource() = default; - virtual u32 getTextureId(const std::string &name) = 0; - virtual std::string getTextureName(u32 id) = 0; - virtual video::ITexture *getTexture(u32 id) = 0; - virtual video::ITexture *getTexture( - const std::string &name, u32 *id = nullptr) = 0; - virtual bool isKnownSourceImage(const std::string &name) = 0; - - virtual void processQueue() = 0; - virtual void insertSourceImage(const std::string &name, video::IImage *img) = 0; - virtual void rebuildImagesAndTextures() = 0; - virtual video::ITexture *getNormalTexture(const std::string &name) = 0; - virtual video::SColor getTextureAverageColor(const std::string &name) = 0; - virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present) = 0; + virtual u32 getTextureId(const std::string &name)=0; + virtual std::string getTextureName(u32 id)=0; + virtual video::ITexture* getTexture(u32 id)=0; + virtual video::ITexture* getTexture( + const std::string &name, u32 *id = nullptr)=0; + virtual bool isKnownSourceImage(const std::string &name)=0; + + virtual void processQueue()=0; + virtual void insertSourceImage(const std::string &name, video::IImage *img)=0; + virtual void rebuildImagesAndTextures()=0; + virtual video::ITexture* getNormalTexture(const std::string &name)=0; + virtual video::SColor getTextureAverageColor(const std::string &name)=0; + virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0; }; IWritableTextureSource *createTextureSource(); #if ENABLE_GLES bool hasNPotSupport(); -video::IImage *Align2Npot2(video::IImage *image, irr::video::IVideoDriver *driver); +video::IImage * Align2Npot2(video::IImage * image, irr::video::IVideoDriver* driver); #endif -enum MaterialType -{ +enum MaterialType{ TILE_MATERIAL_BASIC, TILE_MATERIAL_ALPHA, TILE_MATERIAL_LIQUID_TRANSPARENT, @@ -193,16 +192,21 @@ struct TileLayer */ bool operator==(const TileLayer &other) const { - return texture_id == other.texture_id && - material_type == other.material_type && - material_flags == other.material_flags && color == other.color && - scale == other.scale; + return + texture_id == other.texture_id && + material_type == other.material_type && + material_flags == other.material_flags && + color == other.color && + scale == other.scale; } /*! * Two tiles are not equal if they must have different vertices. */ - bool operator!=(const TileLayer &other) const { return !(*this == other); } + bool operator!=(const TileLayer &other) const + { + return !(*this == other); + } // Sets everything else except the texture in the material void applyMaterialOptions(video::SMaterial &material) const @@ -228,8 +232,7 @@ struct TileLayer default: break; } - material.BackfaceCulling = - (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; + material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) { material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; } @@ -240,8 +243,7 @@ struct TileLayer void applyMaterialOptionsWithShaders(video::SMaterial &material) const { - material.BackfaceCulling = - (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; + material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) { material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; material.TextureLayer[1].TextureWrapU = video::ETC_CLAMP_TO_EDGE; @@ -254,8 +256,8 @@ struct TileLayer bool isTileable() const { - return (material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) && - (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL); + return (material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) + && (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL); } // Ordered for size, please do not reorder @@ -273,10 +275,10 @@ struct TileLayer u8 material_type = TILE_MATERIAL_BASIC; u8 material_flags = - // 0 // <- DEBUG, Use the one below - MATERIAL_FLAG_BACKFACE_CULLING | - MATERIAL_FLAG_TILEABLE_HORIZONTAL | - MATERIAL_FLAG_TILEABLE_VERTICAL; + //0 // <- DEBUG, Use the one below + MATERIAL_FLAG_BACKFACE_CULLING | + MATERIAL_FLAG_TILEABLE_HORIZONTAL| + MATERIAL_FLAG_TILEABLE_VERTICAL; //! If true, the tile has its own color. bool has_color = false; @@ -302,16 +304,16 @@ struct TileSpec /*! * Returns true if this tile can be merged with the other tile. */ - bool isTileable(const TileSpec &other) const - { + bool isTileable(const TileSpec &other) const { for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { if (layers[layer] != other.layers[layer]) return false; if (!layers[layer].isTileable()) return false; } - return rotation == 0 && rotation == other.rotation && - emissive_light == other.emissive_light; + return rotation == 0 + && rotation == other.rotation + && emissive_light == other.emissive_light; } //! If true, the tile rotation is ignored. diff --git a/src/client/wieldmesh.cpp b/src/client/wieldmesh.cpp index 06053302f..8cd3e29a9 100644 --- a/src/client/wieldmesh.cpp +++ b/src/client/wieldmesh.cpp @@ -45,29 +45,29 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y) const f32 r = 0.5; scene::IMeshBuffer *buf = new scene::SMeshBuffer(); - video::SColor c(255, 255, 255, 255); + video::SColor c(255,255,255,255); v3f scale(1.0, 1.0, 0.1); // Front and back { video::S3DVertex vertices[8] = { - // z- - video::S3DVertex(-r, +r, -r, 0, 0, -1, c, 0, 0), - video::S3DVertex(+r, +r, -r, 0, 0, -1, c, 1, 0), - video::S3DVertex(+r, -r, -r, 0, 0, -1, c, 1, 1), - video::S3DVertex(-r, -r, -r, 0, 0, -1, c, 0, 1), - // z+ - video::S3DVertex(-r, +r, +r, 0, 0, +1, c, 0, 0), - video::S3DVertex(-r, -r, +r, 0, 0, +1, c, 0, 1), - video::S3DVertex(+r, -r, +r, 0, 0, +1, c, 1, 1), - video::S3DVertex(+r, +r, +r, 0, 0, +1, c, 1, 0), + // z- + video::S3DVertex(-r,+r,-r, 0,0,-1, c, 0,0), + video::S3DVertex(+r,+r,-r, 0,0,-1, c, 1,0), + video::S3DVertex(+r,-r,-r, 0,0,-1, c, 1,1), + video::S3DVertex(-r,-r,-r, 0,0,-1, c, 0,1), + // z+ + video::S3DVertex(-r,+r,+r, 0,0,+1, c, 0,0), + video::S3DVertex(-r,-r,+r, 0,0,+1, c, 0,1), + video::S3DVertex(+r,-r,+r, 0,0,+1, c, 1,1), + video::S3DVertex(+r,+r,+r, 0,0,+1, c, 1,0), }; - u16 indices[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4}; + u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4}; buf->append(vertices, 8, indices, 12); } - f32 pixelsize_x = 1 / (f32)resolution_x; - f32 pixelsize_y = 1 / (f32)resolution_y; + f32 pixelsize_x = 1 / (f32) resolution_x; + f32 pixelsize_y = 1 / (f32) resolution_y; for (int i = 0; i < resolution_x; ++i) { f32 pixelpos_x = i * pixelsize_x - 0.5; @@ -76,18 +76,18 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y) f32 tex0 = (i + 0.1) * pixelsize_x; f32 tex1 = (i + 0.9) * pixelsize_x; video::S3DVertex vertices[8] = { - // x- - video::S3DVertex(x0, -r, -r, -1, 0, 0, c, tex0, 1), - video::S3DVertex(x0, -r, +r, -1, 0, 0, c, tex1, 1), - video::S3DVertex(x0, +r, +r, -1, 0, 0, c, tex1, 0), - video::S3DVertex(x0, +r, -r, -1, 0, 0, c, tex0, 0), - // x+ - video::S3DVertex(x1, -r, -r, +1, 0, 0, c, tex0, 1), - video::S3DVertex(x1, +r, -r, +1, 0, 0, c, tex0, 0), - video::S3DVertex(x1, +r, +r, +1, 0, 0, c, tex1, 0), - video::S3DVertex(x1, -r, +r, +1, 0, 0, c, tex1, 1), + // x- + video::S3DVertex(x0,-r,-r, -1,0,0, c, tex0,1), + video::S3DVertex(x0,-r,+r, -1,0,0, c, tex1,1), + video::S3DVertex(x0,+r,+r, -1,0,0, c, tex1,0), + video::S3DVertex(x0,+r,-r, -1,0,0, c, tex0,0), + // x+ + video::S3DVertex(x1,-r,-r, +1,0,0, c, tex0,1), + video::S3DVertex(x1,+r,-r, +1,0,0, c, tex0,0), + video::S3DVertex(x1,+r,+r, +1,0,0, c, tex1,0), + video::S3DVertex(x1,-r,+r, +1,0,0, c, tex1,1), }; - u16 indices[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4}; + u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4}; buf->append(vertices, 8, indices, 12); } for (int i = 0; i < resolution_y; ++i) { @@ -97,18 +97,18 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y) f32 tex0 = (i + 0.1) * pixelsize_y; f32 tex1 = (i + 0.9) * pixelsize_y; video::S3DVertex vertices[8] = { - // y- - video::S3DVertex(-r, y0, -r, 0, -1, 0, c, 0, tex0), - video::S3DVertex(+r, y0, -r, 0, -1, 0, c, 1, tex0), - video::S3DVertex(+r, y0, +r, 0, -1, 0, c, 1, tex1), - video::S3DVertex(-r, y0, +r, 0, -1, 0, c, 0, tex1), - // y+ - video::S3DVertex(-r, y1, -r, 0, +1, 0, c, 0, tex0), - video::S3DVertex(-r, y1, +r, 0, +1, 0, c, 0, tex1), - video::S3DVertex(+r, y1, +r, 0, +1, 0, c, 1, tex1), - video::S3DVertex(+r, y1, -r, 0, +1, 0, c, 1, tex0), + // y- + video::S3DVertex(-r,y0,-r, 0,-1,0, c, 0,tex0), + video::S3DVertex(+r,y0,-r, 0,-1,0, c, 1,tex0), + video::S3DVertex(+r,y0,+r, 0,-1,0, c, 1,tex1), + video::S3DVertex(-r,y0,+r, 0,-1,0, c, 0,tex1), + // y+ + video::S3DVertex(-r,y1,-r, 0,+1,0, c, 0,tex0), + video::S3DVertex(-r,y1,+r, 0,+1,0, c, 0,tex1), + video::S3DVertex(+r,y1,+r, 0,+1,0, c, 1,tex1), + video::S3DVertex(+r,y1,-r, 0,+1,0, c, 1,tex0), }; - u16 indices[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4}; + u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4}; buf->append(vertices, 8, indices, 12); } @@ -116,7 +116,7 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y) scene::SMesh *mesh = new scene::SMesh(); mesh->addMeshBuffer(buf); buf->drop(); - scaleMesh(mesh, scale); // also recalculates bounding box + scaleMesh(mesh, scale); // also recalculates bounding box return mesh; } @@ -131,7 +131,7 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y) rendering related classes (such as WieldMeshSceneNode) will be used from the rendering thread only. */ -class ExtrusionMeshCache : public IReferenceCounted +class ExtrusionMeshCache: public IReferenceCounted { public: // Constructor @@ -141,7 +141,7 @@ class ExtrusionMeshCache : public IReferenceCounted resolution <= MAX_EXTRUSION_MESH_RESOLUTION; resolution *= 2) { m_extrusion_meshes[resolution] = - createExtrusionMesh(resolution, resolution); + createExtrusionMesh(resolution, resolution); } m_cube = createCubeMesh(v3f(1.0, 1.0, 1.0)); } @@ -155,7 +155,7 @@ class ExtrusionMeshCache : public IReferenceCounted } // Get closest extrusion mesh for given image dimensions // Caller must drop the returned pointer - scene::IMesh *create(core::dimension2d dim) + scene::IMesh* create(core::dimension2d dim) { // handle non-power of two textures inefficiently without cache if (!is_power_of_two(dim.Width) || !is_power_of_two(dim.Height)) { @@ -164,8 +164,8 @@ class ExtrusionMeshCache : public IReferenceCounted int maxdim = MYMAX(dim.Width, dim.Height); - std::map::iterator it = - m_extrusion_meshes.lower_bound(maxdim); + std::map::iterator + it = m_extrusion_meshes.lower_bound(maxdim); if (it == m_extrusion_meshes.end()) { // no viable resolution found; use largest one @@ -179,23 +179,24 @@ class ExtrusionMeshCache : public IReferenceCounted } // Returns a 1x1x1 cube mesh with one meshbuffer (material) per face // Caller must drop the returned pointer - scene::IMesh *createCube() + scene::IMesh* createCube() { m_cube->grab(); return m_cube; } private: - std::map m_extrusion_meshes; + std::map m_extrusion_meshes; scene::IMesh *m_cube; }; ExtrusionMeshCache *g_extrusion_mesh_cache = NULL; -WieldMeshSceneNode::WieldMeshSceneNode(scene::ISceneManager *mgr, s32 id, bool lighting) : - scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), - m_material_type(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF), - m_lighting(lighting) + +WieldMeshSceneNode::WieldMeshSceneNode(scene::ISceneManager *mgr, s32 id, bool lighting): + scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), + m_material_type(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF), + m_lighting(lighting) { m_enable_shaders = g_settings->getBool("enable_shaders"); m_anisotropic_filter = g_settings->getBool("anisotropic_filter"); @@ -228,7 +229,8 @@ WieldMeshSceneNode::~WieldMeshSceneNode() g_extrusion_mesh_cache = nullptr; } -void WieldMeshSceneNode::setCube(const ContentFeatures &f, v3f wield_scale) +void WieldMeshSceneNode::setCube(const ContentFeatures &f, + v3f wield_scale) { scene::IMesh *cubemesh = g_extrusion_mesh_cache->createCube(); scene::SMesh *copy = cloneMesh(cubemesh); @@ -240,8 +242,8 @@ void WieldMeshSceneNode::setCube(const ContentFeatures &f, v3f wield_scale) } void WieldMeshSceneNode::setExtruded(const std::string &imagename, - const std::string &overlay_name, v3f wield_scale, ITextureSource *tsrc, - u8 num_frames) + const std::string &overlay_name, v3f wield_scale, ITextureSource *tsrc, + u8 num_frames) { video::ITexture *texture = tsrc->getTexture(imagename); if (!texture) { @@ -249,7 +251,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, return; } video::ITexture *overlay_texture = - overlay_name.empty() ? NULL : tsrc->getTexture(overlay_name); + overlay_name.empty() ? NULL : tsrc->getTexture(overlay_name); core::dimension2d dim = texture->getSize(); // Detect animation texture and pull off top frame instead of using entire thing @@ -260,8 +262,9 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, scene::IMesh *original = g_extrusion_mesh_cache->create(dim); scene::SMesh *mesh = cloneMesh(original); original->drop(); - // set texture - mesh->getMeshBuffer(0)->getMaterial().setTexture(0, tsrc->getTexture(imagename)); + //set texture + mesh->getMeshBuffer(0)->getMaterial().setTexture(0, + tsrc->getTexture(imagename)); if (overlay_texture) { scene::IMeshBuffer *copy = cloneMeshBuffer(mesh->getMeshBuffer(0)); copy->getMaterial().setTexture(0, overlay_texture); @@ -291,8 +294,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, } material.setFlag(video::EMF_ANISOTROPIC_FILTER, m_anisotropic_filter); // mipmaps cause "thin black line" artifacts -#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || \ - IRRLICHT_VERSION_MAJOR >= 2 +#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 material.setFlag(video::EMF_USE_MIP_MAPS, false); #endif if (m_enable_shaders) { @@ -301,8 +303,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, } } -scene::SMesh *createSpecialNodeMesh( - Client *client, content_t id, std::vector *colors) +scene::SMesh *createSpecialNodeMesh(Client *client, content_t id, std::vector *colors) { MeshMakeData mesh_make_data(client, false, false); MeshCollector collector; @@ -324,17 +325,16 @@ scene::SMesh *createSpecialNodeMesh( buf->Material.setTexture(0, p.layer.texture); p.layer.applyMaterialOptions(buf->Material); mesh->addMeshBuffer(buf); - buf->append(&p.vertices[0], p.vertices.size(), &p.indices[0], - p.indices.size()); + buf->append(&p.vertices[0], p.vertices.size(), + &p.indices[0], p.indices.size()); buf->drop(); colors->push_back( - ItemPartColor(p.layer.has_color, p.layer.color)); + ItemPartColor(p.layer.has_color, p.layer.color)); } return mesh; } -void WieldMeshSceneNode::setItem( - const ItemStack &item, Client *client, bool check_wield_image) +void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client, bool check_wield_image) { ITextureSource *tsrc = client->getTextureSource(); IItemDefManager *idef = client->getItemDefManager(); @@ -347,8 +347,7 @@ void WieldMeshSceneNode::setItem( scene::SMesh *mesh = nullptr; if (m_enable_shaders) { - u32 shader_id = shdrsrc->getShader( - "object_shader", TILE_MATERIAL_BASIC, NDT_NORMAL); + u32 shader_id = shdrsrc->getShader("object_shader", TILE_MATERIAL_BASIC, NDT_NORMAL); m_material_type = shdrsrc->getShaderInfo(shader_id).material; } @@ -358,7 +357,8 @@ void WieldMeshSceneNode::setItem( // If wield_image needs to be checked and is defined, it overrides everything else if (!def.wield_image.empty() && check_wield_image) { - setExtruded(def.wield_image, def.wield_overlay, def.wield_scale, tsrc, 1); + setExtruded(def.wield_image, def.wield_overlay, def.wield_scale, tsrc, + 1); m_colors.emplace_back(); // overlay is white, if present m_colors.emplace_back(true, video::SColor(0xFFFFFFFF)); @@ -372,64 +372,55 @@ void WieldMeshSceneNode::setItem( // e.g. mesh nodes and nodeboxes mesh = cloneMesh(f.mesh_ptr[0]); postProcessNodeMesh(mesh, f, m_enable_shaders, true, - &m_material_type, &m_colors); + &m_material_type, &m_colors); changeToMesh(mesh); mesh->drop(); // mesh is pre-scaled by BS * f->visual_scale - m_meshnode->setScale(def.wield_scale * WIELD_SCALE_FACTOR / - (BS * f.visual_scale)); + m_meshnode->setScale( + def.wield_scale * WIELD_SCALE_FACTOR + / (BS * f.visual_scale)); } else { switch (f.drawtype) { - case NDT_AIRLIKE: { - changeToMesh(nullptr); - break; - } - case NDT_PLANTLIKE: { - setExtruded(tsrc->getTextureName( - f.tiles[0].layers[0] - .texture_id), - tsrc->getTextureName( - f.tiles[0].layers[1] - .texture_id), + case NDT_AIRLIKE: { + changeToMesh(nullptr); + break; + } + case NDT_PLANTLIKE: { + setExtruded(tsrc->getTextureName(f.tiles[0].layers[0].texture_id), + tsrc->getTextureName(f.tiles[0].layers[1].texture_id), def.wield_scale, tsrc, - f.tiles[0].layers[0] - .animation_frame_count); - // Add color - const TileLayer &l0 = f.tiles[0].layers[0]; - m_colors.emplace_back(l0.has_color, l0.color); - const TileLayer &l1 = f.tiles[0].layers[1]; - m_colors.emplace_back(l1.has_color, l1.color); - break; - } - case NDT_PLANTLIKE_ROOTED: { - setExtruded(tsrc->getTextureName( - f.special_tiles[0] - .layers[0] - .texture_id), + f.tiles[0].layers[0].animation_frame_count); + // Add color + const TileLayer &l0 = f.tiles[0].layers[0]; + m_colors.emplace_back(l0.has_color, l0.color); + const TileLayer &l1 = f.tiles[0].layers[1]; + m_colors.emplace_back(l1.has_color, l1.color); + break; + } + case NDT_PLANTLIKE_ROOTED: { + setExtruded(tsrc->getTextureName(f.special_tiles[0].layers[0].texture_id), "", def.wield_scale, tsrc, - f.special_tiles[0] - .layers[0] - .animation_frame_count); - // Add color - const TileLayer &l0 = f.special_tiles[0].layers[0]; - m_colors.emplace_back(l0.has_color, l0.color); - break; - } - case NDT_NORMAL: - case NDT_ALLFACES: - case NDT_LIQUID: - case NDT_FLOWINGLIQUID: { - setCube(f, def.wield_scale); - break; - } - default: { - mesh = createSpecialNodeMesh(client, id, &m_colors); - changeToMesh(mesh); - mesh->drop(); - m_meshnode->setScale(def.wield_scale * - WIELD_SCALE_FACTOR / - (BS * f.visual_scale)); - } + f.special_tiles[0].layers[0].animation_frame_count); + // Add color + const TileLayer &l0 = f.special_tiles[0].layers[0]; + m_colors.emplace_back(l0.has_color, l0.color); + break; + } + case NDT_NORMAL: + case NDT_ALLFACES: + case NDT_LIQUID: + case NDT_FLOWINGLIQUID: { + setCube(f, def.wield_scale); + break; + } + default: { + mesh = createSpecialNodeMesh(client, id, &m_colors); + changeToMesh(mesh); + mesh->drop(); + m_meshnode->setScale( + def.wield_scale * WIELD_SCALE_FACTOR + / (BS * f.visual_scale)); + } } } u32 material_count = m_meshnode->getMaterialCount(); @@ -442,9 +433,10 @@ void WieldMeshSceneNode::setItem( material.setFlag(video::EMF_TRILINEAR_FILTER, m_trilinear_filter); } return; - } else if (!def.inventory_image.empty()) { + } + else if (!def.inventory_image.empty()) { setExtruded(def.inventory_image, def.inventory_overlay, def.wield_scale, - tsrc, 1); + tsrc, 1); m_colors.emplace_back(); // overlay is white, if present m_colors.emplace_back(true, video::SColor(0xFFFFFFFF)); @@ -470,8 +462,10 @@ void WieldMeshSceneNode::setColor(video::SColor c) video::SColor bc(m_base_color); if ((m_colors.size() > j) && (m_colors[j].override_base)) bc = m_colors[j].color; - video::SColor buffercolor(255, bc.getRed() * red / 255, - bc.getGreen() * green / 255, bc.getBlue() * blue / 255); + video::SColor buffercolor(255, + bc.getRed() * red / 255, + bc.getGreen() * green / 255, + bc.getBlue() * blue / 255); scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); if (m_enable_shaders) @@ -508,7 +502,7 @@ void WieldMeshSceneNode::changeToMesh(scene::IMesh *mesh) scene::IMesh *dummymesh = g_extrusion_mesh_cache->createCube(); m_meshnode->setVisible(false); m_meshnode->setMesh(dummymesh); - dummymesh->drop(); // m_meshnode grabbed it + dummymesh->drop(); // m_meshnode grabbed it } else { m_meshnode->setMesh(mesh); } @@ -528,9 +522,8 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) const ContentFeatures &f = ndef->get(def.name); content_t id = ndef->getId(def.name); - FATAL_ERROR_IF(!g_extrusion_mesh_cache, - "Extrusion mesh cache is not yet initialized"); - + FATAL_ERROR_IF(!g_extrusion_mesh_cache, "Extrusion mesh cache is not yet initialized"); + scene::SMesh *mesh = nullptr; // Shading is on by default @@ -538,7 +531,8 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) // If inventory_image is defined, it overrides everything else if (!def.inventory_image.empty()) { - mesh = getExtrudedMesh(tsrc, def.inventory_image, def.inventory_overlay); + mesh = getExtrudedMesh(tsrc, def.inventory_image, + def.inventory_overlay); result->buffer_colors.emplace_back(); // overlay is white, if present result->buffer_colors.emplace_back(true, video::SColor(0xFFFFFFFF)); @@ -549,57 +543,45 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) mesh = cloneMesh(f.mesh_ptr[0]); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); postProcessNodeMesh(mesh, f, false, false, nullptr, - &result->buffer_colors); + &result->buffer_colors); } else { switch (f.drawtype) { - case NDT_PLANTLIKE: { - mesh = getExtrudedMesh(tsrc, - tsrc->getTextureName( - f.tiles[0].layers[0] - .texture_id), - tsrc->getTextureName( - f.tiles[0].layers[1] - .texture_id)); - // Add color - const TileLayer &l0 = f.tiles[0].layers[0]; - result->buffer_colors.emplace_back( - l0.has_color, l0.color); - const TileLayer &l1 = f.tiles[0].layers[1]; - result->buffer_colors.emplace_back( - l1.has_color, l1.color); - break; - } - case NDT_PLANTLIKE_ROOTED: { - mesh = getExtrudedMesh(tsrc, - tsrc->getTextureName( - f.special_tiles[0] - .layers[0] - .texture_id), - ""); - // Add color - const TileLayer &l0 = f.special_tiles[0].layers[0]; - result->buffer_colors.emplace_back( - l0.has_color, l0.color); - break; - } - case NDT_NORMAL: - case NDT_ALLFACES: - case NDT_LIQUID: - case NDT_FLOWINGLIQUID: { - scene::IMesh *cube = g_extrusion_mesh_cache->createCube(); - mesh = cloneMesh(cube); - cube->drop(); - scaleMesh(mesh, v3f(1.2, 1.2, 1.2)); - // add overlays - postProcessNodeMesh(mesh, f, false, false, nullptr, + case NDT_PLANTLIKE: { + mesh = getExtrudedMesh(tsrc, + tsrc->getTextureName(f.tiles[0].layers[0].texture_id), + tsrc->getTextureName(f.tiles[0].layers[1].texture_id)); + // Add color + const TileLayer &l0 = f.tiles[0].layers[0]; + result->buffer_colors.emplace_back(l0.has_color, l0.color); + const TileLayer &l1 = f.tiles[0].layers[1]; + result->buffer_colors.emplace_back(l1.has_color, l1.color); + break; + } + case NDT_PLANTLIKE_ROOTED: { + mesh = getExtrudedMesh(tsrc, + tsrc->getTextureName(f.special_tiles[0].layers[0].texture_id), ""); + // Add color + const TileLayer &l0 = f.special_tiles[0].layers[0]; + result->buffer_colors.emplace_back(l0.has_color, l0.color); + break; + } + case NDT_NORMAL: + case NDT_ALLFACES: + case NDT_LIQUID: + case NDT_FLOWINGLIQUID: { + scene::IMesh *cube = g_extrusion_mesh_cache->createCube(); + mesh = cloneMesh(cube); + cube->drop(); + scaleMesh(mesh, v3f(1.2, 1.2, 1.2)); + // add overlays + postProcessNodeMesh(mesh, f, false, false, nullptr, &result->buffer_colors); - break; - } - default: { - mesh = createSpecialNodeMesh( - client, id, &result->buffer_colors); - scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); - } + break; + } + default: { + mesh = createSpecialNodeMesh(client, id, &result->buffer_colors); + scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); + } } } @@ -621,8 +603,10 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) result->mesh = mesh; } -scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename, - const std::string &overlay_name) + + +scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, + const std::string &imagename, const std::string &overlay_name) { // check textures video::ITexture *texture = tsrc->getTextureForMesh(imagename); @@ -630,7 +614,7 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename return NULL; } video::ITexture *overlay_texture = - (overlay_name.empty()) ? NULL : tsrc->getTexture(overlay_name); + (overlay_name.empty()) ? NULL : tsrc->getTexture(overlay_name); // get mesh core::dimension2d dim = texture->getSize(); @@ -638,8 +622,9 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename scene::SMesh *mesh = cloneMesh(original); original->drop(); - // set texture - mesh->getMeshBuffer(0)->getMaterial().setTexture(0, tsrc->getTexture(imagename)); + //set texture + mesh->getMeshBuffer(0)->getMaterial().setTexture(0, + tsrc->getTexture(imagename)); if (overlay_texture) { scene::IMeshBuffer *copy = cloneMeshBuffer(mesh->getMeshBuffer(0)); copy->getMaterial().setTexture(0, overlay_texture); @@ -663,9 +648,9 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename return mesh; } -void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders, - bool set_material, const video::E_MATERIAL_TYPE *mattype, - std::vector *colors, bool apply_scale) +void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, + bool use_shaders, bool set_material, const video::E_MATERIAL_TYPE *mattype, + std::vector *colors, bool apply_scale) { u32 mc = mesh->getMeshBufferCount(); // Allocate colors for existing buffers @@ -686,11 +671,10 @@ void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_ mesh->addMeshBuffer(copy); copy->drop(); buf = copy; - colors->push_back(ItemPartColor( - layer->has_color, layer->color)); + colors->push_back( + ItemPartColor(layer->has_color, layer->color)); } else { - (*colors)[i] = ItemPartColor( - layer->has_color, layer->color); + (*colors)[i] = ItemPartColor(layer->has_color, layer->color); } video::SMaterial &material = buf->getMaterial(); if (set_material) @@ -707,13 +691,10 @@ void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_ if (use_shaders) { if (layer->normal_texture) { if (layer->animation_frame_count > 1) { - const FrameSpec &animation_frame = - (*layer->frames)[0]; - material.setTexture(1, - animation_frame.normal_texture); + const FrameSpec &animation_frame = (*layer->frames)[0]; + material.setTexture(1, animation_frame.normal_texture); } else - material.setTexture( - 1, layer->normal_texture); + material.setTexture(1, layer->normal_texture); } material.setTexture(2, layer->flags_texture); } diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 9effa7eb7..602a44c90 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -34,33 +34,33 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "face_position_cache.h" const char *ClientInterface::statenames[] = { - "Invalid", - "Disconnecting", - "Denied", - "Created", - "AwaitingInit2", - "HelloSent", - "InitDone", - "DefinitionsSent", - "Active", - "SudoMode", + "Invalid", + "Disconnecting", + "Denied", + "Created", + "AwaitingInit2", + "HelloSent", + "InitDone", + "DefinitionsSent", + "Active", + "SudoMode", }; + + std::string ClientInterface::state2Name(ClientState state) { return statenames[state]; } RemoteClient::RemoteClient() : - m_max_simul_sends(g_settings->getU16( - "max_simultaneous_block_sends_per_client")), - m_min_time_from_building(g_settings->getFloat( - "full_block_send_enable_min_time_from_building")), - m_max_send_distance(g_settings->getS16("max_block_send_distance")), - m_block_optimize_distance( - g_settings->getS16("block_send_optimize_distance")), - m_max_gen_distance(g_settings->getS16("max_block_generate_distance")), - m_occ_cull(g_settings->getBool("server_side_occlusion_culling")) + m_max_simul_sends(g_settings->getU16("max_simultaneous_block_sends_per_client")), + m_min_time_from_building( + g_settings->getFloat("full_block_send_enable_min_time_from_building")), + m_max_send_distance(g_settings->getS16("max_block_send_distance")), + m_block_optimize_distance(g_settings->getS16("block_send_optimize_distance")), + m_max_gen_distance(g_settings->getS16("max_block_generate_distance")), + m_occ_cull(g_settings->getBool("server_side_occlusion_culling")) { } @@ -90,8 +90,11 @@ LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env) return dynamic_cast(ao); } -void RemoteClient::GetNextBlocks(ServerEnvironment *env, EmergeManager *emerge, - float dtime, std::vector &dest) +void RemoteClient::GetNextBlocks ( + ServerEnvironment *env, + EmergeManager * emerge, + float dtime, + std::vector &dest) { // Increment timers m_nothing_to_send_pause_timer -= dtime; @@ -111,15 +114,15 @@ void RemoteClient::GetNextBlocks(ServerEnvironment *env, EmergeManager *emerge, // Won't send anything if already sending if (m_blocks_sending.size() >= m_max_simul_sends) { - // infostream<<"Not sending any blocks, Queue full."<getBasePosition(); // if the player is attached, get the velocity from the attached object LuaEntitySAO *lsao = getAttachedObject(sao, env); - const v3f &playerspeed = lsao ? lsao->getVelocity() : player->getSpeed(); - v3f playerspeeddir(0, 0, 0); + const v3f &playerspeed = lsao? lsao->getVelocity() : player->getSpeed(); + v3f playerspeeddir(0,0,0); if (playerspeed.getLength() > 1.0f * BS) playerspeeddir = playerspeed / playerspeed.getLength(); // Predict to next block @@ -131,7 +134,7 @@ void RemoteClient::GetNextBlocks(ServerEnvironment *env, EmergeManager *emerge, // Camera position and direction v3f camera_pos = sao->getEyePosition(); - v3f camera_dir = v3f(0, 0, 1); + v3f camera_dir = v3f(0,0,1); camera_dir.rotateYZBy(sao->getLookPitch()); camera_dir.rotateXZBy(sao->getRotation().Y); @@ -154,14 +157,14 @@ void RemoteClient::GetNextBlocks(ServerEnvironment *env, EmergeManager *emerge, if (m_nearest_unsent_reset_timer > 20.0f) { m_nearest_unsent_reset_timer = 0.0f; m_nearest_unsent_d = 0; - // infostream<<"Resetting m_nearest_unsent_d for " + //infostream<<"Resetting m_nearest_unsent_d for " // <getPlayerName(peer_id)< &blocks) +void RemoteClient::SetBlocksNotSent(std::map &blocks) { m_nearest_unsent_d = 0; m_nothing_to_send_pause_timer = 0; @@ -468,9 +461,10 @@ void RemoteClient::SetBlocksNotSent(std::map &blocks) void RemoteClient::notifyEvent(ClientStateEvent event) { std::ostringstream myerror; - switch (m_state) { + switch (m_state) + { case CS_Invalid: - // intentionally do nothing + //intentionally do nothing break; case CS_Created: switch (event) { @@ -496,12 +490,13 @@ void RemoteClient::notifyEvent(ClientStateEvent event) /* don't do anything if in denied state */ break; case CS_HelloSent: - switch (event) { + switch(event) + { case CSE_AuthAccept: m_state = CS_AwaitingInit2; if (chosen_mech == AUTH_MECHANISM_SRP || chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD) - srp_verifier_delete((SRPVerifier *)auth_data); + srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; case CSE_Disconnect: @@ -511,17 +506,17 @@ void RemoteClient::notifyEvent(ClientStateEvent event) m_state = CS_Denied; if (chosen_mech == AUTH_MECHANISM_SRP || chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD) - srp_verifier_delete((SRPVerifier *)auth_data); + srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; default: - myerror << "HelloSent: Invalid client state transition! " - << event; + myerror << "HelloSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_AwaitingInit2: - switch (event) { + switch(event) + { case CSE_GotInit2: confirmSerializationVersion(); m_state = CS_InitDone; @@ -541,7 +536,8 @@ void RemoteClient::notifyEvent(ClientStateEvent event) break; case CS_InitDone: - switch (event) { + switch(event) + { case CSE_SetDefinitionsSent: m_state = CS_DefinitionsSent; break; @@ -559,7 +555,8 @@ void RemoteClient::notifyEvent(ClientStateEvent event) } break; case CS_DefinitionsSent: - switch (event) { + switch(event) + { case CSE_SetClientReady: m_state = CS_Active; break; @@ -571,13 +568,13 @@ void RemoteClient::notifyEvent(ClientStateEvent event) break; /* Init GotInit2 SetDefinitionsSent */ default: - myerror << "DefinitionsSent: Invalid client state transition! " - << event; + myerror << "DefinitionsSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_Active: - switch (event) { + switch(event) + { case CSE_SetDenied: m_state = CS_Denied; break; @@ -587,7 +584,7 @@ void RemoteClient::notifyEvent(ClientStateEvent event) case CSE_SudoSuccess: m_state = CS_SudoMode; if (chosen_mech == AUTH_MECHANISM_SRP) - srp_verifier_delete((SRPVerifier *)auth_data); + srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */ @@ -598,7 +595,8 @@ void RemoteClient::notifyEvent(ClientStateEvent event) } break; case CS_SudoMode: - switch (event) { + switch(event) + { case CSE_SetDenied: m_state = CS_Denied; break; @@ -625,9 +623,13 @@ u64 RemoteClient::uptime() const return porting::getTimeS() - m_connection_time; } -ClientInterface::ClientInterface(const std::shared_ptr &con) : - m_con(con), m_env(NULL), m_print_info_timer(0.0f) +ClientInterface::ClientInterface(const std::shared_ptr & con) +: + m_con(con), + m_env(NULL), + m_print_info_timer(0.0f) { + } ClientInterface::~ClientInterface() { @@ -691,8 +693,9 @@ void ClientInterface::UpdatePlayerList() std::vector clients = getClientIDs(); m_clients_names.clear(); + if (!clients.empty()) - infostream << "Players:" << std::endl; + infostream<<"Players:"<getPlayer(i); @@ -704,7 +707,7 @@ void ClientInterface::UpdatePlayerList() { RecursiveMutexAutoLock clientslock(m_clients_mutex); - RemoteClient *client = lockedGetClientNoEx(i); + RemoteClient* client = lockedGetClientNoEx(i); if (client) client->PrintInfo(infostream); } @@ -714,8 +717,8 @@ void ClientInterface::UpdatePlayerList() } } -void ClientInterface::send( - session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable) +void ClientInterface::send(session_t peer_id, u8 channelnum, + NetworkPacket *pkt, bool reliable) { m_con->Send(peer_id, channelnum, pkt, reliable); } @@ -728,17 +731,14 @@ void ClientInterface::sendToAll(NetworkPacket *pkt) if (client->net_proto_version != 0) { m_con->Send(client->peer_id, - clientCommandFactoryTable[pkt->getCommand()] - .channel, - pkt, - clientCommandFactoryTable[pkt->getCommand()] - .reliable); + clientCommandFactoryTable[pkt->getCommand()].channel, pkt, + clientCommandFactoryTable[pkt->getCommand()].reliable); } } } -void ClientInterface::sendToAllCompat( - NetworkPacket *pkt, NetworkPacket *legacypkt, u16 min_proto_ver) +void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt, + u16 min_proto_ver) { RecursiveMutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { @@ -751,20 +751,18 @@ void ClientInterface::sendToAllCompat( pkt_to_send = legacypkt; } else { warningstream << "Client with unhandled version to handle: '" - << client->net_proto_version << "'"; + << client->net_proto_version << "'"; continue; } m_con->Send(client->peer_id, - clientCommandFactoryTable[pkt_to_send->getCommand()] - .channel, - pkt_to_send, - clientCommandFactoryTable[pkt_to_send->getCommand()] - .reliable); + clientCommandFactoryTable[pkt_to_send->getCommand()].channel, + pkt_to_send, + clientCommandFactoryTable[pkt_to_send->getCommand()].reliable); } } -RemoteClient *ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min) +RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min) { RecursiveMutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::const_iterator n = m_clients.find(peer_id); @@ -779,8 +777,7 @@ RemoteClient *ClientInterface::getClientNoEx(session_t peer_id, ClientState stat return NULL; } -RemoteClient *ClientInterface::lockedGetClientNoEx( - session_t peer_id, ClientState state_min) +RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min) { RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their @@ -830,14 +827,14 @@ void ClientInterface::DeleteClient(session_t peer_id) /* Mark objects to be not known by the client */ - // TODO this should be done by client destructor!!! + //TODO this should be done by client destructor!!! RemoteClient *client = n->second; // Handle objects for (u16 id : client->m_known_objects) { // Get object - ServerActiveObject *obj = m_env->getActiveObject(id); + ServerActiveObject* obj = m_env->getActiveObject(id); - if (obj && obj->m_known_by_count > 0) + if(obj && obj->m_known_by_count > 0) obj->m_known_by_count--; } @@ -853,8 +850,7 @@ void ClientInterface::CreateClient(session_t peer_id) // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // The client shouldn't already exist - if (n != m_clients.end()) - return; + if (n != m_clients.end()) return; // Create client RemoteClient *client = new RemoteClient(); @@ -876,8 +872,10 @@ void ClientInterface::event(session_t peer_id, ClientStateEvent event) n->second->notifyEvent(event); } - if ((event == CSE_SetClientReady) || (event == CSE_Disconnect) || - (event == CSE_SetDenied)) { + if ((event == CSE_SetClientReady) || + (event == CSE_Disconnect) || + (event == CSE_SetDenied)) + { UpdatePlayerList(); } } @@ -896,8 +894,8 @@ u16 ClientInterface::getProtocolVersion(session_t peer_id) return n->second->net_proto_version; } -void ClientInterface::setClientVersion( - session_t peer_id, u8 major, u8 minor, u8 patch, const std::string &full) +void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch, + const std::string &full) { RecursiveMutexAutoLock conlock(m_clients_mutex); diff --git a/src/clientiface.h b/src/clientiface.h index e629066c4..83fa6fe99 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -19,10 +19,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -#include "irr_v3d.h" // for irrlicht datatypes +#include "irr_v3d.h" // for irrlicht datatypes #include "constants.h" -#include "serialization.h" // for SER_FMT_VER_INVALID +#include "serialization.h" // for SER_FMT_VER_INVALID #include "network/networkpacket.h" #include "network/networkprotocol.h" #include "porting.h" @@ -41,49 +41,49 @@ class EmergeManager; Start (peer connect) - | - v + | + v /-----------------\ | | | Created | | | \-----------------/ - | depending of the incoming packet - ---------------------------------------- - v - +-----------------------------+ - |IN: | - | TOSERVER_INIT | - +-----------------------------+ - | invalid playername - | or denied by mod - v - +-----------------------------+ - |OUT: | - | TOCLIENT_HELLO | - +-----------------------------+ - | - | - v + | depending of the incoming packet + ---------------------------------------- + v + +-----------------------------+ + |IN: | + | TOSERVER_INIT | + +-----------------------------+ + | invalid playername + | or denied by mod + v + +-----------------------------+ + |OUT: | + | TOCLIENT_HELLO | + +-----------------------------+ + | + | + v /-----------------\ /-----------------\ | | | | | AwaitingInit2 |<--------- | HelloSent | | | | | | \-----------------/ | \-----------------/ - | | | + | | | +-----------------------------+ | *-----------------------------* Auth fails |IN: | | |Authentication, depending on |------------------ | TOSERVER_INIT2 | | | packet sent by client | | +-----------------------------+ | *-----------------------------* | - | | | | - | | | Authentication | - v | | successful | + | | | | + | | | Authentication | + v | | successful | /-----------------\ | v | | | | +-----------------------------+ | | InitDone | | |OUT: | | | | | | TOCLIENT_AUTH_ACCEPT | | \-----------------/ | +-----------------------------+ | - | | | | + | | | | +-----------------------------+ --------------------- | |OUT: | | | TOCLIENT_MOVEMENT | | @@ -93,25 +93,25 @@ class EmergeManager; | TOCLIENT_DETACHED_INVENTORY | | | TOCLIENT_TIME_OF_DAY | | +-----------------------------+ | - | | - | | - | ----------------------------- | - v | | | + | | + | | + | ----------------------------- | + v | | | /-----------------\ v | | | +-----------------------------+ | | DefinitionsSent | |IN: | | | | | TOSERVER_REQUEST_MEDIA | | \-----------------/ | | | - | +-----------------------------+ | - | ^ | | - | ----------------------------- | - v v + | +-----------------------------+ | + | ^ | | + | ----------------------------- | + v v +-----------------------------+ --------------------------------+ |IN: | | ^ | TOSERVER_CLIENT_READY | v | +-----------------------------+ +------------------------+ | - | |OUT: | | - v | TOCLIENT_ACCESS_DENIED | | + | |OUT: | | + v | TOCLIENT_ACCESS_DENIED | | +-----------------------------+ +------------------------+ | |OUT: | | | | TOCLIENT_MOVE_PLAYER | v | @@ -123,8 +123,8 @@ class EmergeManager; | TOCLIENT_BREATH | | | TOCLIENT_DEATHSCREEN | | +-----------------------------+ | - | | - v | + | | + v | /-----------------\ async mod action (ban, kick) | | |--------------------------------------------------------------- ---->| Active | @@ -159,14 +159,14 @@ class EmergeManager; | | +-----------------------------+ | | sets password accordingly |IN: | -------------------+-------------------------------| TOSERVER_FIRST_SRP | - +-----------------------------+ + +-----------------------------+ */ -namespace con -{ -class Connection; +namespace con { + class Connection; } + // Also make sure to update the ClientInterface::statenames // array when modifying these enums @@ -205,14 +205,13 @@ enum ClientStateEvent */ struct PrioritySortedBlockTransfer { - PrioritySortedBlockTransfer( - float a_priority, const v3s16 &a_pos, session_t a_peer_id) + PrioritySortedBlockTransfer(float a_priority, const v3s16 &a_pos, session_t a_peer_id) { priority = a_priority; pos = a_pos; peer_id = a_peer_id; } - bool operator<(const PrioritySortedBlockTransfer &other) const + bool operator < (const PrioritySortedBlockTransfer &other) const { return priority < other.priority; } @@ -237,13 +236,15 @@ class RemoteClient /* Authentication information */ std::string enc_pwd = ""; bool create_player_on_auth_success = false; - AuthMechanism chosen_mech = AUTH_MECHANISM_NONE; + AuthMechanism chosen_mech = AUTH_MECHANISM_NONE; void *auth_data = nullptr; u32 allowed_auth_mechs = 0; u32 allowed_sudo_mechs = 0; - bool isSudoMechAllowed(AuthMechanism mech) { return allowed_sudo_mechs & mech; } - bool isMechAllowed(AuthMechanism mech) { return allowed_auth_mechs & mech; } + bool isSudoMechAllowed(AuthMechanism mech) + { return allowed_sudo_mechs & mech; } + bool isMechAllowed(AuthMechanism mech) + { return allowed_auth_mechs & mech; } RemoteClient(); ~RemoteClient() = default; @@ -253,15 +254,15 @@ class RemoteClient Environment should be locked when this is called. dtime is used for resetting send radius at slow interval */ - void GetNextBlocks(ServerEnvironment *env, EmergeManager *emerge, float dtime, - std::vector &dest); + void GetNextBlocks(ServerEnvironment *env, EmergeManager* emerge, + float dtime, std::vector &dest); void GotBlock(v3s16 p); void SentBlock(v3s16 p); void SetBlockNotSent(v3s16 p); - void SetBlocksNotSent(std::map &blocks); + void SetBlocksNotSent(std::map &blocks); /** * tell client about this block being modified right now. @@ -281,15 +282,16 @@ class RemoteClient // Increments timeouts and removes timed-out blocks from list // NOTE: This doesn't fix the server-not-sending-block bug // because it is related to emerging, not sending. - // void RunSendingTimeouts(float dtime, float timeout); + //void RunSendingTimeouts(float dtime, float timeout); void PrintInfo(std::ostream &o) { - o << "RemoteClient " << peer_id << ": " - << "m_blocks_sent.size()=" << m_blocks_sent.size() - << ", m_blocks_sending.size()=" << m_blocks_sending.size() - << ", m_nearest_unsent_d=" << m_nearest_unsent_d - << ", m_excess_gotblocks=" << m_excess_gotblocks << std::endl; + o<<"RemoteClient "< 0 && staticbox.MinEdge.Y - movingbox.MaxEdge.Y > - inner_margin) || - (speed.Y < 0 && movingbox.MinEdge.Y - staticbox.MaxEdge.Y > - inner_margin)) { - if ((std::max(movingbox.MaxEdge.X + speed.X * time, - staticbox.MaxEdge.X) - - std::min(movingbox.MinEdge.X + speed.X * time, - staticbox.MinEdge - .X) - - relbox.MinEdge.X < - 0) && - (std::max(movingbox.MaxEdge.Z + speed.Z * time, - staticbox.MaxEdge.Z) - - std::min(movingbox.MinEdge.Z + speed.Z * time, - staticbox.MinEdge - .Z) - - relbox.MinEdge.Z < - 0)) + inner_margin = std::max(-0.5f * (staticbox.MaxEdge.Y - staticbox.MinEdge.Y), -2.0f); + + if ((speed.Y > 0 && staticbox.MinEdge.Y - movingbox.MaxEdge.Y > inner_margin) || + (speed.Y < 0 && movingbox.MinEdge.Y - staticbox.MaxEdge.Y > inner_margin)) { + if ( + (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X) + - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X) + - relbox.MinEdge.X < 0) && + (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z) + - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z) + - relbox.MinEdge.Z < 0) + ) return COLLISION_AXIS_Y; } - } else { + } + else { return COLLISION_AXIS_NONE; } } @@ -155,29 +142,18 @@ CollisionAxis axisAlignedCollision(const aabb3f &staticbox, const aabb3f &moving time = std::max(*dtime, 0.0f); if (*dtime <= dtime_max) { - inner_margin = std::max( - -0.5f * (staticbox.MaxEdge.X - - staticbox.MinEdge.X), - -2.0f); - - if ((speed.X > 0 && staticbox.MinEdge.X - movingbox.MaxEdge.X > - inner_margin) || - (speed.X < 0 && movingbox.MinEdge.X - staticbox.MaxEdge.X > - inner_margin)) { - if ((std::max(movingbox.MaxEdge.Y + speed.Y * time, - staticbox.MaxEdge.Y) - - std::min(movingbox.MinEdge.Y + speed.Y * time, - staticbox.MinEdge - .Y) - - relbox.MinEdge.Y < - 0) && - (std::max(movingbox.MaxEdge.Z + speed.Z * time, - staticbox.MaxEdge.Z) - - std::min(movingbox.MinEdge.Z + speed.Z * time, - staticbox.MinEdge - .Z) - - relbox.MinEdge.Z < - 0)) + inner_margin = std::max(-0.5f * (staticbox.MaxEdge.X - staticbox.MinEdge.X), -2.0f); + + if ((speed.X > 0 && staticbox.MinEdge.X - movingbox.MaxEdge.X > inner_margin) || + (speed.X < 0 && movingbox.MinEdge.X - staticbox.MaxEdge.X > inner_margin)) { + if ( + (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y) + - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y) + - relbox.MinEdge.Y < 0) && + (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z) + - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z) + - relbox.MinEdge.Z < 0) + ) return COLLISION_AXIS_X; } } else { @@ -193,29 +169,18 @@ CollisionAxis axisAlignedCollision(const aabb3f &staticbox, const aabb3f &moving time = std::max(*dtime, 0.0f); if (*dtime <= dtime_max) { - inner_margin = std::max( - -0.5f * (staticbox.MaxEdge.Z - - staticbox.MinEdge.Z), - -2.0f); - - if ((speed.Z > 0 && staticbox.MinEdge.Z - movingbox.MaxEdge.Z > - inner_margin) || - (speed.Z < 0 && movingbox.MinEdge.Z - staticbox.MaxEdge.Z > - inner_margin)) { - if ((std::max(movingbox.MaxEdge.X + speed.X * time, - staticbox.MaxEdge.X) - - std::min(movingbox.MinEdge.X + speed.X * time, - staticbox.MinEdge - .X) - - relbox.MinEdge.X < - 0) && - (std::max(movingbox.MaxEdge.Y + speed.Y * time, - staticbox.MaxEdge.Y) - - std::min(movingbox.MinEdge.Y + speed.Y * time, - staticbox.MinEdge - .Y) - - relbox.MinEdge.Y < - 0)) + inner_margin = std::max(-0.5f * (staticbox.MaxEdge.Z - staticbox.MinEdge.Z), -2.0f); + + if ((speed.Z > 0 && staticbox.MinEdge.Z - movingbox.MaxEdge.Z > inner_margin) || + (speed.Z < 0 && movingbox.MinEdge.Z - staticbox.MaxEdge.Z > inner_margin)) { + if ( + (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X) + - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X) + - relbox.MinEdge.X < 0) && + (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y) + - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y) + - relbox.MinEdge.Y < 0) + ) return COLLISION_AXIS_Z; } } @@ -226,18 +191,19 @@ CollisionAxis axisAlignedCollision(const aabb3f &staticbox, const aabb3f &moving // Helper function: // Checks if moving the movingbox up by the given distance would hit a ceiling. -bool wouldCollideWithCeiling(const std::vector &cinfo, - const aabb3f &movingbox, f32 y_increase, f32 d) +bool wouldCollideWithCeiling( + const std::vector &cinfo, + const aabb3f &movingbox, + f32 y_increase, f32 d) { - // TimeTaker tt("wouldCollideWithCeiling"); + //TimeTaker tt("wouldCollideWithCeiling"); - assert(y_increase >= 0); // pre-condition + assert(y_increase >= 0); // pre-condition for (const auto &it : cinfo) { const aabb3f &staticbox = it.box; if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) && - (movingbox.MaxEdge.Y + y_increase > - staticbox.MinEdge.Y) && + (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) && (movingbox.MinEdge.X < staticbox.MaxEdge.X) && (movingbox.MaxEdge.X > staticbox.MinEdge.X) && (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) && @@ -249,7 +215,7 @@ bool wouldCollideWithCeiling(const std::vector &cinfo, } static inline void getNeighborConnectingFace(const v3s16 &p, - const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors) + const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors) { MapNode n2 = map->getNode(p); if (nodedef->nodeboxConnects(n, n2, v)) @@ -257,9 +223,11 @@ static inline void getNeighborConnectingFace(const v3s16 &p, } collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, - f32 pos_max_d, const aabb3f &box_0, f32 stepheight, f32 dtime, v3f *pos_f, - v3f *speed_f, v3f accel_f, ActiveObject *self, bool collideWithObjects, - bool jesus) + f32 pos_max_d, const aabb3f &box_0, + f32 stepheight, f32 dtime, + v3f *pos_f, v3f *speed_f, + v3f accel_f, ActiveObject *self, + bool collideWithObjects, bool jesus) { static bool time_notification_done = false; Map *map = &env->getMap(); @@ -274,10 +242,8 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, if (dtime > 0.5f) { if (!time_notification_done) { time_notification_done = true; - infostream << "collisionMoveSimple: maximum step interval " - "exceeded," - " lost movement details!" - << std::endl; + infostream << "collisionMoveSimple: maximum step interval exceeded," + " lost movement details!"< cinfo; { - // TimeTaker tt2("collisionMoveSimple collect boxes"); - ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", - SPT_AVG); - - v3f newpos_f = *pos_f + *speed_f * dtime; - v3f minpos_f(MYMIN(pos_f->X, newpos_f.X), - MYMIN(pos_f->Y, newpos_f.Y) + - 0.01f * BS, // bias rounding, player often - // at +/-n.5 - MYMIN(pos_f->Z, newpos_f.Z)); - v3f maxpos_f(MYMAX(pos_f->X, newpos_f.X), MYMAX(pos_f->Y, newpos_f.Y), - MYMAX(pos_f->Z, newpos_f.Z)); - v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1); - v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1); - - bool any_position_valid = false; - jesus = jesus && g_settings->getBool("jesus"); - - v3s16 p; - for (p.X = min.X; p.X <= max.X; p.X++) - for (p.Y = min.Y; p.Y <= max.Y; p.Y++) - for (p.Z = min.Z; p.Z <= max.Z; p.Z++) { - bool is_position_valid; - MapNode n = map->getNode(p, &is_position_valid); - - if (is_position_valid && - n.getContent() != - CONTENT_IGNORE) { - // Object collides into walkable nodes - - any_position_valid = true; - const NodeDefManager *nodedef = - gamedef->getNodeDefManager(); - const ContentFeatures &f = - nodedef->get(n); - - if (!(f.walkable || (jesus && f.isLiquid()))) - continue; - - int n_bouncy_value = itemgroup_get( - f.groups, "bouncy"); - - int neighbors = 0; - if (f.drawtype == NDT_NODEBOX && - f.node_box.type == - NODEBOX_CONNECTED) { - v3s16 p2 = p; - - p2.Y++; - getNeighborConnectingFace(p2, - nodedef, map, n, - 1, &neighbors); - - p2 = p; - p2.Y--; - getNeighborConnectingFace(p2, - nodedef, map, n, - 2, &neighbors); - - p2 = p; - p2.Z--; - getNeighborConnectingFace(p2, - nodedef, map, n, - 4, &neighbors); - - p2 = p; - p2.X--; - getNeighborConnectingFace(p2, - nodedef, map, n, - 8, &neighbors); - - p2 = p; - p2.Z++; - getNeighborConnectingFace(p2, - nodedef, map, n, - 16, &neighbors); - - p2 = p; - p2.X++; - getNeighborConnectingFace(p2, - nodedef, map, n, - 32, &neighbors); - } - std::vector nodeboxes; - n.getCollisionBoxes(gamedef->ndef(), - &nodeboxes, neighbors); - - // Calculate float position only once - v3f posf = intToFloat(p, BS); - for (auto box : nodeboxes) { - box.MinEdge += posf; - box.MaxEdge += posf; - cinfo.emplace_back(false, - n_bouncy_value, p, - box); - } - } else { - // Collide with unloaded nodes (position - // invalid) and loaded CONTENT_IGNORE - // nodes (position valid) - aabb3f box = getNodeBox(p, BS); - cinfo.emplace_back(true, 0, p, box); - } - } + //TimeTaker tt2("collisionMoveSimple collect boxes"); + ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG); + + v3f newpos_f = *pos_f + *speed_f * dtime; + v3f minpos_f( + MYMIN(pos_f->X, newpos_f.X), + MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5 + MYMIN(pos_f->Z, newpos_f.Z) + ); + v3f maxpos_f( + MYMAX(pos_f->X, newpos_f.X), + MYMAX(pos_f->Y, newpos_f.Y), + MYMAX(pos_f->Z, newpos_f.Z) + ); + v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1); + v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1); + + bool any_position_valid = false; + jesus = jesus && g_settings->getBool("jesus"); + + v3s16 p; + for (p.X = min.X; p.X <= max.X; p.X++) + for (p.Y = min.Y; p.Y <= max.Y; p.Y++) + for (p.Z = min.Z; p.Z <= max.Z; p.Z++) { + bool is_position_valid; + MapNode n = map->getNode(p, &is_position_valid); + + if (is_position_valid && n.getContent() != CONTENT_IGNORE) { + // Object collides into walkable nodes + + any_position_valid = true; + const NodeDefManager *nodedef = gamedef->getNodeDefManager(); + const ContentFeatures &f = nodedef->get(n); + + if (!(f.walkable || (jesus && f.isLiquid()))) + continue; + + int n_bouncy_value = itemgroup_get(f.groups, "bouncy"); + + int neighbors = 0; + if (f.drawtype == NDT_NODEBOX && + f.node_box.type == NODEBOX_CONNECTED) { + v3s16 p2 = p; + + p2.Y++; + getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors); - // Do not move if world has not loaded yet, since custom node boxes - // are not available for collision detection. - // This also intentionally occurs in the case of the object being - // positioned solely on loaded CONTENT_IGNORE nodes, no matter where they - // come from. - if (!any_position_valid) { - *speed_f = v3f(0, 0, 0); - return result; + p2 = p; + p2.Y--; + getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors); + + p2 = p; + p2.Z--; + getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors); + + p2 = p; + p2.X--; + getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors); + + p2 = p; + p2.Z++; + getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors); + + p2 = p; + p2.X++; + getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors); + } + std::vector nodeboxes; + n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors); + + // Calculate float position only once + v3f posf = intToFloat(p, BS); + for (auto box : nodeboxes) { + box.MinEdge += posf; + box.MaxEdge += posf; + cinfo.emplace_back(false, n_bouncy_value, p, box); + } + } else { + // Collide with unloaded nodes (position invalid) and loaded + // CONTENT_IGNORE nodes (position valid) + aabb3f box = getNodeBox(p, BS); + cinfo.emplace_back(true, 0, p, box); } + } + + // Do not move if world has not loaded yet, since custom node boxes + // are not available for collision detection. + // This also intentionally occurs in the case of the object being positioned + // solely on loaded CONTENT_IGNORE nodes, no matter where they come from. + if (!any_position_valid) { + *speed_f = v3f(0, 0, 0); + return result; + } } // tt2 - if (collideWithObjects) { + if(collideWithObjects) + { /* add object boxes to cinfo */ - std::vector objects; + std::vector objects; #ifndef SERVER - ClientEnvironment *c_env = dynamic_cast(env); + ClientEnvironment *c_env = dynamic_cast(env); if (c_env != 0) { - // Calculate distance by speed, add own extent and 1.5m of - // tolerance + // Calculate distance by speed, add own extent and 1.5m of tolerance f32 distance = speed_f->getLength() * dtime + - box_0.getExtent().getLength() + 1.5f * BS; + box_0.getExtent().getLength() + 1.5f * BS; std::vector clientobjects; c_env->getActiveObjects(*pos_f, distance, clientobjects); for (auto &clientobject : clientobjects) { - // Do collide with everything but itself and the parent - // CAO + // Do collide with everything but itself and the parent CAO if (!self || (self != clientobject.obj && - self != clientobject.obj->getParent())) { - objects.push_back( - (ActiveObject *)clientobject.obj); + self != clientobject.obj->getParent())) { + objects.push_back((ActiveObject*) clientobject.obj); } } - } else + } + else #endif { - ServerEnvironment *s_env = dynamic_cast(env); + ServerEnvironment *s_env = dynamic_cast(env); if (s_env != NULL) { - // Calculate distance by speed, add own extent and 1.5m of - // tolerance + // Calculate distance by speed, add own extent and 1.5m of tolerance f32 distance = speed_f->getLength() * dtime + - box_0.getExtent().getLength() + 1.5f * BS; - - // search for objects which are not us, or we are not its - // parent we directly use the callback to populate the - // result to prevent a useless result loop here - auto include_obj_cb = [self, &objects]( - ServerActiveObject * - obj) { + box_0.getExtent().getLength() + 1.5f * BS; + + // search for objects which are not us, or we are not its parent + // we directly use the callback to populate the result to prevent + // a useless result loop here + auto include_obj_cb = [self, &objects] (ServerActiveObject *obj) { if (!obj->isGone() && - (!self || (self != obj && self != obj->getParent()))) { + (!self || (self != obj && self != obj->getParent()))) { objects.push_back((ActiveObject *)obj); } return false; }; std::vector s_objects; - s_env->getObjectsInsideRadius(s_objects, *pos_f, distance, - include_obj_cb); + s_env->getObjectsInsideRadius(s_objects, *pos_f, distance, include_obj_cb); } } - for (std::vector::const_iterator iter = objects.begin(); + for (std::vector::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { ActiveObject *object = *iter; if (object && object->collideWithObjects()) { aabb3f object_collisionbox; if (object->getCollisionBox(&object_collisionbox)) - cinfo.emplace_back( - object, 0, object_collisionbox); + cinfo.emplace_back(object, 0, object_collisionbox); } } #ifndef SERVER @@ -489,12 +428,12 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, v3f lplayer_pos = lplayer->getPosition(); lplayer_collisionbox.MinEdge += lplayer_pos; lplayer_collisionbox.MaxEdge += lplayer_pos; - ActiveObject *obj = (ActiveObject *)lplayer->getCAO(); + ActiveObject *obj = (ActiveObject*) lplayer->getCAO(); cinfo.emplace_back(obj, 0, lplayer_collisionbox); } } #endif - } // tt3 + } //tt3 /* Collision detection @@ -504,13 +443,11 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, int loopcount = 0; - while (dtime > BS * 1e-10f) { + while(dtime > BS * 1e-10f) { // Avoid infinite loop loopcount++; if (loopcount >= 100) { - warningstream << "collisionMoveSimple: Loop count exceeded, " - "aborting to avoid infiniite loop" - << std::endl; + warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl; break; } @@ -533,8 +470,8 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, // Find nearest collision of the two boxes (raytracing-like) f32 dtime_tmp = nearest_dtime; - CollisionAxis collided = axisAlignedCollision( - box_info.box, movingbox, *speed_f, &dtime_tmp); + CollisionAxis collided = axisAlignedCollision(box_info.box, + movingbox, *speed_f, &dtime_tmp); if (collided == -1 || dtime_tmp >= nearest_dtime) continue; @@ -547,38 +484,30 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, if (nearest_collided == COLLISION_AXIS_NONE) { // No collision with any collision box. *pos_f += truncate(*speed_f * dtime, 100.0f); - dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP - // numbers + dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers } else { // Otherwise, a collision occurred. NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex]; - const aabb3f &cbox = nearest_info.box; + const aabb3f& cbox = nearest_info.box; - // movingbox except moved to the horizontal position it would be - // after step up + //movingbox except moved to the horizontal position it would be after step up aabb3f stepbox = movingbox; stepbox.MinEdge.X += speed_f->X * dtime; stepbox.MinEdge.Z += speed_f->Z * dtime; stepbox.MaxEdge.X += speed_f->X * dtime; stepbox.MaxEdge.Z += speed_f->Z * dtime; // Check for stairs. - bool step_up = (nearest_collided != - COLLISION_AXIS_Y) && // must not be - // Y direction - (movingbox.MinEdge.Y < cbox.MaxEdge.Y) && - (movingbox.MinEdge.Y + stepheight > - cbox.MaxEdge.Y) && - (!wouldCollideWithCeiling(cinfo, stepbox, - cbox.MaxEdge.Y - - movingbox.MinEdge - .Y, - d)); + bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction + (movingbox.MinEdge.Y < cbox.MaxEdge.Y) && + (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) && + (!wouldCollideWithCeiling(cinfo, stepbox, + cbox.MaxEdge.Y - movingbox.MinEdge.Y, + d)); // Get bounce multiplier float bounce = -(float)nearest_info.bouncy / 100.0f; - // Move to the point of collision and reduce dtime by - // nearest_dtime + // Move to the point of collision and reduce dtime by nearest_dtime if (nearest_dtime < 0) { // Handle negative nearest_dtime if (!step_up) { @@ -621,7 +550,7 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, speed_f->X = 0; result.collides = true; } else if (nearest_collided == COLLISION_AXIS_Y) { - if (fabs(speed_f->Y) > BS * 3) + if(fabs(speed_f->Y) > BS * 3) speed_f->Y *= bounce; else speed_f->Y = 0; @@ -662,8 +591,7 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, X-Z-area. */ - if (cbox.MaxEdge.X - d > box.MinEdge.X && - cbox.MinEdge.X + d < box.MaxEdge.X && + if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X && cbox.MaxEdge.Z - d > box.MinEdge.Z && cbox.MinEdge.Z + d < box.MaxEdge.Z) { if (box_info.is_step_up) { diff --git a/src/collision.h b/src/collision.h index 5138f4d6a..998598f1e 100644 --- a/src/collision.h +++ b/src/collision.h @@ -47,8 +47,8 @@ struct CollisionInfo CollisionType type = COLLISION_NODE; CollisionAxis axis = COLLISION_AXIS_NONE; - v3s16 node_p = v3s16(-32768, -32768, -32768); // COLLISION_NODE - ActiveObject *object = nullptr; // COLLISION_OBJECT + v3s16 node_p = v3s16(-32768,-32768,-32768); // COLLISION_NODE + ActiveObject *object = nullptr; // COLLISION_OBJECT v3f old_speed; v3f new_speed; int plane = -1; @@ -65,19 +65,24 @@ struct collisionMoveResult }; // Moves using a single iteration; speed should not exceed pos_max_d/dtime -collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, - f32 pos_max_d, const aabb3f &box_0, f32 stepheight, f32 dtime, v3f *pos_f, - v3f *speed_f, v3f accel_f, ActiveObject *self = NULL, - bool collideWithObjects = true, bool jesus = false); +collisionMoveResult collisionMoveSimple(Environment *env,IGameDef *gamedef, + f32 pos_max_d, const aabb3f &box_0, + f32 stepheight, f32 dtime, + v3f *pos_f, v3f *speed_f, + v3f accel_f, ActiveObject *self=NULL, + bool collideWithObjects=true, bool jesus=false); // Helper function: // Checks for collision of a moving aabbox with a static aabbox // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision // dtime receives time until first collision, invalid if -1 is returned -CollisionAxis axisAlignedCollision(const aabb3f &staticbox, const aabb3f &movingbox, +CollisionAxis axisAlignedCollision( + const aabb3f &staticbox, const aabb3f &movingbox, const v3f &speed, f32 *dtime); // Helper function: // Checks if moving the movingbox up by the given distance would hit a ceiling. -bool wouldCollideWithCeiling(const std::vector &staticboxes, - const aabb3f &movingbox, f32 y_increase, f32 d); +bool wouldCollideWithCeiling( + const std::vector &staticboxes, + const aabb3f &movingbox, + f32 y_increase, f32 d); diff --git a/src/config.h b/src/config.h index d4bde7896..5e1164642 100644 --- a/src/config.h +++ b/src/config.h @@ -8,24 +8,23 @@ #define STRINGIFY(x) #x #define STR(x) STRINGIFY(x) + #if defined USE_CMAKE_CONFIG_H -#include "cmake_config.h" -#elif defined(__ANDROID__) -#define PROJECT_NAME "minetest" -#define PROJECT_NAME_C "Minetest" -#define STATIC_SHAREDIR "" -#define VERSION_STRING \ - STR(VERSION_MAJOR) \ - "." STR(VERSION_MINOR) "." STR(VERSION_PATCH) STR(VERSION_EXTRA) -#ifdef NDEBUG -#define BUILD_TYPE "Release" -#else -#define BUILD_TYPE "Debug" -#endif -#else + #include "cmake_config.h" +#elif defined (__ANDROID__) + #define PROJECT_NAME "minetest" + #define PROJECT_NAME_C "Minetest" + #define STATIC_SHAREDIR "" + #define VERSION_STRING STR(VERSION_MAJOR) "." STR(VERSION_MINOR) "." STR(VERSION_PATCH) STR(VERSION_EXTRA) #ifdef NDEBUG -#define BUILD_TYPE "Release" + #define BUILD_TYPE "Release" + #else + #define BUILD_TYPE "Debug" + #endif #else -#define BUILD_TYPE "Debug" -#endif + #ifdef NDEBUG + #define BUILD_TYPE "Release" + #else + #define BUILD_TYPE "Debug" + #endif #endif diff --git a/src/content_mapnode.cpp b/src/content_mapnode.cpp index 11a018fc7..6da5f45ad 100644 --- a/src/content_mapnode.cpp +++ b/src/content_mapnode.cpp @@ -45,27 +45,27 @@ with this program; if not, write to the Free Software Foundation, Inc., #define CONTENT_LADDER 31 #define CONTENT_LAVA 32 #define CONTENT_LAVASOURCE 33 -#define CONTENT_GRASS 0x800 // 1 -#define CONTENT_TREE 0x801 // 4 -#define CONTENT_LEAVES 0x802 // 5 -#define CONTENT_GRASS_FOOTSTEPS 0x803 // 6 -#define CONTENT_MESE 0x804 // 7 -#define CONTENT_MUD 0x805 // 8 -#define CONTENT_CLOUD 0x806 // 10 -#define CONTENT_COALSTONE 0x807 // 11 -#define CONTENT_WOOD 0x808 // 12 -#define CONTENT_SAND 0x809 // 13 -#define CONTENT_COBBLE 0x80a // 18 -#define CONTENT_STEEL 0x80b // 19 -#define CONTENT_GLASS 0x80c // 20 -#define CONTENT_MOSSYCOBBLE 0x80d // 22 -#define CONTENT_GRAVEL 0x80e // 23 -#define CONTENT_SANDSTONE 0x80f // 24 -#define CONTENT_CACTUS 0x810 // 25 -#define CONTENT_BRICK 0x811 // 26 -#define CONTENT_CLAY 0x812 // 27 -#define CONTENT_PAPYRUS 0x813 // 28 -#define CONTENT_BOOKSHELF 0x814 // 29 +#define CONTENT_GRASS 0x800 //1 +#define CONTENT_TREE 0x801 //4 +#define CONTENT_LEAVES 0x802 //5 +#define CONTENT_GRASS_FOOTSTEPS 0x803 //6 +#define CONTENT_MESE 0x804 //7 +#define CONTENT_MUD 0x805 //8 +#define CONTENT_CLOUD 0x806 //10 +#define CONTENT_COALSTONE 0x807 //11 +#define CONTENT_WOOD 0x808 //12 +#define CONTENT_SAND 0x809 //13 +#define CONTENT_COBBLE 0x80a //18 +#define CONTENT_STEEL 0x80b //19 +#define CONTENT_GLASS 0x80c //20 +#define CONTENT_MOSSYCOBBLE 0x80d //22 +#define CONTENT_GRAVEL 0x80e //23 +#define CONTENT_SANDSTONE 0x80f //24 +#define CONTENT_CACTUS 0x810 //25 +#define CONTENT_BRICK 0x811 //26 +#define CONTENT_CLAY 0x812 //27 +#define CONTENT_PAPYRUS 0x813 //28 +#define CONTENT_BOOKSHELF 0x814 //29 #define CONTENT_JUNGLETREE 0x815 #define CONTENT_JUNGLEGRASS 0x816 #define CONTENT_NC 0x817 @@ -79,33 +79,34 @@ with this program; if not, write to the Free Software Foundation, Inc., Should never be touched. */ content_t trans_table_19[21][2] = { - {CONTENT_GRASS, 1}, - {CONTENT_TREE, 4}, - {CONTENT_LEAVES, 5}, - {CONTENT_GRASS_FOOTSTEPS, 6}, - {CONTENT_MESE, 7}, - {CONTENT_MUD, 8}, - {CONTENT_CLOUD, 10}, - {CONTENT_COALSTONE, 11}, - {CONTENT_WOOD, 12}, - {CONTENT_SAND, 13}, - {CONTENT_COBBLE, 18}, - {CONTENT_STEEL, 19}, - {CONTENT_GLASS, 20}, - {CONTENT_MOSSYCOBBLE, 22}, - {CONTENT_GRAVEL, 23}, - {CONTENT_SANDSTONE, 24}, - {CONTENT_CACTUS, 25}, - {CONTENT_BRICK, 26}, - {CONTENT_CLAY, 27}, - {CONTENT_PAPYRUS, 28}, - {CONTENT_BOOKSHELF, 29}, + {CONTENT_GRASS, 1}, + {CONTENT_TREE, 4}, + {CONTENT_LEAVES, 5}, + {CONTENT_GRASS_FOOTSTEPS, 6}, + {CONTENT_MESE, 7}, + {CONTENT_MUD, 8}, + {CONTENT_CLOUD, 10}, + {CONTENT_COALSTONE, 11}, + {CONTENT_WOOD, 12}, + {CONTENT_SAND, 13}, + {CONTENT_COBBLE, 18}, + {CONTENT_STEEL, 19}, + {CONTENT_GLASS, 20}, + {CONTENT_MOSSYCOBBLE, 22}, + {CONTENT_GRAVEL, 23}, + {CONTENT_SANDSTONE, 24}, + {CONTENT_CACTUS, 25}, + {CONTENT_BRICK, 26}, + {CONTENT_CLAY, 27}, + {CONTENT_PAPYRUS, 28}, + {CONTENT_BOOKSHELF, 29}, }; MapNode mapnode_translate_to_internal(MapNode n_from, u8 version) { MapNode result = n_from; - if (version <= 19) { + if(version <= 19) + { content_t c_from = n_from.getContent(); for (const auto &tt_i : trans_table_19) { if (tt_i[1] == c_from) { @@ -163,3 +164,4 @@ void content_mapnode_get_name_id_mapping(NameIdMapping *nimap) nimap->set(CONTENT_IGNORE, "ignore"); nimap->set(CONTENT_AIR, "air"); } + diff --git a/src/content_nodemeta.cpp b/src/content_nodemeta.cpp index 7d38fb78b..fc2859d27 100644 --- a/src/content_nodemeta.cpp +++ b/src/content_nodemeta.cpp @@ -40,92 +40,99 @@ static bool content_nodemeta_deserialize_legacy_body( { meta->clear(); - if (id == NODEMETA_GENERIC) // GenericNodeMetadata (0.4-dev) + if(id == NODEMETA_GENERIC) // GenericNodeMetadata (0.4-dev) { meta->getInventory()->deSerialize(is); - deSerializeLongString(is); // m_text - deSerializeString(is); // m_owner + deSerializeLongString(is); // m_text + deSerializeString(is); // m_owner - meta->setString("infotext", deSerializeString(is)); - meta->setString("formspec", deSerializeString(is)); - readU8(is); // m_allow_text_input - readU8(is); // m_allow_removal - readU8(is); // m_enforce_owner + meta->setString("infotext",deSerializeString(is)); + meta->setString("formspec",deSerializeString(is)); + readU8(is); // m_allow_text_input + readU8(is); // m_allow_removal + readU8(is); // m_enforce_owner int num_vars = readU32(is); - for (int i = 0; i < num_vars; i++) { + for(int i=0; isetString(name, var); } return false; - } else if (id == NODEMETA_SIGN) // SignNodeMetadata + } + else if(id == NODEMETA_SIGN) // SignNodeMetadata { meta->setString("text", deSerializeString(is)); - // meta->setString("infotext","\"${text}\""); + //meta->setString("infotext","\"${text}\""); meta->setString("infotext", std::string("\"") + meta->getString("text") + "\""); - meta->setString("formspec", "field[text;;${text}]"); + meta->setString("formspec","field[text;;${text}]"); return false; - } else if (id == NODEMETA_CHEST) // ChestNodeMetadata + } + else if(id == NODEMETA_CHEST) // ChestNodeMetadata { meta->getInventory()->deSerialize(is); // Rename inventory list "0" to "main" Inventory *inv = meta->getInventory(); - if (!inv->getList("main") && inv->getList("0")) { + if(!inv->getList("main") && inv->getList("0")){ inv->getList("0")->setName("main"); } assert(inv->getList("main") && !inv->getList("0")); - meta->setString("formspec", "size[8,9]" - "list[current_name;main;0,0;8,4;]" - "list[current_player;main;0,5;8,4;]"); + meta->setString("formspec","size[8,9]" + "list[current_name;main;0,0;8,4;]" + "list[current_player;main;0,5;8,4;]"); return false; - } else if (id == NODEMETA_LOCKABLE_CHEST) // LockingChestNodeMetadata + } + else if(id == NODEMETA_LOCKABLE_CHEST) // LockingChestNodeMetadata { meta->setString("owner", deSerializeString(is)); meta->getInventory()->deSerialize(is); // Rename inventory list "0" to "main" Inventory *inv = meta->getInventory(); - if (!inv->getList("main") && inv->getList("0")) { + if(!inv->getList("main") && inv->getList("0")){ inv->getList("0")->setName("main"); } assert(inv->getList("main") && !inv->getList("0")); - meta->setString("formspec", "size[8,9]" - "list[current_name;main;0,0;8,4;]" - "list[current_player;main;0,5;8,4;]"); + meta->setString("formspec","size[8,9]" + "list[current_name;main;0,0;8,4;]" + "list[current_player;main;0,5;8,4;]"); return false; - } else if (id == NODEMETA_FURNACE) // FurnaceNodeMetadata + } + else if(id == NODEMETA_FURNACE) // FurnaceNodeMetadata { meta->getInventory()->deSerialize(is); int temp = 0; - is >> temp; - meta->setString("fuel_totaltime", ftos((float)temp / 10)); + is>>temp; + meta->setString("fuel_totaltime", ftos((float)temp/10)); temp = 0; - is >> temp; - meta->setString("fuel_time", ftos((float)temp / 10)); + is>>temp; + meta->setString("fuel_time", ftos((float)temp/10)); temp = 0; - is >> temp; - // meta->setString("src_totaltime", ftos((float)temp/10)); + is>>temp; + //meta->setString("src_totaltime", ftos((float)temp/10)); temp = 0; - is >> temp; - meta->setString("src_time", ftos((float)temp / 10)); - - meta->setString("formspec", "size[8,9]" - "list[current_name;fuel;2,3;1,1;]" - "list[current_name;src;2,1;1,1;]" - "list[current_name;dst;5,1;2,2;]" - "list[current_player;main;0,5;8,4;]"); + is>>temp; + meta->setString("src_time", ftos((float)temp/10)); + + meta->setString("formspec","size[8,9]" + "list[current_name;fuel;2,3;1,1;]" + "list[current_name;src;2,1;1,1;]" + "list[current_name;dst;5,1;2,2;]" + "list[current_player;main;0,5;8,4;]"); return true; - } else { + } + else + { throw SerializationError("Unknown legacy node metadata"); } } -static bool content_nodemeta_deserialize_legacy_meta(std::istream &is, NodeMetadata *meta) +static bool content_nodemeta_deserialize_legacy_meta( + std::istream &is, NodeMetadata *meta) { // Read id s16 id = readS16(is); @@ -136,37 +143,41 @@ static bool content_nodemeta_deserialize_legacy_meta(std::istream &is, NodeMetad return content_nodemeta_deserialize_legacy_body(tmp_is, id, meta); } -void content_nodemeta_deserialize_legacy(std::istream &is, NodeMetadataList *meta, - NodeTimerList *timers, IItemDefManager *item_def_mgr) +void content_nodemeta_deserialize_legacy(std::istream &is, + NodeMetadataList *meta, NodeTimerList *timers, + IItemDefManager *item_def_mgr) { meta->clear(); timers->clear(); u16 version = readU16(is); - if (version > 1) { - infostream << FUNCTION_NAME << ": version " << version << " not supported" - << std::endl; + if(version > 1) + { + infostream<get(p) != NULL) { - warningstream << FUNCTION_NAME << ": " - << "already set data at position" - << "(" << p.X << "," << p.Y << "," << p.Z - << "): Ignoring." << std::endl; + if(meta->get(p) != NULL) + { + warningstream<set(p, data); - if (need_timer) + if(need_timer) timers->set(NodeTimer(1., 0., p)); } } diff --git a/src/content_nodemeta.h b/src/content_nodemeta.h index 92a9bd546..b853274f5 100644 --- a/src/content_nodemeta.h +++ b/src/content_nodemeta.h @@ -29,5 +29,6 @@ class IItemDefManager; Legacy nodemeta definitions */ -void content_nodemeta_deserialize_legacy(std::istream &is, NodeMetadataList *meta, - NodeTimerList *timers, IItemDefManager *item_def_mgr); +void content_nodemeta_deserialize_legacy(std::istream &is, + NodeMetadataList *meta, NodeTimerList *timers, + IItemDefManager *item_def_mgr); diff --git a/src/convert_json.cpp b/src/convert_json.cpp index 0a8fa1e22..c774aa002 100644 --- a/src/convert_json.cpp +++ b/src/convert_json.cpp @@ -29,8 +29,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "httpfetch.h" #include "porting.h" -Json::Value fetchJsonValue( - const std::string &url, std::vector *extra_headers) +Json::Value fetchJsonValue(const std::string &url, + std::vector *extra_headers) { HTTPFetchRequest fetch_request; HTTPFetchResult fetch_result; @@ -57,12 +57,10 @@ Json::Value fetchJsonValue( errorstream << "Failed to parse json data " << errs << std::endl; if (fetch_result.data.size() > 100) { errorstream << "Data (" << fetch_result.data.size() - << " bytes) printed to warningstream." << std::endl; - warningstream << "data: \"" << fetch_result.data << "\"" - << std::endl; + << " bytes) printed to warningstream." << std::endl; + warningstream << "data: \"" << fetch_result.data << "\"" << std::endl; } else { - errorstream << "data: \"" << fetch_result.data << "\"" - << std::endl; + errorstream << "data: \"" << fetch_result.data << "\"" << std::endl; } return Json::Value(); } diff --git a/src/convert_json.h b/src/convert_json.h index bf2ce2cb9..d8825acdc 100644 --- a/src/convert_json.h +++ b/src/convert_json.h @@ -21,7 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include -Json::Value fetchJsonValue( - const std::string &url, std::vector *extra_headers); +Json::Value fetchJsonValue(const std::string &url, + std::vector *extra_headers); std::string fastWriteJson(const Json::Value &value); diff --git a/src/craftdef.cpp b/src/craftdef.cpp index e821a4620..210605198 100644 --- a/src/craftdef.cpp +++ b/src/craftdef.cpp @@ -55,26 +55,24 @@ inline u64 getHashForString(const std::string &recipe_str) static u64 getHashForGrid(CraftHashType type, const std::vector &grid_names) { switch (type) { - case CRAFT_HASH_TYPE_ITEM_NAMES: { - std::ostringstream os; - bool is_first = true; - for (const std::string &grid_name : grid_names) { - if (!grid_name.empty()) { - os << (is_first ? "" : "\n") << grid_name; - is_first = false; + case CRAFT_HASH_TYPE_ITEM_NAMES: { + std::ostringstream os; + bool is_first = true; + for (const std::string &grid_name : grid_names) { + if (!grid_name.empty()) { + os << (is_first ? "" : "\n") << grid_name; + is_first = false; + } } - } - return getHashForString(os.str()); - } - case CRAFT_HASH_TYPE_COUNT: { - u64 cnt = 0; - for (const std::string &grid_name : grid_names) - if (!grid_name.empty()) - cnt++; - return cnt; - } - case CRAFT_HASH_TYPE_UNHASHED: - return 0; + return getHashForString(os.str()); + } case CRAFT_HASH_TYPE_COUNT: { + u64 cnt = 0; + for (const std::string &grid_name : grid_names) + if (!grid_name.empty()) + cnt++; + return cnt; + } case CRAFT_HASH_TYPE_UNHASHED: + return 0; } // invalid CraftHashType assert(false); @@ -149,8 +147,8 @@ static std::vector craftGetItems( std::vector result; result.reserve(items.size()); for (const auto &item : items) { - result.emplace_back(std::string(item), (u16)1, (u16)0, - gamedef->getItemDefManager()); + result.emplace_back(std::string(item), (u16)1, + (u16)0, gamedef->getItemDefManager()); } return result; } @@ -158,8 +156,8 @@ static std::vector craftGetItems( // Compute bounding rectangle given a matrix of items // Returns false if every item is "" static bool craftGetBounds(const std::vector &items, unsigned int width, - unsigned int &min_x, unsigned int &max_x, unsigned int &min_y, - unsigned int &max_y) + unsigned int &min_x, unsigned int &max_x, + unsigned int &min_y, unsigned int &max_y) { bool success = false; unsigned int x = 0; @@ -173,14 +171,10 @@ static bool craftGetBounds(const std::vector &items, unsigned int w min_y = max_y = y; success = true; } else { - if (x < min_x) - min_x = x; - if (x > max_x) - max_x = x; - if (y < min_y) - min_y = y; - if (y > max_y) - max_y = y; + if (x < min_x) min_x = x; + if (x > max_x) max_x = x; + if (y < min_y) min_y = y; + if (y > max_y) max_y = y; } } @@ -204,12 +198,12 @@ static void craftDecrementInput(CraftInput &input, IGameDef *gamedef) } // Removes 1 from each item stack with replacement support -// Example: if replacements contains the pair ("bucket:bucket_water", -// "bucket:bucket_empty"), +// Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"), // a water bucket will not be removed but replaced by an empty bucket. static void craftDecrementOrReplaceInput(CraftInput &input, std::vector &output_replacements, - const CraftReplacements &replacements, IGameDef *gamedef) + const CraftReplacements &replacements, + IGameDef *gamedef) { if (replacements.pairs.empty()) { craftDecrementInput(input, gamedef); @@ -217,14 +211,13 @@ static void craftDecrementOrReplaceInput(CraftInput &input, } // Make a copy of the replacements pair list - std::vector> pairs = replacements.pairs; + std::vector > pairs = replacements.pairs; for (auto &item : input.items) { // Find an appropriate replacement bool found_replacement = false; for (auto j = pairs.begin(); j != pairs.end(); ++j) { - if (inputItemMatchesRecipe( - item.name, j->first, gamedef->idef())) { + if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) { if (item.count == 1) { item.deSerialize(j->second, gamedef->idef()); found_replacement = true; @@ -238,6 +231,7 @@ static void craftDecrementOrReplaceInput(CraftInput &input, found_replacement = true; output_replacements.push_back(rep); break; + } } // No replacement was found, simply decrement count by one @@ -247,13 +241,14 @@ static void craftDecrementOrReplaceInput(CraftInput &input, } // Dump an itemstring matrix -static std::string craftDumpMatrix( - const std::vector &items, unsigned int width) +static std::string craftDumpMatrix(const std::vector &items, + unsigned int width) { std::ostringstream os(std::ios::binary); os << "{ "; unsigned int x = 0; - for (std::vector::size_type i = 0; i < items.size(); i++, x++) { + for(std::vector::size_type i = 0; + i < items.size(); i++, x++) { if (x == width) { os << "; "; x = 0; @@ -267,12 +262,14 @@ static std::string craftDumpMatrix( } // Dump an item matrix -std::string craftDumpMatrix(const std::vector &items, unsigned int width) +std::string craftDumpMatrix(const std::vector &items, + unsigned int width) { std::ostringstream os(std::ios::binary); os << "{ "; unsigned int x = 0; - for (std::vector::size_type i = 0; i < items.size(); i++, x++) { + for (std::vector::size_type i = 0; + i < items.size(); i++, x++) { if (x == width) { os << "; "; x = 0; @@ -285,6 +282,7 @@ std::string craftDumpMatrix(const std::vector &items, unsigned int wi return os.str(); } + /* CraftInput */ @@ -301,8 +299,8 @@ bool CraftInput::empty() const std::string CraftInput::dump() const { std::ostringstream os(std::ios::binary); - os << "(method=" << ((int)method) << ", items=" << craftDumpMatrix(items, width) - << ")"; + os << "(method=" << ((int)method) << ", items=" + << craftDumpMatrix(items, width) << ")"; return os.str(); } @@ -324,10 +322,12 @@ std::string CraftOutput::dump() const std::string CraftReplacements::dump() const { std::ostringstream os(std::ios::binary); - os << "{"; + os<<"{"; const char *sep = ""; for (const auto &repl_p : pairs) { - os << sep << '"' << (repl_p.first) << "\"=>\"" << (repl_p.second) << '"'; + os << sep + << '"' << (repl_p.first) + << "\"=>\"" << (repl_p.second) << '"'; sep = ","; } os << "}"; @@ -338,11 +338,12 @@ std::string CraftReplacements::dump() const CraftDefinitionShaped */ -CraftDefinitionShaped::CraftDefinitionShaped(const std::string &output_, - unsigned int width_, const std::vector &recipe_, - const CraftReplacements &replacements_) : - output(output_), - width(width_), recipe(recipe_), replacements(replacements_) +CraftDefinitionShaped::CraftDefinitionShaped( + const std::string &output_, + unsigned int width_, + const std::vector &recipe_, + const CraftReplacements &replacements_): + output(output_), width(width_), recipe(recipe_), replacements(replacements_) { if (hasGroupItem(recipe)) priority = PRIORITY_SHAPED_AND_GROUPS; @@ -370,9 +371,9 @@ bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) co // Get input bounds unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0; - if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x, inp_min_y, - inp_max_y)) - return false; // it was empty + if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x, + inp_min_y, inp_max_y)) + return false; // it was empty std::vector rec_names; if (hash_inited) @@ -388,10 +389,10 @@ bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) co rec_names.emplace_back(""); // Get recipe bounds - unsigned int rec_min_x = 0, rec_max_x = 0, rec_min_y = 0, rec_max_y = 0; - if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x, rec_min_y, - rec_max_y)) - return false; // it was empty + unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0; + if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x, + rec_min_y, rec_max_y)) + return false; // it was empty // Different sizes? if (inp_max_x - inp_min_x != rec_max_x - rec_min_x || @@ -402,16 +403,17 @@ bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) co unsigned int w = inp_max_x - inp_min_x + 1; unsigned int h = inp_max_y - inp_min_y + 1; - for (unsigned int y = 0; y < h; y++) { + for (unsigned int y=0; y < h; y++) { unsigned int inp_y = (inp_min_y + y) * inp_width; unsigned int rec_y = (rec_min_y + y) * rec_width; - for (unsigned int x = 0; x < w; x++) { + for (unsigned int x=0; x < w; x++) { unsigned int inp_x = inp_min_x + x; unsigned int rec_x = rec_min_x + x; - if (!inputItemMatchesRecipe(inp_names[inp_y + inp_x], - rec_names[rec_y + rec_x], gamedef->idef())) { + if (!inputItemMatchesRecipe( + inp_names[inp_y + inp_x], + rec_names[rec_y + rec_x], gamedef->idef())) { return false; } } @@ -420,20 +422,18 @@ bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) co return true; } -CraftOutput CraftDefinitionShaped::getOutput( - const CraftInput &input, IGameDef *gamedef) const +CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput(output, 0); } -CraftInput CraftDefinitionShaped::getInput( - const CraftOutput &output, IGameDef *gamedef) const +CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const { - return CraftInput(CRAFT_METHOD_NORMAL, width, craftGetItems(recipe, gamedef)); + return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef)); } -void CraftDefinitionShaped::decrementInput(CraftInput &input, - std::vector &output_replacements, IGameDef *gamedef) const +void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector &output_replacements, + IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } @@ -441,8 +441,8 @@ void CraftDefinitionShaped::decrementInput(CraftInput &input, u64 CraftDefinitionShaped::getHash(CraftHashType type) const { assert(hash_inited); // Pre-condition - assert((type == CRAFT_HASH_TYPE_ITEM_NAMES) || - (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition + assert((type == CRAFT_HASH_TYPE_ITEM_NAMES) + || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition std::vector rec_names = recipe_names; std::sort(rec_names.begin(), rec_names.end()); @@ -466,8 +466,8 @@ std::string CraftDefinitionShaped::dump() const { std::ostringstream os(std::ios::binary); os << "(shaped, output=\"" << output - << "\", recipe=" << craftDumpMatrix(recipe, width) - << ", replacements=" << replacements.dump() << ")"; + << "\", recipe=" << craftDumpMatrix(recipe, width) + << ", replacements=" << replacements.dump() << ")"; return os.str(); } @@ -475,11 +475,11 @@ std::string CraftDefinitionShaped::dump() const CraftDefinitionShapeless */ -CraftDefinitionShapeless::CraftDefinitionShapeless(const std::string &output_, +CraftDefinitionShapeless::CraftDefinitionShapeless( + const std::string &output_, const std::vector &recipe_, - const CraftReplacements &replacements_) : - output(output_), - recipe(recipe_), replacements(replacements_) + const CraftReplacements &replacements_): + output(output_), recipe(recipe_), replacements(replacements_) { if (hasGroupItem(recipe)) priority = PRIORITY_SHAPELESS_AND_GROUPS; @@ -526,16 +526,16 @@ bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) do { // If all items match, the recipe matches bool all_match = true; - // dstream<<"Testing recipe (output="<idef())) { + gamedef->idef())) { all_match = false; break; } } - // dstream<<" -> match="< match="< &output_replacements, IGameDef *gamedef) const +void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector &output_replacements, + IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } @@ -564,8 +562,8 @@ void CraftDefinitionShapeless::decrementInput(CraftInput &input, u64 CraftDefinitionShapeless::getHash(CraftHashType type) const { assert(hash_inited); // Pre-condition - assert(type == CRAFT_HASH_TYPE_ITEM_NAMES || - type == CRAFT_HASH_TYPE_COUNT); // Pre-condition + assert(type == CRAFT_HASH_TYPE_ITEM_NAMES + || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition return getHashForGrid(type, recipe_names); } @@ -587,8 +585,8 @@ std::string CraftDefinitionShapeless::dump() const { std::ostringstream os(std::ios::binary); os << "(shapeless, output=\"" << output - << "\", recipe=" << craftDumpMatrix(recipe, recipe.size()) - << ", replacements=" << replacements.dump() << ")"; + << "\", recipe=" << craftDumpMatrix(recipe, recipe.size()) + << ", replacements=" << replacements.dump() << ")"; return os.str(); } @@ -596,26 +594,28 @@ std::string CraftDefinitionShapeless::dump() const CraftDefinitionToolRepair */ -CraftDefinitionToolRepair::CraftDefinitionToolRepair(float additional_wear_) : - additional_wear(additional_wear_) +CraftDefinitionToolRepair::CraftDefinitionToolRepair(float additional_wear_): + additional_wear(additional_wear_) { priority = PRIORITY_TOOLREPAIR; } -static ItemStack craftToolRepair(const ItemStack &item1, const ItemStack &item2, - float additional_wear, IGameDef *gamedef) +static ItemStack craftToolRepair( + const ItemStack &item1, + const ItemStack &item2, + float additional_wear, + IGameDef *gamedef) { IItemDefManager *idef = gamedef->idef(); - if (item1.count != 1 || item2.count != 1 || item1.name != item2.name || - idef->get(item1.name).type != ITEM_TOOL || - itemgroup_get(idef->get(item1.name).groups, "disable_repair") == - 1) { + if (item1.count != 1 || item2.count != 1 || item1.name != item2.name + || idef->get(item1.name).type != ITEM_TOOL + || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) { // Failure return ItemStack(); } - s32 item1_uses = 65536 - (u32)item1.wear; - s32 item2_uses = 65536 - (u32)item2.wear; + s32 item1_uses = 65536 - (u32) item1.wear; + s32 item2_uses = 65536 - (u32) item2.wear; s32 new_uses = item1_uses + item2_uses; s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5); if (new_wear >= 65536) @@ -654,8 +654,7 @@ bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef return !repaired.empty(); } -CraftOutput CraftDefinitionToolRepair::getOutput( - const CraftInput &input, IGameDef *gamedef) const +CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const { ItemStack item1; ItemStack item2; @@ -671,16 +670,15 @@ CraftOutput CraftDefinitionToolRepair::getOutput( return CraftOutput(repaired.getItemString(), 0); } -CraftInput CraftDefinitionToolRepair::getInput( - const CraftOutput &output, IGameDef *gamedef) const +CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const { std::vector stack; stack.emplace_back(); return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack); } -void CraftDefinitionToolRepair::decrementInput(CraftInput &input, - std::vector &output_replacements, IGameDef *gamedef) const +void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector &output_replacements, + IGameDef *gamedef) const { craftDecrementInput(input, gamedef); } @@ -696,11 +694,12 @@ std::string CraftDefinitionToolRepair::dump() const CraftDefinitionCooking */ -CraftDefinitionCooking::CraftDefinitionCooking(const std::string &output_, - const std::string &recipe_, float cooktime_, - const CraftReplacements &replacements_) : - output(output_), - recipe(recipe_), cooktime(cooktime_), replacements(replacements_) +CraftDefinitionCooking::CraftDefinitionCooking( + const std::string &output_, + const std::string &recipe_, + float cooktime_, + const CraftReplacements &replacements_): + output(output_), recipe(recipe_), cooktime(cooktime_), replacements(replacements_) { if (isGroupRecipeStr(recipe)) priority = PRIORITY_SHAPELESS_AND_GROUPS; @@ -738,22 +737,20 @@ bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) c return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef()); } -CraftOutput CraftDefinitionCooking::getOutput( - const CraftInput &input, IGameDef *gamedef) const +CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput(output, cooktime); } -CraftInput CraftDefinitionCooking::getInput( - const CraftOutput &output, IGameDef *gamedef) const +CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const { std::vector rec; rec.push_back(recipe); - return CraftInput(CRAFT_METHOD_COOKING, cooktime, craftGetItems(rec, gamedef)); + return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef)); } -void CraftDefinitionCooking::decrementInput(CraftInput &input, - std::vector &output_replacements, IGameDef *gamedef) const +void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector &output_replacements, + IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } @@ -789,9 +786,10 @@ void CraftDefinitionCooking::initHash(IGameDef *gamedef) std::string CraftDefinitionCooking::dump() const { std::ostringstream os(std::ios::binary); - os << "(cooking, output=\"" << output << "\", recipe=\"" << recipe - << "\", cooktime=" << cooktime << ")" - << ", replacements=" << replacements.dump() << ")"; + os << "(cooking, output=\"" << output + << "\", recipe=\"" << recipe + << "\", cooktime=" << cooktime << ")" + << ", replacements=" << replacements.dump() << ")"; return os.str(); } @@ -799,10 +797,11 @@ std::string CraftDefinitionCooking::dump() const CraftDefinitionFuel */ -CraftDefinitionFuel::CraftDefinitionFuel(const std::string &recipe_, float burntime_, - const CraftReplacements &replacements_) : - recipe(recipe_), - burntime(burntime_), replacements(replacements_) +CraftDefinitionFuel::CraftDefinitionFuel( + const std::string &recipe_, + float burntime_, + const CraftReplacements &replacements_): + recipe(recipe_), burntime(burntime_), replacements(replacements_) { if (isGroupRecipeStr(recipe_name)) priority = PRIORITY_SHAPELESS_AND_GROUPS; @@ -840,23 +839,20 @@ bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) cons return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef()); } -CraftOutput CraftDefinitionFuel::getOutput( - const CraftInput &input, IGameDef *gamedef) const +CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput("", burntime); } -CraftInput CraftDefinitionFuel::getInput( - const CraftOutput &output, IGameDef *gamedef) const +CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const { std::vector rec; rec.push_back(recipe); - return CraftInput( - CRAFT_METHOD_COOKING, (int)burntime, craftGetItems(rec, gamedef)); + return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef)); } -void CraftDefinitionFuel::decrementInput(CraftInput &input, - std::vector &output_replacements, IGameDef *gamedef) const +void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector &output_replacements, + IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } @@ -892,8 +888,9 @@ void CraftDefinitionFuel::initHash(IGameDef *gamedef) std::string CraftDefinitionFuel::dump() const { std::ostringstream os(std::ios::binary); - os << "(fuel, recipe=\"" << recipe << "\", burntime=" << burntime << ")" - << ", replacements=" << replacements.dump() << ")"; + os << "(fuel, recipe=\"" << recipe + << "\", burntime=" << burntime << ")" + << ", replacements=" << replacements.dump() << ")"; return os.str(); } @@ -901,12 +898,18 @@ std::string CraftDefinitionFuel::dump() const Craft definition manager */ -class CCraftDefManager : public IWritableCraftDefManager +class CCraftDefManager: public IWritableCraftDefManager { public: - CCraftDefManager() { m_craft_defs.resize(craft_hash_type_max + 1); } + CCraftDefManager() + { + m_craft_defs.resize(craft_hash_type_max + 1); + } - virtual ~CCraftDefManager() { clear(); } + virtual ~CCraftDefManager() + { + clear(); + } virtual bool getCraftResult(CraftInput &input, CraftOutput &output, std::vector &output_replacement, bool decrementInput, @@ -922,48 +925,40 @@ class CCraftDefManager : public IWritableCraftDefManager // Try hash types with increasing collision rate // while remembering the latest, highest priority recipe. CraftDefinition::RecipePriority priority_best = - CraftDefinition::PRIORITY_NO_RECIPE; + CraftDefinition::PRIORITY_NO_RECIPE; CraftDefinition *def_best = nullptr; for (int type = 0; type <= craft_hash_type_max; type++) { - u64 hash = getHashForGrid((CraftHashType)type, input_names); + u64 hash = getHashForGrid((CraftHashType) type, input_names); - /*errorstream << "Checking type " << type << " with hash " << hash - * << std::endl;*/ + /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/ - // We'd like to do "const [...] hash_collisions = - // m_craft_defs[type][hash];" but that doesn't compile for some - // reason. This does. + // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];" + // but that doesn't compile for some reason. This does. auto col_iter = (m_craft_defs[type]).find(hash); if (col_iter == (m_craft_defs[type]).end()) continue; - const std::vector &hash_collisions = - col_iter->second; + const std::vector &hash_collisions = col_iter->second; // Walk crafting definitions from back to front, so that later // definitions can override earlier ones. - for (std::vector::size_type i = - hash_collisions.size(); - i > 0; i--) { + for (std::vector::size_type + i = hash_collisions.size(); i > 0; i--) { CraftDefinition *def = hash_collisions[i - 1]; /*errorstream << "Checking " << input.dump() << std::endl << " against " << def->dump() << std::endl;*/ - CraftDefinition::RecipePriority priority = - def->getPriority(); - if (priority > priority_best && - def->check(input, gamedef)) { + CraftDefinition::RecipePriority priority = def->getPriority(); + if (priority > priority_best + && def->check(input, gamedef)) { // Check if the crafted node/item exists CraftOutput out = def->getOutput(input, gamedef); ItemStack is; is.deSerialize(out.item, gamedef->idef()); if (!is.isKnown(gamedef->idef())) { - infostream << "trying to craft " - "non-existent " - << out.item - << ", ignoring recipe" - << std::endl; + infostream << "trying to craft non-existent " + << out.item << ", ignoring recipe" << std::endl; continue; } @@ -980,22 +975,22 @@ class CCraftDefManager : public IWritableCraftDefManager return true; } - virtual std::vector getCraftRecipes( - CraftOutput &output, IGameDef *gamedef, unsigned limit = 0) const + virtual std::vector getCraftRecipes(CraftOutput &output, + IGameDef *gamedef, unsigned limit=0) const { - std::vector recipes; + std::vector recipes; auto vec_iter = m_output_craft_definitions.find(output.item); if (vec_iter == m_output_craft_definitions.end()) return recipes; - const std::vector &vec = vec_iter->second; + const std::vector &vec = vec_iter->second; recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size()); - for (std::vector::size_type i = vec.size(); i > 0; - i--) { + for (std::vector::size_type i = vec.size(); + i > 0; i--) { CraftDefinition *def = vec[i - 1]; if (limit && recipes.size() >= limit) break; @@ -1014,10 +1009,8 @@ class CCraftDefManager : public IWritableCraftDefManager for (auto def : to_clear->second) { // Recipes are not yet hashed at this point - std::vector &defs = - m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0]; - defs.erase(std::remove(defs.begin(), defs.end(), def), - defs.end()); + std::vector &defs = m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0]; + defs.erase(std::remove(defs.begin(), defs.end(), def), defs.end()); delete def; } m_output_craft_definitions.erase(to_clear); @@ -1030,8 +1023,7 @@ class CCraftDefManager : public IWritableCraftDefManager return false; // Recipes are not yet hashed at this point - std::vector &defs = - m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0]; + std::vector &defs = m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0]; std::vector new_defs; bool got_hit = false; for (auto def : defs) { @@ -1042,13 +1034,11 @@ class CCraftDefManager : public IWritableCraftDefManager got_hit = true; std::string output = def->getOutput(input, gamedef).item; delete def; - auto it = m_output_craft_definitions.find( - craftGetItemName(output, gamedef)); + auto it = m_output_craft_definitions.find(craftGetItemName(output, gamedef)); if (it == m_output_craft_definitions.end()) continue; std::vector &outdefs = it->second; - outdefs.erase(std::remove(outdefs.begin(), outdefs.end(), def), - outdefs.end()); + outdefs.erase(std::remove(outdefs.begin(), outdefs.end(), def), outdefs.end()); } if (got_hit) defs.swap(new_defs); @@ -1063,10 +1053,12 @@ class CCraftDefManager : public IWritableCraftDefManager for (int type = 0; type <= craft_hash_type_max; ++type) { for (auto it = m_craft_defs[type].begin(); it != m_craft_defs[type].end(); ++it) { - for (std::vector::size_type i = 0; + for (std::vector::size_type i = 0; i < it->second.size(); i++) { - os << "type " << type << " hash " << it->first - << " def " << it->second[i]->dump() << "\n"; + os << "type " << type + << " hash " << it->first + << " def " << it->second[i]->dump() + << "\n"; } } } @@ -1075,8 +1067,8 @@ class CCraftDefManager : public IWritableCraftDefManager virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef) { TRACESTREAM(<< "registerCraft: registering craft definition: " - << def->dump() << std::endl); - m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0].push_back(def); + << def->dump() << std::endl); + m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def); CraftInput input; std::string output_name = craftGetItemName( @@ -1100,7 +1092,7 @@ class CCraftDefManager : public IWritableCraftDefManager { // Move the CraftDefs from the unhashed layer into layers higher up. std::vector &unhashed = - m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0]; + m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0]; for (auto def : unhashed) { // Initialize and get the definition's hash def->initHash(gamedef); @@ -1112,14 +1104,14 @@ class CCraftDefManager : public IWritableCraftDefManager } unhashed.clear(); } - private: - std::vector>> m_craft_defs; - std::unordered_map> - m_output_craft_definitions; + std::vector > > + m_craft_defs; + std::unordered_map > + m_output_craft_definitions; }; -IWritableCraftDefManager *createCraftDefManager() +IWritableCraftDefManager* createCraftDefManager() { return new CCraftDefManager(); } diff --git a/src/craftdef.h b/src/craftdef.h index dcadabe78..7c14e702a 100644 --- a/src/craftdef.h +++ b/src/craftdef.h @@ -57,13 +57,12 @@ enum CraftHashType // Counts the non-empty slots. CRAFT_HASH_TYPE_COUNT, - // This layer both spares an extra variable, and helps to retain (albeit rarely - // used) functionality. Maps to 0. Before hashes are "initialized", all hashes - // reside here, after initialisation, none are. + // This layer both spares an extra variable, and helps to retain (albeit rarely used) functionality. Maps to 0. + // Before hashes are "initialized", all hashes reside here, after initialisation, none are. CRAFT_HASH_TYPE_UNHASHED }; -const int craft_hash_type_max = (int)CRAFT_HASH_TYPE_UNHASHED; +const int craft_hash_type_max = (int) CRAFT_HASH_TYPE_UNHASHED; /* Input: The contents of the crafting slots, arranged in matrix form @@ -77,11 +76,9 @@ struct CraftInput CraftInput() = default; CraftInput(CraftMethod method_, unsigned int width_, - const std::vector &items_) : - method(method_), - width(width_), items(items_) - { - } + const std::vector &items_): + method(method_), width(width_), items(items_) + {} // Returns true if all items are empty. bool empty() const; @@ -101,7 +98,9 @@ struct CraftOutput CraftOutput() = default; - CraftOutput(const std::string &item_, float time_) : item(item_), time(time_) {} + CraftOutput(const std::string &item_, float time_): + item(item_), time(time_) + {} std::string dump() const; }; @@ -118,14 +117,12 @@ struct CraftOutput struct CraftReplacements { // List of replacements - std::vector> pairs; + std::vector > pairs; CraftReplacements() = default; - CraftReplacements( - const std::vector> &pairs_) : - pairs(pairs_) - { - } + CraftReplacements(const std::vector > &pairs_): + pairs(pairs_) + {} std::string dump() const; }; @@ -156,30 +153,33 @@ class CraftDefinition virtual ~CraftDefinition() = default; // Returns type of crafting definition - virtual std::string getName() const = 0; + virtual std::string getName() const=0; // Checks whether the recipe is applicable - virtual bool check(const CraftInput &input, IGameDef *gamedef) const = 0; - RecipePriority getPriority() const { return priority; } + virtual bool check(const CraftInput &input, IGameDef *gamedef) const=0; + RecipePriority getPriority() const + { + return priority; + } // Returns the output structure, meaning depends on crafting method // The implementation can assume that check(input) returns true - virtual CraftOutput getOutput( - const CraftInput &input, IGameDef *gamedef) const = 0; + virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const=0; // the inverse of the above - virtual CraftInput getInput( - const CraftOutput &output, IGameDef *gamedef) const = 0; + virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const=0; // Decreases count of every input item virtual void decrementInput(CraftInput &input, - std::vector &output_replacements, - IGameDef *gamedef) const = 0; + std::vector &output_replacements, IGameDef *gamedef) const=0; - CraftHashType getHashType() const { return hash_type; } + CraftHashType getHashType() const + { + return hash_type; + } virtual u64 getHash(CraftHashType type) const = 0; // to be called after all mods are loaded, so that we catch all aliases virtual void initHash(IGameDef *gamedef) = 0; - virtual std::string dump() const = 0; + virtual std::string dump() const=0; protected: CraftHashType hash_type; @@ -192,13 +192,15 @@ class CraftDefinition Supported crafting method: CRAFT_METHOD_NORMAL. Requires the input items to be arranged exactly like in the recipe. */ -class CraftDefinitionShaped : public CraftDefinition +class CraftDefinitionShaped: public CraftDefinition { public: CraftDefinitionShaped() = delete; - CraftDefinitionShaped(const std::string &output_, unsigned int width_, - const std::vector &recipe_, - const CraftReplacements &replacements_); + CraftDefinitionShaped( + const std::string &output_, + unsigned int width_, + const std::vector &recipe_, + const CraftReplacements &replacements_); virtual ~CraftDefinitionShaped() = default; @@ -207,8 +209,7 @@ class CraftDefinitionShaped : public CraftDefinition virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, - std::vector &output_replacements, - IGameDef *gamedef) const; + std::vector &output_replacements, IGameDef *gamedef) const; virtual u64 getHash(CraftHashType type) const; @@ -236,13 +237,14 @@ class CraftDefinitionShaped : public CraftDefinition Supported crafting method: CRAFT_METHOD_NORMAL. Input items can arranged in any way. */ -class CraftDefinitionShapeless : public CraftDefinition +class CraftDefinitionShapeless: public CraftDefinition { public: CraftDefinitionShapeless() = delete; - CraftDefinitionShapeless(const std::string &output_, - const std::vector &recipe_, - const CraftReplacements &replacements_); + CraftDefinitionShapeless( + const std::string &output_, + const std::vector &recipe_, + const CraftReplacements &replacements_); virtual ~CraftDefinitionShapeless() = default; @@ -251,8 +253,7 @@ class CraftDefinitionShapeless : public CraftDefinition virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, - std::vector &output_replacements, - IGameDef *gamedef) const; + std::vector &output_replacements, IGameDef *gamedef) const; virtual u64 getHash(CraftHashType type) const; @@ -279,7 +280,7 @@ class CraftDefinitionShapeless : public CraftDefinition Put two damaged tools into the crafting grid, get one tool back. There should only be one crafting definition of this type. */ -class CraftDefinitionToolRepair : public CraftDefinition +class CraftDefinitionToolRepair: public CraftDefinition { public: CraftDefinitionToolRepair() = delete; @@ -292,12 +293,14 @@ class CraftDefinitionToolRepair : public CraftDefinition virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, - std::vector &output_replacements, - IGameDef *gamedef) const; + std::vector &output_replacements, IGameDef *gamedef) const; virtual u64 getHash(CraftHashType type) const { return 2; } - virtual void initHash(IGameDef *gamedef) { hash_type = CRAFT_HASH_TYPE_COUNT; } + virtual void initHash(IGameDef *gamedef) + { + hash_type = CRAFT_HASH_TYPE_COUNT; + } virtual std::string dump() const; @@ -314,12 +317,15 @@ class CraftDefinitionToolRepair : public CraftDefinition A cooking (in furnace) definition Supported crafting method: CRAFT_METHOD_COOKING. */ -class CraftDefinitionCooking : public CraftDefinition +class CraftDefinitionCooking: public CraftDefinition { public: CraftDefinitionCooking() = delete; - CraftDefinitionCooking(const std::string &output_, const std::string &recipe_, - float cooktime_, const CraftReplacements &replacements_); + CraftDefinitionCooking( + const std::string &output_, + const std::string &recipe_, + float cooktime_, + const CraftReplacements &replacements_); virtual ~CraftDefinitionCooking() = default; @@ -328,8 +334,7 @@ class CraftDefinitionCooking : public CraftDefinition virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, - std::vector &output_replacements, - IGameDef *gamedef) const; + std::vector &output_replacements, IGameDef *gamedef) const; virtual u64 getHash(CraftHashType type) const; @@ -356,12 +361,14 @@ class CraftDefinitionCooking : public CraftDefinition A fuel (for furnace) definition Supported crafting method: CRAFT_METHOD_FUEL. */ -class CraftDefinitionFuel : public CraftDefinition +class CraftDefinitionFuel: public CraftDefinition { public: CraftDefinitionFuel() = delete; - CraftDefinitionFuel(const std::string &recipe_, float burntime_, - const CraftReplacements &replacements_); + CraftDefinitionFuel( + const std::string &recipe_, + float burntime_, + const CraftReplacements &replacements_); virtual ~CraftDefinitionFuel() = default; @@ -370,8 +377,7 @@ class CraftDefinitionFuel : public CraftDefinition virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, - std::vector &output_replacements, - IGameDef *gamedef) const; + std::vector &output_replacements, IGameDef *gamedef) const; virtual u64 getHash(CraftHashType type) const; @@ -414,14 +420,14 @@ class ICraftDefManager * @return true if a result was found, otherwise false. */ virtual bool getCraftResult(CraftInput &input, CraftOutput &output, - std::vector &output_replacements, bool decrementInput, - IGameDef *gamedef) const = 0; + std::vector &output_replacements, + bool decrementInput, IGameDef *gamedef) const=0; - virtual std::vector getCraftRecipes(CraftOutput &output, - IGameDef *gamedef, unsigned limit = 0) const = 0; + virtual std::vector getCraftRecipes(CraftOutput &output, + IGameDef *gamedef, unsigned limit=0) const=0; // Print crafting recipes for debugging - virtual std::string dump() const = 0; + virtual std::string dump() const=0; }; class IWritableCraftDefManager : public ICraftDefManager @@ -432,27 +438,26 @@ class IWritableCraftDefManager : public ICraftDefManager // The main crafting function virtual bool getCraftResult(CraftInput &input, CraftOutput &output, - std::vector &output_replacements, bool decrementInput, - IGameDef *gamedef) const = 0; - virtual std::vector getCraftRecipes(CraftOutput &output, - IGameDef *gamedef, unsigned limit = 0) const = 0; + std::vector &output_replacements, + bool decrementInput, IGameDef *gamedef) const=0; + virtual std::vector getCraftRecipes(CraftOutput &output, + IGameDef *gamedef, unsigned limit=0) const=0; - virtual bool clearCraftsByOutput( - const CraftOutput &output, IGameDef *gamedef) = 0; + virtual bool clearCraftsByOutput(const CraftOutput &output, IGameDef *gamedef) = 0; virtual bool clearCraftsByInput(const CraftInput &input, IGameDef *gamedef) = 0; // Print crafting recipes for debugging - virtual std::string dump() const = 0; + virtual std::string dump() const=0; // Add a crafting definition. // After calling this, the pointer belongs to the manager. virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef) = 0; // Delete all crafting definitions - virtual void clear() = 0; + virtual void clear()=0; // To be called after all mods are loaded, so that we catch all aliases virtual void initHashes(IGameDef *gamedef) = 0; }; -IWritableCraftDefManager *createCraftDefManager(); +IWritableCraftDefManager* createCraftDefManager(); diff --git a/src/database/database-dummy.cpp b/src/database/database-dummy.cpp index 3d30761be..a3d8cd579 100644 --- a/src/database/database-dummy.cpp +++ b/src/database/database-dummy.cpp @@ -23,6 +23,7 @@ Dummy database class #include "database-dummy.h" + bool Database_Dummy::saveBlock(const v3s16 &pos, const std::string &data) { m_database[getBlockAsInteger(pos)] = data; @@ -55,3 +56,4 @@ void Database_Dummy::listAllLoadableBlocks(std::vector &dst) dst.push_back(getIntegerAsBlock(x->first)); } } + diff --git a/src/database/database-files.cpp b/src/database/database-files.cpp index fe5293a68..d2b0b1543 100644 --- a/src/database/database-files.cpp +++ b/src/database/database-files.cpp @@ -95,7 +95,7 @@ void PlayerDatabaseFiles::savePlayer(RemotePlayer *player) if (!path_found) { errorstream << "Didn't find free file for player " << player->getName() - << std::endl; + << std::endl; return; } @@ -156,8 +156,7 @@ bool PlayerDatabaseFiles::loadPlayer(RemotePlayer *player, PlayerSAO *sao) path = players_path + player_to_load + itos(i); } - infostream << "Player file for player " << player_to_load << " not found" - << std::endl; + infostream << "Player file for player " << player_to_load << " not found" << std::endl; return false; } @@ -165,8 +164,8 @@ void PlayerDatabaseFiles::listPlayers(std::vector &res) { std::vector files = fs::GetDirListing(m_savedir); // list files into players directory - for (std::vector::const_iterator it = files.begin(); - it != files.end(); ++it) { + for (std::vector::const_iterator it = files.begin(); it != + files.end(); ++it) { // Ignore directories if (it->dir) continue; diff --git a/src/database/database-leveldb.cpp b/src/database/database-leveldb.cpp index 51830ff35..1976ae13d 100644 --- a/src/database/database-leveldb.cpp +++ b/src/database/database-leveldb.cpp @@ -33,18 +33,20 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "leveldb/db.h" -#define ENSURE_STATUS_OK(s) \ - if (!(s).ok()) { \ - throw DatabaseException( \ - std::string("LevelDB error: ") + (s).ToString()); \ + +#define ENSURE_STATUS_OK(s) \ + if (!(s).ok()) { \ + throw DatabaseException(std::string("LevelDB error: ") + \ + (s).ToString()); \ } + Database_LevelDB::Database_LevelDB(const std::string &savedir) { leveldb::Options options; options.create_if_missing = true; - leveldb::Status status = leveldb::DB::Open( - options, savedir + DIR_DELIM + "map.db", &m_database); + leveldb::Status status = leveldb::DB::Open(options, + savedir + DIR_DELIM + "map.db", &m_database); ENSURE_STATUS_OK(status); } @@ -55,11 +57,11 @@ Database_LevelDB::~Database_LevelDB() bool Database_LevelDB::saveBlock(const v3s16 &pos, const std::string &data) { - leveldb::Status status = m_database->Put( - leveldb::WriteOptions(), i64tos(getBlockAsInteger(pos)), data); + leveldb::Status status = m_database->Put(leveldb::WriteOptions(), + i64tos(getBlockAsInteger(pos)), data); if (!status.ok()) { - warningstream << "saveBlock: LevelDB error saving block " << PP(pos) - << ": " << status.ToString() << std::endl; + warningstream << "saveBlock: LevelDB error saving block " + << PP(pos) << ": " << status.ToString() << std::endl; return false; } @@ -69,19 +71,19 @@ bool Database_LevelDB::saveBlock(const v3s16 &pos, const std::string &data) void Database_LevelDB::loadBlock(const v3s16 &pos, std::string *block) { std::string datastr; - leveldb::Status status = m_database->Get( - leveldb::ReadOptions(), i64tos(getBlockAsInteger(pos)), &datastr); + leveldb::Status status = m_database->Get(leveldb::ReadOptions(), + i64tos(getBlockAsInteger(pos)), &datastr); *block = (status.ok()) ? datastr : ""; } bool Database_LevelDB::deleteBlock(const v3s16 &pos) { - leveldb::Status status = m_database->Delete( - leveldb::WriteOptions(), i64tos(getBlockAsInteger(pos))); + leveldb::Status status = m_database->Delete(leveldb::WriteOptions(), + i64tos(getBlockAsInteger(pos))); if (!status.ok()) { - warningstream << "deleteBlock: LevelDB error deleting block " << PP(pos) - << ": " << status.ToString() << std::endl; + warningstream << "deleteBlock: LevelDB error deleting block " + << PP(pos) << ": " << status.ToString() << std::endl; return false; } @@ -90,11 +92,11 @@ bool Database_LevelDB::deleteBlock(const v3s16 &pos) void Database_LevelDB::listAllLoadableBlocks(std::vector &dst) { - leveldb::Iterator *it = m_database->NewIterator(leveldb::ReadOptions()); + leveldb::Iterator* it = m_database->NewIterator(leveldb::ReadOptions()); for (it->SeekToFirst(); it->Valid(); it->Next()) { dst.push_back(getIntegerAsBlock(stoi64(it->key().ToString()))); } - ENSURE_STATUS_OK(it->status()); // Check for any errors found during the scan + ENSURE_STATUS_OK(it->status()); // Check for any errors found during the scan delete it; } @@ -102,8 +104,8 @@ PlayerDatabaseLevelDB::PlayerDatabaseLevelDB(const std::string &savedir) { leveldb::Options options; options.create_if_missing = true; - leveldb::Status status = leveldb::DB::Open( - options, savedir + DIR_DELIM + "players.db", &m_database); + leveldb::Status status = leveldb::DB::Open(options, + savedir + DIR_DELIM + "players.db", &m_database); ENSURE_STATUS_OK(status); } @@ -149,8 +151,8 @@ void PlayerDatabaseLevelDB::savePlayer(RemotePlayer *player) player->inventory.serialize(os); - leveldb::Status status = m_database->Put( - leveldb::WriteOptions(), player->getName(), os.str()); + leveldb::Status status = m_database->Put(leveldb::WriteOptions(), + player->getName(), os.str()); ENSURE_STATUS_OK(status); player->onSuccessfulSave(); } @@ -164,8 +166,8 @@ bool PlayerDatabaseLevelDB::removePlayer(const std::string &name) bool PlayerDatabaseLevelDB::loadPlayer(RemotePlayer *player, PlayerSAO *sao) { std::string raw; - leveldb::Status s = - m_database->Get(leveldb::ReadOptions(), player->getName(), &raw); + leveldb::Status s = m_database->Get(leveldb::ReadOptions(), + player->getName(), &raw); if (!s.ok()) return false; std::istringstream is(raw); @@ -192,7 +194,7 @@ bool PlayerDatabaseLevelDB::loadPlayer(RemotePlayer *player, PlayerSAO *sao) player->inventory.deSerialize(is); } catch (SerializationError &e) { errorstream << "Failed to deserialize player inventory. player_name=" - << player->getName() << " " << e.what() << std::endl; + << player->getName() << " " << e.what() << std::endl; } return true; @@ -200,7 +202,7 @@ bool PlayerDatabaseLevelDB::loadPlayer(RemotePlayer *player, PlayerSAO *sao) void PlayerDatabaseLevelDB::listPlayers(std::vector &res) { - leveldb::Iterator *it = m_database->NewIterator(leveldb::ReadOptions()); + leveldb::Iterator* it = m_database->NewIterator(leveldb::ReadOptions()); res.clear(); for (it->SeekToFirst(); it->Valid(); it->Next()) { res.push_back(it->key().ToString()); @@ -212,8 +214,8 @@ AuthDatabaseLevelDB::AuthDatabaseLevelDB(const std::string &savedir) { leveldb::Options options; options.create_if_missing = true; - leveldb::Status status = leveldb::DB::Open( - options, savedir + DIR_DELIM + "auth.db", &m_database); + leveldb::Status status = leveldb::DB::Open(options, + savedir + DIR_DELIM + "auth.db", &m_database); ENSURE_STATUS_OK(status); } @@ -265,15 +267,16 @@ bool AuthDatabaseLevelDB::saveAuth(const AuthEntry &authEntry) os << serializeString(authEntry.password); size_t privilege_count = authEntry.privileges.size(); - FATAL_ERROR_IF(privilege_count > U16_MAX, "Unsupported number of privileges"); + FATAL_ERROR_IF(privilege_count > U16_MAX, + "Unsupported number of privileges"); writeU16(os, privilege_count); for (const std::string &privilege : authEntry.privileges) { os << serializeString(privilege); } writeS64(os, authEntry.last_login); - leveldb::Status s = m_database->Put( - leveldb::WriteOptions(), authEntry.name, os.str()); + leveldb::Status s = m_database->Put(leveldb::WriteOptions(), + authEntry.name, os.str()); return s.ok(); } @@ -290,7 +293,7 @@ bool AuthDatabaseLevelDB::deleteAuth(const std::string &name) void AuthDatabaseLevelDB::listNames(std::vector &res) { - leveldb::Iterator *it = m_database->NewIterator(leveldb::ReadOptions()); + leveldb::Iterator* it = m_database->NewIterator(leveldb::ReadOptions()); res.clear(); for (it->SeekToFirst(); it->Valid(); it->Next()) { res.emplace_back(it->key().ToString()); diff --git a/src/database/database-postgresql.cpp b/src/database/database-postgresql.cpp index 3d5e1947c..e1bb39928 100644 --- a/src/database/database-postgresql.cpp +++ b/src/database/database-postgresql.cpp @@ -23,12 +23,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database-postgresql.h" #ifdef _WIN32 -// Without this some of the network functions are not found on mingw -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0501 -#endif -#include -#include + // Without this some of the network functions are not found on mingw + #ifndef _WIN32_WINNT + #define _WIN32_WINNT 0x0501 + #endif + #include + #include #else #include #endif @@ -40,21 +40,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server/player_sao.h" Database_PostgreSQL::Database_PostgreSQL(const std::string &connect_string) : - m_connect_string(connect_string) + m_connect_string(connect_string) { if (m_connect_string.empty()) { throw SettingNotFoundException( - "Set pgsql_connection string in world.mt to " - "use the postgresql backend\n" - "Notes:\n" - "pgsql_connection has the following form: \n" - "\tpgsql_connection = host=127.0.0.1 port=5432 " - "user=mt_user " - "password=mt_password dbname=minetest_world\n" - "mt_user should have CREATE TABLE, INSERT, SELECT, " - "UPDATE and " - "DELETE rights on the database.\n" - "Don't create mt_user as a SUPERUSER!"); + "Set pgsql_connection string in world.mt to " + "use the postgresql backend\n" + "Notes:\n" + "pgsql_connection has the following form: \n" + "\tpgsql_connection = host=127.0.0.1 port=5432 user=mt_user " + "password=mt_password dbname=minetest_world\n" + "mt_user should have CREATE TABLE, INSERT, SELECT, UPDATE and " + "DELETE rights on the database.\n" + "Don't create mt_user as a SUPERUSER!"); } } @@ -68,24 +66,25 @@ void Database_PostgreSQL::connectToDatabase() m_conn = PQconnectdb(m_connect_string.c_str()); if (PQstatus(m_conn) != CONNECTION_OK) { - throw DatabaseException(std::string("PostgreSQL database error: ") + - PQerrorMessage(m_conn)); + throw DatabaseException(std::string( + "PostgreSQL database error: ") + + PQerrorMessage(m_conn)); } m_pgversion = PQserverVersion(m_conn); /* - * We are using UPSERT feature from PostgreSQL 9.5 - * to have the better performance where possible. - */ + * We are using UPSERT feature from PostgreSQL 9.5 + * to have the better performance where possible. + */ if (m_pgversion < 90500) { warningstream << "Your PostgreSQL server lacks UPSERT " - << "support. Use version 9.5 or better if possible." - << std::endl; + << "support. Use version 9.5 or better if possible." + << std::endl; } infostream << "PostgreSQL Database: Version " << m_pgversion - << " Connection made." << std::endl; + << " Connection made." << std::endl; createDatabase(); initStatements(); @@ -103,8 +102,9 @@ void Database_PostgreSQL::verifyDatabase() void Database_PostgreSQL::ping() { if (PQping(m_connect_string.c_str()) != PQPING_OK) { - throw DatabaseException(std::string("PostgreSQL database error: ") + - PQerrorMessage(m_conn)); + throw DatabaseException(std::string( + "PostgreSQL database error: ") + + PQerrorMessage(m_conn)); } } @@ -123,8 +123,9 @@ PGresult *Database_PostgreSQL::checkResults(PGresult *result, bool clear) break; case PGRES_FATAL_ERROR: default: - throw DatabaseException(std::string("PostgreSQL database error: ") + - PQresultErrorMessage(result)); + throw DatabaseException( + std::string("PostgreSQL database error: ") + + PQresultErrorMessage(result)); } if (clear) @@ -133,11 +134,11 @@ PGresult *Database_PostgreSQL::checkResults(PGresult *result, bool clear) return result; } -void Database_PostgreSQL::createTableIfNotExists( - const std::string &table_name, const std::string &definition) +void Database_PostgreSQL::createTableIfNotExists(const std::string &table_name, + const std::string &definition) { std::string sql_check_table = "SELECT relname FROM pg_class WHERE relname='" + - table_name + "';"; + table_name + "';"; PGresult *result = checkResults(PQexec(m_conn, sql_check_table.c_str()), false); // If table doesn't exist, create it @@ -164,57 +165,61 @@ void Database_PostgreSQL::rollback() checkResults(PQexec(m_conn, "ROLLBACK;")); } -MapDatabasePostgreSQL::MapDatabasePostgreSQL(const std::string &connect_string) : - Database_PostgreSQL(connect_string), MapDatabase() +MapDatabasePostgreSQL::MapDatabasePostgreSQL(const std::string &connect_string): + Database_PostgreSQL(connect_string), + MapDatabase() { connectToDatabase(); } + void MapDatabasePostgreSQL::createDatabase() { - createTableIfNotExists("blocks", "CREATE TABLE blocks (" - "posX INT NOT NULL," - "posY INT NOT NULL," - "posZ INT NOT NULL," - "data BYTEA," - "PRIMARY KEY (posX,posY,posZ)" - ");"); + createTableIfNotExists("blocks", + "CREATE TABLE blocks (" + "posX INT NOT NULL," + "posY INT NOT NULL," + "posZ INT NOT NULL," + "data BYTEA," + "PRIMARY KEY (posX,posY,posZ)" + ");" + ); infostream << "PostgreSQL: Map Database was initialized." << std::endl; } void MapDatabasePostgreSQL::initStatements() { - prepareStatement("read_block", "SELECT data FROM blocks " - "WHERE posX = $1::int4 AND posY = $2::int4 AND " - "posZ = $3::int4"); + prepareStatement("read_block", + "SELECT data FROM blocks " + "WHERE posX = $1::int4 AND posY = $2::int4 AND " + "posZ = $3::int4"); if (getPGVersion() < 90500) { prepareStatement("write_block_insert", - "INSERT INTO blocks (posX, posY, posZ, data) SELECT " + "INSERT INTO blocks (posX, posY, posZ, data) SELECT " "$1::int4, $2::int4, $3::int4, $4::bytea " "WHERE NOT EXISTS (SELECT true FROM blocks " "WHERE posX = $1::int4 AND posY = $2::int4 AND " "posZ = $3::int4)"); prepareStatement("write_block_update", - "UPDATE blocks SET data = $4::bytea " + "UPDATE blocks SET data = $4::bytea " "WHERE posX = $1::int4 AND posY = $2::int4 AND " "posZ = $3::int4"); } else { prepareStatement("write_block", - "INSERT INTO blocks (posX, posY, posZ, data) VALUES " + "INSERT INTO blocks (posX, posY, posZ, data) VALUES " "($1::int4, $2::int4, $3::int4, $4::bytea) " "ON CONFLICT ON CONSTRAINT blocks_pkey DO " "UPDATE SET data = $4::bytea"); } - prepareStatement("delete_block", - "DELETE FROM blocks WHERE " - "posX = $1::int4 AND posY = $2::int4 AND posZ = $3::int4"); + prepareStatement("delete_block", "DELETE FROM blocks WHERE " + "posX = $1::int4 AND posY = $2::int4 AND posZ = $3::int4"); prepareStatement("list_all_loadable_blocks", - "SELECT posX, posY, posZ FROM blocks"); + "SELECT posX, posY, posZ FROM blocks"); } bool MapDatabasePostgreSQL::saveBlock(const v3s16 &pos, const std::string &data) @@ -222,8 +227,8 @@ bool MapDatabasePostgreSQL::saveBlock(const v3s16 &pos, const std::string &data) // Verify if we don't overflow the platform integer with the mapblock size if (data.size() > INT_MAX) { errorstream << "Database_PostgreSQL::saveBlock: Data truncation! " - << "data.size() over 0xFFFFFFFF (== " << data.size() << ")" - << std::endl; + << "data.size() over 0xFFFFFFFF (== " << data.size() + << ")" << std::endl; return false; } @@ -234,9 +239,11 @@ bool MapDatabasePostgreSQL::saveBlock(const v3s16 &pos, const std::string &data) y = htonl(pos.Y); z = htonl(pos.Z); - const void *args[] = {&x, &y, &z, data.c_str()}; - const int argLen[] = {sizeof(x), sizeof(y), sizeof(z), (int)data.size()}; - const int argFmt[] = {1, 1, 1, 1}; + const void *args[] = { &x, &y, &z, data.c_str() }; + const int argLen[] = { + sizeof(x), sizeof(y), sizeof(z), (int)data.size() + }; + const int argFmt[] = { 1, 1, 1, 1 }; if (getPGVersion() < 90500) { execPrepared("write_block_update", ARRLEN(args), args, argLen, argFmt); @@ -256,18 +263,17 @@ void MapDatabasePostgreSQL::loadBlock(const v3s16 &pos, std::string *block) y = htonl(pos.Y); z = htonl(pos.Z); - const void *args[] = {&x, &y, &z}; - const int argLen[] = {sizeof(x), sizeof(y), sizeof(z)}; - const int argFmt[] = {1, 1, 1}; + const void *args[] = { &x, &y, &z }; + const int argLen[] = { sizeof(x), sizeof(y), sizeof(z) }; + const int argFmt[] = { 1, 1, 1 }; - PGresult *results = execPrepared( - "read_block", ARRLEN(args), args, argLen, argFmt, false); + PGresult *results = execPrepared("read_block", ARRLEN(args), args, + argLen, argFmt, false); *block = ""; if (PQntuples(results)) - *block = std::string( - PQgetvalue(results, 0, 0), PQgetlength(results, 0, 0)); + *block = std::string(PQgetvalue(results, 0, 0), PQgetlength(results, 0, 0)); PQclear(results); } @@ -281,9 +287,9 @@ bool MapDatabasePostgreSQL::deleteBlock(const v3s16 &pos) y = htonl(pos.Y); z = htonl(pos.Z); - const void *args[] = {&x, &y, &z}; - const int argLen[] = {sizeof(x), sizeof(y), sizeof(z)}; - const int argFmt[] = {1, 1, 1}; + const void *args[] = { &x, &y, &z }; + const int argLen[] = { sizeof(x), sizeof(y), sizeof(z) }; + const int argFmt[] = { 1, 1, 1 }; execPrepared("delete_block", ARRLEN(args), args, argLen, argFmt); @@ -294,8 +300,8 @@ void MapDatabasePostgreSQL::listAllLoadableBlocks(std::vector &dst) { verifyDatabase(); - PGresult *results = execPrepared( - "list_all_loadable_blocks", 0, NULL, NULL, NULL, false, false); + PGresult *results = execPrepared("list_all_loadable_blocks", 0, + NULL, NULL, NULL, false, false); int numrows = PQntuples(results); @@ -308,63 +314,67 @@ void MapDatabasePostgreSQL::listAllLoadableBlocks(std::vector &dst) /* * Player Database */ -PlayerDatabasePostgreSQL::PlayerDatabasePostgreSQL(const std::string &connect_string) : - Database_PostgreSQL(connect_string), PlayerDatabase() +PlayerDatabasePostgreSQL::PlayerDatabasePostgreSQL(const std::string &connect_string): + Database_PostgreSQL(connect_string), + PlayerDatabase() { connectToDatabase(); } + void PlayerDatabasePostgreSQL::createDatabase() { - createTableIfNotExists("player", "CREATE TABLE player (" - "name VARCHAR(60) NOT NULL," - "pitch NUMERIC(15, 7) NOT NULL," - "yaw NUMERIC(15, 7) NOT NULL," - "posX NUMERIC(15, 7) NOT NULL," - "posY NUMERIC(15, 7) NOT NULL," - "posZ NUMERIC(15, 7) NOT NULL," - "hp INT NOT NULL," - "breath INT NOT NULL," - "creation_date TIMESTAMP WITHOUT TIME ZONE NOT " - "NULL DEFAULT NOW()," - "modification_date TIMESTAMP WITHOUT TIME ZONE " - "NOT NULL DEFAULT NOW()," - "PRIMARY KEY (name)" - ");"); - - createTableIfNotExists("player_inventories", "CREATE TABLE player_inventories (" - "player VARCHAR(60) NOT NULL," - "inv_id INT NOT NULL," - "inv_width INT NOT NULL," - "inv_name TEXT NOT NULL DEFAULT ''," - "inv_size INT NOT NULL," - "PRIMARY KEY(player, inv_id)," - "CONSTRAINT player_inventories_fkey " - "FOREIGN KEY (player) REFERENCES " - "player (name) ON DELETE CASCADE" - ");"); + createTableIfNotExists("player", + "CREATE TABLE player (" + "name VARCHAR(60) NOT NULL," + "pitch NUMERIC(15, 7) NOT NULL," + "yaw NUMERIC(15, 7) NOT NULL," + "posX NUMERIC(15, 7) NOT NULL," + "posY NUMERIC(15, 7) NOT NULL," + "posZ NUMERIC(15, 7) NOT NULL," + "hp INT NOT NULL," + "breath INT NOT NULL," + "creation_date TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW()," + "modification_date TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW()," + "PRIMARY KEY (name)" + ");" + ); + + createTableIfNotExists("player_inventories", + "CREATE TABLE player_inventories (" + "player VARCHAR(60) NOT NULL," + "inv_id INT NOT NULL," + "inv_width INT NOT NULL," + "inv_name TEXT NOT NULL DEFAULT ''," + "inv_size INT NOT NULL," + "PRIMARY KEY(player, inv_id)," + "CONSTRAINT player_inventories_fkey FOREIGN KEY (player) REFERENCES " + "player (name) ON DELETE CASCADE" + ");" + ); createTableIfNotExists("player_inventory_items", - "CREATE TABLE player_inventory_items (" + "CREATE TABLE player_inventory_items (" "player VARCHAR(60) NOT NULL," "inv_id INT NOT NULL," "slot_id INT NOT NULL," "item TEXT NOT NULL DEFAULT ''," "PRIMARY KEY(player, inv_id, slot_id)," - "CONSTRAINT player_inventory_items_fkey FOREIGN KEY (player) " - "REFERENCES " + "CONSTRAINT player_inventory_items_fkey FOREIGN KEY (player) REFERENCES " "player (name) ON DELETE CASCADE" - ");"); + ");" + ); createTableIfNotExists("player_metadata", - "CREATE TABLE player_metadata (" + "CREATE TABLE player_metadata (" "player VARCHAR(60) NOT NULL," "attr VARCHAR(256) NOT NULL," "value TEXT," "PRIMARY KEY(player, attr)," "CONSTRAINT player_metadata_fkey FOREIGN KEY (player) REFERENCES " "player (name) ON DELETE CASCADE" - ");"); + ");" + ); infostream << "PostgreSQL: Player Database was inited." << std::endl; } @@ -373,24 +383,18 @@ void PlayerDatabasePostgreSQL::initStatements() { if (getPGVersion() < 90500) { prepareStatement("create_player", - "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, " - "hp, breath) VALUES " + "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, hp, breath) VALUES " "($1, $2, $3, $4, $5, $6, $7::int, $8::int)"); prepareStatement("update_player", - "UPDATE SET pitch = $2, yaw = $3, posX = $4, posY = $5, " - "posZ = $6, hp = $7::int, " - "breath = $8::int, modification_date = NOW() WHERE name " - "= $1"); + "UPDATE SET pitch = $2, yaw = $3, posX = $4, posY = $5, posZ = $6, hp = $7::int, " + "breath = $8::int, modification_date = NOW() WHERE name = $1"); } else { prepareStatement("save_player", - "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, " - "hp, breath) VALUES " + "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, hp, breath) VALUES " "($1, $2, $3, $4, $5, $6, $7::int, $8::int)" - "ON CONFLICT ON CONSTRAINT player_pkey DO UPDATE SET " - "pitch = $2, yaw = $3, " - "posX = $4, posY = $5, posZ = $6, hp = $7::int, breath = " - "$8::int, " + "ON CONFLICT ON CONSTRAINT player_pkey DO UPDATE SET pitch = $2, yaw = $3, " + "posX = $4, posY = $5, posZ = $6, hp = $7::int, breath = $8::int, " "modification_date = NOW()"); } @@ -399,47 +403,46 @@ void PlayerDatabasePostgreSQL::initStatements() prepareStatement("load_player_list", "SELECT name FROM player"); prepareStatement("remove_player_inventories", - "DELETE FROM player_inventories WHERE player = $1"); + "DELETE FROM player_inventories WHERE player = $1"); prepareStatement("remove_player_inventory_items", - "DELETE FROM player_inventory_items WHERE player = $1"); + "DELETE FROM player_inventory_items WHERE player = $1"); prepareStatement("add_player_inventory", - "INSERT INTO player_inventories (player, inv_id, inv_width, " - "inv_name, inv_size) VALUES " + "INSERT INTO player_inventories (player, inv_id, inv_width, inv_name, inv_size) VALUES " "($1, $2::int, $3::int, $4, $5::int)"); prepareStatement("add_player_inventory_item", - "INSERT INTO player_inventory_items (player, inv_id, slot_id, " - "item) VALUES " + "INSERT INTO player_inventory_items (player, inv_id, slot_id, item) VALUES " "($1, $2::int, $3::int, $4)"); - prepareStatement("load_player_inventories", "SELECT inv_id, inv_width, inv_name, " - "inv_size FROM player_inventories " - "WHERE player = $1 ORDER BY inv_id"); + prepareStatement("load_player_inventories", + "SELECT inv_id, inv_width, inv_name, inv_size FROM player_inventories " + "WHERE player = $1 ORDER BY inv_id"); prepareStatement("load_player_inventory_items", - "SELECT slot_id, item FROM player_inventory_items WHERE " + "SELECT slot_id, item FROM player_inventory_items WHERE " "player = $1 AND inv_id = $2::int"); - prepareStatement("load_player", "SELECT pitch, yaw, posX, posY, posZ, hp, breath " - "FROM player WHERE name = $1"); + prepareStatement("load_player", + "SELECT pitch, yaw, posX, posY, posZ, hp, breath FROM player WHERE name = $1"); prepareStatement("remove_player_metadata", - "DELETE FROM player_metadata WHERE player = $1"); + "DELETE FROM player_metadata WHERE player = $1"); - prepareStatement("save_player_metadata", "INSERT INTO player_metadata (player, " - "attr, value) VALUES ($1, $2, $3)"); + prepareStatement("save_player_metadata", + "INSERT INTO player_metadata (player, attr, value) VALUES ($1, $2, $3)"); prepareStatement("load_player_metadata", - "SELECT attr, value FROM player_metadata WHERE player = $1"); + "SELECT attr, value FROM player_metadata WHERE player = $1"); + } bool PlayerDatabasePostgreSQL::playerDataExists(const std::string &playername) { verifyDatabase(); - const char *values[] = {playername.c_str()}; + const char *values[] = { playername.c_str() }; PGresult *results = execPrepared("load_player", 1, values, false); bool res = (PQntuples(results) > 0); @@ -449,7 +452,7 @@ bool PlayerDatabasePostgreSQL::playerDataExists(const std::string &playername) void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) { - PlayerSAO *sao = player->getPlayerSAO(); + PlayerSAO* sao = player->getPlayerSAO(); if (!sao) return; @@ -463,11 +466,16 @@ void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) std::string posz = ftos(pos.Z); std::string hp = itos(sao->getHP()); std::string breath = itos(sao->getBreath()); - const char *values[] = {player->getName(), pitch.c_str(), yaw.c_str(), - posx.c_str(), posy.c_str(), posz.c_str(), hp.c_str(), - breath.c_str()}; + const char *values[] = { + player->getName(), + pitch.c_str(), + yaw.c_str(), + posx.c_str(), posy.c_str(), posz.c_str(), + hp.c_str(), + breath.c_str() + }; - const char *rmvalues[] = {player->getName()}; + const char* rmvalues[] = { player->getName() }; beginSave(); if (getPGVersion() < 90500) { @@ -475,23 +483,28 @@ void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) execPrepared("create_player", 8, values, true, false); else execPrepared("update_player", 8, values, true, false); - } else + } + else execPrepared("save_player", 8, values, true, false); // Write player inventories execPrepared("remove_player_inventories", 1, rmvalues); execPrepared("remove_player_inventory_items", 1, rmvalues); - std::vector inventory_lists = - sao->getInventory()->getLists(); + std::vector inventory_lists = sao->getInventory()->getLists(); for (u16 i = 0; i < inventory_lists.size(); i++) { - const InventoryList *list = inventory_lists[i]; + const InventoryList* list = inventory_lists[i]; const std::string &name = list->getName(); - std::string width = itos(list->getWidth()), inv_id = itos(i), - lsize = itos(list->getSize()); - - const char *inv_values[] = {player->getName(), inv_id.c_str(), - width.c_str(), name.c_str(), lsize.c_str()}; + std::string width = itos(list->getWidth()), + inv_id = itos(i), lsize = itos(list->getSize()); + + const char* inv_values[] = { + player->getName(), + inv_id.c_str(), + width.c_str(), + name.c_str(), + lsize.c_str() + }; execPrepared("add_player_inventory", 5, inv_values); for (u32 j = 0; j < list->getSize(); j++) { @@ -499,8 +512,12 @@ void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) list->getItem(j).serialize(os); std::string itemStr = os.str(), slotId = itos(j); - const char *invitem_values[] = {player->getName(), inv_id.c_str(), - slotId.c_str(), itemStr.c_str()}; + const char* invitem_values[] = { + player->getName(), + inv_id.c_str(), + slotId.c_str(), + itemStr.c_str() + }; execPrepared("add_player_inventory_item", 4, invitem_values); } } @@ -508,8 +525,11 @@ void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) execPrepared("remove_player_metadata", 1, rmvalues); const StringMap &attrs = sao->getMeta().getStrings(); for (const auto &attr : attrs) { - const char *meta_values[] = {player->getName(), attr.first.c_str(), - attr.second.c_str()}; + const char *meta_values[] = { + player->getName(), + attr.first.c_str(), + attr.second.c_str() + }; execPrepared("save_player_metadata", 3, meta_values); } endSave(); @@ -522,7 +542,7 @@ bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) sanity_check(sao); verifyDatabase(); - const char *values[] = {player->getName()}; + const char *values[] = { player->getName() }; PGresult *results = execPrepared("load_player", 1, values, false, false); // Player not found, return not found @@ -533,10 +553,13 @@ bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) sao->setLookPitch(pg_to_float(results, 0, 0)); sao->setRotation(v3f(0, pg_to_float(results, 0, 1), 0)); - sao->setBasePosition(v3f(pg_to_float(results, 0, 2), pg_to_float(results, 0, 3), - pg_to_float(results, 0, 4))); - sao->setHPRaw((u16)pg_to_int(results, 0, 5)); - sao->setBreath((u16)pg_to_int(results, 0, 6), false); + sao->setBasePosition(v3f( + pg_to_float(results, 0, 2), + pg_to_float(results, 0, 3), + pg_to_float(results, 0, 4)) + ); + sao->setHPRaw((u16) pg_to_int(results, 0, 5)); + sao->setBreath((u16) pg_to_int(results, 0, 6), false); PQclear(results); @@ -546,16 +569,19 @@ bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) int resultCount = PQntuples(results); for (int row = 0; row < resultCount; ++row) { - InventoryList *invList = player->inventory.addList( - PQgetvalue(results, row, 2), pg_to_uint(results, row, 3)); + InventoryList* invList = player->inventory. + addList(PQgetvalue(results, row, 2), pg_to_uint(results, row, 3)); invList->setWidth(pg_to_uint(results, row, 1)); u32 invId = pg_to_uint(results, row, 0); std::string invIdStr = itos(invId); - const char *values2[] = {player->getName(), invIdStr.c_str()}; - PGresult *results2 = execPrepared( - "load_player_inventory_items", 2, values2, false, false); + const char* values2[] = { + player->getName(), + invIdStr.c_str() + }; + PGresult *results2 = execPrepared("load_player_inventory_items", 2, + values2, false, false); int resultCount2 = PQntuples(results2); for (int row2 = 0; row2 < resultCount2; row2++) { @@ -575,8 +601,7 @@ bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) int numrows = PQntuples(results); for (int row = 0; row < numrows; row++) { - sao->getMeta().setString( - PQgetvalue(results, row, 0), PQgetvalue(results, row, 1)); + sao->getMeta().setString(PQgetvalue(results, row, 0), PQgetvalue(results, row, 1)); } sao->getMeta().setModified(false); @@ -592,7 +617,7 @@ bool PlayerDatabasePostgreSQL::removePlayer(const std::string &name) verifyDatabase(); - const char *values[] = {name.c_str()}; + const char *values[] = { name.c_str() }; execPrepared("remove_player", 1, values); return true; @@ -619,48 +644,43 @@ AuthDatabasePostgreSQL::AuthDatabasePostgreSQL(const std::string &connect_string void AuthDatabasePostgreSQL::createDatabase() { - createTableIfNotExists("auth", "CREATE TABLE auth (" - "id SERIAL," - "name TEXT UNIQUE," - "password TEXT," - "last_login INT NOT NULL DEFAULT 0," - "PRIMARY KEY (id)" - ");"); + createTableIfNotExists("auth", + "CREATE TABLE auth (" + "id SERIAL," + "name TEXT UNIQUE," + "password TEXT," + "last_login INT NOT NULL DEFAULT 0," + "PRIMARY KEY (id)" + ");"); - createTableIfNotExists("user_privileges", "CREATE TABLE user_privileges (" - "id INT," - "privilege TEXT," - "PRIMARY KEY (id, privilege)," - "CONSTRAINT fk_id FOREIGN KEY (id) " - "REFERENCES auth (id) ON DELETE CASCADE" - ");"); + createTableIfNotExists("user_privileges", + "CREATE TABLE user_privileges (" + "id INT," + "privilege TEXT," + "PRIMARY KEY (id, privilege)," + "CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES auth (id) ON DELETE CASCADE" + ");"); } void AuthDatabasePostgreSQL::initStatements() { - prepareStatement("auth_read", "SELECT id, name, password, last_login FROM auth " - "WHERE name = $1"); - prepareStatement("auth_write", "UPDATE auth SET name = $1, password = $2, " - "last_login = $3 WHERE id = $4"); - prepareStatement("auth_create", "INSERT INTO auth (name, password, last_login) " - "VALUES ($1, $2, $3) RETURNING id"); + prepareStatement("auth_read", "SELECT id, name, password, last_login FROM auth WHERE name = $1"); + prepareStatement("auth_write", "UPDATE auth SET name = $1, password = $2, last_login = $3 WHERE id = $4"); + prepareStatement("auth_create", "INSERT INTO auth (name, password, last_login) VALUES ($1, $2, $3) RETURNING id"); prepareStatement("auth_delete", "DELETE FROM auth WHERE name = $1"); prepareStatement("auth_list_names", "SELECT name FROM auth ORDER BY name DESC"); - prepareStatement("auth_read_privs", - "SELECT privilege FROM user_privileges WHERE id = $1"); - prepareStatement("auth_write_privs", - "INSERT INTO user_privileges (id, privilege) VALUES ($1, $2)"); - prepareStatement( - "auth_delete_privs", "DELETE FROM user_privileges WHERE id = $1"); + prepareStatement("auth_read_privs", "SELECT privilege FROM user_privileges WHERE id = $1"); + prepareStatement("auth_write_privs", "INSERT INTO user_privileges (id, privilege) VALUES ($1, $2)"); + prepareStatement("auth_delete_privs", "DELETE FROM user_privileges WHERE id = $1"); } bool AuthDatabasePostgreSQL::getAuth(const std::string &name, AuthEntry &res) { verifyDatabase(); - const char *values[] = {name.c_str()}; + const char *values[] = { name.c_str() }; PGresult *result = execPrepared("auth_read", 1, values, false, false); int numrows = PQntuples(result); if (numrows == 0) { @@ -676,7 +696,7 @@ bool AuthDatabasePostgreSQL::getAuth(const std::string &name, AuthEntry &res) PQclear(result); std::string playerIdStr = itos(res.id); - const char *privsValues[] = {playerIdStr.c_str()}; + const char *privsValues[] = { playerIdStr.c_str() }; PGresult *results = execPrepared("auth_read_privs", 1, privsValues, false); numrows = PQntuples(results); @@ -697,10 +717,10 @@ bool AuthDatabasePostgreSQL::saveAuth(const AuthEntry &authEntry) std::string lastLoginStr = itos(authEntry.last_login); std::string idStr = itos(authEntry.id); const char *values[] = { - authEntry.name.c_str(), - authEntry.password.c_str(), - lastLoginStr.c_str(), - idStr.c_str(), + authEntry.name.c_str() , + authEntry.password.c_str(), + lastLoginStr.c_str(), + idStr.c_str(), }; execPrepared("auth_write", 4, values); @@ -715,8 +735,11 @@ bool AuthDatabasePostgreSQL::createAuth(AuthEntry &authEntry) verifyDatabase(); std::string lastLoginStr = itos(authEntry.last_login); - const char *values[] = {authEntry.name.c_str(), authEntry.password.c_str(), - lastLoginStr.c_str()}; + const char *values[] = { + authEntry.name.c_str() , + authEntry.password.c_str(), + lastLoginStr.c_str() + }; beginSave(); @@ -724,8 +747,7 @@ bool AuthDatabasePostgreSQL::createAuth(AuthEntry &authEntry) int numrows = PQntuples(result); if (numrows == 0) { - errorstream << "Strange behaviour on auth creation, no ID returned." - << std::endl; + errorstream << "Strange behaviour on auth creation, no ID returned." << std::endl; PQclear(result); rollback(); return false; @@ -744,7 +766,7 @@ bool AuthDatabasePostgreSQL::deleteAuth(const std::string &name) { verifyDatabase(); - const char *values[] = {name.c_str()}; + const char *values[] = { name.c_str() }; execPrepared("auth_delete", 1, values); // privileges deleted by foreign key on delete cascade @@ -755,8 +777,8 @@ void AuthDatabasePostgreSQL::listNames(std::vector &res) { verifyDatabase(); - PGresult *results = execPrepared( - "auth_list_names", 0, NULL, NULL, NULL, false, false); + PGresult *results = execPrepared("auth_list_names", 0, + NULL, NULL, NULL, false, false); int numrows = PQntuples(results); @@ -774,13 +796,14 @@ void AuthDatabasePostgreSQL::reload() void AuthDatabasePostgreSQL::writePrivileges(const AuthEntry &authEntry) { std::string authIdStr = itos(authEntry.id); - const char *values[] = {authIdStr.c_str()}; + const char *values[] = { authIdStr.c_str() }; execPrepared("auth_delete_privs", 1, values); for (const std::string &privilege : authEntry.privileges) { - const char *values[] = {authIdStr.c_str(), privilege.c_str()}; + const char *values[] = { authIdStr.c_str(), privilege.c_str() }; execPrepared("auth_write_privs", 2, values); } } + #endif // USE_POSTGRESQL diff --git a/src/database/database-postgresql.h b/src/database/database-postgresql.h index 36940b112..f47deda33 100644 --- a/src/database/database-postgresql.h +++ b/src/database/database-postgresql.h @@ -26,7 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class Settings; -class Database_PostgreSQL : public Database +class Database_PostgreSQL: public Database { public: Database_PostgreSQL(const std::string &connect_string); @@ -38,6 +38,7 @@ class Database_PostgreSQL : public Database bool initialized() const; + protected: // Conversion helpers inline int pg_to_int(PGresult *res, int row, int col) @@ -47,41 +48,41 @@ class Database_PostgreSQL : public Database inline u32 pg_to_uint(PGresult *res, int row, int col) { - return (u32)atoi(PQgetvalue(res, row, col)); + return (u32) atoi(PQgetvalue(res, row, col)); } inline float pg_to_float(PGresult *res, int row, int col) { - return (float)atof(PQgetvalue(res, row, col)); + return (float) atof(PQgetvalue(res, row, col)); } inline v3s16 pg_to_v3s16(PGresult *res, int row, int col) { - return v3s16(pg_to_int(res, row, col), pg_to_int(res, row, col + 1), - pg_to_int(res, row, col + 2)); + return v3s16( + pg_to_int(res, row, col), + pg_to_int(res, row, col + 1), + pg_to_int(res, row, col + 2) + ); } inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, - const void **params, const int *paramsLengths = NULL, - const int *paramsFormats = NULL, bool clear = true, - bool nobinary = true) + const void **params, + const int *paramsLengths = NULL, const int *paramsFormats = NULL, + bool clear = true, bool nobinary = true) { return checkResults(PQexecPrepared(m_conn, stmtName, paramsNumber, - (const char *const *)params, - paramsLengths, paramsFormats, - nobinary ? 1 : 0), - clear); + (const char* const*) params, paramsLengths, paramsFormats, + nobinary ? 1 : 0), clear); } inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, - const char **params, bool clear = true, bool nobinary = true) + const char **params, bool clear = true, bool nobinary = true) { - return execPrepared(stmtName, paramsNumber, (const void **)params, NULL, - NULL, clear, nobinary); + return execPrepared(stmtName, paramsNumber, + (const void **)params, NULL, NULL, clear, nobinary); } - void createTableIfNotExists( - const std::string &table_name, const std::string &definition); + void createTableIfNotExists(const std::string &table_name, const std::string &definition); void verifyDatabase(); // Database initialization @@ -94,7 +95,6 @@ class Database_PostgreSQL : public Database } const int getPGVersion() const { return m_pgversion; } - private: // Database connectivity checks void ping(); diff --git a/src/database/database-redis.cpp b/src/database/database-redis.cpp index e75063f73..096ea504d 100644 --- a/src/database/database-redis.cpp +++ b/src/database/database-redis.cpp @@ -31,6 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include + Database_Redis::Database_Redis(Settings &conf) { std::string tmp; @@ -38,15 +39,13 @@ Database_Redis::Database_Redis(Settings &conf) tmp = conf.get("redis_address"); hash = conf.get("redis_hash"); } catch (SettingNotFoundException &) { - throw SettingNotFoundException( - "Set redis_address and " - "redis_hash in world.mt to use the redis backend"); + throw SettingNotFoundException("Set redis_address and " + "redis_hash in world.mt to use the redis backend"); } const char *addr = tmp.c_str(); int port = conf.exists("redis_port") ? conf.getU16("redis_port") : 6379; // if redis_address contains '/' assume unix socket, else hostname/ip - ctx = tmp.find('/') != std::string::npos ? redisConnectUnix(addr) - : redisConnect(addr, port); + ctx = tmp.find('/') != std::string::npos ? redisConnectUnix(addr) : redisConnect(addr, port); if (!ctx) { throw DatabaseException("Cannot allocate redis context"); } else if (ctx->err) { @@ -56,13 +55,11 @@ Database_Redis::Database_Redis(Settings &conf) } if (conf.exists("redis_password")) { tmp = conf.get("redis_password"); - redisReply *reply = static_cast( - redisCommand(ctx, "AUTH %s", tmp.c_str())); + redisReply *reply = static_cast(redisCommand(ctx, "AUTH %s", tmp.c_str())); if (!reply) throw DatabaseException("Redis authentication failed"); if (reply->type == REDIS_REPLY_ERROR) { - std::string err = "Redis authentication failed: " + - std::string(reply->str, reply->len); + std::string err = "Redis authentication failed: " + std::string(reply->str, reply->len); freeReplyObject(reply); throw DatabaseException(err); } @@ -75,22 +72,20 @@ Database_Redis::~Database_Redis() redisFree(ctx); } -void Database_Redis::beginSave() -{ +void Database_Redis::beginSave() { redisReply *reply = static_cast(redisCommand(ctx, "MULTI")); if (!reply) { - throw DatabaseException(std::string("Redis command 'MULTI' failed: ") + - ctx->errstr); + throw DatabaseException(std::string( + "Redis command 'MULTI' failed: ") + ctx->errstr); } freeReplyObject(reply); } -void Database_Redis::endSave() -{ +void Database_Redis::endSave() { redisReply *reply = static_cast(redisCommand(ctx, "EXEC")); if (!reply) { - throw DatabaseException(std::string("Redis command 'EXEC' failed: ") + - ctx->errstr); + throw DatabaseException(std::string( + "Redis command 'EXEC' failed: ") + ctx->errstr); } freeReplyObject(reply); } @@ -103,16 +98,14 @@ bool Database_Redis::saveBlock(const v3s16 &pos, const std::string &data) hash.c_str(), tmp.c_str(), data.c_str(), data.size())); if (!reply) { warningstream << "saveBlock: redis command 'HSET' failed on " - "block " - << PP(pos) << ": " << ctx->errstr << std::endl; + "block " << PP(pos) << ": " << ctx->errstr << std::endl; freeReplyObject(reply); return false; } if (reply->type == REDIS_REPLY_ERROR) { warningstream << "saveBlock: saving block " << PP(pos) - << " failed: " << std::string(reply->str, reply->len) - << std::endl; + << " failed: " << std::string(reply->str, reply->len) << std::endl; freeReplyObject(reply); return false; } @@ -124,13 +117,12 @@ bool Database_Redis::saveBlock(const v3s16 &pos, const std::string &data) void Database_Redis::loadBlock(const v3s16 &pos, std::string *block) { std::string tmp = i64tos(getBlockAsInteger(pos)); - redisReply *reply = static_cast( - redisCommand(ctx, "HGET %s %s", hash.c_str(), tmp.c_str())); + redisReply *reply = static_cast(redisCommand(ctx, + "HGET %s %s", hash.c_str(), tmp.c_str())); if (!reply) { - throw DatabaseException( - std::string("Redis command 'HGET %s %s' failed: ") + - ctx->errstr); + throw DatabaseException(std::string( + "Redis command 'HGET %s %s' failed: ") + ctx->errstr); } switch (reply->type) { @@ -144,10 +136,9 @@ void Database_Redis::loadBlock(const v3s16 &pos, std::string *block) std::string errstr(reply->str, reply->len); freeReplyObject(reply); errorstream << "loadBlock: loading block " << PP(pos) - << " failed: " << errstr << std::endl; - throw DatabaseException( - std::string("Redis command 'HGET %s %s' errored: ") + - errstr); + << " failed: " << errstr << std::endl; + throw DatabaseException(std::string( + "Redis command 'HGET %s %s' errored: ") + errstr); } case REDIS_REPLY_NIL: { *block = ""; @@ -158,27 +149,25 @@ void Database_Redis::loadBlock(const v3s16 &pos, std::string *block) } errorstream << "loadBlock: loading block " << PP(pos) - << " returned invalid reply type " << reply->type << ": " - << std::string(reply->str, reply->len) << std::endl; + << " returned invalid reply type " << reply->type + << ": " << std::string(reply->str, reply->len) << std::endl; freeReplyObject(reply); - throw DatabaseException( - std::string("Redis command 'HGET %s %s' gave invalid reply.")); + throw DatabaseException(std::string( + "Redis command 'HGET %s %s' gave invalid reply.")); } bool Database_Redis::deleteBlock(const v3s16 &pos) { std::string tmp = i64tos(getBlockAsInteger(pos)); - redisReply *reply = static_cast( - redisCommand(ctx, "HDEL %s %s", hash.c_str(), tmp.c_str())); + redisReply *reply = static_cast(redisCommand(ctx, + "HDEL %s %s", hash.c_str(), tmp.c_str())); if (!reply) { - throw DatabaseException( - std::string("Redis command 'HDEL %s %s' failed: ") + - ctx->errstr); + throw DatabaseException(std::string( + "Redis command 'HDEL %s %s' failed: ") + ctx->errstr); } else if (reply->type == REDIS_REPLY_ERROR) { warningstream << "deleteBlock: deleting block " << PP(pos) - << " failed: " << std::string(reply->str, reply->len) - << std::endl; + << " failed: " << std::string(reply->str, reply->len) << std::endl; freeReplyObject(reply); return false; } @@ -189,11 +178,10 @@ bool Database_Redis::deleteBlock(const v3s16 &pos) void Database_Redis::listAllLoadableBlocks(std::vector &dst) { - redisReply *reply = static_cast( - redisCommand(ctx, "HKEYS %s", hash.c_str())); + redisReply *reply = static_cast(redisCommand(ctx, "HKEYS %s", hash.c_str())); if (!reply) { - throw DatabaseException(std::string("Redis command 'HKEYS %s' failed: ") + - ctx->errstr); + throw DatabaseException(std::string( + "Redis command 'HKEYS %s' failed: ") + ctx->errstr); } switch (reply->type) { case REDIS_REPLY_ARRAY: @@ -204,11 +192,12 @@ void Database_Redis::listAllLoadableBlocks(std::vector &dst) } break; case REDIS_REPLY_ERROR: - throw DatabaseException( - std::string("Failed to get keys from database: ") + - std::string(reply->str, reply->len)); + throw DatabaseException(std::string( + "Failed to get keys from database: ") + + std::string(reply->str, reply->len)); } freeReplyObject(reply); } #endif // USE_REDIS + diff --git a/src/database/database-sqlite3.cpp b/src/database/database-sqlite3.cpp index 5a9cee5ce..4560743b9 100644 --- a/src/database/database-sqlite3.cpp +++ b/src/database/database-sqlite3.cpp @@ -24,6 +24,7 @@ SQLite format specification: BLOB data */ + #include "database-sqlite3.h" #include "log.h" @@ -39,31 +40,32 @@ SQLite format specification: // When to print messages when the database is being held locked by another process // Note: I've seen occasional delays of over 250ms while running minetestmapper. -#define BUSY_INFO_TRESHOLD 100 // Print first informational message after 100ms. -#define BUSY_WARNING_TRESHOLD 250 // Print warning message after 250ms. Lag is increased. -#define BUSY_ERROR_TRESHOLD 1000 // Print error message after 1000ms. Significant lag. -#define BUSY_FATAL_TRESHOLD \ - 3000 // Allow SQLITE_BUSY to be returned, which will cause a minetest crash. -#define BUSY_ERROR_INTERVAL 10000 // Safety net: report again every 10 seconds - -#define SQLRES(s, r, m) \ - if ((s) != (r)) { \ - throw DatabaseException( \ - std::string(m) + ": " + sqlite3_errmsg(m_database)); \ +#define BUSY_INFO_TRESHOLD 100 // Print first informational message after 100ms. +#define BUSY_WARNING_TRESHOLD 250 // Print warning message after 250ms. Lag is increased. +#define BUSY_ERROR_TRESHOLD 1000 // Print error message after 1000ms. Significant lag. +#define BUSY_FATAL_TRESHOLD 3000 // Allow SQLITE_BUSY to be returned, which will cause a minetest crash. +#define BUSY_ERROR_INTERVAL 10000 // Safety net: report again every 10 seconds + + +#define SQLRES(s, r, m) \ + if ((s) != (r)) { \ + throw DatabaseException(std::string(m) + ": " +\ + sqlite3_errmsg(m_database)); \ } #define SQLOK(s, m) SQLRES(s, SQLITE_OK, m) -#define PREPARE_STATEMENT(name, query) \ - SQLOK(sqlite3_prepare_v2(m_database, query, -1, &m_stmt_##name, NULL), \ - "Failed to prepare query '" query "'") +#define PREPARE_STATEMENT(name, query) \ + SQLOK(sqlite3_prepare_v2(m_database, query, -1, &m_stmt_##name, NULL),\ + "Failed to prepare query '" query "'") -#define SQLOK_ERRSTREAM(s, m) \ - if ((s) != SQLITE_OK) { \ - errorstream << (m) << ": " << sqlite3_errmsg(m_database) << std::endl; \ +#define SQLOK_ERRSTREAM(s, m) \ + if ((s) != SQLITE_OK) { \ + errorstream << (m) << ": " \ + << sqlite3_errmsg(m_database) << std::endl; \ } -#define FINALIZE_STATEMENT(statement) \ - SQLOK_ERRSTREAM(sqlite3_finalize(statement), "Failed to finalize " #statement) +#define FINALIZE_STATEMENT(statement) SQLOK_ERRSTREAM(sqlite3_finalize(statement), \ + "Failed to finalize " #statement) int Database_SQLite3::busyHandler(void *data, int count) { @@ -76,7 +78,7 @@ int Database_SQLite3::busyHandler(void *data, int count) prev_time = first_time; } else { while (cur_time < prev_time) - cur_time += s64(1) << 32; + cur_time += s64(1)<<32; } if (cur_time - first_time < BUSY_INFO_TRESHOLD) { @@ -84,25 +86,24 @@ int Database_SQLite3::busyHandler(void *data, int count) } else if (cur_time - first_time >= BUSY_INFO_TRESHOLD && prev_time - first_time < BUSY_INFO_TRESHOLD) { infostream << "SQLite3 database has been locked for " - << cur_time - first_time << " ms." << std::endl; + << cur_time - first_time << " ms." << std::endl; } else if (cur_time - first_time >= BUSY_WARNING_TRESHOLD && prev_time - first_time < BUSY_WARNING_TRESHOLD) { warningstream << "SQLite3 database has been locked for " - << cur_time - first_time << " ms." << std::endl; + << cur_time - first_time << " ms." << std::endl; } else if (cur_time - first_time >= BUSY_ERROR_TRESHOLD && prev_time - first_time < BUSY_ERROR_TRESHOLD) { errorstream << "SQLite3 database has been locked for " - << cur_time - first_time << " ms; this causes lag." - << std::endl; + << cur_time - first_time << " ms; this causes lag." << std::endl; } else if (cur_time - first_time >= BUSY_FATAL_TRESHOLD && prev_time - first_time < BUSY_FATAL_TRESHOLD) { errorstream << "SQLite3 database has been locked for " - << cur_time - first_time << " ms - giving up!" << std::endl; + << cur_time - first_time << " ms - giving up!" << std::endl; } else if ((cur_time - first_time) / BUSY_ERROR_INTERVAL != (prev_time - first_time) / BUSY_ERROR_INTERVAL) { // Safety net: keep reporting every BUSY_ERROR_INTERVAL errorstream << "SQLite3 database has been locked for " - << (cur_time - first_time) / 1000 << " seconds!" << std::endl; + << (cur_time - first_time) / 1000 << " seconds!" << std::endl; } prev_time = cur_time; @@ -111,10 +112,10 @@ int Database_SQLite3::busyHandler(void *data, int count) return cur_time - first_time < BUSY_FATAL_TRESHOLD; } -Database_SQLite3::Database_SQLite3( - const std::string &savedir, const std::string &dbname) : - m_savedir(savedir), - m_dbname(dbname) + +Database_SQLite3::Database_SQLite3(const std::string &savedir, const std::string &dbname) : + m_savedir(savedir), + m_dbname(dbname) { } @@ -122,7 +123,7 @@ void Database_SQLite3::beginSave() { verifyDatabase(); SQLRES(sqlite3_step(m_stmt_begin), SQLITE_DONE, - "Failed to start SQLite3 transaction"); + "Failed to start SQLite3 transaction"); sqlite3_reset(m_stmt_begin); } @@ -130,14 +131,13 @@ void Database_SQLite3::endSave() { verifyDatabase(); SQLRES(sqlite3_step(m_stmt_end), SQLITE_DONE, - "Failed to commit SQLite3 transaction"); + "Failed to commit SQLite3 transaction"); sqlite3_reset(m_stmt_end); } void Database_SQLite3::openDatabase() { - if (m_database) - return; + if (m_database) return; std::string dbp = m_savedir + DIR_DELIM + m_dbname + ".sqlite"; @@ -145,37 +145,35 @@ void Database_SQLite3::openDatabase() if (!fs::CreateAllDirs(m_savedir)) { infostream << "Database_SQLite3: Failed to create directory \"" - << m_savedir << "\"" << std::endl; + << m_savedir << "\"" << std::endl; throw FileNotGoodException("Failed to create database " - "save directory"); + "save directory"); } bool needs_create = !fs::PathExists(dbp); SQLOK(sqlite3_open_v2(dbp.c_str(), &m_database, - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL), - std::string("Failed to open SQLite3 database file ") + dbp); + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL), + std::string("Failed to open SQLite3 database file ") + dbp); SQLOK(sqlite3_busy_handler(m_database, Database_SQLite3::busyHandler, - m_busy_handler_data), - "Failed to set SQLite3 busy handler"); + m_busy_handler_data), "Failed to set SQLite3 busy handler"); if (needs_create) { createDatabase(); } - std::string query_str = std::string("PRAGMA synchronous = ") + - itos(g_settings->getU16("sqlite_synchronous")); + std::string query_str = std::string("PRAGMA synchronous = ") + + itos(g_settings->getU16("sqlite_synchronous")); SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL), - "Failed to modify sqlite3 synchronous mode"); + "Failed to modify sqlite3 synchronous mode"); SQLOK(sqlite3_exec(m_database, "PRAGMA foreign_keys = ON", NULL, NULL, NULL), - "Failed to enable sqlite3 foreign key support"); + "Failed to enable sqlite3 foreign key support"); } void Database_SQLite3::verifyDatabase() { - if (m_initialized) - return; + if (m_initialized) return; openDatabase(); @@ -199,8 +197,9 @@ Database_SQLite3::~Database_SQLite3() * Map database */ -MapDatabaseSQLite3::MapDatabaseSQLite3(const std::string &savedir) : - Database_SQLite3(savedir, "map"), MapDatabase() +MapDatabaseSQLite3::MapDatabaseSQLite3(const std::string &savedir): + Database_SQLite3(savedir, "map"), + MapDatabase() { } @@ -212,24 +211,25 @@ MapDatabaseSQLite3::~MapDatabaseSQLite3() FINALIZE_STATEMENT(m_stmt_delete) } + void MapDatabaseSQLite3::createDatabase() { assert(m_database); // Pre-condition SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `blocks` (\n" - " `pos` INT PRIMARY KEY,\n" - " `data` BLOB\n" - ");\n", - NULL, NULL, NULL), - "Failed to create database table"); + "CREATE TABLE IF NOT EXISTS `blocks` (\n" + " `pos` INT PRIMARY KEY,\n" + " `data` BLOB\n" + ");\n", + NULL, NULL, NULL), + "Failed to create database table"); } void MapDatabaseSQLite3::initStatements() { PREPARE_STATEMENT(read, "SELECT `data` FROM `blocks` WHERE `pos` = ? LIMIT 1"); #ifdef __ANDROID__ - PREPARE_STATEMENT(write, "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)"); + PREPARE_STATEMENT(write, "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)"); #else PREPARE_STATEMENT(write, "REPLACE INTO `blocks` (`pos`, `data`) VALUES (?, ?)"); #endif @@ -242,8 +242,7 @@ void MapDatabaseSQLite3::initStatements() inline void MapDatabaseSQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index) { SQLOK(sqlite3_bind_int64(stmt, index, getBlockAsInteger(pos)), - "Internal error: failed to bind query at " __FILE__ - ":" TOSTRING(__LINE__)); + "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__)); } bool MapDatabaseSQLite3::deleteBlock(const v3s16 &pos) @@ -256,8 +255,8 @@ bool MapDatabaseSQLite3::deleteBlock(const v3s16 &pos) sqlite3_reset(m_stmt_delete); if (!good) { - warningstream << "deleteBlock: Block failed to delete " << PP(pos) << ": " - << sqlite3_errmsg(m_database) << std::endl; + warningstream << "deleteBlock: Block failed to delete " + << PP(pos) << ": " << sqlite3_errmsg(m_database) << std::endl; } return good; } @@ -281,8 +280,7 @@ bool MapDatabaseSQLite3::saveBlock(const v3s16 &pos, const std::string &data) bindPos(m_stmt_write, pos); SQLOK(sqlite3_bind_blob(m_stmt_write, 2, data.data(), data.size(), NULL), - "Internal error: failed to bind query at " __FILE__ - ":" TOSTRING(__LINE__)); + "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__)); SQLRES(sqlite3_step(m_stmt_write), SQLITE_DONE, "Failed to save block") sqlite3_reset(m_stmt_write); @@ -301,7 +299,7 @@ void MapDatabaseSQLite3::loadBlock(const v3s16 &pos, std::string *block) return; } - const char *data = (const char *)sqlite3_column_blob(m_stmt_read, 0); + const char *data = (const char *) sqlite3_column_blob(m_stmt_read, 0); size_t len = sqlite3_column_bytes(m_stmt_read, 0); *block = (data) ? std::string(data, len) : ""; @@ -325,128 +323,118 @@ void MapDatabaseSQLite3::listAllLoadableBlocks(std::vector &dst) * Player Database */ -PlayerDatabaseSQLite3::PlayerDatabaseSQLite3(const std::string &savedir) : - Database_SQLite3(savedir, "players"), PlayerDatabase() +PlayerDatabaseSQLite3::PlayerDatabaseSQLite3(const std::string &savedir): + Database_SQLite3(savedir, "players"), + PlayerDatabase() { } -PlayerDatabaseSQLite3::~PlayerDatabaseSQLite3(){ - FINALIZE_STATEMENT(m_stmt_player_load) FINALIZE_STATEMENT(m_stmt_player_add) FINALIZE_STATEMENT( - m_stmt_player_update) FINALIZE_STATEMENT(m_stmt_player_remove) FINALIZE_STATEMENT(m_stmt_player_list) - FINALIZE_STATEMENT(m_stmt_player_add_inventory) FINALIZE_STATEMENT( - m_stmt_player_add_inventory_items) FINALIZE_STATEMENT(m_stmt_player_remove_inventory) - FINALIZE_STATEMENT(m_stmt_player_remove_inventory_items) FINALIZE_STATEMENT( - m_stmt_player_load_inventory) FINALIZE_STATEMENT(m_stmt_player_load_inventory_items) - FINALIZE_STATEMENT(m_stmt_player_metadata_load) FINALIZE_STATEMENT( - m_stmt_player_metadata_add) - FINALIZE_STATEMENT( - m_stmt_player_metadata_remove)}; +PlayerDatabaseSQLite3::~PlayerDatabaseSQLite3() +{ + FINALIZE_STATEMENT(m_stmt_player_load) + FINALIZE_STATEMENT(m_stmt_player_add) + FINALIZE_STATEMENT(m_stmt_player_update) + FINALIZE_STATEMENT(m_stmt_player_remove) + FINALIZE_STATEMENT(m_stmt_player_list) + FINALIZE_STATEMENT(m_stmt_player_add_inventory) + FINALIZE_STATEMENT(m_stmt_player_add_inventory_items) + FINALIZE_STATEMENT(m_stmt_player_remove_inventory) + FINALIZE_STATEMENT(m_stmt_player_remove_inventory_items) + FINALIZE_STATEMENT(m_stmt_player_load_inventory) + FINALIZE_STATEMENT(m_stmt_player_load_inventory_items) + FINALIZE_STATEMENT(m_stmt_player_metadata_load) + FINALIZE_STATEMENT(m_stmt_player_metadata_add) + FINALIZE_STATEMENT(m_stmt_player_metadata_remove) +}; + void PlayerDatabaseSQLite3::createDatabase() { assert(m_database); // Pre-condition SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `player` (" - "`name` VARCHAR(50) NOT NULL," - "`pitch` NUMERIC(11, 4) NOT NULL," - "`yaw` NUMERIC(11, 4) NOT NULL," - "`posX` NUMERIC(11, 4) NOT NULL," - "`posY` NUMERIC(11, 4) NOT NULL," - "`posZ` NUMERIC(11, 4) NOT NULL," - "`hp` INT NOT NULL," - "`breath` INT NOT NULL," - "`creation_date` DATETIME NOT NULL DEFAULT " - "CURRENT_TIMESTAMP," - "`modification_date` DATETIME NOT NULL DEFAULT " - "CURRENT_TIMESTAMP," - "PRIMARY KEY (`name`));", - NULL, NULL, NULL), - "Failed to create player table"); + "CREATE TABLE IF NOT EXISTS `player` (" + "`name` VARCHAR(50) NOT NULL," + "`pitch` NUMERIC(11, 4) NOT NULL," + "`yaw` NUMERIC(11, 4) NOT NULL," + "`posX` NUMERIC(11, 4) NOT NULL," + "`posY` NUMERIC(11, 4) NOT NULL," + "`posZ` NUMERIC(11, 4) NOT NULL," + "`hp` INT NOT NULL," + "`breath` INT NOT NULL," + "`creation_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + "`modification_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`name`));", + NULL, NULL, NULL), + "Failed to create player table"); SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `player_metadata` (" - " `player` VARCHAR(50) NOT NULL," - " `metadata` VARCHAR(256) NOT NULL," - " `value` TEXT," - " PRIMARY KEY(`player`, `metadata`)," - " FOREIGN KEY (`player`) REFERENCES player (`name`) ON " - "DELETE CASCADE );", - NULL, NULL, NULL), - "Failed to create player metadata table"); + "CREATE TABLE IF NOT EXISTS `player_metadata` (" + " `player` VARCHAR(50) NOT NULL," + " `metadata` VARCHAR(256) NOT NULL," + " `value` TEXT," + " PRIMARY KEY(`player`, `metadata`)," + " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", + NULL, NULL, NULL), + "Failed to create player metadata table"); SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `player_inventories` (" - " `player` VARCHAR(50) NOT NULL," - " `inv_id` INT NOT NULL," - " `inv_width` INT NOT NULL," - " `inv_name` TEXT NOT NULL DEFAULT ''," - " `inv_size` INT NOT NULL," - " PRIMARY KEY(player, inv_id)," - " FOREIGN KEY (`player`) REFERENCES player (`name`) ON " - "DELETE CASCADE );", - NULL, NULL, NULL), - "Failed to create player inventory table"); + "CREATE TABLE IF NOT EXISTS `player_inventories` (" + " `player` VARCHAR(50) NOT NULL," + " `inv_id` INT NOT NULL," + " `inv_width` INT NOT NULL," + " `inv_name` TEXT NOT NULL DEFAULT ''," + " `inv_size` INT NOT NULL," + " PRIMARY KEY(player, inv_id)," + " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", + NULL, NULL, NULL), + "Failed to create player inventory table"); SQLOK(sqlite3_exec(m_database, - "CREATE TABLE `player_inventory_items` (" - " `player` VARCHAR(50) NOT NULL," - " `inv_id` INT NOT NULL," - " `slot_id` INT NOT NULL," - " `item` TEXT NOT NULL DEFAULT ''," - " PRIMARY KEY(player, inv_id, slot_id)," - " FOREIGN KEY (`player`) REFERENCES player (`name`) ON " - "DELETE CASCADE );", - NULL, NULL, NULL), - "Failed to create player inventory items table"); + "CREATE TABLE `player_inventory_items` (" + " `player` VARCHAR(50) NOT NULL," + " `inv_id` INT NOT NULL," + " `slot_id` INT NOT NULL," + " `item` TEXT NOT NULL DEFAULT ''," + " PRIMARY KEY(player, inv_id, slot_id)," + " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", + NULL, NULL, NULL), + "Failed to create player inventory items table"); } void PlayerDatabaseSQLite3::initStatements() { - PREPARE_STATEMENT(player_load, - "SELECT `pitch`, `yaw`, `posX`, `posY`, `posZ`, `hp`, " - "`breath`" - "FROM `player` WHERE `name` = ?") - PREPARE_STATEMENT(player_add, - "INSERT INTO `player` (`name`, `pitch`, `yaw`, `posX`, " - "`posY`, `posZ`, `hp`, `breath`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") - PREPARE_STATEMENT(player_update, - "UPDATE `player` SET `pitch` = ?, `yaw` = ?, " + PREPARE_STATEMENT(player_load, "SELECT `pitch`, `yaw`, `posX`, `posY`, `posZ`, `hp`, " + "`breath`" + "FROM `player` WHERE `name` = ?") + PREPARE_STATEMENT(player_add, "INSERT INTO `player` (`name`, `pitch`, `yaw`, `posX`, " + "`posY`, `posZ`, `hp`, `breath`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + PREPARE_STATEMENT(player_update, "UPDATE `player` SET `pitch` = ?, `yaw` = ?, " "`posX` = ?, `posY` = ?, `posZ` = ?, `hp` = ?, `breath` = ?, " "`modification_date` = CURRENT_TIMESTAMP WHERE `name` = ?") PREPARE_STATEMENT(player_remove, "DELETE FROM `player` WHERE `name` = ?") PREPARE_STATEMENT(player_list, "SELECT `name` FROM `player`") - PREPARE_STATEMENT(player_add_inventory, - "INSERT INTO `player_inventories` " - "(`player`, `inv_id`, `inv_width`, `inv_name`, `inv_size`) " - "VALUES (?, ?, ?, ?, ?)") - PREPARE_STATEMENT(player_add_inventory_items, - "INSERT INTO `player_inventory_items` " - "(`player`, `inv_id`, `slot_id`, `item`) VALUES (?, ?, ?, ?)") + PREPARE_STATEMENT(player_add_inventory, "INSERT INTO `player_inventories` " + "(`player`, `inv_id`, `inv_width`, `inv_name`, `inv_size`) VALUES (?, ?, ?, ?, ?)") + PREPARE_STATEMENT(player_add_inventory_items, "INSERT INTO `player_inventory_items` " + "(`player`, `inv_id`, `slot_id`, `item`) VALUES (?, ?, ?, ?)") PREPARE_STATEMENT(player_remove_inventory, "DELETE FROM `player_inventories` " - "WHERE `player` = ?") - PREPARE_STATEMENT(player_remove_inventory_items, - "DELETE FROM `player_inventory_items` " - "WHERE `player` = ?") - PREPARE_STATEMENT(player_load_inventory, - "SELECT `inv_id`, `inv_width`, `inv_name`, " - "`inv_size` FROM `player_inventories` WHERE `player` = ? ORDER " - "BY inv_id") - PREPARE_STATEMENT(player_load_inventory_items, - "SELECT `slot_id`, `item` " - "FROM `player_inventory_items` WHERE `player` = ? AND `inv_id` = " - "?") + "WHERE `player` = ?") + PREPARE_STATEMENT(player_remove_inventory_items, "DELETE FROM `player_inventory_items` " + "WHERE `player` = ?") + PREPARE_STATEMENT(player_load_inventory, "SELECT `inv_id`, `inv_width`, `inv_name`, " + "`inv_size` FROM `player_inventories` WHERE `player` = ? ORDER BY inv_id") + PREPARE_STATEMENT(player_load_inventory_items, "SELECT `slot_id`, `item` " + "FROM `player_inventory_items` WHERE `player` = ? AND `inv_id` = ?") PREPARE_STATEMENT(player_metadata_load, "SELECT `metadata`, `value` FROM " - "`player_metadata` WHERE `player` = ?") - PREPARE_STATEMENT(player_metadata_add, - "INSERT INTO `player_metadata` " - "(`player`, `metadata`, `value`) VALUES (?, ?, ?)") + "`player_metadata` WHERE `player` = ?") + PREPARE_STATEMENT(player_metadata_add, "INSERT INTO `player_metadata` " + "(`player`, `metadata`, `value`) VALUES (?, ?, ?)") PREPARE_STATEMENT(player_metadata_remove, "DELETE FROM `player_metadata` " - "WHERE `player` = ?") - verbosestream << "ServerEnvironment: SQLite3 database opened (players)." - << std::endl; + "WHERE `player` = ?") + verbosestream << "ServerEnvironment: SQLite3 database opened (players)." << std::endl; } bool PlayerDatabaseSQLite3::playerDataExists(const std::string &name) @@ -460,7 +448,7 @@ bool PlayerDatabaseSQLite3::playerDataExists(const std::string &name) void PlayerDatabaseSQLite3::savePlayer(RemotePlayer *player) { - PlayerSAO *sao = player->getPlayerSAO(); + PlayerSAO* sao = player->getPlayerSAO(); sanity_check(sao); const v3f &pos = sao->getBasePosition(); @@ -502,10 +490,9 @@ void PlayerDatabaseSQLite3::savePlayer(RemotePlayer *player) sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory_items), SQLITE_DONE); sqlite3_reset(m_stmt_player_remove_inventory_items); - std::vector inventory_lists = - sao->getInventory()->getLists(); + std::vector inventory_lists = sao->getInventory()->getLists(); for (u16 i = 0; i < inventory_lists.size(); i++) { - const InventoryList *list = inventory_lists[i]; + const InventoryList* list = inventory_lists[i]; str_to_sqlite(m_stmt_player_add_inventory, 1, player->getName()); int_to_sqlite(m_stmt_player_add_inventory, 2, i); @@ -520,13 +507,11 @@ void PlayerDatabaseSQLite3::savePlayer(RemotePlayer *player) list->getItem(j).serialize(os); std::string itemStr = os.str(); - str_to_sqlite(m_stmt_player_add_inventory_items, 1, - player->getName()); + str_to_sqlite(m_stmt_player_add_inventory_items, 1, player->getName()); int_to_sqlite(m_stmt_player_add_inventory_items, 2, i); int_to_sqlite(m_stmt_player_add_inventory_items, 3, j); str_to_sqlite(m_stmt_player_add_inventory_items, 4, itemStr); - sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory_items), - SQLITE_DONE); + sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory_items), SQLITE_DONE); sqlite3_reset(m_stmt_player_add_inventory_items); } } @@ -561,16 +546,16 @@ bool PlayerDatabaseSQLite3::loadPlayer(RemotePlayer *player, PlayerSAO *sao) sao->setLookPitch(sqlite_to_float(m_stmt_player_load, 0)); sao->setPlayerYaw(sqlite_to_float(m_stmt_player_load, 1)); sao->setBasePosition(sqlite_to_v3f(m_stmt_player_load, 2)); - sao->setHPRaw((u16)MYMIN(sqlite_to_int(m_stmt_player_load, 5), U16_MAX)); - sao->setBreath((u16)MYMIN(sqlite_to_int(m_stmt_player_load, 6), U16_MAX), false); + sao->setHPRaw((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 5), U16_MAX)); + sao->setBreath((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 6), U16_MAX), false); sqlite3_reset(m_stmt_player_load); // Load inventory str_to_sqlite(m_stmt_player_load_inventory, 1, player->getName()); while (sqlite3_step(m_stmt_player_load_inventory) == SQLITE_ROW) { InventoryList *invList = player->inventory.addList( - sqlite_to_string(m_stmt_player_load_inventory, 2), - sqlite_to_uint(m_stmt_player_load_inventory, 3)); + sqlite_to_string(m_stmt_player_load_inventory, 2), + sqlite_to_uint(m_stmt_player_load_inventory, 3)); invList->setWidth(sqlite_to_uint(m_stmt_player_load_inventory, 1)); u32 invId = sqlite_to_uint(m_stmt_player_load_inventory, 0); @@ -578,15 +563,11 @@ bool PlayerDatabaseSQLite3::loadPlayer(RemotePlayer *player, PlayerSAO *sao) str_to_sqlite(m_stmt_player_load_inventory_items, 1, player->getName()); int_to_sqlite(m_stmt_player_load_inventory_items, 2, invId); while (sqlite3_step(m_stmt_player_load_inventory_items) == SQLITE_ROW) { - const std::string itemStr = sqlite_to_string( - m_stmt_player_load_inventory_items, 1); + const std::string itemStr = sqlite_to_string(m_stmt_player_load_inventory_items, 1); if (itemStr.length() > 0) { ItemStack stack; stack.deSerialize(itemStr); - invList->changeItem( - sqlite_to_uint(m_stmt_player_load_inventory_items, - 0), - stack); + invList->changeItem(sqlite_to_uint(m_stmt_player_load_inventory_items, 0), stack); } } sqlite3_reset(m_stmt_player_load_inventory_items); @@ -654,43 +635,37 @@ void AuthDatabaseSQLite3::createDatabase() assert(m_database); // Pre-condition SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `auth` (" - "`id` INTEGER PRIMARY KEY AUTOINCREMENT," - "`name` VARCHAR(32) UNIQUE," - "`password` VARCHAR(512)," - "`last_login` INTEGER" - ");", - NULL, NULL, NULL), - "Failed to create auth table"); + "CREATE TABLE IF NOT EXISTS `auth` (" + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," + "`name` VARCHAR(32) UNIQUE," + "`password` VARCHAR(512)," + "`last_login` INTEGER" + ");", + NULL, NULL, NULL), + "Failed to create auth table"); SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `user_privileges` (" - "`id` INTEGER," - "`privilege` VARCHAR(32)," - "PRIMARY KEY (id, privilege)" - "CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES auth (id) ON " - "DELETE CASCADE" - ");", - NULL, NULL, NULL), - "Failed to create auth privileges table"); + "CREATE TABLE IF NOT EXISTS `user_privileges` (" + "`id` INTEGER," + "`privilege` VARCHAR(32)," + "PRIMARY KEY (id, privilege)" + "CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES auth (id) ON DELETE CASCADE" + ");", + NULL, NULL, NULL), + "Failed to create auth privileges table"); } void AuthDatabaseSQLite3::initStatements() { - PREPARE_STATEMENT(read, - "SELECT id, name, password, last_login FROM auth WHERE name = ?"); - PREPARE_STATEMENT(write, "UPDATE auth set name = ?, password = ?, last_login = ? " - "WHERE id = ?"); - PREPARE_STATEMENT(create, - "INSERT INTO auth (name, password, last_login) VALUES (?, ?, ?)"); + PREPARE_STATEMENT(read, "SELECT id, name, password, last_login FROM auth WHERE name = ?"); + PREPARE_STATEMENT(write, "UPDATE auth set name = ?, password = ?, last_login = ? WHERE id = ?"); + PREPARE_STATEMENT(create, "INSERT INTO auth (name, password, last_login) VALUES (?, ?, ?)"); PREPARE_STATEMENT(delete, "DELETE FROM auth WHERE name = ?"); PREPARE_STATEMENT(list_names, "SELECT name FROM auth ORDER BY name DESC"); - PREPARE_STATEMENT( - read_privs, "SELECT privilege FROM user_privileges WHERE id = ?"); - PREPARE_STATEMENT(write_privs, "INSERT OR IGNORE INTO user_privileges (id, " - "privilege) VALUES (?, ?)"); + PREPARE_STATEMENT(read_privs, "SELECT privilege FROM user_privileges WHERE id = ?"); + PREPARE_STATEMENT(write_privs, "INSERT OR IGNORE INTO user_privileges (id, privilege) VALUES (?, ?)"); PREPARE_STATEMENT(delete_privs, "DELETE FROM user_privileges WHERE id = ?"); PREPARE_STATEMENT(last_insert_rowid, "SELECT last_insert_rowid()"); diff --git a/src/database/database-sqlite3.h b/src/database/database-sqlite3.h index ce568ae27..d7202a918 100644 --- a/src/database/database-sqlite3.h +++ b/src/database/database-sqlite3.h @@ -37,7 +37,6 @@ class Database_SQLite3 : public Database void endSave(); bool initialized() const { return m_initialized; } - protected: Database_SQLite3(const std::string &savedir, const std::string &dbname); @@ -62,7 +61,7 @@ class Database_SQLite3 : public Database inline void int64_to_sqlite(sqlite3_stmt *s, int iCol, s64 val) const { - sqlite3_vrfy(sqlite3_bind_int64(s, iCol, (sqlite3_int64)val)); + sqlite3_vrfy(sqlite3_bind_int64(s, iCol, (sqlite3_int64) val)); } inline void double_to_sqlite(sqlite3_stmt *s, int iCol, double val) const @@ -72,8 +71,7 @@ class Database_SQLite3 : public Database inline std::string sqlite_to_string(sqlite3_stmt *s, int iCol) { - const char *text = reinterpret_cast( - sqlite3_column_text(s, iCol)); + const char* text = reinterpret_cast(sqlite3_column_text(s, iCol)); return std::string(text ? text : ""); } @@ -84,22 +82,22 @@ class Database_SQLite3 : public Database inline u32 sqlite_to_uint(sqlite3_stmt *s, int iCol) { - return (u32)sqlite3_column_int(s, iCol); + return (u32) sqlite3_column_int(s, iCol); } inline s64 sqlite_to_int64(sqlite3_stmt *s, int iCol) { - return (s64)sqlite3_column_int64(s, iCol); + return (s64) sqlite3_column_int64(s, iCol); } inline u64 sqlite_to_uint64(sqlite3_stmt *s, int iCol) { - return (u64)sqlite3_column_int64(s, iCol); + return (u64) sqlite3_column_int64(s, iCol); } inline float sqlite_to_float(sqlite3_stmt *s, int iCol) { - return (float)sqlite3_column_double(s, iCol); + return (float) sqlite3_column_double(s, iCol); } inline const v3f sqlite_to_v3f(sqlite3_stmt *s, int iCol) @@ -109,15 +107,13 @@ class Database_SQLite3 : public Database } // Query verifiers helpers - inline void sqlite3_vrfy( - int s, const std::string &m = "", int r = SQLITE_OK) const + inline void sqlite3_vrfy(int s, const std::string &m = "", int r = SQLITE_OK) const { if (s != r) throw DatabaseException(m + ": " + sqlite3_errmsg(m_database)); } - inline void sqlite3_vrfy( - const int s, const int r, const std::string &m = "") const + inline void sqlite3_vrfy(const int s, const int r, const std::string &m = "") const { sqlite3_vrfy(s, m, r); } @@ -127,7 +123,6 @@ class Database_SQLite3 : public Database virtual void initStatements() = 0; sqlite3 *m_database = nullptr; - private: // Open the database void openDatabase(); @@ -158,7 +153,6 @@ class MapDatabaseSQLite3 : private Database_SQLite3, public MapDatabase void beginSave() { Database_SQLite3::beginSave(); } void endSave() { Database_SQLite3::endSave(); } - protected: virtual void createDatabase(); virtual void initStatements(); diff --git a/src/database/database.cpp b/src/database/database.cpp index 01cb2b5fc..12e0e1a0f 100644 --- a/src/database/database.cpp +++ b/src/database/database.cpp @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database.h" #include "irrlichttypes.h" + /**************** * Black magic! * **************** @@ -36,6 +37,7 @@ static inline s16 unsigned_to_signed(u16 i, u16 max_positive) return i - (max_positive * 2); } + // Modulo of a negative number does not work consistently in C static inline s64 pythonmodulo(s64 i, s16 mod) { @@ -45,11 +47,15 @@ static inline s64 pythonmodulo(s64 i, s16 mod) return mod - ((-i) % mod); } + s64 MapDatabase::getBlockAsInteger(const v3s16 &pos) { - return (u64)pos.Z * 0x1000000 + (u64)pos.Y * 0x1000 + (u64)pos.X; + return (u64) pos.Z * 0x1000000 + + (u64) pos.Y * 0x1000 + + (u64) pos.X; } + v3s16 MapDatabase::getIntegerAsBlock(s64 i) { v3s16 pos; @@ -60,3 +66,4 @@ v3s16 MapDatabase::getIntegerAsBlock(s64 i) pos.Z = unsigned_to_signed(pythonmodulo(i, 4096), 2048); return pos; } + diff --git a/src/daynightratio.h b/src/daynightratio.h index 110ff855b..538767cad 100644 --- a/src/daynightratio.h +++ b/src/daynightratio.h @@ -30,15 +30,15 @@ inline u32 time_to_daynight_ratio(float time_of_day, bool smooth) t = 24000.0f - t; const float values[9][2] = { - {4250.0f + 125.0f, 175.0f}, - {4500.0f + 125.0f, 175.0f}, - {4750.0f + 125.0f, 250.0f}, - {5000.0f + 125.0f, 350.0f}, - {5250.0f + 125.0f, 500.0f}, - {5500.0f + 125.0f, 675.0f}, - {5750.0f + 125.0f, 875.0f}, - {6000.0f + 125.0f, 1000.0f}, - {6250.0f + 125.0f, 1000.0f}, + {4250.0f + 125.0f, 175.0f}, + {4500.0f + 125.0f, 175.0f}, + {4750.0f + 125.0f, 250.0f}, + {5000.0f + 125.0f, 350.0f}, + {5250.0f + 125.0f, 500.0f}, + {5500.0f + 125.0f, 675.0f}, + {5750.0f + 125.0f, 875.0f}, + {6000.0f + 125.0f, 1000.0f}, + {6250.0f + 125.0f, 1000.0f}, }; if (!smooth) { diff --git a/src/debug.cpp b/src/debug.cpp index 5fdfadba7..3c82ed9e1 100644 --- a/src/debug.cpp +++ b/src/debug.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "porting.h" #include "debug.h" #include "exceptions.h" @@ -30,48 +31,45 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "config.h" #ifdef _MSC_VER -#include -#include "version.h" -#include "filesys.h" + #include + #include "version.h" + #include "filesys.h" #endif #if USE_CURSES -#include "terminal_chat_console.h" + #include "terminal_chat_console.h" #endif /* Assert */ -void sanity_check_fn(const char *assertion, const char *file, unsigned int line, - const char *function) +void sanity_check_fn(const char *assertion, const char *file, + unsigned int line, const char *function) { #if USE_CURSES g_term_console.stopAndWaitforThread(); #endif - errorstream << std::endl - << "In thread " << std::hex << std::this_thread::get_id() << ":" - << std::endl; + errorstream << std::endl << "In thread " << std::hex + << std::this_thread::get_id() << ":" << std::endl; errorstream << file << ":" << line << ": " << function - << ": An engine assumption '" << assertion << "' failed." - << std::endl; + << ": An engine assumption '" << assertion << "' failed." << std::endl; abort(); } -void fatal_error_fn(const char *msg, const char *file, unsigned int line, - const char *function) +void fatal_error_fn(const char *msg, const char *file, + unsigned int line, const char *function) { #if USE_CURSES g_term_console.stopAndWaitforThread(); #endif - errorstream << std::endl - << "In thread " << std::hex << std::this_thread::get_id() << ":" - << std::endl; + errorstream << std::endl << "In thread " << std::hex + << std::this_thread::get_id() << ":" << std::endl; errorstream << file << ":" << line << ": " << function - << ": A fatal error occurred: " << msg << std::endl; + << ": A fatal error occurred: " << msg << std::endl; abort(); } @@ -143,27 +141,27 @@ long WINAPI Win32ExceptionHandler(struct _EXCEPTION_POINTERS *pExceptInfo) std::string version_str(PROJECT_NAME " "); version_str += g_version_hash; - HANDLE hFile = CreateFileA(dumpfile.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, - NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE hFile = CreateFileA(dumpfile.c_str(), GENERIC_WRITE, + FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) goto minidump_failed; if (SetEndOfFile(hFile) == FALSE) goto minidump_failed; - mdei.ClientPointers = NULL; + mdei.ClientPointers = NULL; mdei.ExceptionPointers = pExceptInfo; - mdei.ThreadId = GetCurrentThreadId(); + mdei.ThreadId = GetCurrentThreadId(); - mdus.Type = CommentStreamA; + mdus.Type = CommentStreamA; mdus.BufferSize = version_str.size(); - mdus.Buffer = (PVOID)version_str.c_str(); + mdus.Buffer = (PVOID)version_str.c_str(); mdusi.UserStreamArray = &mdus; mdusi.UserStreamCount = 1; if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, - MiniDumpNormal, &mdei, &mdusi, NULL) == FALSE) + MiniDumpNormal, &mdei, &mdusi, NULL) == FALSE) goto minidump_failed; minidump_created = true; @@ -174,10 +172,10 @@ long WINAPI Win32ExceptionHandler(struct _EXCEPTION_POINTERS *pExceptInfo) DWORD excode = pExceptInfo->ExceptionRecord->ExceptionCode; _snprintf(buf, sizeof(buf), - " >> === FATAL ERROR ===\n" - " >> %s (Exception 0x%08X) at 0x%p\n", - Win32ExceptionCodeToString(excode), excode, - pExceptInfo->ExceptionRecord->ExceptionAddress); + " >> === FATAL ERROR ===\n" + " >> %s (Exception 0x%08X) at 0x%p\n", + Win32ExceptionCodeToString(excode), excode, + pExceptInfo->ExceptionRecord->ExceptionAddress); dstream << buf; if (minidump_created) @@ -196,3 +194,4 @@ void debug_set_exception_handler() SetUnhandledExceptionFilter(Win32ExceptionHandler); #endif } + diff --git a/src/debug.h b/src/debug.h index 75acf493f..1faeece8d 100644 --- a/src/debug.h +++ b/src/debug.h @@ -26,38 +26,42 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #ifdef _WIN32 -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0501 -#endif -#include -#ifdef _MSC_VER -#include -#endif -#define NORETURN __declspec(noreturn) -#define FUNCTION_NAME __FUNCTION__ + #ifndef _WIN32_WINNT + #define _WIN32_WINNT 0x0501 + #endif + #include + #ifdef _MSC_VER + #include + #endif + #define NORETURN __declspec(noreturn) + #define FUNCTION_NAME __FUNCTION__ #else -#define NORETURN __attribute__((__noreturn__)) -#define FUNCTION_NAME __PRETTY_FUNCTION__ + #define NORETURN __attribute__ ((__noreturn__)) + #define FUNCTION_NAME __PRETTY_FUNCTION__ #endif // Whether to catch all std::exceptions. // When "catching", the program will abort with an error message. // In debug mode, leave these for the debugger and don't catch them. #ifdef NDEBUG -#define CATCH_UNHANDLED_EXCEPTIONS 1 + #define CATCH_UNHANDLED_EXCEPTIONS 1 #else -#define CATCH_UNHANDLED_EXCEPTIONS 0 + #define CATCH_UNHANDLED_EXCEPTIONS 0 #endif /* Abort program execution immediately */ -NORETURN extern void fatal_error_fn(const char *msg, const char *file, unsigned int line, - const char *function); +NORETURN extern void fatal_error_fn( + const char *msg, const char *file, + unsigned int line, const char *function); -#define FATAL_ERROR(msg) fatal_error_fn((msg), __FILE__, __LINE__, FUNCTION_NAME) +#define FATAL_ERROR(msg) \ + fatal_error_fn((msg), __FILE__, __LINE__, FUNCTION_NAME) -#define FATAL_ERROR_IF(expr, msg) \ - ((expr) ? fatal_error_fn((msg), __FILE__, __LINE__, FUNCTION_NAME) : (void)(0)) +#define FATAL_ERROR_IF(expr, msg) \ + ((expr) \ + ? fatal_error_fn((msg), __FILE__, __LINE__, FUNCTION_NAME) \ + : (void)(0)) /* sanity_check() @@ -65,14 +69,18 @@ NORETURN extern void fatal_error_fn(const char *msg, const char *file, unsigned defined) */ -NORETURN extern void sanity_check_fn(const char *assertion, const char *file, +NORETURN extern void sanity_check_fn( + const char *assertion, const char *file, unsigned int line, const char *function); -#define SANITY_CHECK(expr) \ - ((expr) ? (void)(0) : sanity_check_fn(#expr, __FILE__, __LINE__, FUNCTION_NAME)) +#define SANITY_CHECK(expr) \ + ((expr) \ + ? (void)(0) \ + : sanity_check_fn(#expr, __FILE__, __LINE__, FUNCTION_NAME)) #define sanity_check(expr) SANITY_CHECK(expr) + void debug_set_exception_handler(); /* @@ -80,17 +88,15 @@ void debug_set_exception_handler(); */ #if CATCH_UNHANDLED_EXCEPTIONS == 1 -#define BEGIN_DEBUG_EXCEPTION_HANDLER try { -#define END_DEBUG_EXCEPTION_HANDLER \ - } \ - catch (std::exception & e) \ - { \ - errorstream << "An unhandled exception occurred: " << e.what() \ - << std::endl; \ - FATAL_ERROR(e.what()); \ - } + #define BEGIN_DEBUG_EXCEPTION_HANDLER try { + #define END_DEBUG_EXCEPTION_HANDLER \ + } catch (std::exception &e) { \ + errorstream << "An unhandled exception occurred: " \ + << e.what() << std::endl; \ + FATAL_ERROR(e.what()); \ + } #else -// Dummy ones -#define BEGIN_DEBUG_EXCEPTION_HANDLER -#define END_DEBUG_EXCEPTION_HANDLER + // Dummy ones + #define BEGIN_DEBUG_EXCEPTION_HANDLER + #define END_DEBUG_EXCEPTION_HANDLER #endif diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 37425916c..a00d39c30 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -74,7 +74,7 @@ void set_default_settings(Settings *settings) settings->setDefault("cheat_menu_font_color_alpha", "195"); settings->setDefault("cheat_menu_selected_font_color", "(255, 255, 255)"); settings->setDefault("cheat_menu_selected_font_color_alpha", "235"); - + // Cheats settings->setDefault("xray", "false"); settings->setDefault("xray_nodes", "default:stone,mcl_core:stone"); @@ -344,6 +344,7 @@ void set_default_settings(Settings *settings) settings->setDefault("enable_waving_leaves", "false"); settings->setDefault("enable_waving_plants", "false"); + // Input settings->setDefault("invert_mouse", "false"); settings->setDefault("mouse_sensitivity", "0.2"); @@ -372,29 +373,19 @@ void set_default_settings(Settings *settings) #if USE_FREETYPE settings->setDefault("freetype", "true"); - 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")); - settings->setDefault("font_path_bold_italic", - porting::getDataPath("fonts" DIR_DELIM "Arimo-BoldItalic.ttf")); + 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")); + settings->setDefault("font_path_bold_italic", porting::getDataPath("fonts" DIR_DELIM "Arimo-BoldItalic.ttf")); settings->setDefault("font_bold", "false"); settings->setDefault("font_italic", "false"); settings->setDefault("font_shadow", "1"); settings->setDefault("font_shadow_alpha", "127"); - 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("fallback_font_path", - porting::getDataPath( - "fonts" DIR_DELIM "DroidSansFallbackFull.ttf")); + 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("fallback_font_path", porting::getDataPath("fonts" DIR_DELIM "DroidSansFallbackFull.ttf")); settings->setDefault("fallback_font_shadow", "1"); settings->setDefault("fallback_font_shadow_alpha", "128"); @@ -404,10 +395,8 @@ void set_default_settings(Settings *settings) settings->setDefault("fallback_font_size", font_size_str); #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")); + 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 @@ -424,6 +413,7 @@ void set_default_settings(Settings *settings) settings->setDefault("contentdb_flag_blacklist", "nonfree, desktop_default"); #endif + // Server settings->setDefault("disable_escape_sequences", "false"); settings->setDefault("strip_color_codes", "false"); @@ -434,7 +424,7 @@ void set_default_settings(Settings *settings) // Network settings->setDefault("enable_ipv6", "true"); settings->setDefault("ipv6_server", "false"); - settings->setDefault("max_packets_per_iteration", "1024"); + settings->setDefault("max_packets_per_iteration","1024"); settings->setDefault("port", "30000"); settings->setDefault("strict_protocol_version_checking", "false"); settings->setDefault("player_transfer_distance", "0"); @@ -460,15 +450,14 @@ void set_default_settings(Settings *settings) #endif settings->setDefault("kick_msg_shutdown", "Server shutting down."); - settings->setDefault("kick_msg_crash", "This server has experienced an internal " - "error. You will now be disconnected."); + settings->setDefault("kick_msg_crash", "This server has experienced an internal error. You will now be disconnected."); settings->setDefault("ask_reconnect_on_crash", "false"); settings->setDefault("chat_message_format", "<@name> @message"); settings->setDefault("profiler_print_interval", "0"); settings->setDefault("active_object_send_range_blocks", "4"); settings->setDefault("active_block_range", "3"); - // settings->setDefault("max_simultaneous_block_sends_per_client", "1"); + //settings->setDefault("max_simultaneous_block_sends_per_client", "1"); // This causes frametime jitter on client side, or does it? settings->setDefault("max_block_send_distance", "10"); settings->setDefault("block_send_optimize_distance", "4"); @@ -556,7 +545,7 @@ void set_default_settings(Settings *settings) settings->setDefault("fullscreen", "true"); settings->setDefault("touchtarget", "true"); settings->setDefault("TMPFolder", porting::path_cache); - settings->setDefault("touchscreen_threshold", "20"); + settings->setDefault("touchscreen_threshold","20"); settings->setDefault("fixed_virtual_joystick", "false"); settings->setDefault("virtual_joystick_triggers_aux", "false"); settings->setDefault("smooth_lighting", "false"); @@ -574,11 +563,11 @@ void set_default_settings(Settings *settings) settings->setDefault("active_block_range", "2"); settings->setDefault("viewing_range", "50"); settings->setDefault("leaves_style", "simple"); - settings->setDefault("curl_verify_cert", "false"); + settings->setDefault("curl_verify_cert","false"); // Apply settings according to screen size - float x_inches = (float)porting::getDisplaySize().X / - (160.f * porting::getDisplayDensity()); + float x_inches = (float) porting::getDisplaySize().X / + (160.f * porting::getDisplayDensity()); if (x_inches < 3.7f) { settings->setDefault("hud_scaling", "0.6"); diff --git a/src/emerge.cpp b/src/emerge.cpp index e76383d09..0ac26a682 100644 --- a/src/emerge.cpp +++ b/src/emerge.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "emerge.h" #include @@ -44,8 +45,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "voxel.h" -class EmergeThread : public Thread -{ +class EmergeThread : public Thread { public: bool enable_mapgen_debug_info; int id; @@ -61,8 +61,9 @@ class EmergeThread : public Thread void cancelPendingItems(); - static void runCompletionCallbacks(const v3s16 &pos, EmergeAction action, - const EmergeCallbackList &callbacks); + static void runCompletionCallbacks( + const v3s16 &pos, EmergeAction action, + const EmergeCallbackList &callbacks); private: Server *m_server; @@ -75,10 +76,10 @@ class EmergeThread : public Thread bool popBlockEmerge(v3s16 *pos, BlockEmergeData *bedata); - EmergeAction getBlockOrStartGen(const v3s16 &pos, bool allow_gen, - MapBlock **block, BlockMakeData *data); + EmergeAction getBlockOrStartGen( + const v3s16 &pos, bool allow_gen, MapBlock **block, BlockMakeData *data); MapBlock *finishGen(v3s16 pos, BlockMakeData *bmdata, - std::map *modified_blocks); + std::map *modified_blocks); friend class EmergeManager; }; @@ -86,10 +87,10 @@ class EmergeThread : public Thread class MapEditEventAreaIgnorer { public: - MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a) : - m_ignorevariable(ignorevariable) + MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a): + m_ignorevariable(ignorevariable) { - if (m_ignorevariable->getVolume() == 0) + if(m_ignorevariable->getVolume() == 0) *m_ignorevariable = a; else m_ignorevariable = NULL; @@ -97,7 +98,8 @@ class MapEditEventAreaIgnorer ~MapEditEventAreaIgnorer() { - if (m_ignorevariable) { + if(m_ignorevariable) + { assert(m_ignorevariable->getVolume() != 0); *m_ignorevariable = VoxelArea(); } @@ -118,14 +120,14 @@ EmergeParams::~EmergeParams() } EmergeParams::EmergeParams(EmergeManager *parent, const BiomeManager *biomemgr, - const OreManager *oremgr, const DecorationManager *decomgr, - const SchematicManager *schemmgr) : - ndef(parent->ndef), - enable_mapgen_debug_info(parent->enable_mapgen_debug_info), - gen_notify_on(parent->gen_notify_on), - gen_notify_on_deco_ids(&parent->gen_notify_on_deco_ids), - biomemgr(biomemgr->clone()), oremgr(oremgr->clone()), - decomgr(decomgr->clone()), schemmgr(schemmgr->clone()) + const OreManager *oremgr, const DecorationManager *decomgr, + const SchematicManager *schemmgr) : + ndef(parent->ndef), + enable_mapgen_debug_info(parent->enable_mapgen_debug_info), + gen_notify_on(parent->gen_notify_on), + gen_notify_on_deco_ids(&parent->gen_notify_on_deco_ids), + biomemgr(biomemgr->clone()), oremgr(oremgr->clone()), + decomgr(decomgr->clone()), schemmgr(schemmgr->clone()) { } @@ -135,11 +137,11 @@ EmergeParams::EmergeParams(EmergeManager *parent, const BiomeManager *biomemgr, EmergeManager::EmergeManager(Server *server) { - this->ndef = server->getNodeDefManager(); - this->biomemgr = new BiomeManager(server); - this->oremgr = new OreManager(server); - this->decomgr = new DecorationManager(server); - this->schemmgr = new SchematicManager(server); + this->ndef = server->getNodeDefManager(); + this->biomemgr = new BiomeManager(server); + this->oremgr = new OreManager(server); + this->decomgr = new DecorationManager(server); + this->schemmgr = new SchematicManager(server); // Note that accesses to this variable are not synchronized. // This is because the *only* thread ever starting or stopping @@ -177,6 +179,7 @@ EmergeManager::EmergeManager(Server *server) infostream << "EmergeManager: using " << nthreads << " threads" << std::endl; } + EmergeManager::~EmergeManager() { for (u32 i = 0; i != m_threads.size(); i++) { @@ -201,34 +204,36 @@ EmergeManager::~EmergeManager() delete schemmgr; } + BiomeManager *EmergeManager::getWritableBiomeManager() { FATAL_ERROR_IF(!m_mapgens.empty(), - "Writable managers can only be returned before mapgen init"); + "Writable managers can only be returned before mapgen init"); return biomemgr; } OreManager *EmergeManager::getWritableOreManager() { FATAL_ERROR_IF(!m_mapgens.empty(), - "Writable managers can only be returned before mapgen init"); + "Writable managers can only be returned before mapgen init"); return oremgr; } DecorationManager *EmergeManager::getWritableDecorationManager() { FATAL_ERROR_IF(!m_mapgens.empty(), - "Writable managers can only be returned before mapgen init"); + "Writable managers can only be returned before mapgen init"); return decomgr; } SchematicManager *EmergeManager::getWritableSchematicManager() { FATAL_ERROR_IF(!m_mapgens.empty(), - "Writable managers can only be returned before mapgen init"); + "Writable managers can only be returned before mapgen init"); return schemmgr; } + void EmergeManager::initMapgens(MapgenParams *params) { FATAL_ERROR_IF(!m_mapgens.empty(), "Mapgen already initialised."); @@ -237,13 +242,14 @@ void EmergeManager::initMapgens(MapgenParams *params) for (u32 i = 0; i != m_threads.size(); i++) { EmergeParams *p = new EmergeParams( - this, biomemgr, oremgr, decomgr, schemmgr); - infostream << "EmergeManager: Created params " << p << " for thread " << i - << std::endl; + this, biomemgr, oremgr, decomgr, schemmgr); + infostream << "EmergeManager: Created params " << p + << " for thread " << i << std::endl; m_mapgens.push_back(Mapgen::createMapgen(params->mgtype, params, p)); } } + Mapgen *EmergeManager::getCurrentMapgen() { if (!m_threads_active) @@ -258,6 +264,7 @@ Mapgen *EmergeManager::getCurrentMapgen() return nullptr; } + void EmergeManager::startThreads() { if (m_threads_active) @@ -269,6 +276,7 @@ void EmergeManager::startThreads() m_threads_active = true; } + void EmergeManager::stopThreads() { if (!m_threads_active) @@ -287,13 +295,18 @@ void EmergeManager::stopThreads() m_threads_active = false; } + bool EmergeManager::isRunning() { return m_threads_active; } -bool EmergeManager::enqueueBlockEmerge(session_t peer_id, v3s16 blockpos, - bool allow_generate, bool ignore_queue_limits) + +bool EmergeManager::enqueueBlockEmerge( + session_t peer_id, + v3s16 blockpos, + bool allow_generate, + bool ignore_queue_limits) { u16 flags = 0; if (allow_generate) @@ -304,8 +317,13 @@ bool EmergeManager::enqueueBlockEmerge(session_t peer_id, v3s16 blockpos, return enqueueBlockEmergeEx(blockpos, peer_id, flags, NULL, NULL); } -bool EmergeManager::enqueueBlockEmergeEx(v3s16 blockpos, session_t peer_id, u16 flags, - EmergeCompletionCallback callback, void *callback_param) + +bool EmergeManager::enqueueBlockEmergeEx( + v3s16 blockpos, + session_t peer_id, + u16 flags, + EmergeCompletionCallback callback, + void *callback_param) { EmergeThread *thread = NULL; bool entry_already_exists = false; @@ -313,8 +331,8 @@ bool EmergeManager::enqueueBlockEmergeEx(v3s16 blockpos, session_t peer_id, u16 { MutexAutoLock queuelock(m_queue_mutex); - if (!pushBlockEmergeData(blockpos, peer_id, flags, callback, - callback_param, &entry_already_exists)) + if (!pushBlockEmergeData(blockpos, peer_id, flags, + callback, callback_param, &entry_already_exists)) return false; if (entry_already_exists) @@ -329,10 +347,12 @@ bool EmergeManager::enqueueBlockEmergeEx(v3s16 blockpos, session_t peer_id, u16 return true; } + // // Mapgen-related helper functions // + // TODO(hmmmm): Move this to ServerMap v3s16 EmergeManager::getContainingChunk(v3s16 blockpos) { @@ -345,28 +365,28 @@ v3s16 EmergeManager::getContainingChunk(v3s16 blockpos, s16 chunksize) s16 coff = -chunksize / 2; v3s16 chunk_offset(coff, coff, coff); - return getContainerPos(blockpos - chunk_offset, chunksize) * chunksize + - chunk_offset; + return getContainerPos(blockpos - chunk_offset, chunksize) + * chunksize + chunk_offset; } + int EmergeManager::getSpawnLevelAtPoint(v2s16 p) { if (m_mapgens.empty() || !m_mapgens[0]) { errorstream << "EmergeManager: getSpawnLevelAtPoint() called" - " before mapgen init" - << std::endl; + " before mapgen init" << std::endl; return 0; } return m_mapgens[0]->getSpawnLevelAtPoint(p); } + int EmergeManager::getGroundLevelAtPoint(v2s16 p) { if (m_mapgens.empty() || !m_mapgens[0]) { errorstream << "EmergeManager: getGroundLevelAtPoint() called" - " before mapgen init" - << std::endl; + " before mapgen init" << std::endl; return 0; } @@ -387,9 +407,13 @@ bool EmergeManager::isBlockUnderground(v3s16 blockpos) return blockpos.Y * (MAP_BLOCKSIZE + 1) <= mgparams->water_level; } -bool EmergeManager::pushBlockEmergeData(v3s16 pos, u16 peer_requested, u16 flags, - EmergeCompletionCallback callback, void *callback_param, - bool *entry_already_exists) +bool EmergeManager::pushBlockEmergeData( + v3s16 pos, + u16 peer_requested, + u16 flags, + EmergeCompletionCallback callback, + void *callback_param, + bool *entry_already_exists) { u16 &count_peer = m_peer_queue_count[peer_requested]; @@ -398,9 +422,8 @@ bool EmergeManager::pushBlockEmergeData(v3s16 pos, u16 peer_requested, u16 flags return false; if (peer_requested != PEER_ID_INEXISTENT) { - u16 qlimit_peer = (flags & BLOCK_EMERGE_ALLOW_GEN) - ? m_qlimit_generate - : m_qlimit_diskonly; + u16 qlimit_peer = (flags & BLOCK_EMERGE_ALLOW_GEN) ? + m_qlimit_generate : m_qlimit_diskonly; if (count_peer >= qlimit_peer) return false; } @@ -410,7 +433,7 @@ bool EmergeManager::pushBlockEmergeData(v3s16 pos, u16 peer_requested, u16 flags findres = m_blocks_enqueued.insert(std::make_pair(pos, BlockEmergeData())); BlockEmergeData &bedata = findres.first->second; - *entry_already_exists = !findres.second; + *entry_already_exists = !findres.second; if (callback) bedata.callbacks.emplace_back(callback, callback_param); @@ -427,6 +450,7 @@ bool EmergeManager::pushBlockEmergeData(v3s16 pos, u16 peer_requested, u16 flags return true; } + bool EmergeManager::popBlockEmergeData(v3s16 pos, BlockEmergeData *bedata) { std::map::iterator it; @@ -451,6 +475,7 @@ bool EmergeManager::popBlockEmergeData(v3s16 pos, BlockEmergeData *bedata) return true; } + EmergeThread *EmergeManager::getOptimalThread() { size_t nthreads = m_threads.size(); @@ -471,28 +496,36 @@ EmergeThread *EmergeManager::getOptimalThread() return m_threads[index]; } + //// //// EmergeThread //// EmergeThread::EmergeThread(Server *server, int ethreadid) : - enable_mapgen_debug_info(false), id(ethreadid), m_server(server), - m_map(NULL), m_emerge(NULL), m_mapgen(NULL) + enable_mapgen_debug_info(false), + id(ethreadid), + m_server(server), + m_map(NULL), + m_emerge(NULL), + m_mapgen(NULL) { m_name = "Emerge-" + itos(ethreadid); } + void EmergeThread::signal() { m_queue_event.signal(); } + bool EmergeThread::pushBlock(const v3s16 &pos) { m_block_queue.push(pos); return true; } + void EmergeThread::cancelPendingItems() { MutexAutoLock queuelock(m_emerge->m_queue_mutex); @@ -510,20 +543,22 @@ void EmergeThread::cancelPendingItems() } } + void EmergeThread::runCompletionCallbacks(const v3s16 &pos, EmergeAction action, - const EmergeCallbackList &callbacks) + const EmergeCallbackList &callbacks) { for (size_t i = 0; i != callbacks.size(); i++) { EmergeCompletionCallback callback; void *param; callback = callbacks[i].first; - param = callbacks[i].second; + param = callbacks[i].second; callback(pos, action, param); } } + bool EmergeThread::popBlockEmerge(v3s16 *pos, BlockEmergeData *bedata) { MutexAutoLock queuelock(m_emerge->m_queue_mutex); @@ -539,8 +574,9 @@ bool EmergeThread::popBlockEmerge(v3s16 *pos, BlockEmergeData *bedata) return true; } + EmergeAction EmergeThread::getBlockOrStartGen( - const v3s16 &pos, bool allow_gen, MapBlock **block, BlockMakeData *bmdata) + const v3s16 &pos, bool allow_gen, MapBlock **block, BlockMakeData *bmdata) { MutexAutoLock envlock(m_server->m_env_mutex); @@ -564,11 +600,13 @@ EmergeAction EmergeThread::getBlockOrStartGen( return EMERGE_CANCELLED; } + MapBlock *EmergeThread::finishGen(v3s16 pos, BlockMakeData *bmdata, - std::map *modified_blocks) + std::map *modified_blocks) { MutexAutoLock envlock(m_server->m_env_mutex); - ScopeProfiler sp(g_profiler, "EmergeThread: after Mapgen::makeChunk", SPT_AVG); + ScopeProfiler sp(g_profiler, + "EmergeThread: after Mapgen::makeChunk", SPT_AVG); /* Perform post-processing on blocks (invalidate lighting, queue liquid @@ -579,26 +617,26 @@ MapBlock *EmergeThread::finishGen(v3s16 pos, BlockMakeData *bmdata, MapBlock *block = m_map->getBlockNoCreateNoEx(pos); if (!block) { errorstream << "EmergeThread::finishGen: Couldn't grab block we " - "just generated: " - << PP(pos) << std::endl; + "just generated: " << PP(pos) << std::endl; return NULL; } v3s16 minp = bmdata->blockpos_min * MAP_BLOCKSIZE; v3s16 maxp = bmdata->blockpos_max * MAP_BLOCKSIZE + - v3s16(1, 1, 1) * (MAP_BLOCKSIZE - 1); + v3s16(1,1,1) * (MAP_BLOCKSIZE - 1); // Ignore map edit events, they will not need to be sent // to anybody because the block hasn't been sent to anybody MapEditEventAreaIgnorer ign( - &m_server->m_ignore_map_edit_events_area, VoxelArea(minp, maxp)); + &m_server->m_ignore_map_edit_events_area, + VoxelArea(minp, maxp)); /* Run Lua on_generated callbacks */ try { m_server->getScriptIface()->environment_OnGenerated( - minp, maxp, m_mapgen->blockseed); + minp, maxp, m_mapgen->blockseed); } catch (LuaError &e) { m_server->setAsyncFatalError("Lua: finishGen" + std::string(e.what())); } @@ -618,74 +656,74 @@ MapBlock *EmergeThread::finishGen(v3s16 pos, BlockMakeData *bmdata, return block; } + void *EmergeThread::run() { BEGIN_DEBUG_EXCEPTION_HANDLER v3s16 pos; - m_map = (ServerMap *)&(m_server->m_env->getMap()); + m_map = (ServerMap *)&(m_server->m_env->getMap()); m_emerge = m_server->m_emerge; m_mapgen = m_emerge->m_mapgens[id]; enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info; try { - while (!stopRequested()) { - std::map modified_blocks; - BlockEmergeData bedata; - BlockMakeData bmdata; - EmergeAction action; - MapBlock *block; - - if (!popBlockEmerge(&pos, &bedata)) { - m_queue_event.wait(); - continue; - } + while (!stopRequested()) { + std::map modified_blocks; + BlockEmergeData bedata; + BlockMakeData bmdata; + EmergeAction action; + MapBlock *block; - if (blockpos_over_max_limit(pos)) - continue; + if (!popBlockEmerge(&pos, &bedata)) { + m_queue_event.wait(); + continue; + } - bool allow_gen = bedata.flags & BLOCK_EMERGE_ALLOW_GEN; - EMERGE_DBG_OUT("pos=" PP(pos) " allow_gen=" << allow_gen); + if (blockpos_over_max_limit(pos)) + continue; - action = getBlockOrStartGen(pos, allow_gen, &block, &bmdata); - if (action == EMERGE_GENERATED) { - { - ScopeProfiler sp(g_profiler, - "EmergeThread: Mapgen::makeChunk", - SPT_AVG); + bool allow_gen = bedata.flags & BLOCK_EMERGE_ALLOW_GEN; + EMERGE_DBG_OUT("pos=" PP(pos) " allow_gen=" << allow_gen); - m_mapgen->makeChunk(&bmdata); - } + action = getBlockOrStartGen(pos, allow_gen, &block, &bmdata); + if (action == EMERGE_GENERATED) { + { + ScopeProfiler sp(g_profiler, + "EmergeThread: Mapgen::makeChunk", SPT_AVG); - block = finishGen(pos, &bmdata, &modified_blocks); + m_mapgen->makeChunk(&bmdata); } - runCompletionCallbacks(pos, action, bedata.callbacks); + block = finishGen(pos, &bmdata, &modified_blocks); + } - if (block) - modified_blocks[pos] = block; + runCompletionCallbacks(pos, action, bedata.callbacks); - if (!modified_blocks.empty()) - m_server->SetBlocksNotSent(modified_blocks); - } + if (block) + modified_blocks[pos] = block; + + if (!modified_blocks.empty()) + m_server->SetBlocksNotSent(modified_blocks); + } } catch (VersionMismatchException &e) { std::ostringstream err; err << "World data version mismatch in MapBlock " << PP(pos) << std::endl - << "----" << std::endl - << "\"" << e.what() << "\"" << std::endl - << "See debug.txt." << std::endl - << "World probably saved by a newer version of " PROJECT_NAME_C "." - << std::endl; + << "----" << std::endl + << "\"" << e.what() << "\"" << std::endl + << "See debug.txt." << std::endl + << "World probably saved by a newer version of " PROJECT_NAME_C "." + << std::endl; m_server->setAsyncFatalError(err.str()); } catch (SerializationError &e) { std::ostringstream err; err << "Invalid data in MapBlock " << PP(pos) << std::endl - << "----" << std::endl - << "\"" << e.what() << "\"" << std::endl - << "See debug.txt." << std::endl - << "You can ignore this using [ignore_world_load_errors = true]." - << std::endl; + << "----" << std::endl + << "\"" << e.what() << "\"" << std::endl + << "See debug.txt." << std::endl + << "You can ignore this using [ignore_world_load_errors = true]." + << std::endl; m_server->setAsyncFatalError(err.str()); } diff --git a/src/emerge.h b/src/emerge.h index d27aa804d..6f204666d 100644 --- a/src/emerge.h +++ b/src/emerge.h @@ -27,14 +27,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen/mapgen.h" // for MapgenParams #include "map.h" -#define BLOCK_EMERGE_ALLOW_GEN (1 << 0) +#define BLOCK_EMERGE_ALLOW_GEN (1 << 0) #define BLOCK_EMERGE_FORCE_QUEUE (1 << 1) -#define EMERGE_DBG_OUT(x) \ - { \ - if (enable_mapgen_debug_info) \ - infostream << "EmergeThread: " x << std::endl; \ - } +#define EMERGE_DBG_OUT(x) { \ + if (enable_mapgen_debug_info) \ + infostream << "EmergeThread: " x << std::endl; \ +} class EmergeThread; class NodeDefManager; @@ -48,8 +47,7 @@ class Server; class ModApiMapgen; // Structure containing inputs/outputs for chunk generation -struct BlockMakeData -{ +struct BlockMakeData { MMVManip *vmanip = nullptr; u64 seed = 0; v3s16 blockpos_min; @@ -64,8 +62,7 @@ struct BlockMakeData }; // Result from processing an item on the emerge queue -enum EmergeAction -{ +enum EmergeAction { EMERGE_CANCELLED, EMERGE_ERRORED, EMERGE_FROM_MEMORY, @@ -75,21 +72,23 @@ enum EmergeAction // Callback typedef void (*EmergeCompletionCallback)( - v3s16 blockpos, EmergeAction action, void *param); + v3s16 blockpos, EmergeAction action, void *param); -typedef std::vector> EmergeCallbackList; +typedef std::vector< + std::pair< + EmergeCompletionCallback, + void * + > +> EmergeCallbackList; -struct BlockEmergeData -{ +struct BlockEmergeData { u16 peer_requested; u16 flags; EmergeCallbackList callbacks; }; -class EmergeParams -{ +class EmergeParams { friend class EmergeManager; - public: EmergeParams() = delete; ~EmergeParams(); @@ -108,18 +107,16 @@ class EmergeParams private: EmergeParams(EmergeManager *parent, const BiomeManager *biomemgr, - const OreManager *oremgr, const DecorationManager *decomgr, - const SchematicManager *schemmgr); + const OreManager *oremgr, const DecorationManager *decomgr, + const SchematicManager *schemmgr); }; -class EmergeManager -{ +class EmergeManager { /* The mod API needs unchecked access to allow: * - using decomgr or oremgr to place decos/ores * - using schemmgr to load and place schematics */ friend class ModApiMapgen; - public: const NodeDefManager *ndef; bool enable_mapgen_debug_info; @@ -161,11 +158,18 @@ class EmergeManager void stopThreads(); bool isRunning(); - bool enqueueBlockEmerge(session_t peer_id, v3s16 blockpos, bool allow_generate, - bool ignore_queue_limits = false); + bool enqueueBlockEmerge( + session_t peer_id, + v3s16 blockpos, + bool allow_generate, + bool ignore_queue_limits=false); - bool enqueueBlockEmergeEx(v3s16 blockpos, session_t peer_id, u16 flags, - EmergeCompletionCallback callback, void *callback_param); + bool enqueueBlockEmergeEx( + v3s16 blockpos, + session_t peer_id, + u16 flags, + EmergeCompletionCallback callback, + void *callback_param); v3s16 getContainingChunk(v3s16 blockpos); @@ -201,9 +205,13 @@ class EmergeManager // Requires m_queue_mutex held EmergeThread *getOptimalThread(); - bool pushBlockEmergeData(v3s16 pos, u16 peer_requested, u16 flags, - EmergeCompletionCallback callback, void *callback_param, - bool *entry_already_exists); + bool pushBlockEmergeData( + v3s16 pos, + u16 peer_requested, + u16 flags, + EmergeCompletionCallback callback, + void *callback_param, + bool *entry_already_exists); bool popBlockEmergeData(v3s16 pos, BlockEmergeData *bedata); diff --git a/src/environment.cpp b/src/environment.cpp index 0a08a1d68..7acad313e 100644 --- a/src/environment.cpp +++ b/src/environment.cpp @@ -26,12 +26,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "daynightratio.h" #include "emerge.h" -Environment::Environment(IGameDef *gamedef) : - m_time_of_day_speed(0.0f), m_day_count(0), m_gamedef(gamedef) + +Environment::Environment(IGameDef *gamedef): + m_time_of_day_speed(0.0f), + m_day_count(0), + m_gamedef(gamedef) { m_cache_enable_shaders = g_settings->getBool("enable_shaders"); - m_cache_active_block_mgmt_interval = - g_settings->getFloat("active_block_mgmt_interval"); + m_cache_active_block_mgmt_interval = g_settings->getFloat("active_block_mgmt_interval"); m_cache_abm_interval = g_settings->getFloat("abm_interval"); m_cache_nodetimer_interval = g_settings->getFloat("nodetimer_interval"); @@ -103,15 +105,14 @@ bool Environment::line_of_sight(v3f pos1, v3f pos2, v3s16 *p) /* Check if a node is pointable */ -inline static bool isPointableNode(const MapNode &n, const NodeDefManager *nodedef, - bool liquids_pointable, bool nodes_pointable) +inline static bool isPointableNode(const MapNode &n, + const NodeDefManager *nodedef , bool liquids_pointable, bool nodes_pointable) { - if (!nodes_pointable) + if (! nodes_pointable) return false; const ContentFeatures &features = nodedef->get(n); return features.pointable || - ((liquids_pointable || g_settings->getBool("point_liquids")) && - features.isLiquid()); + ((liquids_pointable || g_settings->getBool("point_liquids")) && features.isLiquid()); } void Environment::continueRaycast(RaycastState *state, PointedThing *result) @@ -139,7 +140,7 @@ void Environment::continueRaycast(RaycastState *state, PointedThing *result) s16 lastIndex = state->m_iterator.m_last_index; if (!state->m_found.empty()) { lastIndex = state->m_iterator.getIndex( - floatToInt(state->m_found.top().intersection_point, BS)); + floatToInt(state->m_found.top().intersection_point, BS)); } Map &map = getMap(); @@ -155,8 +156,8 @@ void Environment::continueRaycast(RaycastState *state, PointedThing *result) new_nodes.MaxEdge += state->m_iterator.m_current_node_pos; // Only check new nodes - v3s16 delta = state->m_iterator.m_current_node_pos - - state->m_previous_node; + v3s16 delta = state->m_iterator.m_current_node_pos + - state->m_previous_node; if (delta.X > 0) { new_nodes.MinEdge.X = new_nodes.MaxEdge.X; } else if (delta.X < 0) { @@ -173,113 +174,99 @@ void Environment::continueRaycast(RaycastState *state, PointedThing *result) // For each untested node for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) - for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) - for (s16 z = new_nodes.MinEdge.Z; - z <= new_nodes.MaxEdge.Z; z++) { - MapNode n; - v3s16 np(x, y, z); - bool is_valid_position; - - n = map.getNode(np, &is_valid_position); - if (!(is_valid_position && - isPointableNode(n, nodedef, - state->m_liquids_pointable, - state->m_nodes_pointable))) { - continue; - } - - PointedThing result; - - std::vector boxes; - n.getSelectionBoxes(nodedef, &boxes, - n.getNeighbors(np, &map)); - - // Is there a collision with a selection box? - bool is_colliding = false; - // Minimal distance of all collisions - float min_distance_sq = 10000000; - // ID of the current box (loop counter) - u16 id = 0; - - v3f npf = intToFloat(np, BS); - // This loop translates the boxes to their - // in-world place. - for (aabb3f &box : boxes) { - box.MinEdge += npf; - box.MaxEdge += npf; - - v3f intersection_point; - v3s16 intersection_normal; - if (!boxLineCollision(box, - state->m_shootline - .start, - state->m_shootline - .getVector(), - &intersection_point, - &intersection_normal)) { - ++id; - continue; - } - - f32 distanceSq = (intersection_point - - state->m_shootline - .start) - .getLengthSQ(); - // If this is the nearest collision, save - // it - if (min_distance_sq > distanceSq) { - min_distance_sq = distanceSq; - result.intersection_point = - intersection_point; - result.intersection_normal = - intersection_normal; - result.box_id = id; - found_boxcenter = box.getCenter(); - is_colliding = true; - } - ++id; - } - // If there wasn't a collision, stop - if (!is_colliding) { - continue; - } - result.type = POINTEDTHING_NODE; - result.node_undersurface = np; - result.distanceSq = min_distance_sq; - // Set undersurface and abovesurface nodes - f32 d = 0.002 * BS; - v3f fake_intersection = result.intersection_point; - // Move intersection towards its source block. - if (fake_intersection.X < found_boxcenter.X) { - fake_intersection.X += d; - } else { - fake_intersection.X -= d; - } - if (fake_intersection.Y < found_boxcenter.Y) { - fake_intersection.Y += d; - } else { - fake_intersection.Y -= d; - } - if (fake_intersection.Z < found_boxcenter.Z) { - fake_intersection.Z += d; - } else { - fake_intersection.Z -= d; - } - result.node_real_undersurface = - floatToInt(fake_intersection, BS); - result.node_abovesurface = - result.node_real_undersurface + - result.intersection_normal; - // Push found PointedThing - state->m_found.push(result); - // If this is nearer than the old nearest object, - // the search can be shorter - s16 newIndex = state->m_iterator.getIndex( - result.node_real_undersurface); - if (newIndex < lastIndex) { - lastIndex = newIndex; - } + for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) + for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) { + MapNode n; + v3s16 np(x, y, z); + bool is_valid_position; + + n = map.getNode(np, &is_valid_position); + if (!(is_valid_position && isPointableNode(n, nodedef, + state->m_liquids_pointable, state->m_nodes_pointable))) { + continue; + } + + PointedThing result; + + std::vector boxes; + n.getSelectionBoxes(nodedef, &boxes, + n.getNeighbors(np, &map)); + + // Is there a collision with a selection box? + bool is_colliding = false; + // Minimal distance of all collisions + float min_distance_sq = 10000000; + // ID of the current box (loop counter) + u16 id = 0; + + v3f npf = intToFloat(np, BS); + // This loop translates the boxes to their in-world place. + for (aabb3f &box : boxes) { + box.MinEdge += npf; + box.MaxEdge += npf; + + v3f intersection_point; + v3s16 intersection_normal; + if (!boxLineCollision(box, state->m_shootline.start, + state->m_shootline.getVector(), &intersection_point, + &intersection_normal)) { + ++id; + continue; } + + f32 distanceSq = (intersection_point + - state->m_shootline.start).getLengthSQ(); + // If this is the nearest collision, save it + if (min_distance_sq > distanceSq) { + min_distance_sq = distanceSq; + result.intersection_point = intersection_point; + result.intersection_normal = intersection_normal; + result.box_id = id; + found_boxcenter = box.getCenter(); + is_colliding = true; + } + ++id; + } + // If there wasn't a collision, stop + if (!is_colliding) { + continue; + } + result.type = POINTEDTHING_NODE; + result.node_undersurface = np; + result.distanceSq = min_distance_sq; + // Set undersurface and abovesurface nodes + f32 d = 0.002 * BS; + v3f fake_intersection = result.intersection_point; + // Move intersection towards its source block. + if (fake_intersection.X < found_boxcenter.X) { + fake_intersection.X += d; + } else { + fake_intersection.X -= d; + } + if (fake_intersection.Y < found_boxcenter.Y) { + fake_intersection.Y += d; + } else { + fake_intersection.Y -= d; + } + if (fake_intersection.Z < found_boxcenter.Z) { + fake_intersection.Z += d; + } else { + fake_intersection.Z -= d; + } + result.node_real_undersurface = floatToInt( + fake_intersection, BS); + result.node_abovesurface = result.node_real_undersurface + + result.intersection_normal; + // Push found PointedThing + state->m_found.push(result); + // If this is nearer than the old nearest object, + // the search can be shorter + s16 newIndex = state->m_iterator.getIndex( + result.node_real_undersurface); + if (newIndex < lastIndex) { + lastIndex = newIndex; + } + } // Next node state->m_previous_node = state->m_iterator.m_current_node_pos; state->m_iterator.next(); diff --git a/src/exceptions.h b/src/exceptions.h index b96d6c8d8..c54307653 100644 --- a/src/exceptions.h +++ b/src/exceptions.h @@ -22,120 +22,110 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include + class BaseException : public std::exception { public: - BaseException(const std::string &s) throw() : m_s(s) {} + BaseException(const std::string &s) throw(): m_s(s) {} ~BaseException() throw() = default; - virtual const char *what() const throw() { return m_s.c_str(); } - + virtual const char * what() const throw() + { + return m_s.c_str(); + } protected: std::string m_s; }; -class AlreadyExistsException : public BaseException -{ +class AlreadyExistsException : public BaseException { public: - AlreadyExistsException(const std::string &s) : BaseException(s) {} + AlreadyExistsException(const std::string &s): BaseException(s) {} }; -class VersionMismatchException : public BaseException -{ +class VersionMismatchException : public BaseException { public: - VersionMismatchException(const std::string &s) : BaseException(s) {} + VersionMismatchException(const std::string &s): BaseException(s) {} }; -class FileNotGoodException : public BaseException -{ +class FileNotGoodException : public BaseException { public: - FileNotGoodException(const std::string &s) : BaseException(s) {} + FileNotGoodException(const std::string &s): BaseException(s) {} }; -class DatabaseException : public BaseException -{ +class DatabaseException : public BaseException { public: - DatabaseException(const std::string &s) : BaseException(s) {} + DatabaseException(const std::string &s): BaseException(s) {} }; -class SerializationError : public BaseException -{ +class SerializationError : public BaseException { public: - SerializationError(const std::string &s) : BaseException(s) {} + SerializationError(const std::string &s): BaseException(s) {} }; -class PacketError : public BaseException -{ +class PacketError : public BaseException { public: - PacketError(const std::string &s) : BaseException(s) {} + PacketError(const std::string &s): BaseException(s) {} }; -class SettingNotFoundException : public BaseException -{ +class SettingNotFoundException : public BaseException { public: - SettingNotFoundException(const std::string &s) : BaseException(s) {} + SettingNotFoundException(const std::string &s): BaseException(s) {} }; -class InvalidFilenameException : public BaseException -{ +class InvalidFilenameException : public BaseException { public: - InvalidFilenameException(const std::string &s) : BaseException(s) {} + InvalidFilenameException(const std::string &s): BaseException(s) {} }; -class ItemNotFoundException : public BaseException -{ +class ItemNotFoundException : public BaseException { public: - ItemNotFoundException(const std::string &s) : BaseException(s) {} + ItemNotFoundException(const std::string &s): BaseException(s) {} }; -class ServerError : public BaseException -{ +class ServerError : public BaseException { public: - ServerError(const std::string &s) : BaseException(s) {} + ServerError(const std::string &s): BaseException(s) {} }; -class ClientStateError : public BaseException -{ +class ClientStateError : public BaseException { public: - ClientStateError(const std::string &s) : BaseException(s) {} + ClientStateError(const std::string &s): BaseException(s) {} }; -class PrngException : public BaseException -{ +class PrngException : public BaseException { public: - PrngException(const std::string &s) : BaseException(s) {} + PrngException(const std::string &s): BaseException(s) {} }; -class ModError : public BaseException -{ +class ModError : public BaseException { public: - ModError(const std::string &s) : BaseException(s) {} + ModError(const std::string &s): BaseException(s) {} }; + /* Some "old-style" interrupts: */ -class InvalidNoiseParamsException : public BaseException -{ +class InvalidNoiseParamsException : public BaseException { public: - InvalidNoiseParamsException() : - BaseException("One or more noise parameters were invalid or " - "require " - "too much memory") - { - } + InvalidNoiseParamsException(): + BaseException("One or more noise parameters were invalid or require " + "too much memory") + {} - InvalidNoiseParamsException(const std::string &s) : BaseException(s) {} + InvalidNoiseParamsException(const std::string &s): + BaseException(s) + {} }; class InvalidPositionException : public BaseException { public: - InvalidPositionException() : - BaseException("Somebody tried to get/set something in a " - "nonexistent position.") - { - } - InvalidPositionException(const std::string &s) : BaseException(s) {} + InvalidPositionException(): + BaseException("Somebody tried to get/set something in a nonexistent position.") + {} + InvalidPositionException(const std::string &s): + BaseException(s) + {} }; diff --git a/src/face_position_cache.cpp b/src/face_position_cache.cpp index 8b222aa29..7a8f235fa 100644 --- a/src/face_position_cache.cpp +++ b/src/face_position_cache.cpp @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "face_position_cache.h" #include "threading/mutex_auto_lock.h" + std::unordered_map> FacePositionCache::cache; std::mutex FacePositionCache::cache_mutex; @@ -39,39 +40,39 @@ const std::vector &FacePositionCache::generateFacePosition(u16 d) cache[d] = std::vector(); std::vector &c = cache[d]; if (d == 0) { - c.emplace_back(0, 0, 0); + c.emplace_back(0,0,0); return c; } if (d == 1) { // This is an optimized sequence of coordinates. - c.emplace_back(0, 1, 0); // Top - c.emplace_back(0, 0, 1); // Back + c.emplace_back(0, 1, 0); // Top + c.emplace_back(0, 0, 1); // Back c.emplace_back(-1, 0, 0); // Left - c.emplace_back(1, 0, 0); // Right - c.emplace_back(0, 0, -1); // Front - c.emplace_back(0, -1, 0); // Bottom + c.emplace_back(1, 0, 0); // Right + c.emplace_back(0, 0,-1); // Front + c.emplace_back(0,-1, 0); // Bottom // 6 - c.emplace_back(-1, 0, 1); // Back left - c.emplace_back(1, 0, 1); // Back right - c.emplace_back(-1, 0, -1); // Front left - c.emplace_back(1, 0, -1); // Front right - c.emplace_back(-1, -1, 0); // Bottom left - c.emplace_back(1, -1, 0); // Bottom right - c.emplace_back(0, -1, 1); // Bottom back - c.emplace_back(0, -1, -1); // Bottom front - c.emplace_back(-1, 1, 0); // Top left - c.emplace_back(1, 1, 0); // Top right - c.emplace_back(0, 1, 1); // Top back - c.emplace_back(0, 1, -1); // Top front + c.emplace_back(-1, 0, 1); // Back left + c.emplace_back(1, 0, 1); // Back right + c.emplace_back(-1, 0,-1); // Front left + c.emplace_back(1, 0,-1); // Front right + c.emplace_back(-1,-1, 0); // Bottom left + c.emplace_back(1,-1, 0); // Bottom right + c.emplace_back(0,-1, 1); // Bottom back + c.emplace_back(0,-1,-1); // Bottom front + c.emplace_back(-1, 1, 0); // Top left + c.emplace_back(1, 1, 0); // Top right + c.emplace_back(0, 1, 1); // Top back + c.emplace_back(0, 1,-1); // Top front // 18 - c.emplace_back(-1, 1, 1); // Top back-left - c.emplace_back(1, 1, 1); // Top back-right - c.emplace_back(-1, 1, -1); // Top front-left - c.emplace_back(1, 1, -1); // Top front-right - c.emplace_back(-1, -1, 1); // Bottom back-left - c.emplace_back(1, -1, 1); // Bottom back-right - c.emplace_back(-1, -1, -1); // Bottom front-left - c.emplace_back(1, -1, -1); // Bottom front-right + c.emplace_back(-1, 1, 1); // Top back-left + c.emplace_back(1, 1, 1); // Top back-right + c.emplace_back(-1, 1,-1); // Top front-left + c.emplace_back(1, 1,-1); // Top front-right + c.emplace_back(-1,-1, 1); // Bottom back-left + c.emplace_back(1,-1, 1); // Bottom back-right + c.emplace_back(-1,-1,-1); // Bottom front-left + c.emplace_back(1,-1,-1); // Bottom front-right // 26 return c; } @@ -79,7 +80,7 @@ const std::vector &FacePositionCache::generateFacePosition(u16 d) // Take blocks in all sides, starting from y=0 and going +-y for (s16 y = 0; y <= d - 1; y++) { // Left and right side, including borders - for (s16 z = -d; z <= d; z++) { + for (s16 z =- d; z <= d; z++) { c.emplace_back(d, y, z); c.emplace_back(-d, y, z); if (y != 0) { @@ -101,9 +102,9 @@ const std::vector &FacePositionCache::generateFacePosition(u16 d) // Take the bottom and top face with borders // -d < x < d, y = +-d, -d < z < d for (s16 x = -d; x <= d; x++) - for (s16 z = -d; z <= d; z++) { - c.emplace_back(x, -d, z); - c.emplace_back(x, d, z); - } + for (s16 z = -d; z <= d; z++) { + c.emplace_back(x, -d, z); + c.emplace_back(x, d, z); + } return c; } diff --git a/src/face_position_cache.h b/src/face_position_cache.h index 0fc7a21e9..36cb06484 100644 --- a/src/face_position_cache.h +++ b/src/face_position_cache.h @@ -30,8 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., * This class permits caching getFacePosition call results. * This reduces CPU usage and vector calls. */ -class FacePositionCache -{ +class FacePositionCache { public: static const std::vector &getFacePositions(u16 d); diff --git a/src/filesys.cpp b/src/filesys.cpp index e09867d89..0bc351669 100644 --- a/src/filesys.cpp +++ b/src/filesys.cpp @@ -57,7 +57,7 @@ std::vector GetDirListing(const std::string &pathstring) dwError = GetLastError(); if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) { errorstream << "GetDirListing: FindFirstFile error." - << " Error is " << dwError << std::endl; + << " Error is " << dwError << std::endl; } } else { // NOTE: @@ -74,9 +74,8 @@ std::vector GetDirListing(const std::string &pathstring) while (FindNextFile(hFind, &FindFileData) != 0) { DirListNode node; node.name = FindFileData.cFileName; - node.dir = FindFileData.dwFileAttributes & - FILE_ATTRIBUTE_DIRECTORY; - if (node.name != "." && node.name != "..") + node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; + if(node.name != "." && node.name != "..") listing.push_back(node); } @@ -84,10 +83,10 @@ std::vector GetDirListing(const std::string &pathstring) FindClose(hFind); if (dwError != ERROR_NO_MORE_FILES) { errorstream << "GetDirListing: FindNextFile error." - << " Error is " << dwError << std::endl; + << " Error is " << dwError << std::endl; listing.clear(); return listing; - } + } } return listing; } @@ -95,9 +94,9 @@ std::vector GetDirListing(const std::string &pathstring) bool CreateDir(const std::string &path) { bool r = CreateDirectory(path.c_str(), NULL); - if (r == true) + if(r == true) return true; - if (GetLastError() == ERROR_ALREADY_EXISTS) + if(GetLastError() == ERROR_ALREADY_EXISTS) return true; return false; } @@ -115,7 +114,8 @@ bool IsPathAbsolute(const std::string &path) bool IsDir(const std::string &path) { DWORD attr = GetFileAttributes(path.c_str()); - return (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY)); + return (attr != INVALID_FILE_ATTRIBUTES && + (attr & FILE_ATTRIBUTE_DIRECTORY)); } bool IsDirDelimiter(char c) @@ -129,27 +129,27 @@ bool RecursiveDelete(const std::string &path) if (!IsDir(path)) { infostream << "RecursiveDelete: Deleting file " << path << std::endl; if (!DeleteFile(path.c_str())) { - errorstream << "RecursiveDelete: Failed to delete file " << path - << std::endl; + errorstream << "RecursiveDelete: Failed to delete file " + << path << std::endl; return false; } return true; } - infostream << "RecursiveDelete: Deleting content of directory " << path - << std::endl; + infostream << "RecursiveDelete: Deleting content of directory " + << path << std::endl; std::vector content = GetDirListing(path); - for (const DirListNode &n : content) { + for (const DirListNode &n: content) { std::string fullpath = path + DIR_DELIM + n.name; if (!RecursiveDelete(fullpath)) { errorstream << "RecursiveDelete: Failed to recurse to " - << fullpath << std::endl; + << fullpath << std::endl; return false; } } infostream << "RecursiveDelete: Deleting directory " << path << std::endl; if (!RemoveDirectory(path.c_str())) { - errorstream << "Failed to recursively delete directory " << path - << std::endl; + errorstream << "Failed to recursively delete directory " + << path << std::endl; return false; } return true; @@ -159,11 +159,14 @@ bool DeleteSingleFileOrEmptyDirectory(const std::string &path) { DWORD attr = GetFileAttributes(path.c_str()); bool is_directory = (attr != INVALID_FILE_ATTRIBUTES && - (attr & FILE_ATTRIBUTE_DIRECTORY)); - if (!is_directory) { + (attr & FILE_ATTRIBUTE_DIRECTORY)); + if(!is_directory) + { bool did = DeleteFile(path.c_str()); return did; - } else { + } + else + { bool did = RemoveDirectory(path.c_str()); return did; } @@ -172,16 +175,14 @@ bool DeleteSingleFileOrEmptyDirectory(const std::string &path) std::string TempPath() { DWORD bufsize = GetTempPath(0, NULL); - if (bufsize == 0) { - errorstream << "GetTempPath failed, error = " << GetLastError() - << std::endl; + if(bufsize == 0){ + errorstream<<"GetTempPath failed, error = "< buf(bufsize); DWORD len = GetTempPath(bufsize, &buf[0]); - if (len == 0 || len > bufsize) { - errorstream << "GetTempPath failed, error = " << GetLastError() - << std::endl; + if(len == 0 || len > bufsize){ + errorstream<<"GetTempPath failed, error = "< GetDirListing(const std::string &pathstring) DIR *dp; struct dirent *dirp; - if ((dp = opendir(pathstring.c_str())) == NULL) { - // infostream<<"Error("< GetDirListing(const std::string &pathstring) // NOTE: // Be very sure to not include '..' in the results, it will // result in an epic failure when deleting stuff. - if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0) + if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0) continue; DirListNode node; @@ -226,7 +227,7 @@ std::vector GetDirListing(const std::string &pathstring) Also we don't know whether symlinks are directories or not. */ #ifdef _DIRENT_HAVE_D_TYPE - if (dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK) + if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK) isdir = (dirp->d_type == DT_DIR); #endif /* _DIRENT_HAVE_D_TYPE */ @@ -234,10 +235,8 @@ std::vector GetDirListing(const std::string &pathstring) Was d_type DT_UNKNOWN, DT_LNK or nonexistent? If so, try stat(). */ - if (isdir == -1) { - struct stat statbuf - { - }; + if(isdir == -1) { + struct stat statbuf{}; if (stat((pathstring + "/" + node.name).c_str(), &statbuf)) continue; isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR); @@ -261,14 +260,13 @@ bool CreateDir(const std::string &path) if (errno == EEXIST) return true; return false; + } bool PathExists(const std::string &path) { - struct stat st - { - }; - return (stat(path.c_str(), &st) == 0); + struct stat st{}; + return (stat(path.c_str(),&st) == 0); } bool IsPathAbsolute(const std::string &path) @@ -278,10 +276,8 @@ bool IsPathAbsolute(const std::string &path) bool IsDir(const std::string &path) { - struct stat statbuf - { - }; - if (stat(path.c_str(), &statbuf)) + struct stat statbuf{}; + if(stat(path.c_str(), &statbuf)) return false; // Actually error; but certainly not a directory return ((statbuf.st_mode & S_IFDIR) == S_IFDIR); } @@ -297,13 +293,14 @@ bool RecursiveDelete(const std::string &path) Execute the 'rm' command directly, by fork() and execve() */ - infostream << "Removing \"" << path << "\"" << std::endl; + infostream<<"Removing \""< &dirs, const std::string &dir) { - static const std::set chars_to_ignore = {'_', '.'}; + static const std::set chars_to_ignore = { '_', '.' }; if (dir.empty() || !IsDir(dir)) return; dirs.push_back(dir); @@ -391,8 +390,10 @@ std::vector GetRecursiveDirs(const std::string &dir) return result; } -void GetRecursiveSubPaths(const std::string &path, std::vector &dst, - bool list_files, const std::set &ignore) +void GetRecursiveSubPaths(const std::string &path, + std::vector &dst, + bool list_files, + const std::set &ignore) { std::vector content = GetDirListing(path); for (const auto &n : content) { @@ -410,11 +411,11 @@ bool DeletePaths(const std::vector &paths) { bool success = true; // Go backwards to succesfully delete the output of GetRecursiveSubPaths - for (int i = paths.size() - 1; i >= 0; i--) { + for(int i=paths.size()-1; i>=0; i--){ const std::string &path = paths[i]; bool did = DeleteSingleFileOrEmptyDirectory(path); - if (!did) { - errorstream << "Failed to delete " << path << std::endl; + if(!did){ + errorstream<<"Failed to delete "< &paths) bool RecursiveDeleteContent(const std::string &path) { - infostream << "Removing content of \"" << path << "\"" << std::endl; + infostream<<"Removing content of \""< list = GetDirListing(path); for (const DirListNode &dln : list) { - if (trim(dln.name) == "." || trim(dln.name) == "..") + if(trim(dln.name) == "." || trim(dln.name) == "..") continue; std::string childpath = path + DIR_DELIM + dln.name; bool r = RecursiveDelete(childpath); - if (!r) { - errorstream << "Removing \"" << childpath << "\" failed" - << std::endl; + if(!r) { + errorstream << "Removing \"" << childpath << "\" failed" << std::endl; return false; } } @@ -444,14 +444,15 @@ bool CreateAllDirs(const std::string &path) std::vector tocreate; std::string basepath = path; - while (!PathExists(basepath)) { + while(!PathExists(basepath)) + { tocreate.push_back(basepath); basepath = RemoveLastPathComponent(basepath); - if (basepath.empty()) + if(basepath.empty()) break; } - for (int i = tocreate.size() - 1; i >= 0; i--) - if (!CreateDir(tocreate[i])) + for(int i=tocreate.size()-1;i>=0;i--) + if(!CreateDir(tocreate[i])) return false; return true; } @@ -459,16 +460,16 @@ bool CreateAllDirs(const std::string &path) bool CopyFileContents(const std::string &source, const std::string &target) { FILE *sourcefile = fopen(source.c_str(), "rb"); - if (sourcefile == NULL) { - errorstream << source << ": can't open for reading: " << strerror(errno) - << std::endl; + if(sourcefile == NULL){ + errorstream< 0) { + if(readbytes > 0){ fwrite(readbuffer, 1, readbytes, targetfile); } - if (feof(sourcefile) || ferror(sourcefile)) { + if(feof(sourcefile) || ferror(sourcefile)){ // flush destination file to catch write errors // (e.g. disk full) fflush(targetfile); done = true; } - if (ferror(targetfile)) { - errorstream << target << ": IO error: " << strerror(errno) - << std::endl; + if(ferror(targetfile)){ + errorstream< 0) pos++; @@ -665,7 +670,7 @@ std::string RemoveRelativePathComponents(std::string path) // remove trailing dir delimiters pos = path.size(); - while (pos != 0 && IsDirDelimiter(path[pos - 1])) + while (pos != 0 && IsDirDelimiter(path[pos-1])) pos--; return path.substr(0, pos); } @@ -677,8 +682,7 @@ std::string AbsolutePath(const std::string &path) #else char *abs_path = realpath(path.c_str(), NULL); #endif - if (!abs_path) - return ""; + if (!abs_path) return ""; std::string abs_path_str(abs_path); free(abs_path); return abs_path_str; @@ -717,10 +721,9 @@ bool safeWriteToFile(const std::string &path, const std::string &content) // Move the finished temporary file over the real file #ifdef _WIN32 - // When creating the file, it can cause Windows Search indexer, virus scanners and - // other apps to query the file. This can make the move file call below fail. We - // retry up to 5 times, with a 1ms sleep between, before we consider the whole - // operation failed + // When creating the file, it can cause Windows Search indexer, virus scanners and other apps + // to query the file. This can make the move file call below fail. + // We retry up to 5 times, with a 1ms sleep between, before we consider the whole operation failed int number_attempts = 0; while (number_attempts < 5) { rename_success = MoveFileEx(tmp_file.c_str(), path.c_str(), @@ -753,3 +756,4 @@ bool Rename(const std::string &from, const std::string &to) } } // namespace fs + diff --git a/src/filesys.h b/src/filesys.h index 41395320c..09f129aa3 100644 --- a/src/filesys.h +++ b/src/filesys.h @@ -80,8 +80,10 @@ std::vector GetRecursiveDirs(const std::string &dir); list files - include files in the list of subpaths. ignore - paths that start with these charcters will not be listed. */ -void GetRecursiveSubPaths(const std::string &path, std::vector &dst, - bool list_files, const std::set &ignore = {}); +void GetRecursiveSubPaths(const std::string &path, + std::vector &dst, + bool list_files, + const std::set &ignore = {}); // Tries to delete all, returns false if any failed bool DeletePaths(const std::vector &paths); @@ -108,8 +110,8 @@ bool PathStartsWith(const std::string &path, const std::string &prefix); // returns "" if there is only one path component. // removed: If non-NULL, receives the removed component(s). // count: Number of components to remove -std::string RemoveLastPathComponent( - const std::string &path, std::string *removed = NULL, int count = 1); +std::string RemoveLastPathComponent(const std::string &path, + std::string *removed = NULL, int count = 1); // Remove "." and ".." path components and for every ".." removed, remove // the last normal path component before it. Unlike AbsolutePath, diff --git a/src/gamedef.h b/src/gamedef.h index 726b9cef4..723404106 100644 --- a/src/gamedef.h +++ b/src/gamedef.h @@ -35,14 +35,10 @@ class Camera; class ModChannel; class ModMetadata; -namespace irr -{ -namespace scene -{ -class IAnimatedMesh; -class ISceneManager; -} -} +namespace irr { namespace scene { + class IAnimatedMesh; + class ISceneManager; +}} struct ModSpec; /* @@ -55,27 +51,27 @@ class IGameDef public: // These are thread-safe IF they are not edited while running threads. // Thus, first they are set up and then they are only read. - virtual IItemDefManager *getItemDefManager() = 0; - virtual IWritableItemDefManager *getWritableItemDefManager() = 0; - virtual const NodeDefManager *getNodeDefManager() = 0; - virtual NodeDefManager *getWritableNodeDefManager() = 0; - virtual ICraftDefManager *getCraftDefManager() = 0; + virtual IItemDefManager* getItemDefManager()=0; + virtual IWritableItemDefManager* getWritableItemDefManager()=0; + virtual const NodeDefManager* getNodeDefManager()=0; + virtual NodeDefManager* getWritableNodeDefManager()=0; + virtual ICraftDefManager* getCraftDefManager()=0; // Used for keeping track of names/ids of unknown nodes - virtual u16 allocateUnknownNodeId(const std::string &name) = 0; + virtual u16 allocateUnknownNodeId(const std::string &name)=0; // Only usable on the server, and NOT thread-safe. It is usable from the // environment thread. - virtual IRollbackManager *getRollbackManager() { return NULL; } + virtual IRollbackManager* getRollbackManager() { return NULL; } // Shorthands - IItemDefManager *idef() { return getItemDefManager(); } - const NodeDefManager *ndef() { return getNodeDefManager(); } - ICraftDefManager *cdef() { return getCraftDefManager(); } + IItemDefManager *idef() { return getItemDefManager(); } + const NodeDefManager *ndef() { return getNodeDefManager(); } + ICraftDefManager *cdef() { return getCraftDefManager(); } IRollbackManager *rollback() { return getRollbackManager(); } virtual const std::vector &getMods() const = 0; - virtual const ModSpec *getModSpec(const std::string &modname) const = 0; + virtual const ModSpec* getModSpec(const std::string &modname) const = 0; virtual std::string getWorldPath() const { return ""; } virtual std::string getModStoragePath() const = 0; virtual bool registerModStorage(ModMetadata *storage) = 0; @@ -83,7 +79,7 @@ class IGameDef virtual bool joinModChannel(const std::string &channel) = 0; virtual bool leaveModChannel(const std::string &channel) = 0; - virtual bool sendModChannelMessage( - const std::string &channel, const std::string &message) = 0; + virtual bool sendModChannelMessage(const std::string &channel, + const std::string &message) = 0; virtual ModChannel *getModChannel(const std::string &channel) = 0; }; diff --git a/src/gettext.cpp b/src/gettext.cpp index 518e3f451..6818004df 100644 --- a/src/gettext.cpp +++ b/src/gettext.cpp @@ -31,32 +31,42 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "filesys.h" -#define setlocale(category, localename) setlocale(category, MSVC_LocaleLookup(localename)) +#define setlocale(category, localename) \ + setlocale(category, MSVC_LocaleLookup(localename)) static std::map glb_supported_locales; /******************************************************************************/ BOOL CALLBACK UpdateLocaleCallback(LPTSTR pStr) { - char *endptr = 0; - int LOCALEID = strtol(pStr, &endptr, 16); + char* endptr = 0; + int LOCALEID = strtol(pStr, &endptr,16); wchar_t buffer[LOCALE_NAME_MAX_LENGTH]; memset(buffer, 0, sizeof(buffer)); - if (GetLocaleInfoW(LOCALEID, LOCALE_SISO639LANGNAME, buffer, - LOCALE_NAME_MAX_LENGTH)) { + if (GetLocaleInfoW( + LOCALEID, + LOCALE_SISO639LANGNAME, + buffer, + LOCALE_NAME_MAX_LENGTH)) { std::wstring name = buffer; memset(buffer, 0, sizeof(buffer)); - GetLocaleInfoW(LOCALEID, LOCALE_SISO3166CTRYNAME, buffer, - LOCALE_NAME_MAX_LENGTH); + GetLocaleInfoW( + LOCALEID, + LOCALE_SISO3166CTRYNAME, + buffer, + LOCALE_NAME_MAX_LENGTH); std::wstring country = buffer; memset(buffer, 0, sizeof(buffer)); - GetLocaleInfoW(LOCALEID, LOCALE_SENGLISHLANGUAGENAME, buffer, - LOCALE_NAME_MAX_LENGTH); + GetLocaleInfoW( + LOCALEID, + LOCALE_SENGLISHLANGUAGENAME, + buffer, + LOCALE_NAME_MAX_LENGTH); std::wstring languagename = buffer; @@ -68,18 +78,14 @@ BOOL CALLBACK UpdateLocaleCallback(LPTSTR pStr) } /******************************************************************************/ -const char *MSVC_LocaleLookup(const char *raw_shortname) -{ +const char* MSVC_LocaleLookup(const char* raw_shortname) { /* NULL is used to read locale only so we need to return it too */ - if (raw_shortname == NULL) - return NULL; + if (raw_shortname == NULL) return NULL; std::string shortname(raw_shortname); - if (shortname == "C") - return "C"; - if (shortname == "") - return ""; + if (shortname == "C") return "C"; + if (shortname == "") return ""; static std::string last_raw_value = ""; static std::string last_full_name = ""; @@ -90,31 +96,29 @@ const char *MSVC_LocaleLookup(const char *raw_shortname) } if (first_use) { - EnumSystemLocalesA(UpdateLocaleCallback, - LCID_SUPPORTED | LCID_ALTERNATE_SORTS); + EnumSystemLocalesA(UpdateLocaleCallback, LCID_SUPPORTED | LCID_ALTERNATE_SORTS); first_use = false; } last_raw_value = shortname; - if (glb_supported_locales.find(utf8_to_wide(shortname)) != - glb_supported_locales.end()) { + if (glb_supported_locales.find(utf8_to_wide(shortname)) != glb_supported_locales.end()) { last_full_name = wide_to_utf8( - glb_supported_locales[utf8_to_wide(shortname)]); + glb_supported_locales[utf8_to_wide(shortname)]); return last_full_name.c_str(); } /* empty string is system default */ errorstream << "MSVC_LocaleLookup: unsupported locale: \"" << shortname - << "\" switching to system default!" << std::endl; + << "\" switching to system default!" << std::endl; return ""; } #endif /******************************************************************************/ -void init_gettext(const char *path, const std::string &configured_language, int argc, - char *argv[]) +void init_gettext(const char *path, const std::string &configured_language, + int argc, char *argv[]) { #if USE_GETTEXT // First, try to set user override environment @@ -138,9 +142,7 @@ void init_gettext(const char *path, const std::string &configured_language, int // Hack to force gettext to see the right environment if (current_language != configured_language) { errorstream << "MSVC localization workaround active. " - "Restarting " PROJECT_NAME_C - " in a new environment!" - << std::endl; + "Restarting " PROJECT_NAME_C " in a new environment!" << std::endl; std::string parameters; @@ -164,10 +166,9 @@ void init_gettext(const char *path, const std::string &configured_language, int STARTUPINFO startup_info = {0}; PROCESS_INFORMATION process_info = {0}; - bool success = CreateProcess(app_name.c_str(), - (char *)ptr_parameters, NULL, NULL, false, - DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT, - NULL, NULL, &startup_info, &process_info); + bool success = CreateProcess(app_name.c_str(), (char *)ptr_parameters, + NULL, NULL, false, DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT, + NULL, NULL, &startup_info, &process_info); if (success) { exit(0); @@ -175,41 +176,33 @@ void init_gettext(const char *path, const std::string &configured_language, int } else { char buffer[1024]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - buffer, sizeof(buffer) - 1, NULL); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), buffer, + sizeof(buffer) - 1, NULL); - errorstream << "*****************************************" - "**************" - << std::endl; + errorstream << "*******************************************************" << std::endl; errorstream << "CMD: " << app_name << std::endl; - errorstream << "Failed to restart with current locale: " - << std::endl; + errorstream << "Failed to restart with current locale: " << std::endl; errorstream << buffer; - errorstream << "Expect language to be broken!" - << std::endl; - errorstream << "*****************************************" - "**************" - << std::endl; + errorstream << "Expect language to be broken!" << std::endl; + errorstream << "*******************************************************" << std::endl; } } #else - errorstream << "*******************************************************" - << std::endl; + errorstream << "*******************************************************" << std::endl; errorstream << "Can't apply locale workaround for server!" << std::endl; errorstream << "Expect language to be broken!" << std::endl; - errorstream << "*******************************************************" - << std::endl; + errorstream << "*******************************************************" << std::endl; #endif setlocale(LC_ALL, configured_language.c_str()); -#else // Mingw +#else // Mingw _putenv(("LANGUAGE=" + configured_language).c_str()); setlocale(LC_ALL, ""); #endif // ifndef _WIN32 - } else { - /* set current system default locale */ + } + else { + /* set current system default locale */ setlocale(LC_ALL, ""); } @@ -225,23 +218,23 @@ void init_gettext(const char *path, const std::string &configured_language, int #endif std::string name = lowercase(PROJECT_NAME); - infostream << "Gettext: domainname=\"" << name << "\" path=\"" << path << "\"" - << std::endl; + infostream << "Gettext: domainname=\"" << name + << "\" path=\"" << path << "\"" << std::endl; bindtextdomain(name.c_str(), path); textdomain(name.c_str()); #if defined(_WIN32) // Set character encoding for Win32 - char *tdomain = textdomain((char *)NULL); - if (tdomain == NULL) { - errorstream << "Warning: domainname parameter is the null pointer" - << ", default domain is not set" << std::endl; - tdomain = (char *)"messages"; + char *tdomain = textdomain( (char *) NULL ); + if( tdomain == NULL ) + { + errorstream << "Warning: domainname parameter is the null pointer" << + ", default domain is not set" << std::endl; + tdomain = (char *) "messages"; } - /* char *codeset = */ bind_textdomain_codeset(tdomain, "UTF-8"); - // errorstream << "Gettext debug: domainname = " << tdomain << "; codeset = "<< - // codeset << std::endl; + /* char *codeset = */bind_textdomain_codeset( tdomain, "UTF-8" ); + //errorstream << "Gettext debug: domainname = " << tdomain << "; codeset = "<< codeset << std::endl; #endif // defined(_WIN32) #else @@ -253,6 +246,6 @@ void init_gettext(const char *path, const std::string &configured_language, int /* to ensure formspec parameters are evaluated correct! */ setlocale(LC_NUMERIC, "C"); - infostream << "Message locale is now set to: " << setlocale(LC_ALL, 0) - << std::endl; + infostream << "Message locale is now set to: " + << setlocale(LC_ALL, 0) << std::endl; } diff --git a/src/gettext.h b/src/gettext.h index b3f571afb..42b375d86 100644 --- a/src/gettext.h +++ b/src/gettext.h @@ -23,27 +23,27 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #if USE_GETTEXT -#include + #include #else -// In certain environments, some standard headers like -// and include libintl.h. If libintl.h is included after -// we define our gettext macro below, this causes a syntax error -// at the declaration of the gettext function in libintl.h. -// Fix this by including such a header before defining the macro. -// See issue #4446. -// Note that we can't include libintl.h directly since we're in -// the USE_GETTEXT=0 case and can't assume that gettext is installed. -#include - -#define gettext(String) String + // In certain environments, some standard headers like + // and include libintl.h. If libintl.h is included after + // we define our gettext macro below, this causes a syntax error + // at the declaration of the gettext function in libintl.h. + // Fix this by including such a header before defining the macro. + // See issue #4446. + // Note that we can't include libintl.h directly since we're in + // the USE_GETTEXT=0 case and can't assume that gettext is installed. + #include + + #define gettext(String) String #endif #define _(String) gettext(String) #define gettext_noop(String) (String) #define N_(String) gettext_noop((String)) -void init_gettext(const char *path, const std::string &configured_language, int argc, - char *argv[]); +void init_gettext(const char *path, const std::string &configured_language, + int argc, char *argv[]); extern wchar_t *utf8_to_wide_c(const char *str); diff --git a/src/gui/StyleSpec.h b/src/gui/StyleSpec.h index aae2d46f8..67caf4f7b 100644 --- a/src/gui/StyleSpec.h +++ b/src/gui/StyleSpec.h @@ -138,7 +138,10 @@ class StyleSpec } //! Gets the state that this style is intended for - State getState() const { return state_map; } + State getState() const + { + return state_map; + } //! Set the given state on this style void addState(State state) @@ -150,8 +153,7 @@ class StyleSpec //! Using a list of styles mapped to state values, calculate the final // combined style for a state by propagating values in its component states - static StyleSpec getStyleFromStatePropagation( - const std::array &styles, State state) + static StyleSpec getStyleFromStatePropagation(const std::array &styles, State state) { StyleSpec temp = styles[StyleSpec::STATE_DEFAULT]; temp.state_map = state; @@ -208,8 +210,7 @@ class StyleSpec return rect; } - irr::core::vector2d getVector2i( - Property prop, irr::core::vector2d def) const + irr::core::vector2d getVector2i(Property prop, irr::core::vector2d def) const { const auto &val = properties[prop]; if (val.empty()) @@ -259,13 +260,10 @@ class StyleSpec int calc_size = 1; if (size[0] == '*') { - std::string new_size = size.substr( - 1); // Remove '*' (invalid for stof) - calc_size = stof(new_size) * - g_fontengine->getFontSize(spec.mode); + std::string new_size = size.substr(1); // Remove '*' (invalid for stof) + calc_size = stof(new_size) * g_fontengine->getFontSize(spec.mode); } else if (size[0] == '+' || size[0] == '-') { - calc_size = stoi(size) + - g_fontengine->getFontSize(spec.mode); + calc_size = stoi(size) + g_fontengine->getFontSize(spec.mode); } else { calc_size = stoi(size); } @@ -347,7 +345,7 @@ class StyleSpec rect.LowerRightCorner = irr::core::vector2di(-x, -x); } else if (v_rect.size() == 2) { s32 x = stoi(v_rect[0]); - s32 y = stoi(v_rect[1]); + s32 y = stoi(v_rect[1]); rect.UpperLeftCorner = irr::core::vector2di(x, y); rect.LowerRightCorner = irr::core::vector2di(-x, -y); // `-x` is interpreted as `w - x` @@ -358,7 +356,7 @@ class StyleSpec stoi(v_rect[2]), stoi(v_rect[3])); } else { warningstream << "Invalid rectangle string format: \"" << value - << "\"" << std::endl; + << "\"" << std::endl; return false; } @@ -367,8 +365,7 @@ class StyleSpec return true; } - bool parseVector2i(const std::string &value, - irr::core::vector2d *parsed_vec) const + bool parseVector2i(const std::string &value, irr::core::vector2d *parsed_vec) const { irr::core::vector2d vec; std::vector v_vector = split(value, ','); @@ -379,12 +376,12 @@ class StyleSpec vec.Y = x; } else if (v_vector.size() == 2) { s32 x = stoi(v_vector[0]); - s32 y = stoi(v_vector[1]); + s32 y = stoi(v_vector[1]); vec.X = x; vec.Y = y; } else { warningstream << "Invalid vector2d string format: \"" << value - << "\"" << std::endl; + << "\"" << std::endl; return false; } diff --git a/src/gui/cheatMenu.cpp b/src/gui/cheatMenu.cpp index d441e8dfc..e66fbc250 100644 --- a/src/gui/cheatMenu.cpp +++ b/src/gui/cheatMenu.cpp @@ -23,9 +23,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cheatMenu.h" #include -FontMode CheatMenu::fontStringToEnum(std::string str) -{ - if (str == "FM_Standard") +FontMode CheatMenu::fontStringToEnum(std::string str) { + if (str == "FM_Standard") return FM_Standard; else if (str == "FM_Mono") return FM_Mono; @@ -53,21 +52,18 @@ CheatMenu::CheatMenu(Client *client) : m_client(client) font_color = g_settings->getV3F("cheat_menu_font_color"); selected_font_color = g_settings->getV3F("cheat_menu_selected_font_color"); - m_bg_color = video::SColor(g_settings->getU32("cheat_menu_bg_color_alpha"), - bg_color.X, bg_color.Y, bg_color.Z); - - m_active_bg_color = video::SColor( - g_settings->getU32("cheat_menu_active_bg_color_alpha"), - active_bg_color.X, active_bg_color.Y, active_bg_color.Z); + m_bg_color = video::SColor(g_settings->getU32("cheat_menu_bg_color_alpha"), + bg_color.X, bg_color.Y, bg_color.Z); + + m_active_bg_color = video::SColor(g_settings->getU32("cheat_menu_active_bg_color_alpha"), + active_bg_color.X, active_bg_color.Y, active_bg_color.Z); m_font_color = video::SColor(g_settings->getU32("cheat_menu_font_color_alpha"), - font_color.X, font_color.Y, font_color.Z); - - m_selected_font_color = video::SColor( - g_settings->getU32("cheat_menu_selected_font_color_alpha"), - selected_font_color.X, selected_font_color.Y, - selected_font_color.Z); + font_color.X, font_color.Y, font_color.Z); + m_selected_font_color = video::SColor(g_settings->getU32("cheat_menu_selected_font_color_alpha"), + selected_font_color.X, selected_font_color.Y, selected_font_color.Z); + m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, fontMode); if (!m_font) { @@ -141,73 +137,64 @@ void CheatMenu::draw(video::IVideoDriver *driver, bool show_debug) void CheatMenu::drawHUD(video::IVideoDriver *driver, double dtime) { CHEAT_MENU_GET_SCRIPTPTR - + m_rainbow_offset += dtime; m_rainbow_offset = fmod(m_rainbow_offset, 6.0f); - + std::vector enabled_cheats; - + int cheat_count = 0; - - for (auto category = script->m_cheat_categories.begin(); - category != script->m_cheat_categories.end(); category++) { - for (auto cheat = (*category)->m_cheats.begin(); - cheat != (*category)->m_cheats.end(); cheat++) { + + for (auto category = script->m_cheat_categories.begin(); category != script->m_cheat_categories.end(); category++) { + for (auto cheat = (*category)->m_cheats.begin(); cheat != (*category)->m_cheats.end(); cheat++) { if ((*cheat)->is_enabled()) { enabled_cheats.push_back((*cheat)->m_name); cheat_count++; } } } - + if (enabled_cheats.empty()) return; - + std::vector colors; - + for (int i = 0; i < cheat_count; i++) { video::SColor color; f32 h = (f32)i * 2.0f / (f32)cheat_count - m_rainbow_offset; if (h < 0) h = 6.0f + h; f32 x = (1 - fabs(fmod(h, 2.0f) - 1.0f)) * 255.0f; - switch ((int)h) { + switch((int)h) { case 0: - color = video::SColor(255, 255, x, 0); - break; + color = video::SColor(255, 255, x, 0); break; case 1: - color = video::SColor(255, x, 255, 0); - break; + color = video::SColor(255, x, 255, 0); break; case 2: - color = video::SColor(255, 0, 255, x); - break; + color = video::SColor(255, 0, 255, x); break; case 3: - color = video::SColor(255, 0, x, 255); - break; + color = video::SColor(255, 0, x, 255); break; case 4: - color = video::SColor(255, x, 0, 255); - break; + color = video::SColor(255, x, 0, 255); break; case 5: - color = video::SColor(255, 255, 0, x); - break; + color = video::SColor(255, 255, 0, x); break; } colors.push_back(color); } - + core::dimension2d screensize = driver->getScreenSize(); - + u32 y = 5; - + int i = 0; for (std::string cheat : enabled_cheats) { - core::dimension2d dim = - m_font->getDimension(utf8_to_wide(cheat).c_str()); + core::dimension2d dim = m_font->getDimension(utf8_to_wide(cheat).c_str()); u32 x = screensize.Width - 5 - dim.Width; - + core::rect fontbounds(x, y, x + dim.Width, y + dim.Height); m_font->draw(cheat.c_str(), fontbounds, colors[i], false, false); - + y += dim.Height; i++; } diff --git a/src/gui/cheatMenu.h b/src/gui/cheatMenu.h index b15858a48..8be73c483 100644 --- a/src/gui/cheatMenu.h +++ b/src/gui/cheatMenu.h @@ -42,15 +42,18 @@ class CheatMenu public: CheatMenu(Client *client); - ClientScripting *getScript() { return m_client->getScript(); } + ClientScripting *getScript() + { + return m_client->getScript(); + } void draw(video::IVideoDriver *driver, bool show_debug); - + void drawHUD(video::IVideoDriver *driver, double dtime); void drawEntry(video::IVideoDriver *driver, std::string name, int number, - bool selected, bool active, - CheatMenuEntryType entry_type = CHEAT_MENU_ENTRY_TYPE_ENTRY); + bool selected, bool active, + CheatMenuEntryType entry_type = CHEAT_MENU_ENTRY_TYPE_ENTRY); void selectUp(); void selectDown(); @@ -79,6 +82,6 @@ class CheatMenu gui::IGUIFont *m_font = nullptr; v2u32 m_fontsize; - + float m_rainbow_offset = 0.0; }; diff --git a/src/gui/guiAnimatedImage.cpp b/src/gui/guiAnimatedImage.cpp index d8648111f..b1447c45f 100644 --- a/src/gui/guiAnimatedImage.cpp +++ b/src/gui/guiAnimatedImage.cpp @@ -9,14 +9,13 @@ #include GUIAnimatedImage::GUIAnimatedImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, const core::rect &rectangle, const std::string &texture_name, - s32 frame_count, s32 frame_duration, ISimpleTextureSource *tsrc) : - gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), - m_tsrc(tsrc) + s32 id, const core::rect &rectangle, const std::string &texture_name, + s32 frame_count, s32 frame_duration, ISimpleTextureSource *tsrc) : + gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), m_tsrc(tsrc) { m_texture = m_tsrc->getTexture(texture_name); - m_frame_count = std::max(frame_count, 1); + m_frame_count = std::max(frame_count, 1); m_frame_duration = std::max(frame_duration, 0); if (m_texture != nullptr) { @@ -42,10 +41,8 @@ void GUIAnimatedImage::draw() size.Height /= m_frame_count; draw2DImageFilterScaled(driver, m_texture, AbsoluteRect, - core::rect(core::position2d(0, - size.Height * m_frame_idx), - size), - NoClip ? nullptr : &AbsoluteClippingRect, colors, true); + core::rect(core::position2d(0, size.Height * m_frame_idx), size), + NoClip ? nullptr : &AbsoluteClippingRect, colors, true); } // Step the animation @@ -67,6 +64,7 @@ void GUIAnimatedImage::draw() } } + void GUIAnimatedImage::setFrameIndex(s32 frame) { s32 idx = std::max(frame, 0); diff --git a/src/gui/guiAnimatedImage.h b/src/gui/guiAnimatedImage.h index c814f609c..f8e6a506e 100644 --- a/src/gui/guiAnimatedImage.h +++ b/src/gui/guiAnimatedImage.h @@ -5,12 +5,11 @@ class ISimpleTextureSource; -class GUIAnimatedImage : public gui::IGUIElement -{ +class GUIAnimatedImage : public gui::IGUIElement { public: - GUIAnimatedImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, const std::string &texture_name, - s32 frame_count, s32 frame_duration, ISimpleTextureSource *tsrc); + GUIAnimatedImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, + s32 id, const core::rect &rectangle, const std::string &texture_name, + s32 frame_count, s32 frame_duration, ISimpleTextureSource *tsrc); virtual void draw() override; diff --git a/src/gui/guiBackgroundImage.cpp b/src/gui/guiBackgroundImage.cpp index 6b9559087..21c1e88cf 100644 --- a/src/gui/guiBackgroundImage.cpp +++ b/src/gui/guiBackgroundImage.cpp @@ -20,11 +20,11 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "log.h" GUIBackgroundImage::GUIBackgroundImage(gui::IGUIEnvironment *env, - gui::IGUIElement *parent, s32 id, const core::rect &rectangle, - const std::string &name, const core::rect &middle, - ISimpleTextureSource *tsrc, bool autoclip) : - gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), - m_name(name), m_middle(middle), m_tsrc(tsrc), m_autoclip(autoclip) + gui::IGUIElement *parent, s32 id, const core::rect &rectangle, + const std::string &name, const core::rect &middle, + ISimpleTextureSource *tsrc, bool autoclip) : + gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), + m_name(name), m_middle(middle), m_tsrc(tsrc), m_autoclip(autoclip) { } @@ -37,7 +37,7 @@ void GUIBackgroundImage::draw() if (!texture) { errorstream << "GUIBackgroundImage::draw() Unable to load texture:" - << std::endl; + << std::endl; errorstream << "\t" << m_name << std::endl; return; } @@ -53,8 +53,7 @@ void GUIBackgroundImage::draw() const video::SColor colors[] = {color, color, color, color}; draw2DImageFilterScaled(driver, texture, rect, core::rect(core::position2d(0, 0), - core::dimension2di( - texture->getOriginalSize())), + core::dimension2di(texture->getOriginalSize())), nullptr, colors, true); } else { core::rect middle = m_middle; diff --git a/src/gui/guiBackgroundImage.h b/src/gui/guiBackgroundImage.h index 5c8ca690d..31fbfd09c 100644 --- a/src/gui/guiBackgroundImage.h +++ b/src/gui/guiBackgroundImage.h @@ -25,9 +25,8 @@ class GUIBackgroundImage : public gui::IGUIElement { public: GUIBackgroundImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, const std::string &name, - const core::rect &middle, ISimpleTextureSource *tsrc, - bool autoclip); + const core::rect &rectangle, const std::string &name, + const core::rect &middle, ISimpleTextureSource *tsrc, bool autoclip); virtual void draw() override; diff --git a/src/gui/guiBox.cpp b/src/gui/guiBox.cpp index 23551a7c7..7f329cc32 100644 --- a/src/gui/guiBox.cpp +++ b/src/gui/guiBox.cpp @@ -20,9 +20,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiBox.h" GUIBox::GUIBox(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, const video::SColor &color) : - gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), - m_color(color) + const core::rect &rectangle, const video::SColor &color) : + gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), + m_color(color) { } @@ -31,8 +31,8 @@ void GUIBox::draw() if (!IsVisible) return; - Environment->getVideoDriver()->draw2DRectangle( - m_color, AbsoluteRect, &AbsoluteClippingRect); + Environment->getVideoDriver()->draw2DRectangle(m_color, AbsoluteRect, + &AbsoluteClippingRect); IGUIElement::draw(); } diff --git a/src/gui/guiBox.h b/src/gui/guiBox.h index 2367e43e3..5306fdf65 100644 --- a/src/gui/guiBox.h +++ b/src/gui/guiBox.h @@ -25,7 +25,7 @@ class GUIBox : public gui::IGUIElement { public: GUIBox(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, const video::SColor &color); + const core::rect &rectangle, const video::SColor &color); virtual void draw() override; diff --git a/src/gui/guiButton.cpp b/src/gui/guiButton.cpp index 2fb7659d7..e0d6337cd 100644 --- a/src/gui/guiButton.cpp +++ b/src/gui/guiButton.cpp @@ -4,6 +4,7 @@ #include "guiButton.h" + #include "client/guiscalingfilter.h" #include "client/tile.h" #include "IGUISkin.h" @@ -25,14 +26,16 @@ using namespace gui; #define COLOR_PRESSED_MOD 0.85f //! constructor -GUIButton::GUIButton(IGUIEnvironment *environment, IGUIElement *parent, s32 id, - core::rect rectangle, ISimpleTextureSource *tsrc, bool noclip) : - IGUIButton(environment, parent, id, rectangle), - SpriteBank(0), OverrideFont(0), OverrideColorEnabled(false), - OverrideColor(video::SColor(101, 255, 255, 255)), ClickTime(0), - HoverTime(0), FocusTime(0), ClickShiftState(false), - ClickControlState(false), IsPushButton(false), Pressed(false), - UseAlphaChannel(false), DrawBorder(true), ScaleImage(false), TSrc(tsrc) +GUIButton::GUIButton(IGUIEnvironment* environment, IGUIElement* parent, + s32 id, core::rect rectangle, ISimpleTextureSource *tsrc, + bool noclip) +: IGUIButton(environment, parent, id, rectangle), + SpriteBank(0), OverrideFont(0), + OverrideColorEnabled(false), OverrideColor(video::SColor(101,255,255,255)), + ClickTime(0), HoverTime(0), FocusTime(0), + ClickShiftState(false), ClickControlState(false), + IsPushButton(false), Pressed(false), + UseAlphaChannel(false), DrawBorder(true), ScaleImage(false), TSrc(tsrc) { setNotClipped(noclip); @@ -44,10 +47,7 @@ GUIButton::GUIButton(IGUIEnvironment *environment, IGUIElement *parent, s32 id, for (size_t i = 0; i < 4; i++) { Colors[i] = Environment->getSkin()->getColor((EGUI_DEFAULT_COLOR)i); } - StaticText = gui::StaticText::add(Environment, Text.c_str(), - core::rect(0, 0, rectangle.getWidth(), - rectangle.getHeight()), - false, false, this, id); + StaticText = gui::StaticText::add(Environment, Text.c_str(), core::rect(0,0,rectangle.getWidth(),rectangle.getHeight()), false, false, this, id); StaticText->setTextAlignment(EGUIA_CENTER, EGUIA_CENTER); // END PATCH } @@ -62,25 +62,29 @@ GUIButton::~GUIButton() SpriteBank->drop(); } + //! Sets if the images should be scaled to fit the button void GUIButton::setScaleImage(bool scaleImage) { ScaleImage = scaleImage; } + //! Returns whether the button scale the used images bool GUIButton::isScalingImage() const { return ScaleImage; } + //! Sets if the button should use the skin to draw its border void GUIButton::setDrawBorder(bool border) { DrawBorder = border; } -void GUIButton::setSpriteBank(IGUISpriteBank *sprites) + +void GUIButton::setSpriteBank(IGUISpriteBank* sprites) { if (sprites) sprites->grab(); @@ -91,12 +95,11 @@ void GUIButton::setSpriteBank(IGUISpriteBank *sprites) SpriteBank = sprites; } -void GUIButton::setSprite(EGUI_BUTTON_STATE state, s32 index, video::SColor color, - bool loop, bool scale) +void GUIButton::setSprite(EGUI_BUTTON_STATE state, s32 index, video::SColor color, bool loop, bool scale) { - ButtonSprites[(u32)state].Index = index; - ButtonSprites[(u32)state].Color = color; - ButtonSprites[(u32)state].Loop = loop; + ButtonSprites[(u32)state].Index = index; + ButtonSprites[(u32)state].Color = color; + ButtonSprites[(u32)state].Loop = loop; ButtonSprites[(u32)state].Scale = scale; } @@ -125,16 +128,17 @@ bool GUIButton::getSpriteScale(EGUI_BUTTON_STATE state) const } //! called if an event happened. -bool GUIButton::OnEvent(const SEvent &event) +bool GUIButton::OnEvent(const SEvent& event) { if (!isEnabled()) return IGUIElement::OnEvent(event); - switch (event.EventType) { + switch(event.EventType) + { case EET_KEY_INPUT_EVENT: if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_RETURN || - event.KeyInput.Key == KEY_SPACE)) { + (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) + { if (!IsPushButton) setPressed(true); else @@ -142,18 +146,21 @@ bool GUIButton::OnEvent(const SEvent &event) return true; } - if (Pressed && !IsPushButton && event.KeyInput.PressedDown && - event.KeyInput.Key == KEY_ESCAPE) { + if (Pressed && !IsPushButton && event.KeyInput.PressedDown && event.KeyInput.Key == KEY_ESCAPE) + { setPressed(false); return true; - } else if (!event.KeyInput.PressedDown && Pressed && - (event.KeyInput.Key == KEY_RETURN || - event.KeyInput.Key == KEY_SPACE)) { + } + else + if (!event.KeyInput.PressedDown && Pressed && + (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) + { if (!IsPushButton) setPressed(false); - if (Parent) { + if (Parent) + { ClickShiftState = event.KeyInput.Shift; ClickControlState = event.KeyInput.Control; @@ -168,37 +175,43 @@ bool GUIButton::OnEvent(const SEvent &event) } break; case EET_GUI_EVENT: - if (event.GUIEvent.Caller == this) { - if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { + if (event.GUIEvent.Caller == this) + { + if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) + { if (!IsPushButton) setPressed(false); FocusTime = (u32)porting::getTimeMs(); - } else if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED) { + } + else if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED) + { FocusTime = (u32)porting::getTimeMs(); - } else if (event.GUIEvent.EventType == EGET_ELEMENT_HOVERED || - event.GUIEvent.EventType == EGET_ELEMENT_LEFT) { + } + else if (event.GUIEvent.EventType == EGET_ELEMENT_HOVERED || event.GUIEvent.EventType == EGET_ELEMENT_LEFT) + { HoverTime = (u32)porting::getTimeMs(); } } break; case EET_MOUSE_INPUT_EVENT: - if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { + if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) + { // Sometimes formspec elements can receive mouse events when the - // mouse is outside of the formspec. Thus, we test the position - // here. - if (!IsPushButton && - AbsoluteClippingRect.isPointInside(core::position2d< - s32>(event.MouseInput.X, - event.MouseInput.Y))) { + // mouse is outside of the formspec. Thus, we test the position here. + if ( !IsPushButton && AbsoluteClippingRect.isPointInside( + core::position2d(event.MouseInput.X, event.MouseInput.Y ))) { setPressed(true); } return true; - } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { + } + else + if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) + { bool wasPressed = Pressed; - if (!AbsoluteClippingRect.isPointInside(core::position2d( - event.MouseInput.X, event.MouseInput.Y))) { + if ( !AbsoluteClippingRect.isPointInside( core::position2d(event.MouseInput.X, event.MouseInput.Y ) ) ) + { if (!IsPushButton) setPressed(false); return true; @@ -206,12 +219,14 @@ bool GUIButton::OnEvent(const SEvent &event) if (!IsPushButton) setPressed(false); - else { + else + { setPressed(!Pressed); } if ((!IsPushButton && wasPressed && Parent) || - (IsPushButton && wasPressed != Pressed)) { + (IsPushButton && wasPressed != Pressed)) + { ClickShiftState = event.MouseInput.Shift; ClickControlState = event.MouseInput.Control; @@ -233,6 +248,7 @@ bool GUIButton::OnEvent(const SEvent &event) return Parent ? Parent->OnEvent(event) : false; } + //! draws the element and its children void GUIButton::draw() { @@ -247,17 +263,21 @@ void GUIButton::draw() setFromState(); } - GUISkin *skin = dynamic_cast(Environment->getSkin()); - video::IVideoDriver *driver = Environment->getVideoDriver(); + GUISkin* skin = dynamic_cast(Environment->getSkin()); + video::IVideoDriver* driver = Environment->getVideoDriver(); // END PATCH - if (DrawBorder) { - if (!Pressed) { + if (DrawBorder) + { + if (!Pressed) + { // PATCH skin->drawColored3DButtonPaneStandard(this, AbsoluteRect, &AbsoluteClippingRect, Colors); // END PATCH - } else { + } + else + { // PATCH skin->drawColored3DButtonPanePressed(this, AbsoluteRect, &AbsoluteClippingRect, Colors); @@ -270,108 +290,94 @@ void GUIButton::draw() // The image changes based on the state, so we use the default every time. EGUI_BUTTON_IMAGE_STATE imageState = EGBIS_IMAGE_UP; // END PATCH - if (ButtonImages[(u32)imageState].Texture) { + if ( ButtonImages[(u32)imageState].Texture ) + { core::position2d pos(buttonCenter); core::rect sourceRect(ButtonImages[(u32)imageState].SourceRect); - if (sourceRect.getWidth() == 0 && sourceRect.getHeight() == 0) - sourceRect = core::rect(core::position2di(0, 0), - ButtonImages[(u32)imageState] - .Texture->getOriginalSize()); + if ( sourceRect.getWidth() == 0 && sourceRect.getHeight() == 0 ) + sourceRect = core::rect(core::position2di(0,0), ButtonImages[(u32)imageState].Texture->getOriginalSize()); pos.X -= sourceRect.getWidth() / 2; pos.Y -= sourceRect.getHeight() / 2; - if (Pressed) { - // Create a pressed-down effect by moving the image when it looks - // identical to the unpressed state image + if ( Pressed ) + { + // Create a pressed-down effect by moving the image when it looks identical to the unpressed state image EGUI_BUTTON_IMAGE_STATE unpressedState = getImageState(false); - if (unpressedState == imageState || - ButtonImages[(u32)imageState] == - ButtonImages[(u32)unpressedState]) { - pos.X += skin->getSize( - EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X); - pos.Y += skin->getSize( - EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y); + if ( unpressedState == imageState || ButtonImages[(u32)imageState] == ButtonImages[(u32)unpressedState] ) + { + pos.X += skin->getSize(EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X); + pos.Y += skin->getSize(EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y); } } // PATCH - video::ITexture *texture = ButtonImages[(u32)imageState].Texture; + video::ITexture* texture = ButtonImages[(u32)imageState].Texture; if (BgMiddle.getArea() == 0) { driver->draw2DImage(texture, - ScaleImage ? AbsoluteRect - : core::rect(pos, - sourceRect.getSize()), - sourceRect, &AbsoluteClippingRect, 0, - UseAlphaChannel); + ScaleImage? AbsoluteRect : core::rect(pos, sourceRect.getSize()), + sourceRect, &AbsoluteClippingRect, + 0, UseAlphaChannel); } else { core::rect middle = BgMiddle; // `-x` is interpreted as `w - x` if (middle.LowerRightCorner.X < 0) - middle.LowerRightCorner.X += - texture->getOriginalSize().Width; + middle.LowerRightCorner.X += texture->getOriginalSize().Width; if (middle.LowerRightCorner.Y < 0) - middle.LowerRightCorner.Y += - texture->getOriginalSize().Height; + middle.LowerRightCorner.Y += texture->getOriginalSize().Height; draw2DImage9Slice(driver, texture, - ScaleImage ? AbsoluteRect - : core::rect(pos, - sourceRect.getSize()), + ScaleImage ? AbsoluteRect : core::rect(pos, sourceRect.getSize()), middle, &AbsoluteClippingRect); } // END PATCH } - if (SpriteBank) { + if (SpriteBank) + { core::position2di pos(buttonCenter); - if (isEnabled()) { + if (isEnabled()) + { // pressed / unpressed animation - EGUI_BUTTON_STATE state = - Pressed ? EGBS_BUTTON_DOWN : EGBS_BUTTON_UP; + EGUI_BUTTON_STATE state = Pressed ? EGBS_BUTTON_DOWN : EGBS_BUTTON_UP; drawSprite(state, ClickTime, pos); // focused / unfocused animation - state = Environment->hasFocus(this) ? EGBS_BUTTON_FOCUSED - : EGBS_BUTTON_NOT_FOCUSED; + state = Environment->hasFocus(this) ? EGBS_BUTTON_FOCUSED : EGBS_BUTTON_NOT_FOCUSED; drawSprite(state, FocusTime, pos); // mouse over / off animation - state = isHovered() ? EGBS_BUTTON_MOUSE_OVER - : EGBS_BUTTON_MOUSE_OFF; + state = isHovered() ? EGBS_BUTTON_MOUSE_OVER : EGBS_BUTTON_MOUSE_OFF; drawSprite(state, HoverTime, pos); - } else { + } + else + { // draw disabled - // drawSprite(EGBS_BUTTON_DISABLED, 0, pos); +// drawSprite(EGBS_BUTTON_DISABLED, 0, pos); } } IGUIElement::draw(); } -void GUIButton::drawSprite( - EGUI_BUTTON_STATE state, u32 startTime, const core::position2di ¢er) +void GUIButton::drawSprite(EGUI_BUTTON_STATE state, u32 startTime, const core::position2di& center) { u32 stateIdx = (u32)state; - if (ButtonSprites[stateIdx].Index != -1) { - if (ButtonSprites[stateIdx].Scale) { - const video::SColor colors[] = {ButtonSprites[stateIdx].Color, - ButtonSprites[stateIdx].Color, - ButtonSprites[stateIdx].Color, - ButtonSprites[stateIdx].Color}; - SpriteBank->draw2DSprite(ButtonSprites[stateIdx].Index, - AbsoluteRect.UpperLeftCorner, - &AbsoluteClippingRect, - colors[0], // FIXME: remove [0] - porting::getTimeMs() - startTime, - ButtonSprites[stateIdx].Loop); - } else { + if (ButtonSprites[stateIdx].Index != -1) + { + if ( ButtonSprites[stateIdx].Scale ) + { + const video::SColor colors[] = {ButtonSprites[stateIdx].Color,ButtonSprites[stateIdx].Color,ButtonSprites[stateIdx].Color,ButtonSprites[stateIdx].Color}; + SpriteBank->draw2DSprite(ButtonSprites[stateIdx].Index, AbsoluteRect.UpperLeftCorner, + &AbsoluteClippingRect, colors[0], // FIXME: remove [0] + porting::getTimeMs()-startTime, ButtonSprites[stateIdx].Loop); + } + else + { SpriteBank->draw2DSprite(ButtonSprites[stateIdx].Index, center, - &AbsoluteClippingRect, - ButtonSprites[stateIdx].Color, startTime, - porting::getTimeMs(), - ButtonSprites[stateIdx].Loop, true); + &AbsoluteClippingRect, ButtonSprites[stateIdx].Color, startTime, porting::getTimeMs(), + ButtonSprites[stateIdx].Loop, true); } } } @@ -383,30 +389,32 @@ EGUI_BUTTON_IMAGE_STATE GUIButton::getImageState(bool pressed) const // END PATCH } -EGUI_BUTTON_IMAGE_STATE GUIButton::getImageState( - bool pressed, const ButtonImage *images) const +EGUI_BUTTON_IMAGE_STATE GUIButton::getImageState(bool pressed, const ButtonImage* images) const { // figure state we should have EGUI_BUTTON_IMAGE_STATE state = EGBIS_IMAGE_DISABLED; - bool focused = Environment->hasFocus((IGUIElement *)this); + bool focused = Environment->hasFocus((IGUIElement*)this); bool mouseOver = isHovered(); - if (isEnabled()) { - if (pressed) { - if (focused && mouseOver) + if (isEnabled()) + { + if ( pressed ) + { + if ( focused && mouseOver ) state = EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER; - else if (focused) + else if ( focused ) state = EGBIS_IMAGE_DOWN_FOCUSED; - else if (mouseOver) + else if ( mouseOver ) state = EGBIS_IMAGE_DOWN_MOUSEOVER; else state = EGBIS_IMAGE_DOWN; - } else // !pressed + } + else // !pressed { - if (focused && mouseOver) + if ( focused && mouseOver ) state = EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER; - else if (focused) + else if ( focused ) state = EGBIS_IMAGE_UP_FOCUSED; - else if (mouseOver) + else if ( mouseOver ) state = EGBIS_IMAGE_UP_MOUSEOVER; else state = EGBIS_IMAGE_UP; @@ -414,32 +422,34 @@ EGUI_BUTTON_IMAGE_STATE GUIButton::getImageState( } // find a compatible state that has images - while (state != EGBIS_IMAGE_UP && !images[(u32)state].Texture) { + while ( state != EGBIS_IMAGE_UP && !images[(u32)state].Texture ) + { // PATCH - switch (state) { - case EGBIS_IMAGE_UP_FOCUSED: - state = EGBIS_IMAGE_UP; - break; - case EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER: - state = EGBIS_IMAGE_UP_FOCUSED; - break; - case EGBIS_IMAGE_DOWN_MOUSEOVER: - state = EGBIS_IMAGE_DOWN; - break; - case EGBIS_IMAGE_DOWN_FOCUSED: - state = EGBIS_IMAGE_DOWN; - break; - case EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER: - state = EGBIS_IMAGE_DOWN_FOCUSED; - break; - case EGBIS_IMAGE_DISABLED: - if (pressed) + switch ( state ) + { + case EGBIS_IMAGE_UP_FOCUSED: + state = EGBIS_IMAGE_UP; + break; + case EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER: + state = EGBIS_IMAGE_UP_FOCUSED; + break; + case EGBIS_IMAGE_DOWN_MOUSEOVER: state = EGBIS_IMAGE_DOWN; - else + break; + case EGBIS_IMAGE_DOWN_FOCUSED: + state = EGBIS_IMAGE_DOWN; + break; + case EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER: + state = EGBIS_IMAGE_DOWN_FOCUSED; + break; + case EGBIS_IMAGE_DISABLED: + if ( pressed ) + state = EGBIS_IMAGE_DOWN; + else + state = EGBIS_IMAGE_UP; + break; + default: state = EGBIS_IMAGE_UP; - break; - default: - state = EGBIS_IMAGE_UP; } // END PATCH } @@ -447,9 +457,8 @@ EGUI_BUTTON_IMAGE_STATE GUIButton::getImageState( return state; } -//! sets another skin independent font. if this is set to zero, the button uses the font -//! of the skin. -void GUIButton::setOverrideFont(IGUIFont *font) +//! sets another skin independent font. if this is set to zero, the button uses the font of the skin. +void GUIButton::setOverrideFont(IGUIFont* font) { if (OverrideFont == font) return; @@ -466,17 +475,17 @@ void GUIButton::setOverrideFont(IGUIFont *font) } //! Gets the override font (if any) -IGUIFont *GUIButton::getOverrideFont() const +IGUIFont * GUIButton::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing -IGUIFont *GUIButton::getActiveFont() const +IGUIFont* GUIButton::getActiveFont() const { - if (OverrideFont) + if ( OverrideFont ) return OverrideFont; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(EGDF_BUTTON); return 0; @@ -506,17 +515,16 @@ bool GUIButton::isOverrideColorEnabled() const return OverrideColorEnabled; } -void GUIButton::setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture *image, - const core::rect &sourceRect) +void GUIButton::setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture* image, const core::rect& sourceRect) { - if (state >= EGBIS_COUNT) + if ( state >= EGBIS_COUNT ) return; - if (image) + if ( image ) image->grab(); u32 stateIdx = (u32)state; - if (ButtonImages[stateIdx].Texture) + if ( ButtonImages[stateIdx].Texture ) ButtonImages[stateIdx].Texture->drop(); ButtonImages[stateIdx].Texture = image; @@ -524,28 +532,28 @@ void GUIButton::setImage(EGUI_BUTTON_IMAGE_STATE state, video::ITexture *image, } // PATCH -void GUIButton::setImage(video::ITexture *image) +void GUIButton::setImage(video::ITexture* image) { setImage(gui::EGBIS_IMAGE_UP, image); } -void GUIButton::setImage(video::ITexture *image, const core::rect &pos) +void GUIButton::setImage(video::ITexture* image, const core::rect& pos) { setImage(gui::EGBIS_IMAGE_UP, image, pos); } -void GUIButton::setPressedImage(video::ITexture *image) +void GUIButton::setPressedImage(video::ITexture* image) { setImage(gui::EGBIS_IMAGE_DOWN, image); } -void GUIButton::setPressedImage(video::ITexture *image, const core::rect &pos) +void GUIButton::setPressedImage(video::ITexture* image, const core::rect& pos) { setImage(gui::EGBIS_IMAGE_DOWN, image, pos); } //! Sets the text displayed by the button -void GUIButton::setText(const wchar_t *text) +void GUIButton::setText(const wchar_t* text) { StaticText->setText(text); @@ -561,6 +569,7 @@ void GUIButton::setIsPushButton(bool isPushButton) IsPushButton = isPushButton; } + //! Returns if the button is currently pressed bool GUIButton::isPressed() const { @@ -572,110 +581,118 @@ bool GUIButton::isPressed() const bool GUIButton::isHovered() const { IGUIElement *hovered = Environment->getHovered(); - return hovered == this || (hovered != nullptr && hovered->getParent() == this); + return hovered == this || (hovered != nullptr && hovered->getParent() == this); } // END PATCH //! Sets the pressed state of the button if this is a pushbutton void GUIButton::setPressed(bool pressed) { - if (Pressed != pressed) { + if (Pressed != pressed) + { ClickTime = porting::getTimeMs(); Pressed = pressed; setFromState(); } } + //! Returns whether the button is a push button bool GUIButton::isPushButton() const { return IsPushButton; } -//! Sets if the alpha channel should be used for drawing images on the button (default is -//! false) + +//! Sets if the alpha channel should be used for drawing images on the button (default is false) void GUIButton::setUseAlphaChannel(bool useAlphaChannel) { UseAlphaChannel = useAlphaChannel; } + //! Returns if the alpha channel should be used for drawing images on the button bool GUIButton::isAlphaChannelUsed() const { return UseAlphaChannel; } + bool GUIButton::isDrawingBorder() const { return DrawBorder; } + //! Writes attributes of the element. -void GUIButton::serializeAttributes( - io::IAttributes *out, io::SAttributeReadWriteOptions *options = 0) const +void GUIButton::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const { - IGUIButton::serializeAttributes(out, options); + IGUIButton::serializeAttributes(out,options); - out->addBool("PushButton", IsPushButton); + out->addBool ("PushButton", IsPushButton ); if (IsPushButton) - out->addBool("Pressed", Pressed); + out->addBool("Pressed", Pressed); - for (u32 i = 0; i < (u32)EGBIS_COUNT; ++i) { - if (ButtonImages[i].Texture) { - core::stringc name(GUIButtonImageStateNames[i]); + for ( u32 i=0; i<(u32)EGBIS_COUNT; ++i ) + { + if ( ButtonImages[i].Texture ) + { + core::stringc name( GUIButtonImageStateNames[i] ); out->addTexture(name.c_str(), ButtonImages[i].Texture); name += "Rect"; out->addRect(name.c_str(), ButtonImages[i].SourceRect); } } - out->addBool("UseAlphaChannel", UseAlphaChannel); - out->addBool("Border", DrawBorder); - out->addBool("ScaleImage", ScaleImage); + out->addBool ("UseAlphaChannel", UseAlphaChannel); + out->addBool ("Border", DrawBorder); + out->addBool ("ScaleImage", ScaleImage); - for (u32 i = 0; i < (u32)EGBS_COUNT; ++i) { - if (ButtonSprites[i].Index >= 0) { - core::stringc nameIndex(GUIButtonStateNames[i]); + for ( u32 i=0; i<(u32)EGBS_COUNT; ++i ) + { + if ( ButtonSprites[i].Index >= 0 ) + { + core::stringc nameIndex( GUIButtonStateNames[i] ); nameIndex += "Index"; - out->addInt(nameIndex.c_str(), ButtonSprites[i].Index); + out->addInt(nameIndex.c_str(), ButtonSprites[i].Index ); - core::stringc nameColor(GUIButtonStateNames[i]); + core::stringc nameColor( GUIButtonStateNames[i] ); nameColor += "Color"; - out->addColor(nameColor.c_str(), ButtonSprites[i].Color); + out->addColor(nameColor.c_str(), ButtonSprites[i].Color ); - core::stringc nameLoop(GUIButtonStateNames[i]); + core::stringc nameLoop( GUIButtonStateNames[i] ); nameLoop += "Loop"; - out->addBool(nameLoop.c_str(), ButtonSprites[i].Loop); + out->addBool(nameLoop.c_str(), ButtonSprites[i].Loop ); - core::stringc nameScale(GUIButtonStateNames[i]); + core::stringc nameScale( GUIButtonStateNames[i] ); nameScale += "Scale"; - out->addBool(nameScale.c_str(), ButtonSprites[i].Scale); + out->addBool(nameScale.c_str(), ButtonSprites[i].Scale ); } } // out->addString ("OverrideFont", OverrideFont); } + //! Reads attributes of the element -void GUIButton::deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0) +void GUIButton::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { - IGUIButton::deserializeAttributes(in, options); + IGUIButton::deserializeAttributes(in,options); - IsPushButton = in->getAttributeAsBool("PushButton"); - Pressed = IsPushButton ? in->getAttributeAsBool("Pressed") : false; + IsPushButton = in->getAttributeAsBool("PushButton"); + Pressed = IsPushButton ? in->getAttributeAsBool("Pressed") : false; core::rect rec = in->getAttributeAsRect("ImageRect"); if (rec.isValid()) - setImage(in->getAttributeAsTexture("Image"), rec); + setImage( in->getAttributeAsTexture("Image"), rec); else - setImage(in->getAttributeAsTexture("Image")); + setImage( in->getAttributeAsTexture("Image") ); rec = in->getAttributeAsRect("PressedImageRect"); if (rec.isValid()) - setPressedImage(in->getAttributeAsTexture("PressedImage"), rec); + setPressedImage( in->getAttributeAsTexture("PressedImage"), rec); else - setPressedImage(in->getAttributeAsTexture("PressedImage")); + setPressedImage( in->getAttributeAsTexture("PressedImage") ); setDrawBorder(in->getAttributeAsBool("Border")); setUseAlphaChannel(in->getAttributeAsBool("UseAlphaChannel")); @@ -687,19 +704,17 @@ void GUIButton::deserializeAttributes( } // PATCH -GUIButton *GUIButton::addButton(IGUIEnvironment *environment, - const core::rect &rectangle, ISimpleTextureSource *tsrc, - IGUIElement *parent, s32 id, const wchar_t *text, +GUIButton* GUIButton::addButton(IGUIEnvironment *environment, + const core::rect& rectangle, ISimpleTextureSource *tsrc, + IGUIElement* parent, s32 id, const wchar_t* text, const wchar_t *tooltiptext) { - GUIButton *button = new GUIButton(environment, - parent ? parent : environment->getRootGUIElement(), id, rectangle, - tsrc); + GUIButton* button = new GUIButton(environment, parent ? parent : environment->getRootGUIElement(), id, rectangle, tsrc); if (text) button->setText(text); - if (tooltiptext) - button->setToolTipText(tooltiptext); + if ( tooltiptext ) + button->setToolTipText ( tooltiptext ); button->drop(); return button; @@ -709,8 +724,7 @@ void GUIButton::setColor(video::SColor color) { float d = 0.65f; for (size_t i = 0; i < 4; i++) { - video::SColor base = Environment->getSkin()->getColor( - (gui::EGUI_DEFAULT_COLOR)i); + video::SColor base = Environment->getSkin()->getColor((gui::EGUI_DEFAULT_COLOR)i); Colors[i] = base.getInterpolated(color, d); } } @@ -730,7 +744,7 @@ void GUIButton::setFromState() } //! Set element properties from a StyleSpec -void GUIButton::setFromStyle(const StyleSpec &style) +void GUIButton::setFromStyle(const StyleSpec& style) { bool hovered = (style.getState() & StyleSpec::STATE_HOVERED) != 0; bool pressed = (style.getState() & StyleSpec::STATE_PRESSED) != 0; @@ -744,19 +758,17 @@ void GUIButton::setFromStyle(const StyleSpec &style) if (!Styles[style.getState()].isNotDefault(StyleSpec::BGCOLOR)) { for (size_t i = 0; i < 4; i++) { if (pressed) { - Colors[i] = multiplyColorValue( - Colors[i], COLOR_PRESSED_MOD); + Colors[i] = multiplyColorValue(Colors[i], COLOR_PRESSED_MOD); } else if (hovered) { - Colors[i] = multiplyColorValue( - Colors[i], COLOR_HOVERED_MOD); + Colors[i] = multiplyColorValue(Colors[i], COLOR_HOVERED_MOD); } } } } else { for (size_t i = 0; i < 4; i++) { - video::SColor base = Environment->getSkin()->getColor( - (gui::EGUI_DEFAULT_COLOR)i); + video::SColor base = + Environment->getSkin()->getColor((gui::EGUI_DEFAULT_COLOR)i); if (pressed) { Colors[i] = multiplyColorValue(base, COLOR_PRESSED_MOD); } else if (hovered) { @@ -770,7 +782,7 @@ void GUIButton::setFromStyle(const StyleSpec &style) if (style.isNotDefault(StyleSpec::TEXTCOLOR)) { setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR)); } else { - setOverrideColor(video::SColor(255, 255, 255, 255)); + setOverrideColor(video::SColor(255,255,255,255)); OverrideColorEnabled = false; } setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); @@ -779,10 +791,11 @@ void GUIButton::setFromStyle(const StyleSpec &style) setOverrideFont(style.getFont()); if (style.isNotDefault(StyleSpec::BGIMG)) { - video::ITexture *texture = - style.getTexture(StyleSpec::BGIMG, getTextureSource()); - setImage(guiScalingImageButton(Environment->getVideoDriver(), texture, - AbsoluteRect.getWidth(), AbsoluteRect.getHeight())); + video::ITexture *texture = style.getTexture(StyleSpec::BGIMG, + getTextureSource()); + setImage(guiScalingImageButton( + Environment->getVideoDriver(), texture, + AbsoluteRect.getWidth(), AbsoluteRect.getHeight())); setScaleImage(true); } else { setImage(nullptr); @@ -792,22 +805,23 @@ void GUIButton::setFromStyle(const StyleSpec &style) // Child padding and offset Padding = style.getRect(StyleSpec::PADDING, core::rect()); - Padding = core::rect(Padding.UpperLeftCorner + BgMiddle.UpperLeftCorner, + Padding = core::rect( + Padding.UpperLeftCorner + BgMiddle.UpperLeftCorner, Padding.LowerRightCorner + BgMiddle.LowerRightCorner); - GUISkin *skin = dynamic_cast(Environment->getSkin()); + GUISkin* skin = dynamic_cast(Environment->getSkin()); core::vector2d defaultPressOffset( skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X), skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y)); - ContentOffset = style.getVector2i(StyleSpec::CONTENT_OFFSET, - isPressed() ? defaultPressOffset : core::vector2d(0)); + ContentOffset = style.getVector2i(StyleSpec::CONTENT_OFFSET, isPressed() + ? defaultPressOffset + : core::vector2d(0)); - core::rect childBounds(Padding.UpperLeftCorner.X + ContentOffset.X, - Padding.UpperLeftCorner.Y + ContentOffset.Y, - AbsoluteRect.getWidth() + Padding.LowerRightCorner.X + - ContentOffset.X, - AbsoluteRect.getHeight() + Padding.LowerRightCorner.Y + - ContentOffset.Y); + core::rect childBounds( + Padding.UpperLeftCorner.X + ContentOffset.X, + Padding.UpperLeftCorner.Y + ContentOffset.Y, + AbsoluteRect.getWidth() + Padding.LowerRightCorner.X + ContentOffset.X, + AbsoluteRect.getHeight() + Padding.LowerRightCorner.Y + ContentOffset.Y); for (IGUIElement *child : getChildren()) { child->setRelativePosition(childBounds); @@ -815,7 +829,7 @@ void GUIButton::setFromStyle(const StyleSpec &style) } //! Set the styles used for each state -void GUIButton::setStyles(const std::array &styles) +void GUIButton::setStyles(const std::array& styles) { Styles = styles; setFromState(); diff --git a/src/gui/guiButton.h b/src/gui/guiButton.h index cd0b4ec5f..95fa1a2a1 100644 --- a/src/gui/guiButton.h +++ b/src/gui/guiButton.h @@ -18,55 +18,52 @@ using namespace irr; #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8) -namespace irr -{ -namespace gui -{ - -//! State of buttons used for drawing texture images. -//! Note that only a single state is active at a time -//! Also when no image is defined for a state it will use images from another state -//! and if that state is not set from the replacement for that,etc. -//! So in many cases setting EGBIS_IMAGE_UP and EGBIS_IMAGE_DOWN is sufficient. -enum EGUI_BUTTON_IMAGE_STATE -{ - //! When no other states have images they will all use this one. - EGBIS_IMAGE_UP, - //! When not set EGBIS_IMAGE_UP is used. - EGBIS_IMAGE_UP_MOUSEOVER, - //! When not set EGBIS_IMAGE_UP_MOUSEOVER is used. - EGBIS_IMAGE_UP_FOCUSED, - //! When not set EGBIS_IMAGE_UP_FOCUSED is used. - EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER, - //! When not set EGBIS_IMAGE_UP is used. - EGBIS_IMAGE_DOWN, - //! When not set EGBIS_IMAGE_DOWN is used. - EGBIS_IMAGE_DOWN_MOUSEOVER, - //! When not set EGBIS_IMAGE_DOWN_MOUSEOVER is used. - EGBIS_IMAGE_DOWN_FOCUSED, - //! When not set EGBIS_IMAGE_DOWN_FOCUSED is used. - EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER, - //! When not set EGBIS_IMAGE_UP or EGBIS_IMAGE_DOWN are used (depending on button - //! state). - EGBIS_IMAGE_DISABLED, - //! not used, counts the number of enumerated items - EGBIS_COUNT -}; - -//! Names for gui button image states -const c8 *const GUIButtonImageStateNames[EGBIS_COUNT + 1] = { - "Image", // not "ImageUp" as it otherwise breaks serialization of old - // files - "ImageUpOver", "ImageUpFocused", "ImageUpFocusedOver", - "PressedImage", // not "ImageDown" as it otherwise breaks serialization of - // old files - "ImageDownOver", "ImageDownFocused", "ImageDownFocusedOver", - "ImageDisabled", - 0 // count -}; - -} -} + namespace irr { namespace gui { + + //! State of buttons used for drawing texture images. + //! Note that only a single state is active at a time + //! Also when no image is defined for a state it will use images from another state + //! and if that state is not set from the replacement for that,etc. + //! So in many cases setting EGBIS_IMAGE_UP and EGBIS_IMAGE_DOWN is sufficient. + enum EGUI_BUTTON_IMAGE_STATE { + //! When no other states have images they will all use this one. + EGBIS_IMAGE_UP, + //! When not set EGBIS_IMAGE_UP is used. + EGBIS_IMAGE_UP_MOUSEOVER, + //! When not set EGBIS_IMAGE_UP_MOUSEOVER is used. + EGBIS_IMAGE_UP_FOCUSED, + //! When not set EGBIS_IMAGE_UP_FOCUSED is used. + EGBIS_IMAGE_UP_FOCUSED_MOUSEOVER, + //! When not set EGBIS_IMAGE_UP is used. + EGBIS_IMAGE_DOWN, + //! When not set EGBIS_IMAGE_DOWN is used. + EGBIS_IMAGE_DOWN_MOUSEOVER, + //! When not set EGBIS_IMAGE_DOWN_MOUSEOVER is used. + EGBIS_IMAGE_DOWN_FOCUSED, + //! When not set EGBIS_IMAGE_DOWN_FOCUSED is used. + EGBIS_IMAGE_DOWN_FOCUSED_MOUSEOVER, + //! When not set EGBIS_IMAGE_UP or EGBIS_IMAGE_DOWN are used (depending on button state). + EGBIS_IMAGE_DISABLED, + //! not used, counts the number of enumerated items + EGBIS_COUNT + }; + + //! Names for gui button image states + const c8 *const GUIButtonImageStateNames[EGBIS_COUNT + 1] = + { + "Image", // not "ImageUp" as it otherwise breaks serialization of old files + "ImageUpOver", + "ImageUpFocused", + "ImageUpFocusedOver", + "PressedImage", // not "ImageDown" as it otherwise breaks serialization of old files + "ImageDownOver", + "ImageDownFocused", + "ImageDownFocusedOver", + "ImageDisabled", + 0 // count + }; + + }} #endif @@ -75,29 +72,29 @@ class ISimpleTextureSource; class GUIButton : public gui::IGUIButton { public: + //! constructor - GUIButton(gui::IGUIEnvironment *environment, gui::IGUIElement *parent, s32 id, - core::rect rectangle, ISimpleTextureSource *tsrc, - bool noclip = false); + GUIButton(gui::IGUIEnvironment* environment, gui::IGUIElement* parent, + s32 id, core::rect rectangle, ISimpleTextureSource *tsrc, + bool noclip=false); //! destructor virtual ~GUIButton(); //! called if an event happened. - virtual bool OnEvent(const SEvent &event) override; + virtual bool OnEvent(const SEvent& event) override; //! draws the element and its children virtual void draw() override; - //! sets another skin independent font. if this is set to zero, the button uses - //! the font of the skin. - virtual void setOverrideFont(gui::IGUIFont *font = 0) override; + //! sets another skin independent font. if this is set to zero, the button uses the font of the skin. + virtual void setOverrideFont(gui::IGUIFont* font=0) override; //! Gets the override font (if any) - virtual gui::IGUIFont *getOverrideFont() const override; + virtual gui::IGUIFont* getOverrideFont() const override; //! Get the font which is used right now for drawing - virtual gui::IGUIFont *getActiveFont() const override; + virtual gui::IGUIFont* getActiveFont() const override; //! Sets another color for the button text. virtual void setOverrideColor(video::SColor color); @@ -105,58 +102,49 @@ class GUIButton : public gui::IGUIButton //! Gets the override color virtual video::SColor getOverrideColor(void) const; - //! Sets if the button text should use the override color or the color in the gui - //! skin. + //! Sets if the button text should use the override color or the color in the gui skin. virtual void enableOverrideColor(bool enable); //! Checks if an override color is enabled virtual bool isOverrideColorEnabled(void) const; // PATCH - //! Sets an image which should be displayed on the button when it is in the given - //! state. + //! Sets an image which should be displayed on the button when it is in the given state. virtual void setImage(gui::EGUI_BUTTON_IMAGE_STATE state, - video::ITexture *image = nullptr, - const core::rect &sourceRect = core::rect(0, 0, 0, 0)); + video::ITexture* image=nullptr, + const core::rect& sourceRect=core::rect(0,0,0,0)); - //! Sets an image which should be displayed on the button when it is in normal - //! state. - virtual void setImage(video::ITexture *image = nullptr) override; + //! Sets an image which should be displayed on the button when it is in normal state. + virtual void setImage(video::ITexture* image=nullptr) override; - //! Sets an image which should be displayed on the button when it is in normal - //! state. - virtual void setImage( - video::ITexture *image, const core::rect &pos) override; + //! Sets an image which should be displayed on the button when it is in normal state. + virtual void setImage(video::ITexture* image, const core::rect& pos) override; - //! Sets an image which should be displayed on the button when it is in pressed - //! state. - virtual void setPressedImage(video::ITexture *image = nullptr) override; + //! Sets an image which should be displayed on the button when it is in pressed state. + virtual void setPressedImage(video::ITexture* image=nullptr) override; - //! Sets an image which should be displayed on the button when it is in pressed - //! state. - virtual void setPressedImage( - video::ITexture *image, const core::rect &pos) override; + //! Sets an image which should be displayed on the button when it is in pressed state. + virtual void setPressedImage(video::ITexture* image, const core::rect& pos) override; //! Sets the text displayed by the button - virtual void setText(const wchar_t *text) override; + virtual void setText(const wchar_t* text) override; // END PATCH //! Sets the sprite bank used by the button - virtual void setSpriteBank(gui::IGUISpriteBank *bank = 0) override; + virtual void setSpriteBank(gui::IGUISpriteBank* bank=0) override; //! Sets the animated sprite for a specific button state - /** \param index: Number of the sprite within the sprite bank, use -1 for no - sprite \param state: State of the button to set the sprite for \param index: The - sprite number from the current sprite bank \param color: The color of the sprite + /** \param index: Number of the sprite within the sprite bank, use -1 for no sprite + \param state: State of the button to set the sprite for + \param index: The sprite number from the current sprite bank + \param color: The color of the sprite */ virtual void setSprite(gui::EGUI_BUTTON_STATE state, s32 index, - video::SColor color = video::SColor(255, 255, 255, 255), - bool loop = false, bool scale = false); + video::SColor color=video::SColor(255,255,255,255), + bool loop=false, bool scale=false); #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8) - void setSprite(gui::EGUI_BUTTON_STATE state, s32 index, video::SColor color, - bool loop) override - { + void setSprite(gui::EGUI_BUTTON_STATE state, s32 index, video::SColor color, bool loop) override { setSprite(state, index, color, loop, false); } #endif @@ -164,8 +152,7 @@ class GUIButton : public gui::IGUIButton //! Get the sprite-index for the given state or -1 when no sprite is set virtual s32 getSpriteIndex(gui::EGUI_BUTTON_STATE state) const; - //! Get the sprite color for the given state. Color is only used when a sprite is - //! set. + //! Get the sprite color for the given state. Color is only used when a sprite is set. virtual video::SColor getSpriteColor(gui::EGUI_BUTTON_STATE state) const; //! Returns if the sprite in the given state does loop @@ -177,13 +164,13 @@ class GUIButton : public gui::IGUIButton //! Sets if the button should behave like a push button. Which means it //! can be in two states: Normal or Pressed. With a click on the button, //! the user can change the state of the button. - virtual void setIsPushButton(bool isPushButton = true) override; + virtual void setIsPushButton(bool isPushButton=true) override; //! Checks whether the button is a push button virtual bool isPushButton() const override; //! Sets the pressed state of the button if this is a pushbutton - virtual void setPressed(bool pressed = true) override; + virtual void setPressed(bool pressed=true) override; //! Returns if the button is currently pressed virtual bool isPressed() const override; @@ -194,37 +181,42 @@ class GUIButton : public gui::IGUIButton // END PATCH //! Sets if the button should use the skin to draw its border - virtual void setDrawBorder(bool border = true) override; + virtual void setDrawBorder(bool border=true) override; //! Checks if the button face and border are being drawn virtual bool isDrawingBorder() const override; - //! Sets if the alpha channel should be used for drawing images on the button - //! (default is false) - virtual void setUseAlphaChannel(bool useAlphaChannel = true) override; + //! Sets if the alpha channel should be used for drawing images on the button (default is false) + virtual void setUseAlphaChannel(bool useAlphaChannel=true) override; //! Checks if the alpha channel should be used for drawing images on the button virtual bool isAlphaChannelUsed() const override; //! Sets if the button should scale the button images to fit - virtual void setScaleImage(bool scaleImage = true) override; + virtual void setScaleImage(bool scaleImage=true) override; //! Checks whether the button scales the used images virtual bool isScalingImage() const override; //! Get if the shift key was pressed in last EGET_BUTTON_CLICKED event - virtual bool getClickShiftState() const { return ClickShiftState; } + virtual bool getClickShiftState() const + { + return ClickShiftState; + } //! Get if the control key was pressed in last EGET_BUTTON_CLICKED event - virtual bool getClickControlState() const { return ClickControlState; } + virtual bool getClickControlState() const + { + return ClickControlState; + } //! Writes attributes of the element. - virtual void serializeAttributes(io::IAttributes *out, - io::SAttributeReadWriteOptions *options) const override; + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const override; //! Reads attributes of the element - virtual void deserializeAttributes(io::IAttributes *in, - io::SAttributeReadWriteOptions *options) override; + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options) override; + + void setColor(video::SColor color); // PATCH @@ -232,76 +224,79 @@ class GUIButton : public gui::IGUIButton void setFromState(); //! Set element properties from a StyleSpec - virtual void setFromStyle(const StyleSpec &style); + virtual void setFromStyle(const StyleSpec& style); //! Set the styles used for each state - void setStyles(const std::array &styles); + void setStyles(const std::array& styles); // END PATCH + //! Do not drop returned handle - static GUIButton *addButton(gui::IGUIEnvironment *environment, - const core::rect &rectangle, ISimpleTextureSource *tsrc, - IGUIElement *parent, s32 id, const wchar_t *text, - const wchar_t *tooltiptext = L""); + static GUIButton* addButton(gui::IGUIEnvironment *environment, + const core::rect& rectangle, ISimpleTextureSource *tsrc, + IGUIElement* parent, s32 id, const wchar_t* text, + const wchar_t *tooltiptext=L""); protected: - void drawSprite(gui::EGUI_BUTTON_STATE state, u32 startTime, - const core::position2di ¢er); + void drawSprite(gui::EGUI_BUTTON_STATE state, u32 startTime, const core::position2di& center); gui::EGUI_BUTTON_IMAGE_STATE getImageState(bool pressed) const; ISimpleTextureSource *getTextureSource() { return TSrc; } struct ButtonImage { - ButtonImage() : Texture(0), SourceRect(core::rect(0, 0, 0, 0)) {} + ButtonImage() : Texture(0), SourceRect(core::rect(0,0,0,0)) + { + } - ButtonImage(const ButtonImage &other) : - Texture(0), SourceRect(core::rect(0, 0, 0, 0)) + ButtonImage(const ButtonImage& other) : Texture(0), SourceRect(core::rect(0,0,0,0)) { *this = other; } ~ButtonImage() { - if (Texture) + if ( Texture ) Texture->drop(); } - ButtonImage &operator=(const ButtonImage &other) + ButtonImage& operator=(const ButtonImage& other) { - if (this == &other) + if ( this == &other ) return *this; if (other.Texture) other.Texture->grab(); - if (Texture) + if ( Texture ) Texture->drop(); Texture = other.Texture; SourceRect = other.SourceRect; return *this; } - bool operator==(const ButtonImage &other) const + bool operator==(const ButtonImage& other) const { return Texture == other.Texture && SourceRect == other.SourceRect; } - video::ITexture *Texture; + + video::ITexture* Texture; core::rect SourceRect; }; - gui::EGUI_BUTTON_IMAGE_STATE getImageState( - bool pressed, const ButtonImage *images) const; + gui::EGUI_BUTTON_IMAGE_STATE getImageState(bool pressed, const ButtonImage* images) const; private: + struct ButtonSprite { - ButtonSprite() : Index(-1), Loop(false), Scale(false) {} + ButtonSprite() : Index(-1), Loop(false), Scale(false) + { + } - bool operator==(const ButtonSprite &other) const + bool operator==(const ButtonSprite& other) const { - return Index == other.Index && Color == other.Color && - Loop == other.Loop && Scale == other.Scale; + return Index == other.Index && Color == other.Color && Loop == other.Loop && Scale == other.Scale; } s32 Index; @@ -311,13 +306,13 @@ class GUIButton : public gui::IGUIButton }; ButtonSprite ButtonSprites[gui::EGBS_COUNT]; - gui::IGUISpriteBank *SpriteBank; + gui::IGUISpriteBank* SpriteBank; ButtonImage ButtonImages[gui::EGBIS_COUNT]; std::array Styles; - gui::IGUIFont *OverrideFont; + gui::IGUIFont* OverrideFont; bool OverrideColorEnabled; video::SColor OverrideColor; diff --git a/src/gui/guiButtonImage.cpp b/src/gui/guiButtonImage.cpp index 2f574c1a8..b507ffece 100644 --- a/src/gui/guiButtonImage.cpp +++ b/src/gui/guiButtonImage.cpp @@ -31,12 +31,11 @@ using namespace gui; GUIButtonImage::GUIButtonImage(gui::IGUIEnvironment *environment, gui::IGUIElement *parent, s32 id, core::rect rectangle, - ISimpleTextureSource *tsrc, bool noclip) : - GUIButton(environment, parent, id, rectangle, tsrc, noclip) + ISimpleTextureSource *tsrc, bool noclip) + : GUIButton (environment, parent, id, rectangle, tsrc, noclip) { - m_image = Environment->addImage(core::rect(0, 0, rectangle.getWidth(), - rectangle.getHeight()), - this); + m_image = Environment->addImage( + core::rect(0,0,rectangle.getWidth(),rectangle.getHeight()), this); m_image->setScaleImage(isScalingImage()); sendToBack(m_image); } @@ -57,18 +56,18 @@ void GUIButtonImage::setForegroundImage(video::ITexture *image) } //! Set element properties from a StyleSpec -void GUIButtonImage::setFromStyle(const StyleSpec &style) +void GUIButtonImage::setFromStyle(const StyleSpec& style) { GUIButton::setFromStyle(style); video::IVideoDriver *driver = Environment->getVideoDriver(); if (style.isNotDefault(StyleSpec::FGIMG)) { - video::ITexture *texture = - style.getTexture(StyleSpec::FGIMG, getTextureSource()); + video::ITexture *texture = style.getTexture(StyleSpec::FGIMG, + getTextureSource()); setForegroundImage(guiScalingImageButton(driver, texture, - AbsoluteRect.getWidth(), AbsoluteRect.getHeight())); + AbsoluteRect.getWidth(), AbsoluteRect.getHeight())); setScaleImage(true); } else { setForegroundImage(nullptr); @@ -87,8 +86,7 @@ GUIButtonImage *GUIButtonImage::addButton(IGUIEnvironment *environment, const wchar_t *tooltiptext) { GUIButtonImage *button = new GUIButtonImage(environment, - parent ? parent : environment->getRootGUIElement(), id, rectangle, - tsrc); + parent ? parent : environment->getRootGUIElement(), id, rectangle, tsrc); if (text) button->setText(text); diff --git a/src/gui/guiButtonImage.h b/src/gui/guiButtonImage.h index c46ef36f0..59a25b4f0 100644 --- a/src/gui/guiButtonImage.h +++ b/src/gui/guiButtonImage.h @@ -35,9 +35,9 @@ class GUIButtonImage : public GUIButton void setForegroundImage(video::ITexture *image = nullptr); //! Set element properties from a StyleSpec - virtual void setFromStyle(const StyleSpec &style) override; + virtual void setFromStyle(const StyleSpec& style) override; - virtual void setScaleImage(bool scaleImage = true) override; + virtual void setScaleImage(bool scaleImage=true) override; //! Do not drop returned handle static GUIButtonImage *addButton(gui::IGUIEnvironment *environment, diff --git a/src/gui/guiButtonItemImage.cpp b/src/gui/guiButtonItemImage.cpp index bbd20582b..d8b9042ac 100644 --- a/src/gui/guiButtonItemImage.cpp +++ b/src/gui/guiButtonItemImage.cpp @@ -31,12 +31,11 @@ using namespace gui; GUIButtonItemImage::GUIButtonItemImage(gui::IGUIEnvironment *environment, gui::IGUIElement *parent, s32 id, core::rect rectangle, ISimpleTextureSource *tsrc, std::string item, Client *client, - bool noclip) : - GUIButton(environment, parent, id, rectangle, tsrc, noclip) + bool noclip) + : GUIButton (environment, parent, id, rectangle, tsrc, noclip) { m_image = new GUIItemImage(environment, this, id, - core::rect(0, 0, rectangle.getWidth(), - rectangle.getHeight()), + core::rect(0,0,rectangle.getWidth(),rectangle.getHeight()), item, getActiveFont(), client); sendToBack(m_image); @@ -50,8 +49,8 @@ GUIButtonItemImage *GUIButtonItemImage::addButton(IGUIEnvironment *environment, Client *client) { GUIButtonItemImage *button = new GUIButtonItemImage(environment, - parent ? parent : environment->getRootGUIElement(), id, rectangle, - tsrc, item, client); + parent ? parent : environment->getRootGUIElement(), + id, rectangle, tsrc, item, client); if (text) button->setText(text); diff --git a/src/gui/guiButtonItemImage.h b/src/gui/guiButtonItemImage.h index bc93c08d2..aad923bda 100644 --- a/src/gui/guiButtonItemImage.h +++ b/src/gui/guiButtonItemImage.h @@ -38,8 +38,8 @@ class GUIButtonItemImage : public GUIButton //! Do not drop returned handle static GUIButtonItemImage *addButton(gui::IGUIEnvironment *environment, const core::rect &rectangle, ISimpleTextureSource *tsrc, - IGUIElement *parent, s32 id, const wchar_t *text, - std::string item, Client *client); + IGUIElement *parent, s32 id, const wchar_t *text, std::string item, + Client *client); private: std::string m_item_name; diff --git a/src/gui/guiChatConsole.cpp b/src/gui/guiChatConsole.cpp index 7170fad15..8de00c12f 100644 --- a/src/gui/guiChatConsole.cpp +++ b/src/gui/guiChatConsole.cpp @@ -32,20 +32,29 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #if USE_FREETYPE -#include "irrlicht_changes/CGUITTFont.h" + #include "irrlicht_changes/CGUITTFont.h" #endif inline u32 clamp_u8(s32 value) { - return (u32)MYMIN(MYMAX(value, 0), 255); + return (u32) MYMIN(MYMAX(value, 0), 255); } -GUIChatConsole::GUIChatConsole(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, ChatBackend *backend, Client *client, IMenuManager *menumgr) : - IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, - core::rect(0, 0, 100, 100)), - m_chat_backend(backend), m_client(client), m_menumgr(menumgr), - m_animate_time_old(porting::getTimeMs()) + +GUIChatConsole::GUIChatConsole( + gui::IGUIEnvironment* env, + gui::IGUIElement* parent, + s32 id, + ChatBackend* backend, + Client* client, + IMenuManager* menumgr +): + IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, + core::rect(0,0,100,100)), + m_chat_backend(backend), + m_client(client), + m_menumgr(menumgr), + m_animate_time_old(porting::getTimeMs()) { // load background settings s32 console_alpha = g_settings->getS32("console_alpha"); @@ -66,9 +75,8 @@ GUIChatConsole::GUIChatConsole(gui::IGUIEnvironment *env, gui::IGUIElement *pare } u16 chat_font_size = g_settings->getU16("chat_font_size"); - m_font = g_fontengine->getFont( - chat_font_size != 0 ? chat_font_size : FONT_SIZE_UNSPECIFIED, - FM_Mono); + m_font = g_fontengine->getFont(chat_font_size != 0 ? + chat_font_size : FONT_SIZE_UNSPECIFIED, FM_Mono); if (!m_font) { errorstream << "GUIChatConsole: Unable to load mono font" << std::endl; @@ -135,24 +143,31 @@ f32 GUIChatConsole::getDesiredHeight() const void GUIChatConsole::replaceAndAddToHistory(const std::wstring &line) { - ChatPrompt &prompt = m_chat_backend->getPrompt(); + ChatPrompt& prompt = m_chat_backend->getPrompt(); prompt.addToHistory(prompt.getLine()); prompt.replace(line); } + void GUIChatConsole::setCursor( - bool visible, bool blinking, f32 blink_speed, f32 relative_height) + bool visible, bool blinking, f32 blink_speed, f32 relative_height) { - if (visible) { - if (blinking) { + if (visible) + { + if (blinking) + { // leave m_cursor_blink unchanged m_cursor_blink_speed = blink_speed; - } else { - m_cursor_blink = 0x8000; // on + } + else + { + m_cursor_blink = 0x8000; // on m_cursor_blink_speed = 0.0; } - } else { - m_cursor_blink = 0; // off + } + else + { + m_cursor_blink = 0; // off m_cursor_blink_speed = 0.0; } m_cursor_height = relative_height; @@ -160,14 +175,15 @@ void GUIChatConsole::setCursor( void GUIChatConsole::draw() { - if (!IsVisible) + if(!IsVisible) return; - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); // Check screen size v2u32 screensize = driver->getScreenSize(); - if (screensize != m_screensize) { + if (screensize != m_screensize) + { // screen size has changed // scale current console height to new window size if (m_screensize.Y != 0) @@ -183,7 +199,8 @@ void GUIChatConsole::draw() m_animate_time_old = now; // Draw console elements if visible - if (m_height > 0) { + if (m_height > 0) + { drawBackground(); drawText(); drawPrompt(); @@ -194,8 +211,7 @@ void GUIChatConsole::draw() void GUIChatConsole::reformatConsole() { - s32 cols = m_screensize.X / m_fontsize.X - - 2; // make room for a margin (looks better) + s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt if (cols <= 0 || rows <= 0) cols = rows = 0; @@ -216,24 +232,27 @@ void GUIChatConsole::animate(u32 msec) s32 goal = m_open ? m_desired_height : 0; // Set invisible if close animation finished (reset by openConsole) - // This function (animate()) is never called once its visibility becomes false so - // do not + // This function (animate()) is never called once its visibility becomes false so do not // actually set visible to false before the inhibited period is over if (!m_open && m_height == 0 && m_open_inhibited == 0) IGUIElement::setVisible(false); - if (m_height != goal) { + if (m_height != goal) + { s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); if (max_change == 0) max_change = 1; - if (m_height < goal) { + if (m_height < goal) + { // increase height if (m_height + max_change < goal) m_height += max_change; else m_height = goal; - } else { + } + else + { // decrease height if (m_height > goal + max_change) m_height -= max_change; @@ -245,7 +264,8 @@ void GUIChatConsole::animate(u32 msec) } // blink the cursor - if (m_cursor_blink_speed != 0.0) { + if (m_cursor_blink_speed != 0.0) + { u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); if (blink_increase == 0) blink_increase = 1; @@ -261,15 +281,24 @@ void GUIChatConsole::animate(u32 msec) void GUIChatConsole::drawBackground() { - video::IVideoDriver *driver = Environment->getVideoDriver(); - if (m_background != NULL) { + video::IVideoDriver* driver = Environment->getVideoDriver(); + if (m_background != NULL) + { core::rect sourcerect(0, -m_height, m_screensize.X, 0); - driver->draw2DImage(m_background, v2s32(0, 0), sourcerect, - &AbsoluteClippingRect, m_background_color, false); - } else { - driver->draw2DRectangle(m_background_color, - core::rect(0, 0, m_screensize.X, m_height), - &AbsoluteClippingRect); + driver->draw2DImage( + m_background, + v2s32(0, 0), + sourcerect, + &AbsoluteClippingRect, + m_background_color, + false); + } + else + { + driver->draw2DRectangle( + m_background_color, + core::rect(0, 0, m_screensize.X, m_height), + &AbsoluteClippingRect); } } @@ -278,9 +307,10 @@ void GUIChatConsole::drawText() if (m_font == NULL) return; - ChatBuffer &buf = m_chat_backend->getConsoleBuffer(); - for (u32 row = 0; row < buf.getRows(); ++row) { - const ChatFormattedLine &line = buf.getFormattedLine(row); + ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); + for (u32 row = 0; row < buf.getRows(); ++row) + { + const ChatFormattedLine& line = buf.getFormattedLine(row); if (line.fragments.empty()) continue; @@ -291,26 +321,31 @@ void GUIChatConsole::drawText() for (const ChatFormattedFragment &fragment : line.fragments) { s32 x = (fragment.column + 1) * m_fontsize.X; - core::rect destrect(x, y, - x + m_fontsize.X * fragment.text.size(), - y + m_fontsize.Y); + 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); - tmp->draw(fragment.text, destrect, - video::SColor(255, 255, 255, 255), false, - false, &AbsoluteClippingRect); - } else + irr::gui::CGUITTFont *tmp = dynamic_cast(m_font); + tmp->draw( + fragment.text, + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); + } else #endif { // Otherwise use standard text - m_font->draw(fragment.text.c_str(), destrect, - video::SColor(255, 255, 255, 255), false, - false, &AbsoluteClippingRect); + m_font->draw( + fragment.text.c_str(), + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); } } } @@ -325,44 +360,58 @@ void GUIChatConsole::drawPrompt() s32 line_height = m_fontsize.Y; s32 y = row * line_height + m_height - m_desired_height; - ChatPrompt &prompt = m_chat_backend->getPrompt(); + ChatPrompt& prompt = m_chat_backend->getPrompt(); std::wstring prompt_text = prompt.getVisiblePortion(); // FIXME Draw string at once, not character by character // That will only work with the cursor once we have a monospace font - for (u32 i = 0; i < prompt_text.size(); ++i) { + for (u32 i = 0; i < prompt_text.size(); ++i) + { wchar_t ws[2] = {prompt_text[i], 0}; s32 x = (1 + i) * m_fontsize.X; - core::rect destrect(x, y, x + m_fontsize.X, y + m_fontsize.Y); - m_font->draw(ws, destrect, video::SColor(255, 255, 255, 255), false, - false, &AbsoluteClippingRect); + core::rect destrect( + x, y, x + m_fontsize.X, y + m_fontsize.Y); + m_font->draw( + ws, + destrect, + video::SColor(255, 255, 255, 255), + false, + false, + &AbsoluteClippingRect); } // Draw the cursor during on periods - if ((m_cursor_blink & 0x8000) != 0) { + if ((m_cursor_blink & 0x8000) != 0) + { s32 cursor_pos = prompt.getVisibleCursorPosition(); - if (cursor_pos >= 0) { + if (cursor_pos >= 0) + { s32 cursor_len = prompt.getCursorLength(); - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); s32 x = (1 + cursor_pos) * m_fontsize.X; - core::rect destrect(x, - y + m_fontsize.Y * (1.0 - m_cursor_height), - x + m_fontsize.X * MYMAX(cursor_len, 1), - y + m_fontsize.Y * (cursor_len ? m_cursor_height + 1 - : 1)); - video::SColor cursor_color(255, 255, 255, 255); + core::rect destrect( + x, + y + m_fontsize.Y * (1.0 - m_cursor_height), + x + m_fontsize.X * MYMAX(cursor_len, 1), + y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) + ); + video::SColor cursor_color(255,255,255,255); driver->draw2DRectangle( - cursor_color, destrect, &AbsoluteClippingRect); + cursor_color, + destrect, + &AbsoluteClippingRect); } } + } -bool GUIChatConsole::OnEvent(const SEvent &event) +bool GUIChatConsole::OnEvent(const SEvent& event) { ChatPrompt &prompt = m_chat_backend->getPrompt(); - if (event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) { + if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) + { // Key input if (KeyPress(event.KeyInput) == getKeySetting("keymap_console")) { closeConsole(); @@ -377,16 +426,21 @@ bool GUIChatConsole::OnEvent(const SEvent &event) closeConsoleAtOnce(); m_close_on_enter = false; // inhibit open so the_game doesn't reopen immediately - m_open_inhibited = 1; // so the ESCAPE button doesn't open the - // "pause menu" + m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" return true; - } else if (event.KeyInput.Key == KEY_PRIOR) { + } + else if(event.KeyInput.Key == KEY_PRIOR) + { m_chat_backend->scrollPageUp(); return true; - } else if (event.KeyInput.Key == KEY_NEXT) { + } + else if(event.KeyInput.Key == KEY_NEXT) + { m_chat_backend->scrollPageDown(); return true; - } else if (event.KeyInput.Key == KEY_RETURN) { + } + else if(event.KeyInput.Key == KEY_RETURN) + { prompt.addToHistory(prompt.getLine()); std::wstring text = prompt.replace(L""); m_client->typeChatMessage(text); @@ -395,76 +449,97 @@ bool GUIChatConsole::OnEvent(const SEvent &event) m_close_on_enter = false; } return true; - } else if (event.KeyInput.Key == KEY_UP) { + } + else if(event.KeyInput.Key == KEY_UP) + { // Up pressed // Move back in history prompt.historyPrev(); return true; - } else if (event.KeyInput.Key == KEY_DOWN) { + } + else if(event.KeyInput.Key == KEY_DOWN) + { // Down pressed // Move forward in history prompt.historyNext(); return true; - } else if (event.KeyInput.Key == KEY_LEFT || - event.KeyInput.Key == KEY_RIGHT) { + } + else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) + { // Left/right pressed - // Move/select character/word to the left depending on control and - // shift keys - ChatPrompt::CursorOp op = - event.KeyInput.Shift ? ChatPrompt::CURSOROP_SELECT - : ChatPrompt::CURSOROP_MOVE; - ChatPrompt::CursorOpDir dir = - event.KeyInput.Key == KEY_LEFT - ? ChatPrompt::CURSOROP_DIR_LEFT - : ChatPrompt::CURSOROP_DIR_RIGHT; - ChatPrompt::CursorOpScope scope = - event.KeyInput.Control - ? ChatPrompt::CURSOROP_SCOPE_WORD - : ChatPrompt::CURSOROP_SCOPE_CHARACTER; + // Move/select character/word to the left depending on control and shift keys + ChatPrompt::CursorOp op = event.KeyInput.Shift ? + ChatPrompt::CURSOROP_SELECT : + ChatPrompt::CURSOROP_MOVE; + ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? + ChatPrompt::CURSOROP_DIR_LEFT : + ChatPrompt::CURSOROP_DIR_RIGHT; + ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation(op, dir, scope); return true; - } else if (event.KeyInput.Key == KEY_HOME) { + } + else if(event.KeyInput.Key == KEY_HOME) + { // Home pressed // move to beginning of line - prompt.cursorOperation(ChatPrompt::CURSOROP_MOVE, - ChatPrompt::CURSOROP_DIR_LEFT, - ChatPrompt::CURSOROP_SCOPE_LINE); + prompt.cursorOperation( + ChatPrompt::CURSOROP_MOVE, + ChatPrompt::CURSOROP_DIR_LEFT, + ChatPrompt::CURSOROP_SCOPE_LINE); return true; - } else if (event.KeyInput.Key == KEY_END) { + } + else if(event.KeyInput.Key == KEY_END) + { // End pressed // move to end of line - prompt.cursorOperation(ChatPrompt::CURSOROP_MOVE, - ChatPrompt::CURSOROP_DIR_RIGHT, - ChatPrompt::CURSOROP_SCOPE_LINE); + prompt.cursorOperation( + ChatPrompt::CURSOROP_MOVE, + ChatPrompt::CURSOROP_DIR_RIGHT, + ChatPrompt::CURSOROP_SCOPE_LINE); return true; - } else if (event.KeyInput.Key == KEY_BACK) { + } + else if(event.KeyInput.Key == KEY_BACK) + { // Backspace or Ctrl-Backspace pressed // delete character / word to the left ChatPrompt::CursorOpScope scope = - event.KeyInput.Control - ? ChatPrompt::CURSOROP_SCOPE_WORD - : ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation(ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, scope); + event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, + scope); return true; - } else if (event.KeyInput.Key == KEY_DELETE) { + } + else if(event.KeyInput.Key == KEY_DELETE) + { // Delete or Ctrl-Delete pressed // delete character / word to the right ChatPrompt::CursorOpScope scope = - event.KeyInput.Control - ? ChatPrompt::CURSOROP_SCOPE_WORD - : ChatPrompt::CURSOROP_SCOPE_CHARACTER; - prompt.cursorOperation(ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_RIGHT, scope); + event.KeyInput.Control ? + ChatPrompt::CURSOROP_SCOPE_WORD : + ChatPrompt::CURSOROP_SCOPE_CHARACTER; + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_RIGHT, + scope); return true; - } else if (event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) { + } + else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) + { // Ctrl-A pressed // Select all text - prompt.cursorOperation(ChatPrompt::CURSOROP_SELECT, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_LINE); + prompt.cursorOperation( + ChatPrompt::CURSOROP_SELECT, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_LINE); return true; - } else if (event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) { + } + else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) + { // Ctrl-C pressed // Copy text to clipboard if (prompt.getCursorLength() <= 0) @@ -473,23 +548,28 @@ bool GUIChatConsole::OnEvent(const SEvent &event) std::string selected(wselected.begin(), wselected.end()); Environment->getOSOperator()->copyToClipboard(selected.c_str()); return true; - } else if (event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) { + } + else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) + { // Ctrl-V pressed // paste text from clipboard if (prompt.getCursorLength() > 0) { // Delete selected section of text - prompt.cursorOperation(ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_SELECTION); + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_SELECTION); } IOSOperator *os_operator = Environment->getOSOperator(); const c8 *text = os_operator->getTextFromClipboard(); if (!text) return true; - std::basic_string str((const unsigned char *)text); + std::basic_string str((const unsigned char*)text); prompt.input(std::wstring(str.begin(), str.end())); return true; - } else if (event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) { + } + else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) + { // Ctrl-X pressed // Cut text to clipboard if (prompt.getCursorLength() <= 0) @@ -497,45 +577,55 @@ bool GUIChatConsole::OnEvent(const SEvent &event) std::wstring wselected = prompt.getSelection(); std::string selected(wselected.begin(), wselected.end()); Environment->getOSOperator()->copyToClipboard(selected.c_str()); - prompt.cursorOperation(ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, // Ignored - ChatPrompt::CURSOROP_SCOPE_SELECTION); + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, // Ignored + ChatPrompt::CURSOROP_SCOPE_SELECTION); return true; - } else if (event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) { + } + else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) + { // Ctrl-U pressed // kill line to left end - prompt.cursorOperation(ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_LEFT, - ChatPrompt::CURSOROP_SCOPE_LINE); + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_LEFT, + ChatPrompt::CURSOROP_SCOPE_LINE); return true; - } else if (event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) { + } + else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) + { // Ctrl-K pressed // kill line to right end - prompt.cursorOperation(ChatPrompt::CURSOROP_DELETE, - ChatPrompt::CURSOROP_DIR_RIGHT, - ChatPrompt::CURSOROP_SCOPE_LINE); + prompt.cursorOperation( + ChatPrompt::CURSOROP_DELETE, + ChatPrompt::CURSOROP_DIR_RIGHT, + ChatPrompt::CURSOROP_SCOPE_LINE); return true; - } else if (event.KeyInput.Key == KEY_TAB) { + } + else if(event.KeyInput.Key == KEY_TAB) + { // Tab or Shift-Tab pressed // Nick completion - std::list names = - m_client->getConnectedPlayerNames(); + std::list names = m_client->getConnectedPlayerNames(); bool backwards = event.KeyInput.Shift; prompt.nickCompletion(names, backwards); return true; } else if (!iswcntrl(event.KeyInput.Char) && !event.KeyInput.Control) { -#if defined(__linux__) && (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9) - wchar_t wc = L'_'; - mbtowc(&wc, (char *)&event.KeyInput.Char, - sizeof(event.KeyInput.Char)); - prompt.input(wc); -#else - prompt.input(event.KeyInput.Char); -#endif + #if defined(__linux__) && (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9) + wchar_t wc = L'_'; + mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); + prompt.input(wc); + #else + prompt.input(event.KeyInput.Char); + #endif return true; } - } else if (event.EventType == EET_MOUSE_INPUT_EVENT) { - if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { + } + else if(event.EventType == EET_MOUSE_INPUT_EVENT) + { + if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) + { s32 rows = myround(-3.0 * event.MouseInput.Wheel); m_chat_backend->scroll(rows); } @@ -553,3 +643,4 @@ void GUIChatConsole::setVisible(bool visible) recalculateConsolePosition(); } } + diff --git a/src/gui/guiChatConsole.h b/src/gui/guiChatConsole.h index adf89e88c..7be40e27c 100644 --- a/src/gui/guiChatConsole.h +++ b/src/gui/guiChatConsole.h @@ -29,8 +29,12 @@ class Client; class GUIChatConsole : public gui::IGUIElement { public: - GUIChatConsole(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - ChatBackend *backend, Client *client, IMenuManager *menumgr); + GUIChatConsole(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, + s32 id, + ChatBackend* backend, + Client* client, + IMenuManager* menumgr); virtual ~GUIChatConsole(); // Open the console (height = desired fraction of screen size) @@ -59,15 +63,18 @@ class GUIChatConsole : public gui::IGUIElement void replaceAndAddToHistory(const std::wstring &line); // Change how the cursor looks - void setCursor(bool visible, bool blinking = false, f32 blink_speed = 1.0, - f32 relative_height = 1.0); + void setCursor( + bool visible, + bool blinking = false, + f32 blink_speed = 1.0, + f32 relative_height = 1.0); // Irrlicht draw method virtual void draw(); - bool canTakeFocus(gui::IGUIElement *element) { return false; } + bool canTakeFocus(gui::IGUIElement* element) { return false; } - virtual bool OnEvent(const SEvent &event); + virtual bool OnEvent(const SEvent& event); virtual void setVisible(bool visible); @@ -82,9 +89,9 @@ class GUIChatConsole : public gui::IGUIElement void drawPrompt(); private: - ChatBackend *m_chat_backend; - Client *m_client; - IMenuManager *m_menumgr; + ChatBackend* m_chat_backend; + Client* m_client; + IMenuManager* m_menumgr; // current screen size v2u32 m_screensize; diff --git a/src/gui/guiConfirmRegistration.cpp b/src/gui/guiConfirmRegistration.cpp index d4679b5dc..55c111df8 100644 --- a/src/gui/guiConfirmRegistration.cpp +++ b/src/gui/guiConfirmRegistration.cpp @@ -39,8 +39,8 @@ const int ID_message = 266; GUIConfirmRegistration::GUIConfirmRegistration(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, Client *client, - const std::string &playername, const std::string &password, bool *aborted, - ISimpleTextureSource *tsrc) : + const std::string &playername, const std::string &password, + bool *aborted, ISimpleTextureSource *tsrc) : GUIModalMenu(env, parent, id, menumgr), m_client(client), m_playername(playername), m_password(password), m_aborted(aborted), m_tsrc(tsrc) @@ -74,9 +74,12 @@ void GUIConfirmRegistration::regenerateGui(v2u32 screensize) Calculate new sizes and positions */ const float s = m_gui_scale; - DesiredRect = core::rect(screensize.X / 2 - 600 * s / 2, - screensize.Y / 2 - 360 * s / 2, screensize.X / 2 + 600 * s / 2, - screensize.Y / 2 + 360 * s / 2); + DesiredRect = core::rect( + screensize.X / 2 - 600 * s / 2, + screensize.Y / 2 - 360 * s / 2, + screensize.X / 2 + 600 * s / 2, + screensize.Y / 2 + 360 * s / 2 + ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); @@ -92,14 +95,11 @@ void GUIConfirmRegistration::regenerateGui(v2u32 screensize) core::rect rect2(0, 0, 540 * s, 180 * s); rect2 += topleft_client + v2s32(30 * s, ypos); static const std::string info_text_template = strgettext( - "You are about to join this server with the name \"%s\" " - "for the " + "You are about to join this server with the name \"%s\" for the " "first time.\n" - "If you proceed, a new account using your credentials " - "will be " + "If you proceed, a new account using your credentials will be " "created on this server.\n" - "Please retype your password and click 'Register and " - "Join' to " + "Please retype your password and click 'Register and Join' to " "confirm account creation, or click 'Cancel' to abort."); char info_text_buf[1024]; porting::mt_snprintf(info_text_buf, sizeof(info_text_buf), @@ -223,7 +223,7 @@ bool GUIConfirmRegistration::OnEvent(const SEvent &event) if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { infostream << "GUIConfirmRegistration: Not allowing focus change." - << std::endl; + << std::endl; // Returning true disables focus change return true; } diff --git a/src/gui/guiEditBoxWithScrollbar.cpp b/src/gui/guiEditBoxWithScrollbar.cpp index c803ba58c..442406688 100644 --- a/src/gui/guiEditBoxWithScrollbar.cpp +++ b/src/gui/guiEditBoxWithScrollbar.cpp @@ -17,30 +17,31 @@ todo: optional scrollbars [done] ctrl+left/right to select word -double click/ctrl click: word select + drag to select whole words, triple click to select -line optional? dragging selected text numerical +double click/ctrl click: word select + drag to select whole words, triple click to select line +optional? dragging selected text +numerical */ + //! constructor -GUIEditBoxWithScrollBar::GUIEditBoxWithScrollBar(const wchar_t *text, bool border, - IGUIEnvironment *environment, IGUIElement *parent, s32 id, - const core::rect &rectangle, bool writable, bool has_vscrollbar) : - IGUIEditBox(environment, parent, id, rectangle), - m_mouse_marking(false), m_border(border), m_background(true), - m_override_color_enabled(false), m_mark_begin(0), m_mark_end(0), - m_override_color(video::SColor(101, 255, 255, 255)), m_override_font(0), - m_last_break_font(0), m_operator(0), m_blink_start_time(0), - m_cursor_pos(0), m_hscroll_pos(0), m_vscroll_pos(0), m_max(0), - m_word_wrap(false), m_multiline(false), m_autoscroll(true), - m_passwordbox(false), m_passwordchar(L'*'), m_halign(EGUIA_UPPERLEFT), - m_valign(EGUIA_CENTER), m_current_text_rect(0, 0, 1, 1), - m_frame_rect(rectangle), m_scrollbar_width(0), m_vscrollbar(NULL), - m_writable(writable), m_bg_color_used(false) +GUIEditBoxWithScrollBar::GUIEditBoxWithScrollBar(const wchar_t* text, bool border, + IGUIEnvironment* environment, IGUIElement* parent, s32 id, + const core::rect& rectangle, bool writable, bool has_vscrollbar) + : IGUIEditBox(environment, parent, id, rectangle), m_mouse_marking(false), + m_border(border), m_background(true), m_override_color_enabled(false), m_mark_begin(0), m_mark_end(0), + m_override_color(video::SColor(101, 255, 255, 255)), m_override_font(0), m_last_break_font(0), + m_operator(0), m_blink_start_time(0), m_cursor_pos(0), m_hscroll_pos(0), m_vscroll_pos(0), m_max(0), + m_word_wrap(false), m_multiline(false), m_autoscroll(true), m_passwordbox(false), + m_passwordchar(L'*'), m_halign(EGUIA_UPPERLEFT), m_valign(EGUIA_CENTER), + m_current_text_rect(0, 0, 1, 1), m_frame_rect(rectangle), + m_scrollbar_width(0), m_vscrollbar(NULL), m_writable(writable), + m_bg_color_used(false) { #ifdef _DEBUG setDebugName("GUIEditBoxWithScrollBar"); #endif + Text = text; if (Environment) @@ -64,6 +65,7 @@ GUIEditBoxWithScrollBar::GUIEditBoxWithScrollBar(const wchar_t *text, bool borde setWritable(writable); } + //! destructor GUIEditBoxWithScrollBar::~GUIEditBoxWithScrollBar() { @@ -77,8 +79,9 @@ GUIEditBoxWithScrollBar::~GUIEditBoxWithScrollBar() m_vscrollbar->drop(); } + //! Sets another skin independent font. -void GUIEditBoxWithScrollBar::setOverrideFont(IGUIFont *font) +void GUIEditBoxWithScrollBar::setOverrideFont(IGUIFont* font) { if (m_override_font == font) return; @@ -95,17 +98,17 @@ void GUIEditBoxWithScrollBar::setOverrideFont(IGUIFont *font) } //! Gets the override font (if any) -IGUIFont *GUIEditBoxWithScrollBar::getOverrideFont() const +IGUIFont * GUIEditBoxWithScrollBar::getOverrideFont() const { return m_override_font; } //! Get the font which is used right now for drawing -IGUIFont *GUIEditBoxWithScrollBar::getActiveFont() const +IGUIFont* GUIEditBoxWithScrollBar::getActiveFont() const { if (m_override_font) return m_override_font; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; @@ -118,11 +121,13 @@ void GUIEditBoxWithScrollBar::setOverrideColor(video::SColor color) m_override_color_enabled = true; } + video::SColor GUIEditBoxWithScrollBar::getOverrideColor() const { return m_override_color; } + //! Turns the border on or off void GUIEditBoxWithScrollBar::setDrawBorder(bool border) { @@ -153,6 +158,7 @@ void GUIEditBoxWithScrollBar::setWordWrap(bool enable) breakText(); } + void GUIEditBoxWithScrollBar::updateAbsolutePosition() { core::rect old_absolute_rect(AbsoluteRect); @@ -170,18 +176,21 @@ bool GUIEditBoxWithScrollBar::isWordWrapEnabled() const return m_word_wrap; } + //! Enables or disables newlines. void GUIEditBoxWithScrollBar::setMultiLine(bool enable) { m_multiline = enable; } + //! Checks if multi line editing is enabled bool GUIEditBoxWithScrollBar::isMultiLineEnabled() const { return m_multiline; } + void GUIEditBoxWithScrollBar::setPasswordBox(bool password_box, wchar_t password_char) { m_passwordbox = password_box; @@ -193,24 +202,27 @@ void GUIEditBoxWithScrollBar::setPasswordBox(bool password_box, wchar_t password } } + bool GUIEditBoxWithScrollBar::isPasswordBox() const { return m_passwordbox; } + //! Sets text justification -void GUIEditBoxWithScrollBar::setTextAlignment( - EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) +void GUIEditBoxWithScrollBar::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { m_halign = horizontal; m_valign = vertical; } + //! called if an event happened. -bool GUIEditBoxWithScrollBar::OnEvent(const SEvent &event) +bool GUIEditBoxWithScrollBar::OnEvent(const SEvent& event) { if (isEnabled()) { - switch (event.EventType) { + switch (event.EventType) + { case EET_GUI_EVENT: if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (event.GUIEvent.Caller == this) { @@ -235,7 +247,8 @@ bool GUIEditBoxWithScrollBar::OnEvent(const SEvent &event) return IGUIElement::OnEvent(event); } -bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) + +bool GUIEditBoxWithScrollBar::processKey(const SEvent& event) { if (!m_writable) { return false; @@ -266,13 +279,10 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) break; case KEY_KEY_C: // copy to clipboard - if (!m_passwordbox && m_operator && m_mark_begin != m_mark_end) { - const s32 realmbgn = m_mark_begin < m_mark_end - ? m_mark_begin - : m_mark_end; - const s32 realmend = m_mark_begin < m_mark_end - ? m_mark_end - : m_mark_begin; + if (!m_passwordbox && m_operator && m_mark_begin != m_mark_end) + { + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; core::stringc s; s = Text.subString(realmbgn, realmend - realmbgn).c_str(); @@ -282,25 +292,20 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) case KEY_KEY_X: // cut to the clipboard if (!m_passwordbox && m_operator && m_mark_begin != m_mark_end) { - const s32 realmbgn = m_mark_begin < m_mark_end - ? m_mark_begin - : m_mark_end; - const s32 realmend = m_mark_begin < m_mark_end - ? m_mark_end - : m_mark_begin; + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; // copy core::stringc sc; - sc = Text.subString(realmbgn, realmend - realmbgn) - .c_str(); + sc = Text.subString(realmbgn, realmend - realmbgn).c_str(); m_operator->copyToClipboard(sc.c_str()); - if (isEnabled()) { + if (isEnabled()) + { // delete core::stringw s; s = Text.subString(0, realmbgn); - s.append(Text.subString(realmend, - Text.size() - realmend)); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn; @@ -316,28 +321,19 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) // paste from the clipboard if (m_operator) { - const s32 realmbgn = m_mark_begin < m_mark_end - ? m_mark_begin - : m_mark_end; - const s32 realmend = m_mark_begin < m_mark_end - ? m_mark_end - : m_mark_begin; + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; // add new character - const c8 *p = m_operator->getTextFromClipboard(); + const c8* p = m_operator->getTextFromClipboard(); if (p) { if (m_mark_begin == m_mark_end) { // insert text - core::stringw s = Text.subString( - 0, m_cursor_pos); + core::stringw s = Text.subString(0, m_cursor_pos); s.append(p); - s.append(Text.subString(m_cursor_pos, - Text.size() - m_cursor_pos)); + s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos)); - if (!m_max || s.size() <= m_max) // thx to - // Fish - // FH for - // fix + if (!m_max || s.size() <= m_max) // thx to Fish FH for fix { Text = s; s = p; @@ -346,21 +342,15 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) } else { // replace text - core::stringw s = Text.subString( - 0, realmbgn); + core::stringw s = Text.subString(0, realmbgn); s.append(p); - s.append(Text.subString(realmend, - Text.size() - realmend)); + s.append(Text.subString(realmend, Text.size() - realmend)); - if (!m_max || s.size() <= m_max) // thx to - // Fish - // FH for - // fix + if (!m_max || s.size() <= m_max) // thx to Fish FH for fix { Text = s; s = p; - m_cursor_pos = realmbgn + - s.size(); + m_cursor_pos = realmbgn + s.size(); } } } @@ -400,15 +390,14 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) } // default keyboard handling else - switch (event.KeyInput.Key) { - case KEY_END: { + switch (event.KeyInput.Key) { + case KEY_END: + { s32 p = Text.size(); if (m_word_wrap || m_multiline) { p = getLineFromPos(m_cursor_pos); - p = m_broken_text_positions[p] + - (s32)m_broken_text[p].size(); - if (p > 0 && (Text[p - 1] == L'\r' || - Text[p - 1] == L'\n')) + p = m_broken_text_positions[p] + (s32)m_broken_text[p].size(); + if (p > 0 && (Text[p - 1] == L'\r' || Text[p - 1] == L'\n')) p -= 1; } @@ -423,8 +412,10 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) } m_cursor_pos = p; m_blink_start_time = porting::getTimeMs(); - } break; - case KEY_HOME: { + } + break; + case KEY_HOME: + { s32 p = 0; if (m_word_wrap || m_multiline) { @@ -442,7 +433,8 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) } m_cursor_pos = p; m_blink_start_time = porting::getTimeMs(); - } break; + } + break; case KEY_RETURN: if (m_multiline) { inputChar(L'\n'); @@ -490,25 +482,13 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) case KEY_UP: if (m_multiline || (m_word_wrap && m_broken_text.size() > 1)) { s32 lineNo = getLineFromPos(m_cursor_pos); - s32 mb = (m_mark_begin == m_mark_end) - ? m_cursor_pos - : (m_mark_begin > m_mark_end ? m_mark_begin - : m_mark_end); - if (lineNo > 0) { - s32 cp = m_cursor_pos - - m_broken_text_positions[lineNo]; + s32 mb = (m_mark_begin == m_mark_end) ? m_cursor_pos : (m_mark_begin > m_mark_end ? m_mark_begin : m_mark_end); + if (lineNo > 0) { + s32 cp = m_cursor_pos - m_broken_text_positions[lineNo]; if ((s32)m_broken_text[lineNo - 1].size() < cp) - m_cursor_pos = m_broken_text_positions - [lineNo - 1] + - core::max_((u32)1, - m_broken_text[lineNo - - 1] - .size()) - - 1; + m_cursor_pos = m_broken_text_positions[lineNo - 1] + core::max_((u32)1, m_broken_text[lineNo - 1].size()) - 1; else - m_cursor_pos = m_broken_text_positions - [lineNo - 1] + - cp; + m_cursor_pos = m_broken_text_positions[lineNo - 1] + cp; } if (event.KeyInput.Shift) { @@ -525,25 +505,14 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) case KEY_DOWN: if (m_multiline || (m_word_wrap && m_broken_text.size() > 1)) { s32 lineNo = getLineFromPos(m_cursor_pos); - s32 mb = (m_mark_begin == m_mark_end) - ? m_cursor_pos - : (m_mark_begin < m_mark_end ? m_mark_begin - : m_mark_end); - if (lineNo < (s32)m_broken_text.size() - 1) { - s32 cp = m_cursor_pos - - m_broken_text_positions[lineNo]; + s32 mb = (m_mark_begin == m_mark_end) ? m_cursor_pos : (m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end); + if (lineNo < (s32)m_broken_text.size() - 1) + { + s32 cp = m_cursor_pos - m_broken_text_positions[lineNo]; if ((s32)m_broken_text[lineNo + 1].size() < cp) - m_cursor_pos = m_broken_text_positions - [lineNo + 1] + - core::max_((u32)1, - m_broken_text[lineNo + - 1] - .size()) - - 1; + m_cursor_pos = m_broken_text_positions[lineNo + 1] + core::max_((u32)1, m_broken_text[lineNo + 1].size()) - 1; else - m_cursor_pos = m_broken_text_positions - [lineNo + 1] + - cp; + m_cursor_pos = m_broken_text_positions[lineNo + 1] + cp; } if (event.KeyInput.Shift) { @@ -568,18 +537,11 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) if (m_mark_begin != m_mark_end) { // delete marked text - const s32 realmbgn = - m_mark_begin < m_mark_end - ? m_mark_begin - : m_mark_end; - const s32 realmend = - m_mark_begin < m_mark_end - ? m_mark_end - : m_mark_begin; + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; s = Text.subString(0, realmbgn); - s.append(Text.subString(realmend, - Text.size() - realmend)); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn; @@ -589,16 +551,14 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) s = Text.subString(0, m_cursor_pos - 1); else s = L""; - s.append(Text.subString(m_cursor_pos, - Text.size() - m_cursor_pos)); + s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos)); Text = s; --m_cursor_pos; } if (m_cursor_pos < 0) m_cursor_pos = 0; - m_blink_start_time = porting:: - getTimeMs(); // os::Timer::getTime(); + m_blink_start_time = porting::getTimeMs(); // os::Timer::getTime(); new_mark_begin = 0; new_mark_end = 0; text_changed = true; @@ -613,34 +573,25 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) if (m_mark_begin != m_mark_end) { // delete marked text - const s32 realmbgn = - m_mark_begin < m_mark_end - ? m_mark_begin - : m_mark_end; - const s32 realmend = - m_mark_begin < m_mark_end - ? m_mark_end - : m_mark_begin; + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; s = Text.subString(0, realmbgn); - s.append(Text.subString(realmend, - Text.size() - realmend)); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn; } else { // delete text before cursor s = Text.subString(0, m_cursor_pos); - s.append(Text.subString(m_cursor_pos + 1, - Text.size() - m_cursor_pos - 1)); + s.append(Text.subString(m_cursor_pos + 1, Text.size() - m_cursor_pos - 1)); Text = s; } if (m_cursor_pos > (s32)Text.size()) m_cursor_pos = (s32)Text.size(); - m_blink_start_time = porting:: - getTimeMs(); // os::Timer::getTime(); + m_blink_start_time = porting::getTimeMs(); // os::Timer::getTime(); new_mark_begin = 0; new_mark_end = 0; text_changed = true; @@ -690,13 +641,16 @@ bool GUIEditBoxWithScrollBar::processKey(const SEvent &event) breakText(); calculateScrollPos(); sendGuiEvent(EGET_EDITBOX_CHANGED); - } else { + } + else + { calculateScrollPos(); } return true; } + //! draws the element and its children void GUIEditBoxWithScrollBar::draw() { @@ -705,7 +659,7 @@ void GUIEditBoxWithScrollBar::draw() const bool focus = Environment->hasFocus(this); - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (!skin) return; @@ -716,8 +670,7 @@ void GUIEditBoxWithScrollBar::draw() bg_color = m_bg_color_used ? m_bg_color : default_bg_color; if (!m_border && m_background) { - skin->draw2DRectangle( - this, bg_color, AbsoluteRect, &AbsoluteClippingRect); + skin->draw2DRectangle(this, bg_color, AbsoluteRect, &AbsoluteClippingRect); } // draw the border @@ -726,7 +679,7 @@ void GUIEditBoxWithScrollBar::draw() if (m_writable) { skin->draw3DSunkenPane(this, bg_color, false, m_background, - AbsoluteRect, &AbsoluteClippingRect); + AbsoluteRect, &AbsoluteClippingRect); } calculateFrameRect(); @@ -737,7 +690,7 @@ void GUIEditBoxWithScrollBar::draw() // draw the text - IGUIFont *font = getActiveFont(); + IGUIFont* font = getActiveFont(); s32 cursor_line = 0; s32 charcursorpos = 0; @@ -756,13 +709,10 @@ void GUIEditBoxWithScrollBar::draw() // get mark position const bool ml = (!m_passwordbox && (m_word_wrap || m_multiline)); - const s32 realmbgn = - m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; - const s32 realmend = - m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; const s32 hline_start = ml ? getLineFromPos(realmbgn) : 0; - const s32 hline_count = - ml ? getLineFromPos(realmend) - hline_start + 1 : 1; + const s32 hline_count = ml ? getLineFromPos(realmend) - hline_start + 1 : 1; const s32 line_count = ml ? m_broken_text.size() : 1; // Save the override color information. @@ -779,8 +729,7 @@ void GUIEditBoxWithScrollBar::draw() for (s32 i = 0; i < line_count; ++i) { setTextRect(i); - // clipping test - don't draw anything outside the visible - // area + // clipping test - don't draw anything outside the visible area core::rect c = local_clip_rect; c.clipAgainst(m_current_text_rect); if (!c.isValid()) @@ -792,11 +741,11 @@ void GUIEditBoxWithScrollBar::draw() m_broken_text.clear(); m_broken_text.emplace_back(); } - if (m_broken_text[0].size() != Text.size()) { + if (m_broken_text[0].size() != Text.size()){ m_broken_text[0] = Text; - for (u32 q = 0; q < Text.size(); ++q) { - m_broken_text[0][q] = - m_passwordchar; + for (u32 q = 0; q < Text.size(); ++q) + { + m_broken_text[0][q] = m_passwordchar; } } txt_line = &m_broken_text[0]; @@ -806,77 +755,55 @@ void GUIEditBoxWithScrollBar::draw() start_pos = ml ? m_broken_text_positions[i] : 0; } + // draw normal text font->draw(txt_line->c_str(), m_current_text_rect, - m_override_color_enabled - ? m_override_color - : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &local_clip_rect); + m_override_color_enabled ? m_override_color : skin->getColor(EGDC_BUTTON_TEXT), + false, true, &local_clip_rect); // draw mark and marked text - if (focus && m_mark_begin != m_mark_end && - i >= hline_start && - i < hline_start + hline_count) { + if (focus && m_mark_begin != m_mark_end && i >= hline_start && i < hline_start + hline_count) { s32 mbegin = 0, mend = 0; - s32 lineStartPos = 0, - lineEndPos = txt_line->size(); + s32 lineStartPos = 0, lineEndPos = txt_line->size(); if (i == hline_start) { // highlight start is on this line - s = txt_line->subString( - 0, realmbgn - start_pos); - mbegin = font->getDimension(s.c_str()) - .Width; + s = txt_line->subString(0, realmbgn - start_pos); + mbegin = font->getDimension(s.c_str()).Width; // deal with kerning mbegin += font->getKerningWidth( - &((*txt_line)[realmbgn - - start_pos]), - realmbgn - start_pos > 0 - ? &((*txt_line)[realmbgn - - start_pos - - 1]) - : 0); + &((*txt_line)[realmbgn - start_pos]), + realmbgn - start_pos > 0 ? &((*txt_line)[realmbgn - start_pos - 1]) : 0); lineStartPos = realmbgn - start_pos; } if (i == hline_start + hline_count - 1) { // highlight end is on this line - s2 = txt_line->subString( - 0, realmend - start_pos); - mend = font->getDimension(s2.c_str()) - .Width; + s2 = txt_line->subString(0, realmend - start_pos); + mend = font->getDimension(s2.c_str()).Width; lineEndPos = (s32)s2.size(); } else { - mend = font->getDimension(txt_line->c_str()) - .Width; + mend = font->getDimension(txt_line->c_str()).Width; } + m_current_text_rect.UpperLeftCorner.X += mbegin; - m_current_text_rect.LowerRightCorner.X = - m_current_text_rect - .UpperLeftCorner - .X + - mend - mbegin; + m_current_text_rect.LowerRightCorner.X = m_current_text_rect.UpperLeftCorner.X + mend - mbegin; + // draw mark - skin->draw2DRectangle(this, - skin->getColor(EGDC_HIGH_LIGHT), - m_current_text_rect, - &local_clip_rect); + skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), m_current_text_rect, &local_clip_rect); // draw marked text - s = txt_line->subString(lineStartPos, - lineEndPos - lineStartPos); + s = txt_line->subString(lineStartPos, lineEndPos - lineStartPos); if (s.size()) font->draw(s.c_str(), m_current_text_rect, - m_override_color_enabled - ? m_override_color - : skin->getColor(EGDC_HIGH_LIGHT_TEXT), - false, true, - &local_clip_rect); + m_override_color_enabled ? m_override_color : skin->getColor(EGDC_HIGH_LIGHT_TEXT), + false, true, &local_clip_rect); + } } @@ -894,23 +821,15 @@ void GUIEditBoxWithScrollBar::draw() } s = txt_line->subString(0, m_cursor_pos - start_pos); charcursorpos = font->getDimension(s.c_str()).Width + - font->getKerningWidth(L"_", - m_cursor_pos - start_pos > 0 - ? &((*txt_line)[m_cursor_pos - - start_pos - - 1]) - : 0); - - if (focus && (porting::getTimeMs() - m_blink_start_time) % 700 < - 350) { + font->getKerningWidth(L"_", m_cursor_pos - start_pos > 0 ? &((*txt_line)[m_cursor_pos - start_pos - 1]) : 0); + + if (focus && (porting::getTimeMs() - m_blink_start_time) % 700 < 350) { setTextRect(cursor_line); m_current_text_rect.UpperLeftCorner.X += charcursorpos; font->draw(L"_", m_current_text_rect, - m_override_color_enabled - ? m_override_color - : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &local_clip_rect); + m_override_color_enabled ? m_override_color : skin->getColor(EGDC_BUTTON_TEXT), + false, true, &local_clip_rect); } } } @@ -919,8 +838,9 @@ void GUIEditBoxWithScrollBar::draw() IGUIElement::draw(); } + //! Sets the new caption of this element. -void GUIEditBoxWithScrollBar::setText(const wchar_t *text) +void GUIEditBoxWithScrollBar::setText(const wchar_t* text) { Text = text; if (u32(m_cursor_pos) > Text.size()) @@ -929,6 +849,7 @@ void GUIEditBoxWithScrollBar::setText(const wchar_t *text) breakText(); } + //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position void GUIEditBoxWithScrollBar::setAutoScroll(bool enable) @@ -936,6 +857,7 @@ void GUIEditBoxWithScrollBar::setAutoScroll(bool enable) m_autoscroll = enable; } + //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not bool GUIEditBoxWithScrollBar::isAutoScrollEnabled() const @@ -943,6 +865,7 @@ bool GUIEditBoxWithScrollBar::isAutoScrollEnabled() const return m_autoscroll; } + //! Gets the area of the text in the edit box //! \return Returns the size in pixels of the text core::dimension2du GUIEditBoxWithScrollBar::getTextDimension() @@ -961,6 +884,7 @@ core::dimension2du GUIEditBoxWithScrollBar::getTextDimension() return core::dimension2du(ret.getSize()); } + //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. @@ -972,19 +896,21 @@ void GUIEditBoxWithScrollBar::setMax(u32 max) Text = Text.subString(0, m_max); } + //! Returns maximum amount of characters, previously set by setMax(); u32 GUIEditBoxWithScrollBar::getMax() const { return m_max; } -bool GUIEditBoxWithScrollBar::processMouse(const SEvent &event) + +bool GUIEditBoxWithScrollBar::processMouse(const SEvent& event) { - switch (event.MouseInput.Event) { + switch (event.MouseInput.Event) + { case irr::EMIE_LMOUSE_LEFT_UP: if (Environment->hasFocus(this)) { - m_cursor_pos = getCursorPos( - event.MouseInput.X, event.MouseInput.Y); + m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); if (m_mouse_marking) { setTextMarkers(m_mark_begin, m_cursor_pos); } @@ -993,33 +919,32 @@ bool GUIEditBoxWithScrollBar::processMouse(const SEvent &event) return true; } break; - case irr::EMIE_MOUSE_MOVED: { + case irr::EMIE_MOUSE_MOVED: + { if (m_mouse_marking) { - m_cursor_pos = getCursorPos( - event.MouseInput.X, event.MouseInput.Y); + m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); setTextMarkers(m_mark_begin, m_cursor_pos); calculateScrollPos(); return true; } - } break; + } + break; case EMIE_LMOUSE_PRESSED_DOWN: if (!Environment->hasFocus(this)) { m_blink_start_time = porting::getTimeMs(); m_mouse_marking = true; - m_cursor_pos = getCursorPos( - event.MouseInput.X, event.MouseInput.Y); + m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); setTextMarkers(m_cursor_pos, m_cursor_pos); calculateScrollPos(); return true; } else { - if (!AbsoluteClippingRect.isPointInside(core::position2d( - event.MouseInput.X, event.MouseInput.Y))) { + if (!AbsoluteClippingRect.isPointInside( + core::position2d(event.MouseInput.X, event.MouseInput.Y))) { return false; } else { // move cursor - m_cursor_pos = getCursorPos( - event.MouseInput.X, event.MouseInput.Y); + m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); s32 newMarkBegin = m_mark_begin; if (!m_mouse_marking) @@ -1038,9 +963,10 @@ bool GUIEditBoxWithScrollBar::processMouse(const SEvent &event) return false; } + s32 GUIEditBoxWithScrollBar::getCursorPos(s32 x, s32 y) { - IGUIFont *font = getActiveFont(); + IGUIFont* font = getActiveFont(); const u32 line_count = (m_word_wrap || m_multiline) ? m_broken_text.size() : 1; @@ -1056,14 +982,10 @@ s32 GUIEditBoxWithScrollBar::getCursorPos(s32 x, s32 y) y = m_current_text_rect.LowerRightCorner.Y; // is it inside this region? - if (y >= m_current_text_rect.UpperLeftCorner.Y && - y <= m_current_text_rect.LowerRightCorner.Y) { + if (y >= m_current_text_rect.UpperLeftCorner.Y && y <= m_current_text_rect.LowerRightCorner.Y) { // we've found the clicked line - txt_line = (m_word_wrap || m_multiline) ? &m_broken_text[i] - : &Text; - start_pos = (m_word_wrap || m_multiline) - ? m_broken_text_positions[i] - : 0; + txt_line = (m_word_wrap || m_multiline) ? &m_broken_text[i] : &Text; + start_pos = (m_word_wrap || m_multiline) ? m_broken_text_positions[i] : 0; break; } } @@ -1074,8 +996,7 @@ s32 GUIEditBoxWithScrollBar::getCursorPos(s32 x, s32 y) if (!txt_line) return 0; - s32 idx = font->getCharacterFromPos( - txt_line->c_str(), x - m_current_text_rect.UpperLeftCorner.X); + s32 idx = font->getCharacterFromPos(txt_line->c_str(), x - m_current_text_rect.UpperLeftCorner.X); // click was on or left of the line if (idx != -1) @@ -1085,6 +1006,7 @@ s32 GUIEditBoxWithScrollBar::getCursorPos(s32 x, s32 y) return txt_line->size() + start_pos; } + //! Breaks the single text line. void GUIEditBoxWithScrollBar::breakText() { @@ -1094,7 +1016,7 @@ void GUIEditBoxWithScrollBar::breakText() m_broken_text.clear(); // need to reallocate :/ m_broken_text_positions.clear(); - IGUIFont *font = getActiveFont(); + IGUIFont* font = getActiveFont(); if (!font) return; @@ -1118,11 +1040,9 @@ void GUIEditBoxWithScrollBar::breakText() line_break = true; c = 0; if (Text[i + 1] == L'\n') { // Windows breaks - // TODO: I (Michael) think that we shouldn't change the - // text given by the user for whatever reason. Instead - // rework the cursor positioning to be able to handle this - // (but not in stable release branch as users might - // already expect this behavior). + // TODO: I (Michael) think that we shouldn't change the text given by the user for whatever reason. + // Instead rework the cursor positioning to be able to handle this (but not in stable release + // branch as users might already expect this behavior). Text.erase(i + 1); --size; if (m_cursor_pos > i) @@ -1140,13 +1060,11 @@ void GUIEditBoxWithScrollBar::breakText() if (c == L' ' || c == 0 || i == (size - 1)) { // here comes the next whitespace, look if // we can break the last word to the next line - // We also break whitespace, otherwise cursor would vanish beside - // the right border. + // We also break whitespace, otherwise cursor would vanish beside the right border. s32 whitelgth = font->getDimension(whitespace.c_str()).Width; s32 worldlgth = font->getDimension(word.c_str()).Width; - if (m_word_wrap && length + worldlgth + whitelgth > el_width && - line.size() > 0) { + if (m_word_wrap && length + worldlgth + whitelgth > el_width && line.size() > 0) { // break to next line length = worldlgth; m_broken_text.push_back(line); @@ -1163,6 +1081,7 @@ void GUIEditBoxWithScrollBar::breakText() word = L""; whitespace = L""; + if (c) whitespace += c; @@ -1202,7 +1121,7 @@ void GUIEditBoxWithScrollBar::setTextRect(s32 line) if (line < 0) return; - IGUIFont *font = getActiveFont(); + IGUIFont* font = getActiveFont(); if (!font) return; @@ -1222,10 +1141,8 @@ void GUIEditBoxWithScrollBar::setTextRect(s32 line) switch (m_halign) { case EGUIA_CENTER: // align to h centre - m_current_text_rect.UpperLeftCorner.X = - (m_frame_rect.getWidth() / 2) - (d.Width / 2); - m_current_text_rect.LowerRightCorner.X = - (m_frame_rect.getWidth() / 2) + (d.Width / 2); + m_current_text_rect.UpperLeftCorner.X = (m_frame_rect.getWidth() / 2) - (d.Width / 2); + m_current_text_rect.LowerRightCorner.X = (m_frame_rect.getWidth() / 2) + (d.Width / 2); break; case EGUIA_LOWERRIGHT: // align to right edge @@ -1236,36 +1153,35 @@ void GUIEditBoxWithScrollBar::setTextRect(s32 line) // align to left edge m_current_text_rect.UpperLeftCorner.X = 0; m_current_text_rect.LowerRightCorner.X = d.Width; + } switch (m_valign) { case EGUIA_CENTER: // align to v centre - m_current_text_rect.UpperLeftCorner.Y = (m_frame_rect.getHeight() / 2) - - (line_count * d.Height) / 2 + - d.Height * line; + m_current_text_rect.UpperLeftCorner.Y = + (m_frame_rect.getHeight() / 2) - (line_count*d.Height) / 2 + d.Height*line; break; case EGUIA_LOWERRIGHT: // align to bottom edge - m_current_text_rect.UpperLeftCorner.Y = m_frame_rect.getHeight() - - line_count * d.Height + - d.Height * line; + m_current_text_rect.UpperLeftCorner.Y = + m_frame_rect.getHeight() - line_count*d.Height + d.Height*line; break; default: // align to top edge - m_current_text_rect.UpperLeftCorner.Y = d.Height * line; + m_current_text_rect.UpperLeftCorner.Y = d.Height*line; break; } m_current_text_rect.UpperLeftCorner.X -= m_hscroll_pos; m_current_text_rect.LowerRightCorner.X -= m_hscroll_pos; m_current_text_rect.UpperLeftCorner.Y -= m_vscroll_pos; - m_current_text_rect.LowerRightCorner.Y = - m_current_text_rect.UpperLeftCorner.Y + d.Height; + m_current_text_rect.LowerRightCorner.Y = m_current_text_rect.UpperLeftCorner.Y + d.Height; m_current_text_rect += m_frame_rect.UpperLeftCorner; } + s32 GUIEditBoxWithScrollBar::getLineFromPos(s32 pos) { if (!m_word_wrap && !m_multiline) @@ -1280,36 +1196,31 @@ s32 GUIEditBoxWithScrollBar::getLineFromPos(s32 pos) return (s32)m_broken_text_positions.size() - 1; } + void GUIEditBoxWithScrollBar::inputChar(wchar_t c) { if (!isEnabled()) return; - if (c != 0) { + if (c != 0) { if (Text.size() < m_max || m_max == 0) { core::stringw s; if (m_mark_begin != m_mark_end) { // replace marked text - const s32 realmbgn = m_mark_begin < m_mark_end - ? m_mark_begin - : m_mark_end; - const s32 realmend = m_mark_begin < m_mark_end - ? m_mark_end - : m_mark_begin; + const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; s = Text.subString(0, realmbgn); s.append(c); - s.append(Text.subString( - realmend, Text.size() - realmend)); + s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn + 1; } else { // add new character s = Text.subString(0, m_cursor_pos); s.append(c); - s.append(Text.subString(m_cursor_pos, - Text.size() - m_cursor_pos)); + s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos)); Text = s; ++m_cursor_pos; } @@ -1329,10 +1240,10 @@ void GUIEditBoxWithScrollBar::calculateScrollPos() if (!m_autoscroll) return; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (!skin) return; - IGUIFont *font = m_override_font ? m_override_font : skin->getFont(); + IGUIFont* font = m_override_font ? m_override_font : skin->getFont(); if (!font) return; @@ -1343,59 +1254,46 @@ void GUIEditBoxWithScrollBar::calculateScrollPos() const bool has_broken_text = m_multiline || m_word_wrap; // Check horizonal scrolling - // NOTE: Calculations different to vertical scrolling because setTextRect - // interprets VAlign relative to line but HAlign not relative to row + // NOTE: Calculations different to vertical scrolling because setTextRect interprets VAlign relative to line but HAlign not relative to row { // get cursor position - IGUIFont *font = getActiveFont(); + IGUIFont* font = getActiveFont(); if (!font) return; // get cursor area irr::u32 cursor_width = font->getDimension(L"_").Width; - core::stringw *txt_line = - has_broken_text ? &m_broken_text[curs_line] : &Text; - s32 cpos = has_broken_text ? m_cursor_pos - m_broken_text_positions - [curs_line] - : m_cursor_pos; // column - s32 cstart = font->getDimension(txt_line->subString(0, cpos).c_str()) - .Width; // pixels from text-start + core::stringw *txt_line = has_broken_text ? &m_broken_text[curs_line] : &Text; + s32 cpos = has_broken_text ? m_cursor_pos - m_broken_text_positions[curs_line] : m_cursor_pos; // column + s32 cstart = font->getDimension(txt_line->subString(0, cpos).c_str()).Width; // pixels from text-start s32 cend = cstart + cursor_width; s32 txt_width = font->getDimension(txt_line->c_str()).Width; if (txt_width < m_frame_rect.getWidth()) { - // TODO: Needs a clean left and right gap removal depending on - // HAlign, similar to vertical scrolling tests for top/bottom. - // This check just fixes the case where it was most noticable - // (text smaller than clipping area). + // TODO: Needs a clean left and right gap removal depending on HAlign, similar to vertical scrolling tests for top/bottom. + // This check just fixes the case where it was most noticable (text smaller than clipping area). m_hscroll_pos = 0; setTextRect(curs_line); } - if (m_current_text_rect.UpperLeftCorner.X + cstart < - m_frame_rect.UpperLeftCorner.X) { + if (m_current_text_rect.UpperLeftCorner.X + cstart < m_frame_rect.UpperLeftCorner.X) { // cursor to the left of the clipping area - m_hscroll_pos -= m_frame_rect.UpperLeftCorner.X - - (m_current_text_rect.UpperLeftCorner.X + cstart); + m_hscroll_pos -= m_frame_rect.UpperLeftCorner.X - (m_current_text_rect.UpperLeftCorner.X + cstart); setTextRect(curs_line); - // TODO: should show more characters to the left when we're - // scrolling left + // TODO: should show more characters to the left when we're scrolling left // and the cursor reaches the border. - } else if (m_current_text_rect.UpperLeftCorner.X + cend > - m_frame_rect.LowerRightCorner.X) { + } else if (m_current_text_rect.UpperLeftCorner.X + cend > m_frame_rect.LowerRightCorner.X) { // cursor to the right of the clipping area - m_hscroll_pos += (m_current_text_rect.UpperLeftCorner.X + cend) - - m_frame_rect.LowerRightCorner.X; + m_hscroll_pos += (m_current_text_rect.UpperLeftCorner.X + cend) - m_frame_rect.LowerRightCorner.X; setTextRect(curs_line); } } // calculate vertical scrolling if (has_broken_text) { - irr::u32 line_height = font->getDimension(L"A").Height + - font->getKerningHeight(); + irr::u32 line_height = font->getDimension(L"A").Height + font->getKerningHeight(); // only up to 1 line fits? if (line_height >= (irr::u32)m_frame_rect.getHeight()) { m_vscroll_pos = 0; @@ -1419,39 +1317,27 @@ void GUIEditBoxWithScrollBar::calculateScrollPos() } else { // First 2 checks are necessary when people delete lines setTextRect(0); - if (m_current_text_rect.UpperLeftCorner.Y > - m_frame_rect.UpperLeftCorner.Y && - m_valign != EGUIA_LOWERRIGHT) { + if (m_current_text_rect.UpperLeftCorner.Y > m_frame_rect.UpperLeftCorner.Y && m_valign != EGUIA_LOWERRIGHT) { // first line is leaving a gap on top m_vscroll_pos = 0; } else if (m_valign != EGUIA_UPPERLEFT) { - u32 lastLine = m_broken_text_positions.empty() - ? 0 - : m_broken_text_positions.size() - - 1; + u32 lastLine = m_broken_text_positions.empty() ? 0 : m_broken_text_positions.size() - 1; setTextRect(lastLine); - if (m_current_text_rect.LowerRightCorner.Y < - m_frame_rect.LowerRightCorner.Y) { + if (m_current_text_rect.LowerRightCorner.Y < m_frame_rect.LowerRightCorner.Y) + { // last line is leaving a gap on bottom - m_vscroll_pos -= m_frame_rect.LowerRightCorner.Y - - m_current_text_rect - .LowerRightCorner - .Y; + m_vscroll_pos -= m_frame_rect.LowerRightCorner.Y - m_current_text_rect.LowerRightCorner.Y; } } setTextRect(curs_line); - if (m_current_text_rect.UpperLeftCorner.Y < - m_frame_rect.UpperLeftCorner.Y) { + if (m_current_text_rect.UpperLeftCorner.Y < m_frame_rect.UpperLeftCorner.Y) { // text above valid area - m_vscroll_pos -= m_frame_rect.UpperLeftCorner.Y - - m_current_text_rect.UpperLeftCorner.Y; + m_vscroll_pos -= m_frame_rect.UpperLeftCorner.Y - m_current_text_rect.UpperLeftCorner.Y; setTextRect(curs_line); - } else if (m_current_text_rect.LowerRightCorner.Y > - m_frame_rect.LowerRightCorner.Y) { + } else if (m_current_text_rect.LowerRightCorner.Y > m_frame_rect.LowerRightCorner.Y){ // text below valid area - m_vscroll_pos += m_current_text_rect.LowerRightCorner.Y - - m_frame_rect.LowerRightCorner.Y; + m_vscroll_pos += m_current_text_rect.LowerRightCorner.Y - m_frame_rect.LowerRightCorner.Y; setTextRect(curs_line); } } @@ -1466,16 +1352,15 @@ void GUIEditBoxWithScrollBar::calculateFrameRect() { m_frame_rect = AbsoluteRect; + IGUISkin *skin = 0; if (Environment) skin = Environment->getSkin(); if (m_border && skin) { m_frame_rect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; m_frame_rect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; - m_frame_rect.LowerRightCorner.X -= - skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; - m_frame_rect.LowerRightCorner.Y -= - skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; + m_frame_rect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; + m_frame_rect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; } updateVScrollBar(); @@ -1518,8 +1403,8 @@ void GUIEditBoxWithScrollBar::createVScrollBar() irr::core::rect scrollbarrect = m_frame_rect; scrollbarrect.UpperLeftCorner.X += m_frame_rect.getWidth() - m_scrollbar_width; - m_vscrollbar = new GUIScrollBar( - Environment, getParent(), -1, scrollbarrect, false, true); + m_vscrollbar = new GUIScrollBar(Environment, getParent(), -1, + scrollbarrect, false, true); m_vscrollbar->setVisible(false); m_vscrollbar->setSmallStep(1); @@ -1551,7 +1436,7 @@ void GUIEditBoxWithScrollBar::updateVScrollBar() } // check if a vertical scrollbar is needed ? - if (getTextDimension().Height > (u32)m_frame_rect.getHeight()) { + if (getTextDimension().Height > (u32) m_frame_rect.getHeight()) { m_frame_rect.LowerRightCorner.X -= m_scrollbar_width; s32 scrollymax = getTextDimension().Height - m_frame_rect.getHeight(); @@ -1564,7 +1449,8 @@ void GUIEditBoxWithScrollBar::updateVScrollBar() m_vscrollbar->setVisible(true); } } else { - if (m_vscrollbar->isVisible()) { + if (m_vscrollbar->isVisible()) + { m_vscrollbar->setVisible(false); m_vscroll_pos = 0; m_vscrollbar->setPos(0); @@ -1572,6 +1458,7 @@ void GUIEditBoxWithScrollBar::updateVScrollBar() m_vscrollbar->setPageSize(s32(getTextDimension().Height)); } } + } //! set true if this editbox is writable @@ -1588,8 +1475,7 @@ void GUIEditBoxWithScrollBar::setBackgroundColor(const video::SColor &bg_color) } //! Writes attributes of the element. -void GUIEditBoxWithScrollBar::serializeAttributes( - io::IAttributes *out, io::SAttributeReadWriteOptions *options = 0) const +void GUIEditBoxWithScrollBar::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options = 0) const { // IGUIEditBox::serializeAttributes(out,options); @@ -1613,9 +1499,9 @@ void GUIEditBoxWithScrollBar::serializeAttributes( IGUIEditBox::serializeAttributes(out, options); } + //! Reads attributes of the element -void GUIEditBoxWithScrollBar::deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0) +void GUIEditBoxWithScrollBar::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options = 0) { IGUIEditBox::deserializeAttributes(in, options); @@ -1634,34 +1520,16 @@ void GUIEditBoxWithScrollBar::deserializeAttributes( else setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]); - setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration( - "HTextAlign", GUIAlignmentNames), - (EGUI_ALIGNMENT)in->getAttributeAsEnumeration( - "VTextAlign", GUIAlignmentNames)); + setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), + (EGUI_ALIGNMENT)in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); // setOverrideFont(in->getAttributeAsFont("OverrideFont")); setWritable(in->getAttributeAsBool("Writable")); } -bool GUIEditBoxWithScrollBar::isDrawBackgroundEnabled() const -{ - return false; -} -bool GUIEditBoxWithScrollBar::isDrawBorderEnabled() const -{ - return false; -} -void GUIEditBoxWithScrollBar::setCursorChar(const wchar_t cursorChar) -{ -} -wchar_t GUIEditBoxWithScrollBar::getCursorChar() const -{ - return '|'; -} -void GUIEditBoxWithScrollBar::setCursorBlinkTime(irr::u32 timeMs) -{ -} -irr::u32 GUIEditBoxWithScrollBar::getCursorBlinkTime() const -{ - return 500; -} +bool GUIEditBoxWithScrollBar::isDrawBackgroundEnabled() const { return false; } +bool GUIEditBoxWithScrollBar::isDrawBorderEnabled() const { return false; } +void GUIEditBoxWithScrollBar::setCursorChar(const wchar_t cursorChar) { } +wchar_t GUIEditBoxWithScrollBar::getCursorChar() const { return '|'; } +void GUIEditBoxWithScrollBar::setCursorBlinkTime(irr::u32 timeMs) { } +irr::u32 GUIEditBoxWithScrollBar::getCursorBlinkTime() const { return 500; } diff --git a/src/gui/guiEditBoxWithScrollbar.h b/src/gui/guiEditBoxWithScrollbar.h index ff98fe4cb..77538e2f7 100644 --- a/src/gui/guiEditBoxWithScrollbar.h +++ b/src/gui/guiEditBoxWithScrollbar.h @@ -16,26 +16,26 @@ using namespace irr::gui; class GUIEditBoxWithScrollBar : public IGUIEditBox { public: + //! constructor - GUIEditBoxWithScrollBar(const wchar_t *text, bool border, - IGUIEnvironment *environment, IGUIElement *parent, s32 id, - const core::rect &rectangle, bool writable = true, - bool has_vscrollbar = true); + GUIEditBoxWithScrollBar(const wchar_t* text, bool border, IGUIEnvironment* environment, + IGUIElement* parent, s32 id, const core::rect& rectangle, + bool writable = true, bool has_vscrollbar = true); //! destructor virtual ~GUIEditBoxWithScrollBar(); //! Sets another skin independent font. - virtual void setOverrideFont(IGUIFont *font = 0); + virtual void setOverrideFont(IGUIFont* font = 0); //! Gets the override font (if any) /** \return The override font (may be 0) */ - virtual IGUIFont *getOverrideFont() const; + virtual IGUIFont* getOverrideFont() const; //! Get the font which is used right now for drawing /** Currently this is the override font when one is set and the font of the active skin otherwise */ - virtual IGUIFont *getActiveFont() const; + virtual IGUIFont* getActiveFont() const; //! Sets another color for the text. virtual void setOverrideColor(video::SColor color); @@ -74,8 +74,7 @@ class GUIEditBoxWithScrollBar : public IGUIEditBox virtual bool isMultiLineEnabled() const; //! Enables or disables automatic scrolling with cursor position - //! \param enable: If set to true, the text will move around with the cursor - //! position + //! \param enable: If set to true, the text will move around with the cursor position virtual void setAutoScroll(bool enable); //! Checks to see if automatic scrolling is enabled @@ -90,13 +89,13 @@ class GUIEditBoxWithScrollBar : public IGUIEditBox virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); //! called if an event happened. - virtual bool OnEvent(const SEvent &event); + virtual bool OnEvent(const SEvent& event); //! draws the element and its children virtual void draw(); //! Sets the new caption of this element. - virtual void setText(const wchar_t *text); + virtual void setText(const wchar_t* text); //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is @@ -124,12 +123,10 @@ class GUIEditBoxWithScrollBar : public IGUIEditBox virtual void setBackgroundColor(const video::SColor &bg_color); //! Writes attributes of the element. - virtual void serializeAttributes(io::IAttributes *out, - io::SAttributeReadWriteOptions *options) const; + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; //! Reads attributes of the element - virtual void deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options); + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); virtual bool isDrawBackgroundEnabled() const; virtual bool isDrawBorderEnabled() const; @@ -160,8 +157,8 @@ class GUIEditBoxWithScrollBar : public IGUIEditBox //! update the vertical scrollBar (visibilty & position) void updateVScrollBar(); - bool processKey(const SEvent &event); - bool processMouse(const SEvent &event); + bool processKey(const SEvent& event); + bool processMouse(const SEvent& event); s32 getCursorPos(s32 x, s32 y); bool m_mouse_marking; @@ -173,7 +170,7 @@ class GUIEditBoxWithScrollBar : public IGUIEditBox video::SColor m_override_color; gui::IGUIFont *m_override_font, *m_last_break_font; - IOSOperator *m_operator; + IOSOperator* m_operator; u32 m_blink_start_time; s32 m_cursor_pos; @@ -197,4 +194,6 @@ class GUIEditBoxWithScrollBar : public IGUIEditBox video::SColor m_bg_color; }; + #endif // GUIEDITBOXWITHSCROLLBAR_HEADER + diff --git a/src/gui/guiEngine.cpp b/src/gui/guiEngine.cpp index 2e1bc7fed..b40707d01 100644 --- a/src/gui/guiEngine.cpp +++ b/src/gui/guiEngine.cpp @@ -43,6 +43,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/tile.h" #endif + /******************************************************************************/ void TextDestGuiEngine::gotText(const StringMap &fields) { @@ -98,72 +99,84 @@ video::ITexture *MenuTextureSource::getTexture(const std::string &name, u32 *id) /** MenuMusicFetcher */ /******************************************************************************/ void MenuMusicFetcher::fetchSounds(const std::string &name, - std::set &dst_paths, std::set &dst_datas) + std::set &dst_paths, + std::set &dst_datas) { - if (m_fetched.count(name)) + if(m_fetched.count(name)) return; m_fetched.insert(name); std::string base; base = porting::path_share + DIR_DELIM + "sounds"; dst_paths.insert(base + DIR_DELIM + name + ".ogg"); int i; - for (i = 0; i < 10; i++) - dst_paths.insert(base + DIR_DELIM + name + "." + itos(i) + ".ogg"); + for(i=0; i<10; i++) + dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg"); base = porting::path_user + DIR_DELIM + "sounds"; dst_paths.insert(base + DIR_DELIM + name + ".ogg"); - for (i = 0; i < 10; i++) - dst_paths.insert(base + DIR_DELIM + name + "." + itos(i) + ".ogg"); + for(i=0; i<10; i++) + dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg"); } /******************************************************************************/ /** GUIEngine */ /******************************************************************************/ -GUIEngine::GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, - IMenuManager *menumgr, MainMenuData *data, bool &kill) : - m_parent(parent), - m_menumanager(menumgr), m_smgr(RenderingEngine::get_scene_manager()), - m_data(data), m_kill(kill) +GUIEngine::GUIEngine(JoystickController *joystick, + gui::IGUIElement *parent, + IMenuManager *menumgr, + MainMenuData *data, + bool &kill) : + m_parent(parent), + m_menumanager(menumgr), + m_smgr(RenderingEngine::get_scene_manager()), + m_data(data), + m_kill(kill) { - // initialize texture pointers + //initialize texture pointers for (image_definition &texture : m_textures) { texture.texture = NULL; } // is deleted by guiformspec! m_buttonhandler = new TextDestGuiEngine(this); - // create texture source + //create texture source m_texture_source = new MenuTextureSource(RenderingEngine::get_video_driver()); - // create soundmanager + //create soundmanager MenuMusicFetcher soundfetcher; #if USE_SOUND if (g_settings->getBool("enable_sound") && g_sound_manager_singleton.get()) - m_sound_manager = createOpenALSoundManager( - g_sound_manager_singleton.get(), &soundfetcher); + m_sound_manager = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher); #endif if (!m_sound_manager) m_sound_manager = &dummySoundManager; - // create topleft header + //create topleft header m_toplefttext = L""; core::rect rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()), - g_fontengine->getTextHeight()); + g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext = gui::StaticText::add(RenderingEngine::get_gui_env(), m_toplefttext, rect, false, true, 0, -1); - // create formspecsource + //create formspecsource m_formspecgui = new FormspecFormSource(""); /* Create menu */ - m_menu = new GUIFormSpecMenu(joystick, m_parent, -1, m_menumanager, - NULL /* &client */, m_texture_source, m_formspecgui, - m_buttonhandler, "", false); + m_menu = new GUIFormSpecMenu(joystick, + m_parent, + -1, + m_menumanager, + NULL /* &client */, + m_texture_source, + m_formspecgui, + m_buttonhandler, + "", + false); m_menu->allowClose(false); - m_menu->lockSize(true, v2u32(800, 600)); + m_menu->lockSize(true,v2u32(800,600)); // Initialize scripting @@ -197,20 +210,18 @@ bool GUIEngine::loadMainMenuScript() // Set main menu path (for core.get_mainmenu_path()) m_scriptdir = g_settings->get("main_menu_path"); if (m_scriptdir.empty()) { - m_scriptdir = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM + - "mainmenu"; + m_scriptdir = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM + "mainmenu"; } // Load builtin (which will load the main menu script) - std::string script = - porting::path_share + DIR_DELIM "builtin" + DIR_DELIM "init.lua"; + std::string script = porting::path_share + DIR_DELIM "builtin" + DIR_DELIM "init.lua"; try { m_script->loadScript(script); // Menu script loaded return true; } catch (const ModError &e) { - errorstream << "GUIEngine: execution of menu script failed: " << e.what() - << std::endl; + errorstream << "GUIEngine: execution of menu script failed: " + << e.what() << std::endl; } return false; @@ -227,8 +238,8 @@ void GUIEngine::run() unsigned int text_height = g_fontengine->getTextHeight(); - irr::core::dimension2d previous_screen_size( - g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); + irr::core::dimension2d previous_screen_size(g_settings->getU16("screen_w"), + g_settings->getU16("screen_h")); static const video::SColor sky_color(255, 140, 186, 250); @@ -251,20 +262,19 @@ void GUIEngine::run() while (RenderingEngine::run() && (!m_startgame) && (!m_kill)) { const irr::core::dimension2d ¤t_screen_size = - RenderingEngine::get_video_driver()->getScreenSize(); + RenderingEngine::get_video_driver()->getScreenSize(); // Verify if window size has changed and save it if it's the case // Ensure evaluating settings->getBool after verifying screensize // First condition is cheaper if (previous_screen_size != current_screen_size && - current_screen_size != - irr::core::dimension2d(0, 0) && + current_screen_size != irr::core::dimension2d(0,0) && g_settings->getBool("autosave_screensize")) { g_settings->setU16("screen_w", current_screen_size.Width); g_settings->setU16("screen_h", current_screen_size.Height); previous_screen_size = current_screen_size; } - // check if we need to update the "upper left corner"-text + //check if we need to update the "upper left corner"-text if (text_height != g_fontengine->getTextHeight()) { updateTopLeftTextSize(); text_height = g_fontengine->getTextHeight(); @@ -272,10 +282,12 @@ void GUIEngine::run() driver->beginScene(true, true, sky_color); - if (m_clouds_enabled) { + if (m_clouds_enabled) + { cloudPreProcess(); drawOverlay(driver); - } else + } + else drawBackground(driver); drawHeader(driver); @@ -301,21 +313,20 @@ void GUIEngine::run() /******************************************************************************/ GUIEngine::~GUIEngine() { - if (m_sound_manager != &dummySoundManager) { + if (m_sound_manager != &dummySoundManager){ delete m_sound_manager; m_sound_manager = NULL; } - infostream << "GUIEngine: Deinitializing scripting" << std::endl; + infostream<<"GUIEngine: Deinitializing scripting"<setText(L""); - // clean up texture pointers + //clean up texture pointers for (image_definition &texture : m_textures) { if (texture.texture) - RenderingEngine::get_video_driver()->removeTexture( - texture.texture); + RenderingEngine::get_video_driver()->removeTexture(texture.texture); } delete m_texture_source; @@ -329,9 +340,10 @@ void GUIEngine::cloudInit() { m_cloud.clouds = new Clouds(m_smgr, -1, rand()); m_cloud.clouds->setHeight(100.0f); - m_cloud.clouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255)); + m_cloud.clouds->update(v3f(0, 0, 0), video::SColor(255,240,240,255)); - m_cloud.camera = m_smgr->addCameraSceneNode(0, v3f(0, 0, 0), v3f(0, 60, 100)); + m_cloud.camera = m_smgr->addCameraSceneNode(0, + v3f(0,0,0), v3f(0, 60, 100)); m_cloud.camera->setFarValue(10000); m_cloud.lasttime = RenderingEngine::get_timer_time(); @@ -342,14 +354,14 @@ void GUIEngine::cloudPreProcess() { u32 time = RenderingEngine::get_timer_time(); - if (time > m_cloud.lasttime) + if(time > m_cloud.lasttime) m_cloud.dtime = (time - m_cloud.lasttime) / 1000.0; else m_cloud.dtime = 0; m_cloud.lasttime = time; - m_cloud.clouds->step(m_cloud.dtime * 3); + m_cloud.clouds->step(m_cloud.dtime*3); m_cloud.clouds->render(); m_smgr->drawAll(); } @@ -363,13 +375,13 @@ void GUIEngine::cloudPostProcess() // not using getRealTime is necessary for wine u32 time = RenderingEngine::get_timer_time(); - if (time > m_cloud.lasttime) + if(time > m_cloud.lasttime) busytime_u32 = time - m_cloud.lasttime; else busytime_u32 = 0; // FPS limiter - u32 frametime_min = 1000. / fps_max; + u32 frametime_min = 1000./fps_max; if (busytime_u32 < frametime_min) { u32 sleeptime = frametime_min - busytime_u32; @@ -385,16 +397,17 @@ void GUIEngine::setFormspecPrepend(const std::string &fs) } } + /******************************************************************************/ void GUIEngine::drawBackground(video::IVideoDriver *driver) { v2u32 screensize = driver->getScreenSize(); - video::ITexture *texture = m_textures[TEX_LAYER_BACKGROUND].texture; + video::ITexture* texture = m_textures[TEX_LAYER_BACKGROUND].texture; /* If no texture, draw background of solid color */ - if (!texture) { - video::SColor color(255, 80, 58, 37); + if(!texture){ + video::SColor color(255,80,58,37); core::rect rect(0, 0, screensize.X, screensize.Y); driver->draw2DRectangle(color, rect, NULL); return; @@ -402,19 +415,19 @@ void GUIEngine::drawBackground(video::IVideoDriver *driver) v2u32 sourcesize = texture->getOriginalSize(); - if (m_textures[TEX_LAYER_BACKGROUND].tile) { - v2u32 tilesize(MYMAX(sourcesize.X, - m_textures[TEX_LAYER_BACKGROUND].minsize), - MYMAX(sourcesize.Y, m_textures[TEX_LAYER_BACKGROUND] - .minsize)); - for (unsigned int x = 0; x < screensize.X; x += tilesize.X) { - for (unsigned int y = 0; y < screensize.Y; y += tilesize.Y) { + if (m_textures[TEX_LAYER_BACKGROUND].tile) + { + v2u32 tilesize( + MYMAX(sourcesize.X,m_textures[TEX_LAYER_BACKGROUND].minsize), + MYMAX(sourcesize.Y,m_textures[TEX_LAYER_BACKGROUND].minsize)); + for (unsigned int x = 0; x < screensize.X; x += tilesize.X ) + { + for (unsigned int y = 0; y < screensize.Y; y += tilesize.Y ) + { draw2DImageFilterScaled(driver, texture, - core::rect(x, y, x + tilesize.X, - y + tilesize.Y), - core::rect(0, 0, sourcesize.X, - sourcesize.Y), - NULL, NULL, true); + core::rect(x, y, x+tilesize.X, y+tilesize.Y), + core::rect(0, 0, sourcesize.X, sourcesize.Y), + NULL, NULL, true); } } return; @@ -422,9 +435,9 @@ void GUIEngine::drawBackground(video::IVideoDriver *driver) /* Draw background texture */ draw2DImageFilterScaled(driver, texture, - core::rect(0, 0, screensize.X, screensize.Y), - core::rect(0, 0, sourcesize.X, sourcesize.Y), NULL, NULL, - true); + core::rect(0, 0, screensize.X, screensize.Y), + core::rect(0, 0, sourcesize.X, sourcesize.Y), + NULL, NULL, true); } /******************************************************************************/ @@ -432,18 +445,18 @@ void GUIEngine::drawOverlay(video::IVideoDriver *driver) { v2u32 screensize = driver->getScreenSize(); - video::ITexture *texture = m_textures[TEX_LAYER_OVERLAY].texture; + video::ITexture* texture = m_textures[TEX_LAYER_OVERLAY].texture; /* If no texture, draw nothing */ - if (!texture) + if(!texture) return; /* Draw background texture */ v2u32 sourcesize = texture->getOriginalSize(); draw2DImageFilterScaled(driver, texture, - core::rect(0, 0, screensize.X, screensize.Y), - core::rect(0, 0, sourcesize.X, sourcesize.Y), NULL, NULL, - true); + core::rect(0, 0, screensize.X, screensize.Y), + core::rect(0, 0, sourcesize.X, sourcesize.Y), + NULL, NULL, true); } /******************************************************************************/ @@ -451,33 +464,32 @@ void GUIEngine::drawHeader(video::IVideoDriver *driver) { core::dimension2d screensize = driver->getScreenSize(); - video::ITexture *texture = m_textures[TEX_LAYER_HEADER].texture; + video::ITexture* texture = m_textures[TEX_LAYER_HEADER].texture; /* If no texture, draw nothing */ - if (!texture) + if(!texture) return; f32 mult = (((f32)screensize.Width / 2.0)) / - ((f32)texture->getOriginalSize().Width); + ((f32)texture->getOriginalSize().Width); v2s32 splashsize(((f32)texture->getOriginalSize().Width) * mult, ((f32)texture->getOriginalSize().Height) * mult); // Don't draw the header if there isn't enough room - s32 free_space = (((s32)screensize.Height) - 320) / 2; + s32 free_space = (((s32)screensize.Height)-320)/2; if (free_space > splashsize.Y) { core::rect splashrect(0, 0, splashsize.X, splashsize.Y); - splashrect += v2s32((screensize.Width / 2) - (splashsize.X / 2), - ((free_space / 2) - splashsize.Y / 2) + 10); + splashrect += v2s32((screensize.Width/2)-(splashsize.X/2), + ((free_space/2)-splashsize.Y/2)+10); - video::SColor bgcolor(255, 50, 50, 50); + video::SColor bgcolor(255,50,50,50); - draw2DImageFilterScaled(driver, texture, splashrect, - core::rect(core::position2d(0, 0), - core::dimension2di( - texture->getOriginalSize())), - NULL, NULL, true); + draw2DImageFilterScaled(driver, texture, splashrect, + core::rect(core::position2d(0,0), + core::dimension2di(texture->getOriginalSize())), + NULL, NULL, true); } } @@ -486,30 +498,30 @@ void GUIEngine::drawFooter(video::IVideoDriver *driver) { core::dimension2d screensize = driver->getScreenSize(); - video::ITexture *texture = m_textures[TEX_LAYER_FOOTER].texture; + video::ITexture* texture = m_textures[TEX_LAYER_FOOTER].texture; /* If no texture, draw nothing */ - if (!texture) + if(!texture) return; - f32 mult = (((f32)screensize.Width)) / ((f32)texture->getOriginalSize().Width); + f32 mult = (((f32)screensize.Width)) / + ((f32)texture->getOriginalSize().Width); v2s32 footersize(((f32)texture->getOriginalSize().Width) * mult, ((f32)texture->getOriginalSize().Height) * mult); // Don't draw the footer if there isn't enough room - s32 free_space = (((s32)screensize.Height) - 320) / 2; + s32 free_space = (((s32)screensize.Height)-320)/2; if (free_space > footersize.Y) { - core::rect rect(0, 0, footersize.X, footersize.Y); - rect += v2s32(screensize.Width / 2, screensize.Height - footersize.Y); - rect -= v2s32(footersize.X / 2, 0); + core::rect rect(0,0,footersize.X,footersize.Y); + rect += v2s32(screensize.Width/2,screensize.Height-footersize.Y); + rect -= v2s32(footersize.X/2, 0); draw2DImageFilterScaled(driver, texture, rect, - core::rect(core::position2d(0, 0), - core::dimension2di( - texture->getOriginalSize())), - NULL, NULL, true); + core::rect(core::position2d(0,0), + core::dimension2di(texture->getOriginalSize())), + NULL, NULL, true); } } @@ -529,7 +541,7 @@ bool GUIEngine::setTexture(texture_layer layer, const std::string &texturepath, } m_textures[layer].texture = driver->getTexture(texturepath.c_str()); - m_textures[layer].tile = tile_image; + m_textures[layer].tile = tile_image; m_textures[layer].minsize = minsize; if (!m_textures[layer].texture) { @@ -580,7 +592,7 @@ void GUIEngine::setTopleftText(const std::string &text) void GUIEngine::updateTopLeftTextSize() { core::rect rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()), - g_fontengine->getTextHeight()); + g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext->remove(); @@ -602,8 +614,8 @@ void GUIEngine::stopSound(s32 handle) } /******************************************************************************/ -unsigned int GUIEngine::queueAsync( - const std::string &serialized_func, const std::string &serialized_params) +unsigned int GUIEngine::queueAsync(const std::string &serialized_func, + const std::string &serialized_params) { return m_script->queueAsync(serialized_func, serialized_params); } diff --git a/src/gui/guiEngine.h b/src/gui/guiEngine.h index b94bbef12..f9ad0fb0a 100644 --- a/src/gui/guiEngine.h +++ b/src/gui/guiEngine.h @@ -32,8 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Typedefs and macros */ /******************************************************************************/ /** texture layer ids */ -typedef enum -{ +typedef enum { TEX_LAYER_BACKGROUND = 0, TEX_LAYER_OVERLAY, TEX_LAYER_HEADER, @@ -41,11 +40,10 @@ typedef enum TEX_LAYER_MAX } texture_layer; -typedef struct -{ +typedef struct { video::ITexture *texture = nullptr; - bool tile; - unsigned int minsize; + bool tile; + unsigned int minsize; } image_definition; /******************************************************************************/ @@ -68,7 +66,7 @@ class TextDestGuiEngine : public TextDest * default constructor * @param engine the engine data is transmitted for further processing */ - TextDestGuiEngine(GUIEngine *engine) : m_engine(engine){}; + TextDestGuiEngine(GUIEngine* engine) : m_engine(engine) {}; /** * receive fields transmitted by guiFormSpecMenu @@ -95,7 +93,7 @@ class MenuTextureSource : public ISimpleTextureSource * default constructor * @param driver the video driver to load textures from */ - MenuTextureSource(video::IVideoDriver *driver) : m_driver(driver){}; + MenuTextureSource(video::IVideoDriver *driver) : m_driver(driver) {}; /** * destructor, removes all loaded textures @@ -117,7 +115,7 @@ class MenuTextureSource : public ISimpleTextureSource }; /** GUIEngine specific implementation of OnDemandSoundFetcher */ -class MenuMusicFetcher : public OnDemandSoundFetcher +class MenuMusicFetcher: public OnDemandSoundFetcher { public: /** @@ -126,7 +124,8 @@ class MenuMusicFetcher : public OnDemandSoundFetcher * @param dst_paths receives possible paths to sound files * @param dst_datas receives binary sound data (not used here) */ - void fetchSounds(const std::string &name, std::set &dst_paths, + void fetchSounds(const std::string &name, + std::set &dst_paths, std::set &dst_datas); private: @@ -135,8 +134,7 @@ class MenuMusicFetcher : public OnDemandSoundFetcher }; /** implementation of main menu based uppon formspecs */ -class GUIEngine -{ +class GUIEngine { /** grant ModApiMainMenu access to private members */ friend class ModApiMainMenu; friend class ModApiSound; @@ -150,8 +148,11 @@ class GUIEngine * @param smgr scene manager to add scene elements to * @param data struct to transfer data to main game handling */ - GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, - IMenuManager *menumgr, MainMenuData *data, bool &kill); + GUIEngine(JoystickController *joystick, + gui::IGUIElement *parent, + IMenuManager *menumgr, + MainMenuData *data, + bool &kill); /** default destructor */ virtual ~GUIEngine(); @@ -159,18 +160,25 @@ class GUIEngine /** * return MainMenuScripting interface */ - MainMenuScripting *getScriptIface() { return m_script; } + MainMenuScripting *getScriptIface() + { + return m_script; + } /** * return dir of current menuscript */ - std::string getScriptDir() { return m_scriptdir; } + std::string getScriptDir() + { + return m_scriptdir; + } /** pass async callback to scriptengine **/ unsigned int queueAsync(const std::string &serialized_fct, const std::string &serialized_params); private: + /** find and run the main menu script */ bool loadMainMenuScript(); @@ -181,36 +189,36 @@ class GUIEngine void updateTopLeftTextSize(); /** parent gui element */ - gui::IGUIElement *m_parent = nullptr; + gui::IGUIElement *m_parent = nullptr; /** manager to add menus to */ - IMenuManager *m_menumanager = nullptr; + IMenuManager *m_menumanager = nullptr; /** scene manager to add scene elements to */ - scene::ISceneManager *m_smgr = nullptr; + scene::ISceneManager *m_smgr = nullptr; /** pointer to data beeing transfered back to main game handling */ - MainMenuData *m_data = nullptr; + MainMenuData *m_data = nullptr; /** pointer to texture source */ - ISimpleTextureSource *m_texture_source = nullptr; + ISimpleTextureSource *m_texture_source = nullptr; /** pointer to soundmanager*/ - ISoundManager *m_sound_manager = nullptr; + ISoundManager *m_sound_manager = nullptr; /** representation of form source to be used in mainmenu formspec */ - FormspecFormSource *m_formspecgui = nullptr; + FormspecFormSource *m_formspecgui = nullptr; /** formspec input receiver */ - TextDestGuiEngine *m_buttonhandler = nullptr; + TextDestGuiEngine *m_buttonhandler = nullptr; /** the formspec menu */ - GUIFormSpecMenu *m_menu = nullptr; + GUIFormSpecMenu *m_menu = nullptr; /** reference to kill variable managed by SIGINT handler */ - bool &m_kill; + bool &m_kill; /** variable used to abort menu and return back to main game handling */ - bool m_startgame = false; + bool m_startgame = false; /** scripting interface */ - MainMenuScripting *m_script = nullptr; + MainMenuScripting *m_script = nullptr; /** script basefolder */ - std::string m_scriptdir = ""; + std::string m_scriptdir = ""; void setFormspecPrepend(const std::string &fs); @@ -272,12 +280,11 @@ class GUIEngine void cloudPostProcess(); /** internam data required for drawing clouds */ - struct clouddata - { + struct clouddata { /** delta time since last cloud processing */ - f32 dtime; + f32 dtime; /** absolute time of last cloud processing */ - u32 lasttime; + u32 lasttime; /** pointer to cloud class */ Clouds *clouds = nullptr; /** camera required for drawing clouds */ @@ -285,12 +292,14 @@ class GUIEngine }; /** is drawing of clouds enabled atm */ - bool m_clouds_enabled = true; + bool m_clouds_enabled = true; /** data used to draw clouds */ - clouddata m_cloud; + clouddata m_cloud; /** start playing a sound and return handle */ s32 playSound(const SimpleSoundSpec &spec, bool looped); /** stop playing a sound started with playSound() */ void stopSound(s32 handle); + + }; diff --git a/src/gui/guiFormSpecMenu.cpp b/src/gui/guiFormSpecMenu.cpp index 5013ffe14..601c5c18e 100644 --- a/src/gui/guiFormSpecMenu.cpp +++ b/src/gui/guiFormSpecMenu.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include #include #include @@ -37,7 +38,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/renderingengine.h" #include "log.h" #include "client/tile.h" // ITextureSource -#include "client/hud.h" // drawItemStack +#include "client/hud.h" // drawItemStack #include "filesys.h" #include "gettime.h" #include "gettext.h" @@ -65,18 +66,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "intlGUIEditBox.h" #include "guiHyperText.h" -#define MY_CHECKPOS(a, b) \ - if (v_pos.size() != 2) { \ - errorstream << "Invalid pos for element " << a << "specified: \"" \ - << parts[b] << "\"" << std::endl; \ - return; \ +#define MY_CHECKPOS(a,b) \ + if (v_pos.size() != 2) { \ + errorstream<< "Invalid pos for element " << a << "specified: \"" \ + << parts[b] << "\"" << std::endl; \ + return; \ } -#define MY_CHECKGEOM(a, b) \ - if (v_geom.size() != 2) { \ - errorstream << "Invalid geometry for element " << a << "specified: \"" \ - << parts[b] << "\"" << std::endl; \ - return; \ +#define MY_CHECKGEOM(a,b) \ + if (v_geom.size() != 2) { \ + errorstream<< "Invalid geometry for element " << a << \ + "specified: \"" << parts[b] << "\"" << std::endl; \ + return; \ } /* GUIFormSpecMenu @@ -88,18 +89,21 @@ static unsigned int font_line_height(gui::IGUIFont *font) inline u32 clamp_u8(s32 value) { - return (u32)MYMIN(MYMAX(value, 0), 255); + return (u32) MYMIN(MYMAX(value, 0), 255); } -GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick, gui::IGUIElement *parent, - s32 id, IMenuManager *menumgr, Client *client, ISimpleTextureSource *tsrc, - IFormSource *fsrc, TextDest *tdst, const std::string &formspecPrepend, - bool remap_dbl_click) : - GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr, - remap_dbl_click), - m_invmgr(client), m_tsrc(tsrc), m_client(client), - m_formspec_prepend(formspecPrepend), m_form_src(fsrc), m_text_dst(tdst), - m_joystick(joystick) +GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick, + gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, + Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst, + const std::string &formspecPrepend, bool remap_dbl_click): + GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr, remap_dbl_click), + m_invmgr(client), + m_tsrc(tsrc), + m_client(client), + m_formspec_prepend(formspecPrepend), + m_form_src(fsrc), + m_text_dst(tdst), + m_joystick(joystick) { current_keys_pending.key_down = false; current_keys_pending.key_up = false; @@ -137,13 +141,12 @@ GUIFormSpecMenu::~GUIFormSpecMenu() } void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client, - JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, - const std::string &formspecPrepend) + JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, + const std::string &formspecPrepend) { if (cur_formspec == nullptr) { cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr, - client, client->getTextureSource(), fs_src, txt_dest, - formspecPrepend); + client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend); cur_formspec->doPause = false; /* @@ -163,7 +166,7 @@ void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client, void GUIFormSpecMenu::removeChildren() { - const core::list &children = getChildren(); + const core::list &children = getChildren(); while (!children.empty()) { (*children.getLast())->remove(); @@ -186,10 +189,10 @@ void GUIFormSpecMenu::setInitialFocus() // 5. first focusable (not statictext, not tabheader) // 6. first child element - core::list children = getChildren(); + core::list children = getChildren(); // in case "children" contains any NULL elements, remove them - for (core::list::Iterator it = children.begin(); + for (core::list::Iterator it = children.begin(); it != children.end();) { if (*it) ++it; @@ -199,7 +202,8 @@ void GUIFormSpecMenu::setInitialFocus() // 1. first empty editbox for (gui::IGUIElement *it : children) { - if (it->getType() == gui::EGUIET_EDIT_BOX && it->getText()[0] == 0) { + if (it->getType() == gui::EGUIET_EDIT_BOX + && it->getText()[0] == 0) { Environment->setFocus(it); return; } @@ -222,7 +226,7 @@ void GUIFormSpecMenu::setInitialFocus() } // 4. last button - for (core::list::Iterator it = children.getLast(); + for (core::list::Iterator it = children.getLast(); it != children.end(); --it) { if ((*it)->getType() == gui::EGUIET_BUTTON) { Environment->setFocus(*it); @@ -233,7 +237,7 @@ void GUIFormSpecMenu::setInitialFocus() // 5. first focusable (not statictext, not tabheader) for (gui::IGUIElement *it : children) { if (it->getType() != gui::EGUIET_STATIC_TEXT && - it->getType() != gui::EGUIET_TAB_CONTROL) { + it->getType() != gui::EGUIET_TAB_CONTROL) { Environment->setFocus(it); return; } @@ -246,7 +250,7 @@ void GUIFormSpecMenu::setInitialFocus() Environment->setFocus(*(children.begin())); } -GUITable *GUIFormSpecMenu::getTable(const std::string &tablename) +GUITable* GUIFormSpecMenu::getTable(const std::string &tablename) { for (auto &table : m_tables) { if (tablename == table.first.fname) @@ -255,7 +259,7 @@ GUITable *GUIFormSpecMenu::getTable(const std::string &tablename) return 0; } -std::vector *GUIFormSpecMenu::getDropDownValues(const std::string &name) +std::vector* GUIFormSpecMenu::getDropDownValues(const std::string &name) { for (auto &dropdown : m_dropdowns) { if (name == dropdown.first.fname) @@ -277,7 +281,7 @@ v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector *v_pos) v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector &v_pos) { return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X, - (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y); + (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y); } v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector &v_geom) @@ -285,15 +289,15 @@ v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y); } -void GUIFormSpecMenu::parseSize(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element) { - std::vector parts = split(element, ','); + std::vector parts = split(element,','); if (((parts.size() == 2) || parts.size() == 3) || - ((parts.size() > 3) && - (m_formspec_version > FORMSPEC_API_VERSION))) { + ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) + { if (parts[1].find(';') != std::string::npos) - parts[1] = parts[1].substr(0, parts[1].find(';')); + parts[1] = parts[1].substr(0,parts[1].find(';')); data->invsize.X = MYMAX(0, stof(parts[0])); data->invsize.Y = MYMAX(0, stof(parts[1])); @@ -302,18 +306,17 @@ void GUIFormSpecMenu::parseSize(parserData *data, const std::string &element) #ifndef __ANDROID__ if (parts.size() == 3) { if (parts[2] == "true") { - lockSize(true, v2u32(800, 600)); + lockSize(true,v2u32(800,600)); } } #endif data->explicit_size = true; return; } - errorstream << "Invalid size element (" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseContainer(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element) { std::vector parts = split(element, ','); @@ -326,16 +329,13 @@ void GUIFormSpecMenu::parseContainer(parserData *data, const std::string &elemen pos_offset.Y += stof(parts[1]); return; } - errorstream << "Invalid container start element (" << parts.size() << "): '" - << element << "'" << std::endl; + errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseContainerEnd(parserData *data) +void GUIFormSpecMenu::parseContainerEnd(parserData* data) { if (container_stack.empty()) { - errorstream << "Invalid container end element, no matching container " - "start element" - << std::endl; + errorstream<< "Invalid container end element, no matching container start element" << std::endl; } else { pos_offset = container_stack.top(); container_stack.pop(); @@ -347,14 +347,13 @@ void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string & std::vector parts = split(element, ';'); if (parts.size() < 4 || - (parts.size() > 5 && - m_formspec_version <= FORMSPEC_API_VERSION)) { + (parts.size() > 5 && m_formspec_version <= FORMSPEC_API_VERSION)) { errorstream << "Invalid scroll_container start element (" << parts.size() - << "): '" << element << "'" << std::endl; + << "): '" << element << "'" << std::endl; return; } - std::vector v_pos = split(parts[0], ','); + std::vector v_pos = split(parts[0], ','); std::vector v_geom = split(parts[1], ','); std::string scrollbar_name = parts[2]; std::string orientation = parts[3]; @@ -374,8 +373,8 @@ void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string & scroll_factor *= -imgsize.X; else warningstream << "GUIFormSpecMenu::parseScrollContainer(): " - << "Invalid scroll_container orientation: " << orientation - << std::endl; + << "Invalid scroll_container orientation: " << orientation + << std::endl; // old parent (at first: this) // ^ is parent of clipper @@ -389,12 +388,17 @@ void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string & data->current_parent, 0, rect_clipper); // make mover - FieldSpec spec_mover("", L"", L"", 258 + m_fields.size()); + FieldSpec spec_mover( + "", + L"", + L"", + 258 + m_fields.size() + ); core::rect rect_mover = core::rect(0, 0, geom.X, geom.Y); - GUIScrollContainer *mover = new GUIScrollContainer(Environment, clipper, - spec_mover.fid, rect_mover, orientation, scroll_factor); + GUIScrollContainer *mover = new GUIScrollContainer(Environment, + clipper, spec_mover.fid, rect_mover, orientation, scroll_factor); data->current_parent = mover; @@ -415,7 +419,7 @@ void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data) if (data->current_parent == this || data->current_parent->getParent() == this || container_stack.empty()) { errorstream << "Invalid scroll_container end element, " - << "no matching scroll_container start element" << std::endl; + << "no matching scroll_container start element" << std::endl; return; } @@ -425,7 +429,7 @@ void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data) // not 0,0, it is a normal container that was opened last, not a // scroll_container errorstream << "Invalid scroll_container end element, " - << "an inner container was left open" << std::endl; + << "an inner container was left open" << std::endl; return; } @@ -437,25 +441,25 @@ void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data) void GUIFormSpecMenu::parseList(parserData *data, const std::string &element) { if (m_client == 0) { - warningstream << "invalid use of 'list' with m_client==0" << std::endl; + warningstream<<"invalid use of 'list' with m_client==0"< parts = split(element, ';'); + std::vector parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 5)) || - ((parts.size() > 5) && - (m_formspec_version > FORMSPEC_API_VERSION))) { + ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) + { std::string location = parts[0]; std::string listname = parts[1]; - std::vector v_pos = split(parts[2], ','); - std::vector v_geom = split(parts[3], ','); + std::vector v_pos = split(parts[2],','); + std::vector v_geom = split(parts[3],','); std::string startindex; if (parts.size() == 5) startindex = parts[4]; - MY_CHECKPOS("list", 2); - MY_CHECKGEOM("list", 3); + MY_CHECKPOS("list",2); + MY_CHECKGEOM("list",3); InventoryLocation loc; @@ -473,47 +477,46 @@ void GUIFormSpecMenu::parseList(parserData *data, const std::string &element) start_i = stoi(startindex); if (geom.X < 0 || geom.Y < 0 || start_i < 0) { - errorstream << "Invalid list element: '" << element << "'" - << std::endl; + errorstream << "Invalid list element: '" << element << "'" << std::endl; return; } if (!data->explicit_size) - warningstream << "invalid use of list without a size[] element" - << std::endl; + warningstream << "invalid use of list without a size[] element" << std::endl; - FieldSpec spec("", L"", L"", 258 + m_fields.size(), 3); + FieldSpec spec( + "", + L"", + L"", + 258 + m_fields.size(), + 3 + ); - v2f32 slot_spacing = data->real_coordinates - ? v2f32(imgsize.X * 1.25f, - imgsize.Y * 1.25f) - : spacing; + v2f32 slot_spacing = data->real_coordinates ? + v2f32(imgsize.X * 1.25f, imgsize.Y * 1.25f) : spacing; v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos) - : getElementBasePos(&v_pos); + : getElementBasePos(&v_pos); core::rect rect = core::rect(pos.X, pos.Y, pos.X + (geom.X - 1) * slot_spacing.X + imgsize.X, pos.Y + (geom.Y - 1) * slot_spacing.Y + imgsize.Y); - GUIInventoryList *e = new GUIInventoryList(Environment, - data->current_parent, spec.fid, rect, m_invmgr, loc, - listname, geom, start_i, imgsize, slot_spacing, this, - data->inventorylist_options, m_font); + GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent, + spec.fid, rect, m_invmgr, loc, listname, geom, start_i, imgsize, + slot_spacing, this, data->inventorylist_options, m_font); m_inventorylists.push_back(e); m_fields.push_back(spec); return; } - errorstream << "Invalid list element(" << parts.size() << "): '" << element << "'" - << std::endl; + errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element) { if (m_client == 0) { - errorstream << "WARNING: invalid use of 'listring' with m_client==0" - << std::endl; + errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl; return; } @@ -539,25 +542,23 @@ void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element // insert the last two inv list elements into the list ring const GUIInventoryList *spa = m_inventorylists[siz - 2]; const GUIInventoryList *spb = m_inventorylists[siz - 1]; - m_inventory_rings.emplace_back( - spa->getInventoryloc(), spa->getListname()); - m_inventory_rings.emplace_back( - spb->getInventoryloc(), spb->getListname()); + m_inventory_rings.emplace_back(spa->getInventoryloc(), spa->getListname()); + m_inventory_rings.emplace_back(spb->getInventoryloc(), spb->getListname()); return; } - errorstream << "Invalid list ring element(" << parts.size() << ", " - << m_inventorylists.size() << "): '" << element << "'" << std::endl; + errorstream<< "Invalid list ring element(" << parts.size() << ", " + << m_inventorylists.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseCheckbox(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (((parts.size() >= 3) && (parts.size() <= 4)) || - ((parts.size() > 4) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); + ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); std::string name = parts[1]; std::string label = parts[2]; std::string selected; @@ -565,17 +566,15 @@ void GUIFormSpecMenu::parseCheckbox(parserData *data, const std::string &element if (parts.size() >= 4) selected = parts[3]; - MY_CHECKPOS("checkbox", 0); + MY_CHECKPOS("checkbox",0); bool fselected = false; if (selected == "true") fselected = true; - std::wstring wlabel = - translate_string(utf8_to_wide(unescape_string(label))); - const core::dimension2d label_size = - m_font->getDimension(wlabel.c_str()); + std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); + const core::dimension2d label_size = m_font->getDimension(wlabel.c_str()); s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH); s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2; @@ -585,19 +584,28 @@ void GUIFormSpecMenu::parseCheckbox(parserData *data, const std::string &element if (data->real_coordinates) { pos = getRealCoordinateBasePos(v_pos); - rect = core::rect(pos.X, pos.Y - y_center, + rect = core::rect( + pos.X, + pos.Y - y_center, pos.X + label_size.Width + cb_size + 7, - pos.Y + y_center); + pos.Y + y_center + ); } else { pos = getElementBasePos(&v_pos); - rect = core::rect(pos.X, pos.Y + imgsize.Y / 2 - y_center, + rect = core::rect( + pos.X, + pos.Y + imgsize.Y / 2 - y_center, pos.X + label_size.Width + cb_size + 7, - pos.Y + imgsize.Y / 2 + y_center); + pos.Y + imgsize.Y / 2 + y_center + ); } - FieldSpec spec(name, - wlabel, // Needed for displaying text on MSVC - wlabel, 258 + m_fields.size()); + FieldSpec spec( + name, + wlabel, //Needed for displaying text on MSVC + wlabel, + 258+m_fields.size() + ); spec.ftype = f_CheckBox; @@ -616,22 +624,21 @@ void GUIFormSpecMenu::parseCheckbox(parserData *data, const std::string &element m_fields.push_back(spec); return; } - errorstream << "Invalid checkbox element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseScrollBar(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (parts.size() >= 5) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[3]; std::string value = parts[4]; - MY_CHECKPOS("scrollbar", 0); - MY_CHECKGEOM("scrollbar", 1); + MY_CHECKPOS("scrollbar",0); + MY_CHECKGEOM("scrollbar",1); v2s32 pos; v2s32 dim; @@ -645,10 +652,15 @@ void GUIFormSpecMenu::parseScrollBar(parserData *data, const std::string &elemen dim.Y = stof(v_geom[1]) * spacing.Y; } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y); + core::rect rect = + core::rect(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y); - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + FieldSpec spec( + name, + L"", + L"", + 258+m_fields.size() + ); bool is_horizontal = true; @@ -656,7 +668,7 @@ void GUIFormSpecMenu::parseScrollBar(parserData *data, const std::string &elemen is_horizontal = false; spec.ftype = f_ScrollBar; - spec.send = true; + spec.send = true; GUIScrollBar *e = new GUIScrollBar(Environment, data->current_parent, spec.fid, rect, is_horizontal, true); @@ -677,28 +689,27 @@ void GUIFormSpecMenu::parseScrollBar(parserData *data, const std::string &elemen s32 scrollbar_size = is_horizontal ? dim.X : dim.Y; - e->setPageSize(scrollbar_size * (max - min + 1) / - data->scrollbar_options.thumb_size); + e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size); if (spec.fname == m_focused_element) { Environment->setFocus(e); } - m_scrollbars.emplace_back(spec, e); + m_scrollbars.emplace_back(spec,e); m_fields.push_back(spec); return; } errorstream << "Invalid scrollbar element(" << parts.size() << "): '" << element - << "'" << std::endl; + << "'" << std::endl; } -void GUIFormSpecMenu::parseScrollBarOptions(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element) { std::vector parts = split(element, ';'); if (parts.size() == 0) { - warningstream << "Invalid scrollbaroptions element(" << parts.size() - << "): '" << element << "'" << std::endl; + warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" << + element << "'" << std::endl; return; } @@ -706,8 +717,8 @@ void GUIFormSpecMenu::parseScrollBarOptions(parserData *data, const std::string std::vector options = split(i, '='); if (options.size() != 2) { - warningstream << "Invalid scrollbaroptions option syntax: '" - << element << "'" << std::endl; + warningstream << "Invalid scrollbaroptions option syntax: '" << + element << "'" << std::endl; continue; // Go to next option } @@ -732,31 +743,28 @@ void GUIFormSpecMenu::parseScrollBarOptions(parserData *data, const std::string } else if (options[0] == "arrows") { std::string value = trim(options[1]); if (value == "hide") - data->scrollbar_options.arrow_visiblity = - GUIScrollBar::HIDE; + data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE; else if (value == "show") - data->scrollbar_options.arrow_visiblity = - GUIScrollBar::SHOW; + data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW; else // Auto hide/show - data->scrollbar_options.arrow_visiblity = - GUIScrollBar::DEFAULT; + data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT; continue; } - warningstream << "Invalid scrollbaroptions option(" << options[0] - << "): '" << element << "'" << std::endl; + warningstream << "Invalid scrollbaroptions option(" << options[0] << + "): '" << element << "'" << std::endl; } } -void GUIFormSpecMenu::parseImage(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 3) || - ((parts.size() > 3) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = unescape_string(parts[2]); MY_CHECKPOS("image", 0); @@ -775,27 +783,29 @@ void GUIFormSpecMenu::parseImage(parserData *data, const std::string &element) } if (!data->explicit_size) - warningstream << "invalid use of image without a size[] element" - << std::endl; + warningstream<<"invalid use of image without a size[] element"<getTexture(name); if (!texture) { - errorstream << "GUIFormSpecMenu::parseImage() Unable to load " - "texture:" - << std::endl - << "\t" << name << std::endl; + errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:" + << std::endl << "\t" << name << std::endl; return; } - FieldSpec spec(name, L"", L"", 258 + m_fields.size(), 1); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size(), + 1 + ); core::rect rect(pos, pos + geom); - gui::IGUIImage *e = Environment->addImage( - rect, data->current_parent, spec.fid, 0, true); + gui::IGUIImage *e = Environment->addImage(rect, data->current_parent, + spec.fid, 0, true); e->setImage(texture); e->setScaleImage(true); auto style = getDefaultStyleForElement("image", spec.fname); - e->setNotClipped( - style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3)); + e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3)); m_fields.push_back(spec); // images should let events through @@ -805,7 +815,7 @@ void GUIFormSpecMenu::parseImage(parserData *data, const std::string &element) } if (parts.size() == 2) { - std::vector v_pos = split(parts[0], ','); + std::vector v_pos = split(parts[0],','); std::string name = unescape_string(parts[1]); MY_CHECKPOS("image", 0); @@ -813,24 +823,25 @@ void GUIFormSpecMenu::parseImage(parserData *data, const std::string &element) v2s32 pos = getElementBasePos(&v_pos); if (!data->explicit_size) - warningstream << "invalid use of image without a size[] element" - << std::endl; + warningstream<<"invalid use of image without a size[] element"<getTexture(name); if (!texture) { - errorstream << "GUIFormSpecMenu::parseImage() Unable to load " - "texture:" - << std::endl - << "\t" << name << std::endl; + errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:" + << std::endl << "\t" << name << std::endl; return; } - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); - gui::IGUIImage *e = Environment->addImage( - texture, pos, true, data->current_parent, spec.fid, 0); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); + gui::IGUIImage *e = Environment->addImage(texture, pos, true, + data->current_parent, spec.fid, 0); auto style = getDefaultStyleForElement("image", spec.fname); - e->setNotClipped( - style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3)); + e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3)); m_fields.push_back(spec); // images should let events through @@ -838,8 +849,7 @@ void GUIFormSpecMenu::parseImage(parserData *data, const std::string &element) m_clickthrough_elements.push_back(e); return; } - errorstream << "Invalid image element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element) @@ -847,14 +857,13 @@ void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &el std::vector parts = split(element, ';'); if (parts.size() != 6 && parts.size() != 7 && - !(parts.size() > 7 && - m_formspec_version > FORMSPEC_API_VERSION)) { - errorstream << "Invalid animated_image element(" << parts.size() << "): '" - << element << "'" << std::endl; + !(parts.size() > 7 && m_formspec_version > FORMSPEC_API_VERSION)) { + errorstream << "Invalid animated_image element(" << parts.size() + << "): '" << element << "'" << std::endl; return; } - std::vector v_pos = split(parts[0], ','); + std::vector v_pos = split(parts[0], ','); std::vector v_geom = split(parts[1], ','); std::string name = parts[2]; std::string texture_name = unescape_string(parts[3]); @@ -877,17 +886,21 @@ void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &el } if (!data->explicit_size) - warningstream << "Invalid use of animated_image without a size[] element" - << std::endl; - - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + warningstream << "Invalid use of animated_image without a size[] element" << std::endl; + + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); spec.ftype = f_AnimatedImage; spec.send = true; core::rect rect = core::rect(pos, pos + geom); - GUIAnimatedImage *e = new GUIAnimatedImage(Environment, this, spec.fid, rect, - texture_name, frame_count, frame_duration, m_tsrc); + GUIAnimatedImage *e = new GUIAnimatedImage(Environment, this, spec.fid, + rect, texture_name, frame_count, frame_duration, m_tsrc); if (parts.size() >= 7) e->setFrameIndex(stoi(parts[6]) - 1); @@ -901,19 +914,19 @@ void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &el m_fields.push_back(spec); } -void GUIFormSpecMenu::parseItemImage(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 3) || - ((parts.size() > 3) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[2]; - MY_CHECKPOS("itemimage", 0); - MY_CHECKGEOM("itemimage", 1); + MY_CHECKPOS("itemimage",0); + MY_CHECKGEOM("itemimage",1); v2s32 pos; v2s32 geom; @@ -927,17 +940,20 @@ void GUIFormSpecMenu::parseItemImage(parserData *data, const std::string &elemen geom.Y = stof(v_geom[1]) * (float)imgsize.Y; } - if (!data->explicit_size) - warningstream << "invalid use of item_image without a size[] " - "element" - << std::endl; + if(!data->explicit_size) + warningstream<<"invalid use of item_image without a size[] element"<current_parent, - spec.fid, core::rect(pos, pos + geom), name, m_font, - m_client); + GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid, + core::rect(pos, pos + geom), name, m_font, m_client); auto style = getDefaultStyleForElement("item_image", spec.fname); e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); @@ -947,25 +963,24 @@ void GUIFormSpecMenu::parseItemImage(parserData *data, const std::string &elemen m_fields.push_back(spec); return; } - errorstream << "Invalid ItemImage element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseButton( - parserData *data, const std::string &element, const std::string &type) +void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element, + const std::string &type) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 4) || - ((parts.size() > 4) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; - MY_CHECKPOS("button", 0); - MY_CHECKGEOM("button", 1); + MY_CHECKPOS("button",0); + MY_CHECKGEOM("button",1); v2s32 pos; v2s32 geom; @@ -974,34 +989,36 @@ void GUIFormSpecMenu::parseButton( if (data->real_coordinates) { pos = getRealCoordinateBasePos(v_pos); geom = getRealCoordinateGeometry(v_geom); - rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + rect = core::rect(pos.X, pos.Y, pos.X+geom.X, + pos.Y+geom.Y); } else { pos = getElementBasePos(&v_pos); geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); - pos.Y += (stof(v_geom[1]) * (float)imgsize.Y) / 2; + pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; rect = core::rect(pos.X, pos.Y - m_btn_height, - pos.X + geom.X, pos.Y + m_btn_height); + pos.X + geom.X, pos.Y + m_btn_height); } - if (!data->explicit_size) - warningstream << "invalid use of button without a size[] element" - << std::endl; + if(!data->explicit_size) + warningstream<<"invalid use of button without a size[] element"<current_parent, spec.fid, spec.flabel.c_str()); - auto style = getStyleForElement( - type, name, (type != "button") ? "button" : ""); + auto style = getStyleForElement(type, name, (type != "button") ? "button" : ""); e->setStyles(style); if (spec.fname == m_focused_element) { @@ -1011,22 +1028,21 @@ void GUIFormSpecMenu::parseButton( m_fields.push_back(spec); return; } - errorstream << "Invalid button element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseBackground(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() >= 3 && parts.size() <= 5) || (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = unescape_string(parts[2]); - MY_CHECKPOS("background", 0); - MY_CHECKGEOM("background", 1); + MY_CHECKPOS("background",0); + MY_CHECKGEOM("background",1); v2s32 pos; v2s32 geom; @@ -1049,7 +1065,7 @@ void GUIFormSpecMenu::parseBackground(parserData *data, const std::string &eleme pos = getRealCoordinateBasePos(v_pos) * -1; geom = v2s32(0, 0); } else { - pos.X = stoi(v_pos[0]); // acts as offset + pos.X = stoi(v_pos[0]); //acts as offset pos.Y = stoi(v_pos[1]); } clip = true; @@ -1064,28 +1080,27 @@ void GUIFormSpecMenu::parseBackground(parserData *data, const std::string &eleme middle.LowerRightCorner = core::vector2di(-x, -x); } else if (v_middle.size() == 2) { s32 x = stoi(v_middle[0]); - s32 y = stoi(v_middle[1]); + s32 y = stoi(v_middle[1]); middle.UpperLeftCorner = core::vector2di(x, y); middle.LowerRightCorner = core::vector2di(-x, -y); // `-x` is interpreted as `w - x` } else if (v_middle.size() == 4) { - middle.UpperLeftCorner = core::vector2di( - stoi(v_middle[0]), stoi(v_middle[1])); - middle.LowerRightCorner = core::vector2di( - stoi(v_middle[2]), stoi(v_middle[3])); + middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1])); + middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3])); } else { - warningstream << "Invalid rectangle given to middle " - "param of background[] element" - << std::endl; + warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl; } } if (!data->explicit_size && !clip) - warningstream << "invalid use of unclipped background without a " - "size[] element" - << std::endl; + warningstream << "invalid use of unclipped background without a size[] element" << std::endl; - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); core::rect rect; if (!clip) { @@ -1096,8 +1111,8 @@ void GUIFormSpecMenu::parseBackground(parserData *data, const std::string &eleme rect = core::rect(-pos, pos); } - GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, - spec.fid, rect, name, middle, m_tsrc, clip); + GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid, + rect, name, middle, m_tsrc, clip); FATAL_ERROR_IF(!e, "Failed to create background formspec element"); @@ -1109,13 +1124,12 @@ void GUIFormSpecMenu::parseBackground(parserData *data, const std::string &eleme m_fields.push_back(spec); return; } - errorstream << "Invalid background element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTableOptions(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); data->table_options.clear(); for (const std::string &part : parts) { @@ -1125,13 +1139,13 @@ void GUIFormSpecMenu::parseTableOptions(parserData *data, const std::string &ele } } -void GUIFormSpecMenu::parseTableColumns(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); data->table_columns.clear(); for (const std::string &part : parts) { - std::vector col_parts = split(part, ','); + std::vector col_parts = split(part,','); GUITable::TableColumn column; // Parse column type if (!col_parts.empty()) @@ -1145,25 +1159,25 @@ void GUIFormSpecMenu::parseTableColumns(parserData *data, const std::string &ele } } -void GUIFormSpecMenu::parseTable(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 5)) || - ((parts.size() > 5) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[2]; - std::vector items = split(parts[3], ','); + std::vector items = split(parts[3],','); std::string str_initial_selection; std::string str_transparent = "false"; if (parts.size() >= 5) str_initial_selection = parts[4]; - MY_CHECKPOS("table", 0); - MY_CHECKGEOM("table", 1); + MY_CHECKPOS("table",0); + MY_CHECKGEOM("table",1); v2s32 pos; v2s32 geom; @@ -1177,19 +1191,22 @@ void GUIFormSpecMenu::parseTable(parserData *data, const std::string &element) geom.Y = stof(v_geom[1]) * spacing.Y; } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); spec.ftype = f_Table; for (std::string &item : items) { - item = wide_to_utf8(unescape_translate( - utf8_to_wide(unescape_string(item)))); + item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item)))); } - // now really show table + //now really show table GUITable *e = new GUITable(Environment, data->current_parent, spec.fid, rect, m_tsrc); @@ -1213,21 +1230,20 @@ void GUIFormSpecMenu::parseTable(parserData *data, const std::string &element) m_fields.push_back(spec); return; } - errorstream << "Invalid table element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTextList(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) || - ((parts.size() > 6) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[2]; - std::vector items = split(parts[3], ','); + std::vector items = split(parts[3],','); std::string str_initial_selection; std::string str_transparent = "false"; @@ -1237,8 +1253,8 @@ void GUIFormSpecMenu::parseTextList(parserData *data, const std::string &element if (parts.size() >= 6) str_transparent = parts[5]; - MY_CHECKPOS("textlist", 0); - MY_CHECKGEOM("textlist", 1); + MY_CHECKPOS("textlist",0); + MY_CHECKGEOM("textlist",1); v2s32 pos; v2s32 geom; @@ -1252,19 +1268,22 @@ void GUIFormSpecMenu::parseTextList(parserData *data, const std::string &element geom.Y = stof(v_geom[1]) * spacing.Y; } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); spec.ftype = f_Table; for (std::string &item : items) { - item = wide_to_utf8(unescape_translate( - utf8_to_wide(unescape_string(item)))); + item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item)))); } - // now really show list + //now really show list GUITable *e = new GUITable(Environment, data->current_parent, spec.fid, rect, m_tsrc); @@ -1288,16 +1307,16 @@ void GUIFormSpecMenu::parseTextList(parserData *data, const std::string &element m_fields.push_back(spec); return; } - errorstream << "Invalid textlist element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseDropDown(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element) { std::vector parts = split(element, ';'); if (parts.size() == 5 || parts.size() == 6 || - (parts.size() > 6 && m_formspec_version > FORMSPEC_API_VERSION)) { + (parts.size() > 6 && m_formspec_version > FORMSPEC_API_VERSION)) + { std::vector v_pos = split(parts[0], ','); std::string name = parts[2]; std::vector items = split(parts[3], ','); @@ -1306,53 +1325,57 @@ void GUIFormSpecMenu::parseDropDown(parserData *data, const std::string &element if (parts.size() >= 6 && is_yes(parts[5])) m_dropdown_index_event[name] = true; - MY_CHECKPOS("dropdown", 0); + MY_CHECKPOS("dropdown",0); v2s32 pos; v2s32 geom; core::rect rect; if (data->real_coordinates) { - std::vector v_geom = split(parts[1], ','); + std::vector v_geom = split(parts[1],','); if (v_geom.size() == 1) v_geom.emplace_back("1"); - MY_CHECKGEOM("dropdown", 1); + MY_CHECKGEOM("dropdown",1); pos = getRealCoordinateBasePos(v_pos); geom = getRealCoordinateGeometry(v_geom); - rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + rect = core::rect(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); } else { pos = getElementBasePos(&v_pos); s32 width = stof(parts[1]) * spacing.Y; - rect = core::rect(pos.X, pos.Y, pos.X + width, - pos.Y + (m_btn_height * 2)); + rect = core::rect(pos.X, pos.Y, + pos.X + width, pos.Y + (m_btn_height * 2)); } - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); spec.ftype = f_DropDown; spec.send = true; - // now really show list - gui::IGUIComboBox *e = Environment->addComboBox( - rect, data->current_parent, spec.fid); + //now really show list + gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent, + spec.fid); if (spec.fname == m_focused_element) { Environment->setFocus(e); } for (const std::string &item : items) { - e->addItem(unescape_translate(unescape_string(utf8_to_wide(item))) - .c_str()); + e->addItem(unescape_translate(unescape_string( + utf8_to_wide(item))).c_str()); } if (!str_initial_selection.empty()) - e->setSelected(stoi(str_initial_selection) - 1); + e->setSelected(stoi(str_initial_selection)-1); auto style = getDefaultStyleForElement("dropdown", name); e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); @@ -1368,31 +1391,32 @@ void GUIFormSpecMenu::parseDropDown(parserData *data, const std::string &element return; } errorstream << "Invalid dropdown element(" << parts.size() << "): '" << element - << "'" << std::endl; + << "'" << std::endl; } void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (parts.size() == 2 || (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) { field_close_on_enter[parts[0]] = is_yes(parts[1]); } } -void GUIFormSpecMenu::parsePwdField(parserData *data, const std::string &element) +void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (parts.size() == 4 || - (parts.size() > 4 && m_formspec_version > FORMSPEC_API_VERSION)) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + (parts.size() > 4 && m_formspec_version > FORMSPEC_API_VERSION)) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; - MY_CHECKPOS("pwdfield", 0); - MY_CHECKGEOM("pwdfield", 1); + MY_CHECKPOS("pwdfield",0); + MY_CHECKGEOM("pwdfield",1); v2s32 pos; v2s32 geom; @@ -1406,22 +1430,27 @@ void GUIFormSpecMenu::parsePwdField(parserData *data, const std::string &element geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); - pos.Y += (stof(v_geom[1]) * (float)imgsize.Y) / 2; + pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; pos.Y -= m_btn_height; - geom.Y = m_btn_height * 2; + geom.Y = m_btn_height*2; } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); - std::wstring wlabel = - translate_string(utf8_to_wide(unescape_string(label))); + std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); - FieldSpec spec(name, wlabel, L"", 258 + m_fields.size(), 0, ECI_IBEAM); + FieldSpec spec( + name, + wlabel, + L"", + 258 + m_fields.size(), + 0, + ECI_IBEAM + ); spec.send = true; - gui::IGUIEditBox *e = Environment->addEditBox( - 0, rect, true, data->current_parent, spec.fid); + gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true, + data->current_parent, spec.fid); if (spec.fname == m_focused_element) { Environment->setFocus(e); @@ -1431,25 +1460,24 @@ void GUIFormSpecMenu::parsePwdField(parserData *data, const std::string &element int font_height = g_fontengine->getTextHeight(); rect.UpperLeftCorner.Y -= font_height; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height; - gui::StaticText::add(Environment, spec.flabel.c_str(), rect, - false, true, data->current_parent, 0); + gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true, + data->current_parent, 0); } - e->setPasswordBox(true, L'*'); + e->setPasswordBox(true,L'*'); auto style = getDefaultStyleForElement("pwdfield", name, "field"); e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); e->setDrawBorder(style.getBool(StyleSpec::BORDER, true)); - e->setOverrideColor(style.getColor( - StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); + e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); e->setOverrideFont(style.getFont()); irr::SEvent evt; - evt.EventType = EET_KEY_INPUT_EVENT; - evt.KeyInput.Key = KEY_END; - evt.KeyInput.Char = 0; - evt.KeyInput.Control = false; - evt.KeyInput.Shift = false; + evt.EventType = EET_KEY_INPUT_EVENT; + evt.KeyInput.Key = KEY_END; + evt.KeyInput.Char = 0; + evt.KeyInput.Control = false; + evt.KeyInput.Shift = false; evt.KeyInput.PressedDown = true; e->OnEvent(evt); @@ -1459,17 +1487,15 @@ void GUIFormSpecMenu::parsePwdField(parserData *data, const std::string &element m_fields.push_back(spec); return; } - errorstream << "Invalid pwdfield element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, - core::rect &rect, bool is_multiline) + core::rect &rect, bool is_multiline) { bool is_editable = !spec.fname.empty(); if (!is_editable && !is_multiline) { - // spec field id to 0, this stops submit searching for a value that isn't - // there + // spec field id to 0, this stops submit searching for a value that isn't there gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true, data->current_parent, 0); return; @@ -1477,25 +1503,23 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, if (is_editable) { spec.send = true; - } else if (is_multiline && spec.fdefault.empty() && !spec.flabel.empty()) { + } else if (is_multiline && + spec.fdefault.empty() && !spec.flabel.empty()) { // Multiline textareas: swap default and label for backwards compat spec.flabel.swap(spec.fdefault); } gui::IGUIEditBox *e = nullptr; static constexpr bool use_intl_edit_box = USE_FREETYPE && - IRRLICHT_VERSION_MAJOR == 1 && - IRRLICHT_VERSION_MINOR < 9; + IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9; if (use_intl_edit_box && g_settings->getBool("freetype")) { e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment, - data->current_parent, spec.fid, rect, is_editable, - is_multiline); + data->current_parent, spec.fid, rect, is_editable, is_multiline); } else { if (is_multiline) { - e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, - Environment, data->current_parent, spec.fid, rect, - is_editable, true); + e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment, + data->current_parent, spec.fid, rect, is_editable, true); } else if (is_editable) { e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, data->current_parent, spec.fid); @@ -1503,8 +1527,7 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, } } - auto style = getDefaultStyleForElement( - is_multiline ? "textarea" : "field", spec.fname); + auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname); if (e) { if (is_editable && spec.fname == m_focused_element) @@ -1516,19 +1539,18 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT); } else { irr::SEvent evt; - evt.EventType = EET_KEY_INPUT_EVENT; - evt.KeyInput.Key = KEY_END; - evt.KeyInput.Char = 0; - evt.KeyInput.Control = 0; - evt.KeyInput.Shift = 0; + evt.EventType = EET_KEY_INPUT_EVENT; + evt.KeyInput.Key = KEY_END; + evt.KeyInput.Char = 0; + evt.KeyInput.Control = 0; + evt.KeyInput.Shift = 0; evt.KeyInput.PressedDown = true; e->OnEvent(evt); } e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); e->setDrawBorder(style.getBool(StyleSpec::BORDER, true)); - e->setOverrideColor(style.getColor( - StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); + e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); if (style.get(StyleSpec::BGCOLOR, "") == "transparent") { e->setDrawBackground(false); } @@ -1549,7 +1571,8 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, } } -void GUIFormSpecMenu::parseSimpleField(parserData *data, std::vector &parts) +void GUIFormSpecMenu::parseSimpleField(parserData *data, + std::vector &parts) { std::string name = parts[0]; std::string label = parts[1]; @@ -1558,23 +1581,32 @@ void GUIFormSpecMenu::parseSimpleField(parserData *data, std::vector rect; if (data->explicit_size) - warningstream << "invalid use of unpositioned \"field\" in inventory" - << std::endl; + warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl; v2s32 pos = getElementBasePos(nullptr); pos.Y = (data->simple_field_count + 2) * 60; v2s32 size = DesiredRect.getSize(); - rect = core::rect(size.X / 2 - 150, pos.Y, size.X / 2 - 150 + 300, - pos.Y + m_btn_height * 2); + rect = core::rect( + size.X / 2 - 150, pos.Y, + size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2 + ); + if (m_form_src) default_val = m_form_src->resolveText(default_val); + std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); - FieldSpec spec(name, wlabel, utf8_to_wide(unescape_string(default_val)), - 258 + m_fields.size(), 0, ECI_IBEAM); + FieldSpec spec( + name, + wlabel, + utf8_to_wide(unescape_string(default_val)), + 258 + m_fields.size(), + 0, + ECI_IBEAM + ); createTextField(data, spec, rect, false); @@ -1583,17 +1615,17 @@ void GUIFormSpecMenu::parseSimpleField(parserData *data, std::vectorsimple_field_count++; } -void GUIFormSpecMenu::parseTextArea(parserData *data, std::vector &parts, +void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector& parts, const std::string &type) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; std::string default_val = parts[4]; - MY_CHECKPOS(type, 0); - MY_CHECKGEOM(type, 1); + MY_CHECKPOS(type,0); + MY_CHECKGEOM(type,1); v2s32 pos; v2s32 geom; @@ -1607,31 +1639,38 @@ void GUIFormSpecMenu::parseTextArea(parserData *data, std::vector & geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X); - if (type == "textarea") { - geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - - (spacing.Y - imgsize.Y); + if (type == "textarea") + { + geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y); pos.Y += m_btn_height; - } else { - pos.Y += (stof(v_geom[1]) * (float)imgsize.Y) / 2; + } + else + { + pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; pos.Y -= m_btn_height; - geom.Y = m_btn_height * 2; + geom.Y = m_btn_height*2; } } - core::rect rect = - core::rect(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); - if (!data->explicit_size) - warningstream << "invalid use of positioned " << type - << " without a size[] element" << std::endl; + if(!data->explicit_size) + warningstream<<"invalid use of positioned "<resolveText(default_val); + std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label))); - FieldSpec spec(name, wlabel, utf8_to_wide(unescape_string(default_val)), - 258 + m_fields.size(), 0, ECI_IBEAM); + FieldSpec spec( + name, + wlabel, + utf8_to_wide(unescape_string(default_val)), + 258 + m_fields.size(), + 0, + ECI_IBEAM + ); createTextField(data, spec, rect, type == "textarea"); @@ -1641,24 +1680,23 @@ void GUIFormSpecMenu::parseTextArea(parserData *data, std::vector & m_fields.push_back(spec); } -void GUIFormSpecMenu::parseField( - parserData *data, const std::string &element, const std::string &type) +void GUIFormSpecMenu::parseField(parserData* data, const std::string &element, + const std::string &type) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (parts.size() == 3 || parts.size() == 4) { - parseSimpleField(data, parts); + parseSimpleField(data,parts); return; } if ((parts.size() == 5) || - ((parts.size() > 5) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - parseTextArea(data, parts, type); + ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + parseTextArea(data,parts,type); return; } - errorstream << "Invalid field element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element) @@ -1666,8 +1704,7 @@ void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &elemen std::vector parts = split(element, ';'); if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) { - errorstream << "Invalid text element(" << parts.size() << "): '" - << element << "'" << std::endl; + errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'" << std::endl; return; } @@ -1694,14 +1731,17 @@ void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &elemen pos.Y += m_btn_height; } - core::rect rect = - core::rect(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); - if (m_form_src) + if(m_form_src) text = m_form_src->resolveText(text); - FieldSpec spec(name, utf8_to_wide(unescape_string(text)), L"", - 258 + m_fields.size()); + FieldSpec spec( + name, + utf8_to_wide(unescape_string(text)), + L"", + 258 + m_fields.size() + ); spec.ftype = f_HyperText; GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment, @@ -1711,21 +1751,20 @@ void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &elemen m_fields.push_back(spec); } -void GUIFormSpecMenu::parseLabel(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 2) || - ((parts.size() > 2) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); + ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); std::string text = parts[1]; - MY_CHECKPOS("label", 0); + MY_CHECKPOS("label",0); - if (!data->explicit_size) - warningstream << "invalid use of label without a size[] element" - << std::endl; + if(!data->explicit_size) + warningstream<<"invalid use of label without a size[] element"< lines = split(text, '\n'); @@ -1736,7 +1775,7 @@ void GUIFormSpecMenu::parseLabel(parserData *data, const std::string &element) for (unsigned int i = 0; i != lines.size(); i++) { std::wstring wlabel_colors = translate_string( - utf8_to_wide(unescape_string(lines[i]))); + utf8_to_wide(unescape_string(lines[i]))); // Without color escapes to get the font dimensions std::wstring wlabel_plain = unescape_enriched(wlabel_colors); @@ -1751,13 +1790,12 @@ void GUIFormSpecMenu::parseLabel(parserData *data, const std::string &element) v2s32 pos = getRealCoordinateBasePos(v_pos); // Labels are positioned by their center, not their top. - pos.Y += (((float)imgsize.Y) / -2) + - (((float)imgsize.Y) * i / 2); + pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2); - rect = core::rect(pos.X, pos.Y, - pos.X + font->getDimension(wlabel_plain.c_str()) - .Width, - pos.Y + imgsize.Y); + rect = core::rect( + pos.X, pos.Y, + pos.X + font->getDimension(wlabel_plain.c_str()).Width, + pos.Y + imgsize.Y); } else { // Lines are spaced at the nominal distance of @@ -1774,23 +1812,28 @@ void GUIFormSpecMenu::parseLabel(parserData *data, const std::string &element) pos.X += stof(v_pos[0]) * spacing.X; pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y; - pos.Y += ((float)i) * spacing.Y * 2.0 / 5.0; + pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0; - rect = core::rect(pos.X, pos.Y - m_btn_height, - pos.X + font->getDimension(wlabel_plain.c_str()) - .Width, - pos.Y + m_btn_height); + rect = core::rect( + pos.X, pos.Y - m_btn_height, + pos.X + font->getDimension(wlabel_plain.c_str()).Width, + pos.Y + m_btn_height); } - FieldSpec spec("", wlabel_colors, L"", 258 + m_fields.size(), 4); + FieldSpec spec( + "", + wlabel_colors, + L"", + 258 + m_fields.size(), + 4 + ); gui::IGUIStaticText *e = gui::StaticText::add(Environment, - spec.flabel.c_str(), rect, false, false, - data->current_parent, spec.fid); + spec.flabel.c_str(), rect, false, false, data->current_parent, + spec.fid); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER); e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); - e->setOverrideColor(style.getColor( - StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); + e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); e->setOverrideFont(font); m_fields.push_back(spec); @@ -1803,21 +1846,21 @@ void GUIFormSpecMenu::parseLabel(parserData *data, const std::string &element) return; } errorstream << "Invalid label element(" << parts.size() << "): '" << element - << "'" << std::endl; + << "'" << std::endl; } -void GUIFormSpecMenu::parseVertLabel(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 2) || - ((parts.size() > 2) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); + ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); std::wstring text = unescape_translate( - unescape_string(utf8_to_wide(parts[1]))); + unescape_string(utf8_to_wide(parts[1]))); - MY_CHECKPOS("vertlabel", 1); + MY_CHECKPOS("vertlabel",1); auto style = getDefaultStyleForElement("vertlabel", "", "label"); gui::IGUIFont *font = style.getFont(); @@ -1835,10 +1878,10 @@ void GUIFormSpecMenu::parseVertLabel(parserData *data, const std::string &elemen // We use text.length + 1 because without it, the rect // isn't quite tall enough and cuts off the text. - rect = core::rect(pos.X, pos.Y, pos.X + imgsize.X, - pos.Y + font_line_height(font) * - (text.length() + - 1)); + rect = core::rect(pos.X, pos.Y, + pos.X + imgsize.X, + pos.Y + font_line_height(font) * + (text.length() + 1)); } else { pos = getElementBasePos(&v_pos); @@ -1846,19 +1889,16 @@ void GUIFormSpecMenu::parseVertLabel(parserData *data, const std::string &elemen // As above, the length must be one longer. The width of // the rect (15 pixels) seems rather arbitrary, but // changing it might break something. - rect = core::rect(pos.X, - pos.Y + ((imgsize.Y / 2) - m_btn_height), - pos.X + 15, - pos.Y + - font_line_height(font) * - (text.length() + - 1) + - ((imgsize.Y / 2) - m_btn_height)); + rect = core::rect( + pos.X, pos.Y+((imgsize.Y/2) - m_btn_height), + pos.X+15, pos.Y + + font_line_height(font) * + (text.length() + 1) + + ((imgsize.Y/2) - m_btn_height)); } - if (!data->explicit_size) - warningstream << "invalid use of label without a size[] element" - << std::endl; + if(!data->explicit_size) + warningstream<<"invalid use of label without a size[] element"<current_parent, spec.fid); + FieldSpec spec( + "", + label, + L"", + 258 + m_fields.size() + ); + gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(), + rect, false, false, data->current_parent, spec.fid); e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); - e->setOverrideColor(style.getColor( - StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); + e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); e->setOverrideFont(font); m_fields.push_back(spec); @@ -1885,26 +1928,25 @@ void GUIFormSpecMenu::parseVertLabel(parserData *data, const std::string &elemen m_clickthrough_elements.push_back(e); return; } - errorstream << "Invalid vertlabel element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseImageButton( - parserData *data, const std::string &element, const std::string &type) +void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element, + const std::string &type) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) || - ((parts.size() > 8) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string image_name = parts[2]; std::string name = parts[3]; std::string label = parts[4]; - MY_CHECKPOS("imagebutton", 0); - MY_CHECKGEOM("imagebutton", 1); + MY_CHECKPOS("imagebutton",0); + MY_CHECKGEOM("imagebutton",1); std::string pressed_image_name; @@ -1924,21 +1966,23 @@ void GUIFormSpecMenu::parseImageButton( geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y); } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, + pos.Y+geom.Y); if (!data->explicit_size) - warningstream << "invalid use of image_button without a size[] " - "element" - << std::endl; + warningstream<<"invalid use of image_button without a size[] element"<= 7) { style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]); @@ -1972,19 +2015,18 @@ void GUIFormSpecMenu::parseImageButton( return; } - errorstream << "Invalid imagebutton element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTabHeader(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element) { std::vector parts = split(element, ';'); - if (((parts.size() == 4) || (parts.size() == 6)) || - (parts.size() == 7 && data->real_coordinates) || - ((parts.size() > 6) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); + if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 && + data->real_coordinates) || ((parts.size() > 6) && + (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); // If we're using real coordinates, add an extra field for height. // Width is not here because tabs are the width of the text, and @@ -2002,9 +2044,9 @@ void GUIFormSpecMenu::parseTabHeader(parserData *data, const std::string &elemen auto_width = false; } - std::string name = parts[i + 1]; - std::vector buttons = split(parts[i + 2], ','); - std::string str_index = parts[i + 3]; + std::string name = parts[i+1]; + std::vector buttons = split(parts[i+2], ','); + std::string str_index = parts[i+3]; bool show_background = true; bool show_border = true; int tab_index = stoi(str_index) - 1; @@ -2012,13 +2054,18 @@ void GUIFormSpecMenu::parseTabHeader(parserData *data, const std::string &elemen MY_CHECKPOS("tabheader", 0); if (parts.size() == 6 + i) { - if (parts[4 + i] == "true") + if (parts[4+i] == "true") show_background = false; - if (parts[5 + i] == "false") + if (parts[5+i] == "false") show_border = false; } - FieldSpec spec(name, L"", L"", 258 + m_fields.size()); + FieldSpec spec( + name, + L"", + L"", + 258 + m_fields.size() + ); spec.ftype = f_TabHeader; @@ -2047,12 +2094,11 @@ void GUIFormSpecMenu::parseTabHeader(parserData *data, const std::string &elemen geom.X = DesiredRect.getWidth(); } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, + pos.Y+geom.Y); - gui::IGUITabControl *e = - Environment->addTabControl(rect, data->current_parent, - show_background, show_border, spec.fid); + gui::IGUITabControl *e = Environment->addTabControl(rect, + data->current_parent, show_background, show_border, spec.fid); e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT); e->setTabHeight(geom.Y); @@ -2061,45 +2107,41 @@ void GUIFormSpecMenu::parseTabHeader(parserData *data, const std::string &elemen e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true)); for (const std::string &button : buttons) { - auto tab = e->addTab( - unescape_translate(unescape_string(utf8_to_wide( - button))) - .c_str(), - -1); + auto tab = e->addTab(unescape_translate(unescape_string( + utf8_to_wide(button))).c_str(), -1); if (style.isNotDefault(StyleSpec::BGCOLOR)) - tab->setBackgroundColor( - style.getColor(StyleSpec::BGCOLOR)); + tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR)); - tab->setTextColor(style.getColor( - StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); + tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF))); } - if ((tab_index >= 0) && (buttons.size() < INT_MAX) && - (tab_index < (int)buttons.size())) + if ((tab_index >= 0) && + (buttons.size() < INT_MAX) && + (tab_index < (int) buttons.size())) e->setActiveTab(tab_index); m_fields.push_back(spec); return; } - errorstream << "Invalid TabHeader element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream << "Invalid TabHeader element(" << parts.size() << "): '" + << element << "'" << std::endl; } -void GUIFormSpecMenu::parseItemImageButton(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element) { if (m_client == 0) { warningstream << "invalid use of item_image_button with m_client==0" - << std::endl; + << std::endl; return; } - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 5) || - ((parts.size() > 5) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); std::string item_name = parts[2]; std::string name = parts[3]; std::string label = parts[4]; @@ -2107,8 +2149,8 @@ void GUIFormSpecMenu::parseItemImageButton(parserData *data, const std::string & label = unescape_string(label); item_name = unescape_string(item_name); - MY_CHECKPOS("itemimagebutton", 0); - MY_CHECKGEOM("itemimagebutton", 1); + MY_CHECKPOS("itemimagebutton",0); + MY_CHECKGEOM("itemimagebutton",1); v2s32 pos; v2s32 geom; @@ -2122,32 +2164,34 @@ void GUIFormSpecMenu::parseItemImageButton(parserData *data, const std::string & geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y); } - core::rect rect = core::rect( - pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y); + core::rect rect = core::rect(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); - if (!data->explicit_size) - warningstream << "invalid use of item_image_button without a " - "size[] element" - << std::endl; + if(!data->explicit_size) + warningstream<<"invalid use of item_image_button without a size[] element"<idef(); ItemStack item; item.deSerialize(item_name, idef); - m_tooltips[name] = TooltipSpec( - utf8_to_wide(item.getDefinition(idef).description), - m_default_tooltip_bgcolor, m_default_tooltip_color); + m_tooltips[name] = + TooltipSpec(utf8_to_wide(item.getDefinition(idef).description), + m_default_tooltip_bgcolor, + m_default_tooltip_color); // the spec for the button - FieldSpec spec_btn(name, utf8_to_wide(label), utf8_to_wide(item_name), - 258 + m_fields.size(), 2); + FieldSpec spec_btn( + name, + utf8_to_wide(label), + utf8_to_wide(item_name), + 258 + m_fields.size(), + 2 + ); GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment, - rect, m_tsrc, data->current_parent, spec_btn.fid, - spec_btn.flabel.c_str(), item_name, m_client); + rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(), + item_name, m_client); - auto style = getStyleForElement( - "item_image_button", spec_btn.fname, "image_button"); + auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button"); e_btn->setStyles(style); if (spec_btn.fname == m_focused_element) { @@ -2155,27 +2199,26 @@ void GUIFormSpecMenu::parseItemImageButton(parserData *data, const std::string & } spec_btn.ftype = f_Button; - rect += data->basepos - padding; + rect += data->basepos-padding; spec_btn.rect = rect; m_fields.push_back(spec_btn); return; } - errorstream << "Invalid ItemImagebutton element(" << parts.size() << "): '" - << element << "'" << std::endl; + errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseBox(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if ((parts.size() == 3) || - ((parts.size() > 3) && - (m_formspec_version > FORMSPEC_API_VERSION))) { - std::vector v_pos = split(parts[0], ','); - std::vector v_geom = split(parts[1], ','); + ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION))) + { + std::vector v_pos = split(parts[0],','); + std::vector v_geom = split(parts[1],','); - MY_CHECKPOS("box", 0); - MY_CHECKGEOM("box", 1); + MY_CHECKPOS("box",0); + MY_CHECKGEOM("box",1); v2s32 pos; v2s32 geom; @@ -2192,42 +2235,44 @@ void GUIFormSpecMenu::parseBox(parserData *data, const std::string &element) video::SColor tmp_color; if (parseColorString(parts[2], tmp_color, false, 0x8C)) { - FieldSpec spec("", L"", L"", 258 + m_fields.size(), -2); + FieldSpec spec( + "", + L"", + L"", + 258 + m_fields.size(), + -2 + ); spec.ftype = f_Box; core::rect rect(pos, pos + geom); - GUIBox *e = new GUIBox(Environment, data->current_parent, - spec.fid, rect, tmp_color); + GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid, + rect, tmp_color); auto style = getDefaultStyleForElement("box", spec.fname); - e->setNotClipped(style.getBool( - StyleSpec::NOCLIP, m_formspec_version < 3)); + e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3)); e->drop(); m_fields.push_back(spec); } else { - errorstream << "Invalid Box element(" << parts.size() << "): '" - << element << "' INVALID COLOR" << std::endl; + errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl; } return; } - errorstream << "Invalid Box element(" << parts.size() << "): '" << element << "'" - << std::endl; + errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseBackgroundColor(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); const u32 parameter_count = parts.size(); if ((parameter_count > 2 && m_formspec_version < 3) || - (parameter_count > 3 && - m_formspec_version <= FORMSPEC_API_VERSION)) { + (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) { errorstream << "Invalid bgcolor element(" << parameter_count << "): '" - << element << "'" << std::endl; + << element << "'" << std::endl; return; } @@ -2254,20 +2299,19 @@ void GUIFormSpecMenu::parseBackgroundColor(parserData *data, const std::string & parseColorString(parts[2], m_fullscreen_bgcolor, false); } -void GUIFormSpecMenu::parseListColors(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) || - ((parts.size() > 5) && - (m_formspec_version > FORMSPEC_API_VERSION))) { + ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION))) + { parseColorString(parts[0], data->inventorylist_options.slotbg_n, false); parseColorString(parts[1], data->inventorylist_options.slotbg_h, false); if (parts.size() >= 3) { - if (parseColorString(parts[2], - data->inventorylist_options.slotbordercolor, - false)) { + if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor, + false)) { data->inventorylist_options.slotborder = true; } } @@ -2289,16 +2333,15 @@ void GUIFormSpecMenu::parseListColors(parserData *data, const std::string &eleme } return; } - errorstream << "Invalid listcolors element(" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTooltip(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element) { - std::vector parts = split(element, ';'); + std::vector parts = split(element,';'); if (parts.size() < 2) { errorstream << "Invalid tooltip element(" << parts.size() << "): '" - << element << "'" << std::endl; + << element << "'" << std::endl; return; } @@ -2307,19 +2350,18 @@ void GUIFormSpecMenu::parseTooltip(parserData *data, const std::string &element) size_t base_size = rect_mode ? 3 : 2; if (parts.size() != base_size && parts.size() != base_size + 2) { errorstream << "Invalid tooltip element(" << parts.size() << "): '" - << element << "'" << std::endl; + << element << "'" << std::endl; return; } // Read colors video::SColor bgcolor = m_default_tooltip_bgcolor; - video::SColor color = m_default_tooltip_color; + video::SColor color = m_default_tooltip_color; if (parts.size() == base_size + 2 && (!parseColorString(parts[base_size], bgcolor, false) || - !parseColorString(parts[base_size + 1], color, - false))) { + !parseColorString(parts[base_size + 1], color, false))) { errorstream << "Invalid color in tooltip element(" << parts.size() - << "): '" << element << "'" << std::endl; + << "): '" << element << "'" << std::endl; return; } @@ -2329,7 +2371,7 @@ void GUIFormSpecMenu::parseTooltip(parserData *data, const std::string &element) // Add tooltip if (rect_mode) { - std::vector v_pos = split(parts[0], ','); + std::vector v_pos = split(parts[0], ','); std::vector v_geom = split(parts[1], ','); MY_CHECKPOS("tooltip", 0); @@ -2347,7 +2389,12 @@ void GUIFormSpecMenu::parseTooltip(parserData *data, const std::string &element) geom.Y = stof(v_geom[1]) * spacing.Y; } - FieldSpec fieldspec("", L"", L"", 258 + m_fields.size()); + FieldSpec fieldspec( + "", + L"", + L"", + 258 + m_fields.size() + ); core::rect rect(pos, pos + geom); @@ -2367,11 +2414,11 @@ void GUIFormSpecMenu::parseTooltip(parserData *data, const std::string &element) bool GUIFormSpecMenu::parseVersionDirect(const std::string &data) { - // some prechecks + //some prechecks if (data.empty()) return false; - std::vector parts = split(data, '['); + std::vector parts = split(data,'['); if (parts.size() < 2) { return false; @@ -2389,12 +2436,12 @@ bool GUIFormSpecMenu::parseVersionDirect(const std::string &data) return false; } -bool GUIFormSpecMenu::parseSizeDirect(parserData *data, const std::string &element) +bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element) { if (element.empty()) return false; - std::vector parts = split(element, '['); + std::vector parts = split(element,'['); if (parts.size() < 2) return false; @@ -2406,8 +2453,7 @@ bool GUIFormSpecMenu::parseSizeDirect(parserData *data, const std::string &eleme return false; if (type == "invsize") - warningstream << "Deprecated formspec element \"invsize\" is used" - << std::endl; + warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl; parseSize(data, description); @@ -2445,8 +2491,7 @@ void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element return; } - errorstream << "Invalid position element (" << parts.size() << "): '" << element - << "'" << std::endl; + errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl; } bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element) @@ -2481,17 +2526,16 @@ void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element) } errorstream << "Invalid anchor element (" << parts.size() << "): '" << element - << "'" << std::endl; + << "'" << std::endl; } -bool GUIFormSpecMenu::parseStyle( - parserData *data, const std::string &element, bool style_type) +bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type) { std::vector parts = split(element, ';'); if (parts.size() < 2) { - errorstream << "Invalid style element (" << parts.size() << "): '" - << element << "'" << std::endl; + errorstream << "Invalid style element (" << parts.size() << "): '" << element + << "'" << std::endl; return false; } @@ -2501,24 +2545,22 @@ bool GUIFormSpecMenu::parseStyle( for (size_t i = 1; i < parts.size(); i++) { size_t equal_pos = parts[i].find('='); if (equal_pos == std::string::npos) { - errorstream << "Invalid style element (Property missing value): '" - << element << "'" << std::endl; + errorstream << "Invalid style element (Property missing value): '" << element + << "'" << std::endl; return false; } std::string propname = trim(parts[i].substr(0, equal_pos)); - std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1))); + std::string value = trim(unescape_string(parts[i].substr(equal_pos + 1))); - std::transform(propname.begin(), propname.end(), propname.begin(), - ::tolower); + std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower); StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname); if (prop == StyleSpec::NONE) { if (property_warned.find(propname) != property_warned.end()) { - warningstream << "Invalid style element (Unknown " - "property " - << propname << "): '" << element << "'" - << std::endl; + warningstream << "Invalid style element (Unknown property " << propname << "): '" + << element + << "'" << std::endl; property_warned.insert(propname); } continue; @@ -2543,18 +2585,16 @@ bool GUIFormSpecMenu::parseStyle( selector = selector.substr(0, state_pos); if (state_str.empty()) { - errorstream << "Invalid style element (Invalid state): '" - << element << "'" << std::endl; + errorstream << "Invalid style element (Invalid state): '" << element + << "'" << std::endl; state_valid = false; } else { std::vector states = split(state_str, '+'); for (std::string &state : states) { - StyleSpec::State converted = - StyleSpec::getStateByName(state); + StyleSpec::State converted = StyleSpec::getStateByName(state); if (converted == StyleSpec::STATE_INVALID) { - infostream << "Unknown style state " - << state << " in element '" - << element << "'" << std::endl; + infostream << "Unknown style state " << state << + " in element '" << element << "'" << std::endl; state_valid = false; break; } @@ -2576,29 +2616,20 @@ bool GUIFormSpecMenu::parseStyle( } // Backwards-compatibility for existing _hovered/_pressed properties - if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED) || - selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED) || - selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) { + if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED) + || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED) + || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) { StyleSpec hover_spec; hover_spec.addState(StyleSpec::STATE_HOVERED); if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) { - hover_spec.set(StyleSpec::BGCOLOR, - selector_spec.get( - StyleSpec::BGCOLOR_HOVERED, - "")); + hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, "")); } if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) { - hover_spec.set(StyleSpec::BGIMG, - selector_spec.get( - StyleSpec::BGIMG_HOVERED, - "")); + hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, "")); } if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) { - hover_spec.set(StyleSpec::FGIMG, - selector_spec.get( - StyleSpec::FGIMG_HOVERED, - "")); + hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, "")); } if (style_type) { @@ -2607,29 +2638,20 @@ bool GUIFormSpecMenu::parseStyle( theme_by_name[selector].push_back(hover_spec); } } - if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED) || - selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED) || - selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) { + if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED) + || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED) + || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) { StyleSpec press_spec; press_spec.addState(StyleSpec::STATE_PRESSED); if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) { - press_spec.set(StyleSpec::BGCOLOR, - selector_spec.get( - StyleSpec::BGCOLOR_PRESSED, - "")); + press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, "")); } if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) { - press_spec.set(StyleSpec::BGIMG, - selector_spec.get( - StyleSpec::BGIMG_PRESSED, - "")); + press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, "")); } if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) { - press_spec.set(StyleSpec::FGIMG, - selector_spec.get( - StyleSpec::FGIMG_PRESSED, - "")); + press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, "")); } if (style_type) { @@ -2648,7 +2670,8 @@ void GUIFormSpecMenu::parseSetFocus(const std::string &element) std::vector parts = split(element, ';'); if (parts.size() <= 2 || - (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) { + (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) + { if (m_is_form_regenerated) return; // Never focus on resizing @@ -2660,12 +2683,12 @@ void GUIFormSpecMenu::parseSetFocus(const std::string &element) } errorstream << "Invalid set_focus element (" << parts.size() << "): '" << element - << "'" << std::endl; + << "'" << std::endl; } -void GUIFormSpecMenu::parseElement(parserData *data, const std::string &element) +void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element) { - // some prechecks + //some prechecks if (element.empty()) return; @@ -2677,7 +2700,7 @@ void GUIFormSpecMenu::parseElement(parserData *data, const std::string &element) return; std::string type = trim(element.substr(0, pos)); - std::string description = element.substr(pos + 1); + std::string description = element.substr(pos+1); if (type == "container") { parseContainer(data, description); @@ -2729,28 +2752,28 @@ void GUIFormSpecMenu::parseElement(parserData *data, const std::string &element) return; } - if (type == "tableoptions") { - parseTableOptions(data, description); + if (type == "tableoptions"){ + parseTableOptions(data,description); return; } - if (type == "tablecolumns") { - parseTableColumns(data, description); + if (type == "tablecolumns"){ + parseTableColumns(data,description); return; } - if (type == "table") { - parseTable(data, description); + if (type == "table"){ + parseTable(data,description); return; } - if (type == "textlist") { - parseTextList(data, description); + if (type == "textlist"){ + parseTextList(data,description); return; } - if (type == "dropdown") { - parseDropDown(data, description); + if (type == "dropdown"){ + parseDropDown(data,description); return; } @@ -2760,62 +2783,62 @@ void GUIFormSpecMenu::parseElement(parserData *data, const std::string &element) } if (type == "pwdfield") { - parsePwdField(data, description); + parsePwdField(data,description); return; } - if ((type == "field") || (type == "textarea")) { - parseField(data, description, type); + if ((type == "field") || (type == "textarea")){ + parseField(data,description,type); return; } if (type == "hypertext") { - parseHyperText(data, description); + parseHyperText(data,description); return; } if (type == "label") { - parseLabel(data, description); + parseLabel(data,description); return; } if (type == "vertlabel") { - parseVertLabel(data, description); + parseVertLabel(data,description); return; } if (type == "item_image_button") { - parseItemImageButton(data, description); + parseItemImageButton(data,description); return; } if ((type == "image_button") || (type == "image_button_exit")) { - parseImageButton(data, description, type); + parseImageButton(data,description,type); return; } if (type == "tabheader") { - parseTabHeader(data, description); + parseTabHeader(data,description); return; } if (type == "box") { - parseBox(data, description); + parseBox(data,description); return; } if (type == "bgcolor") { - parseBackgroundColor(data, description); + parseBackgroundColor(data,description); return; } if (type == "listcolors") { - parseListColors(data, description); + parseListColors(data,description); return; } if (type == "tooltip") { - parseTooltip(data, description); + parseTooltip(data,description); return; } @@ -2860,8 +2883,8 @@ void GUIFormSpecMenu::parseElement(parserData *data, const std::string &element) } // Ignore others - infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description - << "\"" << std::endl; + infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\"" + << std::endl; } void GUIFormSpecMenu::regenerateGui(v2u32 screensize) @@ -2956,33 +2979,33 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) { v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color"); - m_bgcolor = video::SColor((u8)clamp_u8(g_settings->getS32( - "formspec_default_bg_opacity")), - clamp_u8(myround(formspec_bgcolor.X)), - clamp_u8(myround(formspec_bgcolor.Y)), - clamp_u8(myround(formspec_bgcolor.Z))); + m_bgcolor = video::SColor( + (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")), + clamp_u8(myround(formspec_bgcolor.X)), + clamp_u8(myround(formspec_bgcolor.Y)), + clamp_u8(myround(formspec_bgcolor.Z)) + ); } { v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color"); m_fullscreen_bgcolor = video::SColor( - (u8)clamp_u8(g_settings->getS32( - "formspec_fullscreen_bg_opacity")), - clamp_u8(myround(formspec_bgcolor.X)), - clamp_u8(myround(formspec_bgcolor.Y)), - clamp_u8(myround(formspec_bgcolor.Z))); + (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")), + clamp_u8(myround(formspec_bgcolor.X)), + clamp_u8(myround(formspec_bgcolor.Y)), + clamp_u8(myround(formspec_bgcolor.Z)) + ); } - m_default_tooltip_bgcolor = video::SColor(255, 110, 130, 60); - m_default_tooltip_color = video::SColor(255, 255, 255, 255); + m_default_tooltip_bgcolor = video::SColor(255,110,130,60); + m_default_tooltip_color = video::SColor(255,255,255,255); // Add tooltip { assert(!m_tooltip_element); - // Note: parent != this so that the tooltip isn't clipped by the menu - // rectangle - m_tooltip_element = gui::StaticText::add( - Environment, L"", core::rect(0, 0, 110, 18)); + // Note: parent != this so that the tooltip isn't clipped by the menu rectangle + m_tooltip_element = gui::StaticText::add(Environment, L"", + core::rect(0, 0, 110, 18)); m_tooltip_element->enableOverrideColor(true); m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor); m_tooltip_element->setDrawBackground(true); @@ -2990,11 +3013,11 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) m_tooltip_element->setOverrideColor(m_default_tooltip_color); m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); m_tooltip_element->setWordWrap(false); - // we're not parent so no autograb for this one! + //we're not parent so no autograb for this one! m_tooltip_element->grab(); } - std::vector elements = split(m_formspec_string, ']'); + std::vector elements = split(m_formspec_string,']'); unsigned int i = 0; /* try to read version from first element only */ @@ -3006,28 +3029,27 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) /* we need size first in order to calculate image scale */ mydata.explicit_size = false; - for (; i < elements.size(); i++) { + for (; i< elements.size(); i++) { if (!parseSizeDirect(&mydata, elements[i])) { break; } } /* "position" element is always after "size" element if it used */ - for (; i < elements.size(); i++) { + for (; i< elements.size(); i++) { if (!parsePositionDirect(&mydata, elements[i])) { break; } } /* "anchor" element is always after "position" (or "size" element) if it used */ - for (; i < elements.size(); i++) { + for (; i< elements.size(); i++) { if (!parseAnchorDirect(&mydata, elements[i])) { break; } } - /* "no_prepend" element is always after "position" (or "size" element) if it used - */ + /* "no_prepend" element is always after "position" (or "size" element) if it used */ bool enable_prepends = true; for (; i < elements.size(); i++) { if (elements[i].empty()) @@ -3054,8 +3076,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) if (mydata.explicit_size) { // compute scaling for specified form size if (m_lock) { - v2u32 current_screensize = RenderingEngine::get_video_driver() - ->getScreenSize(); + v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize(); v2u32 delta = current_screensize - m_lockscreensize; if (current_screensize.Y > m_lockscreensize.Y) @@ -3068,11 +3089,11 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) else delta.X = 0; - offset = v2s32(delta.X, delta.Y); + offset = v2s32(delta.X,delta.Y); mydata.screensize = m_lockscreensize; } else { - offset = v2s32(0, 0); + offset = v2s32(0,0); } double gui_scaling = g_settings->getFloat("gui_scaling"); @@ -3109,23 +3130,21 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) // maximum screen space available. double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling; double fitx_imgsize = mydata.screensize.X / - ((12.0 / 8.0) * (0.5 + mydata.invsize.X)); + ((12.0 / 8.0) * (0.5 + mydata.invsize.X)); double fity_imgsize = mydata.screensize.Y / - ((15.0 / 11.0) * (0.85 + mydata.invsize.Y)); + ((15.0 / 11.0) * (0.85 + mydata.invsize.Y)); use_imgsize = MYMIN(prefer_imgsize, MYMIN(fitx_imgsize, fity_imgsize)); #else double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling; double fitx_imgsize = mydata.screensize.X / - ((5.0 / 4.0) * (0.5 + mydata.invsize.X)); + ((5.0 / 4.0) * (0.5 + mydata.invsize.X)); double fity_imgsize = mydata.screensize.Y / - ((15.0 / 13.0) * (0.85 * mydata.invsize.Y)); + ((15.0 / 13.0) * (0.85 * mydata.invsize.Y)); double screen_dpi = RenderingEngine::getDisplayDensity() * 96; double min_imgsize = 0.3 * screen_dpi * gui_scaling; - use_imgsize = MYMAX(min_imgsize, - MYMIN(prefer_imgsize, - MYMIN(fitx_imgsize, - fity_imgsize))); + use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize, + MYMIN(fitx_imgsize, fity_imgsize))); #endif } @@ -3138,45 +3157,30 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) // is 2/5 vertical inventory slot spacing, and button // half-height is 7/8 of font height. imgsize = v2s32(use_imgsize, use_imgsize); - spacing = v2f32(use_imgsize * 5.0 / 4, use_imgsize * 15.0 / 13); - padding = v2s32(use_imgsize * 3.0 / 8, use_imgsize * 3.0 / 8); - m_btn_height = use_imgsize * 15.0 / 13 * 0.35; + spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13); + padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8); + m_btn_height = use_imgsize*15.0/13 * 0.35; m_font = g_fontengine->getFont(); if (mydata.real_coordinates) { - mydata.size = v2s32(mydata.invsize.X * imgsize.X, - mydata.invsize.Y * imgsize.Y); + mydata.size = v2s32( + mydata.invsize.X*imgsize.X, + mydata.invsize.Y*imgsize.Y + ); } else { mydata.size = v2s32( - padding.X * 2 + - spacing.X * (mydata.invsize.X - - 1.0) + - imgsize.X, - padding.Y * 2 + - spacing.Y * (mydata.invsize.Y - - 1.0) + - imgsize.Y + - m_btn_height * 2.0 / 3.0); + padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X, + padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0 + ); } DesiredRect = mydata.rect = core::rect( - (s32)((f32)mydata.screensize.X * mydata.offset.X) - - (s32)(mydata.anchor.X * - (f32)mydata.size.X) + - offset.X, - (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - - (s32)(mydata.anchor.Y * - (f32)mydata.size.Y) + - offset.Y, - (s32)((f32)mydata.screensize.X * mydata.offset.X) + - (s32)((1.0 - mydata.anchor.X) * - (f32)mydata.size.X) + - offset.X, - (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + - (s32)((1.0 - mydata.anchor.Y) * - (f32)mydata.size.Y) + - offset.Y); + (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X, + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y, + (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X, + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y + ); } else { // Non-size[] form must consist only of text fields and // implicit "Proceed" button. Use default font, and @@ -3184,14 +3188,11 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) m_font = g_fontengine->getFont(); m_btn_height = font_line_height(m_font) * 0.875; DesiredRect = core::rect( - (s32)((f32)mydata.screensize.X * mydata.offset.X) - - (s32)(mydata.anchor.X * 580.0), - (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - - (s32)(mydata.anchor.Y * 300.0), - (s32)((f32)mydata.screensize.X * mydata.offset.X) + - (s32)((1.0 - mydata.anchor.X) * 580.0), - (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + - (s32)((1.0 - mydata.anchor.Y) * 300.0)); + (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0), + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0), + (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0), + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0) + ); } recalculateAbsolutePosition(false); mydata.basepos = getBasePos(); @@ -3208,14 +3209,12 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) core::list::Iterator legacy_sort_start = Children.getLast(); if (enable_prepends) { - // Backup the coordinates so that prepends can use the coordinates of - // choice. + // Backup the coordinates so that prepends can use the coordinates of choice. bool rc_backup = mydata.real_coordinates; u16 version_backup = m_formspec_version; mydata.real_coordinates = false; // Old coordinates by default. - std::vector prepend_elements = - split(m_formspec_prepend, ']'); + std::vector prepend_elements = split(m_formspec_prepend, ']'); for (const auto &element : prepend_elements) parseElement(&mydata, element); @@ -3231,22 +3230,20 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) mydata.real_coordinates = rc_backup; // Restore coordinates } - for (; i < elements.size(); i++) { + for (; i< elements.size(); i++) { parseElement(&mydata, elements[i]); } if (mydata.current_parent != this) { - errorstream << "Invalid formspec string: scroll_container was never " - "closed!" - << std::endl; + errorstream << "Invalid formspec string: scroll_container was never closed!" + << std::endl; } else if (!container_stack.empty()) { errorstream << "Invalid formspec string: container was never closed!" - << std::endl; + << std::endl; } // get the scrollbar elements for scroll_containers - for (const std::pair &c : - m_scroll_containers) { + for (const std::pair &c : m_scroll_containers) { for (const std::pair &b : m_scrollbars) { if (c.first == b.first.fname) { c.second->setScrollBar(b.second); @@ -3258,11 +3255,12 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) // If there are fields without explicit size[], add a "Proceed" // button and adjust size to fit all the fields. if (mydata.simple_field_count > 0 && !mydata.explicit_size) { - mydata.rect = core::rect(mydata.screensize.X / 2 - 580 / 2, + mydata.rect = core::rect( + mydata.screensize.X / 2 - 580 / 2, mydata.screensize.Y / 2 - 300 / 2, mydata.screensize.X / 2 + 580 / 2, - mydata.screensize.Y / 2 + 240 / 2 + - mydata.simple_field_count * 60); + mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60 + ); DesiredRect = mydata.rect; recalculateAbsolutePosition(false); @@ -3273,19 +3271,21 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) pos.Y = (mydata.simple_field_count + 2) * 60; v2s32 size = DesiredRect.getSize(); - mydata.rect = core::rect(size.X / 2 - 70, pos.Y, - size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2); + mydata.rect = core::rect( + size.X / 2 - 70, pos.Y, + size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2 + ); const wchar_t *text = wgettext("Proceed"); - GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, - text); + GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text); delete[] text; } } // Set initial focus if parser didn't set it gui::IGUIElement *focused_element = Environment->getFocus(); - if (!focused_element || !isMyChild(focused_element) || - focused_element->getType() == gui::EGUIET_TAB_CONTROL) + if (!focused_element + || !isMyChild(focused_element) + || focused_element->getType() == gui::EGUIET_TAB_CONTROL) setInitialFocus(); skin->setFont(old_font); @@ -3329,12 +3329,12 @@ void GUIFormSpecMenu::legacySortElements(core::list::Iterator fro // 2: Sort the container std::stable_sort(elements.begin(), elements.end(), - [this](const IGUIElement *a, const IGUIElement *b) -> bool { - const FieldSpec *spec_a = getSpecByID(a->getID()); - const FieldSpec *spec_b = getSpecByID(b->getID()); - return spec_a && spec_b && - spec_a->priority < spec_b->priority; - }); + [this] (const IGUIElement *a, const IGUIElement *b) -> bool { + const FieldSpec *spec_a = getSpecByID(a->getID()); + const FieldSpec *spec_b = getSpecByID(b->getID()); + return spec_a && spec_b && + spec_a->priority < spec_b->priority; + }); // 3: Re-assign the pointers for (auto e : elements) { @@ -3379,8 +3379,8 @@ GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const for (const GUIInventoryList *e : m_inventorylists) { s32 item_index = e->getItemIndexAtPos(p); if (item_index != -1) - return GUIInventoryList::ItemSpec(e->getInventoryloc(), - e->getListname(), item_index); + return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(), + item_index); } return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1); @@ -3388,13 +3388,13 @@ GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const void GUIFormSpecMenu::drawSelectedItem() { - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); if (!m_selected_item) { // reset rotation time drawItemStack(driver, m_font, ItemStack(), - core::rect(v2s32(0, 0), v2s32(0, 0)), NULL, m_client, - IT_ROT_DRAGGED); + core::rect(v2s32(0, 0), v2s32(0, 0)), NULL, + m_client, IT_ROT_DRAGGED); return; } @@ -3405,7 +3405,7 @@ void GUIFormSpecMenu::drawSelectedItem() ItemStack stack = list->getItem(m_selected_item->i); stack.count = m_selected_amount; - core::rect imgrect(0, 0, imgsize.X, imgsize.Y); + core::rect imgrect(0,0,imgsize.X,imgsize.Y); core::rect rect = imgrect + (m_pointer - imgrect.getCenter()); rect.constrainTo(driver->getViewPort()); drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED); @@ -3422,7 +3422,7 @@ void GUIFormSpecMenu::drawMenu() } } - gui::IGUISkin *skin = Environment->getSkin(); + gui::IGUISkin* skin = Environment->getSkin(); sanity_check(skin != NULL); gui::IGUIFont *old_font = skin->getFont(); skin->setFont(m_font); @@ -3431,7 +3431,7 @@ void GUIFormSpecMenu::drawMenu() updateSelectedItem(); - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); /* Draw background color @@ -3491,8 +3491,8 @@ void GUIFormSpecMenu::drawMenu() if (m_hovered_item_tooltips.empty()) { // reset rotation time drawItemStack(driver, m_font, ItemStack(), - core::rect(v2s32(0, 0), v2s32(0, 0)), NULL, m_client, - IT_ROT_HOVERED); + core::rect(v2s32(0, 0), v2s32(0, 0)), + NULL, m_client, IT_ROT_HOVERED); } /* TODO find way to show tooltips on touchscreen */ @@ -3507,8 +3507,8 @@ void GUIFormSpecMenu::drawMenu() Environment->getRootGUIElement()->getElementFromPoint(m_pointer); #ifndef HAVE_TOUCHSCREENGUI - gui::ICursorControl *cursor_control = - RenderingEngine::get_raw_device()->getCursorControl(); + gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()-> + getCursorControl(); gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon(); #endif bool hovered_element_found = false; @@ -3525,8 +3525,7 @@ void GUIFormSpecMenu::drawMenu() m_old_tooltip_id = id; } else { if (id == m_old_tooltip_id) { - delta = porting::getDeltaMs( - m_hovered_time, porting::getTimeMs()); + delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs()); } else { m_hovered_time = porting::getTimeMs(); m_old_tooltip_id = id; @@ -3541,19 +3540,14 @@ void GUIFormSpecMenu::drawMenu() continue; if (delta >= m_tooltip_show_delay) { - const std::wstring &text = - m_tooltips[field.fname].tooltip; + const std::wstring &text = m_tooltips[field.fname].tooltip; if (!text.empty()) - showTooltip(text, - m_tooltips[field.fname] - .color, - m_tooltips[field.fname] - .bgcolor); + showTooltip(text, m_tooltips[field.fname].color, + m_tooltips[field.fname].bgcolor); } #ifndef HAVE_TOUCHSCREENGUI - if (field.ftype != f_HyperText && // Handled directly in - // guiHyperText + if (field.ftype != f_HyperText && // Handled directly in guiHyperText current_cursor_icon != field.fcursor_icon) cursor_control->setActiveIcon(field.fcursor_icon); #endif @@ -3583,8 +3577,9 @@ void GUIFormSpecMenu::drawMenu() skin->setFont(old_font); } + void GUIFormSpecMenu::showTooltip(const std::wstring &text, - const irr::video::SColor &color, const irr::video::SColor &bgcolor) + const irr::video::SColor &color, const irr::video::SColor &bgcolor) { EnrichedString ntext(text); ntext.setDefaultColor(color); @@ -3601,7 +3596,7 @@ void GUIFormSpecMenu::showTooltip(const std::wstring &text, int tooltip_offset_y = m_btn_height; #ifdef __ANDROID__ tooltip_offset_x *= 3; - tooltip_offset_y = 0; + tooltip_offset_y = 0; if (m_pointer.X > (s32)screenSize.X / 2) tooltip_offset_x = -(tooltip_offset_x + tooltip_width); @@ -3614,13 +3609,16 @@ void GUIFormSpecMenu::showTooltip(const std::wstring &text, s32 tooltip_x = m_pointer.X + tooltip_offset_x; s32 tooltip_y = m_pointer.Y + tooltip_offset_y; if (tooltip_x + tooltip_width > (s32)screenSize.X) - tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height; + tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height; if (tooltip_y + tooltip_height > (s32)screenSize.Y) tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height; - m_tooltip_element->setRelativePosition(core::rect( + m_tooltip_element->setRelativePosition( + core::rect( core::position2d(tooltip_x, tooltip_y), - core::dimension2d(tooltip_width, tooltip_height))); + core::dimension2d(tooltip_width, tooltip_height) + ) + ); // Display the tooltip m_tooltip_element->setVisible(true); @@ -3675,23 +3673,17 @@ ItemStack GUIFormSpecMenu::verifySelectedItem() if (m_selected_item) { if (m_selected_item->isValid()) { - Inventory *inv = m_invmgr->getInventory( - m_selected_item->inventoryloc); + Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc); if (inv) { - InventoryList *list = - inv->getList(m_selected_item->listname); - if (list && (u32)m_selected_item->i < list->getSize()) { - ItemStack stack = - list->getItem(m_selected_item->i); + InventoryList *list = inv->getList(m_selected_item->listname); + if (list && (u32) m_selected_item->i < list->getSize()) { + ItemStack stack = list->getItem(m_selected_item->i); if (!m_selected_swap.empty()) { if (m_selected_swap.name == stack.name && - m_selected_swap.count == - stack.count) + m_selected_swap.count == stack.count) m_selected_swap.clear(); } else { - m_selected_amount = std::min( - m_selected_amount, - stack.count); + m_selected_amount = std::min(m_selected_amount, stack.count); } if (!stack.empty()) @@ -3709,9 +3701,10 @@ ItemStack GUIFormSpecMenu::verifySelectedItem() return ItemStack(); } -void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode = quit_mode_no) +void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no) { - if (m_text_dst) { + if(m_text_dst) + { StringMap fields; if (quitmode == quit_mode_accept) { @@ -3760,74 +3753,50 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode = quit_mode_no) fields[name] = table->checkEvent(); } } else if (s.ftype == f_DropDown) { - // No dynamic cast possible due to some - // distributions shipped without rtti support in - // Irrlicht - IGUIElement *element = - getElementFromId(s.fid, true); + // No dynamic cast possible due to some distributions shipped + // without rtti support in Irrlicht + IGUIElement *element = getElementFromId(s.fid, true); gui::IGUIComboBox *e = NULL; - if ((element) && - (element->getType() == - gui::EGUIET_COMBO_BOX)) { - e = static_cast( - element); + if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) { + e = static_cast(element); } else { - warningstream << "GUIFormSpecMenu::" - "acceptInput: dropdown " - << "field without dropdown " - "element" - << std::endl; + warningstream << "GUIFormSpecMenu::acceptInput: dropdown " + << "field without dropdown element" << std::endl; continue; } s32 selected = e->getSelected(); if (selected >= 0) { - if (m_dropdown_index_event.find( - s.fname) != - m_dropdown_index_event - .end()) { - fields[name] = std::to_string( - selected + 1); + if (m_dropdown_index_event.find(s.fname) != + m_dropdown_index_event.end()) { + fields[name] = std::to_string(selected + 1); } else { std::vector *dropdown_values = - getDropDownValues( - s.fname); - if (dropdown_values && - selected < (s32)dropdown_values->size()) - fields[name] = (*dropdown_values) - [selected]; + getDropDownValues(s.fname); + if (dropdown_values && selected < (s32)dropdown_values->size()) + fields[name] = (*dropdown_values)[selected]; } } } else if (s.ftype == f_TabHeader) { - // No dynamic cast possible due to some - // distributions shipped without rtti support in - // Irrlicht - IGUIElement *element = - getElementFromId(s.fid, true); + // No dynamic cast possible due to some distributions shipped + // without rtti support in Irrlicht + IGUIElement *element = getElementFromId(s.fid, true); gui::IGUITabControl *e = nullptr; - if ((element) && - (element->getType() == - gui::EGUIET_TAB_CONTROL)) { - e = static_cast( - element); + if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) { + e = static_cast(element); } if (e != 0) { std::stringstream ss; - ss << (e->getActiveTab() + 1); + ss << (e->getActiveTab() +1); fields[name] = ss.str(); } } else if (s.ftype == f_CheckBox) { - // No dynamic cast possible due to some - // distributions shipped without rtti support in - // Irrlicht - IGUIElement *element = - getElementFromId(s.fid, true); + // No dynamic cast possible due to some distributions shipped + // without rtti support in Irrlicht + IGUIElement *element = getElementFromId(s.fid, true); gui::IGUICheckBox *e = nullptr; - if ((element) && - (element->getType() == - gui::EGUIET_CHECK_BOX)) { - e = static_cast( - element); + if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) { + e = static_cast(element); } if (e != 0) { @@ -3837,14 +3806,11 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode = quit_mode_no) fields[name] = "false"; } } else if (s.ftype == f_ScrollBar) { - // No dynamic cast possible due to some - // distributions shipped without rtti support in - // Irrlicht - IGUIElement *element = - getElementFromId(s.fid, true); + // No dynamic cast possible due to some distributions shipped + // without rtti support in Irrlicht + IGUIElement *element = getElementFromId(s.fid, true); GUIScrollBar *e = nullptr; - if (element && element->getType() == - gui::EGUIET_ELEMENT) + if (element && element->getType() == gui::EGUIET_ELEMENT) e = static_cast(element); if (e) { @@ -3854,22 +3820,17 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode = quit_mode_no) fields[name] = "CHG:" + os.str(); else fields[name] = "VAL:" + os.str(); - } + } } else if (s.ftype == f_AnimatedImage) { - // No dynamic cast possible due to some - // distributions shipped without rtti support in - // Irrlicht - IGUIElement *element = - getElementFromId(s.fid, true); + // No dynamic cast possible due to some distributions shipped + // without rtti support in Irrlicht + IGUIElement *element = getElementFromId(s.fid, true); GUIAnimatedImage *e = nullptr; - if (element && element->getType() == - gui::EGUIET_ELEMENT) - e = static_cast( - element); + if (element && element->getType() == gui::EGUIET_ELEMENT) + e = static_cast(element); if (e) - fields[name] = std::to_string( - e->getFrameIndex() + 1); + fields[name] = std::to_string(e->getFrameIndex() + 1); } else { IGUIElement *e = getElementFromId(s.fid, true); if (e) @@ -3882,7 +3843,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode = quit_mode_no) } } -bool GUIFormSpecMenu::preprocessEvent(const SEvent &event) +bool GUIFormSpecMenu::preprocessEvent(const SEvent& event) { // The IGUITabControl renders visually using the skin's selected // font, which we override for the duration of form drawing, @@ -3895,11 +3856,11 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent &event) s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; gui::IGUIElement *hovered = - Environment->getRootGUIElement()->getElementFromPoint( - core::position2d(x, y)); + Environment->getRootGUIElement()->getElementFromPoint( + core::position2d(x, y)); if (hovered && isMyChild(hovered) && hovered->getType() == gui::EGUIET_TAB_CONTROL) { - gui::IGUISkin *skin = Environment->getSkin(); + gui::IGUISkin* skin = Environment->getSkin(); sanity_check(skin != NULL); gui::IGUIFont *old_font = skin->getFont(); skin->setFont(m_font); @@ -3911,19 +3872,16 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent &event) // Fix Esc/Return key being eaten by checkboxen and tables if (event.EventType == EET_KEY_INPUT_EVENT) { - KeyPress kp(event.KeyInput); - if (kp == EscapeKey || kp == CancelKey || - kp == getKeySetting("keymap_inventory") || - event.KeyInput.Key == KEY_RETURN) { + KeyPress kp(event.KeyInput); + if (kp == EscapeKey || kp == CancelKey + || kp == getKeySetting("keymap_inventory") + || event.KeyInput.Key==KEY_RETURN) { gui::IGUIElement *focused = Environment->getFocus(); if (focused && isMyChild(focused) && (focused->getType() == gui::EGUIET_LIST_BOX || - focused->getType() == - gui::EGUIET_CHECK_BOX) && - (focused->getParent()->getType() != - gui::EGUIET_COMBO_BOX || - event.KeyInput.Key != - KEY_RETURN)) { + focused->getType() == gui::EGUIET_CHECK_BOX) && + (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX || + event.KeyInput.Key != KEY_RETURN)) { OnEvent(event); return true; } @@ -3932,14 +3890,13 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent &event) // Mouse wheel and move events: send to hovered element instead of focused if (event.EventType == EET_MOUSE_INPUT_EVENT && (event.MouseInput.Event == EMIE_MOUSE_WHEEL || - (event.MouseInput.Event == EMIE_MOUSE_MOVED && - event.MouseInput.ButtonStates == - 0))) { + (event.MouseInput.Event == EMIE_MOUSE_MOVED && + event.MouseInput.ButtonStates == 0))) { s32 x = event.MouseInput.X; s32 y = event.MouseInput.Y; gui::IGUIElement *hovered = - Environment->getRootGUIElement()->getElementFromPoint( - core::position2d(x, y)); + Environment->getRootGUIElement()->getElementFromPoint( + core::position2d(x, y)); if (hovered && isMyChild(hovered)) { hovered->OnEvent(event); return event.MouseInput.Event == EMIE_MOUSE_WHEEL; @@ -3992,19 +3949,13 @@ enum ButtonEventType : u8 BET_OTHER }; -bool GUIFormSpecMenu::OnEvent(const SEvent &event) +bool GUIFormSpecMenu::OnEvent(const SEvent& event) { - if (event.EventType == EET_KEY_INPUT_EVENT) { + if (event.EventType==EET_KEY_INPUT_EVENT) { KeyPress kp(event.KeyInput); - if (event.KeyInput.PressedDown && - ((kp == EscapeKey) || (kp == CancelKey) || - ((m_client != NULL) && - (kp == getKeySetting("key" - "map" - "_in" - "ven" - "tor" - "y"))))) { + if (event.KeyInput.PressedDown && ( + (kp == EscapeKey) || (kp == CancelKey) || + ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) { tryClose(); return true; } @@ -4014,30 +3965,29 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) m_client->makeScreenshot(); } - if (event.KeyInput.PressedDown && - kp == getKeySetting("keymap_toggle_debug")) + if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug")) m_show_debug = !m_show_debug; if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_RETURN || - event.KeyInput.Key == KEY_UP || - event.KeyInput.Key == KEY_DOWN)) { + (event.KeyInput.Key==KEY_RETURN || + event.KeyInput.Key==KEY_UP || + event.KeyInput.Key==KEY_DOWN) + ) { switch (event.KeyInput.Key) { - case KEY_RETURN: - current_keys_pending.key_enter = true; - break; - case KEY_UP: - current_keys_pending.key_up = true; - break; - case KEY_DOWN: - current_keys_pending.key_down = true; - break; - break; - default: - // can't happen at all! - FATAL_ERROR("Reached a source line that can't ever been " - "reached"); + case KEY_RETURN: + current_keys_pending.key_enter = true; + break; + case KEY_UP: + current_keys_pending.key_up = true; + break; + case KEY_DOWN: + current_keys_pending.key_down = true; + break; break; + default: + //can't happen at all! + FATAL_ERROR("Reached a source line that can't ever been reached"); + break; } if (current_keys_pending.key_enter && m_allowclose) { acceptInput(quit_mode_accept); @@ -4047,6 +3997,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) } return true; } + } /* Mouse event other than movement, or crossing the border of inventory @@ -4054,11 +4005,9 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) */ if (event.EventType == EET_MOUSE_INPUT_EVENT && (event.MouseInput.Event != EMIE_MOUSE_MOVED || - (event.MouseInput.Event == EMIE_MOUSE_MOVED && - event.MouseInput.isRightPressed() && - getItemAtPos(m_pointer).i != - getItemAtPos(m_old_pointer) - .i))) { + (event.MouseInput.Event == EMIE_MOUSE_MOVED && + event.MouseInput.isRightPressed() && + getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) { // Get selected item and hovered/clicked item (s) @@ -4071,88 +4020,74 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) InventoryList *list_s = NULL; if (m_selected_item) { - inv_selected = m_invmgr->getInventory( - m_selected_item->inventoryloc); + inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc); sanity_check(inv_selected); - sanity_check(inv_selected->getList(m_selected_item->listname) != - NULL); + sanity_check(inv_selected->getList(m_selected_item->listname) != NULL); } u32 s_count = 0; if (s.isValid()) - do { // breakable - inv_s = m_invmgr->getInventory(s.inventoryloc); - - if (!inv_s) { - errorstream << "InventoryMenu: The selected " - "inventory location " - << "\"" << s.inventoryloc.dump() - << "\" doesn't exist" << std::endl; - s.i = -1; // make it invalid again - break; - } + do { // breakable + inv_s = m_invmgr->getInventory(s.inventoryloc); + + if (!inv_s) { + errorstream << "InventoryMenu: The selected inventory location " + << "\"" << s.inventoryloc.dump() << "\" doesn't exist" + << std::endl; + s.i = -1; // make it invalid again + break; + } - list_s = inv_s->getList(s.listname); - if (list_s == NULL) { - verbosestream << "InventoryMenu: The selected " - "inventory list \"" - << s.listname << "\" does not exist" - << std::endl; - s.i = -1; // make it invalid again - break; - } + list_s = inv_s->getList(s.listname); + if (list_s == NULL) { + verbosestream << "InventoryMenu: The selected inventory list \"" + << s.listname << "\" does not exist" << std::endl; + s.i = -1; // make it invalid again + break; + } - if ((u32)s.i >= list_s->getSize()) { - infostream << "InventoryMenu: The selected " - "inventory list \"" - << s.listname - << "\" is too small (i=" << s.i - << ", size=" << list_s->getSize() - << ")" << std::endl; - s.i = -1; // make it invalid again - break; - } + if ((u32)s.i >= list_s->getSize()) { + infostream << "InventoryMenu: The selected inventory list \"" + << s.listname << "\" is too small (i=" << s.i << ", size=" + << list_s->getSize() << ")" << std::endl; + s.i = -1; // make it invalid again + break; + } - s_count = list_s->getItem(s.i).count; - } while (0); + s_count = list_s->getItem(s.i).count; + } while(0); bool identical = m_selected_item && s.isValid() && - (inv_selected == inv_s) && - (m_selected_item->listname == s.listname) && - (m_selected_item->i == s.i); + (inv_selected == inv_s) && + (m_selected_item->listname == s.listname) && + (m_selected_item->i == s.i); ButtonEventType button = BET_LEFT; ButtonEventType updown = BET_OTHER; switch (event.MouseInput.Event) { case EMIE_LMOUSE_PRESSED_DOWN: - button = BET_LEFT; - updown = BET_DOWN; + button = BET_LEFT; updown = BET_DOWN; break; case EMIE_RMOUSE_PRESSED_DOWN: - button = BET_RIGHT; - updown = BET_DOWN; + button = BET_RIGHT; updown = BET_DOWN; break; case EMIE_MMOUSE_PRESSED_DOWN: - button = BET_MIDDLE; - updown = BET_DOWN; + button = BET_MIDDLE; updown = BET_DOWN; break; case EMIE_MOUSE_WHEEL: - button = (event.MouseInput.Wheel > 0) ? BET_WHEEL_UP - : BET_WHEEL_DOWN; + button = (event.MouseInput.Wheel > 0) ? + BET_WHEEL_UP : BET_WHEEL_DOWN; updown = BET_DOWN; break; case EMIE_LMOUSE_LEFT_UP: - button = BET_LEFT; - updown = BET_UP; + button = BET_LEFT; updown = BET_UP; break; case EMIE_RMOUSE_LEFT_UP: - button = BET_RIGHT; - updown = BET_UP; + button = BET_RIGHT; updown = BET_UP; break; case EMIE_MMOUSE_LEFT_UP: - button = BET_MIDDLE; - updown = BET_UP; + button = BET_MIDDLE; updown = BET_UP; break; case EMIE_MOUSE_MOVED: updown = BET_MOVE; @@ -4180,7 +4115,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) case BET_DOWN: // Some mouse button has been pressed - // infostream << "Mouse button " << button << " pressed at p=(" + //infostream << "Mouse button " << button << " pressed at p=(" // << event.MouseInput.X << "," << event.MouseInput.Y << ")" // << std::endl; @@ -4191,10 +4126,8 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) craft_amount = (button == BET_MIDDLE ? 10 : 1); } else if (!m_selected_item) { if (s_count && button != BET_WHEEL_UP) { - // Non-empty stack has been clicked: select or - // shift-move it - m_selected_item = - new GUIInventoryList::ItemSpec(s); + // Non-empty stack has been clicked: select or shift-move it + m_selected_item = new GUIInventoryList::ItemSpec(s); u32 count; if (button == BET_RIGHT) @@ -4203,22 +4136,17 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) count = MYMIN(s_count, 10); else if (button == BET_WHEEL_DOWN) count = 1; - else // left + else // left count = s_count; if (!event.MouseInput.Shift) { // no shift: select item m_selected_amount = count; - m_selected_dragging = - button != BET_WHEEL_DOWN; + m_selected_dragging = button != BET_WHEEL_DOWN; m_auto_place = false; } else { - // shift pressed: move item, right click - // moves 1 - shift_move_amount = - button == BET_RIGHT - ? 1 - : count; + // shift pressed: move item, right click moves 1 + shift_move_amount = button == BET_RIGHT ? 1 : count; } } } else { // m_selected_item != NULL @@ -4229,8 +4157,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) if (button == BET_RIGHT || button == BET_WHEEL_UP) move_amount = 1; else if (button == BET_MIDDLE) - move_amount = MYMIN( - m_selected_amount, 10); + move_amount = MYMIN(m_selected_amount, 10); else if (button == BET_LEFT) move_amount = m_selected_amount; // else wheeldown @@ -4240,44 +4167,38 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) if (m_selected_amount < s_count) ++m_selected_amount; } else { - if (move_amount >= - m_selected_amount) + if (move_amount >= m_selected_amount) m_selected_amount = 0; else - m_selected_amount -= - move_amount; + m_selected_amount -= move_amount; move_amount = 0; } } - } else if (!getAbsoluteClippingRect().isPointInside( - m_pointer) && - button != BET_WHEEL_DOWN) { + } else if (!getAbsoluteClippingRect().isPointInside(m_pointer) + && button != BET_WHEEL_DOWN) { // Clicked outside of the window: drop if (button == BET_RIGHT || button == BET_WHEEL_UP) drop_amount = 1; else if (button == BET_MIDDLE) - drop_amount = MYMIN( - m_selected_amount, 10); - else // left + drop_amount = MYMIN(m_selected_amount, 10); + else // left drop_amount = m_selected_amount; } } - break; + break; case BET_UP: // Some mouse button has been released - // infostream<<"Mouse button "<getList( - m_selected_item->listname); + // Only move an item if the destination slot is empty + // or contains the same item type as what is going to be + // moved + InventoryList *list_from = inv_selected->getList(m_selected_item->listname); InventoryList *list_to = list_s; assert(list_from && list_to); - ItemStack stack_from = list_from->getItem( - m_selected_item->i); + ItemStack stack_from = list_from->getItem(m_selected_item->i); ItemStack stack_to = list_to->getItem(s.i); - if (stack_to.empty() || - stack_to.name == stack_from.name) + if (stack_to.empty() || stack_to.name == stack_from.name) move_amount = 1; } } - break; + break; default: break; } @@ -4327,18 +4244,15 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) assert(s.isValid()); assert(inv_selected && inv_s); - InventoryList *list_from = - inv_selected->getList(m_selected_item->listname); + InventoryList *list_from = inv_selected->getList(m_selected_item->listname); InventoryList *list_to = list_s; assert(list_from && list_to); ItemStack stack_from = list_from->getItem(m_selected_item->i); ItemStack stack_to = list_to->getItem(s.i); // Check how many items can be moved - move_amount = stack_from.count = - MYMIN(move_amount, stack_from.count); - ItemStack leftover = - stack_to.addItem(stack_from, m_client->idef()); + move_amount = stack_from.count = MYMIN(move_amount, stack_from.count); + ItemStack leftover = stack_to.addItem(stack_from, m_client->idef()); bool move = true; // If source stack cannot be added to destination stack at all, // they are swapped @@ -4350,8 +4264,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) m_selected_dragging = false; // WARNING: BLACK MAGIC, BUT IN A REDUCED SET - // Skip next validation checks due async inventory - // calls + // Skip next validation checks due async inventory calls m_selected_swap = stack_to; } else { move = false; @@ -4368,8 +4281,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) } if (move) { - infostream << "Handing IAction::Move to manager" - << std::endl; + infostream << "Handing IAction::Move to manager" << std::endl; IMoveAction *a = new IMoveAction(); a->count = move_amount; a->from_inv = m_selected_item->inventoryloc; @@ -4385,32 +4297,28 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) u32 i = 0; for (; i < mis; i++) { const ListRingSpec &sp = m_inventory_rings[i]; - if (sp.inventoryloc == s.inventoryloc && - sp.listname == s.listname) + if (sp.inventoryloc == s.inventoryloc + && sp.listname == s.listname) break; } do { if (i >= mis) // if not found break; u32 to_inv_ind = (i + 1) % mis; - const ListRingSpec &to_inv_sp = - m_inventory_rings[to_inv_ind]; + const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind]; InventoryList *list_from = list_s; if (!s.isValid()) break; - Inventory *inv_to = m_invmgr->getInventory( - to_inv_sp.inventoryloc); + Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc); if (!inv_to) break; - InventoryList *list_to = - inv_to->getList(to_inv_sp.listname); + InventoryList *list_to = inv_to->getList(to_inv_sp.listname); if (!list_to) break; ItemStack stack_from = list_from->getItem(s.i); assert(shift_move_amount <= stack_from.count); - infostream << "Handing IAction::Move to manager" - << std::endl; + infostream << "Handing IAction::Move to manager" << std::endl; IMoveAction *a = new IMoveAction(); a->count = shift_move_amount; a->from_inv = s.inventoryloc; @@ -4426,14 +4334,12 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) assert(m_selected_item && m_selected_item->isValid()); assert(inv_selected); - InventoryList *list_from = - inv_selected->getList(m_selected_item->listname); + InventoryList *list_from = inv_selected->getList(m_selected_item->listname); assert(list_from); ItemStack stack_from = list_from->getItem(m_selected_item->i); // Check how many items can be dropped - drop_amount = stack_from.count = - MYMIN(drop_amount, stack_from.count); + drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count); assert(drop_amount > 0 && drop_amount <= m_selected_amount); m_selected_amount -= drop_amount; @@ -4449,14 +4355,13 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) // if there are no items selected or the selected item // belongs to craftresult list, proceed with crafting - if (!m_selected_item || !m_selected_item->isValid() || - m_selected_item->listname == "craftresult") { + if (!m_selected_item || + !m_selected_item->isValid() || m_selected_item->listname == "craftresult") { assert(inv_s); // Send IACTION_CRAFT - infostream << "Handing IACTION_CRAFT to manager" - << std::endl; + infostream << "Handing IACTION_CRAFT to manager" << std::endl; ICraftAction *a = new ICraftAction(); a->count = craft_amount; a->craft_inv = s.inventoryloc; @@ -4476,7 +4381,8 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) } if (event.EventType == EET_GUI_EVENT) { - if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED && isVisible()) { + if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED + && isVisible()) { // find the element that was clicked for (GUIFormSpecMenu::FieldSpec &s : m_fields) { if ((s.ftype == f_TabHeader) && @@ -4488,23 +4394,19 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) } } } - if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && - isVisible()) { + if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { - infostream << "GUIFormSpecMenu: Not allowing focus " - "change." - << std::endl; + infostream<<"GUIFormSpecMenu: Not allowing focus change." + <getID(); if (caller_id == 257) { @@ -4534,8 +4436,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) acceptInput(quit_mode_accept); quitMenu(); } else { - m_text_dst->gotText( - L"ExitButton"); + m_text_dst->gotText(L"ExitButton"); } return true; } @@ -4554,8 +4455,8 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) s.send = true; acceptInput(quit_mode_no); - // revert configuration to make sure dropdowns are - // sent on regular button click + // revert configuration to make sure dropdowns are sent on + // regular button click for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) { if (s2.ftype == f_DropDown) { s2.send = true; @@ -4566,8 +4467,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) s.fdefault = L"Changed"; acceptInput(quit_mode_no); s.fdefault = L""; - } else if (s.ftype == f_Unknown || - s.ftype == f_HyperText) { + } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) { s.send = true; acceptInput(); s.send = false; @@ -4577,8 +4477,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) { // move scroll_containers - for (const std::pair &c : - m_scroll_containers) + for (const std::pair &c : m_scroll_containers) c.second->onScrollEvent(event.GUIEvent.Caller); } @@ -4589,10 +4488,8 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) if (s.ftype == f_Unknown && s.fid == event.GUIEvent.Caller->getID()) { current_field_enter_pending = s.fname; - std::unordered_map::const_iterator it = - field_close_on_enter.find( - s.fname); + std::unordered_map::const_iterator it = + field_close_on_enter.find(s.fname); if (it != field_close_on_enter.end()) close_on_enter = (*it).second; @@ -4620,11 +4517,10 @@ bool GUIFormSpecMenu::OnEvent(const SEvent &event) for (GUIFormSpecMenu::FieldSpec &s : m_fields) { // if it's a table, set the send field // so lua knows which table was changed - if ((s.ftype == f_Table) && - (s.fid == current_id)) { + if ((s.ftype == f_Table) && (s.fid == current_id)) { s.send = true; acceptInput(); - s.send = false; + s.send=false; } } return true; @@ -4649,6 +4545,7 @@ std::string GUIFormSpecMenu::getNameByID(s32 id) return ""; } + const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id) { for (FieldSpec &spec : m_fields) { @@ -4673,14 +4570,12 @@ std::wstring GUIFormSpecMenu::getLabelByID(s32 id) } StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type, - const std::string &name, const std::string &parent_type) -{ + const std::string &name, const std::string &parent_type) { return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT]; } std::array GUIFormSpecMenu::getStyleForElement( - const std::string &type, const std::string &name, - const std::string &parent_type) + const std::string &type, const std::string &name, const std::string &parent_type) { std::array ret; diff --git a/src/gui/guiFormSpecMenu.h b/src/gui/guiFormSpecMenu.h index ea9731258..613acaa04 100644 --- a/src/gui/guiFormSpecMenu.h +++ b/src/gui/guiFormSpecMenu.h @@ -41,8 +41,7 @@ class Client; class TexturePool; class GUIScrollContainer; -typedef enum -{ +typedef enum { f_Button, f_Table, f_TabHeader, @@ -56,8 +55,7 @@ typedef enum f_Unknown } FormspecFieldType; -typedef enum -{ +typedef enum { quit_mode_no, quit_mode_accept, quit_mode_cancel @@ -90,9 +88,9 @@ class GUIFormSpecMenu : public GUIModalMenu ListRingSpec() = default; ListRingSpec(const InventoryLocation &a_inventoryloc, - const std::string &a_listname) : - inventoryloc(a_inventoryloc), - listname(a_listname) + const std::string &a_listname): + inventoryloc(a_inventoryloc), + listname(a_listname) { } @@ -105,15 +103,17 @@ class GUIFormSpecMenu : public GUIModalMenu FieldSpec() = default; FieldSpec(const std::string &name, const std::wstring &label, - const std::wstring &default_text, s32 id, - int priority = 0, + const std::wstring &default_text, s32 id, int priority = 0, gui::ECURSOR_ICON cursor_icon = ECI_NORMAL) : - fname(name), - flabel(label), - fdefault(unescape_enriched( - translate_string(default_text))), - fid(id), send(false), ftype(f_Unknown), is_exit(false), - priority(priority), fcursor_icon(cursor_icon) + fname(name), + flabel(label), + fdefault(unescape_enriched(translate_string(default_text))), + fid(id), + send(false), + ftype(f_Unknown), + is_exit(false), + priority(priority), + fcursor_icon(cursor_icon) { } @@ -134,9 +134,10 @@ class GUIFormSpecMenu : public GUIModalMenu { TooltipSpec() = default; TooltipSpec(const std::wstring &a_tooltip, irr::video::SColor a_bgcolor, - irr::video::SColor a_color) : - tooltip(translate_string(a_tooltip)), - bgcolor(a_bgcolor), color(a_color) + irr::video::SColor a_color): + tooltip(translate_string(a_tooltip)), + bgcolor(a_bgcolor), + color(a_color) { } @@ -146,16 +147,21 @@ class GUIFormSpecMenu : public GUIModalMenu }; public: - GUIFormSpecMenu(JoystickController *joystick, gui::IGUIElement *parent, s32 id, - IMenuManager *menumgr, Client *client, ISimpleTextureSource *tsrc, - IFormSource *fs_src, TextDest *txt_dst, - const std::string &formspecPrepend, bool remap_dbl_click = true); + GUIFormSpecMenu(JoystickController *joystick, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + Client *client, + ISimpleTextureSource *tsrc, + IFormSource* fs_src, + TextDest* txt_dst, + const std::string &formspecPrepend, + bool remap_dbl_click = true); ~GUIFormSpecMenu(); static void create(GUIFormSpecMenu *&cur_formspec, Client *client, - JoystickController *joystick, IFormSource *fs_src, - TextDest *txt_dest, const std::string &formspecPrepend); + JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, + const std::string &formspecPrepend); void setFormSpec(const std::string &formspec_string, const InventoryLocation ¤t_inventory_location) @@ -190,9 +196,12 @@ class GUIFormSpecMenu : public GUIModalMenu m_text_dst = text_dst; } - void allowClose(bool value) { m_allowclose = value; } + void allowClose(bool value) + { + m_allowclose = value; + } - void lockSize(bool lock, v2u32 basescreensize = v2u32(0, 0)) + void lockSize(bool lock,v2u32 basescreensize=v2u32(0,0)) { m_lock = lock; m_lockscreensize = basescreensize; @@ -201,18 +210,30 @@ class GUIFormSpecMenu : public GUIModalMenu void removeChildren(); void setInitialFocus(); - void setFocus(const std::string &elementname) { m_focused_element = elementname; } + void setFocus(const std::string &elementname) + { + m_focused_element = elementname; + } - Client *getClient() const { return m_client; } + Client *getClient() const + { + return m_client; + } const GUIInventoryList::ItemSpec *getSelectedItem() const { return m_selected_item; } - const u16 getSelectedAmount() const { return m_selected_amount; } + const u16 getSelectedAmount() const + { + return m_selected_amount; + } - bool doTooltipAppendItemname() const { return m_tooltip_append_itemname; } + bool doTooltipAppendItemname() const + { + return m_tooltip_append_itemname; + } void addHoveredItemTooltip(const std::string &name) { @@ -231,13 +252,13 @@ class GUIFormSpecMenu : public GUIModalMenu ItemStack verifySelectedItem(); void acceptInput(FormspecQuitMode quitmode); - bool preprocessEvent(const SEvent &event); - bool OnEvent(const SEvent &event); + bool preprocessEvent(const SEvent& event); + bool OnEvent(const SEvent& event); bool doPause; bool pausesGame() { return doPause; } - GUITable *getTable(const std::string &tablename); - std::vector *getDropDownValues(const std::string &name); + GUITable* getTable(const std::string &tablename); + std::vector* getDropDownValues(const std::string &name); #ifdef __ANDROID__ bool getAndroidUIInput(); @@ -246,7 +267,7 @@ class GUIFormSpecMenu : public GUIModalMenu protected: v2s32 getBasePos() const { - return padding + offset + AbsoluteRect.UpperLeftCorner; + return padding + offset + AbsoluteRect.UpperLeftCorner; } std::wstring getLabelByID(s32 id); std::string getNameByID(s32 id); @@ -260,11 +281,9 @@ class GUIFormSpecMenu : public GUIModalMenu std::unordered_set property_warned; StyleSpec getDefaultStyleForElement(const std::string &type, - const std::string &name = "", - const std::string &parent_type = ""); - std::array getStyleForElement( - const std::string &type, const std::string &name = "", - const std::string &parent_type = ""); + const std::string &name="", const std::string &parent_type=""); + std::array getStyleForElement(const std::string &type, + const std::string &name="", const std::string &parent_type=""); v2s32 padding; v2f32 spacing; @@ -326,16 +345,15 @@ class GUIFormSpecMenu : public GUIModalMenu video::SColor m_default_tooltip_color; private: - IFormSource *m_form_src; - TextDest *m_text_dst; - std::string m_last_formname; - u16 m_formspec_version = 1; - std::string m_focused_element = ""; + IFormSource *m_form_src; + TextDest *m_text_dst; + std::string m_last_formname; + u16 m_formspec_version = 1; + std::string m_focused_element = ""; JoystickController *m_joystick; bool m_show_debug = false; - typedef struct - { + typedef struct { bool explicit_size; bool real_coordinates; u8 simple_field_count; @@ -352,23 +370,20 @@ class GUIFormSpecMenu : public GUIModalMenu GUIInventoryList::Options inventorylist_options; - struct - { + struct { s32 max = 1000; s32 min = 0; s32 small_step = 10; s32 large_step = 100; s32 thumb_size = 1; - GUIScrollBar::ArrowVisibility arrow_visiblity = - GUIScrollBar::DEFAULT; + GUIScrollBar::ArrowVisibility arrow_visiblity = GUIScrollBar::DEFAULT; } scrollbar_options; // used to restore table selection/scroll/treeview state std::unordered_map table_dyndata; } parserData; - typedef struct - { + typedef struct { bool key_up; bool key_down; bool key_enter; @@ -379,50 +394,49 @@ class GUIFormSpecMenu : public GUIModalMenu std::string current_field_enter_pending = ""; std::vector m_hovered_item_tooltips; - void parseElement(parserData *data, const std::string &element); + void parseElement(parserData* data, const std::string &element); - void parseSize(parserData *data, const std::string &element); - void parseContainer(parserData *data, const std::string &element); - void parseContainerEnd(parserData *data); + void parseSize(parserData* data, const std::string &element); + void parseContainer(parserData* data, const std::string &element); + void parseContainerEnd(parserData* data); void parseScrollContainer(parserData *data, const std::string &element); void parseScrollContainerEnd(parserData *data); - void parseList(parserData *data, const std::string &element); - void parseListRing(parserData *data, const std::string &element); - void parseCheckbox(parserData *data, const std::string &element); - void parseImage(parserData *data, const std::string &element); + void parseList(parserData* data, const std::string &element); + void parseListRing(parserData* data, const std::string &element); + void parseCheckbox(parserData* data, const std::string &element); + void parseImage(parserData* data, const std::string &element); void parseAnimatedImage(parserData *data, const std::string &element); - void parseItemImage(parserData *data, const std::string &element); - void parseButton(parserData *data, const std::string &element, + void parseItemImage(parserData* data, const std::string &element); + void parseButton(parserData* data, const std::string &element, const std::string &typ); - void parseBackground(parserData *data, const std::string &element); - void parseTableOptions(parserData *data, const std::string &element); - void parseTableColumns(parserData *data, const std::string &element); - void parseTable(parserData *data, const std::string &element); - void parseTextList(parserData *data, const std::string &element); - void parseDropDown(parserData *data, const std::string &element); + void parseBackground(parserData* data, const std::string &element); + void parseTableOptions(parserData* data, const std::string &element); + void parseTableColumns(parserData* data, const std::string &element); + void parseTable(parserData* data, const std::string &element); + void parseTextList(parserData* data, const std::string &element); + void parseDropDown(parserData* data, const std::string &element); void parseFieldCloseOnEnter(parserData *data, const std::string &element); - void parsePwdField(parserData *data, const std::string &element); - void parseField(parserData *data, const std::string &element, - const std::string &type); - void createTextField(parserData *data, FieldSpec &spec, core::rect &rect, - bool is_multiline); - void parseSimpleField(parserData *data, std::vector &parts); - void parseTextArea(parserData *data, std::vector &parts, + void parsePwdField(parserData* data, const std::string &element); + void parseField(parserData* data, const std::string &element, const std::string &type); + void createTextField(parserData *data, FieldSpec &spec, + core::rect &rect, bool is_multiline); + void parseSimpleField(parserData* data,std::vector &parts); + void parseTextArea(parserData* data,std::vector& parts, const std::string &type); void parseHyperText(parserData *data, const std::string &element); - void parseLabel(parserData *data, const std::string &element); - void parseVertLabel(parserData *data, const std::string &element); - void parseImageButton(parserData *data, const std::string &element, + void parseLabel(parserData* data, const std::string &element); + void parseVertLabel(parserData* data, const std::string &element); + void parseImageButton(parserData* data, const std::string &element, const std::string &type); - void parseItemImageButton(parserData *data, const std::string &element); - void parseTabHeader(parserData *data, const std::string &element); - void parseBox(parserData *data, const std::string &element); - void parseBackgroundColor(parserData *data, const std::string &element); - void parseListColors(parserData *data, const std::string &element); - void parseTooltip(parserData *data, const std::string &element); + void parseItemImageButton(parserData* data, const std::string &element); + void parseTabHeader(parserData* data, const std::string &element); + void parseBox(parserData* data, const std::string &element); + void parseBackgroundColor(parserData* data, const std::string &element); + void parseListColors(parserData* data, const std::string &element); + void parseTooltip(parserData* data, const std::string &element); bool parseVersionDirect(const std::string &data); - bool parseSizeDirect(parserData *data, const std::string &element); - void parseScrollBar(parserData *data, const std::string &element); + bool parseSizeDirect(parserData* data, const std::string &element); + void parseScrollBar(parserData* data, const std::string &element); void parseScrollBarOptions(parserData *data, const std::string &element); bool parsePositionDirect(parserData *data, const std::string &element); void parsePosition(parserData *data, const std::string &element); @@ -434,7 +448,7 @@ class GUIFormSpecMenu : public GUIModalMenu void tryClose(); void showTooltip(const std::wstring &text, const irr::video::SColor &color, - const irr::video::SColor &bgcolor); + const irr::video::SColor &bgcolor); /** * In formspec version < 2 the elements were not ordered properly. Some element @@ -447,16 +461,25 @@ class GUIFormSpecMenu : public GUIModalMenu gui::IGUIFont *m_font = nullptr; }; -class FormspecFormSource : public IFormSource +class FormspecFormSource: public IFormSource { public: - FormspecFormSource(const std::string &formspec) : m_formspec(formspec) {} + FormspecFormSource(const std::string &formspec): + m_formspec(formspec) + { + } ~FormspecFormSource() = default; - void setForm(const std::string &formspec) { m_formspec = formspec; } + void setForm(const std::string &formspec) + { + m_formspec = formspec; + } - const std::string &getForm() const { return m_formspec; } + const std::string &getForm() const + { + return m_formspec; + } std::string m_formspec; }; diff --git a/src/gui/guiHyperText.cpp b/src/gui/guiHyperText.cpp index 70c5d3f66..88931cdf9 100644 --- a/src/gui/guiHyperText.cpp +++ b/src/gui/guiHyperText.cpp @@ -71,8 +71,8 @@ void ParsedText::Element::setStyle(StyleList &style) if (style["fontstyle"] == "mono") font_mode = FM_Mono; - FontSpec spec(font_size, font_mode, is_yes(style["bold"]), - is_yes(style["italic"])); + FontSpec spec(font_size, font_mode, + is_yes(style["bold"]), is_yes(style["italic"])); // TODO: find a way to check font validity // Build a new fontengine ? @@ -247,9 +247,8 @@ void ParsedText::endParagraph(EndReason reason) EndReason previous = m_end_paragraph_reason; m_end_paragraph_reason = reason; - if (m_empty_paragraph && - (reason == ER_TAG || - (reason == ER_NEWLINE && previous == ER_TAG))) { + if (m_empty_paragraph && (reason == ER_TAG || + (reason == ER_NEWLINE && previous == ER_TAG))) { // Ignore last empty paragraph m_paragraph = nullptr; m_paragraphs.pop_back(); @@ -540,13 +539,10 @@ u32 ParsedText::parseTag(const wchar_t *text, u32 cursor) std::string str = attrs["rotate"]; std::vector parts = split(str, ','); if (parts.size() == 3) { - m_element->rotation = v3s16( - rangelim(stoi(parts[0]), -1000, - 1000), - rangelim(stoi(parts[1]), -1000, - 1000), - rangelim(stoi(parts[2]), -1000, - 1000)); + m_element->rotation = v3s16 ( + rangelim(stoi(parts[0]), -1000, 1000), + rangelim(stoi(parts[1]), -1000, 1000), + rangelim(stoi(parts[2]), -1000, 1000)); } } } @@ -618,14 +614,12 @@ TextDrawer::TextDrawer(const wchar_t *text, Client *client, case ParsedText::ELEMENT_SEPARATOR: case ParsedText::ELEMENT_TEXT: if (e.font) { - e.dim.Width = e.font->getDimension(e.text.c_str()) - .Width; + 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; + ((irr::gui::CGUITTFont *)e.font)->getAscender() / 64; } #endif } else { @@ -644,8 +638,8 @@ TextDrawer::TextDrawer(const wchar_t *text, Client *client, if (e.type == ParsedText::ELEMENT_IMAGE) { video::ITexture *texture = - m_client->getTextureSource()->getTexture( - stringw_to_utf8(e.text)); + m_client->getTextureSource()-> + getTexture(stringw_to_utf8(e.text)); if (texture) dim = texture->getOriginalSize(); } @@ -655,10 +649,10 @@ TextDrawer::TextDrawer(const wchar_t *text, Client *client, e.dim = dim; else e.dim.Height = dim.Height * e.dim.Width / - dim.Width; + dim.Width; else e.dim.Width = dim.Width * e.dim.Height / - dim.Height; + dim.Height; break; } } @@ -712,7 +706,7 @@ void TextDrawer::place(const core::rect &dest_rect) e->pos.X = m_text.margin; if (e->floating == ParsedText::FLOAT_RIGHT) e->pos.X = dest_rect.getWidth() - e->dim.Width - - m_text.margin; + m_text.margin; RectWithMargin floating; floating.rect = core::rect(e->pos, e->dim); @@ -745,54 +739,38 @@ void TextDrawer::place(const core::rect &dest_rect) for (const auto &f : m_floating) { // Does floating rect intersect paragraph y line? if (f.rect.UpperLeftCorner.Y - f.margin <= y && - f.rect.LowerRightCorner.Y + f.margin >= - y) { + f.rect.LowerRightCorner.Y + f.margin >= y) { // Next Y to try if no room left - if (!nexty || f.rect.LowerRightCorner.Y + std::max(f.margin, - p.margin) < - nexty) { - nexty = f.rect.LowerRightCorner - .Y + - std::max(f.margin, - p.margin) + - 1; + if (!nexty || f.rect.LowerRightCorner.Y + + std::max(f.margin, p.margin) < nexty) { + nexty = f.rect.LowerRightCorner.Y + + std::max(f.margin, p.margin) + 1; } - if (f.rect.UpperLeftCorner.X - f.margin <= - left && - f.rect.LowerRightCorner.X + f.margin < - right) { + if (f.rect.UpperLeftCorner.X - f.margin <= left && + f.rect.LowerRightCorner.X + f.margin < right) { // float on left - if (f.rect.LowerRightCorner.X + std::max(f.margin, - p.margin) > - left) { - left = f.rect.LowerRightCorner - .X + - std::max(f.margin, - p.margin); + if (f.rect.LowerRightCorner.X + + std::max(f.margin, p.margin) > left) { + left = f.rect.LowerRightCorner.X + + std::max(f.margin, p.margin); } - } else if (f.rect.LowerRightCorner.X + f.margin >= - right && - f.rect.UpperLeftCorner.X - f.margin > - left) { + } else if (f.rect.LowerRightCorner.X + f.margin >= right && + f.rect.UpperLeftCorner.X - f.margin > left) { // float on right - if (f.rect.UpperLeftCorner.X - std::max(f.margin, - p.margin) < - right) - right = f.rect.UpperLeftCorner - .X - - std::max(f.margin, - p.margin); - - } else if (f.rect.UpperLeftCorner.X - f.margin <= - left && - f.rect.LowerRightCorner.X + f.margin >= - right) { + if (f.rect.UpperLeftCorner.X - + std::max(f.margin, p.margin) < right) + right = f.rect.UpperLeftCorner.X - + std::max(f.margin, p.margin); + + } else if (f.rect.UpperLeftCorner.X - f.margin <= left && + f.rect.LowerRightCorner.X + f.margin >= right) { // float taking all space left = right; - } else { // float in the middle -- should - // not occure yet, see that later + } + else + { // float in the middle -- should not occure yet, see that later } } } @@ -818,14 +796,12 @@ void TextDrawer::place(const core::rect &dest_rect) } std::vector::iterator linestart = el; - std::vector::iterator lineend = - p.elements.end(); + std::vector::iterator lineend = p.elements.end(); // First pass, find elements fitting into line // (or at least one element) - while (el != p.elements.end() && - (charswidth == 0 || charswidth + el->dim.Width <= - linewidth)) { + while (el != p.elements.end() && (charswidth == 0 || + charswidth + el->dim.Width <= linewidth)) { if (el->floating == ParsedText::FLOAT_NONE) { if (el->type != ParsedText::ELEMENT_SEPARATOR) { lineend = el; @@ -868,14 +844,9 @@ void TextDrawer::place(const core::rect &dest_rect) x += (linewidth - charswidth) / 2.f; break; case ParsedText::HALIGN_JUSTIFY: - if (wordcount > 1 && // Justification only if at least two - // words - !(lineend == p.elements.end())) // Don't - // justify - // last - // line - extraspace = ((float)(linewidth - charswidth)) / - (wordcount - 1); + if (wordcount > 1 && // Justification only if at least two words + !(lineend == p.elements.end())) // Don't justify last line + extraspace = ((float)(linewidth - charswidth)) / (wordcount - 1); break; case ParsedText::HALIGN_RIGHT: x += linewidth - charswidth; @@ -918,7 +889,7 @@ void TextDrawer::place(const core::rect &dest_rect) } y += charsheight; } // Elements (actually lines) - } // Paragraph + } // Paragraph // Check if float goes under paragraph for (const auto &f : m_floating) { @@ -978,18 +949,16 @@ void TextDrawer::draw(const core::rect &clip_rect, el.font->draw(el.text, rect, color, false, true, &clip_rect); - if (el.underline && el.drawwidth) { + if (el.underline && el.drawwidth) { s32 linepos = el.pos.Y + offset.Y + - el.dim.Height - (el.baseline >> 1); + el.dim.Height - (el.baseline >> 1); core::rect linerect(el.pos.X + offset.X, linepos - (el.baseline >> 3) - 1, - el.pos.X + offset.X + - el.drawwidth, + el.pos.X + offset.X + el.drawwidth, linepos + (el.baseline >> 3)); - driver->draw2DRectangle( - color, linerect, &clip_rect); + driver->draw2DRectangle(color, linerect, &clip_rect); } } break; @@ -1001,10 +970,7 @@ void TextDrawer::draw(const core::rect &clip_rect, m_environment->getVideoDriver()->draw2DImage( texture, rect, irr::core::rect( - core::position2d< - s32>( - 0, - 0), + core::position2d(0, 0), texture->getOriginalSize()), &clip_rect, 0, true); } break; @@ -1014,10 +980,11 @@ void TextDrawer::draw(const core::rect &clip_rect, ItemStack item; item.deSerialize(stringw_to_utf8(el.text), idef); - drawItemStack(m_environment->getVideoDriver(), - g_fontengine->getFont(), item, rect, - &clip_rect, m_client, IT_ROT_OTHER, - el.angle, el.rotation); + drawItemStack( + m_environment->getVideoDriver(), + g_fontengine->getFont(), item, rect, &clip_rect, + m_client, IT_ROT_OTHER, el.angle, el.rotation + ); } break; } } @@ -1122,10 +1089,8 @@ bool GUIHyperText::OnEvent(const SEvent &event) checkHover(event.MouseInput.X, event.MouseInput.Y); if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { - m_vscrollbar->setPos( - m_vscrollbar->getPos() - - event.MouseInput.Wheel * - m_vscrollbar->getSmallStep()); + m_vscrollbar->setPos(m_vscrollbar->getPos() - + event.MouseInput.Wheel * m_vscrollbar->getSmallStep()); m_text_scrollpos.Y = -m_vscrollbar->getPos(); m_drawer.draw(m_display_text_rect, m_text_scrollpos); checkHover(event.MouseInput.X, event.MouseInput.Y); @@ -1139,16 +1104,13 @@ bool GUIHyperText::OnEvent(const SEvent &event) for (auto &tag : element->tags) { if (tag->name == "action") { Text = core::stringw(L"action:") + - utf8_to_stringw(tag->attrs["nam" - "e"]); + utf8_to_stringw(tag->attrs["name"]); if (Parent) { SEvent newEvent; - newEvent.EventType = - EET_GUI_EVENT; + newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; newEvent.GUIEvent.Element = 0; - newEvent.GUIEvent.EventType = - EGET_BUTTON_CLICKED; + newEvent.GUIEvent.EventType = EGET_BUTTON_CLICKED; Parent->OnEvent(newEvent); } break; @@ -1175,8 +1137,7 @@ void GUIHyperText::draw() if (m_drawer.getHeight() > m_display_text_rect.getHeight()) { m_vscrollbar->setSmallStep(m_display_text_rect.getHeight() * 0.1f); m_vscrollbar->setLargeStep(m_display_text_rect.getHeight() * 0.5f); - m_vscrollbar->setMax( - m_drawer.getHeight() - m_display_text_rect.getHeight()); + m_vscrollbar->setMax(m_drawer.getHeight() - m_display_text_rect.getHeight()); m_vscrollbar->setVisible(true); diff --git a/src/gui/guiHyperText.h b/src/gui/guiHyperText.h index 8371157e2..5b936262e 100644 --- a/src/gui/guiHyperText.h +++ b/src/gui/guiHyperText.h @@ -134,12 +134,7 @@ class ParsedText Tag m_root_tag; protected: - typedef enum - { - ER_NONE, - ER_TAG, - ER_NEWLINE - } EndReason; + typedef enum { ER_NONE, ER_TAG, ER_NEWLINE } EndReason; // Parser functions void enterElement(ElementType type); diff --git a/src/gui/guiInventoryList.cpp b/src/gui/guiInventoryList.cpp index a0fef4073..58d7ae771 100644 --- a/src/gui/guiInventoryList.cpp +++ b/src/gui/guiInventoryList.cpp @@ -19,17 +19,33 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/hud.h" #include "client/client.h" -GUIInventoryList::GUIInventoryList(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, const core::rect &rectangle, InventoryManager *invmgr, - const InventoryLocation &inventoryloc, const std::string &listname, - const v2s32 &geom, const s32 start_item_i, const v2s32 &slot_size, - const v2f32 &slot_spacing, GUIFormSpecMenu *fs_menu, - const Options &options, gui::IGUIFont *font) : - gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), - m_invmgr(invmgr), m_inventoryloc(inventoryloc), m_listname(listname), - m_geom(geom), m_start_item_i(start_item_i), m_slot_size(slot_size), - m_slot_spacing(slot_spacing), m_fs_menu(fs_menu), m_options(options), - m_font(font), m_hovered_i(-1), m_already_warned(false) +GUIInventoryList::GUIInventoryList(gui::IGUIEnvironment *env, + gui::IGUIElement *parent, + s32 id, + const core::rect &rectangle, + InventoryManager *invmgr, + const InventoryLocation &inventoryloc, + const std::string &listname, + const v2s32 &geom, + const s32 start_item_i, + const v2s32 &slot_size, + const v2f32 &slot_spacing, + GUIFormSpecMenu *fs_menu, + const Options &options, + gui::IGUIFont *font) : + gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), + m_invmgr(invmgr), + m_inventoryloc(inventoryloc), + m_listname(listname), + m_geom(geom), + m_start_item_i(start_item_i), + m_slot_size(slot_size), + m_slot_spacing(slot_spacing), + m_fs_menu(fs_menu), + m_options(options), + m_font(font), + m_hovered_i(-1), + m_already_warned(false) { } @@ -42,9 +58,9 @@ void GUIInventoryList::draw() if (!inv) { if (!m_already_warned) { warningstream << "GUIInventoryList::draw(): " - << "The inventory location " - << "\"" << m_inventoryloc.dump() - << "\" doesn't exist" << std::endl; + << "The inventory location " + << "\"" << m_inventoryloc.dump() << "\" doesn't exist" + << std::endl; m_already_warned = true; } return; @@ -53,9 +69,9 @@ void GUIInventoryList::draw() if (!ilist) { if (!m_already_warned) { warningstream << "GUIInventoryList::draw(): " - << "The inventory list \"" << m_listname - << "\" @ \"" << m_inventoryloc.dump() - << "\" doesn't exist" << std::endl; + << "The inventory list \"" << m_listname << "\" @ \"" + << m_inventoryloc.dump() << "\" doesn't exist" + << std::endl; m_already_warned = true; } return; @@ -81,25 +97,21 @@ void GUIInventoryList::draw() core::rect rect = imgrect + base_pos + p; ItemStack item = ilist->getItem(item_i); - bool selected = selected_item && - m_invmgr->getInventory(selected_item->inventoryloc) == - inv && - selected_item->listname == m_listname && - selected_item->i == item_i; + bool selected = selected_item + && m_invmgr->getInventory(selected_item->inventoryloc) == inv + && selected_item->listname == m_listname + && selected_item->i == item_i; core::rect clipped_rect(rect); clipped_rect.clipAgainst(AbsoluteClippingRect); bool hovering = m_hovered_i == item_i; - ItemRotationKind rotation_kind = - selected ? IT_ROT_SELECTED - : (hovering ? IT_ROT_HOVERED : IT_ROT_NONE); + ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED : + (hovering ? IT_ROT_HOVERED : IT_ROT_NONE); // layer 0 if (hovering) { - driver->draw2DRectangle( - m_options.slotbg_h, rect, &AbsoluteClippingRect); + driver->draw2DRectangle(m_options.slotbg_h, rect, &AbsoluteClippingRect); } else { - driver->draw2DRectangle( - m_options.slotbg_n, rect, &AbsoluteClippingRect); + driver->draw2DRectangle(m_options.slotbg_n, rect, &AbsoluteClippingRect); } // Draw inv slot borders @@ -109,27 +121,21 @@ void GUIInventoryList::draw() s32 x2 = rect.LowerRightCorner.X; s32 y2 = rect.LowerRightCorner.Y; s32 border = 1; - core::rect clipping_rect = - Parent ? Parent->getAbsoluteClippingRect() - : core::rect(); - core::rect *clipping_rect_ptr = - Parent ? &clipping_rect : nullptr; + core::rect clipping_rect = Parent ? Parent->getAbsoluteClippingRect() + : core::rect(); + core::rect *clipping_rect_ptr = Parent ? &clipping_rect : nullptr; driver->draw2DRectangle(m_options.slotbordercolor, - core::rect(v2s32(x1 - border, y1 - border), - v2s32(x2 + border, y1)), - clipping_rect_ptr); + core::rect(v2s32(x1 - border, y1 - border), + v2s32(x2 + border, y1)), clipping_rect_ptr); driver->draw2DRectangle(m_options.slotbordercolor, - core::rect(v2s32(x1 - border, y2), - v2s32(x2 + border, y2 + border)), - clipping_rect_ptr); + core::rect(v2s32(x1 - border, y2), + v2s32(x2 + border, y2 + border)), clipping_rect_ptr); driver->draw2DRectangle(m_options.slotbordercolor, - core::rect(v2s32(x1 - border, y1), - v2s32(x1, y2)), - clipping_rect_ptr); + core::rect(v2s32(x1 - border, y1), + v2s32(x1, y2)), clipping_rect_ptr); driver->draw2DRectangle(m_options.slotbordercolor, - core::rect(v2s32(x2, y1), - v2s32(x2 + border, y2)), - clipping_rect_ptr); + core::rect(v2s32(x2, y1), + v2s32(x2 + border, y2)), clipping_rect_ptr); } // layer 1 @@ -173,7 +179,8 @@ bool GUIInventoryList::OnEvent(const SEvent &event) // find the element that would be hovered if this inventorylist was invisible bool was_visible = IsVisible; IsVisible = false; - IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint( + IGUIElement *hovered = + Environment->getRootGUIElement()->getElementFromPoint( core::position2d(event.MouseInput.X, event.MouseInput.Y)); // if the player clicks outside of the formspec window, hovered is not @@ -209,10 +216,11 @@ s32 GUIInventoryList::getItemIndexAtPos(v2s32 p) const v2s32 base_pos = AbsoluteRect.UpperLeftCorner; // instead of looping through each slot, we look where p would be in the grid - s32 i = (p.X - base_pos.X) / (s32)m_slot_spacing.X + - m_geom.X * ((p.Y - base_pos.Y) / (s32)m_slot_spacing.Y); + s32 i = (p.X - base_pos.X) / (s32)m_slot_spacing.X + + m_geom.X * ((p.Y - base_pos.Y) / (s32)m_slot_spacing.Y); - v2s32 p0((i % m_geom.X) * m_slot_spacing.X, (i / m_geom.X) * m_slot_spacing.Y); + v2s32 p0((i % m_geom.X) * m_slot_spacing.X, + (i / m_geom.X) * m_slot_spacing.Y); core::rect rect = imgrect + base_pos + p0; diff --git a/src/gui/guiInventoryList.h b/src/gui/guiInventoryList.h index 58d71cabf..934d9ea3a 100644 --- a/src/gui/guiInventoryList.h +++ b/src/gui/guiInventoryList.h @@ -30,9 +30,11 @@ class GUIInventoryList : public gui::IGUIElement ItemSpec() = default; ItemSpec(const InventoryLocation &a_inventoryloc, - const std::string &a_listname, s32 a_i) : - inventoryloc(a_inventoryloc), - listname(a_listname), i(a_i) + const std::string &a_listname, + s32 a_i) : + inventoryloc(a_inventoryloc), + listname(a_listname), + i(a_i) { } @@ -44,8 +46,7 @@ class GUIInventoryList : public gui::IGUIElement }; // options for inventorylists that are setable with the lua api - struct Options - { + struct Options { // whether a one-pixel border for the slots should be drawn and its color bool slotborder = false; video::SColor slotbordercolor = video::SColor(200, 0, 0, 0); @@ -54,21 +55,34 @@ class GUIInventoryList : public gui::IGUIElement video::SColor slotbg_h = video::SColor(255, 192, 192, 192); }; - GUIInventoryList(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, InventoryManager *invmgr, - const InventoryLocation &inventoryloc, - const std::string &listname, const v2s32 &geom, - const s32 start_item_i, const v2s32 &slot_size, - const v2f32 &slot_spacing, GUIFormSpecMenu *fs_menu, - const Options &options, gui::IGUIFont *font); + GUIInventoryList(gui::IGUIEnvironment *env, + gui::IGUIElement *parent, + s32 id, + const core::rect &rectangle, + InventoryManager *invmgr, + const InventoryLocation &inventoryloc, + const std::string &listname, + const v2s32 &geom, + const s32 start_item_i, + const v2s32 &slot_size, + const v2f32 &slot_spacing, + GUIFormSpecMenu *fs_menu, + const Options &options, + gui::IGUIFont *font); virtual void draw() override; virtual bool OnEvent(const SEvent &event) override; - const InventoryLocation &getInventoryloc() const { return m_inventoryloc; } + const InventoryLocation &getInventoryloc() const + { + return m_inventoryloc; + } - const std::string &getListname() const { return m_listname; } + const std::string &getListname() const + { + return m_listname; + } void setSlotBGColors(const video::SColor &slotbg_n, const video::SColor &slotbg_h) { diff --git a/src/gui/guiItemImage.cpp b/src/gui/guiItemImage.cpp index 95775dbba..f93d5476c 100644 --- a/src/gui/guiItemImage.cpp +++ b/src/gui/guiItemImage.cpp @@ -20,12 +20,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiItemImage.h" #include "client/client.h" -GUIItemImage::GUIItemImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, const std::string &item_name, - gui::IGUIFont *font, Client *client) : - gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), - m_item_name(item_name), m_font(font), m_client(client), - m_label(core::stringw()) +GUIItemImage::GUIItemImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, + s32 id, const core::rect &rectangle, const std::string &item_name, + gui::IGUIFont *font, Client *client) : + gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), + m_item_name(item_name), m_font(font), m_client(client), m_label(core::stringw()) { } diff --git a/src/gui/guiItemImage.h b/src/gui/guiItemImage.h index ced693ee2..6fede6564 100644 --- a/src/gui/guiItemImage.h +++ b/src/gui/guiItemImage.h @@ -28,12 +28,15 @@ class GUIItemImage : public gui::IGUIElement { public: GUIItemImage(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - const core::rect &rectangle, const std::string &item_name, - gui::IGUIFont *font, Client *client); + const core::rect &rectangle, const std::string &item_name, + gui::IGUIFont *font, Client *client); virtual void draw() override; - virtual void setText(const wchar_t *text) override { m_label = text; } + virtual void setText(const wchar_t *text) override + { + m_label = text; + } private: std::string m_item_name; diff --git a/src/gui/guiKeyChangeMenu.cpp b/src/gui/guiKeyChangeMenu.cpp index e65a8311c..94fe0074a 100644 --- a/src/gui/guiKeyChangeMenu.cpp +++ b/src/gui/guiKeyChangeMenu.cpp @@ -32,7 +32,7 @@ #include "settings.h" #include -#include "mainmenumanager.h" // for g_gamecallback +#include "mainmenumanager.h" // for g_gamecallback #define KMaxButtonPerColumns 12 @@ -40,9 +40,7 @@ extern MainGameCallback *g_gamecallback; enum { - GUI_ID_BACK_BUTTON = 101, - GUI_ID_ABORT_BUTTON, - GUI_ID_SCROLL_BAR, + GUI_ID_BACK_BUTTON = 101, GUI_ID_ABORT_BUTTON, GUI_ID_SCROLL_BAR, // buttons GUI_ID_KEY_FORWARD_BUTTON, GUI_ID_KEY_BACKWARD_BUTTON, @@ -94,8 +92,9 @@ enum GUI_ID_CB_AUTOJUMP, }; -GUIKeyChangeMenu::GUIKeyChangeMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, IMenuManager *menumgr, ISimpleTextureSource *tsrc) : +GUIKeyChangeMenu::GUIKeyChangeMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, + ISimpleTextureSource *tsrc) : GUIModalMenu(env, parent, id, menumgr), m_tsrc(tsrc) { @@ -115,9 +114,9 @@ GUIKeyChangeMenu::~GUIKeyChangeMenu() void GUIKeyChangeMenu::removeChildren() { - const core::list &children = getChildren(); - core::list children_copy; - for (gui::IGUIElement *i : children) { + const core::list &children = getChildren(); + core::list children_copy; + for (gui::IGUIElement*i : children) { children_copy.push_back(i); } @@ -132,9 +131,12 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) removeChildren(); const float s = m_gui_scale; - DesiredRect = core::rect(screensize.X / 2 - 1113 * s / 2, - screensize.Y / 2 - 430 * s / 2, screensize.X / 2 + 1113 * s / 2, - screensize.Y / 2 + 430 * s / 2); + DesiredRect = core::rect( + screensize.X / 2 - 1113 * s / 2, + screensize.Y / 2 - 430 * s / 2, + screensize.X / 2 + 1113 * s / 2, + screensize.Y / 2 + 430 * s / 2 + ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); @@ -143,33 +145,32 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) { core::rect rect(0, 0, 600 * s, 40 * s); rect += topleft + v2s32(25 * s, 3 * s); - // gui::IGUIStaticText *t = - const wchar_t *text = wgettext("Keybindings. (If this menu screws up, " - "remove stuff from minetest.conf)"); - Environment->addStaticText(text, rect, false, true, this, -1); + //gui::IGUIStaticText *t = + const wchar_t *text = wgettext("Keybindings. (If this menu screws up, remove stuff from minetest.conf)"); + Environment->addStaticText(text, + rect, false, true, this, -1); delete[] text; - // t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); } // Build buttons v2s32 offset(25 * s, 60 * s); - for (size_t i = 0; i < key_settings.size(); i++) { + for(size_t i = 0; i < key_settings.size(); i++) + { key_setting *k = key_settings.at(i); { core::rect rect(0, 0, 150 * s, 20 * s); rect += topleft + v2s32(offset.X, offset.Y); - Environment->addStaticText( - k->button_name, rect, false, true, this, -1); + Environment->addStaticText(k->button_name, rect, false, true, this, -1); } { core::rect rect(0, 0, 100 * s, 30 * s); rect += topleft + v2s32(offset.X + 150 * s, offset.Y - 5 * s); const wchar_t *text = wgettext(k->key.name()); - k->button = GUIButton::addButton( - Environment, rect, m_tsrc, this, k->id, text); + k->button = GUIButton::addButton(Environment, rect, m_tsrc, this, k->id, text); delete[] text; } if ((i + 1) % KMaxButtonPerColumns == 0) { @@ -188,8 +189,8 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) core::rect rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); const wchar_t *text = wgettext("\"Special\" = climb down"); - Environment->addCheckBox(g_settings->getBool("aux1_descends"), - rect, this, GUI_ID_CB_AUX1_DESCENDS, text); + Environment->addCheckBox(g_settings->getBool("aux1_descends"), rect, this, + GUI_ID_CB_AUX1_DESCENDS, text); delete[] text; } offset += v2s32(0, 25 * s); @@ -202,10 +203,9 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) { core::rect rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); - const wchar_t *text = - wgettext("Double tap \"jump\" to toggle fly"); - Environment->addCheckBox(g_settings->getBool("doubletap_jump"), - rect, this, GUI_ID_CB_DOUBLETAP_JUMP, text); + const wchar_t *text = wgettext("Double tap \"jump\" to toggle fly"); + Environment->addCheckBox(g_settings->getBool("doubletap_jump"), rect, this, + GUI_ID_CB_DOUBLETAP_JUMP, text); delete[] text; } offset += v2s32(0, 25 * s); @@ -219,8 +219,8 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) core::rect rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); const wchar_t *text = wgettext("Automatic jumping"); - Environment->addCheckBox(g_settings->getBool("autojump"), rect, - this, GUI_ID_CB_AUTOJUMP, text); + Environment->addCheckBox(g_settings->getBool("autojump"), rect, this, + GUI_ID_CB_AUTOJUMP, text); delete[] text; } offset += v2s32(0, 25); @@ -229,27 +229,25 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) { core::rect rect(0, 0, 100 * s, 30 * s); rect += topleft + v2s32(size.X / 2 - 105 * s, size.Y - 40 * s); - const wchar_t *text = wgettext("Save"); - GUIButton::addButton(Environment, rect, m_tsrc, this, GUI_ID_BACK_BUTTON, - text); + const wchar_t *text = wgettext("Save"); + GUIButton::addButton(Environment, rect, m_tsrc, this, GUI_ID_BACK_BUTTON, text); delete[] text; } { core::rect rect(0, 0, 100 * s, 30 * s); rect += topleft + v2s32(size.X / 2 + 5 * s, size.Y - 40 * s); const wchar_t *text = wgettext("Cancel"); - GUIButton::addButton(Environment, rect, m_tsrc, this, GUI_ID_ABORT_BUTTON, - text); + GUIButton::addButton(Environment, rect, m_tsrc, this, GUI_ID_ABORT_BUTTON, text); delete[] text; } } void GUIKeyChangeMenu::drawMenu() { - gui::IGUISkin *skin = Environment->getSkin(); + gui::IGUISkin* skin = Environment->getSkin(); if (!skin) return; - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); @@ -271,21 +269,18 @@ bool GUIKeyChangeMenu::acceptInput() { gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUX1_DESCENDS); - if (e && e->getType() == gui::EGUIET_CHECK_BOX) - g_settings->setBool("aux1_descends", - ((gui::IGUICheckBox *)e)->isChecked()); + if(e && e->getType() == gui::EGUIET_CHECK_BOX) + g_settings->setBool("aux1_descends", ((gui::IGUICheckBox*)e)->isChecked()); } { gui::IGUIElement *e = getElementFromId(GUI_ID_CB_DOUBLETAP_JUMP); - if (e && e->getType() == gui::EGUIET_CHECK_BOX) - g_settings->setBool("doubletap_jump", - ((gui::IGUICheckBox *)e)->isChecked()); + if(e && e->getType() == gui::EGUIET_CHECK_BOX) + g_settings->setBool("doubletap_jump", ((gui::IGUICheckBox*)e)->isChecked()); } { gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUTOJUMP); - if (e && e->getType() == gui::EGUIET_CHECK_BOX) - g_settings->setBool("autojump", - ((gui::IGUICheckBox *)e)->isChecked()); + if(e && e->getType() == gui::EGUIET_CHECK_BOX) + g_settings->setBool("autojump", ((gui::IGUICheckBox*)e)->isChecked()); } clearKeyCache(); @@ -306,10 +301,10 @@ bool GUIKeyChangeMenu::resetMenu() } return true; } -bool GUIKeyChangeMenu::OnEvent(const SEvent &event) +bool GUIKeyChangeMenu::OnEvent(const SEvent& event) { - if (event.EventType == EET_KEY_INPUT_EVENT && active_key && - event.KeyInput.PressedDown) { + if (event.EventType == EET_KEY_INPUT_EVENT && active_key + && event.KeyInput.PressedDown) { bool prefer_character = shift_down; KeyPress kp(event.KeyInput, prefer_character); @@ -320,10 +315,10 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent &event) kp = active_key->key; // Cancel bool shift_went_down = false; - if (!shift_down && + if(!shift_down && (event.KeyInput.Key == irr::KEY_SHIFT || - event.KeyInput.Key == irr::KEY_LSHIFT || - event.KeyInput.Key == irr::KEY_RSHIFT)) + event.KeyInput.Key == irr::KEY_LSHIFT || + event.KeyInput.Key == irr::KEY_RSHIFT)) shift_went_down = true; // Display Key already in use message @@ -341,8 +336,8 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent &event) core::rect rect(0, 0, 600, 40); rect += v2s32(0, 0) + v2s32(25, 30); const wchar_t *text = wgettext("Key already in use"); - this->key_used_text = Environment->addStaticText( - text, rect, false, true, this, -1); + this->key_used_text = Environment->addStaticText(text, + rect, false, true, this, -1); delete[] text; } else if (!key_in_use && this->key_used_text) { this->key_used_text->remove(); @@ -357,7 +352,7 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent &event) delete[] text; // Allow characters made with shift - if (shift_went_down) { + if (shift_went_down){ shift_down = true; return false; } @@ -365,46 +360,49 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent &event) active_key = nullptr; return true; } - } else if (event.EventType == EET_KEY_INPUT_EVENT && !active_key && - event.KeyInput.PressedDown && - event.KeyInput.Key == irr::KEY_ESCAPE) { + } else if (event.EventType == EET_KEY_INPUT_EVENT && !active_key + && event.KeyInput.PressedDown + && event.KeyInput.Key == irr::KEY_ESCAPE) { quitMenu(); return true; } else if (event.EventType == EET_GUI_EVENT) { - if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && - isVisible()) { - if (!canTakeFocus(event.GUIEvent.Element)) { - infostream << "GUIKeyChangeMenu: Not allowing focus " - "change." - << std::endl; + if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if (!canTakeFocus(event.GUIEvent.Element)) + { + infostream << "GUIKeyChangeMenu: Not allowing focus change." + << std::endl; // Returning true disables focus change return true; } } - if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) { - switch (event.GUIEvent.Caller->getID()) { - case GUI_ID_BACK_BUTTON: // back - acceptInput(); - quitMenu(); - return true; - case GUI_ID_ABORT_BUTTON: // abort - quitMenu(); - return true; - default: - resetMenu(); - for (key_setting *ks : key_settings) { - if (ks->id == event.GUIEvent.Caller->getID()) { - active_key = ks; - break; + if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) + { + switch (event.GUIEvent.Caller->getID()) + { + case GUI_ID_BACK_BUTTON: //back + acceptInput(); + quitMenu(); + return true; + case GUI_ID_ABORT_BUTTON: //abort + quitMenu(); + return true; + default: + resetMenu(); + for (key_setting *ks : key_settings) { + if (ks->id == event.GUIEvent.Caller->getID()) { + active_key = ks; + break; + } } - } - FATAL_ERROR_IF(!active_key, "Key setting not found"); + FATAL_ERROR_IF(!active_key, "Key setting not found"); - shift_down = false; - const wchar_t *text = wgettext("press key"); - active_key->button->setText(text); - delete[] text; - break; + shift_down = false; + const wchar_t *text = wgettext("press key"); + active_key->button->setText(text); + delete[] text; + break; } Environment->setFocus(this); } @@ -412,8 +410,7 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent &event) return Parent ? Parent->OnEvent(event) : false; } -void GUIKeyChangeMenu::add_key( - int id, const wchar_t *button_name, const std::string &setting_name) +void GUIKeyChangeMenu::add_key(int id, const wchar_t *button_name, const std::string &setting_name) { key_setting *k = new key_setting; k->id = id; @@ -426,76 +423,48 @@ void GUIKeyChangeMenu::add_key( void GUIKeyChangeMenu::init_keys() { - this->add_key(GUI_ID_KEY_FORWARD_BUTTON, wgettext("Forward"), "keymap_forward"); - this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, wgettext("Backward"), - "keymap_backward"); - this->add_key(GUI_ID_KEY_LEFT_BUTTON, wgettext("Left"), "keymap_left"); - this->add_key(GUI_ID_KEY_RIGHT_BUTTON, wgettext("Right"), "keymap_right"); - this->add_key(GUI_ID_KEY_USE_BUTTON, wgettext("Special"), "keymap_special1"); - this->add_key(GUI_ID_KEY_JUMP_BUTTON, wgettext("Jump"), "keymap_jump"); - this->add_key(GUI_ID_KEY_SNEAK_BUTTON, wgettext("Sneak"), "keymap_sneak"); - this->add_key(GUI_ID_KEY_DROP_BUTTON, wgettext("Drop"), "keymap_drop"); - this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, wgettext("Inventory"), - "keymap_inventory"); - this->add_key(GUI_ID_KEY_ENDERCHEST_BUTTON, wgettext("Enderchest"), - "keymap_enderchest"); - this->add_key(GUI_ID_KEY_HOTBAR_PREV_BUTTON, wgettext("Prev. item"), - "keymap_hotbar_previous"); - this->add_key(GUI_ID_KEY_HOTBAR_NEXT_BUTTON, wgettext("Next item"), - "keymap_hotbar_next"); - this->add_key(GUI_ID_KEY_ZOOM_BUTTON, wgettext("Zoom"), "keymap_zoom"); - this->add_key(GUI_ID_KEY_CAMERA_BUTTON, wgettext("Change camera"), - "keymap_camera_mode"); - this->add_key(GUI_ID_KEY_MINIMAP_BUTTON, wgettext("Toggle minimap"), - "keymap_minimap"); - this->add_key(GUI_ID_KEY_FLY_BUTTON, wgettext("Toggle fly"), "keymap_freemove"); - this->add_key(GUI_ID_KEY_PITCH_MOVE, wgettext("Toggle pitchmove"), - "keymap_pitchmove"); - this->add_key(GUI_ID_KEY_FAST_BUTTON, wgettext("Toggle fast"), "keymap_fastmove"); - this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, wgettext("Toggle noclip"), - "keymap_noclip"); - this->add_key(GUI_ID_KEY_MUTE_BUTTON, wgettext("Mute"), "keymap_mute"); - this->add_key(GUI_ID_KEY_DEC_VOLUME_BUTTON, wgettext("Dec. volume"), - "keymap_decrease_volume"); - this->add_key(GUI_ID_KEY_INC_VOLUME_BUTTON, wgettext("Inc. volume"), - "keymap_increase_volume"); - this->add_key(GUI_ID_KEY_AUTOFWD_BUTTON, wgettext("Autoforward"), - "keymap_autoforward"); - this->add_key(GUI_ID_KEY_CHAT_BUTTON, wgettext("Chat"), "keymap_chat"); - this->add_key(GUI_ID_KEY_SCREENSHOT_BUTTON, wgettext("Screenshot"), - "keymap_screenshot"); - this->add_key(GUI_ID_KEY_RANGE_BUTTON, wgettext("Range select"), - "keymap_rangeselect"); - this->add_key(GUI_ID_KEY_DEC_RANGE_BUTTON, wgettext("Dec. range"), - "keymap_decrease_viewing_range_min"); - this->add_key(GUI_ID_KEY_INC_RANGE_BUTTON, wgettext("Inc. range"), - "keymap_increase_viewing_range_min"); - this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, wgettext("Console"), "keymap_console"); - this->add_key(GUI_ID_KEY_CMD_BUTTON, wgettext("Command"), "keymap_cmd"); - this->add_key(GUI_ID_KEY_CMD_LOCAL_BUTTON, wgettext("Local command"), - "keymap_cmd_local"); - this->add_key(GUI_ID_KEY_HUD_BUTTON, wgettext("Toggle HUD"), "keymap_toggle_hud"); - this->add_key(GUI_ID_KEY_CHATLOG_BUTTON, wgettext("Toggle chat log"), - "keymap_toggle_chat"); - this->add_key(GUI_ID_KEY_FOG_BUTTON, wgettext("Toggle fog"), "keymap_toggle_fog"); - this->add_key(GUI_ID_KEY_CHEAT_MENU_BUTTON, wgettext("Toggle C. Menu"), - "keymap_toggle_cheat_menu"); - this->add_key(GUI_ID_KEY_KILLAURA_BUTTON, wgettext("Killaura"), - "keymap_toggle_killaura"); - this->add_key(GUI_ID_KEY_FREECAM_BUTTON, wgettext("Freecam"), - "keymap_toggle_freecam"); - this->add_key(GUI_ID_KEY_SCAFFOLD_BUTTON, wgettext("Scaffold"), - "keymap_toggle_scaffold"); - this->add_key(GUI_ID_KEY_NEXT_ITEM_BUTTON, wgettext("NextItem"), - "keymap_toggle_next_item"); - this->add_key(GUI_ID_KEY_SELECT_UP_BUTTON, wgettext("C. Menu Up"), - "keymap_select_up"); - this->add_key(GUI_ID_KEY_SELECT_DOWN_BUTTON, wgettext("C. Menu Down"), - "keymap_select_down"); - this->add_key(GUI_ID_KEY_SELECT_LEFT_BUTTON, wgettext("C. Menu Left"), - "keymap_select_left"); - this->add_key(GUI_ID_KEY_SELECT_RIGHT_BUTTON, wgettext("C. Menu Right"), - "keymap_select_right"); - this->add_key(GUI_ID_KEY_SELECT_CONFIRM_BUTTON, wgettext("C. Menu Enter"), - "keymap_select_confirm"); + this->add_key(GUI_ID_KEY_FORWARD_BUTTON, wgettext("Forward"), "keymap_forward"); + this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, wgettext("Backward"), "keymap_backward"); + this->add_key(GUI_ID_KEY_LEFT_BUTTON, wgettext("Left"), "keymap_left"); + this->add_key(GUI_ID_KEY_RIGHT_BUTTON, wgettext("Right"), "keymap_right"); + this->add_key(GUI_ID_KEY_USE_BUTTON, wgettext("Special"), "keymap_special1"); + this->add_key(GUI_ID_KEY_JUMP_BUTTON, wgettext("Jump"), "keymap_jump"); + this->add_key(GUI_ID_KEY_SNEAK_BUTTON, wgettext("Sneak"), "keymap_sneak"); + this->add_key(GUI_ID_KEY_DROP_BUTTON, wgettext("Drop"), "keymap_drop"); + this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, wgettext("Inventory"), "keymap_inventory"); + this->add_key(GUI_ID_KEY_ENDERCHEST_BUTTON,wgettext("Enderchest"), "keymap_enderchest"); + this->add_key(GUI_ID_KEY_HOTBAR_PREV_BUTTON,wgettext("Prev. item"), "keymap_hotbar_previous"); + this->add_key(GUI_ID_KEY_HOTBAR_NEXT_BUTTON,wgettext("Next item"), "keymap_hotbar_next"); + this->add_key(GUI_ID_KEY_ZOOM_BUTTON, wgettext("Zoom"), "keymap_zoom"); + this->add_key(GUI_ID_KEY_CAMERA_BUTTON, wgettext("Change camera"), "keymap_camera_mode"); + this->add_key(GUI_ID_KEY_MINIMAP_BUTTON, wgettext("Toggle minimap"), "keymap_minimap"); + this->add_key(GUI_ID_KEY_FLY_BUTTON, wgettext("Toggle fly"), "keymap_freemove"); + this->add_key(GUI_ID_KEY_PITCH_MOVE, wgettext("Toggle pitchmove"), "keymap_pitchmove"); + this->add_key(GUI_ID_KEY_FAST_BUTTON, wgettext("Toggle fast"), "keymap_fastmove"); + this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, wgettext("Toggle noclip"), "keymap_noclip"); + this->add_key(GUI_ID_KEY_MUTE_BUTTON, wgettext("Mute"), "keymap_mute"); + this->add_key(GUI_ID_KEY_DEC_VOLUME_BUTTON,wgettext("Dec. volume"), "keymap_decrease_volume"); + this->add_key(GUI_ID_KEY_INC_VOLUME_BUTTON,wgettext("Inc. volume"), "keymap_increase_volume"); + this->add_key(GUI_ID_KEY_AUTOFWD_BUTTON, wgettext("Autoforward"), "keymap_autoforward"); + this->add_key(GUI_ID_KEY_CHAT_BUTTON, wgettext("Chat"), "keymap_chat"); + this->add_key(GUI_ID_KEY_SCREENSHOT_BUTTON,wgettext("Screenshot"), "keymap_screenshot"); + this->add_key(GUI_ID_KEY_RANGE_BUTTON, wgettext("Range select"), "keymap_rangeselect"); + this->add_key(GUI_ID_KEY_DEC_RANGE_BUTTON, wgettext("Dec. range"), "keymap_decrease_viewing_range_min"); + this->add_key(GUI_ID_KEY_INC_RANGE_BUTTON, wgettext("Inc. range"), "keymap_increase_viewing_range_min"); + this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, wgettext("Console"), "keymap_console"); + this->add_key(GUI_ID_KEY_CMD_BUTTON, wgettext("Command"), "keymap_cmd"); + this->add_key(GUI_ID_KEY_CMD_LOCAL_BUTTON, wgettext("Local command"), "keymap_cmd_local"); + this->add_key(GUI_ID_KEY_HUD_BUTTON, wgettext("Toggle HUD"), "keymap_toggle_hud"); + this->add_key(GUI_ID_KEY_CHATLOG_BUTTON, wgettext("Toggle chat log"), "keymap_toggle_chat"); + this->add_key(GUI_ID_KEY_FOG_BUTTON, wgettext("Toggle fog"), "keymap_toggle_fog"); + this->add_key(GUI_ID_KEY_CHEAT_MENU_BUTTON,wgettext("Toggle C. Menu"),"keymap_toggle_cheat_menu"); + this->add_key(GUI_ID_KEY_KILLAURA_BUTTON, wgettext("Killaura"), "keymap_toggle_killaura"); + this->add_key(GUI_ID_KEY_FREECAM_BUTTON, wgettext("Freecam"), "keymap_toggle_freecam"); + this->add_key(GUI_ID_KEY_SCAFFOLD_BUTTON, wgettext("Scaffold"), "keymap_toggle_scaffold"); + this->add_key(GUI_ID_KEY_NEXT_ITEM_BUTTON, wgettext("NextItem"), "keymap_toggle_next_item"); + this->add_key(GUI_ID_KEY_SELECT_UP_BUTTON, wgettext("C. Menu Up"), "keymap_select_up"); + this->add_key(GUI_ID_KEY_SELECT_DOWN_BUTTON,wgettext("C. Menu Down"), "keymap_select_down"); + this->add_key(GUI_ID_KEY_SELECT_LEFT_BUTTON,wgettext("C. Menu Left"), "keymap_select_left"); + this->add_key(GUI_ID_KEY_SELECT_RIGHT_BUTTON,wgettext("C. Menu Right"),"keymap_select_right"); + this->add_key(GUI_ID_KEY_SELECT_CONFIRM_BUTTON,wgettext("C. Menu Enter"),"keymap_select_confirm"); } diff --git a/src/gui/guiMainMenu.h b/src/gui/guiMainMenu.h index 957ffbc41..1dca8bf2d 100644 --- a/src/gui/guiMainMenu.h +++ b/src/gui/guiMainMenu.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -struct MainMenuDataForScript -{ +struct MainMenuDataForScript { MainMenuDataForScript() = default; @@ -33,8 +32,7 @@ struct MainMenuDataForScript std::string errormessage = ""; }; -struct MainMenuData -{ +struct MainMenuData { // Client options std::string servername; std::string serverdescription; diff --git a/src/gui/guiPasswordChange.cpp b/src/gui/guiPasswordChange.cpp index 5eb777173..5311c6fef 100644 --- a/src/gui/guiPasswordChange.cpp +++ b/src/gui/guiPasswordChange.cpp @@ -35,11 +35,15 @@ const int ID_change = 259; const int ID_message = 260; const int ID_cancel = 261; -GUIPasswordChange::GUIPasswordChange(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, IMenuManager *menumgr, Client *client, - ISimpleTextureSource *tsrc) : - GUIModalMenu(env, parent, id, menumgr), - m_client(client), m_tsrc(tsrc) +GUIPasswordChange::GUIPasswordChange(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + Client* client, + ISimpleTextureSource *tsrc +): + GUIModalMenu(env, parent, id, menumgr), + m_client(client), + m_tsrc(tsrc) { } @@ -76,9 +80,12 @@ void GUIPasswordChange::regenerateGui(v2u32 screensize) Calculate new sizes and positions */ const float s = m_gui_scale; - DesiredRect = core::rect(screensize.X / 2 - 580 * s / 2, - screensize.Y / 2 - 300 * s / 2, screensize.X / 2 + 580 * s / 2, - screensize.Y / 2 + 300 * s / 2); + DesiredRect = core::rect( + screensize.X / 2 - 580 * s / 2, + screensize.Y / 2 - 300 * s / 2, + screensize.X / 2 + 580 * s / 2, + screensize.Y / 2 + 300 * s / 2 + ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); @@ -131,8 +138,8 @@ void GUIPasswordChange::regenerateGui(v2u32 screensize) { core::rect rect(0, 0, 230 * s, 30 * s); rect += topleft_client + v2s32(160 * s, ypos); - gui::IGUIEditBox *e = Environment->addEditBox(m_newpass_confirm.c_str(), - rect, true, this, ID_newPassword2); + gui::IGUIEditBox *e = Environment->addEditBox( + m_newpass_confirm.c_str(), rect, true, this, ID_newPassword2); e->setPasswordBox(true); } @@ -157,8 +164,9 @@ void GUIPasswordChange::regenerateGui(v2u32 screensize) core::rect rect(0, 0, 300 * s, 20 * s); rect += topleft_client + v2s32(35 * s, ypos); text = wgettext("Passwords do not match!"); - IGUIElement *e = Environment->addStaticText( - text, rect, false, true, this, ID_message); + IGUIElement *e = + Environment->addStaticText( + text, rect, false, true, this, ID_message); e->setVisible(false); delete[] text; } @@ -228,9 +236,8 @@ bool GUIPasswordChange::OnEvent(const SEvent &event) if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { - infostream << "GUIPasswordChange: Not allowing focus " - "change." - << std::endl; + infostream << "GUIPasswordChange: Not allowing focus change." + << std::endl; // Returning true disables focus change return true; } diff --git a/src/gui/guiPathSelectMenu.cpp b/src/gui/guiPathSelectMenu.cpp index 562778894..489927a11 100644 --- a/src/gui/guiPathSelectMenu.cpp +++ b/src/gui/guiPathSelectMenu.cpp @@ -19,12 +19,14 @@ #include "guiPathSelectMenu.h" -GUIFileSelectMenu::GUIFileSelectMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, IMenuManager *menumgr, const std::string &title, - const std::string &formname, bool is_file_select) : - GUIModalMenu(env, parent, id, menumgr), - m_title(utf8_to_wide(title)), m_formname(formname), - m_file_select_dialog(is_file_select) +GUIFileSelectMenu::GUIFileSelectMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, + const std::string &title, const std::string &formname, + bool is_file_select) : + GUIModalMenu(env, parent, id, menumgr), + m_title(utf8_to_wide(title)), + m_formname(formname), + m_file_select_dialog(is_file_select) { } diff --git a/src/gui/guiScrollBar.cpp b/src/gui/guiScrollBar.cpp index 4f4b555ab..b04ccb9d5 100644 --- a/src/gui/guiScrollBar.cpp +++ b/src/gui/guiScrollBar.cpp @@ -21,8 +21,7 @@ GUIScrollBar::GUIScrollBar(IGUIEnvironment *environment, IGUIElement *parent, s3 is_horizontal(horizontal), is_auto_scaling(auto_scale), dragged_by_slider(false), tray_clicked(false), scroll_pos(0), draw_center(0), thumb_size(0), min_pos(0), max_pos(100), small_step(10), - large_step(50), last_change(0), drag_offset(0), page_size(100), - border_size(0) + large_step(50), last_change(0), drag_offset(0), page_size(100), border_size(0) { refreshControls(); setNotClipped(false); @@ -116,10 +115,8 @@ bool GUIScrollBar::OnEvent(const SEvent &event) if (is_inside) { is_dragging = true; dragged_by_slider = slider_rect.isPointInside(p); - core::vector2di corner = - slider_rect.UpperLeftCorner; - drag_offset = is_horizontal ? p.X - corner.X - : p.Y - corner.Y; + core::vector2di corner = slider_rect.UpperLeftCorner; + drag_offset = is_horizontal ? p.X - corner.X : p.Y - corner.Y; tray_clicked = !dragged_by_slider; if (tray_clicked) { const s32 new_pos = getPosFromMousePos(p); @@ -133,8 +130,7 @@ bool GUIScrollBar::OnEvent(const SEvent &event) e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; e.GUIEvent.Element = nullptr; - e.GUIEvent.EventType = - EGET_SCROLL_BAR_CHANGED; + e.GUIEvent.EventType = EGET_SCROLL_BAR_CHANGED; Parent->OnEvent(e); } } @@ -251,8 +247,7 @@ s32 GUIScrollBar::getPosFromMousePos(const core::position2di &pos) const w = RelativeRect.getHeight() - border_size * 2 - thumb_size; p = pos.Y - AbsoluteRect.UpperLeftCorner.Y - border_size - offset; } - return core::isnotzero(range()) ? s32(f32(p) / f32(w) * range() + 0.5f) + min_pos - : 0; + return core::isnotzero(range()) ? s32(f32(p) / f32(w) * range() + 0.5f) + min_pos : 0; } void GUIScrollBar::setPos(const s32 &pos) @@ -278,7 +273,7 @@ void GUIScrollBar::setPos(const s32 &pos) f32 f = core::isnotzero(range()) ? (f32(thumb_area) - f32(thumb_size)) / range() : 1.0f; draw_center = s32((f32(scroll_pos - min_pos) * f) + (f32(thumb_size) * 0.5f)) + - border_size; + border_size; } void GUIScrollBar::setSmallStep(const s32 &step) diff --git a/src/gui/guiSkin.cpp b/src/gui/guiSkin.cpp index e2a6af5fd..8892a00b4 100644 --- a/src/gui/guiSkin.cpp +++ b/src/gui/guiSkin.cpp @@ -18,39 +18,41 @@ namespace irr namespace gui { -GUISkin::GUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver *driver) : - SpriteBank(0), Driver(driver), Type(type) +GUISkin::GUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver) +: SpriteBank(0), Driver(driver), Type(type) { -#ifdef _DEBUG + #ifdef _DEBUG setDebugName("GUISkin"); -#endif - - if ((Type == EGST_WINDOWS_CLASSIC) || (Type == EGST_WINDOWS_METALLIC)) { - Colors[EGDC_3D_DARK_SHADOW] = video::SColor(101, 50, 50, 50); - Colors[EGDC_3D_SHADOW] = video::SColor(101, 130, 130, 130); - Colors[EGDC_3D_FACE] = video::SColor(101, 210, 210, 210); - Colors[EGDC_3D_HIGH_LIGHT] = video::SColor(101, 255, 255, 255); - Colors[EGDC_3D_LIGHT] = video::SColor(101, 210, 210, 210); - Colors[EGDC_ACTIVE_BORDER] = video::SColor(101, 16, 14, 115); - Colors[EGDC_ACTIVE_CAPTION] = video::SColor(255, 255, 255, 255); - Colors[EGDC_APP_WORKSPACE] = video::SColor(101, 100, 100, 100); - Colors[EGDC_BUTTON_TEXT] = video::SColor(240, 10, 10, 10); - Colors[EGDC_GRAY_TEXT] = video::SColor(240, 130, 130, 130); - Colors[EGDC_HIGH_LIGHT] = video::SColor(101, 8, 36, 107); - Colors[EGDC_HIGH_LIGHT_TEXT] = video::SColor(240, 255, 255, 255); - Colors[EGDC_INACTIVE_BORDER] = video::SColor(101, 165, 165, 165); - Colors[EGDC_INACTIVE_CAPTION] = video::SColor(255, 30, 30, 30); - Colors[EGDC_TOOLTIP] = video::SColor(200, 0, 0, 0); - Colors[EGDC_TOOLTIP_BACKGROUND] = video::SColor(200, 255, 255, 225); - Colors[EGDC_SCROLLBAR] = video::SColor(101, 230, 230, 230); - Colors[EGDC_WINDOW] = video::SColor(101, 255, 255, 255); - Colors[EGDC_WINDOW_SYMBOL] = video::SColor(200, 10, 10, 10); - Colors[EGDC_ICON] = video::SColor(200, 255, 255, 255); - Colors[EGDC_ICON_HIGH_LIGHT] = video::SColor(200, 8, 36, 107); - Colors[EGDC_GRAY_WINDOW_SYMBOL] = video::SColor(240, 100, 100, 100); - Colors[EGDC_EDITABLE] = video::SColor(255, 255, 255, 255); - Colors[EGDC_GRAY_EDITABLE] = video::SColor(255, 120, 120, 120); - Colors[EGDC_FOCUSED_EDITABLE] = video::SColor(255, 240, 240, 255); + #endif + + if ((Type == EGST_WINDOWS_CLASSIC) || (Type == EGST_WINDOWS_METALLIC)) + { + Colors[EGDC_3D_DARK_SHADOW] = video::SColor(101,50,50,50); + Colors[EGDC_3D_SHADOW] = video::SColor(101,130,130,130); + Colors[EGDC_3D_FACE] = video::SColor(101,210,210,210); + Colors[EGDC_3D_HIGH_LIGHT] = video::SColor(101,255,255,255); + Colors[EGDC_3D_LIGHT] = video::SColor(101,210,210,210); + Colors[EGDC_ACTIVE_BORDER] = video::SColor(101,16,14,115); + Colors[EGDC_ACTIVE_CAPTION] = video::SColor(255,255,255,255); + Colors[EGDC_APP_WORKSPACE] = video::SColor(101,100,100,100); + Colors[EGDC_BUTTON_TEXT] = video::SColor(240,10,10,10); + Colors[EGDC_GRAY_TEXT] = video::SColor(240,130,130,130); + Colors[EGDC_HIGH_LIGHT] = video::SColor(101,8,36,107); + Colors[EGDC_HIGH_LIGHT_TEXT] = video::SColor(240,255,255,255); + Colors[EGDC_INACTIVE_BORDER] = video::SColor(101,165,165,165); + Colors[EGDC_INACTIVE_CAPTION] = video::SColor(255,30,30,30); + Colors[EGDC_TOOLTIP] = video::SColor(200,0,0,0); + Colors[EGDC_TOOLTIP_BACKGROUND] = video::SColor(200,255,255,225); + Colors[EGDC_SCROLLBAR] = video::SColor(101,230,230,230); + Colors[EGDC_WINDOW] = video::SColor(101,255,255,255); + Colors[EGDC_WINDOW_SYMBOL] = video::SColor(200,10,10,10); + Colors[EGDC_ICON] = video::SColor(200,255,255,255); + Colors[EGDC_ICON_HIGH_LIGHT] = video::SColor(200,8,36,107); + Colors[EGDC_GRAY_WINDOW_SYMBOL] = video::SColor(240,100,100,100); + Colors[EGDC_EDITABLE] = video::SColor(255,255,255,255); + Colors[EGDC_GRAY_EDITABLE] = video::SColor(255,120,120,120); + Colors[EGDC_FOCUSED_EDITABLE] = video::SColor(255,240,240,255); + Sizes[EGDS_SCROLLBAR_SIZE] = 14; Sizes[EGDS_MENU_HEIGHT] = 30; @@ -66,36 +68,36 @@ GUISkin::GUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver *driver) : Sizes[EGDS_TITLEBARTEXT_DISTANCE_X] = 2; Sizes[EGDS_TITLEBARTEXT_DISTANCE_Y] = 0; - } else { - // 0x80a6a8af - Colors[EGDC_3D_DARK_SHADOW] = 0x60767982; - // Colors[EGDC_3D_FACE] = 0xc0c9ccd4; // tab - // background - Colors[EGDC_3D_FACE] = 0xc0cbd2d9; // tab background - Colors[EGDC_3D_SHADOW] = - 0x50e4e8f1; // tab background, and left-top highlight - Colors[EGDC_3D_HIGH_LIGHT] = 0x40c7ccdc; - Colors[EGDC_3D_LIGHT] = 0x802e313a; - Colors[EGDC_ACTIVE_BORDER] = 0x80404040; // window title - Colors[EGDC_ACTIVE_CAPTION] = 0xffd0d0d0; - Colors[EGDC_APP_WORKSPACE] = 0xc0646464; // unused - Colors[EGDC_BUTTON_TEXT] = 0xd0161616; - Colors[EGDC_GRAY_TEXT] = 0x3c141414; - Colors[EGDC_HIGH_LIGHT] = 0x6c606060; - Colors[EGDC_HIGH_LIGHT_TEXT] = 0xd0e0e0e0; - Colors[EGDC_INACTIVE_BORDER] = 0xf0a5a5a5; - Colors[EGDC_INACTIVE_CAPTION] = 0xffd2d2d2; - Colors[EGDC_TOOLTIP] = 0xf00f2033; - Colors[EGDC_TOOLTIP_BACKGROUND] = 0xc0cbd2d9; - Colors[EGDC_SCROLLBAR] = 0xf0e0e0e0; - Colors[EGDC_WINDOW] = 0xf0f0f0f0; - Colors[EGDC_WINDOW_SYMBOL] = 0xd0161616; - Colors[EGDC_ICON] = 0xd0161616; - Colors[EGDC_ICON_HIGH_LIGHT] = 0xd0606060; - Colors[EGDC_GRAY_WINDOW_SYMBOL] = 0x3c101010; - Colors[EGDC_EDITABLE] = 0xf0ffffff; - Colors[EGDC_GRAY_EDITABLE] = 0xf0cccccc; - Colors[EGDC_FOCUSED_EDITABLE] = 0xf0fffff0; + } + else + { + //0x80a6a8af + Colors[EGDC_3D_DARK_SHADOW] = 0x60767982; + //Colors[EGDC_3D_FACE] = 0xc0c9ccd4; // tab background + Colors[EGDC_3D_FACE] = 0xc0cbd2d9; // tab background + Colors[EGDC_3D_SHADOW] = 0x50e4e8f1; // tab background, and left-top highlight + Colors[EGDC_3D_HIGH_LIGHT] = 0x40c7ccdc; + Colors[EGDC_3D_LIGHT] = 0x802e313a; + Colors[EGDC_ACTIVE_BORDER] = 0x80404040; // window title + Colors[EGDC_ACTIVE_CAPTION] = 0xffd0d0d0; + Colors[EGDC_APP_WORKSPACE] = 0xc0646464; // unused + Colors[EGDC_BUTTON_TEXT] = 0xd0161616; + Colors[EGDC_GRAY_TEXT] = 0x3c141414; + Colors[EGDC_HIGH_LIGHT] = 0x6c606060; + Colors[EGDC_HIGH_LIGHT_TEXT] = 0xd0e0e0e0; + Colors[EGDC_INACTIVE_BORDER] = 0xf0a5a5a5; + Colors[EGDC_INACTIVE_CAPTION] = 0xffd2d2d2; + Colors[EGDC_TOOLTIP] = 0xf00f2033; + Colors[EGDC_TOOLTIP_BACKGROUND] = 0xc0cbd2d9; + Colors[EGDC_SCROLLBAR] = 0xf0e0e0e0; + Colors[EGDC_WINDOW] = 0xf0f0f0f0; + Colors[EGDC_WINDOW_SYMBOL] = 0xd0161616; + Colors[EGDC_ICON] = 0xd0161616; + Colors[EGDC_ICON_HIGH_LIGHT] = 0xd0606060; + Colors[EGDC_GRAY_WINDOW_SYMBOL] = 0x3c101010; + Colors[EGDC_EDITABLE] = 0xf0ffffff; + Colors[EGDC_GRAY_EDITABLE] = 0xf0cccccc; + Colors[EGDC_FOCUSED_EDITABLE] = 0xf0fffff0; Sizes[EGDS_SCROLLBAR_SIZE] = 14; Sizes[EGDS_MENU_HEIGHT] = 48; @@ -158,16 +160,18 @@ GUISkin::GUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver *driver) : Icons[EGDI_FILE] = 245; Icons[EGDI_DIRECTORY] = 246; - for (u32 i = 0; i < EGDF_COUNT; ++i) + for (u32 i=0; idrop(); } @@ -176,6 +180,7 @@ GUISkin::~GUISkin() SpriteBank->drop(); } + //! returns default color video::SColor GUISkin::getColor(EGUI_DEFAULT_COLOR color) const { @@ -185,6 +190,7 @@ video::SColor GUISkin::getColor(EGUI_DEFAULT_COLOR color) const return video::SColor(); } + //! sets a default color void GUISkin::setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) { @@ -192,6 +198,7 @@ void GUISkin::setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor) Colors[which] = newColor; } + //! returns size for the given size type s32 GUISkin::getSize(EGUI_DEFAULT_SIZE size) const { @@ -201,6 +208,7 @@ s32 GUISkin::getSize(EGUI_DEFAULT_SIZE size) const return 0; } + //! sets a default size void GUISkin::setSize(EGUI_DEFAULT_SIZE which, s32 size) { @@ -208,8 +216,9 @@ void GUISkin::setSize(EGUI_DEFAULT_SIZE which, s32 size) Sizes[which] = size; } + //! returns the default font -IGUIFont *GUISkin::getFont(EGUI_DEFAULT_FONT which) const +IGUIFont* GUISkin::getFont(EGUI_DEFAULT_FONT which) const { if (((u32)which < EGDF_COUNT) && Fonts[which]) return Fonts[which]; @@ -217,13 +226,15 @@ IGUIFont *GUISkin::getFont(EGUI_DEFAULT_FONT which) const return Fonts[EGDF_DEFAULT]; } + //! sets a default font -void GUISkin::setFont(IGUIFont *font, EGUI_DEFAULT_FONT which) +void GUISkin::setFont(IGUIFont* font, EGUI_DEFAULT_FONT which) { if ((u32)which >= EGDF_COUNT) return; - if (font) { + if (font) + { font->grab(); if (Fonts[which]) Fonts[which]->drop(); @@ -232,14 +243,16 @@ void GUISkin::setFont(IGUIFont *font, EGUI_DEFAULT_FONT which) } } + //! gets the sprite bank stored -IGUISpriteBank *GUISkin::getSpriteBank() const +IGUISpriteBank* GUISkin::getSpriteBank() const { return SpriteBank; } + //! set a new sprite bank or remove one by passing 0 -void GUISkin::setSpriteBank(IGUISpriteBank *bank) +void GUISkin::setSpriteBank(IGUISpriteBank* bank) { if (bank) bank->grab(); @@ -250,6 +263,7 @@ void GUISkin::setSpriteBank(IGUISpriteBank *bank) SpriteBank = bank; } + //! Returns a default icon u32 GUISkin::getIcon(EGUI_DEFAULT_ICON icon) const { @@ -259,6 +273,7 @@ u32 GUISkin::getIcon(EGUI_DEFAULT_ICON icon) const return 0; } + //! Sets a default icon void GUISkin::setIcon(EGUI_DEFAULT_ICON icon, u32 index) { @@ -266,9 +281,10 @@ void GUISkin::setIcon(EGUI_DEFAULT_ICON icon, u32 index) Icons[icon] = index; } + //! Returns a default text. For example for Message box button captions: //! "OK", "Cancel", "Yes", "No" and so on. -const wchar_t *GUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const +const wchar_t* GUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const { if ((u32)text < EGDT_COUNT) return Texts[text].c_str(); @@ -276,14 +292,16 @@ const wchar_t *GUISkin::getDefaultText(EGUI_DEFAULT_TEXT text) const return Texts[0].c_str(); } + //! Sets a default text. For example for Message box button captions: //! "OK", "Cancel", "Yes", "No" and so on. -void GUISkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t *newText) +void GUISkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText) { if ((u32)which < EGDT_COUNT) Texts[which] = newText; } + //! draws a standard 3d button pane /** Used for drawing for example buttons in normal state. It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and @@ -294,9 +312,10 @@ EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. is usually not used by ISkin, but can be used for example by more complex implementations to find out how to draw the part exactly. */ // PATCH -void GUISkin::drawColored3DButtonPaneStandard(IGUIElement *element, - const core::rect &r, const core::rect *clip, - const video::SColor *colors) +void GUISkin::drawColored3DButtonPaneStandard(IGUIElement* element, + const core::rect& r, + const core::rect* clip, + const video::SColor* colors) { if (!Driver) return; @@ -306,14 +325,15 @@ void GUISkin::drawColored3DButtonPaneStandard(IGUIElement *element, core::rect rect = r; - if (Type == EGST_BURNING_SKIN) { + if ( Type == EGST_BURNING_SKIN ) + { rect.UpperLeftCorner.X -= 1; rect.UpperLeftCorner.Y -= 1; rect.LowerRightCorner.X += 1; rect.LowerRightCorner.Y += 1; draw3DSunkenPane(element, - colors[EGDC_WINDOW].getInterpolated(0xFFFFFFFF, 0.9f), - false, true, rect, clip); + colors[ EGDC_WINDOW ].getInterpolated( 0xFFFFFFFF, 0.9f ) + ,false, true, rect, clip); return; } @@ -330,17 +350,20 @@ void GUISkin::drawColored3DButtonPaneStandard(IGUIElement *element, rect.LowerRightCorner.X -= 1; rect.LowerRightCorner.Y -= 1; - if (!UseGradient) { + if (!UseGradient) + { Driver->draw2DRectangle(colors[EGDC_3D_FACE], rect, clip); - } else { + } + else + { const video::SColor c1 = colors[EGDC_3D_FACE]; - const video::SColor c2 = - c1.getInterpolated(colors[EGDC_3D_DARK_SHADOW], 0.4f); + const video::SColor c2 = c1.getInterpolated(colors[EGDC_3D_DARK_SHADOW], 0.4f); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); } } // END PATCH + //! draws a pressed 3d button pane /** Used for drawing for example buttons in pressed state. It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and @@ -351,9 +374,10 @@ EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. is usually not used by ISkin, but can be used for example by more complex implementations to find out how to draw the part exactly. */ // PATCH -void GUISkin::drawColored3DButtonPanePressed(IGUIElement *element, - const core::rect &r, const core::rect *clip, - const video::SColor *colors) +void GUISkin::drawColored3DButtonPanePressed(IGUIElement* element, + const core::rect& r, + const core::rect* clip, + const video::SColor* colors) { if (!Driver) return; @@ -375,17 +399,20 @@ void GUISkin::drawColored3DButtonPanePressed(IGUIElement *element, rect.UpperLeftCorner.X += 1; rect.UpperLeftCorner.Y += 1; - if (!UseGradient) { + if (!UseGradient) + { Driver->draw2DRectangle(colors[EGDC_3D_FACE], rect, clip); - } else { + } + else + { const video::SColor c1 = colors[EGDC_3D_FACE]; - const video::SColor c2 = - c1.getInterpolated(colors[EGDC_3D_DARK_SHADOW], 0.4f); + const video::SColor c2 = c1.getInterpolated(colors[EGDC_3D_DARK_SHADOW], 0.4f); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); } } // END PATCH + //! draws a sunken 3d pane /** Used for drawing the background of edit, combo or check boxes. \param element: Pointer to the element which wishes to draw this. This parameter @@ -397,9 +424,11 @@ deep into the ground. \param rect: Defining area where to draw. \param clip: Clip area. */ // PATCH -void GUISkin::drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolor, - bool flat, bool fillBackGround, const core::rect &r, - const core::rect *clip, const video::SColor *colors) +void GUISkin::drawColored3DSunkenPane(IGUIElement* element, video::SColor bgcolor, + bool flat, bool fillBackGround, + const core::rect& r, + const core::rect* clip, + const video::SColor* colors) { if (!Driver) return; @@ -412,31 +441,34 @@ void GUISkin::drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolo if (fillBackGround) Driver->draw2DRectangle(bgcolor, rect, clip); - if (flat) { + if (flat) + { // draw flat sunken pane rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1; - Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // top + Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // top ++rect.UpperLeftCorner.Y; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1; - Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // left + Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // left rect = r; ++rect.UpperLeftCorner.Y; rect.UpperLeftCorner.X = rect.LowerRightCorner.X - 1; - Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // right + Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // right rect = r; ++rect.UpperLeftCorner.X; rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1; --rect.LowerRightCorner.X; - Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // bottom - } else { + Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // bottom + } + else + { // draw deep sunken pane rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1; - Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // top + Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // top ++rect.UpperLeftCorner.X; ++rect.UpperLeftCorner.Y; --rect.LowerRightCorner.X; @@ -444,10 +476,10 @@ void GUISkin::drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolo Driver->draw2DRectangle(colors[EGDC_3D_DARK_SHADOW], rect, clip); rect.UpperLeftCorner.X = r.UpperLeftCorner.X; - rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y + 1; + rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y+1; rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; - Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // left + Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); // left ++rect.UpperLeftCorner.X; ++rect.UpperLeftCorner.Y; ++rect.LowerRightCorner.X; @@ -457,7 +489,7 @@ void GUISkin::drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolo rect = r; rect.UpperLeftCorner.X = rect.LowerRightCorner.X - 1; ++rect.UpperLeftCorner.Y; - Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // right + Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // right --rect.UpperLeftCorner.X; ++rect.UpperLeftCorner.Y; --rect.LowerRightCorner.X; @@ -468,7 +500,7 @@ void GUISkin::drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolo ++rect.UpperLeftCorner.X; rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1; --rect.LowerRightCorner.X; - Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // bottom + Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); // bottom ++rect.UpperLeftCorner.X; --rect.UpperLeftCorner.Y; --rect.LowerRightCorner.X; @@ -481,13 +513,17 @@ void GUISkin::drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolo //! draws a window background // return where to draw title bar text. // PATCH -core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, - bool drawTitleBar, video::SColor titleBarColor, const core::rect &r, - const core::rect *clip, core::rect *checkClientArea, - const video::SColor *colors) +core::rect GUISkin::drawColored3DWindowBackground(IGUIElement* element, + bool drawTitleBar, video::SColor titleBarColor, + const core::rect& r, + const core::rect* clip, + core::rect* checkClientArea, + const video::SColor* colors) { - if (!Driver) { - if (checkClientArea) { + if (!Driver) + { + if ( checkClientArea ) + { *checkClientArea = r; } return r; @@ -500,14 +536,16 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, // top border rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 1; - if (!checkClientArea) { + if ( !checkClientArea ) + { Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); } // left border rect.LowerRightCorner.Y = r.LowerRightCorner.Y; rect.LowerRightCorner.X = rect.UpperLeftCorner.X + 1; - if (!checkClientArea) { + if ( !checkClientArea ) + { Driver->draw2DRectangle(colors[EGDC_3D_HIGH_LIGHT], rect, clip); } @@ -516,7 +554,8 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, rect.LowerRightCorner.X = r.LowerRightCorner.X; rect.UpperLeftCorner.Y = r.UpperLeftCorner.Y; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; - if (!checkClientArea) { + if ( !checkClientArea ) + { Driver->draw2DRectangle(colors[EGDC_3D_DARK_SHADOW], rect, clip); } @@ -525,7 +564,8 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, rect.LowerRightCorner.X -= 1; rect.UpperLeftCorner.Y += 1; rect.LowerRightCorner.Y -= 1; - if (!checkClientArea) { + if ( !checkClientArea ) + { Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); } @@ -534,7 +574,8 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, rect.UpperLeftCorner.Y = r.LowerRightCorner.Y - 1; rect.LowerRightCorner.Y = r.LowerRightCorner.Y; rect.LowerRightCorner.X = r.LowerRightCorner.X; - if (!checkClientArea) { + if ( !checkClientArea ) + { Driver->draw2DRectangle(colors[EGDC_3D_DARK_SHADOW], rect, clip); } @@ -543,31 +584,37 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, rect.LowerRightCorner.X -= 1; rect.UpperLeftCorner.Y -= 1; rect.LowerRightCorner.Y -= 1; - if (!checkClientArea) { + if ( !checkClientArea ) + { Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); } // client area for background rect = r; - rect.UpperLeftCorner.X += 1; - rect.UpperLeftCorner.Y += 1; + rect.UpperLeftCorner.X +=1; + rect.UpperLeftCorner.Y +=1; rect.LowerRightCorner.X -= 2; rect.LowerRightCorner.Y -= 2; - if (checkClientArea) { + if (checkClientArea) + { *checkClientArea = rect; } - if (!checkClientArea) { - if (!UseGradient) { + if ( !checkClientArea ) + { + if (!UseGradient) + { Driver->draw2DRectangle(colors[EGDC_3D_FACE], rect, clip); - } else if (Type == EGST_BURNING_SKIN) { - const video::SColor c1 = colors[EGDC_WINDOW].getInterpolated( - 0xFFFFFFFF, 0.9f); - const video::SColor c2 = colors[EGDC_WINDOW].getInterpolated( - 0xFFFFFFFF, 0.8f); + } + else if ( Type == EGST_BURNING_SKIN ) + { + const video::SColor c1 = colors[EGDC_WINDOW].getInterpolated ( 0xFFFFFFFF, 0.9f ); + const video::SColor c2 = colors[EGDC_WINDOW].getInterpolated ( 0xFFFFFFFF, 0.8f ); Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); - } else { + } + else + { const video::SColor c2 = colors[EGDC_3D_SHADOW]; const video::SColor c1 = colors[EGDC_3D_FACE]; Driver->draw2DRectangle(rect, c1, c1, c1, c2, clip); @@ -579,31 +626,29 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, rect.UpperLeftCorner.X += 2; rect.UpperLeftCorner.Y += 2; rect.LowerRightCorner.X -= 2; - rect.LowerRightCorner.Y = - rect.UpperLeftCorner.Y + getSize(EGDS_WINDOW_BUTTON_WIDTH) + 2; + rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + getSize(EGDS_WINDOW_BUTTON_WIDTH) + 2; - if (drawTitleBar) { - if (checkClientArea) { + if (drawTitleBar ) + { + if (checkClientArea) + { (*checkClientArea).UpperLeftCorner.Y = rect.LowerRightCorner.Y; - } else { + } + else + { // draw title bar - // if (!UseGradient) + //if (!UseGradient) // Driver->draw2DRectangle(titleBarColor, rect, clip); - // else - if (Type == EGST_BURNING_SKIN) { - const video::SColor c = titleBarColor.getInterpolated( - video::SColor(titleBarColor.getAlpha(), - 255, 255, 255), - 0.8f); - Driver->draw2DRectangle(rect, titleBarColor, - titleBarColor, c, c, clip); - } else { - const video::SColor c = titleBarColor.getInterpolated( - video::SColor(titleBarColor.getAlpha(), 0, - 0, 0), - 0.2f); - Driver->draw2DRectangle(rect, titleBarColor, c, - titleBarColor, c, clip); + //else + if ( Type == EGST_BURNING_SKIN ) + { + const video::SColor c = titleBarColor.getInterpolated( video::SColor(titleBarColor.getAlpha(),255,255,255), 0.8f); + Driver->draw2DRectangle(rect, titleBarColor, titleBarColor, c, c, clip); + } + else + { + const video::SColor c = titleBarColor.getInterpolated(video::SColor(titleBarColor.getAlpha(),0,0,0), 0.2f); + Driver->draw2DRectangle(rect, titleBarColor, c, titleBarColor, c, clip); } } } @@ -612,6 +657,7 @@ core::rect GUISkin::drawColored3DWindowBackground(IGUIElement *element, } // END PATCH + //! draws a standard 3d menu pane /** Used for drawing for menus and context menus. It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and @@ -622,8 +668,9 @@ implementations to find out how to draw the part exactly. \param rect: Defining area where to draw. \param clip: Clip area. */ // PATCH -void GUISkin::drawColored3DMenuPane(IGUIElement *element, const core::rect &r, - const core::rect *clip, const video::SColor *colors) +void GUISkin::drawColored3DMenuPane(IGUIElement* element, + const core::rect& r, const core::rect* clip, + const video::SColor* colors) { if (!Driver) return; @@ -633,7 +680,8 @@ void GUISkin::drawColored3DMenuPane(IGUIElement *element, const core::rect core::rect rect = r; - if (Type == EGST_BURNING_SKIN) { + if ( Type == EGST_BURNING_SKIN ) + { rect.UpperLeftCorner.Y -= 3; draw3DButtonPaneStandard(element, rect, clip); return; @@ -679,14 +727,15 @@ void GUISkin::drawColored3DMenuPane(IGUIElement *element, const core::rect Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], rect, clip); rect = r; - rect.UpperLeftCorner.X += 1; - rect.UpperLeftCorner.Y += 1; + rect.UpperLeftCorner.X +=1; + rect.UpperLeftCorner.Y +=1; rect.LowerRightCorner.X -= 2; rect.LowerRightCorner.Y -= 2; if (!UseGradient) Driver->draw2DRectangle(colors[EGDC_3D_FACE], rect, clip); - else { + else + { const video::SColor c1 = colors[EGDC_3D_FACE]; const video::SColor c2 = colors[EGDC_3D_SHADOW]; Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); @@ -694,6 +743,7 @@ void GUISkin::drawColored3DMenuPane(IGUIElement *element, const core::rect } // END PATCH + //! draws a standard 3d tool bar /** Used for drawing for toolbars and menus. \param element: Pointer to the element which wishes to draw this. This parameter @@ -702,8 +752,10 @@ implementations to find out how to draw the part exactly. \param rect: Defining area where to draw. \param clip: Clip area. */ // PATCH -void GUISkin::drawColored3DToolBar(IGUIElement *element, const core::rect &r, - const core::rect *clip, const video::SColor *colors) +void GUISkin::drawColored3DToolBar(IGUIElement* element, + const core::rect& r, + const core::rect* clip, + const video::SColor* colors) { if (!Driver) return; @@ -722,15 +774,21 @@ void GUISkin::drawColored3DToolBar(IGUIElement *element, const core::rect & rect = r; rect.LowerRightCorner.Y -= 1; - if (!UseGradient) { + if (!UseGradient) + { Driver->draw2DRectangle(colors[EGDC_3D_FACE], rect, clip); - } else if (Type == EGST_BURNING_SKIN) { + } + else + if ( Type == EGST_BURNING_SKIN ) + { const video::SColor c1 = 0xF0000000 | colors[EGDC_3D_FACE].color; const video::SColor c2 = 0xF0000000 | colors[EGDC_3D_SHADOW].color; rect.LowerRightCorner.Y += 1; Driver->draw2DRectangle(rect, c1, c2, c1, c2, clip); - } else { + } + else + { const video::SColor c1 = colors[EGDC_3D_FACE]; const video::SColor c2 = colors[EGDC_3D_SHADOW]; Driver->draw2DRectangle(rect, c1, c1, c2, c2, clip); @@ -747,9 +805,9 @@ implementations to find out how to draw the part exactly. \param rect: Defining area where to draw. \param clip: Clip area. */ // PATCH -void GUISkin::drawColored3DTabButton(IGUIElement *element, bool active, - const core::rect &frameRect, const core::rect *clip, - EGUI_ALIGNMENT alignment, const video::SColor *colors) +void GUISkin::drawColored3DTabButton(IGUIElement* element, bool active, + const core::rect& frameRect, const core::rect* clip, EGUI_ALIGNMENT alignment, + const video::SColor* colors) { if (!Driver) return; @@ -759,7 +817,8 @@ void GUISkin::drawColored3DTabButton(IGUIElement *element, bool active, core::rect tr = frameRect; - if (alignment == EGUIA_UPPERLEFT) { + if ( alignment == EGUIA_UPPERLEFT ) + { tr.LowerRightCorner.X -= 2; tr.LowerRightCorner.Y = tr.UpperLeftCorner.Y + 1; tr.UpperLeftCorner.X += 1; @@ -787,7 +846,9 @@ void GUISkin::drawColored3DTabButton(IGUIElement *element, bool active, tr.UpperLeftCorner.X += 1; tr.UpperLeftCorner.Y += 1; Driver->draw2DRectangle(colors[EGDC_3D_DARK_SHADOW], tr, clip); - } else { + } + else + { tr.LowerRightCorner.X -= 2; tr.UpperLeftCorner.Y = tr.LowerRightCorner.Y - 1; tr.UpperLeftCorner.X += 1; @@ -810,7 +871,7 @@ void GUISkin::drawColored3DTabButton(IGUIElement *element, bool active, // draw right middle gray shadow tr.LowerRightCorner.X += 1; tr.UpperLeftCorner.X = tr.LowerRightCorner.X - 1; - // tr.LowerRightCorner.Y -= 1; + //tr.LowerRightCorner.Y -= 1; Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], tr, clip); tr.LowerRightCorner.X += 1; @@ -821,6 +882,7 @@ void GUISkin::drawColored3DTabButton(IGUIElement *element, bool active, } // END PATCH + //! draws a tab control body /** \param element: Pointer to the element which wishes to draw this. This parameter is usually not used by ISkin, but can be used for example by more complex @@ -830,9 +892,9 @@ implementations to find out how to draw the part exactly. \param rect: Defining area where to draw. \param clip: Clip area. */ // PATCH -void GUISkin::drawColored3DTabBody(IGUIElement *element, bool border, bool background, - const core::rect &rect, const core::rect *clip, s32 tabHeight, - EGUI_ALIGNMENT alignment, const video::SColor *colors) +void GUISkin::drawColored3DTabBody(IGUIElement* element, bool border, bool background, + const core::rect& rect, const core::rect* clip, s32 tabHeight, EGUI_ALIGNMENT alignment, + const video::SColor* colors) { if (!Driver) return; @@ -842,12 +904,14 @@ void GUISkin::drawColored3DTabBody(IGUIElement *element, bool border, bool backg core::rect tr = rect; - if (tabHeight == -1) + if ( tabHeight == -1 ) tabHeight = getSize(gui::EGDS_BUTTON_HEIGHT); // draw border. - if (border) { - if (alignment == EGUIA_UPPERLEFT) { + if (border) + { + if ( alignment == EGUIA_UPPERLEFT ) + { // draw left hightlight tr.UpperLeftCorner.Y += tabHeight + 2; tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1; @@ -862,7 +926,9 @@ void GUISkin::drawColored3DTabBody(IGUIElement *element, bool border, bool backg tr = rect; tr.UpperLeftCorner.Y = tr.LowerRightCorner.Y - 1; Driver->draw2DRectangle(colors[EGDC_3D_SHADOW], tr, clip); - } else { + } + else + { // draw left hightlight tr.LowerRightCorner.Y -= tabHeight + 2; tr.LowerRightCorner.X = tr.UpperLeftCorner.X + 1; @@ -880,25 +946,30 @@ void GUISkin::drawColored3DTabBody(IGUIElement *element, bool border, bool backg } } - if (background) { - if (alignment == EGUIA_UPPERLEFT) { + if (background) + { + if ( alignment == EGUIA_UPPERLEFT ) + { tr = rect; tr.UpperLeftCorner.Y += tabHeight + 2; tr.LowerRightCorner.X -= 1; tr.UpperLeftCorner.X += 1; tr.LowerRightCorner.Y -= 1; - } else { + } + else + { tr = rect; tr.UpperLeftCorner.X += 1; tr.UpperLeftCorner.Y -= 1; tr.LowerRightCorner.X -= 1; tr.LowerRightCorner.Y -= tabHeight + 2; - // tr.UpperLeftCorner.X += 1; + //tr.UpperLeftCorner.X += 1; } if (!UseGradient) Driver->draw2DRectangle(colors[EGDC_3D_FACE], tr, clip); - else { + else + { video::SColor c1 = colors[EGDC_3D_FACE]; video::SColor c2 = colors[EGDC_3D_SHADOW]; Driver->draw2DRectangle(tr, c1, c1, c2, c2, clip); @@ -907,6 +978,7 @@ void GUISkin::drawColored3DTabBody(IGUIElement *element, bool border, bool backg } // END PATCH + //! draws an icon, usually from the skin's sprite bank /** \param parent: Pointer to the element which wishes to draw this icon. This parameter is usually not used by IGUISkin, but can be used for example @@ -918,9 +990,11 @@ by more complex implementations to find out how to draw the part exactly. \param loop: Whether the animation should loop or not \param clip: Clip area. */ // PATCH -void GUISkin::drawColoredIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, - const core::position2di position, u32 starttime, u32 currenttime, - bool loop, const core::rect *clip, const video::SColor *colors) +void GUISkin::drawColoredIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, + const core::position2di position, + u32 starttime, u32 currenttime, + bool loop, const core::rect* clip, + const video::SColor* colors) { if (!SpriteBank) return; @@ -930,71 +1004,74 @@ void GUISkin::drawColoredIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, bool gray = element && !element->isEnabled(); SpriteBank->draw2DSprite(Icons[icon], position, clip, - colors[gray ? EGDC_GRAY_WINDOW_SYMBOL : EGDC_WINDOW_SYMBOL], - starttime, currenttime, loop, true); + colors[gray? EGDC_GRAY_WINDOW_SYMBOL : EGDC_WINDOW_SYMBOL], starttime, currenttime, loop, true); } // END PATCH + EGUI_SKIN_TYPE GUISkin::getType() const { return Type; } + //! draws a 2d rectangle. -void GUISkin::draw2DRectangle(IGUIElement *element, const video::SColor &color, - const core::rect &pos, const core::rect *clip) +void GUISkin::draw2DRectangle(IGUIElement* element, + const video::SColor &color, const core::rect& pos, + const core::rect* clip) { Driver->draw2DRectangle(color, pos, clip); } + //! Writes attributes of the object. //! Implement this to expose the attributes of your scene node animator for //! scripting languages, editors, debuggers or xml serialization purposes. -void GUISkin::serializeAttributes( - io::IAttributes *out, io::SAttributeReadWriteOptions *options) const +void GUISkin::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const { u32 i; - for (i = 0; i < EGDC_COUNT; ++i) + for (i=0; iaddColor(GUISkinColorNames[i], Colors[i]); - for (i = 0; i < EGDS_COUNT; ++i) + for (i=0; iaddInt(GUISkinSizeNames[i], Sizes[i]); - for (i = 0; i < EGDT_COUNT; ++i) + for (i=0; iaddString(GUISkinTextNames[i], Texts[i].c_str()); - for (i = 0; i < EGDI_COUNT; ++i) + for (i=0; iaddInt(GUISkinIconNames[i], Icons[i]); } + //! Reads attributes of the object. //! Implement this to set the attributes of your scene node animator for //! scripting languages, editors, debuggers or xml deserialization purposes. -void GUISkin::deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options) +void GUISkin::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options) { - // TODO: This is not nice code for downward compatibility, whenever new values are - // added and users load an old skin the corresponding values will be set to 0. + // TODO: This is not nice code for downward compatibility, whenever new values are added and users + // load an old skin the corresponding values will be set to 0. u32 i; - for (i = 0; i < EGDC_COUNT; ++i) + for (i=0; igetAttributeAsColor(GUISkinColorNames[i]); - for (i = 0; i < EGDS_COUNT; ++i) + for (i=0; igetAttributeAsInt(GUISkinSizeNames[i]); - for (i = 0; i < EGDT_COUNT; ++i) + for (i=0; igetAttributeAsStringW(GUISkinTextNames[i]); - for (i = 0; i < EGDI_COUNT; ++i) + for (i=0; igetAttributeAsInt(GUISkinIconNames[i]); } + //! gets the colors // PATCH -void GUISkin::getColors(video::SColor *colors) +void GUISkin::getColors(video::SColor* colors) { u32 i; - for (i = 0; i < EGDC_COUNT; ++i) + for (i=0; i &rect, const core::rect *clip = 0) - { - drawColored3DButtonPaneStandard(element, rect, clip); - } - - virtual void drawColored3DButtonPaneStandard(IGUIElement *element, - const core::rect &rect, const core::rect *clip = 0, - const video::SColor *colors = 0); - - //! draws a pressed 3d button pane - /** Used for drawing for example buttons in pressed state. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. */ - virtual void draw3DButtonPanePressed(IGUIElement *element, - const core::rect &rect, const core::rect *clip = 0) - { - drawColored3DButtonPanePressed(element, rect, clip); - } - - virtual void drawColored3DButtonPanePressed(IGUIElement *element, - const core::rect &rect, const core::rect *clip = 0, - const video::SColor *colors = 0); - - //! draws a sunken 3d pane - /** Used for drawing the background of edit, combo or check boxes. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param bgcolor: Background color. - \param flat: Specifies if the sunken pane should be flat or displayed as sunken - deep into the ground. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DSunkenPane(IGUIElement *element, video::SColor bgcolor, - bool flat, bool fillBackGround, const core::rect &rect, - const core::rect *clip = 0) - { - drawColored3DSunkenPane( - element, bgcolor, flat, fillBackGround, rect, clip); - } - - virtual void drawColored3DSunkenPane(IGUIElement *element, video::SColor bgcolor, - bool flat, bool fillBackGround, const core::rect &rect, - const core::rect *clip = 0, const video::SColor *colors = 0); - - //! draws a window background - /** Used for drawing the background of dialogs and windows. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param titleBarColor: Title color. - \param drawTitleBar: True to enable title drawing. - \param rect: Defining area where to draw. - \param clip: Clip area. - \param checkClientArea: When set to non-null the function will not draw anything, - but will instead return the clientArea which can be used for drawing by the - calling window. That is the area without borders and without titlebar. \return - Returns rect where it would be good to draw title bar text. This will work even - when checkClientArea is set to a non-null value.*/ - virtual core::rect draw3DWindowBackground(IGUIElement *element, - bool drawTitleBar, video::SColor titleBarColor, - const core::rect &rect, const core::rect *clip, - core::rect *checkClientArea) + class GUISkin : public IGUISkin { - return drawColored3DWindowBackground(element, drawTitleBar, titleBarColor, + public: + + GUISkin(EGUI_SKIN_TYPE type, video::IVideoDriver* driver); + + //! destructor + virtual ~GUISkin(); + + //! returns default color + virtual video::SColor getColor(EGUI_DEFAULT_COLOR color) const; + + //! sets a default color + virtual void setColor(EGUI_DEFAULT_COLOR which, video::SColor newColor); + + //! returns size for the given size type + virtual s32 getSize(EGUI_DEFAULT_SIZE size) const; + + //! sets a default size + virtual void setSize(EGUI_DEFAULT_SIZE which, s32 size); + + //! returns the default font + virtual IGUIFont* getFont(EGUI_DEFAULT_FONT which=EGDF_DEFAULT) const; + + //! sets a default font + virtual void setFont(IGUIFont* font, EGUI_DEFAULT_FONT which=EGDF_DEFAULT); + + //! sets the sprite bank used for drawing icons + virtual void setSpriteBank(IGUISpriteBank* bank); + + //! gets the sprite bank used for drawing icons + virtual IGUISpriteBank* getSpriteBank() const; + + //! Returns a default icon + /** Returns the sprite index within the sprite bank */ + virtual u32 getIcon(EGUI_DEFAULT_ICON icon) const; + + //! Sets a default icon + /** Sets the sprite index used for drawing icons like arrows, + close buttons and ticks in checkboxes + \param icon: Enum specifying which icon to change + \param index: The sprite index used to draw this icon */ + virtual void setIcon(EGUI_DEFAULT_ICON icon, u32 index); + + //! Returns a default text. + /** For example for Message box button captions: + "OK", "Cancel", "Yes", "No" and so on. */ + virtual const wchar_t* getDefaultText(EGUI_DEFAULT_TEXT text) const; + + //! Sets a default text. + /** For example for Message box button captions: + "OK", "Cancel", "Yes", "No" and so on. */ + virtual void setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText); + + //! draws a standard 3d button pane + /** Used for drawing for example buttons in normal state. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. */ + virtual void draw3DButtonPaneStandard(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0) + { + drawColored3DButtonPaneStandard(element, rect,clip); + } + + virtual void drawColored3DButtonPaneStandard(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0, + const video::SColor* colors=0); + + //! draws a pressed 3d button pane + /** Used for drawing for example buttons in pressed state. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. */ + virtual void draw3DButtonPanePressed(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0) + { + drawColored3DButtonPanePressed(element, rect, clip); + } + + virtual void drawColored3DButtonPanePressed(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0, + const video::SColor* colors=0); + + //! draws a sunken 3d pane + /** Used for drawing the background of edit, combo or check boxes. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param bgcolor: Background color. + \param flat: Specifies if the sunken pane should be flat or displayed as sunken + deep into the ground. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DSunkenPane(IGUIElement* element, + video::SColor bgcolor, bool flat, + bool fillBackGround, + const core::rect& rect, + const core::rect* clip=0) + { + drawColored3DSunkenPane(element, bgcolor, flat, fillBackGround, rect, clip); + } + + virtual void drawColored3DSunkenPane(IGUIElement* element, + video::SColor bgcolor, bool flat, + bool fillBackGround, + const core::rect& rect, + const core::rect* clip=0, + const video::SColor* colors=0); + + //! draws a window background + /** Used for drawing the background of dialogs and windows. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param titleBarColor: Title color. + \param drawTitleBar: True to enable title drawing. + \param rect: Defining area where to draw. + \param clip: Clip area. + \param checkClientArea: When set to non-null the function will not draw anything, + but will instead return the clientArea which can be used for drawing by the calling window. + That is the area without borders and without titlebar. + \return Returns rect where it would be good to draw title bar text. This will + work even when checkClientArea is set to a non-null value.*/ + virtual core::rect draw3DWindowBackground(IGUIElement* element, + bool drawTitleBar, video::SColor titleBarColor, + const core::rect& rect, + const core::rect* clip, + core::rect* checkClientArea) + { + return drawColored3DWindowBackground(element, drawTitleBar, titleBarColor, rect, clip, checkClientArea); - } - - virtual core::rect drawColored3DWindowBackground(IGUIElement *element, - bool drawTitleBar, video::SColor titleBarColor, - const core::rect &rect, const core::rect *clip, - core::rect *checkClientArea, - const video::SColor *colors = 0); - - //! draws a standard 3d menu pane - /** Used for drawing for menus and context menus. - It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and - EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DMenuPane(IGUIElement *element, const core::rect &rect, - const core::rect *clip = 0) - { - drawColored3DMenuPane(element, rect, clip); - } - - virtual void drawColored3DMenuPane(IGUIElement *element, - const core::rect &rect, const core::rect *clip = 0, - const video::SColor *colors = 0); - - //! draws a standard 3d tool bar - /** Used for drawing for toolbars and menus. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DToolBar(IGUIElement *element, const core::rect &rect, - const core::rect *clip = 0) - { - drawColored3DToolBar(element, rect, clip); - } - - virtual void drawColored3DToolBar(IGUIElement *element, - const core::rect &rect, const core::rect *clip = 0, - const video::SColor *colors = 0); - - //! draws a tab button - /** Used for drawing for tab buttons on top of tabs. - \param element: Pointer to the element which wishes to draw this. This parameter - is usually not used by ISkin, but can be used for example by more complex - implementations to find out how to draw the part exactly. - \param active: Specifies if the tab is currently active. - \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DTabButton(IGUIElement *element, bool active, - const core::rect &rect, const core::rect *clip = 0, - EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT) - { - drawColored3DTabButton(element, active, rect, clip, alignment); - } - - virtual void drawColored3DTabButton(IGUIElement *element, bool active, - const core::rect &rect, const core::rect *clip = 0, - EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT, - const video::SColor *colors = 0); - - //! draws a tab control body - /** \param element: Pointer to the element which wishes to draw this. This - parameter is usually not used by ISkin, but can be used for example by more - complex implementations to find out how to draw the part exactly. \param border: - Specifies if the border should be drawn. \param background: Specifies if the - background should be drawn. \param rect: Defining area where to draw. - \param clip: Clip area. */ - virtual void draw3DTabBody(IGUIElement *element, bool border, bool background, - const core::rect &rect, const core::rect *clip = 0, - s32 tabHeight = -1, EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT) - { - drawColored3DTabBody(element, border, background, rect, clip, tabHeight, - alignment); - } - - virtual void drawColored3DTabBody(IGUIElement *element, bool border, - bool background, const core::rect &rect, - const core::rect *clip = 0, s32 tabHeight = -1, - EGUI_ALIGNMENT alignment = EGUIA_UPPERLEFT, - const video::SColor *colors = 0); - - //! draws an icon, usually from the skin's sprite bank - /** \param element: Pointer to the element which wishes to draw this icon. - This parameter is usually not used by IGUISkin, but can be used for example - by more complex implementations to find out how to draw the part exactly. - \param icon: Specifies the icon to be drawn. - \param position: The position to draw the icon - \param starttime: The time at the start of the animation - \param currenttime: The present time, used to calculate the frame number - \param loop: Whether the animation should loop or not - \param clip: Clip area. */ - virtual void drawIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, - const core::position2di position, u32 starttime = 0, - u32 currenttime = 0, bool loop = false, - const core::rect *clip = 0) - { - drawColoredIcon(element, icon, position, starttime, currenttime, loop, - clip); - } - - virtual void drawColoredIcon(IGUIElement *element, EGUI_DEFAULT_ICON icon, - const core::position2di position, u32 starttime = 0, - u32 currenttime = 0, bool loop = false, - const core::rect *clip = 0, const video::SColor *colors = 0); - - //! draws a 2d rectangle. - /** \param element: Pointer to the element which wishes to draw this icon. - This parameter is usually not used by IGUISkin, but can be used for example - by more complex implementations to find out how to draw the part exactly. - \param color: Color of the rectangle to draw. The alpha component specifies how - transparent the rectangle will be. - \param pos: Position of the rectangle. - \param clip: Pointer to rectangle against which the rectangle will be clipped. - If the pointer is null, no clipping will be performed. */ - virtual void draw2DRectangle(IGUIElement *element, const video::SColor &color, - const core::rect &pos, const core::rect *clip = 0); - - //! get the type of this skin - virtual EGUI_SKIN_TYPE getType() const; - - //! Writes attributes of the object. - //! Implement this to expose the attributes of your scene node animator for - //! scripting languages, editors, debuggers or xml serialization purposes. - virtual void serializeAttributes(io::IAttributes *out, - io::SAttributeReadWriteOptions *options = 0) const; - - //! Reads attributes of the object. - //! Implement this to set the attributes of your scene node animator for - //! scripting languages, editors, debuggers or xml deserialization purposes. - virtual void deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0); - - //! gets the colors - virtual void getColors(video::SColor *colors); // ::PATCH: - -private: - video::SColor Colors[EGDC_COUNT]; - s32 Sizes[EGDS_COUNT]; - u32 Icons[EGDI_COUNT]; - IGUIFont *Fonts[EGDF_COUNT]; - IGUISpriteBank *SpriteBank; - core::stringw Texts[EGDT_COUNT]; - video::IVideoDriver *Driver; - bool UseGradient; - - EGUI_SKIN_TYPE Type; -}; - -#define set3DSkinColors(skin, button_color) \ - { \ - skin->setColor(EGDC_3D_FACE, button_color); \ - skin->setColor(EGDC_3D_DARK_SHADOW, button_color, 0.25f); \ - skin->setColor(EGDC_3D_SHADOW, button_color, 0.5f); \ - skin->setColor(EGDC_3D_LIGHT, button_color); \ - skin->setColor(EGDC_3D_HIGH_LIGHT, button_color, 1.5f); \ - } - -#define getElementSkinColor(color) \ - { \ - if (!Colors) { \ - IGUISkin *skin = Environment->getSkin(); \ - if (skin) \ - return skin->getColor(color); \ - } \ - return Colors[color]; \ - } - -#define setElementSkinColor(which, newColor, shading) \ - { \ - if (!Colors) { \ - Colors = new video::SColor[EGDC_COUNT]; \ - GUISkin *skin = (GUISkin *)Environment->getSkin(); \ - if (skin) \ - skin->getColors(Colors); \ - } \ - Colors[which] = newColor; \ - setShading(Colors[which], shading); \ - } + } + + virtual core::rect drawColored3DWindowBackground(IGUIElement* element, + bool drawTitleBar, video::SColor titleBarColor, + const core::rect& rect, + const core::rect* clip, + core::rect* checkClientArea, + const video::SColor* colors=0); + + //! draws a standard 3d menu pane + /** Used for drawing for menus and context menus. + It uses the colors EGDC_3D_DARK_SHADOW, EGDC_3D_HIGH_LIGHT, EGDC_3D_SHADOW and + EGDC_3D_FACE for this. See EGUI_DEFAULT_COLOR for details. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DMenuPane(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0) + { + drawColored3DMenuPane(element, rect, clip); + } + + virtual void drawColored3DMenuPane(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0, + const video::SColor* colors=0); + + //! draws a standard 3d tool bar + /** Used for drawing for toolbars and menus. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DToolBar(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0) + { + drawColored3DToolBar(element, rect, clip); + } + + virtual void drawColored3DToolBar(IGUIElement* element, + const core::rect& rect, + const core::rect* clip=0, + const video::SColor* colors=0); + + //! draws a tab button + /** Used for drawing for tab buttons on top of tabs. + \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param active: Specifies if the tab is currently active. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DTabButton(IGUIElement* element, bool active, + const core::rect& rect, const core::rect* clip=0, EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT) + { + drawColored3DTabButton(element, active, rect, clip, alignment); + } + + virtual void drawColored3DTabButton(IGUIElement* element, bool active, + const core::rect& rect, const core::rect* clip=0, EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT, + const video::SColor* colors=0); + + //! draws a tab control body + /** \param element: Pointer to the element which wishes to draw this. This parameter + is usually not used by ISkin, but can be used for example by more complex + implementations to find out how to draw the part exactly. + \param border: Specifies if the border should be drawn. + \param background: Specifies if the background should be drawn. + \param rect: Defining area where to draw. + \param clip: Clip area. */ + virtual void draw3DTabBody(IGUIElement* element, bool border, bool background, + const core::rect& rect, const core::rect* clip=0, s32 tabHeight=-1, EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT) + { + drawColored3DTabBody(element, border, background, rect, clip, tabHeight, alignment); + } + + virtual void drawColored3DTabBody(IGUIElement* element, bool border, bool background, + const core::rect& rect, const core::rect* clip=0, s32 tabHeight=-1, EGUI_ALIGNMENT alignment=EGUIA_UPPERLEFT, + const video::SColor* colors=0); + + //! draws an icon, usually from the skin's sprite bank + /** \param element: Pointer to the element which wishes to draw this icon. + This parameter is usually not used by IGUISkin, but can be used for example + by more complex implementations to find out how to draw the part exactly. + \param icon: Specifies the icon to be drawn. + \param position: The position to draw the icon + \param starttime: The time at the start of the animation + \param currenttime: The present time, used to calculate the frame number + \param loop: Whether the animation should loop or not + \param clip: Clip area. */ + virtual void drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, + const core::position2di position, + u32 starttime=0, u32 currenttime=0, + bool loop=false, const core::rect* clip=0) + { + drawColoredIcon(element, icon, position, starttime, currenttime, loop, clip); + } + + virtual void drawColoredIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, + const core::position2di position, + u32 starttime=0, u32 currenttime=0, + bool loop=false, const core::rect* clip=0, + const video::SColor* colors=0); + + //! draws a 2d rectangle. + /** \param element: Pointer to the element which wishes to draw this icon. + This parameter is usually not used by IGUISkin, but can be used for example + by more complex implementations to find out how to draw the part exactly. + \param color: Color of the rectangle to draw. The alpha component specifies how + transparent the rectangle will be. + \param pos: Position of the rectangle. + \param clip: Pointer to rectangle against which the rectangle will be clipped. + If the pointer is null, no clipping will be performed. */ + virtual void draw2DRectangle(IGUIElement* element, const video::SColor &color, + const core::rect& pos, const core::rect* clip = 0); + + + //! get the type of this skin + virtual EGUI_SKIN_TYPE getType() const; + + //! Writes attributes of the object. + //! Implement this to expose the attributes of your scene node animator for + //! scripting languages, editors, debuggers or xml serialization purposes. + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const; + + //! Reads attributes of the object. + //! Implement this to set the attributes of your scene node animator for + //! scripting languages, editors, debuggers or xml deserialization purposes. + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0); + + //! gets the colors + virtual void getColors(video::SColor* colors); // ::PATCH: + + private: + + video::SColor Colors[EGDC_COUNT]; + s32 Sizes[EGDS_COUNT]; + u32 Icons[EGDI_COUNT]; + IGUIFont* Fonts[EGDF_COUNT]; + IGUISpriteBank* SpriteBank; + core::stringw Texts[EGDT_COUNT]; + video::IVideoDriver* Driver; + bool UseGradient; + + EGUI_SKIN_TYPE Type; + }; + + #define set3DSkinColors(skin, button_color) \ + { \ + skin->setColor(EGDC_3D_FACE, button_color); \ + skin->setColor(EGDC_3D_DARK_SHADOW, button_color, 0.25f); \ + skin->setColor(EGDC_3D_SHADOW, button_color, 0.5f); \ + skin->setColor(EGDC_3D_LIGHT, button_color); \ + skin->setColor(EGDC_3D_HIGH_LIGHT, button_color, 1.5f); \ + } + + #define getElementSkinColor(color) \ + { \ + if (!Colors) \ + { \ + IGUISkin* skin = Environment->getSkin(); \ + if (skin) \ + return skin->getColor(color); \ + } \ + return Colors[color]; \ + } + + #define setElementSkinColor(which, newColor, shading) \ + { \ + if (!Colors) \ + { \ + Colors = new video::SColor[EGDC_COUNT]; \ + GUISkin* skin = (GUISkin *)Environment->getSkin(); \ + if (skin) \ + skin->getColors(Colors); \ + } \ + Colors[which] = newColor; \ + setShading(Colors[which],shading); \ + } } // end namespace gui //! Sets the shading -inline void setShading(video::SColor &color, f32 s) // :PATCH: +inline void setShading(video::SColor &color,f32 s) // :PATCH: { - if (s < 1.0f) { + if (s < 1.0f) + { color.setRed(color.getRed() * s); color.setGreen(color.getGreen() * s); color.setBlue(color.getBlue() * s); - } else if (s > 1.0f) { + } + else if (s > 1.0f) + { s -= 1.0f; color.setRed(color.getRed() + (255 - color.getRed()) * s); @@ -355,6 +370,7 @@ inline void setShading(video::SColor &color, f32 s) // :PATCH: } } // end namespace irr + #endif // _IRR_COMPILE_WITH_GUI_ #endif diff --git a/src/gui/guiTable.cpp b/src/gui/guiTable.cpp index 2f761cc77..c705e17fb 100644 --- a/src/gui/guiTable.cpp +++ b/src/gui/guiTable.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "guiTable.h" #include #include @@ -32,22 +33,25 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/string.h" #include "util/numeric.h" #include "util/string.h" // for parseColorString() -#include "settings.h" // for settings -#include "porting.h" // for dpi +#include "settings.h" // for settings +#include "porting.h" // for dpi #include "client/guiscalingfilter.h" /* GUITable */ -GUITable::GUITable(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - core::rect rectangle, ISimpleTextureSource *tsrc) : - gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), - m_tsrc(tsrc) +GUITable::GUITable(gui::IGUIEnvironment *env, + gui::IGUIElement* parent, s32 id, + core::rect rectangle, + ISimpleTextureSource *tsrc +): + gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle), + m_tsrc(tsrc) { assert(tsrc != NULL); - gui::IGUISkin *skin = Environment->getSkin(); + gui::IGUISkin* skin = Environment->getSkin(); m_font = skin->getFont(); if (m_font) { @@ -58,7 +62,8 @@ GUITable::GUITable(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, const s32 s = skin->getSize(gui::EGDS_SCROLLBAR_SIZE); m_scrollbar = new GUIScrollBar(Environment, this, -1, - core::rect(RelativeRect.getWidth() - s, 0, + core::rect(RelativeRect.getWidth() - s, + 0, RelativeRect.getWidth(), RelativeRect.getHeight()), false, true); @@ -78,11 +83,11 @@ GUITable::GUITable(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, #endif core::rect relative_rect = m_scrollbar->getRelativePosition(); s32 width = (relative_rect.getWidth() / (2.0 / 3.0)) * density * - g_settings->getFloat("gui_scaling"); + g_settings->getFloat("gui_scaling"); m_scrollbar->setRelativePosition(core::rect( - relative_rect.LowerRightCorner.X - width, - relative_rect.UpperLeftCorner.Y, relative_rect.LowerRightCorner.X, - relative_rect.LowerRightCorner.Y)); + relative_rect.LowerRightCorner.X-width,relative_rect.UpperLeftCorner.Y, + relative_rect.LowerRightCorner.X,relative_rect.LowerRightCorner.Y + )); } GUITable::~GUITable() @@ -103,10 +108,12 @@ GUITable::Option GUITable::splitOption(const std::string &str) if (equal_pos == std::string::npos) return GUITable::Option(str, ""); - return GUITable::Option(str.substr(0, equal_pos), str.substr(equal_pos + 1)); + return GUITable::Option(str.substr(0, equal_pos), + str.substr(equal_pos + 1)); } -void GUITable::setTextList(const std::vector &content, bool transparent) +void GUITable::setTextList(const std::vector &content, + bool transparent) { clear(); @@ -120,7 +127,7 @@ void GUITable::setTextList(const std::vector &content, bool transpa s32 empty_string_index = allocString(""); m_rows.resize(content.size()); - for (s32 i = 0; i < (s32)content.size(); ++i) { + for (s32 i = 0; i < (s32) content.size(); ++i) { Row *row = &m_rows[i]; row->cells = new Cell[1]; row->cellcount = 1; @@ -130,7 +137,7 @@ void GUITable::setTextList(const std::vector &content, bool transpa Cell *cell = row->cells; cell->xmin = 0; - cell->xmax = 0x7fff; // something large enough + cell->xmax = 0x7fff; // something large enough cell->xpos = 6; cell->content_type = COLUMN_TYPE_TEXT; cell->content_index = empty_string_index; @@ -144,15 +151,19 @@ void GUITable::setTextList(const std::vector &content, bool transpa if (s[0] == '#' && s[1] == '#') { // double # to escape cell->content_index = allocString(s.substr(2)); - } else if (s[0] == '#' && s.size() >= 7 && - parseColorString(s.substr(0, 7), cell->color, false)) { + } + else if (s[0] == '#' && s.size() >= 7 && + parseColorString( + s.substr(0,7), cell->color, false)) { // single # for color cell->color_defined = true; cell->content_index = allocString(s.substr(7)); - } else { + } + else { // no #, just text cell->content_index = allocString(s); } + } allocationComplete(); @@ -161,7 +172,8 @@ void GUITable::setTextList(const std::vector &content, bool transpa updateScrollBar(); } -void GUITable::setTable(const TableOptions &options, const TableColumns &columns, +void GUITable::setTable(const TableOptions &options, + const TableColumns &columns, std::vector &content) { clear(); @@ -200,8 +212,8 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns else if (name == "opendepth") opendepth = stoi(value); else - errorstream << "Invalid table option: \"" << name << "\"" - << " (value=\"" << value << "\")" << std::endl; + errorstream<<"Invalid table option: \""<= 0); // Append empty strings to content if there is an incomplete row s32 cellcount = rowcount * colcount; - while (content.size() < (u32)cellcount) + while (content.size() < (u32) cellcount) content.emplace_back(""); // Create temporary rows (for processing columns) - struct TempRow - { + struct TempRow { // Current horizontal position (may different between rows due // to indent/tree columns, or text/image columns with width<0) s32 x; @@ -231,9 +242,9 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns // Vector of completed cells in this row std::vector cells; // Stores colors and how long they last (maximum column index) - std::vector> colors; + std::vector > colors; - TempRow() : x(0), indent(0), content_index(0), content_width(0) {} + TempRow(): x(0), indent(0), content_index(0), content_width(0) {} }; TempRow *rows = new TempRow[rowcount]; @@ -262,8 +273,8 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns else if (columns[j].type == "tree") columntype = COLUMN_TYPE_TREE; else - errorstream << "Invalid table column type: \"" << columns[j].type - << "\"" << std::endl; + errorstream<<"Invalid table column type: \"" + <colors.empty() && - row->colors.back().second < j) + while (!row->colors.empty() && row->colors.back().second < j) row->colors.pop_back(); } } @@ -326,20 +338,17 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns Cell newcell; newcell.content_type = columntype; newcell.tooltip_index = tooltip_index; - newcell.reported_column = j + 1; + newcell.reported_column = j+1; if (columntype == COLUMN_TYPE_TEXT) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; - row->content_index = - allocString(content[i * colcount + j]); + row->content_index = allocString(content[i * colcount + j]); const core::stringw &text = m_strings[row->content_index]; - row->content_width = - m_font ? m_font->getDimension(text.c_str()) - .Width - : 0; + row->content_width = m_font ? + m_font->getDimension(text.c_str()).Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); @@ -347,8 +356,7 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns // Add a new cell (of text type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; - alignContent(&newcell, xmax, rows[i].content_width, - align); + alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) @@ -356,7 +364,8 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } - } else if (columntype == COLUMN_TYPE_IMAGE) { + } + else if (columntype == COLUMN_TYPE_IMAGE) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { @@ -367,7 +376,7 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns // column options so check active_image_indices. s32 image_index = stoi(content[i * colcount + j]); std::map::iterator image_iter = - active_image_indices.find(image_index); + active_image_indices.find(image_index); if (image_iter != active_image_indices.end()) row->content_index = image_iter->second; @@ -377,9 +386,7 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns image = m_images[row->content_index]; // Get content width and update xmax - row->content_width = - image ? image->getOriginalSize().Width - : 0; + row->content_width = image ? image->getOriginalSize().Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); @@ -387,28 +394,27 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns // Add a new cell (of image type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; - alignContent(&newcell, xmax, rows[i].content_width, - align); + alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } active_image_indices.clear(); - } else if (columntype == COLUMN_TYPE_COLOR) { + } + else if (columntype == COLUMN_TYPE_COLOR) { for (s32 i = 0; i < rowcount; ++i) { video::SColor cellcolor(255, 255, 255, 255); - if (parseColorString(content[i * colcount + j], cellcolor, - true)) - rows[i].colors.emplace_back(cellcolor, j + span); + if (parseColorString(content[i * colcount + j], cellcolor, true)) + rows[i].colors.emplace_back(cellcolor, j+span); } - } else if (columntype == COLUMN_TYPE_INDENT || + } + else if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { // For column type "tree", reserve additional space for +/- // Also enable special processing for treeview-type tables s32 content_width = 0; if (columntype == COLUMN_TYPE_TREE) { - content_width = m_font ? m_font->getDimension(L"+").Width - : 0; + content_width = m_font ? m_font->getDimension(L"+").Width : 0; m_has_tree_column = true; } // Add a new cell (of indent or tree type) to each row @@ -440,7 +446,7 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns Row *row = &m_rows[i]; row->cellcount = rows[i].cells.size(); row->cells = new Cell[row->cellcount]; - memcpy((void *)row->cells, (void *)&rows[i].cells[0], + memcpy((void*) row->cells, (void*) &rows[i].cells[0], row->cellcount * sizeof(Cell)); row->indent = rows[i].indent; row->visible_index = i; @@ -451,12 +457,10 @@ void GUITable::setTable(const TableOptions &options, const TableColumns &columns if (m_has_tree_column) { // Treeview: convert tree to indent cells on leaf rows for (s32 i = 0; i < rowcount; ++i) { - if (i == rowcount - 1 || m_rows[i].indent >= m_rows[i + 1].indent) + if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent) for (s32 j = 0; j < m_rows[i].cellcount; ++j) - if (m_rows[i].cells[j].content_type == - COLUMN_TYPE_TREE) - m_rows[i].cells[j].content_type = - COLUMN_TYPE_INDENT; + if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE) + m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT; } // Treeview: close rows according to opendepth option @@ -485,9 +489,9 @@ void GUITable::clear() // Get colors from skin gui::IGUISkin *skin = Environment->getSkin(); - m_color = skin->getColor(gui::EGDC_BUTTON_TEXT); - m_background = skin->getColor(gui::EGDC_3D_HIGH_LIGHT); - m_highlight = skin->getColor(gui::EGDC_HIGH_LIGHT); + m_color = skin->getColor(gui::EGDC_BUTTON_TEXT); + m_background = skin->getColor(gui::EGDC_3D_HIGH_LIGHT); + m_highlight = skin->getColor(gui::EGDC_HIGH_LIGHT); m_highlight_text = skin->getColor(gui::EGDC_HIGH_LIGHT_TEXT); // Reset members @@ -516,14 +520,15 @@ std::string GUITable::checkEvent() std::ostringstream os(std::ios::binary); if (m_sel_doubleclick) { - os << "DCL:"; + os<<"DCL:"; m_sel_doubleclick = false; - } else { - os << "CHG:"; } - os << sel; + else { + os<<"CHG:"; + } + os<= 0 && m_selected < (s32)m_visible_rows.size()); + assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); return m_visible_rows[m_selected] + 1; } @@ -573,7 +578,7 @@ void GUITable::setSelected(s32 index) if (index >= 0) { m_selected = m_rows[index].visible_index; - assert(m_selected >= 0 && m_selected < (s32)m_visible_rows.size()); + assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); } if (m_selected != old_selected || selection_invisible) { @@ -608,7 +613,7 @@ void GUITable::setDynamicData(const DynamicData &dyndata) m_scrollbar->setPos(dyndata.scrollpos); } -const c8 *GUITable::getTypeName() const +const c8* GUITable::getTypeName() const { return "GUITable"; } @@ -630,11 +635,12 @@ void GUITable::draw() bool draw_background = m_background.getAlpha() > 0; if (m_border) - skin->draw3DSunkenPane(this, m_background, true, draw_background, + skin->draw3DSunkenPane(this, m_background, + true, draw_background, AbsoluteRect, &AbsoluteClippingRect); else if (draw_background) - skin->draw2DRectangle( - this, m_background, AbsoluteRect, &AbsoluteClippingRect); + skin->draw2DRectangle(this, m_background, + AbsoluteRect, &AbsoluteClippingRect); // get clipping rect @@ -653,12 +659,14 @@ void GUITable::draw() s32 scrollpos = m_scrollbar->getPos(); s32 row_min = scrollpos / m_rowheight; - s32 row_max = (scrollpos + AbsoluteRect.getHeight() - 1) / m_rowheight + 1; - row_max = MYMIN(row_max, (s32)m_visible_rows.size()); + s32 row_max = (scrollpos + AbsoluteRect.getHeight() - 1) + / m_rowheight + 1; + row_max = MYMIN(row_max, (s32) m_visible_rows.size()); core::rect row_rect(AbsoluteRect); if (m_scrollbar->isVisible()) - row_rect.LowerRightCorner.X -= skin->getSize(gui::EGDS_SCROLLBAR_SIZE); + row_rect.LowerRightCorner.X -= + skin->getSize(gui::EGDS_SCROLLBAR_SIZE); row_rect.UpperLeftCorner.Y += row_min * m_rowheight - scrollpos; row_rect.LowerRightCorner.Y = row_rect.UpperLeftCorner.Y + m_rowheight; @@ -684,27 +692,33 @@ void GUITable::draw() } void GUITable::drawCell(const Cell *cell, video::SColor color, - const core::rect &row_rect, const core::rect &client_clip) + const core::rect &row_rect, + const core::rect &client_clip) { - if ((cell->content_type == COLUMN_TYPE_TEXT) || - (cell->content_type == COLUMN_TYPE_TREE)) { + if ((cell->content_type == COLUMN_TYPE_TEXT) + || (cell->content_type == COLUMN_TYPE_TREE)) { core::rect text_rect = row_rect; - text_rect.UpperLeftCorner.X = row_rect.UpperLeftCorner.X + cell->xpos; - text_rect.LowerRightCorner.X = row_rect.UpperLeftCorner.X + cell->xmax; + text_rect.UpperLeftCorner.X = row_rect.UpperLeftCorner.X + + cell->xpos; + text_rect.LowerRightCorner.X = row_rect.UpperLeftCorner.X + + cell->xmax; if (cell->color_defined) color = cell->color; if (m_font) { if (cell->content_type == COLUMN_TYPE_TEXT) - m_font->draw(m_strings[cell->content_index], text_rect, - color, false, true, &client_clip); + m_font->draw(m_strings[cell->content_index], + text_rect, color, + false, true, &client_clip); else // tree - m_font->draw(cell->content_index ? L"+" : L"-", text_rect, - color, false, true, &client_clip); + m_font->draw(cell->content_index ? L"+" : L"-", + text_rect, color, + false, true, &client_clip); } - } else if (cell->content_type == COLUMN_TYPE_IMAGE) { + } + else if (cell->content_type == COLUMN_TYPE_IMAGE) { if (cell->content_index < 0) return; @@ -713,9 +727,11 @@ void GUITable::drawCell(const Cell *cell, video::SColor color, video::ITexture *image = m_images[cell->content_index]; if (image) { - core::position2d dest_pos = row_rect.UpperLeftCorner; + core::position2d dest_pos = + row_rect.UpperLeftCorner; dest_pos.X += cell->xpos; - core::rect source_rect(core::position2d(0, 0), + core::rect source_rect( + core::position2d(0, 0), image->getOriginalSize()); s32 imgh = source_rect.LowerRightCorner.Y; s32 rowh = row_rect.getHeight(); @@ -726,8 +742,8 @@ void GUITable::drawCell(const Cell *cell, video::SColor color, video::SColor color(255, 255, 255, 255); - driver->draw2DImage(image, dest_pos, source_rect, &client_clip, - color, true); + driver->draw2DImage(image, dest_pos, source_rect, + &client_clip, color, true); } } } @@ -738,41 +754,40 @@ bool GUITable::OnEvent(const SEvent &event) return IGUIElement::OnEvent(event); if (event.EventType == EET_KEY_INPUT_EVENT) { - if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_DOWN || - event.KeyInput.Key == KEY_UP || - event.KeyInput.Key == KEY_HOME || - event.KeyInput.Key == KEY_END || - event.KeyInput.Key == KEY_NEXT || - event.KeyInput.Key == KEY_PRIOR)) { + if (event.KeyInput.PressedDown && ( + event.KeyInput.Key == KEY_DOWN || + event.KeyInput.Key == KEY_UP || + event.KeyInput.Key == KEY_HOME || + event.KeyInput.Key == KEY_END || + event.KeyInput.Key == KEY_NEXT || + event.KeyInput.Key == KEY_PRIOR)) { s32 offset = 0; switch (event.KeyInput.Key) { - case KEY_DOWN: - offset = 1; - break; - case KEY_UP: - offset = -1; - break; - case KEY_HOME: - offset = -(s32)m_visible_rows.size(); - break; - case KEY_END: - offset = m_visible_rows.size(); - break; - case KEY_NEXT: - offset = AbsoluteRect.getHeight() / m_rowheight; - break; - case KEY_PRIOR: - offset = -(s32)(AbsoluteRect.getHeight() / m_rowheight); - break; - default: - break; + case KEY_DOWN: + offset = 1; + break; + case KEY_UP: + offset = -1; + break; + case KEY_HOME: + offset = - (s32) m_visible_rows.size(); + break; + case KEY_END: + offset = m_visible_rows.size(); + break; + case KEY_NEXT: + offset = AbsoluteRect.getHeight() / m_rowheight; + break; + case KEY_PRIOR: + offset = - (s32) (AbsoluteRect.getHeight() / m_rowheight); + break; + default: + break; } s32 old_selected = m_selected; s32 rowcount = m_visible_rows.size(); if (rowcount != 0) { - m_selected = rangelim( - m_selected + offset, 0, rowcount - 1); + m_selected = rangelim(m_selected + offset, 0, rowcount-1); autoScroll(); } @@ -782,24 +797,27 @@ bool GUITable::OnEvent(const SEvent &event) return true; } - if (event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_LEFT || - event.KeyInput.Key == KEY_RIGHT)) { + if (event.KeyInput.PressedDown && ( + event.KeyInput.Key == KEY_LEFT || + event.KeyInput.Key == KEY_RIGHT)) { // Open/close subtree via keyboard if (m_selected >= 0) { int dir = event.KeyInput.Key == KEY_LEFT ? -1 : 1; toggleVisibleTree(m_selected, dir, true); } return true; - } else if (!event.KeyInput.PressedDown && - (event.KeyInput.Key == KEY_RETURN || - event.KeyInput.Key == KEY_SPACE)) { + } + else if (!event.KeyInput.PressedDown && ( + event.KeyInput.Key == KEY_RETURN || + event.KeyInput.Key == KEY_SPACE)) { sendTableEvent(0, true); return true; - } else if (event.KeyInput.Key == KEY_ESCAPE || + } + else if (event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_SPACE) { // pass to parent - } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { + } + else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed u64 now = porting::getTimeMs(); if (now - m_keynav_time >= 500) @@ -808,13 +826,12 @@ bool GUITable::OnEvent(const SEvent &event) // add to key buffer if not a key repeat if (!(m_keynav_buffer.size() == 1 && - m_keynav_buffer[0] == event.KeyInput.Char)) { + m_keynav_buffer[0] == event.KeyInput.Char)) { m_keynav_buffer.append(event.KeyInput.Char); } // find the selected item, starting at the current selection - // don't change selection if the key buffer matches the current - // item + // don't change selection if the key buffer matches the current item s32 old_selected = m_selected; s32 start = MYMAX(m_selected, 0); s32 rowcount = m_visible_rows.size(); @@ -839,8 +856,8 @@ bool GUITable::OnEvent(const SEvent &event) if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { m_scrollbar->setPos(m_scrollbar->getPos() + - (event.MouseInput.Wheel < 0 ? -3 : 3) * - -(s32)m_rowheight / 2); + (event.MouseInput.Wheel < 0 ? -3 : 3) * + - (s32) m_rowheight / 2); return true; } @@ -861,24 +878,24 @@ bool GUITable::OnEvent(const SEvent &event) // IGUIScrollBar passes double click events to its parent, // which we don't want. Detect this case and discard the event if (event.MouseInput.Event != EMIE_MOUSE_MOVED && - m_scrollbar->isVisible() && m_scrollbar->isPointInside(p)) + m_scrollbar->isVisible() && + m_scrollbar->isPointInside(p)) return true; if (event.MouseInput.isLeftPressed() && - (isPointInside(p) || event.MouseInput.Event == - EMIE_MOUSE_MOVED)) { + (isPointInside(p) || + event.MouseInput.Event == EMIE_MOUSE_MOVED)) { s32 sel_column = 0; - bool sel_doubleclick = (event.MouseInput.Event == - EMIE_LMOUSE_DOUBLE_CLICK); + bool sel_doubleclick = (event.MouseInput.Event + == EMIE_LMOUSE_DOUBLE_CLICK); bool plusminus_clicked = false; // For certain events (left click), report column // Also open/close subtrees when the +/- is clicked - if (cell && (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN || - event.MouseInput.Event == - EMIE_LMOUSE_DOUBLE_CLICK || - event.MouseInput.Event == - EMIE_LMOUSE_TRIPLE_CLICK)) { + if (cell && ( + event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN || + event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK || + event.MouseInput.Event == EMIE_LMOUSE_TRIPLE_CLICK)) { sel_column = cell->reported_column; if (cell->content_type == COLUMN_TYPE_TREE) plusminus_clicked = true; @@ -888,13 +905,15 @@ bool GUITable::OnEvent(const SEvent &event) if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { toggleVisibleTree(row_i, 0, false); } - } else { + } + else { // Normal selection s32 old_selected = m_selected; m_selected = row_i; autoScroll(); - if (m_selected != old_selected || sel_column >= 1 || + if (m_selected != old_selected || + sel_column >= 1 || sel_doubleclick) { sendTableEvent(sel_column, sel_doubleclick); } @@ -956,9 +975,9 @@ void GUITable::allocationComplete() m_alloc_images.clear(); } -const GUITable::Row *GUITable::getRow(s32 i) const +const GUITable::Row* GUITable::getRow(s32 i) const { - if (i >= 0 && i < (s32)m_visible_rows.size()) + if (i >= 0 && i < (s32) m_visible_rows.size()) return &m_rows[m_visible_rows[i]]; return NULL; @@ -974,8 +993,7 @@ bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const if (cell->content_type == COLUMN_TYPE_TEXT) { const core::stringw &cellstr = m_strings[cell->content_index]; if (cellstr.size() >= str.size() && - str.equals_ignore_case( - cellstr.subString(0, str.size()))) + str.equals_ignore_case(cellstr.subString(0, str.size()))) return true; } } @@ -1028,7 +1046,8 @@ s32 GUITable::getCellAt(s32 x, s32 row_i) const jmin = pivot + 1; } - if (jmin >= 0 && jmin < row->cellcount && rel_x >= row->cells[jmin].xmin && + if (jmin >= 0 && jmin < row->cellcount && + rel_x >= row->cells[jmin].xmin && rel_x <= row->cells[jmin].xmax) return jmin; @@ -1079,8 +1098,8 @@ void GUITable::getOpenedTrees(std::set &opened_trees) const opened_trees.clear(); s32 rowcount = m_rows.size(); for (s32 i = 0; i < rowcount - 1; ++i) { - if (m_rows[i].indent < m_rows[i + 1].indent && - m_rows[i + 1].visible_index != -2) + if (m_rows[i].indent < m_rows[i+1].indent && + m_rows[i+1].visible_index != -2) opened_trees.insert(i); } } @@ -1112,16 +1131,18 @@ void GUITable::setOpenedTrees(const std::set &opened_trees) // Visible row row->visible_index = m_visible_rows.size(); m_visible_rows.push_back(i); - } else if (parents.back() == closed_parents.back()) { + } + else if (parents.back() == closed_parents.back()) { // Invisible row, direct parent is closed row->visible_index = -2; - } else { + } + else { // Invisible row, direct parent is open, some ancestor is closed row->visible_index = -1; } // If not a leaf, add to parents list - if (i < m_rows.size() - 1 && row->indent < m_rows[i + 1].indent) { + if (i < m_rows.size()-1 && row->indent < m_rows[i+1].indent) { parents.push_back(i); s32 content_index = 0; // "-", open @@ -1199,13 +1220,14 @@ void GUITable::toggleVisibleTree(s32 row_i, int dir, bool move_selection) const Row *maybe_child = getRow(sel + 1); if (maybe_child && maybe_child->indent > row->indent) sel++; - } else if (!was_open && !do_open) { + } + else if (!was_open && !do_open) { // Move selection to parent assert(getRow(sel) != NULL); while (sel > 0 && getRow(sel - 1)->indent >= row->indent) sel--; sel--; - if (sel < 0) // was root already selected? + if (sel < 0) // was root already selected? sel = row_i; } if (sel != m_selected) { @@ -1223,13 +1245,16 @@ void GUITable::alignContent(Cell *cell, s32 xmax, s32 content_width, s32 align) if (align == 0) { cell->xpos = cell->xmin; cell->xmax = xmax; - } else if (align == 1) { + } + else if (align == 1) { cell->xpos = (cell->xmin + xmax - content_width) / 2; cell->xmax = xmax; - } else if (align == 2) { + } + else if (align == 2) { cell->xpos = xmax - content_width; cell->xmax = xmax; - } else { + } + else { // inline alignment: the cells of the column don't have an aligned // right border, the right border of each cell depends on the content cell->xpos = cell->xmin; diff --git a/src/gui/guiTable.h b/src/gui/guiTable.h index 95cf05922..11093ea72 100644 --- a/src/gui/guiTable.h +++ b/src/gui/guiTable.h @@ -67,9 +67,9 @@ class GUITable : public gui::IGUIElement std::string value; Option(const std::string &name_, const std::string &value_) : - name(name_), value(value_) - { - } + name(name_), + value(value_) + {} }; /* @@ -87,8 +87,11 @@ class GUITable : public gui::IGUIElement }; typedef std::vector TableColumns; - GUITable(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - core::rect rectangle, ISimpleTextureSource *tsrc); + + GUITable(gui::IGUIEnvironment *env, + gui::IGUIElement *parent, s32 id, + core::rect rectangle, + ISimpleTextureSource *tsrc); virtual ~GUITable(); @@ -96,11 +99,13 @@ class GUITable : public gui::IGUIElement static Option splitOption(const std::string &str); /* Set textlist-like options, columns and data */ - void setTextList(const std::vector &content, bool transparent); + void setTextList(const std::vector &content, + bool transparent); /* Set generic table options, columns and content */ // Adds empty strings to end of content if there is an incomplete row - void setTable(const TableOptions &options, const TableColumns &columns, + void setTable(const TableOptions &options, + const TableColumns &columns, std::vector &content); /* Clear the table */ @@ -125,7 +130,7 @@ class GUITable : public gui::IGUIElement void setDynamicData(const DynamicData &dyndata); /* Returns "GUITable" */ - virtual const c8 *getTypeName() const; + virtual const c8* getTypeName() const; /* Must be called when position or size changes */ virtual void updateAbsolutePosition(); @@ -137,8 +142,7 @@ class GUITable : public gui::IGUIElement virtual bool OnEvent(const SEvent &event); protected: - enum ColumnType - { + enum ColumnType { COLUMN_TYPE_TEXT, COLUMN_TYPE_IMAGE, COLUMN_TYPE_COLOR, @@ -146,8 +150,7 @@ class GUITable : public gui::IGUIElement COLUMN_TYPE_TREE, }; - struct Cell - { + struct Cell { s32 xmin; s32 xmax; s32 xpos; @@ -159,8 +162,7 @@ class GUITable : public gui::IGUIElement s32 reported_column; }; - struct Row - { + struct Row { Cell *cells; s32 cellcount; s32 indent; @@ -201,7 +203,7 @@ class GUITable : public gui::IGUIElement // Allocated strings and images std::vector m_strings; - std::vector m_images; + std::vector m_images; std::map m_alloc_strings; std::map m_alloc_images; @@ -250,5 +252,6 @@ class GUITable : public gui::IGUIElement // Aligns cell content in column according to alignment specification // align = 0: left aligned, 1: centered, 2: right aligned, 3: inline - static void alignContent(Cell *cell, s32 xmax, s32 content_width, s32 align); + static void alignContent(Cell *cell, s32 xmax, s32 content_width, + s32 align); }; diff --git a/src/gui/guiVolumeChange.cpp b/src/gui/guiVolumeChange.cpp index 12874594e..f17cfa986 100644 --- a/src/gui/guiVolumeChange.cpp +++ b/src/gui/guiVolumeChange.cpp @@ -36,10 +36,12 @@ const int ID_soundExitButton = 264; const int ID_soundSlider = 265; const int ID_soundMuteButton = 266; -GUIVolumeChange::GUIVolumeChange(gui::IGUIEnvironment *env, gui::IGUIElement *parent, - s32 id, IMenuManager *menumgr, ISimpleTextureSource *tsrc) : - GUIModalMenu(env, parent, id, menumgr), - m_tsrc(tsrc) +GUIVolumeChange::GUIVolumeChange(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, ISimpleTextureSource *tsrc +): + GUIModalMenu(env, parent, id, menumgr), + m_tsrc(tsrc) { } @@ -73,9 +75,12 @@ void GUIVolumeChange::regenerateGui(v2u32 screensize) Calculate new sizes and positions */ const float s = m_gui_scale; - DesiredRect = core::rect(screensize.X / 2 - 380 * s / 2, - screensize.Y / 2 - 200 * s / 2, screensize.X / 2 + 380 * s / 2, - screensize.Y / 2 + 200 * s / 2); + DesiredRect = core::rect( + screensize.X / 2 - 380 * s / 2, + screensize.Y / 2 - 200 * s / 2, + screensize.X / 2 + 380 * s / 2, + screensize.Y / 2 + 200 * s / 2 + ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); @@ -90,25 +95,24 @@ void GUIVolumeChange::regenerateGui(v2u32 screensize) const wchar_t *text = wgettext("Sound Volume: "); core::stringw volume_text = text; - delete[] text; + delete [] text; volume_text += core::stringw(volume) + core::stringw("%"); - Environment->addStaticText(volume_text.c_str(), rect, false, true, this, - ID_soundText); + Environment->addStaticText(volume_text.c_str(), rect, false, + true, this, ID_soundText); } { core::rect rect(0, 0, 80 * s, 30 * s); rect = rect + v2s32(size.X / 2 - 80 * s / 2, size.Y / 2 + 55 * s); const wchar_t *text = wgettext("Exit"); - GUIButton::addButton(Environment, rect, m_tsrc, this, ID_soundExitButton, - text); + GUIButton::addButton(Environment, rect, m_tsrc, this, ID_soundExitButton, text); delete[] text; } { core::rect rect(0, 0, 300 * s, 20 * s); rect = rect + v2s32(size.X / 2 - 150 * s, size.Y / 2); - gui::IGUIScrollBar *e = Environment->addScrollBar( - true, rect, this, ID_soundSlider); + gui::IGUIScrollBar *e = Environment->addScrollBar(true, + rect, this, ID_soundSlider); e->setMax(100); e->setPos(volume); } @@ -124,16 +128,16 @@ void GUIVolumeChange::regenerateGui(v2u32 screensize) void GUIVolumeChange::drawMenu() { - gui::IGUISkin *skin = Environment->getSkin(); + gui::IGUISkin* skin = Environment->getSkin(); if (!skin) return; - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); gui::IGUIElement::draw(); } -bool GUIVolumeChange::OnEvent(const SEvent &event) +bool GUIVolumeChange::OnEvent(const SEvent& event) { if (event.EventType == EET_KEY_INPUT_EVENT) { if (event.KeyInput.Key == KEY_ESCAPE && event.KeyInput.PressedDown) { @@ -149,8 +153,7 @@ bool GUIVolumeChange::OnEvent(const SEvent &event) if (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) { gui::IGUIElement *e = getElementFromId(ID_soundMuteButton); if (e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) { - g_settings->setBool("mute_sound", - ((gui::IGUICheckBox *)e)->isChecked()); + g_settings->setBool("mute_sound", ((gui::IGUICheckBox*)e)->isChecked()); } Environment->setFocus(this); @@ -165,32 +168,31 @@ bool GUIVolumeChange::OnEvent(const SEvent &event) Environment->setFocus(this); } - if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && - isVisible()) { + if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { - infostream << "GUIVolumeChange: Not allowing focus " - "change." - << std::endl; + infostream << "GUIVolumeChange: Not allowing focus change." + << std::endl; // Returning true disables focus change return true; } } if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) { if (event.GUIEvent.Caller->getID() == ID_soundSlider) { - s32 pos = ((gui::IGUIScrollBar *)event.GUIEvent.Caller) - ->getPos(); - g_settings->setFloat("sound_volume", (float)pos / 100); + s32 pos = ((gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos(); + g_settings->setFloat("sound_volume", (float) pos / 100); gui::IGUIElement *e = getElementFromId(ID_soundText); const wchar_t *text = wgettext("Sound Volume: "); core::stringw volume_text = text; - delete[] text; + delete [] text; volume_text += core::stringw(pos) + core::stringw("%"); e->setText(volume_text.c_str()); return true; } } + } return Parent ? Parent->OnEvent(event) : false; diff --git a/src/gui/guiVolumeChange.h b/src/gui/guiVolumeChange.h index f1347a491..466e17f9d 100644 --- a/src/gui/guiVolumeChange.h +++ b/src/gui/guiVolumeChange.h @@ -28,7 +28,8 @@ class ISimpleTextureSource; class GUIVolumeChange : public GUIModalMenu { public: - GUIVolumeChange(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, + GUIVolumeChange(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, ISimpleTextureSource *tsrc); ~GUIVolumeChange(); @@ -40,7 +41,7 @@ class GUIVolumeChange : public GUIModalMenu void drawMenu(); - bool OnEvent(const SEvent &event); + bool OnEvent(const SEvent& event); bool pausesGame() { return true; } diff --git a/src/gui/intlGUIEditBox.cpp b/src/gui/intlGUIEditBox.cpp index 1c8bb64de..10395423c 100644 --- a/src/gui/intlGUIEditBox.cpp +++ b/src/gui/intlGUIEditBox.cpp @@ -45,8 +45,9 @@ todo: optional scrollbars ctrl+left/right to select word - double click/ctrl click: word select + drag to select whole words, triple click to - select line optional? dragging selected text numerical + double click/ctrl click: word select + drag to select whole words, triple click to select line + optional? dragging selected text + numerical */ namespace irr @@ -55,16 +56,16 @@ namespace gui { //! constructor -intlGUIEditBox::intlGUIEditBox(const wchar_t *text, bool border, - IGUIEnvironment *environment, IGUIElement *parent, s32 id, - const core::rect &rectangle, bool writable, bool has_vscrollbar) : - IGUIEditBox(environment, parent, id, rectangle), - Border(border), FrameRect(rectangle), m_scrollbar_width(0), - m_vscrollbar(NULL), m_writable(writable) +intlGUIEditBox::intlGUIEditBox(const wchar_t* text, bool border, + IGUIEnvironment* environment, IGUIElement* parent, s32 id, + const core::rect& rectangle, bool writable, bool has_vscrollbar) + : IGUIEditBox(environment, parent, id, rectangle), + Border(border), FrameRect(rectangle), + m_scrollbar_width(0), m_vscrollbar(NULL), m_writable(writable) { -#ifdef _DEBUG + #ifdef _DEBUG setDebugName("intlintlGUIEditBox"); -#endif + #endif Text = text; @@ -81,11 +82,12 @@ intlGUIEditBox::intlGUIEditBox(const wchar_t *text, bool border, IGUISkin *skin = 0; if (Environment) skin = Environment->getSkin(); - if (Border && skin) { - FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; - FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; - FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; - FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; + if (Border && skin) + { + FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1; + FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; + FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1; + FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; } if (skin && has_vscrollbar) { @@ -102,6 +104,7 @@ intlGUIEditBox::intlGUIEditBox(const wchar_t *text, bool border, setWritable(writable); } + //! destructor intlGUIEditBox::~intlGUIEditBox() { @@ -115,8 +118,9 @@ intlGUIEditBox::~intlGUIEditBox() m_vscrollbar->drop(); } + //! Sets another skin independent font. -void intlGUIEditBox::setOverrideFont(IGUIFont *font) +void intlGUIEditBox::setOverrideFont(IGUIFont* font) { if (OverrideFont == font) return; @@ -132,17 +136,17 @@ void intlGUIEditBox::setOverrideFont(IGUIFont *font) breakText(); } -IGUIFont *intlGUIEditBox::getOverrideFont() const +IGUIFont * intlGUIEditBox::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing -IGUIFont *intlGUIEditBox::getActiveFont() const +IGUIFont* intlGUIEditBox::getActiveFont() const { - if (OverrideFont) + if ( OverrideFont ) return OverrideFont; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; @@ -189,37 +193,44 @@ void intlGUIEditBox::setWordWrap(bool enable) breakText(); } + void intlGUIEditBox::updateAbsolutePosition() { - core::rect oldAbsoluteRect(AbsoluteRect); + core::rect oldAbsoluteRect(AbsoluteRect); IGUIElement::updateAbsolutePosition(); - if (oldAbsoluteRect != AbsoluteRect) { - breakText(); + if ( oldAbsoluteRect != AbsoluteRect ) + { + breakText(); } } + //! Checks if word wrap is enabled bool intlGUIEditBox::isWordWrapEnabled() const { return WordWrap; } + //! Enables or disables newlines. void intlGUIEditBox::setMultiLine(bool enable) { MultiLine = enable; } + //! Checks if multi line editing is enabled bool intlGUIEditBox::isMultiLineEnabled() const { return MultiLine; } + void intlGUIEditBox::setPasswordBox(bool passwordBox, wchar_t passwordChar) { PasswordBox = passwordBox; - if (PasswordBox) { + if (PasswordBox) + { PasswordChar = passwordChar; setMultiLine(false); setWordWrap(false); @@ -227,11 +238,13 @@ void intlGUIEditBox::setPasswordBox(bool passwordBox, wchar_t passwordChar) } } + bool intlGUIEditBox::isPasswordBox() const { return PasswordBox; } + //! Sets text justification void intlGUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { @@ -239,35 +252,40 @@ void intlGUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT VAlign = vertical; } + //! called if an event happened. -bool intlGUIEditBox::OnEvent(const SEvent &event) +bool intlGUIEditBox::OnEvent(const SEvent& event) { - if (IsEnabled) { + if (IsEnabled) + { - switch (event.EventType) { + switch(event.EventType) + { case EET_GUI_EVENT: - if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { - if (event.GUIEvent.Caller == this) { + if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) + { + if (event.GUIEvent.Caller == this) + { MouseMarking = false; - setTextMarkers(0, 0); + setTextMarkers(0,0); } } break; - case EET_KEY_INPUT_EVENT: { + case EET_KEY_INPUT_EVENT: + { #if (defined(__linux__) || defined(__FreeBSD__)) || defined(__DragonFly__) - // ################################################################ + // ################################################################ // ValkaTR: - // This part is the difference from the original intlGUIEditBox - // It converts UTF-8 character into a UCS-2 (wchar_t) - wchar_t wc = L'_'; - mbtowc(&wc, (char *)&event.KeyInput.Char, - sizeof(event.KeyInput.Char)); + // This part is the difference from the original intlGUIEditBox + // It converts UTF-8 character into a UCS-2 (wchar_t) + wchar_t wc = L'_'; + mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); - // printf( "char: %lc (%u) \r\n", wc, wc ); + //printf( "char: %lc (%u) \r\n", wc, wc ); - SEvent irrevent(event); - irrevent.KeyInput.Char = wc; - // ################################################################ + SEvent irrevent(event); + irrevent.KeyInput.Char = wc; + // ################################################################ if (processKey(irrevent)) return true; @@ -277,7 +295,7 @@ bool intlGUIEditBox::OnEvent(const SEvent &event) #endif // defined(linux) break; - } + } case EET_MOUSE_INPUT_EVENT: if (processMouse(event)) return true; @@ -290,7 +308,8 @@ bool intlGUIEditBox::OnEvent(const SEvent &event) return IGUIElement::OnEvent(event); } -bool intlGUIEditBox::processKey(const SEvent &event) + +bool intlGUIEditBox::processKey(const SEvent& event) { if (!event.KeyInput.PressedDown) return false; @@ -301,14 +320,17 @@ bool intlGUIEditBox::processKey(const SEvent &event) // control shortcut handling - if (event.KeyInput.Control) { + if (event.KeyInput.Control) + { // german backlash '\' entered with control + '?' - if (event.KeyInput.Char == '\\') { + if ( event.KeyInput.Char == '\\' ) + { inputChar(event.KeyInput.Char); return true; } - switch (event.KeyInput.Key) { + switch(event.KeyInput.Key) + { case KEY_KEY_A: // select all newMarkBegin = 0; @@ -316,11 +338,10 @@ bool intlGUIEditBox::processKey(const SEvent &event) break; case KEY_KEY_C: // copy to clipboard - if (!PasswordBox && Operator && MarkBegin != MarkEnd) { - const s32 realmbgn = - MarkBegin < MarkEnd ? MarkBegin : MarkEnd; - const s32 realmend = - MarkBegin < MarkEnd ? MarkEnd : MarkBegin; + if (!PasswordBox && Operator && MarkBegin != MarkEnd) + { + const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; + const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; core::stringc s; s = Text.subString(realmbgn, realmend - realmbgn).c_str(); @@ -330,23 +351,19 @@ bool intlGUIEditBox::processKey(const SEvent &event) case KEY_KEY_X: // cut to the clipboard if (!PasswordBox && Operator && MarkBegin != MarkEnd) { - const s32 realmbgn = - MarkBegin < MarkEnd ? MarkBegin : MarkEnd; - const s32 realmend = - MarkBegin < MarkEnd ? MarkEnd : MarkBegin; + const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; + const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; // copy core::stringc sc; - sc = Text.subString(realmbgn, realmend - realmbgn) - .c_str(); + sc = Text.subString(realmbgn, realmend - realmbgn).c_str(); Operator->copyToClipboard(sc.c_str()); if (IsEnabled && m_writable) { // delete core::stringw s; s = Text.subString(0, realmbgn); - s.append(Text.subString(realmend, - Text.size() - realmend)); + s.append( Text.subString(realmend, Text.size()-realmend) ); Text = s; CursorPos = realmbgn; @@ -361,43 +378,38 @@ bool intlGUIEditBox::processKey(const SEvent &event) break; // paste from the clipboard - if (Operator) { - const s32 realmbgn = - MarkBegin < MarkEnd ? MarkBegin : MarkEnd; - const s32 realmend = - MarkBegin < MarkEnd ? MarkEnd : MarkBegin; + if (Operator) + { + const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; + const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; // add new character - const c8 *p = Operator->getTextFromClipboard(); - if (p) { - if (MarkBegin == MarkEnd) { + const c8* p = Operator->getTextFromClipboard(); + if (p) + { + if (MarkBegin == MarkEnd) + { // insert text - core::stringw s = Text.subString( - 0, CursorPos); + core::stringw s = Text.subString(0, CursorPos); s.append(p); - s.append(Text.subString(CursorPos, - Text.size() - CursorPos)); + s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); - if (!Max || s.size() <= Max) // thx to - // Fish FH - // for fix + if (!Max || s.size()<=Max) // thx to Fish FH for fix { Text = s; s = p; CursorPos += s.size(); } - } else { + } + else + { // replace text - core::stringw s = Text.subString( - 0, realmbgn); + core::stringw s = Text.subString(0, realmbgn); s.append(p); - s.append(Text.subString(realmend, - Text.size() - realmend)); + s.append( Text.subString(realmend, Text.size()-realmend) ); - if (!Max || s.size() <= Max) // thx to - // Fish FH - // for fix + if (!Max || s.size()<=Max) // thx to Fish FH for fix { Text = s; s = p; @@ -413,11 +425,14 @@ bool intlGUIEditBox::processKey(const SEvent &event) break; case KEY_HOME: // move/highlight to start of text - if (event.KeyInput.Shift) { + if (event.KeyInput.Shift) + { newMarkEnd = CursorPos; newMarkBegin = 0; CursorPos = 0; - } else { + } + else + { CursorPos = 0; newMarkBegin = 0; newMarkEnd = 0; @@ -425,11 +440,14 @@ bool intlGUIEditBox::processKey(const SEvent &event) break; case KEY_END: // move/highlight to end of text - if (event.KeyInput.Shift) { + if (event.KeyInput.Shift) + { newMarkBegin = CursorPos; newMarkEnd = Text.size(); CursorPos = 0; - } else { + } + else + { CursorPos = Text.size(); newMarkBegin = 0; newMarkEnd = 0; @@ -441,281 +459,293 @@ bool intlGUIEditBox::processKey(const SEvent &event) } // default keyboard handling else - switch (event.KeyInput.Key) { - case KEY_END: { + switch(event.KeyInput.Key) + { + case KEY_END: + { s32 p = Text.size(); - if (WordWrap || MultiLine) { + if (WordWrap || MultiLine) + { p = getLineFromPos(CursorPos); p = BrokenTextPositions[p] + (s32)BrokenText[p].size(); - if (p > 0 && (Text[p - 1] == L'\r' || - Text[p - 1] == L'\n')) - p -= 1; + if (p > 0 && (Text[p-1] == L'\r' || Text[p-1] == L'\n' )) + p-=1; } - if (event.KeyInput.Shift) { + if (event.KeyInput.Shift) + { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; newMarkEnd = p; - } else { + } + else + { newMarkBegin = 0; newMarkEnd = 0; } CursorPos = p; BlinkStartTime = porting::getTimeMs(); - } break; - case KEY_HOME: { + } + break; + case KEY_HOME: + { s32 p = 0; - if (WordWrap || MultiLine) { + if (WordWrap || MultiLine) + { p = getLineFromPos(CursorPos); p = BrokenTextPositions[p]; } - if (event.KeyInput.Shift) { + if (event.KeyInput.Shift) + { if (MarkBegin == MarkEnd) newMarkBegin = CursorPos; newMarkEnd = p; - } else { + } + else + { newMarkBegin = 0; newMarkEnd = 0; } CursorPos = p; BlinkStartTime = porting::getTimeMs(); - } break; - case KEY_RETURN: - if (MultiLine) { - inputChar(L'\n'); - return true; - } else { - sendGuiEvent(EGET_EDITBOX_ENTER); - } - break; - case KEY_LEFT: + } + break; + case KEY_RETURN: + if (MultiLine) + { + inputChar(L'\n'); + return true; + } + else + { + sendGuiEvent( EGET_EDITBOX_ENTER ); + } + break; + case KEY_LEFT: - if (event.KeyInput.Shift) { - if (CursorPos > 0) { - if (MarkBegin == MarkEnd) - newMarkBegin = CursorPos; + if (event.KeyInput.Shift) + { + if (CursorPos > 0) + { + if (MarkBegin == MarkEnd) + newMarkBegin = CursorPos; - newMarkEnd = CursorPos - 1; - } - } else { - newMarkBegin = 0; - newMarkEnd = 0; + newMarkEnd = CursorPos-1; } + } + else + { + newMarkBegin = 0; + newMarkEnd = 0; + } - if (CursorPos > 0) - CursorPos--; - BlinkStartTime = porting::getTimeMs(); - break; + if (CursorPos > 0) CursorPos--; + BlinkStartTime = porting::getTimeMs(); + break; - case KEY_RIGHT: - if (event.KeyInput.Shift) { - if (Text.size() > (u32)CursorPos) { - if (MarkBegin == MarkEnd) - newMarkBegin = CursorPos; + case KEY_RIGHT: + if (event.KeyInput.Shift) + { + if (Text.size() > (u32)CursorPos) + { + if (MarkBegin == MarkEnd) + newMarkBegin = CursorPos; - newMarkEnd = CursorPos + 1; - } - } else { - newMarkBegin = 0; - newMarkEnd = 0; + newMarkEnd = CursorPos+1; } + } + else + { + newMarkBegin = 0; + newMarkEnd = 0; + } - if (Text.size() > (u32)CursorPos) - CursorPos++; - BlinkStartTime = porting::getTimeMs(); - break; - case KEY_UP: - if (MultiLine || (WordWrap && BrokenText.size() > 1)) { - s32 lineNo = getLineFromPos(CursorPos); - s32 mb = (MarkBegin == MarkEnd) - ? CursorPos - : (MarkBegin > MarkEnd ? MarkBegin - : MarkEnd); - if (lineNo > 0) { - s32 cp = CursorPos - BrokenTextPositions[lineNo]; - if ((s32)BrokenText[lineNo - 1].size() < cp) - CursorPos = BrokenTextPositions[lineNo - - 1] + - (s32)BrokenText[lineNo - 1] - .size() - - 1; - else - CursorPos = BrokenTextPositions[lineNo - - 1] + - cp; - } - - if (event.KeyInput.Shift) { - newMarkBegin = mb; - newMarkEnd = CursorPos; - } else { - newMarkBegin = 0; - newMarkEnd = 0; - } + if (Text.size() > (u32)CursorPos) CursorPos++; + BlinkStartTime = porting::getTimeMs(); + break; + case KEY_UP: + if (MultiLine || (WordWrap && BrokenText.size() > 1) ) + { + s32 lineNo = getLineFromPos(CursorPos); + s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin > MarkEnd ? MarkBegin : MarkEnd); + if (lineNo > 0) + { + s32 cp = CursorPos - BrokenTextPositions[lineNo]; + if ((s32)BrokenText[lineNo-1].size() < cp) + CursorPos = BrokenTextPositions[lineNo-1] + (s32)BrokenText[lineNo-1].size()-1; + else + CursorPos = BrokenTextPositions[lineNo-1] + cp; + } - } else { - return false; + if (event.KeyInput.Shift) + { + newMarkBegin = mb; + newMarkEnd = CursorPos; + } + else + { + newMarkBegin = 0; + newMarkEnd = 0; } - break; - case KEY_DOWN: - if (MultiLine || (WordWrap && BrokenText.size() > 1)) { - s32 lineNo = getLineFromPos(CursorPos); - s32 mb = (MarkBegin == MarkEnd) - ? CursorPos - : (MarkBegin < MarkEnd ? MarkBegin - : MarkEnd); - if (lineNo < (s32)BrokenText.size() - 1) { - s32 cp = CursorPos - BrokenTextPositions[lineNo]; - if ((s32)BrokenText[lineNo + 1].size() < cp) - CursorPos = BrokenTextPositions[lineNo + - 1] + - BrokenText[lineNo + 1] - .size() - - 1; - else - CursorPos = BrokenTextPositions[lineNo + - 1] + - cp; - } - if (event.KeyInput.Shift) { - newMarkBegin = mb; - newMarkEnd = CursorPos; - } else { - newMarkBegin = 0; - newMarkEnd = 0; - } + } + else + { + return false; + } + break; + case KEY_DOWN: + if (MultiLine || (WordWrap && BrokenText.size() > 1) ) + { + s32 lineNo = getLineFromPos(CursorPos); + s32 mb = (MarkBegin == MarkEnd) ? CursorPos : (MarkBegin < MarkEnd ? MarkBegin : MarkEnd); + if (lineNo < (s32)BrokenText.size()-1) + { + s32 cp = CursorPos - BrokenTextPositions[lineNo]; + if ((s32)BrokenText[lineNo+1].size() < cp) + CursorPos = BrokenTextPositions[lineNo+1] + BrokenText[lineNo+1].size()-1; + else + CursorPos = BrokenTextPositions[lineNo+1] + cp; + } - } else { - return false; + if (event.KeyInput.Shift) + { + newMarkBegin = mb; + newMarkEnd = CursorPos; + } + else + { + newMarkBegin = 0; + newMarkEnd = 0; } - break; - case KEY_BACK: - if (!this->IsEnabled || !m_writable) - break; + } + else + { + return false; + } + break; - if (!Text.empty()) { - core::stringw s; + case KEY_BACK: + if (!this->IsEnabled || !m_writable) + break; - if (MarkBegin != MarkEnd) { - // delete marked text - const s32 realmbgn = MarkBegin < MarkEnd - ? MarkBegin - : MarkEnd; - const s32 realmend = MarkBegin < MarkEnd - ? MarkEnd - : MarkBegin; + if (!Text.empty()) { + core::stringw s; - s = Text.subString(0, realmbgn); - s.append(Text.subString(realmend, - Text.size() - realmend)); - Text = s; + if (MarkBegin != MarkEnd) + { + // delete marked text + const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; + const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; - CursorPos = realmbgn; - } else { - // delete text behind cursor - if (CursorPos > 0) - s = Text.subString(0, CursorPos - 1); - else - s = L""; - s.append(Text.subString(CursorPos, - Text.size() - CursorPos)); - Text = s; - --CursorPos; - } + s = Text.subString(0, realmbgn); + s.append( Text.subString(realmend, Text.size()-realmend) ); + Text = s; - if (CursorPos < 0) - CursorPos = 0; - BlinkStartTime = porting::getTimeMs(); - newMarkBegin = 0; - newMarkEnd = 0; - textChanged = true; + CursorPos = realmbgn; + } + else + { + // delete text behind cursor + if (CursorPos>0) + s = Text.subString(0, CursorPos-1); + else + s = L""; + s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); + Text = s; + --CursorPos; } - break; - case KEY_DELETE: - if (!this->IsEnabled || !m_writable) - break; - - if (!Text.empty()) { - core::stringw s; - if (MarkBegin != MarkEnd) { - // delete marked text - const s32 realmbgn = MarkBegin < MarkEnd - ? MarkBegin - : MarkEnd; - const s32 realmend = MarkBegin < MarkEnd - ? MarkEnd - : MarkBegin; + if (CursorPos < 0) + CursorPos = 0; + BlinkStartTime = porting::getTimeMs(); + newMarkBegin = 0; + newMarkEnd = 0; + textChanged = true; + } + break; + case KEY_DELETE: + if (!this->IsEnabled || !m_writable) + break; - s = Text.subString(0, realmbgn); - s.append(Text.subString(realmend, - Text.size() - realmend)); - Text = s; + if (!Text.empty()) { + core::stringw s; - CursorPos = realmbgn; - } else { - // delete text before cursor - s = Text.subString(0, CursorPos); - s.append(Text.subString(CursorPos + 1, - Text.size() - CursorPos - 1)); - Text = s; - } + if (MarkBegin != MarkEnd) + { + // delete marked text + const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; + const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; - if (CursorPos > (s32)Text.size()) - CursorPos = (s32)Text.size(); + s = Text.subString(0, realmbgn); + s.append( Text.subString(realmend, Text.size()-realmend) ); + Text = s; - BlinkStartTime = porting::getTimeMs(); - newMarkBegin = 0; - newMarkEnd = 0; - textChanged = true; + CursorPos = realmbgn; + } + else + { + // delete text before cursor + s = Text.subString(0, CursorPos); + s.append( Text.subString(CursorPos+1, Text.size()-CursorPos-1) ); + Text = s; } - break; - case KEY_ESCAPE: - case KEY_TAB: - case KEY_SHIFT: - case KEY_F1: - case KEY_F2: - case KEY_F3: - case KEY_F4: - case KEY_F5: - case KEY_F6: - case KEY_F7: - case KEY_F8: - case KEY_F9: - case KEY_F10: - case KEY_F11: - case KEY_F12: - case KEY_F13: - case KEY_F14: - case KEY_F15: - case KEY_F16: - case KEY_F17: - case KEY_F18: - case KEY_F19: - case KEY_F20: - case KEY_F21: - case KEY_F22: - case KEY_F23: - case KEY_F24: - // ignore these keys - return false; + if (CursorPos > (s32)Text.size()) + CursorPos = (s32)Text.size(); - default: - inputChar(event.KeyInput.Char); - return true; + BlinkStartTime = porting::getTimeMs(); + newMarkBegin = 0; + newMarkEnd = 0; + textChanged = true; } + break; - // Set new text markers - setTextMarkers(newMarkBegin, newMarkEnd); + case KEY_ESCAPE: + case KEY_TAB: + case KEY_SHIFT: + case KEY_F1: + case KEY_F2: + case KEY_F3: + case KEY_F4: + case KEY_F5: + case KEY_F6: + case KEY_F7: + case KEY_F8: + case KEY_F9: + case KEY_F10: + case KEY_F11: + case KEY_F12: + case KEY_F13: + case KEY_F14: + case KEY_F15: + case KEY_F16: + case KEY_F17: + case KEY_F18: + case KEY_F19: + case KEY_F20: + case KEY_F21: + case KEY_F22: + case KEY_F23: + case KEY_F24: + // ignore these keys + return false; + + default: + inputChar(event.KeyInput.Char); + return true; + } + + // Set new text markers + setTextMarkers( newMarkBegin, newMarkEnd ); // break the text if it has changed - if (textChanged) { + if (textChanged) + { breakText(); sendGuiEvent(EGET_EDITBOX_CHANGED); } @@ -725,6 +755,7 @@ bool intlGUIEditBox::processKey(const SEvent &event) return true; } + //! draws the element and its children void intlGUIEditBox::draw() { @@ -733,7 +764,7 @@ void intlGUIEditBox::draw() const bool focus = Environment->hasFocus(this); - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (!skin) return; @@ -741,16 +772,17 @@ void intlGUIEditBox::draw() // draw the border - if (Border) { + if (Border) + { if (m_writable) { - skin->draw3DSunkenPane(this, skin->getColor(EGDC_WINDOW), false, - true, FrameRect, &AbsoluteClippingRect); + skin->draw3DSunkenPane(this, skin->getColor(EGDC_WINDOW), + false, true, FrameRect, &AbsoluteClippingRect); } - FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; - FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; - FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; - FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; + FrameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X)+1; + FrameRect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; + FrameRect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X)+1; + FrameRect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y)+1; } updateVScrollBar(); @@ -759,15 +791,17 @@ void intlGUIEditBox::draw() // draw the text - IGUIFont *font = OverrideFont; + IGUIFont* font = OverrideFont; if (!OverrideFont) font = skin->getFont(); s32 cursorLine = 0; s32 charcursorpos = 0; - if (font) { - if (LastBreakFont != font) { + if (font) + { + if (LastBreakFont != font) + { breakText(); } @@ -792,107 +826,97 @@ void intlGUIEditBox::draw() const video::SColor prevColor = OverrideColor; if (!Text.empty()) { - if (!IsEnabled && !OverrideColorEnabled) { + if (!IsEnabled && !OverrideColorEnabled) + { OverrideColorEnabled = true; OverrideColor = skin->getColor(EGDC_GRAY_TEXT); } - for (s32 i = 0; i < lineCount; ++i) { + for (s32 i=0; i < lineCount; ++i) + { setTextRect(i); - // clipping test - don't draw anything outside the visible - // area + // clipping test - don't draw anything outside the visible area core::rect c = localClipRect; c.clipAgainst(CurrentTextRect); if (!c.isValid()) continue; // get current line - if (PasswordBox) { - if (BrokenText.size() != 1) { + if (PasswordBox) + { + if (BrokenText.size() != 1) + { BrokenText.clear(); BrokenText.push_back(core::stringw()); } - if (BrokenText[0].size() != Text.size()) { + if (BrokenText[0].size() != Text.size()) + { BrokenText[0] = Text; - for (u32 q = 0; q < Text.size(); ++q) { - BrokenText[0][q] = PasswordChar; + for (u32 q = 0; q < Text.size(); ++q) + { + BrokenText[0] [q] = PasswordChar; } } txtLine = &BrokenText[0]; startPos = 0; - } else { + } + else + { txtLine = ml ? &BrokenText[i] : &Text; startPos = ml ? BrokenTextPositions[i] : 0; } + // draw normal text font->draw(txtLine->c_str(), CurrentTextRect, - OverrideColorEnabled - ? OverrideColor - : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &localClipRect); + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), + false, true, &localClipRect); // draw mark and marked text - if (focus && MarkBegin != MarkEnd && i >= hlineStart && - i < hlineStart + hlineCount) { + if (focus && MarkBegin != MarkEnd && i >= hlineStart && i < hlineStart + hlineCount) + { s32 mbegin = 0, mend = 0; - s32 lineStartPos = 0, - lineEndPos = txtLine->size(); + s32 lineStartPos = 0, lineEndPos = txtLine->size(); - if (i == hlineStart) { + if (i == hlineStart) + { // highlight start is on this line - s = txtLine->subString( - 0, realmbgn - startPos); - mbegin = font->getDimension(s.c_str()) - .Width; + s = txtLine->subString(0, realmbgn - startPos); + mbegin = font->getDimension(s.c_str()).Width; // deal with kerning mbegin += font->getKerningWidth( - &((*txtLine)[realmbgn - - startPos]), - realmbgn - startPos > 0 - ? &((*txtLine)[realmbgn - - startPos - - 1]) - : 0); + &((*txtLine)[realmbgn - startPos]), + realmbgn - startPos > 0 ? &((*txtLine)[realmbgn - startPos - 1]) : 0); lineStartPos = realmbgn - startPos; } - if (i == hlineStart + hlineCount - 1) { + if (i == hlineStart + hlineCount - 1) + { // highlight end is on this line - s2 = txtLine->subString( - 0, realmend - startPos); - mend = font->getDimension(s2.c_str()) - .Width; + s2 = txtLine->subString(0, realmend - startPos); + mend = font->getDimension(s2.c_str()).Width; lineEndPos = (s32)s2.size(); - } else - mend = font->getDimension(txtLine->c_str()) - .Width; + } + else + mend = font->getDimension(txtLine->c_str()).Width; CurrentTextRect.UpperLeftCorner.X += mbegin; - CurrentTextRect.LowerRightCorner.X = - CurrentTextRect.UpperLeftCorner - .X + - mend - mbegin; + CurrentTextRect.LowerRightCorner.X = CurrentTextRect.UpperLeftCorner.X + mend - mbegin; // draw mark - skin->draw2DRectangle(this, - skin->getColor(EGDC_HIGH_LIGHT), - CurrentTextRect, &localClipRect); + skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), CurrentTextRect, &localClipRect); // draw marked text - s = txtLine->subString(lineStartPos, - lineEndPos - lineStartPos); + s = txtLine->subString(lineStartPos, lineEndPos - lineStartPos); if (!s.empty()) font->draw(s.c_str(), CurrentTextRect, - OverrideColorEnabled - ? OverrideColor - : skin->getColor(EGDC_HIGH_LIGHT_TEXT), - false, true, - &localClipRect); + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_HIGH_LIGHT_TEXT), + false, true, &localClipRect); + } } @@ -903,31 +927,24 @@ void intlGUIEditBox::draw() // draw cursor - if (WordWrap || MultiLine) { + if (WordWrap || MultiLine) + { cursorLine = getLineFromPos(CursorPos); txtLine = &BrokenText[cursorLine]; startPos = BrokenTextPositions[cursorLine]; } - s = txtLine->subString(0, CursorPos - startPos); + s = txtLine->subString(0,CursorPos-startPos); charcursorpos = font->getDimension(s.c_str()).Width + - font->getKerningWidth(L"_", - CursorPos - startPos > 0 - ? &((*txtLine)[CursorPos - - startPos - - 1]) - : 0); + font->getKerningWidth(L"_", CursorPos-startPos > 0 ? &((*txtLine)[CursorPos-startPos-1]) : 0); - if (m_writable) { - if (focus && (porting::getTimeMs() - BlinkStartTime) % 700 < - 350) { + if (m_writable) { + if (focus && (porting::getTimeMs() - BlinkStartTime) % 700 < 350) { setTextRect(cursorLine); CurrentTextRect.UpperLeftCorner.X += charcursorpos; font->draw(L"_", CurrentTextRect, - OverrideColorEnabled - ? OverrideColor - : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &localClipRect); + OverrideColorEnabled ? OverrideColor : skin->getColor(EGDC_BUTTON_TEXT), + false, true, &localClipRect); } } } @@ -936,8 +953,9 @@ void intlGUIEditBox::draw() IGUIElement::draw(); } + //! Sets the new caption of this element. -void intlGUIEditBox::setText(const wchar_t *text) +void intlGUIEditBox::setText(const wchar_t* text) { Text = text; if (u32(CursorPos) > Text.size()) @@ -946,6 +964,7 @@ void intlGUIEditBox::setText(const wchar_t *text) breakText(); } + //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position void intlGUIEditBox::setAutoScroll(bool enable) @@ -953,6 +972,7 @@ void intlGUIEditBox::setAutoScroll(bool enable) AutoScroll = enable; } + //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not bool intlGUIEditBox::isAutoScrollEnabled() const @@ -960,6 +980,7 @@ bool intlGUIEditBox::isAutoScrollEnabled() const return AutoScroll; } + //! Gets the area of the text in the edit box //! \return Returns the size in pixels of the text core::dimension2du intlGUIEditBox::getTextDimension() @@ -969,7 +990,8 @@ core::dimension2du intlGUIEditBox::getTextDimension() setTextRect(0); ret = CurrentTextRect; - for (u32 i = 1; i < BrokenText.size(); ++i) { + for (u32 i=1; i < BrokenText.size(); ++i) + { setTextRect(i); ret.addInternalPoint(CurrentTextRect.UpperLeftCorner); ret.addInternalPoint(CurrentTextRect.LowerRightCorner); @@ -978,6 +1000,7 @@ core::dimension2du intlGUIEditBox::getTextDimension() return core::dimension2du(ret.getSize()); } + //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. @@ -989,48 +1012,60 @@ void intlGUIEditBox::setMax(u32 max) Text = Text.subString(0, Max); } + //! Returns maximum amount of characters, previously set by setMax(); u32 intlGUIEditBox::getMax() const { return Max; } -bool intlGUIEditBox::processMouse(const SEvent &event) + +bool intlGUIEditBox::processMouse(const SEvent& event) { - switch (event.MouseInput.Event) { + switch(event.MouseInput.Event) + { case irr::EMIE_LMOUSE_LEFT_UP: - if (Environment->hasFocus(this)) { + if (Environment->hasFocus(this)) + { CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); - if (MouseMarking) { - setTextMarkers(MarkBegin, CursorPos); + if (MouseMarking) + { + setTextMarkers( MarkBegin, CursorPos ); } MouseMarking = false; calculateScrollPos(); return true; } break; - case irr::EMIE_MOUSE_MOVED: { - if (MouseMarking) { - CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); - setTextMarkers(MarkBegin, CursorPos); - calculateScrollPos(); - return true; + case irr::EMIE_MOUSE_MOVED: + { + if (MouseMarking) + { + CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); + setTextMarkers( MarkBegin, CursorPos ); + calculateScrollPos(); + return true; + } } - } break; + break; case EMIE_LMOUSE_PRESSED_DOWN: - if (!Environment->hasFocus(this)) { + if (!Environment->hasFocus(this)) + { BlinkStartTime = porting::getTimeMs(); MouseMarking = true; CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); - setTextMarkers(CursorPos, CursorPos); + setTextMarkers(CursorPos, CursorPos ); calculateScrollPos(); return true; - } else { - if (!AbsoluteClippingRect.isPointInside(core::position2d( - event.MouseInput.X, event.MouseInput.Y))) { + } + else + { + if (!AbsoluteClippingRect.isPointInside( + core::position2d(event.MouseInput.X, event.MouseInput.Y))) { return false; } + // move cursor CursorPos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); @@ -1039,7 +1074,7 @@ bool intlGUIEditBox::processMouse(const SEvent &event) newMarkBegin = CursorPos; MouseMarking = true; - setTextMarkers(newMarkBegin, CursorPos); + setTextMarkers( newMarkBegin, CursorPos); calculateScrollPos(); return true; } @@ -1058,10 +1093,11 @@ bool intlGUIEditBox::processMouse(const SEvent &event) return false; } + s32 intlGUIEditBox::getCursorPos(s32 x, s32 y) { - IGUIFont *font = OverrideFont; - IGUISkin *skin = Environment->getSkin(); + IGUIFont* font = OverrideFont; + IGUISkin* skin = Environment->getSkin(); if (!OverrideFont) font = skin->getFont(); @@ -1076,19 +1112,14 @@ s32 intlGUIEditBox::getCursorPos(s32 x, s32 y) setTextRect(curr_line_idx); if (curr_line_idx == 0 && y < CurrentTextRect.UpperLeftCorner.Y) y = CurrentTextRect.UpperLeftCorner.Y; - if (curr_line_idx == lineCount - 1 && - y > CurrentTextRect.LowerRightCorner.Y) + if (curr_line_idx == lineCount - 1 && y > CurrentTextRect.LowerRightCorner.Y) y = CurrentTextRect.LowerRightCorner.Y; // is it inside this region? - if (y >= CurrentTextRect.UpperLeftCorner.Y && - y <= CurrentTextRect.LowerRightCorner.Y) { + if (y >= CurrentTextRect.UpperLeftCorner.Y && y <= CurrentTextRect.LowerRightCorner.Y) { // we've found the clicked line - txtLine = (WordWrap || MultiLine) ? &BrokenText[curr_line_idx] - : &Text; - startPos = (WordWrap || MultiLine) - ? BrokenTextPositions[curr_line_idx] - : 0; + txtLine = (WordWrap || MultiLine) ? &BrokenText[curr_line_idx] : &Text; + startPos = (WordWrap || MultiLine) ? BrokenTextPositions[curr_line_idx] : 0; break; } } @@ -1098,20 +1129,20 @@ s32 intlGUIEditBox::getCursorPos(s32 x, s32 y) else if (x > CurrentTextRect.LowerRightCorner.X) x = CurrentTextRect.LowerRightCorner.X; - s32 idx = font->getCharacterFromPos( - txtLine->c_str(), x - CurrentTextRect.UpperLeftCorner.X); - // Special handling for last line, if we are on limits, add 1 extra shift because - // idx will be the last char, not null char of the wstring + s32 idx = font->getCharacterFromPos(txtLine->c_str(), x - CurrentTextRect.UpperLeftCorner.X); + // Special handling for last line, if we are on limits, add 1 extra shift because idx + // will be the last char, not null char of the wstring if (curr_line_idx == lineCount - 1 && x == CurrentTextRect.LowerRightCorner.X) idx++; return rangelim(idx + startPos, 0, S32_MAX); } + //! Breaks the single text line. void intlGUIEditBox::breakText() { - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if ((!WordWrap && !MultiLine) || !skin) return; @@ -1119,7 +1150,7 @@ void intlGUIEditBox::breakText() BrokenText.clear(); // need to reallocate :/ BrokenTextPositions.set_used(0); - IGUIFont *font = OverrideFont; + IGUIFont* font = OverrideFont; if (!OverrideFont) font = skin->getFont(); @@ -1137,7 +1168,8 @@ void intlGUIEditBox::breakText() s32 elWidth = RelativeRect.getWidth() - 6; wchar_t c; - for (s32 i = 0; i < size; ++i) { + for (s32 i=0; igetDimension(whitespace.c_str()) - .Width; + s32 whitelgth = font->getDimension(whitespace.c_str()).Width; s32 worldlgth = font->getDimension(word.c_str()).Width; - if (WordWrap && length + worldlgth + whitelgth > - elWidth) { + if (WordWrap && length + worldlgth + whitelgth > elWidth) + { // break to next line length = worldlgth; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); lastLineStart = i - (s32)word.size(); line = word; - } else { + } + else + { // add word to line line += whitespace; line += word; @@ -1190,18 +1225,21 @@ void intlGUIEditBox::breakText() whitespace += c; // compute line break - if (lineBreak) { + if (lineBreak) + { line += whitespace; line += word; BrokenText.push_back(line); BrokenTextPositions.push_back(lastLineStart); - lastLineStart = i + 1; + lastLineStart = i+1; line = L""; word = L""; whitespace = L""; length = 0; } - } else { + } + else + { // yippee this is a word.. word += c; } @@ -1213,37 +1251,40 @@ void intlGUIEditBox::breakText() BrokenTextPositions.push_back(lastLineStart); } + void intlGUIEditBox::setTextRect(s32 line) { core::dimension2du d; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (!skin) return; - IGUIFont *font = OverrideFont ? OverrideFont : skin->getFont(); + IGUIFont* font = OverrideFont ? OverrideFont : skin->getFont(); if (!font) return; // get text dimension const u32 lineCount = (WordWrap || MultiLine) ? BrokenText.size() : 1; - if (WordWrap || MultiLine) { + if (WordWrap || MultiLine) + { d = font->getDimension(BrokenText[line].c_str()); - } else { + } + else + { d = font->getDimension(Text.c_str()); d.Height = AbsoluteRect.getHeight(); } d.Height += font->getKerningHeight(); // justification - switch (HAlign) { + switch (HAlign) + { case EGUIA_CENTER: // align to h centre - CurrentTextRect.UpperLeftCorner.X = - (FrameRect.getWidth() / 2) - (d.Width / 2); - CurrentTextRect.LowerRightCorner.X = - (FrameRect.getWidth() / 2) + (d.Width / 2); + CurrentTextRect.UpperLeftCorner.X = (FrameRect.getWidth()/2) - (d.Width/2); + CurrentTextRect.LowerRightCorner.X = (FrameRect.getWidth()/2) + (d.Width/2); break; case EGUIA_LOWERRIGHT: // align to right edge @@ -1254,77 +1295,82 @@ void intlGUIEditBox::setTextRect(s32 line) // align to left edge CurrentTextRect.UpperLeftCorner.X = 0; CurrentTextRect.LowerRightCorner.X = d.Width; + } - switch (VAlign) { + switch (VAlign) + { case EGUIA_CENTER: // align to v centre - CurrentTextRect.UpperLeftCorner.Y = (FrameRect.getHeight() / 2) - - (lineCount * d.Height) / 2 + - d.Height * line; + CurrentTextRect.UpperLeftCorner.Y = + (FrameRect.getHeight()/2) - (lineCount*d.Height)/2 + d.Height*line; break; case EGUIA_LOWERRIGHT: // align to bottom edge - CurrentTextRect.UpperLeftCorner.Y = FrameRect.getHeight() - - lineCount * d.Height + - d.Height * line; + CurrentTextRect.UpperLeftCorner.Y = + FrameRect.getHeight() - lineCount*d.Height + d.Height*line; break; default: // align to top edge - CurrentTextRect.UpperLeftCorner.Y = d.Height * line; + CurrentTextRect.UpperLeftCorner.Y = d.Height*line; break; } - CurrentTextRect.UpperLeftCorner.X -= HScrollPos; + CurrentTextRect.UpperLeftCorner.X -= HScrollPos; CurrentTextRect.LowerRightCorner.X -= HScrollPos; - CurrentTextRect.UpperLeftCorner.Y -= VScrollPos; + CurrentTextRect.UpperLeftCorner.Y -= VScrollPos; CurrentTextRect.LowerRightCorner.Y = CurrentTextRect.UpperLeftCorner.Y + d.Height; CurrentTextRect += FrameRect.UpperLeftCorner; + } + s32 intlGUIEditBox::getLineFromPos(s32 pos) { if (!WordWrap && !MultiLine) return 0; - s32 i = 0; - while (i < (s32)BrokenTextPositions.size()) { + s32 i=0; + while (i < (s32)BrokenTextPositions.size()) + { if (BrokenTextPositions[i] > pos) - return i - 1; + return i-1; ++i; } return (s32)BrokenTextPositions.size() - 1; } + void intlGUIEditBox::inputChar(wchar_t c) { if (!IsEnabled || !m_writable) return; - if (c != 0) { - if (Text.size() < Max || Max == 0) { + if (c != 0) + { + if (Text.size() < Max || Max == 0) + { core::stringw s; - if (MarkBegin != MarkEnd) { + if (MarkBegin != MarkEnd) + { // replace marked text - const s32 realmbgn = - MarkBegin < MarkEnd ? MarkBegin : MarkEnd; - const s32 realmend = - MarkBegin < MarkEnd ? MarkEnd : MarkBegin; + const s32 realmbgn = MarkBegin < MarkEnd ? MarkBegin : MarkEnd; + const s32 realmend = MarkBegin < MarkEnd ? MarkEnd : MarkBegin; s = Text.subString(0, realmbgn); s.append(c); - s.append(Text.subString( - realmend, Text.size() - realmend)); + s.append( Text.subString(realmend, Text.size()-realmend) ); Text = s; - CursorPos = realmbgn + 1; - } else { + CursorPos = realmbgn+1; + } + else + { // add new character s = Text.subString(0, CursorPos); s.append(c); - s.append(Text.subString( - CursorPos, Text.size() - CursorPos)); + s.append( Text.subString(CursorPos, Text.size()-CursorPos) ); Text = s; ++CursorPos; } @@ -1338,6 +1384,7 @@ void intlGUIEditBox::inputChar(wchar_t c) calculateScrollPos(); } + void intlGUIEditBox::calculateScrollPos() { if (!AutoScroll) @@ -1348,22 +1395,21 @@ void intlGUIEditBox::calculateScrollPos() setTextRect(cursLine); // don't do horizontal scrolling when wordwrap is enabled. - if (!WordWrap) { + if (!WordWrap) + { // get cursor position - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (!skin) return; - IGUIFont *font = OverrideFont ? OverrideFont : skin->getFont(); + IGUIFont* font = OverrideFont ? OverrideFont : skin->getFont(); if (!font) return; core::stringw *txtLine = MultiLine ? &BrokenText[cursLine] : &Text; - s32 cPos = MultiLine ? CursorPos - BrokenTextPositions[cursLine] - : CursorPos; + s32 cPos = MultiLine ? CursorPos - BrokenTextPositions[cursLine] : CursorPos; s32 cStart = CurrentTextRect.UpperLeftCorner.X + HScrollPos + - font->getDimension(txtLine->subString(0, cPos).c_str()) - .Width; + font->getDimension(txtLine->subString(0, cPos).c_str()).Width; s32 cEnd = cStart + font->getDimension(L"_ ").Width; @@ -1382,11 +1428,9 @@ void intlGUIEditBox::calculateScrollPos() // vertical scroll position if (FrameRect.LowerRightCorner.Y < CurrentTextRect.LowerRightCorner.Y) - VScrollPos += CurrentTextRect.LowerRightCorner.Y - - FrameRect.LowerRightCorner.Y; // scrolling downwards + VScrollPos += CurrentTextRect.LowerRightCorner.Y - FrameRect.LowerRightCorner.Y; // scrolling downwards else if (FrameRect.UpperLeftCorner.Y > CurrentTextRect.UpperLeftCorner.Y) - VScrollPos += CurrentTextRect.UpperLeftCorner.Y - - FrameRect.UpperLeftCorner.Y; // scrolling upwards + VScrollPos += CurrentTextRect.UpperLeftCorner.Y - FrameRect.UpperLeftCorner.Y; // scrolling upwards // todo: adjust scrollbar if (m_vscrollbar) @@ -1396,24 +1440,26 @@ void intlGUIEditBox::calculateScrollPos() //! set text markers void intlGUIEditBox::setTextMarkers(s32 begin, s32 end) { - if (begin != MarkBegin || end != MarkEnd) { - MarkBegin = begin; - MarkEnd = end; - sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED); - } + if ( begin != MarkBegin || end != MarkEnd ) + { + MarkBegin = begin; + MarkEnd = end; + sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED); + } } //! send some gui event to parent void intlGUIEditBox::sendGuiEvent(EGUI_EVENT_TYPE type) { - if (Parent) { - SEvent e; - e.EventType = EET_GUI_EVENT; - e.GUIEvent.Caller = this; - e.GUIEvent.Element = 0; - e.GUIEvent.EventType = type; - - Parent->OnEvent(e); + if ( Parent ) + { + SEvent e; + e.EventType = EET_GUI_EVENT; + e.GUIEvent.Caller = this; + e.GUIEvent.Element = 0; + e.GUIEvent.EventType = type; + + Parent->OnEvent(e); } } @@ -1425,8 +1471,8 @@ void intlGUIEditBox::createVScrollBar() if (OverrideFont) { fontHeight = OverrideFont->getDimension(L"").Height; } else { - if (IGUISkin *skin = Environment->getSkin()) { - if (IGUIFont *font = skin->getFont()) { + if (IGUISkin* skin = Environment->getSkin()) { + if (IGUIFont* font = skin->getFont()) { fontHeight = font->getDimension(L"").Height; } } @@ -1436,8 +1482,8 @@ void intlGUIEditBox::createVScrollBar() irr::core::rect scrollbarrect = FrameRect; scrollbarrect.UpperLeftCorner.X += FrameRect.getWidth() - m_scrollbar_width; - m_vscrollbar = new GUIScrollBar( - Environment, getParent(), -1, scrollbarrect, false, true); + m_vscrollbar = new GUIScrollBar(Environment, getParent(), -1, + scrollbarrect, false, true); m_vscrollbar->setVisible(false); m_vscrollbar->setSmallStep(3 * fontHeight); @@ -1469,7 +1515,7 @@ void intlGUIEditBox::updateVScrollBar() } // check if a vertical scrollbar is needed ? - if (getTextDimension().Height > (u32)FrameRect.getHeight()) { + if (getTextDimension().Height > (u32) FrameRect.getHeight()) { s32 scrollymax = getTextDimension().Height - FrameRect.getHeight(); if (scrollymax != m_vscrollbar->getMax()) { m_vscrollbar->setMax(scrollymax); @@ -1500,34 +1546,33 @@ void intlGUIEditBox::setWritable(bool can_write_text) } //! Writes attributes of the element. -void intlGUIEditBox::serializeAttributes( - io::IAttributes *out, io::SAttributeReadWriteOptions *options = 0) const +void intlGUIEditBox::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const { // IGUIEditBox::serializeAttributes(out,options); - out->addBool("OverrideColorEnabled", OverrideColorEnabled); - out->addColor("OverrideColor", OverrideColor); + out->addBool ("OverrideColorEnabled",OverrideColorEnabled ); + out->addColor ("OverrideColor", OverrideColor); // out->addFont("OverrideFont",OverrideFont); - out->addInt("MaxChars", Max); - out->addBool("WordWrap", WordWrap); - out->addBool("MultiLine", MultiLine); - out->addBool("AutoScroll", AutoScroll); - out->addBool("PasswordBox", PasswordBox); + out->addInt ("MaxChars", Max); + out->addBool ("WordWrap", WordWrap); + out->addBool ("MultiLine", MultiLine); + out->addBool ("AutoScroll", AutoScroll); + out->addBool ("PasswordBox", PasswordBox); core::stringw ch = L" "; ch[0] = PasswordChar; - out->addString("PasswordChar", ch.c_str()); - out->addEnum("HTextAlign", HAlign, GUIAlignmentNames); - out->addEnum("VTextAlign", VAlign, GUIAlignmentNames); - out->addBool("Writable", m_writable); + out->addString("PasswordChar", ch.c_str()); + out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); + out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); + out->addBool ("Writable", m_writable); - IGUIEditBox::serializeAttributes(out, options); + IGUIEditBox::serializeAttributes(out,options); } + //! Reads attributes of the element -void intlGUIEditBox::deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0) +void intlGUIEditBox::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { - IGUIEditBox::deserializeAttributes(in, options); + IGUIEditBox::deserializeAttributes(in,options); setOverrideColor(in->getAttributeAsColor("OverrideColor")); enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); @@ -1542,14 +1587,13 @@ void intlGUIEditBox::deserializeAttributes( else setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]); - setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration( - "HTextAlign", GUIAlignmentNames), - (EGUI_ALIGNMENT)in->getAttributeAsEnumeration( - "VTextAlign", GUIAlignmentNames)); + setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), + (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); setWritable(in->getAttributeAsBool("Writable")); // setOverrideFont(in->getAttributeAsFont("OverrideFont")); } + } // end namespace gui } // end namespace irr diff --git a/src/gui/intlGUIEditBox.h b/src/gui/intlGUIEditBox.h index 7b5f015fd..9d643495e 100644 --- a/src/gui/intlGUIEditBox.h +++ b/src/gui/intlGUIEditBox.h @@ -16,193 +16,193 @@ namespace irr { namespace gui { -class intlGUIEditBox : public IGUIEditBox -{ -public: - //! constructor - intlGUIEditBox(const wchar_t *text, bool border, IGUIEnvironment *environment, - IGUIElement *parent, s32 id, const core::rect &rectangle, + class intlGUIEditBox : public IGUIEditBox + { + public: + + //! constructor + intlGUIEditBox(const wchar_t* text, bool border, IGUIEnvironment* environment, + IGUIElement* parent, s32 id, const core::rect& rectangle, bool writable = true, bool has_vscrollbar = false); - //! destructor - virtual ~intlGUIEditBox(); + //! destructor + virtual ~intlGUIEditBox(); + + //! Sets another skin independent font. + virtual void setOverrideFont(IGUIFont* font=0); + + //! Gets the override font (if any) + /** \return The override font (may be 0) */ + virtual IGUIFont* getOverrideFont() const; + + //! Get the font which is used right now for drawing + /** Currently this is the override font when one is set and the + font of the active skin otherwise */ + virtual IGUIFont* getActiveFont() const; + + //! Sets another color for the text. + virtual void setOverrideColor(video::SColor color); + + //! Gets the override color + virtual video::SColor getOverrideColor() const; + + //! Sets if the text should use the overide color or the + //! color in the gui skin. + virtual void enableOverrideColor(bool enable); + + //! Checks if an override color is enabled + /** \return true if the override color is enabled, false otherwise */ + virtual bool isOverrideColorEnabled(void) const; + + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw); + + virtual bool isDrawBackgroundEnabled() const { return true; } + + //! Turns the border on or off + virtual void setDrawBorder(bool border); + + virtual bool isDrawBorderEnabled() const { return Border; } + + //! Enables or disables word wrap for using the edit box as multiline text editor. + virtual void setWordWrap(bool enable); + + //! Checks if word wrap is enabled + //! \return true if word wrap is enabled, false otherwise + virtual bool isWordWrapEnabled() const; + + //! Enables or disables newlines. + /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, + instead a newline character will be inserted. */ + virtual void setMultiLine(bool enable); - //! Sets another skin independent font. - virtual void setOverrideFont(IGUIFont *font = 0); + //! Checks if multi line editing is enabled + //! \return true if mult-line is enabled, false otherwise + virtual bool isMultiLineEnabled() const; - //! Gets the override font (if any) - /** \return The override font (may be 0) */ - virtual IGUIFont *getOverrideFont() const; + //! Enables or disables automatic scrolling with cursor position + //! \param enable: If set to true, the text will move around with the cursor position + virtual void setAutoScroll(bool enable); - //! Get the font which is used right now for drawing - /** Currently this is the override font when one is set and the - font of the active skin otherwise */ - virtual IGUIFont *getActiveFont() const; + //! Checks to see if automatic scrolling is enabled + //! \return true if automatic scrolling is enabled, false if not + virtual bool isAutoScrollEnabled() const; - //! Sets another color for the text. - virtual void setOverrideColor(video::SColor color); + //! Gets the size area of the text in the edit box + //! \return Returns the size in pixels of the text + virtual core::dimension2du getTextDimension(); - //! Gets the override color - virtual video::SColor getOverrideColor() const; + //! Sets text justification + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); - //! Sets if the text should use the overide color or the - //! color in the gui skin. - virtual void enableOverrideColor(bool enable); + //! called if an event happened. + virtual bool OnEvent(const SEvent& event); - //! Checks if an override color is enabled - /** \return true if the override color is enabled, false otherwise */ - virtual bool isOverrideColorEnabled(void) const; + //! draws the element and its children + virtual void draw(); - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw); + //! Sets the new caption of this element. + virtual void setText(const wchar_t* text); - virtual bool isDrawBackgroundEnabled() const { return true; } + //! Sets the maximum amount of characters which may be entered in the box. + //! \param max: Maximum amount of characters. If 0, the character amount is + //! infinity. + virtual void setMax(u32 max); - //! Turns the border on or off - virtual void setDrawBorder(bool border); + //! Returns maximum amount of characters, previously set by setMax(); + virtual u32 getMax() const; - virtual bool isDrawBorderEnabled() const { return Border; } + //! Sets whether the edit box is a password box. Setting this to true will + /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x + \param passwordBox: true to enable password, false to disable + \param passwordChar: the character that is displayed instead of letters */ + virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*'); - //! Enables or disables word wrap for using the edit box as multiline text editor. - virtual void setWordWrap(bool enable); + //! Returns true if the edit box is currently a password box. + virtual bool isPasswordBox() const; - //! Checks if word wrap is enabled - //! \return true if word wrap is enabled, false otherwise - virtual bool isWordWrapEnabled() const; + //! Updates the absolute position, splits text if required + virtual void updateAbsolutePosition(); - //! Enables or disables newlines. - /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, - instead a newline character will be inserted. */ - virtual void setMultiLine(bool enable); + //! set true if this EditBox is writable + virtual void setWritable(bool can_write_text); - //! Checks if multi line editing is enabled - //! \return true if mult-line is enabled, false otherwise - virtual bool isMultiLineEnabled() const; + //! Writes attributes of the element. + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; - //! Enables or disables automatic scrolling with cursor position - //! \param enable: If set to true, the text will move around with the cursor - //! position - virtual void setAutoScroll(bool enable); + //! Reads attributes of the element + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); - //! Checks to see if automatic scrolling is enabled - //! \return true if automatic scrolling is enabled, false if not - virtual bool isAutoScrollEnabled() const; + virtual void setCursorChar(const wchar_t cursorChar) {} - //! Gets the size area of the text in the edit box - //! \return Returns the size in pixels of the text - virtual core::dimension2du getTextDimension(); + virtual wchar_t getCursorChar() const { return L'|'; } - //! Sets text justification - virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); + virtual void setCursorBlinkTime(u32 timeMs) {} - //! called if an event happened. - virtual bool OnEvent(const SEvent &event); + virtual u32 getCursorBlinkTime() const { return 500; } - //! draws the element and its children - virtual void draw(); + protected: + //! Breaks the single text line. + void breakText(); + //! sets the area of the given line + void setTextRect(s32 line); + //! returns the line number that the cursor is on + s32 getLineFromPos(s32 pos); + //! adds a letter to the edit box + void inputChar(wchar_t c); + //! calculates the current scroll position + void calculateScrollPos(); + //! send some gui event to parent + void sendGuiEvent(EGUI_EVENT_TYPE type); + //! set text markers + void setTextMarkers(s32 begin, s32 end); - //! Sets the new caption of this element. - virtual void setText(const wchar_t *text); + bool processKey(const SEvent& event); + bool processMouse(const SEvent& event); + s32 getCursorPos(s32 x, s32 y); - //! Sets the maximum amount of characters which may be entered in the box. - //! \param max: Maximum amount of characters. If 0, the character amount is - //! infinity. - virtual void setMax(u32 max); + //! Create a vertical scrollbar + void createVScrollBar(); - //! Returns maximum amount of characters, previously set by setMax(); - virtual u32 getMax() const; + //! Update the vertical scrollbar (visibilty & scroll position) + void updateVScrollBar(); - //! Sets whether the edit box is a password box. Setting this to true will - /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x - \param passwordBox: true to enable password, false to disable - \param passwordChar: the character that is displayed instead of letters */ - virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*'); + bool MouseMarking = false; + bool Border; + bool OverrideColorEnabled = false; + s32 MarkBegin = 0; + s32 MarkEnd = 0; - //! Returns true if the edit box is currently a password box. - virtual bool isPasswordBox() const; + video::SColor OverrideColor = video::SColor(101,255,255,255); + gui::IGUIFont *OverrideFont = nullptr; + gui::IGUIFont *LastBreakFont = nullptr; + IOSOperator *Operator = nullptr; - //! Updates the absolute position, splits text if required - virtual void updateAbsolutePosition(); + u64 BlinkStartTime = 0; + s32 CursorPos = 0; + s32 HScrollPos = 0; + s32 VScrollPos = 0; // scroll position in characters + u32 Max = 0; - //! set true if this EditBox is writable - virtual void setWritable(bool can_write_text); + bool WordWrap = false; + bool MultiLine = false; + bool AutoScroll = true; + bool PasswordBox = false; + wchar_t PasswordChar = L'*'; + EGUI_ALIGNMENT HAlign = EGUIA_UPPERLEFT; + EGUI_ALIGNMENT VAlign = EGUIA_CENTER; - //! Writes attributes of the element. - virtual void serializeAttributes(io::IAttributes *out, - io::SAttributeReadWriteOptions *options) const; - - //! Reads attributes of the element - virtual void deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options); - - virtual void setCursorChar(const wchar_t cursorChar) {} + core::array BrokenText; + core::array BrokenTextPositions; - virtual wchar_t getCursorChar() const { return L'|'; } + core::rect CurrentTextRect = core::rect(0,0,1,1); + core::rect FrameRect; // temporary values + u32 m_scrollbar_width; + GUIScrollBar *m_vscrollbar; + bool m_writable; - virtual void setCursorBlinkTime(u32 timeMs) {} + }; - virtual u32 getCursorBlinkTime() const { return 500; } - -protected: - //! Breaks the single text line. - void breakText(); - //! sets the area of the given line - void setTextRect(s32 line); - //! returns the line number that the cursor is on - s32 getLineFromPos(s32 pos); - //! adds a letter to the edit box - void inputChar(wchar_t c); - //! calculates the current scroll position - void calculateScrollPos(); - //! send some gui event to parent - void sendGuiEvent(EGUI_EVENT_TYPE type); - //! set text markers - void setTextMarkers(s32 begin, s32 end); - - bool processKey(const SEvent &event); - bool processMouse(const SEvent &event); - s32 getCursorPos(s32 x, s32 y); - - //! Create a vertical scrollbar - void createVScrollBar(); - - //! Update the vertical scrollbar (visibilty & scroll position) - void updateVScrollBar(); - - bool MouseMarking = false; - bool Border; - bool OverrideColorEnabled = false; - s32 MarkBegin = 0; - s32 MarkEnd = 0; - - video::SColor OverrideColor = video::SColor(101, 255, 255, 255); - gui::IGUIFont *OverrideFont = nullptr; - gui::IGUIFont *LastBreakFont = nullptr; - IOSOperator *Operator = nullptr; - - u64 BlinkStartTime = 0; - s32 CursorPos = 0; - s32 HScrollPos = 0; - s32 VScrollPos = 0; // scroll position in characters - u32 Max = 0; - - bool WordWrap = false; - bool MultiLine = false; - bool AutoScroll = true; - bool PasswordBox = false; - wchar_t PasswordChar = L'*'; - EGUI_ALIGNMENT HAlign = EGUIA_UPPERLEFT; - EGUI_ALIGNMENT VAlign = EGUIA_CENTER; - - core::array BrokenText; - core::array BrokenTextPositions; - - core::rect CurrentTextRect = core::rect(0, 0, 1, 1); - core::rect FrameRect; // temporary values - u32 m_scrollbar_width; - GUIScrollBar *m_vscrollbar; - bool m_writable; -}; } // end namespace gui } // end namespace irr diff --git a/src/gui/mainmenumanager.h b/src/gui/mainmenumanager.h index e2107ab64..102492255 100644 --- a/src/gui/mainmenumanager.h +++ b/src/gui/mainmenumanager.h @@ -54,7 +54,7 @@ class MainMenuManager : public IMenuManager } #endif - if (!m_stack.empty()) + if(!m_stack.empty()) m_stack.back()->setVisible(false); m_stack.push_back(menu); } @@ -68,32 +68,35 @@ class MainMenuManager : public IMenuManager assert(*i == menu); m_stack.erase(i);*/ - if (!m_stack.empty()) + if(!m_stack.empty()) m_stack.back()->setVisible(true); } // Returns true to prevent further processing - virtual bool preprocessEvent(const SEvent &event) + virtual bool preprocessEvent(const SEvent& event) { if (m_stack.empty()) return false; - GUIModalMenu *mm = dynamic_cast(m_stack.back()); + GUIModalMenu *mm = dynamic_cast(m_stack.back()); return mm && mm->preprocessEvent(event); } - u32 menuCount() { return m_stack.size(); } + u32 menuCount() + { + return m_stack.size(); + } bool pausesGame() { for (gui::IGUIElement *i : m_stack) { - GUIModalMenu *mm = dynamic_cast(i); + GUIModalMenu *mm = dynamic_cast(i); if (mm && mm->pausesGame()) return true; } return false; } - std::list m_stack; + std::list m_stack; }; extern MainMenuManager g_menumgr; @@ -106,17 +109,36 @@ class MainGameCallback : public IGameCallback MainGameCallback() = default; virtual ~MainGameCallback() = default; - virtual void exitToOS() { shutdown_requested = true; } + virtual void exitToOS() + { + shutdown_requested = true; + } - virtual void disconnect() { disconnect_requested = true; } + virtual void disconnect() + { + disconnect_requested = true; + } - virtual void changePassword() { changepassword_requested = true; } + virtual void changePassword() + { + changepassword_requested = true; + } - virtual void changeVolume() { changevolume_requested = true; } + virtual void changeVolume() + { + changevolume_requested = true; + } - virtual void keyConfig() { keyconfig_requested = true; } + virtual void keyConfig() + { + keyconfig_requested = true; + } + + virtual void signalKeyConfigChange() + { + keyconfig_changed = true; + } - virtual void signalKeyConfigChange() { keyconfig_changed = true; } bool disconnect_requested = false; bool changepassword_requested = false; diff --git a/src/gui/modalMenu.h b/src/gui/modalMenu.h index 3fc9124ea..1cb687f82 100644 --- a/src/gui/modalMenu.h +++ b/src/gui/modalMenu.h @@ -38,8 +38,8 @@ class IMenuManager class GUIModalMenu : public gui::IGUIElement { public: - GUIModalMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, - IMenuManager *menumgr, bool remap_dbl_click = true); + GUIModalMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, bool remap_dbl_click = true); virtual ~GUIModalMenu(); void allowFocusRemoval(bool allow); @@ -70,7 +70,7 @@ class GUIModalMenu : public gui::IGUIElement bool DoubleClickDetection(const SEvent &event); v2s32 m_pointer; - v2s32 m_old_pointer; // Mouse position after previous mouse event + v2s32 m_old_pointer; // Mouse position after previous mouse event v2u32 m_screensize_old; float m_gui_scale; #ifdef __ANDROID__ @@ -92,7 +92,7 @@ class GUIModalMenu : public gui::IGUIElement IMenuManager *m_menumgr; /* If true, remap a double-click (or double-tap) action to ESC. This is so * that, for example, Android users can double-tap to close a formspec. - * + * * This value can (currently) only be set by the class constructor * and the default value for the setting is true. */ diff --git a/src/gui/touchscreengui.cpp b/src/gui/touchscreengui.cpp index 1f9da71c9..0d64aa618 100644 --- a/src/gui/touchscreengui.cpp +++ b/src/gui/touchscreengui.cpp @@ -36,75 +36,82 @@ with this program; if not, write to the Free Software Foundation, Inc., using namespace irr::core; -const char **button_imagenames = - (const char *[]){"jump_btn.png", "down.png", "zoom.png", "aux_btn.png"}; - -const char **joystick_imagenames = (const char *[]){ - "joystick_off.png", "joystick_bg.png", "joystick_center.png"}; +const char **button_imagenames = (const char *[]) { + "jump_btn.png", + "down.png", + "zoom.png", + "aux_btn.png" +}; + +const char **joystick_imagenames = (const char *[]) { + "joystick_off.png", + "joystick_bg.png", + "joystick_center.png" +}; static irr::EKEY_CODE id2keycode(touch_gui_button_id id) { std::string key = ""; switch (id) { - case forward_id: - key = "forward"; - break; - case left_id: - key = "left"; - break; - case right_id: - key = "right"; - break; - case backward_id: - key = "backward"; - break; - case inventory_id: - key = "inventory"; - break; - case drop_id: - key = "drop"; - break; - case jump_id: - key = "jump"; - break; - case crunch_id: - key = "sneak"; - break; - case zoom_id: - key = "zoom"; - break; - case special1_id: - key = "special1"; - break; - case fly_id: - key = "freemove"; - break; - case noclip_id: - key = "noclip"; - break; - case fast_id: - key = "fastmove"; - break; - case debug_id: - key = "toggle_debug"; - break; - case toggle_chat_id: - key = "toggle_chat"; - break; - case minimap_id: - key = "minimap"; - break; - case chat_id: - key = "chat"; - break; - case camera_id: - key = "camera_mode"; - break; - case range_id: - key = "rangeselect"; - break; - default: - break; + case forward_id: + key = "forward"; + break; + case left_id: + key = "left"; + break; + case right_id: + key = "right"; + break; + case backward_id: + key = "backward"; + break; + case inventory_id: + key = "inventory"; + break; + case drop_id: + key = "drop"; + break; + case jump_id: + key = "jump"; + break; + case crunch_id: + key = "sneak"; + break; + case zoom_id: + key = "zoom"; + break; + case special1_id: + key = "special1"; + break; + case fly_id: + key = "freemove"; + break; + case noclip_id: + key = "noclip"; + break; + case fast_id: + key = "fastmove"; + break; + case debug_id: + key = "toggle_debug"; + break; + case toggle_chat_id: + key = "toggle_chat"; + break; + case minimap_id: + key = "minimap"; + break; + case chat_id: + key = "chat"; + break; + case camera_id: + key = "camera_mode"; + break; + case range_id: + key = "rangeselect"; + break; + default: + break; } assert(!key.empty()); return keyname_to_keycode(g_settings->get("keymap_" + key).c_str()); @@ -113,18 +120,16 @@ static irr::EKEY_CODE id2keycode(touch_gui_button_id id) TouchScreenGUI *g_touchscreengui; static void load_button_texture(button_info *btn, const char *path, - const rect &button_rect, ISimpleTextureSource *tsrc, - video::IVideoDriver *driver) + const rect &button_rect, ISimpleTextureSource *tsrc, video::IVideoDriver *driver) { unsigned int tid; - video::ITexture *texture = - guiScalingImageButton(driver, tsrc->getTexture(path, &tid), - button_rect.getWidth(), button_rect.getHeight()); + video::ITexture *texture = guiScalingImageButton(driver, + tsrc->getTexture(path, &tid), button_rect.getWidth(), + button_rect.getHeight()); if (texture) { btn->guibutton->setUseAlphaChannel(true); if (g_settings->getBool("gui_scaling_filter")) { - rect txr_rect = rect(0, 0, button_rect.getWidth(), - button_rect.getHeight()); + rect txr_rect = rect(0, 0, button_rect.getWidth(), button_rect.getHeight()); btn->guibutton->setImage(texture, txr_rect); btn->guibutton->setPressedImage(texture, txr_rect); btn->guibutton->setScaleImage(false); @@ -138,15 +143,17 @@ static void load_button_texture(button_info *btn, const char *path, } } -AutoHideButtonBar::AutoHideButtonBar(IrrlichtDevice *device, IEventReceiver *receiver) : - m_driver(device->getVideoDriver()), m_guienv(device->getGUIEnvironment()), - m_receiver(receiver) +AutoHideButtonBar::AutoHideButtonBar(IrrlichtDevice *device, + IEventReceiver *receiver) : + m_driver(device->getVideoDriver()), + m_guienv(device->getGUIEnvironment()), + m_receiver(receiver) { } -void AutoHideButtonBar::init(ISimpleTextureSource *tsrc, const char *starter_img, - int button_id, const v2s32 &UpperLeft, const v2s32 &LowerRight, - autohide_button_bar_dir dir, float timeout) +void AutoHideButtonBar::init(ISimpleTextureSource *tsrc, + const char *starter_img, int button_id, const v2s32 &UpperLeft, + const v2s32 &LowerRight, autohide_button_bar_dir dir, float timeout) { m_texturesource = tsrc; @@ -155,19 +162,18 @@ void AutoHideButtonBar::init(ISimpleTextureSource *tsrc, const char *starter_img // init settings bar - irr::core::rect current_button = - rect(UpperLeft.X, UpperLeft.Y, LowerRight.X, LowerRight.Y); + irr::core::rect current_button = rect(UpperLeft.X, UpperLeft.Y, + LowerRight.X, LowerRight.Y); - m_starter.guibutton = m_guienv->addButton( - current_button, nullptr, button_id, L"", nullptr); + m_starter.guibutton = m_guienv->addButton(current_button, nullptr, button_id, L"", nullptr); m_starter.guibutton->grab(); - m_starter.repeatcounter = -1; - m_starter.keycode = KEY_OEM_8; // use invalid keycode as it's not relevant + m_starter.repeatcounter = -1; + m_starter.keycode = KEY_OEM_8; // use invalid keycode as it's not relevant m_starter.immediate_release = true; m_starter.ids.clear(); - load_button_texture(&m_starter, starter_img, current_button, m_texturesource, - m_driver); + load_button_texture(&m_starter, starter_img, current_button, + m_texturesource, m_driver); m_dir = dir; m_timeout_value = timeout; @@ -183,13 +189,13 @@ AutoHideButtonBar::~AutoHideButtonBar() } } -void AutoHideButtonBar::addButton(touch_gui_button_id button_id, const wchar_t *caption, - const char *btn_image) +void AutoHideButtonBar::addButton(touch_gui_button_id button_id, + const wchar_t *caption, const char *btn_image) { if (!m_initialized) { errorstream << "AutoHideButtonBar::addButton not yet initialized!" - << std::endl; + << std::endl; return; } int button_size = 0; @@ -206,55 +212,55 @@ void AutoHideButtonBar::addButton(touch_gui_button_id button_id, const wchar_t * int x_end = 0; if (m_dir == AHBB_Dir_Left_Right) { - x_start = m_lower_right.X + - (button_size * 1.25 * m_buttons.size()) + - (button_size * 0.25); + x_start = m_lower_right.X + (button_size * 1.25 * m_buttons.size()) + + (button_size * 0.25); x_end = x_start + button_size; } else { - x_end = m_upper_left.X - (button_size * 1.25 * m_buttons.size()) - - (button_size * 0.25); + x_end = m_upper_left.X - (button_size * 1.25 * m_buttons.size()) + - (button_size * 0.25); x_start = x_end - button_size; } - current_button = rect( - x_start, m_upper_left.Y, x_end, m_lower_right.Y); + current_button = rect(x_start, m_upper_left.Y, x_end, + m_lower_right.Y); } else { double y_start = 0; double y_end = 0; if (m_dir == AHBB_Dir_Top_Bottom) { - y_start = m_lower_right.X + - (button_size * 1.25 * m_buttons.size()) + - (button_size * 0.25); + y_start = m_lower_right.X + (button_size * 1.25 * m_buttons.size()) + + (button_size * 0.25); y_end = y_start + button_size; } else { - y_end = m_upper_left.X - (button_size * 1.25 * m_buttons.size()) - - (button_size * 0.25); + y_end = m_upper_left.X - (button_size * 1.25 * m_buttons.size()) + - (button_size * 0.25); y_start = y_end - button_size; } - current_button = rect( - m_upper_left.X, y_start, m_lower_right.Y, y_end); + current_button = rect(m_upper_left.X, y_start, + m_lower_right.Y, y_end); } - auto *btn = new button_info(); - btn->guibutton = m_guienv->addButton( - current_button, nullptr, button_id, caption, nullptr); + auto *btn = new button_info(); + btn->guibutton = m_guienv->addButton(current_button, + nullptr, button_id, caption, nullptr); btn->guibutton->grab(); btn->guibutton->setVisible(false); btn->guibutton->setEnabled(false); - btn->repeatcounter = -1; - btn->keycode = id2keycode(button_id); + btn->repeatcounter = -1; + btn->keycode = id2keycode(button_id); btn->immediate_release = true; btn->ids.clear(); - load_button_texture(btn, btn_image, current_button, m_texturesource, m_driver); + load_button_texture(btn, btn_image, current_button, m_texturesource, + m_driver); m_buttons.push_back(btn); } void AutoHideButtonBar::addToggleButton(touch_gui_button_id button_id, - const wchar_t *caption, const char *btn_image_1, const char *btn_image_2) + const wchar_t *caption, const char *btn_image_1, + const char *btn_image_2) { addButton(button_id, caption, btn_image_1); button_info *btn = m_buttons.back(); @@ -285,11 +291,11 @@ bool AutoHideButtonBar::isButton(const SEvent &event) auto *translated = new SEvent(); memset(translated, 0, sizeof(SEvent)); - translated->EventType = irr::EET_KEY_INPUT_EVENT; - translated->KeyInput.Key = (*iter)->keycode; - translated->KeyInput.Control = false; - translated->KeyInput.Shift = false; - translated->KeyInput.Char = 0; + translated->EventType = irr::EET_KEY_INPUT_EVENT; + translated->KeyInput.Key = (*iter)->keycode; + translated->KeyInput.Control = false; + translated->KeyInput.Shift = false; + translated->KeyInput.Char = 0; // add this event translated->KeyInput.PressedDown = true; @@ -308,14 +314,12 @@ bool AutoHideButtonBar::isButton(const SEvent &event) if ((*iter)->togglable == 1) { (*iter)->togglable = 2; load_button_texture(*iter, (*iter)->textures[1], - (*iter)->guibutton - ->getRelativePosition(), + (*iter)->guibutton->getRelativePosition(), m_texturesource, m_driver); } else if ((*iter)->togglable == 2) { (*iter)->togglable = 1; load_button_texture(*iter, (*iter)->textures[0], - (*iter)->guibutton - ->getRelativePosition(), + (*iter)->guibutton->getRelativePosition(), m_texturesource, m_driver); } @@ -406,41 +410,42 @@ void AutoHideButtonBar::show() } } -TouchScreenGUI::TouchScreenGUI(IrrlichtDevice *device, IEventReceiver *receiver) : - m_device(device), m_guienv(device->getGUIEnvironment()), - m_receiver(receiver), m_settingsbar(device, receiver), - m_rarecontrolsbar(device, receiver) +TouchScreenGUI::TouchScreenGUI(IrrlichtDevice *device, IEventReceiver *receiver): + m_device(device), + m_guienv(device->getGUIEnvironment()), + m_receiver(receiver), + m_settingsbar(device, receiver), + m_rarecontrolsbar(device, receiver) { for (auto &button : m_buttons) { - button.guibutton = nullptr; + button.guibutton = nullptr; button.repeatcounter = -1; - button.repeatdelay = BUTTON_REPEAT_DELAY; + button.repeatdelay = BUTTON_REPEAT_DELAY; } m_touchscreen_threshold = g_settings->getU16("touchscreen_threshold"); m_fixed_joystick = g_settings->getBool("fixed_virtual_joystick"); - m_joystick_triggers_special1 = - g_settings->getBool("virtual_joystick_triggers_aux"); + m_joystick_triggers_special1 = g_settings->getBool("virtual_joystick_triggers_aux"); m_screensize = m_device->getVideoDriver()->getScreenSize(); button_size = MYMIN(m_screensize.Y / 4.5f, porting::getDisplayDensity() * - g_settings->getFloat("hud_scaling") * 65.0f); + g_settings->getFloat("hud_scaling") * 65.0f); } void TouchScreenGUI::initButton(touch_gui_button_id id, const rect &button_rect, const std::wstring &caption, bool immediate_release, float repeat_delay) { - button_info *btn = &m_buttons[id]; - btn->guibutton = m_guienv->addButton(button_rect, nullptr, id, caption.c_str()); + button_info *btn = &m_buttons[id]; + btn->guibutton = m_guienv->addButton(button_rect, nullptr, id, caption.c_str()); btn->guibutton->grab(); - btn->repeatcounter = -1; - btn->repeatdelay = repeat_delay; - btn->keycode = id2keycode(id); + btn->repeatcounter = -1; + btn->repeatdelay = repeat_delay; + btn->keycode = id2keycode(id); btn->immediate_release = immediate_release; btn->ids.clear(); - load_button_texture(btn, button_imagenames[id], button_rect, m_texturesource, - m_device->getVideoDriver()); + load_button_texture(btn, button_imagenames[id], button_rect, + m_texturesource, m_device->getVideoDriver()); } button_info *TouchScreenGUI::initJoystickButton(touch_gui_button_id id, @@ -452,8 +457,8 @@ button_info *TouchScreenGUI::initJoystickButton(touch_gui_button_id id, btn->guibutton->grab(); btn->ids.clear(); - load_button_texture(btn, joystick_imagenames[texture_id], button_rect, - m_texturesource, m_device->getVideoDriver()); + load_button_texture(btn, joystick_imagenames[texture_id], + button_rect, m_texturesource, m_device->getVideoDriver()); return btn; } @@ -462,7 +467,7 @@ void TouchScreenGUI::init(ISimpleTextureSource *tsrc) { assert(tsrc); - m_visible = true; + m_visible = true; m_texturesource = tsrc; /* Init joystick display "button" @@ -470,21 +475,23 @@ void TouchScreenGUI::init(ISimpleTextureSource *tsrc) */ if (m_fixed_joystick) { m_joystick_btn_off = initJoystickButton(joystick_off_id, - rect(button_size, m_screensize.Y - button_size * 4, + rect(button_size, + m_screensize.Y - button_size * 4, button_size * 4, - m_screensize.Y - button_size), - 0); + m_screensize.Y - button_size), 0); } else { m_joystick_btn_off = initJoystickButton(joystick_off_id, - rect(button_size, m_screensize.Y - button_size * 3, + rect(button_size, + m_screensize.Y - button_size * 3, button_size * 3, - m_screensize.Y - button_size), - 0); + m_screensize.Y - button_size), 0); } m_joystick_btn_bg = initJoystickButton(joystick_bg_id, - rect(button_size, m_screensize.Y - button_size * 4, - button_size * 4, m_screensize.Y - button_size), + rect(button_size, + m_screensize.Y - button_size * 4, + button_size * 4, + m_screensize.Y - button_size), 1, false); m_joystick_btn_center = initJoystickButton(joystick_center_id, @@ -524,48 +531,39 @@ void TouchScreenGUI::init(ISimpleTextureSource *tsrc) L"spc1", false); m_settingsbar.init(m_texturesource, "gear_icon.png", settings_starter_id, - v2s32(m_screensize.X - (1.25 * button_size), - m_screensize.Y - - ((SETTINGS_BAR_Y_OFFSET + 1.0) * - button_size) + - (0.5 * button_size)), - v2s32(m_screensize.X - (0.25 * button_size), - m_screensize.Y - - (SETTINGS_BAR_Y_OFFSET * - button_size) + - (0.5 * button_size)), - AHBB_Dir_Right_Left, 3.0); - - m_settingsbar.addButton(fly_id, L"fly", "fly_btn.png"); - m_settingsbar.addButton(noclip_id, L"noclip", "noclip_btn.png"); - m_settingsbar.addButton(fast_id, L"fast", "fast_btn.png"); - m_settingsbar.addButton(debug_id, L"debug", "debug_btn.png"); - m_settingsbar.addButton(camera_id, L"camera", "camera_btn.png"); - m_settingsbar.addButton(range_id, L"rangeview", "rangeview_btn.png"); - m_settingsbar.addButton(minimap_id, L"minimap", "minimap_btn.png"); + v2s32(m_screensize.X - (1.25 * button_size), + m_screensize.Y - ((SETTINGS_BAR_Y_OFFSET + 1.0) * button_size) + + (0.5 * button_size)), + v2s32(m_screensize.X - (0.25 * button_size), + m_screensize.Y - (SETTINGS_BAR_Y_OFFSET * button_size) + + (0.5 * button_size)), + AHBB_Dir_Right_Left, 3.0); + + m_settingsbar.addButton(fly_id, L"fly", "fly_btn.png"); + m_settingsbar.addButton(noclip_id, L"noclip", "noclip_btn.png"); + m_settingsbar.addButton(fast_id, L"fast", "fast_btn.png"); + m_settingsbar.addButton(debug_id, L"debug", "debug_btn.png"); + m_settingsbar.addButton(camera_id, L"camera", "camera_btn.png"); + m_settingsbar.addButton(range_id, L"rangeview", "rangeview_btn.png"); + m_settingsbar.addButton(minimap_id, L"minimap", "minimap_btn.png"); // Chat is shown by default, so chat_hide_btn.png is shown first. - m_settingsbar.addToggleButton(toggle_chat_id, L"togglechat", "chat_hide_btn.png", - "chat_show_btn.png"); + m_settingsbar.addToggleButton(toggle_chat_id, L"togglechat", + "chat_hide_btn.png", "chat_show_btn.png"); m_rarecontrolsbar.init(m_texturesource, "rare_controls.png", - rare_controls_starter_id, - v2s32(0.25 * button_size, - m_screensize.Y - - ((RARE_CONTROLS_BAR_Y_OFFSET + - 1.0) * - button_size) + - (0.5 * button_size)), - v2s32(0.75 * button_size, - m_screensize.Y - - (RARE_CONTROLS_BAR_Y_OFFSET * - button_size) + - (0.5 * button_size)), - AHBB_Dir_Left_Right, 2.0); - - m_rarecontrolsbar.addButton(chat_id, L"Chat", "chat_btn.png"); - m_rarecontrolsbar.addButton(inventory_id, L"inv", "inventory_btn.png"); - m_rarecontrolsbar.addButton(drop_id, L"drop", "drop_btn.png"); + rare_controls_starter_id, + v2s32(0.25 * button_size, + m_screensize.Y - ((RARE_CONTROLS_BAR_Y_OFFSET + 1.0) * button_size) + + (0.5 * button_size)), + v2s32(0.75 * button_size, + m_screensize.Y - (RARE_CONTROLS_BAR_Y_OFFSET * button_size) + + (0.5 * button_size)), + AHBB_Dir_Left_Right, 2.0); + + m_rarecontrolsbar.addButton(chat_id, L"Chat", "chat_btn.png"); + m_rarecontrolsbar.addButton(inventory_id, L"inv", "inventory_btn.png"); + m_rarecontrolsbar.addButton(drop_id, L"drop", "drop_btn.png"); } touch_gui_button_id TouchScreenGUI::getButtonID(s32 x, s32 y) @@ -573,13 +571,13 @@ touch_gui_button_id TouchScreenGUI::getButtonID(s32 x, s32 y) IGUIElement *rootguielement = m_guienv->getRootGUIElement(); if (rootguielement != nullptr) { - gui::IGUIElement *element = rootguielement->getElementFromPoint( - core::position2d(x, y)); + gui::IGUIElement *element = + rootguielement->getElementFromPoint(core::position2d(x, y)); if (element) for (unsigned int i = 0; i < after_last_element_id; i++) if (element == m_buttons[i].guibutton) - return (touch_gui_button_id)i; + return (touch_gui_button_id) i; } return after_last_element_id; @@ -593,7 +591,7 @@ touch_gui_button_id TouchScreenGUI::getButtonID(size_t eventID) auto id = std::find(btn->ids.begin(), btn->ids.end(), eventID); if (id != btn->ids.end()) - return (touch_gui_button_id)i; + return (touch_gui_button_id) i; } return after_last_element_id; @@ -603,18 +601,17 @@ bool TouchScreenGUI::isHUDButton(const SEvent &event) { // check if hud item is pressed for (auto &hud_rect : m_hud_rects) { - if (hud_rect.second.isPointInside( - v2s32(event.TouchInput.X, event.TouchInput.Y))) { + if (hud_rect.second.isPointInside(v2s32(event.TouchInput.X, + event.TouchInput.Y))) { auto *translated = new SEvent(); memset(translated, 0, sizeof(SEvent)); translated->EventType = irr::EET_KEY_INPUT_EVENT; - translated->KeyInput.Key = - (irr::EKEY_CODE)(KEY_KEY_1 + hud_rect.first); - translated->KeyInput.Control = false; - translated->KeyInput.Shift = false; + translated->KeyInput.Key = (irr::EKEY_CODE) (KEY_KEY_1 + hud_rect.first); + translated->KeyInput.Control = false; + translated->KeyInput.Shift = false; translated->KeyInput.PressedDown = true; m_receiver->OnEvent(*translated); - m_hud_ids[event.TouchInput.ID] = translated->KeyInput.Key; + m_hud_ids[event.TouchInput.ID] = translated->KeyInput.Key; delete translated; return true; } @@ -622,27 +619,25 @@ bool TouchScreenGUI::isHUDButton(const SEvent &event) return false; } -void TouchScreenGUI::handleButtonEvent( - touch_gui_button_id button, size_t eventID, bool action) +void TouchScreenGUI::handleButtonEvent(touch_gui_button_id button, + size_t eventID, bool action) { button_info *btn = &m_buttons[button]; auto *translated = new SEvent(); memset(translated, 0, sizeof(SEvent)); - translated->EventType = irr::EET_KEY_INPUT_EVENT; - translated->KeyInput.Key = btn->keycode; - translated->KeyInput.Control = false; - translated->KeyInput.Shift = false; - translated->KeyInput.Char = 0; + translated->EventType = irr::EET_KEY_INPUT_EVENT; + translated->KeyInput.Key = btn->keycode; + translated->KeyInput.Control = false; + translated->KeyInput.Shift = false; + translated->KeyInput.Char = 0; // add this event if (action) { - assert(std::find(btn->ids.begin(), btn->ids.end(), eventID) == - btn->ids.end()); + assert(std::find(btn->ids.begin(), btn->ids.end(), eventID) == btn->ids.end()); btn->ids.push_back(eventID); - if (btn->ids.size() > 1) - return; + if (btn->ids.size() > 1) return; btn->repeatcounter = 0; translated->KeyInput.PressedDown = true; @@ -661,7 +656,7 @@ void TouchScreenGUI::handleButtonEvent( return; translated->KeyInput.PressedDown = false; - btn->repeatcounter = -1; + btn->repeatcounter = -1; m_receiver->OnEvent(*translated); } delete translated; @@ -671,6 +666,7 @@ void TouchScreenGUI::handleReleaseEvent(size_t evt_id) { touch_gui_button_id button = getButtonID(evt_id); + if (button != after_last_element_id) { // handle button events handleButtonEvent(button, evt_id, false); @@ -682,13 +678,13 @@ void TouchScreenGUI::handleReleaseEvent(size_t evt_id) if (m_move_sent_as_mouse_event) { auto *translated = new SEvent; memset(translated, 0, sizeof(SEvent)); - translated->EventType = EET_MOUSE_INPUT_EVENT; - translated->MouseInput.X = m_move_downlocation.X; - translated->MouseInput.Y = m_move_downlocation.Y; - translated->MouseInput.Shift = false; - translated->MouseInput.Control = false; + translated->EventType = EET_MOUSE_INPUT_EVENT; + translated->MouseInput.X = m_move_downlocation.X; + translated->MouseInput.Y = m_move_downlocation.Y; + translated->MouseInput.Shift = false; + translated->MouseInput.Control = false; translated->MouseInput.ButtonStates = 0; - translated->MouseInput.Event = EMIE_LMOUSE_LEFT_UP; + translated->MouseInput.Event = EMIE_LMOUSE_LEFT_UP; m_receiver->OnEvent(*translated); delete translated; } else { @@ -710,11 +706,13 @@ void TouchScreenGUI::handleReleaseEvent(size_t evt_id) m_joystick_btn_bg->guibutton->setVisible(false); m_joystick_btn_center->guibutton->setVisible(false); } else { - infostream << "TouchScreenGUI::translateEvent released unknown button: " - << evt_id << std::endl; + infostream + << "TouchScreenGUI::translateEvent released unknown button: " + << evt_id << std::endl; } - for (auto iter = m_known_ids.begin(); iter != m_known_ids.end(); ++iter) { + for (auto iter = m_known_ids.begin(); + iter != m_known_ids.end(); ++iter) { if (iter->id == evt_id) { m_known_ids.erase(iter); break; @@ -725,8 +723,9 @@ void TouchScreenGUI::handleReleaseEvent(size_t evt_id) void TouchScreenGUI::translateEvent(const SEvent &event) { if (!m_visible) { - infostream << "TouchScreenGUI::translateEvent got event but not visible!" - << std::endl; + infostream + << "TouchScreenGUI::translateEvent got event but not visible!" + << std::endl; return; } @@ -741,8 +740,8 @@ void TouchScreenGUI::translateEvent(const SEvent &event) */ id_status toadd{}; toadd.id = event.TouchInput.ID; - toadd.X = event.TouchInput.X; - toadd.Y = event.TouchInput.Y; + toadd.X = event.TouchInput.X; + toadd.Y = event.TouchInput.Y; m_known_ids.push_back(toadd); size_t eventID = event.TouchInput.ID; @@ -771,67 +770,49 @@ void TouchScreenGUI::translateEvent(const SEvent &event) m_rarecontrolsbar.deactivate(); s32 dxj = event.TouchInput.X - button_size * 5.0f / 2.0f; - s32 dyj = event.TouchInput.Y - m_screensize.Y + - button_size * 5.0f / 2.0f; + s32 dyj = event.TouchInput.Y - m_screensize.Y + button_size * 5.0f / 2.0f; /* Select joystick when left 1/3 of screen dragged or * when joystick tapped (fixed joystick position) */ - if ((m_fixed_joystick && - dxj * dxj + dyj * dyj <= - button_size * button_size * - 1.5 * 1.5) || - (!m_fixed_joystick && - event.TouchInput.X < - m_screensize.X / - 3.0f)) { - // If we don't already have a starting point for joystick - // make this the one. + if ((m_fixed_joystick && dxj * dxj + dyj * dyj <= button_size * button_size * 1.5 * 1.5) || + (!m_fixed_joystick && event.TouchInput.X < m_screensize.X / 3.0f)) { + // If we don't already have a starting point for joystick make this the one. if (m_joystick_id == -1) { - m_joystick_id = event.TouchInput.ID; + m_joystick_id = event.TouchInput.ID; m_joystick_has_really_moved = false; m_joystick_btn_off->guibutton->setVisible(false); m_joystick_btn_bg->guibutton->setVisible(true); - m_joystick_btn_center->guibutton->setVisible( - true); + m_joystick_btn_center->guibutton->setVisible(true); - // If it's a fixed joystick, don't move the - // joystick "button". + // If it's a fixed joystick, don't move the joystick "button". if (!m_fixed_joystick) m_joystick_btn_bg->guibutton->setRelativePosition(v2s32( - event.TouchInput.X - - button_size * 3.0f / - 2.0f, - event.TouchInput.Y - - button_size * 3.0f / - 2.0f)); + event.TouchInput.X - button_size * 3.0f / 2.0f, + event.TouchInput.Y - button_size * 3.0f / 2.0f)); m_joystick_btn_center->guibutton->setRelativePosition(v2s32( - event.TouchInput.X - - button_size / 2.0f, - event.TouchInput.Y - - button_size / 2.0f)); + event.TouchInput.X - button_size / 2.0f, + event.TouchInput.Y - button_size / 2.0f)); } } else { - // If we don't already have a moving point make this the - // moving one. + // If we don't already have a moving point make this the moving one. if (m_move_id == -1) { - m_move_id = event.TouchInput.ID; - m_move_has_really_moved = false; - m_move_downtime = porting::getTimeMs(); - m_move_downlocation = v2s32(event.TouchInput.X, - event.TouchInput.Y); + m_move_id = event.TouchInput.ID; + m_move_has_really_moved = false; + m_move_downtime = porting::getTimeMs(); + m_move_downlocation = v2s32(event.TouchInput.X, event.TouchInput.Y); m_move_sent_as_mouse_event = false; } } } - m_pointerpos[event.TouchInput.ID] = - v2s32(event.TouchInput.X, event.TouchInput.Y); - } else if (event.TouchInput.Event == ETIE_LEFT_UP) { - verbosestream << "Up event for pointerid: " << event.TouchInput.ID - << std::endl; + m_pointerpos[event.TouchInput.ID] = v2s32(event.TouchInput.X, event.TouchInput.Y); + } + else if (event.TouchInput.Event == ETIE_LEFT_UP) { + verbosestream + << "Up event for pointerid: " << event.TouchInput.ID << std::endl; handleReleaseEvent(event.TouchInput.ID); } else { assert(event.TouchInput.Event == ETIE_MOVED); @@ -842,19 +823,13 @@ void TouchScreenGUI::translateEvent(const SEvent &event) if (m_move_id != -1) { if ((event.TouchInput.ID == m_move_id) && - (!m_move_sent_as_mouse_event)) { + (!m_move_sent_as_mouse_event)) { double distance = sqrt( - (m_pointerpos[event.TouchInput.ID].X - - event.TouchInput.X) * - (m_pointerpos[event.TouchInput.ID] - .X - - event.TouchInput.X) + - (m_pointerpos[event.TouchInput.ID].Y - - event.TouchInput.Y) * - (m_pointerpos[event.TouchInput.ID] - .Y - - event.TouchInput.Y)); + (m_pointerpos[event.TouchInput.ID].X - event.TouchInput.X) * + (m_pointerpos[event.TouchInput.ID].X - event.TouchInput.X) + + (m_pointerpos[event.TouchInput.ID].Y - event.TouchInput.Y) * + (m_pointerpos[event.TouchInput.ID].Y - event.TouchInput.Y)); if ((distance > m_touchscreen_threshold) || (m_move_has_really_moved)) { @@ -867,31 +842,25 @@ void TouchScreenGUI::translateEvent(const SEvent &event) s32 dy = Y - m_pointerpos[event.TouchInput.ID].Y; // adapt to similar behaviour as pc screen - double d = g_settings->getFloat( - "mouse_sensitivity") * - 3.0f; + double d = g_settings->getFloat("mouse_sensitivity") * 3.0f; m_camera_yaw_change -= dx * d; - m_camera_pitch = MYMIN( - MYMAX(m_camera_pitch + (dy * d), - -180), - 180); + m_camera_pitch = MYMIN(MYMAX(m_camera_pitch + (dy * d), -180), 180); // update shootline - m_shootline = m_device->getSceneManager() - ->getSceneCollisionManager() - ->getRayFromScreenCoordinates(v2s32( - X, - Y)); + m_shootline = m_device + ->getSceneManager() + ->getSceneCollisionManager() + ->getRayFromScreenCoordinates(v2s32(X, Y)); m_pointerpos[event.TouchInput.ID] = v2s32(X, Y); } } else if ((event.TouchInput.ID == m_move_id) && (m_move_sent_as_mouse_event)) { - m_shootline = m_device->getSceneManager() - ->getSceneCollisionManager() - ->getRayFromScreenCoordinates(v2s32( - event.TouchInput.X, - event.TouchInput.Y)); + m_shootline = m_device + ->getSceneManager() + ->getSceneCollisionManager() + ->getRayFromScreenCoordinates( + v2s32(event.TouchInput.X, event.TouchInput.Y)); } } @@ -909,17 +878,13 @@ void TouchScreenGUI::translateEvent(const SEvent &event) double distance_sq = dx * dx + dy * dy; s32 dxj = event.TouchInput.X - button_size * 5.0f / 2.0f; - s32 dyj = event.TouchInput.Y - m_screensize.Y + - button_size * 5.0f / 2.0f; - bool inside_joystick = (dxj * dxj + dyj * dyj <= - button_size * button_size * 1.5 * 1.5); + s32 dyj = event.TouchInput.Y - m_screensize.Y + button_size * 5.0f / 2.0f; + bool inside_joystick = (dxj * dxj + dyj * dyj <= button_size * button_size * 1.5 * 1.5); if (m_joystick_has_really_moved || - (!m_joystick_has_really_moved && - inside_joystick) || + (!m_joystick_has_really_moved && inside_joystick) || (!m_fixed_joystick && - distance_sq > m_touchscreen_threshold * - m_touchscreen_threshold)) { + distance_sq > m_touchscreen_threshold * m_touchscreen_threshold)) { m_joystick_has_really_moved = true; double distance = sqrt(distance_sq); @@ -931,7 +896,7 @@ void TouchScreenGUI::translateEvent(const SEvent &event) angle = fmod(angle + 180 + 22.5, 360); // reset state before applying - for (bool &joystick_status : m_joystick_status) + for (bool & joystick_status : m_joystick_status) joystick_status = false; if (distance <= m_touchscreen_threshold) { @@ -961,31 +926,20 @@ void TouchScreenGUI::translateEvent(const SEvent &event) if (distance > button_size) { m_joystick_status[j_special1] = true; // move joystick "button" - s32 ndx = button_size * dx / distance - - button_size / 2.0f; - s32 ndy = button_size * dy / distance - - button_size / 2.0f; + s32 ndx = button_size * dx / distance - button_size / 2.0f; + s32 ndy = button_size * dy / distance - button_size / 2.0f; if (m_fixed_joystick) { m_joystick_btn_center->guibutton->setRelativePosition(v2s32( - button_size * 5 / 2 + ndx, - m_screensize.Y - - button_size * 5 / - 2 + - ndy)); + button_size * 5 / 2 + ndx, + m_screensize.Y - button_size * 5 / 2 + ndy)); } else { m_joystick_btn_center->guibutton->setRelativePosition(v2s32( - m_pointerpos[event.TouchInput.ID] - .X + - ndx, - m_pointerpos[event.TouchInput.ID] - .Y + - ndy)); + m_pointerpos[event.TouchInput.ID].X + ndx, + m_pointerpos[event.TouchInput.ID].Y + ndy)); } } else { - m_joystick_btn_center->guibutton - ->setRelativePosition(v2s32( - X - button_size / 2, - Y - button_size / 2)); + m_joystick_btn_center->guibutton->setRelativePosition( + v2s32(X - button_size / 2, Y - button_size / 2)); } } } @@ -1001,23 +955,22 @@ void TouchScreenGUI::handleChangedButton(const SEvent &event) if (m_buttons[i].ids.empty()) continue; - for (auto iter = m_buttons[i].ids.begin(); iter != m_buttons[i].ids.end(); - ++iter) { + for (auto iter = m_buttons[i].ids.begin(); + iter != m_buttons[i].ids.end(); ++iter) { if (event.TouchInput.ID == *iter) { - int current_button_id = getButtonID( - event.TouchInput.X, event.TouchInput.Y); + int current_button_id = + getButtonID(event.TouchInput.X, event.TouchInput.Y); if (current_button_id == i) continue; // remove old button - handleButtonEvent((touch_gui_button_id)i, *iter, false); + handleButtonEvent((touch_gui_button_id) i, *iter, false); if (current_button_id == after_last_element_id) return; - handleButtonEvent((touch_gui_button_id)current_button_id, - *iter, true); + handleButtonEvent((touch_gui_button_id) current_button_id, *iter, true); return; } } @@ -1029,48 +982,48 @@ void TouchScreenGUI::handleChangedButton(const SEvent &event) return; button_info *btn = &m_buttons[current_button_id]; - if (std::find(btn->ids.begin(), btn->ids.end(), event.TouchInput.ID) == - btn->ids.end()) - handleButtonEvent((touch_gui_button_id)current_button_id, + if (std::find(btn->ids.begin(), btn->ids.end(), event.TouchInput.ID) + == btn->ids.end()) + handleButtonEvent((touch_gui_button_id) current_button_id, event.TouchInput.ID, true); } bool TouchScreenGUI::doubleTapDetection() { m_key_events[0].down_time = m_key_events[1].down_time; - m_key_events[0].x = m_key_events[1].x; - m_key_events[0].y = m_key_events[1].y; + m_key_events[0].x = m_key_events[1].x; + m_key_events[0].y = m_key_events[1].y; m_key_events[1].down_time = m_move_downtime; - m_key_events[1].x = m_move_downlocation.X; - m_key_events[1].y = m_move_downlocation.Y; + m_key_events[1].x = m_move_downlocation.X; + m_key_events[1].y = m_move_downlocation.Y; u64 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); if (delta > 400) return false; - double distance = sqrt((m_key_events[0].x - m_key_events[1].x) * - (m_key_events[0].x - m_key_events[1].x) + - (m_key_events[0].y - m_key_events[1].y) * - (m_key_events[0].y - m_key_events[1].y)); + double distance = sqrt( + (m_key_events[0].x - m_key_events[1].x) * + (m_key_events[0].x - m_key_events[1].x) + + (m_key_events[0].y - m_key_events[1].y) * + (m_key_events[0].y - m_key_events[1].y)); if (distance > (20 + m_touchscreen_threshold)) return false; auto *translated = new SEvent(); memset(translated, 0, sizeof(SEvent)); - translated->EventType = EET_MOUSE_INPUT_EVENT; - translated->MouseInput.X = m_key_events[0].x; - translated->MouseInput.Y = m_key_events[0].y; - translated->MouseInput.Shift = false; - translated->MouseInput.Control = false; + translated->EventType = EET_MOUSE_INPUT_EVENT; + translated->MouseInput.X = m_key_events[0].x; + translated->MouseInput.Y = m_key_events[0].y; + translated->MouseInput.Shift = false; + translated->MouseInput.Control = false; translated->MouseInput.ButtonStates = EMBSM_RIGHT; // update shootline - m_shootline = m_device->getSceneManager() - ->getSceneCollisionManager() - ->getRayFromScreenCoordinates( - v2s32(m_key_events[0].x, - m_key_events[0].y)); + m_shootline = m_device + ->getSceneManager() + ->getSceneCollisionManager() + ->getRayFromScreenCoordinates(v2s32(m_key_events[0].x, m_key_events[0].y)); translated->MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN; verbosestream << "TouchScreenGUI::translateEvent right click press" << std::endl; @@ -1078,8 +1031,7 @@ bool TouchScreenGUI::doubleTapDetection() translated->MouseInput.ButtonStates = 0; translated->MouseInput.Event = EMIE_RMOUSE_LEFT_UP; - verbosestream << "TouchScreenGUI::translateEvent right click release" - << std::endl; + verbosestream << "TouchScreenGUI::translateEvent right click release" << std::endl; m_receiver->OnEvent(*translated); delete translated; return true; @@ -1092,8 +1044,8 @@ void TouchScreenGUI::applyJoystickStatus() continue; SEvent translated{}; - translated.EventType = irr::EET_KEY_INPUT_EVENT; - translated.KeyInput.Key = id2keycode(m_joystick_names[i]); + translated.EventType = irr::EET_KEY_INPUT_EVENT; + translated.KeyInput.Key = id2keycode(m_joystick_names[i]); translated.KeyInput.PressedDown = false; m_receiver->OnEvent(translated); @@ -1143,11 +1095,11 @@ void TouchScreenGUI::step(float dtime) if (button.repeatcounter < button.repeatdelay) continue; - button.repeatcounter = 0; + button.repeatcounter = 0; SEvent translated; memset(&translated, 0, sizeof(SEvent)); - translated.EventType = irr::EET_KEY_INPUT_EVENT; - translated.KeyInput.Key = button.keycode; + translated.EventType = irr::EET_KEY_INPUT_EVENT; + translated.KeyInput.Key = button.keycode; translated.KeyInput.PressedDown = false; m_receiver->OnEvent(translated); @@ -1165,33 +1117,31 @@ void TouchScreenGUI::step(float dtime) } // if a new placed pointer isn't moved for some time start digging - if ((m_move_id != -1) && (!m_move_has_really_moved) && + if ((m_move_id != -1) && + (!m_move_has_really_moved) && (!m_move_sent_as_mouse_event)) { u64 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); if (delta > MIN_DIG_TIME_MS) { - m_shootline = m_device->getSceneManager() - ->getSceneCollisionManager() - ->getRayFromScreenCoordinates(v2s32( - m_move_downlocation - .X, - m_move_downlocation - .Y)); + m_shootline = m_device + ->getSceneManager() + ->getSceneCollisionManager() + ->getRayFromScreenCoordinates( + v2s32(m_move_downlocation.X,m_move_downlocation.Y)); SEvent translated; memset(&translated, 0, sizeof(SEvent)); - translated.EventType = EET_MOUSE_INPUT_EVENT; - translated.MouseInput.X = m_move_downlocation.X; - translated.MouseInput.Y = m_move_downlocation.Y; - translated.MouseInput.Shift = false; - translated.MouseInput.Control = false; + translated.EventType = EET_MOUSE_INPUT_EVENT; + translated.MouseInput.X = m_move_downlocation.X; + translated.MouseInput.Y = m_move_downlocation.Y; + translated.MouseInput.Shift = false; + translated.MouseInput.Control = false; translated.MouseInput.ButtonStates = EMBSM_LEFT; - translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN; - verbosestream << "TouchScreenGUI::step left click press" - << std::endl; + translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN; + verbosestream << "TouchScreenGUI::step left click press" << std::endl; m_receiver->OnEvent(translated); - m_move_sent_as_mouse_event = true; + m_move_sent_as_mouse_event = true; } } diff --git a/src/httpfetch.cpp b/src/httpfetch.cpp index 1883cf263..326b5052f 100644 --- a/src/httpfetch.cpp +++ b/src/httpfetch.cpp @@ -38,16 +38,17 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "noise.h" std::mutex g_httpfetch_mutex; -std::map> g_httpfetch_results; +std::map > g_httpfetch_results; PcgRandom g_callerid_randomness; HTTPFetchRequest::HTTPFetchRequest() : - timeout(g_settings->getS32("curl_timeout")), connect_timeout(timeout), - useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + - porting::get_sysinfo() + ")") + timeout(g_settings->getS32("curl_timeout")), + connect_timeout(timeout), + useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")") { } + static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result) { unsigned long caller = fetch_result.caller; @@ -66,11 +67,11 @@ unsigned long httpfetch_caller_alloc() // Check each caller ID except HTTPFETCH_DISCARD const unsigned long discard = HTTPFETCH_DISCARD; for (unsigned long caller = discard + 1; caller != discard; ++caller) { - std::map>::iterator it = - g_httpfetch_results.find(caller); + std::map >::iterator + it = g_httpfetch_results.find(caller); if (it == g_httpfetch_results.end()) { - verbosestream << "httpfetch_caller_alloc: allocating " << caller - << std::endl; + verbosestream << "httpfetch_caller_alloc: allocating " + << caller << std::endl; // Access element to create it g_httpfetch_results[caller]; return caller; @@ -92,18 +93,17 @@ unsigned long httpfetch_caller_alloc_secure() unsigned long caller; do { - caller = (((u64)g_callerid_randomness.next()) << 32) | - g_callerid_randomness.next(); + caller = (((u64) g_callerid_randomness.next()) << 32) | + g_callerid_randomness.next(); if (--tries < 1) { - FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller " - "IDs"); + FATAL_ERROR("httpfetch_caller_alloc_secure: ran out of caller IDs"); return HTTPFETCH_DISCARD; } } while (g_httpfetch_results.find(caller) != g_httpfetch_results.end()); - verbosestream << "httpfetch_caller_alloc_secure: allocating " << caller - << std::endl; + verbosestream << "httpfetch_caller_alloc_secure: allocating " + << caller << std::endl; // Access element to create it g_httpfetch_results[caller]; @@ -112,7 +112,8 @@ unsigned long httpfetch_caller_alloc_secure() void httpfetch_caller_free(unsigned long caller) { - verbosestream << "httpfetch_caller_free: freeing " << caller << std::endl; + verbosestream<<"httpfetch_caller_free: freeing " + <>::iterator it = - g_httpfetch_results.find(caller); + std::map >::iterator + it = g_httpfetch_results.find(caller); if (it == g_httpfetch_results.end()) return false; @@ -152,7 +153,7 @@ bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result) static size_t httpfetch_writefunction( char *ptr, size_t size, size_t nmemb, void *userdata) { - std::ostringstream *stream = (std::ostringstream *)userdata; + std::ostringstream *stream = (std::ostringstream*)userdata; size_t count = size * nmemb; stream->write(ptr, count); return count; @@ -166,28 +167,28 @@ static size_t httpfetch_discardfunction( class CurlHandlePool { - std::list handles; + std::list handles; public: CurlHandlePool() = default; ~CurlHandlePool() { - for (std::list::iterator it = handles.begin(); + for (std::list::iterator it = handles.begin(); it != handles.end(); ++it) { curl_easy_cleanup(*it); } } - CURL *alloc() + CURL * alloc() { CURL *curl; if (handles.empty()) { curl = curl_easy_init(); if (curl == NULL) { - errorstream << "curl_easy_init returned NULL" - << std::endl; + errorstream<<"curl_easy_init returned NULL"<alloc(); if (curl == NULL) { @@ -255,15 +262,21 @@ HTTPFetchOngoing::HTTPFetchOngoing( // other protocols don't affect us. // These settings were introduced in curl 7.19.4. long protocols = - CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS; + CURLPROTO_HTTP | + CURLPROTO_HTTPS | + CURLPROTO_FTP | + CURLPROTO_FTPS; curl_easy_setopt(curl, CURLOPT_PROTOCOLS, protocols); curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, protocols); #endif // Set cURL options based on HTTPFetchRequest - curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str()); - curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, request.timeout); - curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, request.connect_timeout); + curl_easy_setopt(curl, CURLOPT_URL, + request.url.c_str()); + curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, + request.timeout); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, + request.connect_timeout); if (!request.useragent.empty()) curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str()); @@ -272,10 +285,12 @@ HTTPFetchOngoing::HTTPFetchOngoing( // ostringstream ongoing->oss, unless the data // is to be discarded if (request.caller == HTTPFETCH_DISCARD) { - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, httpfetch_discardfunction); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, + httpfetch_discardfunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL); } else { - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, httpfetch_writefunction); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, + httpfetch_writefunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &oss); } @@ -286,7 +301,8 @@ HTTPFetchOngoing::HTTPFetchOngoing( curl_httppost *last = NULL; for (StringMap::iterator it = request.post_fields.begin(); it != request.post_fields.end(); ++it) { - curl_formadd(&post, &last, CURLFORM_NAMELENGTH, it->first.size(), + curl_formadd(&post, &last, + CURLFORM_NAMELENGTH, it->first.size(), CURLFORM_PTRNAME, it->first.c_str(), CURLFORM_CONTENTSLENGTH, it->second.size(), CURLFORM_PTRCONTENTS, it->second.c_str(), @@ -305,12 +321,16 @@ HTTPFetchOngoing::HTTPFetchOngoing( str += "="; str += urlencode(post_field.second); } - curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, str.size()); - curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, str.c_str()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, + str.size()); + curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, + str.c_str()); } else { curl_easy_setopt(curl, CURLOPT_POST, 1); - curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request.post_data.size()); - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.post_data.c_str()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, + request.post_data.size()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, + request.post_data.c_str()); // request.post_data must now *never* be // modified until CURLOPT_POSTFIELDS is cleared } @@ -339,14 +359,15 @@ CURLcode HTTPFetchOngoing::start(CURLM *multi_) CURLMcode mres = curl_multi_add_handle(multi_, curl); if (mres != CURLM_OK) { errorstream << "curl_multi_add_handle" - << " returned error code " << mres << std::endl; + << " returned error code " << mres + << std::endl; return CURLE_FAILED_INIT; } multi = multi_; // store for curl_multi_remove_handle return CURLE_OK; } -const HTTPFetchResult *HTTPFetchOngoing::complete(CURLcode res) +const HTTPFetchResult * HTTPFetchOngoing::complete(CURLcode res) { result.succeeded = (res == CURLE_OK); result.timeout = (res == CURLE_OPERATION_TIMEDOUT); @@ -355,16 +376,16 @@ const HTTPFetchResult *HTTPFetchOngoing::complete(CURLcode res) // Get HTTP/FTP response code result.response_code = 0; if (curl && (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, - &result.response_code) != CURLE_OK)) { + &result.response_code) != CURLE_OK)) { // We failed to get a return code, make sure it is still 0 result.response_code = 0; } if (res != CURLE_OK) { - errorstream << request.url << " not found (" << curl_easy_strerror(res) - << ")" - << " (response code " << result.response_code << ")" - << std::endl; + errorstream << request.url << " not found (" + << curl_easy_strerror(res) << ")" + << " (response code " << result.response_code << ")" + << std::endl; } return &result; @@ -376,12 +397,14 @@ HTTPFetchOngoing::~HTTPFetchOngoing() CURLMcode mres = curl_multi_remove_handle(multi, curl); if (mres != CURLM_OK) { errorstream << "curl_multi_remove_handle" - << " returned error code " << mres << std::endl; + << " returned error code " << mres + << std::endl; } } // Set safe options for the reusable cURL handle - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, httpfetch_discardfunction); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, + httpfetch_discardfunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL); if (http_header) { @@ -397,18 +420,17 @@ HTTPFetchOngoing::~HTTPFetchOngoing() pool->free(curl); } + class CurlFetchThread : public Thread { protected: - enum RequestType - { + enum RequestType { RT_FETCH, RT_CLEAR, RT_WAKEUP, }; - struct Request - { + struct Request { RequestType type; HTTPFetchRequest fetch_request; Event *event; @@ -419,11 +441,12 @@ class CurlFetchThread : public Thread size_t m_parallel_limit; // Variables exclusively used within thread - std::vector m_all_ongoing; + std::vector m_all_ongoing; std::list m_queued_fetches; public: - CurlFetchThread(int parallel_limit) : Thread("CurlFetch") + CurlFetchThread(int parallel_limit) : + Thread("CurlFetch") { if (parallel_limit >= 1) m_parallel_limit = parallel_limit; @@ -469,12 +492,13 @@ class CurlFetchThread : public Thread // see processQueued() for what happens next - } else if (req.type == RT_CLEAR) { + } + else if (req.type == RT_CLEAR) { unsigned long caller = req.fetch_request.caller; // Abort all ongoing fetches for the caller - for (std::vector::iterator it = - m_all_ongoing.begin(); + for (std::vector::iterator + it = m_all_ongoing.begin(); it != m_all_ongoing.end();) { if ((*it)->getRequest().caller == caller) { delete (*it); @@ -485,15 +509,16 @@ class CurlFetchThread : public Thread } // Also abort all queued fetches for the caller - for (std::list::iterator it = - m_queued_fetches.begin(); + for (std::list::iterator + it = m_queued_fetches.begin(); it != m_queued_fetches.end();) { if ((*it).caller == caller) it = m_queued_fetches.erase(it); else ++it; } - } else if (req.type == RT_WAKEUP) { + } + else if (req.type == RT_WAKEUP) { // Wakeup: Nothing to do, thread is awake at this point } @@ -511,13 +536,15 @@ class CurlFetchThread : public Thread // Create ongoing fetch data and make a cURL handle // Set cURL options based on HTTPFetchRequest - HTTPFetchOngoing *ongoing = new HTTPFetchOngoing(request, pool); + HTTPFetchOngoing *ongoing = + new HTTPFetchOngoing(request, pool); // Initiate the connection (curl_multi_add_handle) CURLcode res = ongoing->start(m_multi); if (res == CURLE_OK) { m_all_ongoing.push_back(ongoing); - } else { + } + else { httpfetch_deliver_result(*ongoing->complete(res)); delete ongoing; } @@ -552,8 +579,8 @@ class CurlFetchThread : public Thread try { Request req = m_requests.pop_front(timeout); processRequest(req); - } catch (ItemNotFoundException &e) { } + catch (ItemNotFoundException &e) {} } } @@ -572,18 +599,20 @@ class CurlFetchThread : public Thread FD_ZERO(&write_fd_set); FD_ZERO(&exc_fd_set); - mres = curl_multi_fdset(m_multi, &read_fd_set, &write_fd_set, &exc_fd_set, - &max_fd); + mres = curl_multi_fdset(m_multi, &read_fd_set, + &write_fd_set, &exc_fd_set, &max_fd); if (mres != CURLM_OK) { - errorstream << "curl_multi_fdset" - << " returned error code " << mres << std::endl; + errorstream<<"curl_multi_fdset" + <<" returned error code "<stop(); g_httpfetch_thread->requestWakeUp(); @@ -744,7 +776,8 @@ static void httpfetch_request_clear(unsigned long caller) } } -void httpfetch_sync(const HTTPFetchRequest &fetch_request, HTTPFetchResult &fetch_result) +void httpfetch_sync(const HTTPFetchRequest &fetch_request, + HTTPFetchResult &fetch_result) { // Create ongoing fetch data and make a cURL handle // Set cURL options based on HTTPFetchRequest @@ -756,7 +789,7 @@ void httpfetch_sync(const HTTPFetchRequest &fetch_request, HTTPFetchResult &fetc fetch_result = *ongoing.complete(res); } -#else // USE_CURL +#else // USE_CURL /* USE_CURL is off: @@ -775,7 +808,7 @@ void httpfetch_cleanup() void httpfetch_async(const HTTPFetchRequest &fetch_request) { errorstream << "httpfetch_async: unable to fetch " << fetch_request.url - << " because USE_CURL=0" << std::endl; + << " because USE_CURL=0" << std::endl; HTTPFetchResult fetch_result(fetch_request); // sets succeeded = false etc. httpfetch_deliver_result(fetch_result); @@ -785,12 +818,13 @@ static void httpfetch_request_clear(unsigned long caller) { } -void httpfetch_sync(const HTTPFetchRequest &fetch_request, HTTPFetchResult &fetch_result) +void httpfetch_sync(const HTTPFetchRequest &fetch_request, + HTTPFetchResult &fetch_result) { errorstream << "httpfetch_sync: unable to fetch " << fetch_request.url - << " because USE_CURL=0" << std::endl; + << " because USE_CURL=0" << std::endl; fetch_result = HTTPFetchResult(fetch_request); // sets succeeded = false etc. } -#endif // USE_CURL +#endif // USE_CURL diff --git a/src/hud.cpp b/src/hud.cpp index 705d0cfb3..3079b5cd8 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -20,41 +20,44 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "hud.h" #include -const struct EnumString es_HudElementType[] = { - {HUD_ELEM_IMAGE, "image"}, - {HUD_ELEM_TEXT, "text"}, - {HUD_ELEM_STATBAR, "statbar"}, - {HUD_ELEM_INVENTORY, "inventory"}, - {HUD_ELEM_WAYPOINT, "waypoint"}, - {HUD_ELEM_IMAGE_WAYPOINT, "image_waypoint"}, - {0, NULL}, +const struct EnumString es_HudElementType[] = +{ + {HUD_ELEM_IMAGE, "image"}, + {HUD_ELEM_TEXT, "text"}, + {HUD_ELEM_STATBAR, "statbar"}, + {HUD_ELEM_INVENTORY, "inventory"}, + {HUD_ELEM_WAYPOINT, "waypoint"}, + {HUD_ELEM_IMAGE_WAYPOINT, "image_waypoint"}, + {0, NULL}, }; -const struct EnumString es_HudElementStat[] = { - {HUD_STAT_POS, "position"}, - {HUD_STAT_POS, "pos"}, /* Deprecated, only for compatibility's sake */ - {HUD_STAT_NAME, "name"}, - {HUD_STAT_SCALE, "scale"}, - {HUD_STAT_TEXT, "text"}, - {HUD_STAT_NUMBER, "number"}, - {HUD_STAT_ITEM, "item"}, - {HUD_STAT_DIR, "direction"}, - {HUD_STAT_ALIGN, "alignment"}, - {HUD_STAT_OFFSET, "offset"}, - {HUD_STAT_WORLD_POS, "world_pos"}, - {HUD_STAT_SIZE, "size"}, - {HUD_STAT_Z_INDEX, "z_index"}, - {HUD_STAT_TEXT2, "text2"}, - {0, NULL}, +const struct EnumString es_HudElementStat[] = +{ + {HUD_STAT_POS, "position"}, + {HUD_STAT_POS, "pos"}, /* Deprecated, only for compatibility's sake */ + {HUD_STAT_NAME, "name"}, + {HUD_STAT_SCALE, "scale"}, + {HUD_STAT_TEXT, "text"}, + {HUD_STAT_NUMBER, "number"}, + {HUD_STAT_ITEM, "item"}, + {HUD_STAT_DIR, "direction"}, + {HUD_STAT_ALIGN, "alignment"}, + {HUD_STAT_OFFSET, "offset"}, + {HUD_STAT_WORLD_POS, "world_pos"}, + {HUD_STAT_SIZE, "size"}, + {HUD_STAT_Z_INDEX, "z_index"}, + {HUD_STAT_TEXT2, "text2"}, + {0, NULL}, }; -const struct EnumString es_HudBuiltinElement[] = { - {HUD_FLAG_HOTBAR_VISIBLE, "hotbar"}, - {HUD_FLAG_HEALTHBAR_VISIBLE, "healthbar"}, - {HUD_FLAG_CROSSHAIR_VISIBLE, "crosshair"}, - {HUD_FLAG_WIELDITEM_VISIBLE, "wielditem"}, - {HUD_FLAG_BREATHBAR_VISIBLE, "breathbar"}, - {HUD_FLAG_MINIMAP_VISIBLE, "minimap"}, - {HUD_FLAG_MINIMAP_RADAR_VISIBLE, "minimap_radar"}, - {0, NULL}, +const struct EnumString es_HudBuiltinElement[] = +{ + {HUD_FLAG_HOTBAR_VISIBLE, "hotbar"}, + {HUD_FLAG_HEALTHBAR_VISIBLE, "healthbar"}, + {HUD_FLAG_CROSSHAIR_VISIBLE, "crosshair"}, + {HUD_FLAG_WIELDITEM_VISIBLE, "wielditem"}, + {HUD_FLAG_BREATHBAR_VISIBLE, "breathbar"}, + {HUD_FLAG_MINIMAP_VISIBLE, "minimap"}, + {HUD_FLAG_MINIMAP_RADAR_VISIBLE, "minimap_radar"}, + {0, NULL}, }; diff --git a/src/hud.h b/src/hud.h index 904109580..e015baec1 100644 --- a/src/hud.h +++ b/src/hud.h @@ -29,19 +29,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #define HUD_DIR_TOP_BOTTOM 2 #define HUD_DIR_BOTTOM_TOP 3 -#define HUD_CORNER_UPPER 0 -#define HUD_CORNER_LOWER 1 +#define HUD_CORNER_UPPER 0 +#define HUD_CORNER_LOWER 1 #define HUD_CORNER_CENTER 2 // Note that these visibility flags do not determine if the hud items are // actually drawn, but rather, whether to draw the item should the rest // of the game state permit it. -#define HUD_FLAG_HOTBAR_VISIBLE (1 << 0) -#define HUD_FLAG_HEALTHBAR_VISIBLE (1 << 1) -#define HUD_FLAG_CROSSHAIR_VISIBLE (1 << 2) -#define HUD_FLAG_WIELDITEM_VISIBLE (1 << 3) -#define HUD_FLAG_BREATHBAR_VISIBLE (1 << 4) -#define HUD_FLAG_MINIMAP_VISIBLE (1 << 5) +#define HUD_FLAG_HOTBAR_VISIBLE (1 << 0) +#define HUD_FLAG_HEALTHBAR_VISIBLE (1 << 1) +#define HUD_FLAG_CROSSHAIR_VISIBLE (1 << 2) +#define HUD_FLAG_WIELDITEM_VISIBLE (1 << 3) +#define HUD_FLAG_BREATHBAR_VISIBLE (1 << 4) +#define HUD_FLAG_MINIMAP_VISIBLE (1 << 5) #define HUD_FLAG_MINIMAP_RADAR_VISIBLE (1 << 6) #define HUD_PARAM_HOTBAR_ITEMCOUNT 1 @@ -49,22 +49,21 @@ with this program; if not, write to the Free Software Foundation, Inc., #define HUD_PARAM_HOTBAR_SELECTED_IMAGE 3 #define HUD_HOTBAR_ITEMCOUNT_DEFAULT 8 -#define HUD_HOTBAR_ITEMCOUNT_MAX 32 +#define HUD_HOTBAR_ITEMCOUNT_MAX 32 + #define HOTBAR_IMAGE_SIZE 48 -enum HudElementType -{ - HUD_ELEM_IMAGE = 0, - HUD_ELEM_TEXT = 1, - HUD_ELEM_STATBAR = 2, +enum HudElementType { + HUD_ELEM_IMAGE = 0, + HUD_ELEM_TEXT = 1, + HUD_ELEM_STATBAR = 2, HUD_ELEM_INVENTORY = 3, - HUD_ELEM_WAYPOINT = 4, + HUD_ELEM_WAYPOINT = 4, HUD_ELEM_IMAGE_WAYPOINT = 5 }; -enum HudElementStat -{ +enum HudElementStat { HUD_STAT_POS = 0, HUD_STAT_NAME, HUD_STAT_SCALE, @@ -80,8 +79,7 @@ enum HudElementStat HUD_STAT_TEXT2, }; -struct HudElement -{ +struct HudElement { HudElementType type; v2f pos; std::string name; @@ -101,3 +99,4 @@ struct HudElement extern const EnumString es_HudElementType[]; extern const EnumString es_HudElementStat[]; extern const EnumString es_HudBuiltinElement[]; + diff --git a/src/inventory.cpp b/src/inventory.cpp index 8c4909e01..349ee503d 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -26,7 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "itemdef.h" #include "util/strfnd.h" #include "content_mapnode.h" // For loading legacy MaterialItems -#include "nameidmapping.h" // For loading legacy MaterialItems +#include "nameidmapping.h" // For loading legacy MaterialItems #include "util/serialize.h" #include "util/string.h" @@ -37,17 +37,18 @@ with this program; if not, write to the Free Software Foundation, Inc., static content_t content_translate_from_19_to_internal(content_t c_from) { for (const auto &tt : trans_table_19) { - if (tt[1] == c_from) { + if(tt[1] == c_from) { return tt[0]; } } return c_from; } -ItemStack::ItemStack(const std::string &name_, u16 count_, u16 wear_, - IItemDefManager *itemdef) : - name(itemdef->getAlias(name_)), - count(count_), wear(wear_) +ItemStack::ItemStack(const std::string &name_, u16 count_, + u16 wear_, IItemDefManager *itemdef) : + name(itemdef->getAlias(name_)), + count(count_), + wear(wear_) { if (name.empty() || count == 0) clear(); @@ -93,50 +94,55 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) // Skip space std::string tmp; std::getline(is, tmp, ' '); - if (!tmp.empty()) + if(!tmp.empty()) throw SerializationError("Unexpected text after item name"); - if (name == "MaterialItem") { + if(name == "MaterialItem") + { // Obsoleted on 2011-07-30 u16 material; - is >> material; + is>>material; u16 materialcount; - is >> materialcount; + is>>materialcount; // Convert old materials - if (material <= 0xff) + if(material <= 0xff) material = content_translate_from_19_to_internal(material); - if (material > 0xfff) + if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); - if (name.empty()) + if(name.empty()) name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; - } else if (name == "MaterialItem2") { + } + else if(name == "MaterialItem2") + { // Obsoleted on 2011-11-16 u16 material; - is >> material; + is>>material; u16 materialcount; - is >> materialcount; - if (material > 0xfff) + is>>materialcount; + if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); - if (name.empty()) + if(name.empty()) name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; - } else if (name == "node" || name == "NodeItem" || name == "MaterialItem3" || - name == "craft" || name == "CraftItem") { + } + else if(name == "node" || name == "NodeItem" || name == "MaterialItem3" + || name == "craft" || name == "CraftItem") + { // Obsoleted on 2012-01-07 std::string all; @@ -145,7 +151,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s - if (!fnd.at_end()) { + if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); @@ -155,12 +161,16 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) if (itemdef) name = itemdef->getAlias(name); count = stoi(trim(fnd.next(""))); - if (count == 0) + if(count == 0) count = 1; - } else if (name == "MBOItem") { + } + else if(name == "MBOItem") + { // Obsoleted on 2011-10-14 throw SerializationError("MBOItem not supported anymore"); - } else if (name == "tool" || name == "ToolItem") { + } + else if(name == "tool" || name == "ToolItem") + { // Obsoleted on 2012-01-07 std::string all; @@ -169,7 +179,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s - if (!fnd.at_end()) { + if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); @@ -181,8 +191,10 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) if (itemdef) name = itemdef->getAlias(name); wear = stoi(trim(fnd.next(""))); - } else { - do // This loop is just to allow "break;" + } + else + { + do // This loop is just to allow "break;" { // The real thing @@ -203,7 +215,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) // Read the wear std::string wear_str; std::getline(is, wear_str, ' '); - if (wear_str.empty()) + if(wear_str.empty()) break; wear = stoi(wear_str); @@ -212,12 +224,11 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) metadata.deSerialize(is); // In case fields are added after metadata, skip space here: - // std::getline(is, tmp, ' '); - // if(!tmp.empty()) - // throw SerializationError("Unexpected text after - // metadata"); + //std::getline(is, tmp, ' '); + //if(!tmp.empty()) + // throw SerializationError("Unexpected text after metadata"); - } while (false); + } while(false); } if (name.empty() || count == 0) @@ -247,29 +258,36 @@ std::string ItemStack::getDescription(IItemDefManager *itemdef) const return desc.empty() ? name : desc; } + ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef) { // If the item is empty or the position invalid, bail out - if (newitem.empty()) { + if(newitem.empty()) + { // nothing can be added trivially } // If this is an empty item, it's an easy job. - else if (empty()) { + else if(empty()) + { *this = newitem; newitem.clear(); } // If item name or metadata differs, bail out - else if (name != newitem.name || metadata != newitem.metadata) { + else if (name != newitem.name + || metadata != newitem.metadata) + { // cannot be added } // If the item fits fully, add counter and delete it - else if (newitem.count <= freeSpace(itemdef)) { + else if(newitem.count <= freeSpace(itemdef)) + { add(newitem.count); newitem.clear(); } // Else the item does not fit fully. Add all that fits and return // the rest. - else { + else + { u16 freespace = freeSpace(itemdef); add(freespace); newitem.remove(freespace); @@ -278,33 +296,40 @@ ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef) return newitem; } -bool ItemStack::itemFits( - ItemStack newitem, ItemStack *restitem, IItemDefManager *itemdef) const +bool ItemStack::itemFits(ItemStack newitem, + ItemStack *restitem, + IItemDefManager *itemdef) const { // If the item is empty or the position invalid, bail out - if (newitem.empty()) { + if(newitem.empty()) + { // nothing can be added trivially } // If this is an empty item, it's an easy job. - else if (empty()) { + else if(empty()) + { newitem.clear(); } // If item name or metadata differs, bail out - else if (name != newitem.name || metadata != newitem.metadata) { + else if (name != newitem.name + || metadata != newitem.metadata) + { // cannot be added } // If the item fits fully, delete it - else if (newitem.count <= freeSpace(itemdef)) { + else if(newitem.count <= freeSpace(itemdef)) + { newitem.clear(); } // Else the item does not fit fully. Return the rest. - else { + else + { u16 freespace = freeSpace(itemdef); newitem.remove(freespace); } - if (restitem) + if(restitem) *restitem = newitem; return newitem.empty(); @@ -312,14 +337,17 @@ bool ItemStack::itemFits( ItemStack ItemStack::takeItem(u32 takecount) { - if (takecount == 0 || count == 0) + if(takecount == 0 || count == 0) return ItemStack(); ItemStack result = *this; - if (takecount >= count) { + if(takecount >= count) + { // Take all clear(); - } else { + } + else + { // Take part remove(takecount); result.count = takecount; @@ -329,11 +357,11 @@ ItemStack ItemStack::takeItem(u32 takecount) ItemStack ItemStack::peekItem(u32 peekcount) const { - if (peekcount == 0 || count == 0) + if(peekcount == 0 || count == 0) return ItemStack(); ItemStack result = *this; - if (peekcount < count) + if(peekcount < count) result.count = peekcount; return result; } @@ -342,10 +370,10 @@ ItemStack ItemStack::peekItem(u32 peekcount) const Inventory */ -InventoryList::InventoryList( - const std::string &name, u32 size, IItemDefManager *itemdef) : - m_name(name), - m_size(size), m_itemdef(itemdef) +InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef): + m_name(name), + m_size(size), + m_itemdef(itemdef) { clearItems(); } @@ -354,7 +382,7 @@ void InventoryList::clearItems() { m_items.clear(); - for (u32 i = 0; i < m_size; i++) { + for (u32 i=0; i < m_size; i++) { m_items.emplace_back(); } @@ -385,29 +413,29 @@ void InventoryList::setName(const std::string &name) void InventoryList::serialize(std::ostream &os, bool incremental) const { - // os.imbue(std::locale("C")); + //os.imbue(std::locale("C")); - os << "Width " << m_width << "\n"; + os<<"Width "<> m_width; if (iss.fail()) throw SerializationError("incorrect width property"); - } else if (name == "Item") { - if (item_i > getSize() - 1) + } + else if(name == "Item") + { + if(item_i > getSize() - 1) throw SerializationError("too many items"); ItemStack item; item.deSerialize(iss, m_itemdef); m_items[item_i++] = item; - } else if (name == "Empty") { - if (item_i > getSize() - 1) + } + else if(name == "Empty") + { + if(item_i > getSize() - 1) throw SerializationError("too many items"); m_items[item_i++].clear(); } else if (name == "Keep") { @@ -453,8 +484,9 @@ void InventoryList::deSerialize(std::istream &is) // Contents given to deSerialize() were not terminated properly: throw error. std::ostringstream ss; - ss << "Malformatted inventory list. list=" << m_name << ", read " << item_i - << " of " << getSize() << " ItemStacks." << std::endl; + ss << "Malformatted inventory list. list=" + << m_name << ", read " << item_i << " of " << getSize() + << " ItemStacks." << std::endl; throw SerializationError(ss.str()); } @@ -463,25 +495,25 @@ InventoryList::InventoryList(const InventoryList &other) *this = other; } -InventoryList &InventoryList::operator=(const InventoryList &other) +InventoryList & InventoryList::operator = (const InventoryList &other) { m_items = other.m_items; m_size = other.m_size; m_width = other.m_width; m_name = other.m_name; m_itemdef = other.m_itemdef; - // setDirty(true); + //setDirty(true); return *this; } -bool InventoryList::operator==(const InventoryList &other) const +bool InventoryList::operator == (const InventoryList &other) const { - if (m_size != other.m_size) + if(m_size != other.m_size) return false; - if (m_width != other.m_width) + if(m_width != other.m_width) return false; - if (m_name != other.m_name) + if(m_name != other.m_name) return false; for (u32 i = 0; i < m_items.size(); i++) if (m_items[i] != other.m_items[i]) @@ -520,13 +552,13 @@ u32 InventoryList::getFreeSlots() const return getSize() - getUsedSlots(); } -const ItemStack &InventoryList::getItem(u32 i) const +const ItemStack& InventoryList::getItem(u32 i) const { assert(i < m_size); // Pre-condition return m_items[i]; } -ItemStack &InventoryList::getItem(u32 i) +ItemStack& InventoryList::getItem(u32 i) { assert(i < m_size); // Pre-condition return m_items[i]; @@ -534,7 +566,7 @@ ItemStack &InventoryList::getItem(u32 i) ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem) { - if (i >= m_items.size()) + if(i >= m_items.size()) return newitem; ItemStack olditem = m_items[i]; @@ -554,32 +586,34 @@ ItemStack InventoryList::addItem(const ItemStack &newitem_) { ItemStack newitem = newitem_; - if (newitem.empty()) + if(newitem.empty()) return newitem; /* First try to find if it could be added to some existing items */ - for (u32 i = 0; i < m_items.size(); i++) { + for(u32 i=0; i= m_items.size()) + if(i >= m_items.size()) return newitem; ItemStack leftover = m_items[i].addItem(newitem, m_itemdef); @@ -598,11 +632,12 @@ ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem) return leftover; } -bool InventoryList::itemFits( - const u32 i, const ItemStack &newitem, ItemStack *restitem) const +bool InventoryList::itemFits(const u32 i, const ItemStack &newitem, + ItemStack *restitem) const { - if (i >= m_items.size()) { - if (restitem) + if(i >= m_items.size()) + { + if(restitem) *restitem = newitem; return false; } @@ -614,8 +649,9 @@ bool InventoryList::roomForItem(const ItemStack &item_) const { ItemStack item = item_; ItemStack leftover; - for (u32 i = 0; i < m_items.size(); i++) { - if (itemFits(i, item, &leftover)) + for(u32 i=0; iname == item.name && - (!match_meta || (i->metadata == item.metadata))) { + if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) { if (i->count >= count) return true; @@ -648,8 +683,8 @@ ItemStack InventoryList::removeItem(const ItemStack &item) for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) { if (i->name == item.name) { u32 still_to_remove = item.count - removed.count; - ItemStack leftover = removed.addItem( - i->takeItem(still_to_remove), m_itemdef); + ItemStack leftover = removed.addItem(i->takeItem(still_to_remove), + m_itemdef); // Allow oversized stacks removed.count += leftover.count; @@ -664,7 +699,7 @@ ItemStack InventoryList::removeItem(const ItemStack &item) ItemStack InventoryList::takeItem(u32 i, u32 takecount) { - if (i >= m_items.size()) + if(i >= m_items.size()) return ItemStack(); ItemStack taken = m_items[i].takeItem(takecount); @@ -694,20 +729,20 @@ void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count) } } -u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count, - bool swap_if_needed, bool *did_swap) +u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, + u32 count, bool swap_if_needed, bool *did_swap) { - if (this == dest && i == dest_i) + if(this == dest && i == dest_i) return count; // Take item from source list ItemStack item1; - if (count == 0) + if(count == 0) item1 = changeItem(i, ItemStack()); else item1 = takeItem(i, count); - if (item1.empty()) + if(item1.empty()) return 0; // Try to add the item to destination list @@ -715,7 +750,8 @@ u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count, item1 = dest->addItem(dest_i, item1); // If something is returned, the item was not fully added - if (!item1.empty()) { + if(!item1.empty()) + { // If olditem is returned, nothing was added. bool nothing_added = (item1.count == oldcount); @@ -770,10 +806,11 @@ Inventory::Inventory(const Inventory &other) *this = other; } -Inventory &Inventory::operator=(const Inventory &other) +Inventory & Inventory::operator = (const Inventory &other) { // Gracefully handle self assignment - if (this != &other) { + if(this != &other) + { clear(); m_itemdef = other.m_itemdef; for (InventoryList *list : other.m_lists) { @@ -784,13 +821,14 @@ Inventory &Inventory::operator=(const Inventory &other) return *this; } -bool Inventory::operator==(const Inventory &other) const +bool Inventory::operator == (const Inventory &other) const { - if (m_lists.size() != other.m_lists.size()) + if(m_lists.size() != other.m_lists.size()) return false; - for (u32 i = 0; i < m_lists.size(); i++) { - if (*m_lists[i] != *other.m_lists[i]) + for(u32 i=0; igetName() << " " << list->getSize() - << "\n"; + os << "List " << list->getName() << " " << list->getSize() << "\n"; list->serialize(os, incremental); } else { os << "KeepList " << list->getName() << "\n"; } } - os << "EndInventory\n"; + os<<"EndInventory\n"; } void Inventory::deSerialize(std::istream &is) @@ -830,8 +866,7 @@ void Inventory::deSerialize(std::istream &is) if (name == "EndInventory" || name == "end") { // Remove all lists that were not sent for (auto &list : m_lists) { - if (std::find(new_lists.begin(), new_lists.end(), list) != - new_lists.end()) + if (std::find(new_lists.begin(), new_lists.end(), list) != new_lists.end()) continue; delete list; @@ -839,8 +874,7 @@ void Inventory::deSerialize(std::istream &is) setModified(); } m_lists.erase(std::remove(m_lists.begin(), m_lists.end(), - nullptr), - m_lists.end()); + nullptr), m_lists.end()); return; } @@ -849,7 +883,7 @@ void Inventory::deSerialize(std::istream &is) u32 listsize; std::getline(iss, listname, ' '); - iss >> listsize; + iss>>listsize; InventoryList *list = getList(listname); bool create_new = !list; @@ -872,10 +906,8 @@ void Inventory::deSerialize(std::istream &is) if (list) { new_lists.push_back(list); } else { - errorstream << "Inventory::deSerialize(): Tried to keep " - "list '" - << listname << "' which is non-existent." - << std::endl; + errorstream << "Inventory::deSerialize(): Tried to keep list '" << + listname << "' which is non-existent." << std::endl; } } // Any additional fields will throw errors when received by a client @@ -885,17 +917,19 @@ void Inventory::deSerialize(std::istream &is) // Contents given to deSerialize() were not terminated properly: throw error. std::ostringstream ss; - ss << "Malformatted inventory (damaged?). " << m_lists.size() << " lists read." - << std::endl; + ss << "Malformatted inventory (damaged?). " + << m_lists.size() << " lists read." << std::endl; throw SerializationError(ss.str()); } -InventoryList *Inventory::addList(const std::string &name, u32 size) +InventoryList * Inventory::addList(const std::string &name, u32 size) { setModified(); s32 i = getListIndex(name); - if (i != -1) { - if (m_lists[i]->getSize() != size) { + if(i != -1) + { + if(m_lists[i]->getSize() != size) + { delete m_lists[i]; m_lists[i] = new InventoryList(name, size, m_itemdef); m_lists[i]->setModified(); @@ -903,7 +937,8 @@ InventoryList *Inventory::addList(const std::string &name, u32 size) return m_lists[i]; } - // don't create list with invalid name + + //don't create list with invalid name if (name.find(' ') != std::string::npos) return nullptr; @@ -913,17 +948,17 @@ InventoryList *Inventory::addList(const std::string &name, u32 size) return list; } -InventoryList *Inventory::getList(const std::string &name) +InventoryList * Inventory::getList(const std::string &name) { s32 i = getListIndex(name); - if (i == -1) + if(i == -1) return NULL; return m_lists[i]; } -std::vector Inventory::getLists() +std::vector Inventory::getLists() { - std::vector lists; + std::vector lists; for (auto list : m_lists) { lists.push_back(list); } @@ -933,7 +968,7 @@ std::vector Inventory::getLists() bool Inventory::deleteList(const std::string &name) { s32 i = getListIndex(name); - if (i == -1) + if(i == -1) return false; setModified(); @@ -942,21 +977,22 @@ bool Inventory::deleteList(const std::string &name) return true; } -const InventoryList *Inventory::getList(const std::string &name) const +const InventoryList * Inventory::getList(const std::string &name) const { s32 i = getListIndex(name); - if (i == -1) + if(i == -1) return NULL; return m_lists[i]; } const s32 Inventory::getListIndex(const std::string &name) const { - for (u32 i = 0; i < m_lists.size(); i++) { - if (m_lists[i]->getName() == name) + for(u32 i=0; igetName() == name) return i; } return -1; } -// END +//END diff --git a/src/inventory.h b/src/inventory.h index c87e7ecba..67a7859ed 100644 --- a/src/inventory.h +++ b/src/inventory.h @@ -34,8 +34,8 @@ struct ItemStack { ItemStack() = default; - ItemStack(const std::string &name_, u16 count_, u16 wear, - IItemDefManager *itemdef); + ItemStack(const std::string &name_, u16 count_, + u16 wear, IItemDefManager *itemdef); ~ItemStack() = default; @@ -54,7 +54,10 @@ struct ItemStack Quantity methods */ - bool empty() const { return count == 0; } + bool empty() const + { + return count == 0; + } void clear() { @@ -64,13 +67,16 @@ struct ItemStack metadata.clear(); } - void add(u16 n) { count += n; } + void add(u16 n) + { + count += n; + } void remove(u16 n) { assert(count >= n); // Pre-condition count -= n; - if (count == 0) + if(count == 0) clear(); // reset name, wear and metadata too } @@ -90,19 +96,25 @@ struct ItemStack } // Returns false if item is not known and cannot be used - bool isKnown(IItemDefManager *itemdef) const { return itemdef->isKnown(name); } + bool isKnown(IItemDefManager *itemdef) const + { + return itemdef->isKnown(name); + } // Returns a pointer to the item definition struct, // or a fallback one (name="unknown") if the item is unknown. - const ItemDefinition &getDefinition(IItemDefManager *itemdef) const + const ItemDefinition& getDefinition( + IItemDefManager *itemdef) const { return itemdef->get(name); } // Get tool digging properties, or those of the hand if not a tool - const ToolCapabilities &getToolCapabilities(IItemDefManager *itemdef) const + const ToolCapabilities& getToolCapabilities( + IItemDefManager *itemdef) const { - const ToolCapabilities *item_cap = itemdef->get(name).tool_capabilities; + const ToolCapabilities *item_cap = + itemdef->get(name).tool_capabilities; if (item_cap == NULL) // Fall back to the hand's tool capabilities @@ -116,10 +128,11 @@ struct ItemStack // Returns true if the item is (was) a tool bool addWear(s32 amount, IItemDefManager *itemdef) { - if (getDefinition(itemdef).type == ITEM_TOOL) { - if (amount > 65535 - wear) + if(getDefinition(itemdef).type == ITEM_TOOL) + { + if(amount > 65535 - wear) clear(); - else if (amount < -wear) + else if(amount < -wear) wear = 0; else wear += amount; @@ -139,7 +152,7 @@ struct ItemStack // If restitem is non-NULL, it receives the part of newitem that // would be left over after adding. bool itemFits(ItemStack newitem, - ItemStack *restitem, // may be NULL + ItemStack *restitem, // may be NULL IItemDefManager *itemdef) const; // Takes some items. @@ -150,13 +163,18 @@ struct ItemStack // Similar to takeItem, but keeps this ItemStack intact. ItemStack peekItem(u32 peekcount) const; - bool operator==(const ItemStack &s) const + bool operator ==(const ItemStack &s) const { - return (this->name == s.name && this->count == s.count && - this->wear == s.wear && this->metadata == s.metadata); + return (this->name == s.name && + this->count == s.count && + this->wear == s.wear && + this->metadata == s.metadata); } - bool operator!=(const ItemStack &s) const { return !(*this == s); } + bool operator !=(const ItemStack &s) const + { + return !(*this == s); + } /* Properties @@ -180,9 +198,12 @@ class InventoryList void deSerialize(std::istream &is); InventoryList(const InventoryList &other); - InventoryList &operator=(const InventoryList &other); - bool operator==(const InventoryList &other) const; - bool operator!=(const InventoryList &other) const { return !(*this == other); } + InventoryList & operator = (const InventoryList &other); + bool operator == (const InventoryList &other) const; + bool operator != (const InventoryList &other) const + { + return !(*this == other); + } const std::string &getName() const; u32 getSize() const; @@ -192,8 +213,8 @@ class InventoryList u32 getFreeSlots() const; // Get reference to item - const ItemStack &getItem(u32 i) const; - ItemStack &getItem(u32 i); + const ItemStack& getItem(u32 i) const; + ItemStack& getItem(u32 i); // Returns old item. Parameter can be an empty item. ItemStack changeItem(u32 i, const ItemStack &newitem); // Delete item @@ -237,8 +258,8 @@ class InventoryList // Move an item to a different list (or a different stack in the same list) // count is the maximum number of items to move (0 for everything) // returns number of moved items - u32 moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count = 0, - bool swap_if_needed = true, bool *did_swap = NULL); + u32 moveItem(u32 i, InventoryList *dest, u32 dest_i, + u32 count = 0, bool swap_if_needed = true, bool *did_swap = NULL); // like moveItem, but without a fixed destination index // also with optional rollback recording @@ -265,24 +286,27 @@ class Inventory Inventory(IItemDefManager *itemdef); Inventory(const Inventory &other); - Inventory &operator=(const Inventory &other); - bool operator==(const Inventory &other) const; - bool operator!=(const Inventory &other) const { return !(*this == other); } + Inventory & operator = (const Inventory &other); + bool operator == (const Inventory &other) const; + bool operator != (const Inventory &other) const + { + return !(*this == other); + } // Never ever serialize to disk using "incremental"! void serialize(std::ostream &os, bool incremental = false) const; void deSerialize(std::istream &is); - InventoryList *addList(const std::string &name, u32 size); - InventoryList *getList(const std::string &name); - const InventoryList *getList(const std::string &name) const; - std::vector getLists(); + InventoryList * addList(const std::string &name, u32 size); + InventoryList * getList(const std::string &name); + const InventoryList * getList(const std::string &name) const; + std::vector getLists(); bool deleteList(const std::string &name); // A shorthand for adding items. Returns leftover item (possibly empty). ItemStack addItem(const std::string &listname, const ItemStack &newitem) { InventoryList *list = getList(listname); - if (list == NULL) + if(list == NULL) return newitem; return list->addItem(newitem); } @@ -308,12 +332,11 @@ class Inventory list->setModified(dirty); } } - private: // -1 if not found const s32 getListIndex(const std::string &name) const; - std::vector m_lists; + std::vector m_lists; IItemDefManager *m_itemdef; bool m_dirty = true; }; diff --git a/src/inventorymanager.cpp b/src/inventorymanager.cpp index 6b5a79fd9..b6f464901 100644 --- a/src/inventorymanager.cpp +++ b/src/inventorymanager.cpp @@ -29,7 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/strfnd.h" #include "util/basic_macros.h" -#define PLAYER_TO_SA(p) p->getEnv()->getScriptIface() +#define PLAYER_TO_SA(p) p->getEnv()->getScriptIface() /* InventoryLocation @@ -46,19 +46,19 @@ void InventoryLocation::serialize(std::ostream &os) const { switch (type) { case InventoryLocation::UNDEFINED: - os << "undefined"; + os<<"undefined"; break; case InventoryLocation::CURRENT_PLAYER: - os << "current_player"; + os<<"current_player"; break; case InventoryLocation::PLAYER: - os << "player:" << name; + os<<"player:"<getInventory(from_inv); Inventory *inv_to = mgr->getInventory(to_inv); if (!inv_from) { infostream << "IMoveAction::apply(): FAIL: source inventory not found: " - << "from_inv=\"" << from_inv.dump() << "\"" - << ", to_inv=\"" << to_inv.dump() << "\"" << std::endl; + << "from_inv=\""<getSize(); @@ -234,17 +235,17 @@ void IMoveAction::apply( } if ((u16)to_i > list_to->getSize()) { - infostream << "IMoveAction::apply(): FAIL: destination index out of " - "bounds: " - << "to_i=" << to_i << ", size=" << list_to->getSize() - << std::endl; + infostream << "IMoveAction::apply(): FAIL: destination index out of bounds: " + << "to_i=" << to_i + << ", size=" << list_to->getSize() << std::endl; return; } /* Do not handle rollback if both inventories are that of the same player */ - bool ignore_rollback = (from_inv.type == InventoryLocation::PLAYER && - from_inv == to_inv); + bool ignore_rollback = ( + from_inv.type == InventoryLocation::PLAYER && + from_inv == to_inv); /* Collect information of endpoints @@ -260,28 +261,25 @@ void IMoveAction::apply( /* Query detached inventories */ // Move occurs in the same detached inventory - if (from_inv.type == InventoryLocation::DETACHED && from_inv == to_inv) { + if (from_inv.type == InventoryLocation::DETACHED && + from_inv == to_inv) { src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowMove( - *this, try_take_count, player); + *this, try_take_count, player); dst_can_put_count = src_can_take_count; } else { // Destination is detached if (to_inv.type == InventoryLocation::DETACHED) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; - dst_can_put_count = - PLAYER_TO_SA(player)->detached_inventory_AllowPut( - *this, src_item, player); + dst_can_put_count = PLAYER_TO_SA(player)->detached_inventory_AllowPut( + *this, src_item, player); } // Source is detached if (from_inv.type == InventoryLocation::DETACHED) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; - src_can_take_count = - PLAYER_TO_SA(player) - ->detached_inventory_AllowTake( - *this, src_item, - player); + src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowTake( + *this, src_item, player); } } @@ -289,54 +287,50 @@ void IMoveAction::apply( // Both endpoints are nodemeta // Move occurs in the same nodemeta inventory - if (from_inv.type == InventoryLocation::NODEMETA && from_inv == to_inv) { + if (from_inv.type == InventoryLocation::NODEMETA && + from_inv == to_inv) { src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowMove( - *this, try_take_count, player); + *this, try_take_count, player); dst_can_put_count = src_can_take_count; } else { // Destination is nodemeta if (to_inv.type == InventoryLocation::NODEMETA) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; - dst_can_put_count = - PLAYER_TO_SA(player)->nodemeta_inventory_AllowPut( - *this, src_item, player); + dst_can_put_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowPut( + *this, src_item, player); } // Source is nodemeta if (from_inv.type == InventoryLocation::NODEMETA) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; - src_can_take_count = - PLAYER_TO_SA(player) - ->nodemeta_inventory_AllowTake( - *this, src_item, - player); + src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowTake( + *this, src_item, player); } } // Query player inventories // Move occurs in the same player inventory - if (from_inv.type == InventoryLocation::PLAYER && from_inv == to_inv) { + if (from_inv.type == InventoryLocation::PLAYER && + from_inv == to_inv) { src_can_take_count = PLAYER_TO_SA(player)->player_inventory_AllowMove( - *this, try_take_count, player); + *this, try_take_count, player); dst_can_put_count = src_can_take_count; } else { // Destination is a player if (to_inv.type == InventoryLocation::PLAYER) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; - dst_can_put_count = - PLAYER_TO_SA(player)->player_inventory_AllowPut( - *this, src_item, player); + dst_can_put_count = PLAYER_TO_SA(player)->player_inventory_AllowPut( + *this, src_item, player); } // Source is a player if (from_inv.type == InventoryLocation::PLAYER) { ItemStack src_item = list_from->getItem(from_i); src_item.count = try_take_count; - src_can_take_count = - PLAYER_TO_SA(player)->player_inventory_AllowTake( - *this, src_item, player); + src_can_take_count = PLAYER_TO_SA(player)->player_inventory_AllowTake( + *this, src_item, player); } } @@ -361,13 +355,15 @@ void IMoveAction::apply( if (to_inv.type == InventoryLocation::PLAYER) list_to->setModified(); - infostream << "IMoveAction::apply(): move was completely disallowed:" - << " count=" << old_count << " from inv=\"" << from_inv.dump() - << "\"" - << " list=\"" << from_list << "\"" - << " i=" << from_i << " to inv=\"" << to_inv.dump() << "\"" - << " list=\"" << to_list << "\"" - << " i=" << to_i << std::endl; + infostream<<"IMoveAction::apply(): move was completely disallowed:" + <<" count="<getItem(from_i).empty()) { - infostream << "IDropAction::apply(): FAIL: source item not found: " - << "from_inv=\"" << from_inv.dump() << "\"" - << ", from_list=\"" << from_list << "\"" - << " from_i=" << from_i << std::endl; + infostream<<"IDropAction::apply(): FAIL: source item not found: " + <<"from_inv=\""<takeItem( - from_i, actually_dropped_count); + ItemStack item2 = list_from->takeItem(from_i, actually_dropped_count); if (item2.count != actually_dropped_count) - errorstream << "Could not take dropped count of items" - << std::endl; + errorstream<<"Could not take dropped count of items"<setInventoryModified(from_inv); } - infostream << "IDropAction::apply(): dropped " - << " from inv=\"" << from_inv.dump() << "\"" - << " list=\"" << from_list << "\"" - << " i=" << from_i << std::endl; + infostream<<"IDropAction::apply(): dropped " + <<" from inv=\""<getSize() < 1) { infostream << "ICraftAction::apply(): FAIL: craftresult list too short: " - << "craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; + << "craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; return; } @@ -816,8 +825,7 @@ void ICraftAction::apply( std::vector temp; // Decrement input and add crafting output getCraftingResult(inv_craft, crafted, temp, true, gamedef); - PLAYER_TO_SA(player)->item_OnCraft( - crafted, player, &saved_craft_list, craft_inv); + PLAYER_TO_SA(player)->item_OnCraft(crafted, player, &saved_craft_list, craft_inv); list_craftresult->addItem(0, crafted); mgr->setInventoryModified(craft_inv); @@ -826,8 +834,7 @@ void ICraftAction::apply( for (auto &itemstack : temp) { for (auto &output_replacement : output_replacements) { if (itemstack.name == output_replacement.name) { - itemstack = output_replacement.addItem( - itemstack, itemdef); + itemstack = output_replacement.addItem(itemstack, itemdef); if (itemstack.empty()) continue; } @@ -835,8 +842,10 @@ void ICraftAction::apply( output_replacements.push_back(itemstack); } - actionstream << player->getDescription() << " crafts " - << crafted.getItemString() << std::endl; + actionstream << player->getDescription() + << " crafts " + << crafted.getItemString() + << std::endl; // Decrement counter if (count_remaining == 1) @@ -847,8 +856,7 @@ void ICraftAction::apply( // Get next crafting result getCraftingResult(inv_craft, crafted, temp, false, gamedef); - PLAYER_TO_SA(player)->item_CraftPredict( - crafted, player, list_craft, craft_inv); + PLAYER_TO_SA(player)->item_CraftPredict(crafted, player, list_craft, craft_inv); found = !crafted.empty(); } @@ -862,21 +870,20 @@ void ICraftAction::apply( u16 count = output_replacement.count; do { PLAYER_TO_SA(player)->item_OnDrop(output_replacement, player, - player->getBasePosition()); + player->getBasePosition()); if (count >= output_replacement.count) { - errorstream << "Couldn't drop replacement stack " - << output_replacement.getItemString() - << " because drop loop didn't " - "decrease count." - << std::endl; + errorstream << "Couldn't drop replacement stack " << + output_replacement.getItemString() << " because drop loop didn't " + "decrease count." << std::endl; break; } } while (!output_replacement.empty()); } - infostream << "ICraftAction::apply(): crafted " - << " craft_inv=\"" << craft_inv.dump() << "\"" << std::endl; + infostream<<"ICraftAction::apply(): crafted " + <<" craft_inv=\""< &output_replacements, bool decrementInput, - IGameDef *gamedef) + std::vector &output_replacements, + bool decrementInput, IGameDef *gamedef) { result.clear(); @@ -901,7 +909,7 @@ bool getCraftingResult(Inventory *inv, ItemStack &result, CraftInput ci; ci.method = CRAFT_METHOD_NORMAL; ci.width = clist->getWidth() ? clist->getWidth() : 3; - for (u16 i = 0; i < clist->getSize(); i++) + for (u16 i=0; i < clist->getSize(); i++) ci.items.push_back(clist->getItem(i)); // Find out what is crafted and add it to result item slot @@ -913,10 +921,11 @@ bool getCraftingResult(Inventory *inv, ItemStack &result, if (found && decrementInput) { // CraftInput has been changed, apply changes in clist - for (u16 i = 0; i < clist->getSize(); i++) { + for (u16 i=0; i < clist->getSize(); i++) { clist->changeItem(i, ci.items[i]); } } return found; } + diff --git a/src/inventorymanager.h b/src/inventorymanager.h index fa9e94b63..69bf30169 100644 --- a/src/inventorymanager.h +++ b/src/inventorymanager.h @@ -26,21 +26,29 @@ class ServerActiveObject; struct InventoryLocation { - enum Type - { + enum Type{ UNDEFINED, CURRENT_PLAYER, PLAYER, NODEMETA, - DETACHED, + DETACHED, } type; std::string name; // PLAYER, DETACHED - v3s16 p; // NODEMETA + v3s16 p; // NODEMETA - InventoryLocation() { setUndefined(); } - void setUndefined() { type = UNDEFINED; } - void setCurrentPlayer() { type = CURRENT_PLAYER; } + InventoryLocation() + { + setUndefined(); + } + void setUndefined() + { + type = UNDEFINED; + } + void setCurrentPlayer() + { + type = CURRENT_PLAYER; + } void setPlayer(const std::string &name_) { type = PLAYER; @@ -59,9 +67,9 @@ struct InventoryLocation bool operator==(const InventoryLocation &other) const { - if (type != other.type) + if(type != other.type) return false; - switch (type) { + switch(type){ case UNDEFINED: return false; case CURRENT_PLAYER: @@ -82,7 +90,7 @@ struct InventoryLocation void applyCurrentPlayer(const std::string &name_) { - if (type == CURRENT_PLAYER) + if(type == CURRENT_PLAYER) setPlayer(name_); } @@ -101,15 +109,14 @@ class InventoryManager virtual ~InventoryManager() = default; // Get an inventory (server and client) - virtual Inventory *getInventory(const InventoryLocation &loc) { return NULL; } - // Set modified (will be saved and sent over network; only on server) + virtual Inventory* getInventory(const InventoryLocation &loc){return NULL;} + // Set modified (will be saved and sent over network; only on server) virtual void setInventoryModified(const InventoryLocation &loc) {} - // Send inventory action to server (only on client) - virtual void inventoryAction(InventoryAction *a) {} + // Send inventory action to server (only on client) + virtual void inventoryAction(InventoryAction *a){} }; -enum class IAction : u16 -{ +enum class IAction : u16 { Move, Drop, Craft @@ -124,8 +131,7 @@ struct InventoryAction virtual void apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) = 0; virtual void clientApply(InventoryManager *mgr, IGameDef *gamedef) = 0; - virtual ~InventoryAction() = default; - ; + virtual ~InventoryAction() = default;; }; struct MoveAction @@ -153,7 +159,10 @@ struct IMoveAction : public InventoryAction, public MoveAction IMoveAction(std::istream &is, bool somewhere); - IAction getType() const { return IAction::Move; } + IAction getType() const + { + return IAction::Move; + } void serialize(std::ostream &os) const { @@ -185,15 +194,18 @@ struct IDropAction : public InventoryAction, public MoveAction IDropAction(std::istream &is); - IAction getType() const { return IAction::Drop; } + IAction getType() const + { + return IAction::Drop; + } void serialize(std::ostream &os) const { - os << "Drop "; - os << count << " "; - os << from_inv.dump() << " "; - os << from_list << " "; - os << from_i; + os<<"Drop "; + os< &output_replacements, bool decrementInput, - IGameDef *gamedef); + std::vector &output_replacements, + bool decrementInput, IGameDef *gamedef); diff --git a/src/irrlicht_changes/CGUITTFont.cpp b/src/irrlicht_changes/CGUITTFont.cpp index 3bd6957f5..bd4e700de 100644 --- a/src/irrlicht_changes/CGUITTFont.cpp +++ b/src/irrlicht_changes/CGUITTFont.cpp @@ -43,7 +43,7 @@ struct SGUITTFace : public virtual irr::IReferenceCounted { SGUITTFace() : face_buffer(0), face_buffer_size(0) { - memset((void *)&face, 0, sizeof(FT_Face)); + memset((void*)&face, 0, sizeof(FT_Face)); } ~SGUITTFace() @@ -53,15 +53,15 @@ struct SGUITTFace : public virtual irr::IReferenceCounted } FT_Face face; - FT_Byte *face_buffer; + FT_Byte* face_buffer; FT_Long face_buffer_size; }; // Static variables. FT_Library CGUITTFont::c_library; -core::map CGUITTFont::c_faces; +core::map CGUITTFont::c_faces; bool CGUITTFont::c_libraryLoaded = false; -scene::IMesh *CGUITTFont::shared_plane_ptr_ = 0; +scene::IMesh* CGUITTFont::shared_plane_ptr_ = 0; scene::SMesh CGUITTFont::shared_plane_; // @@ -72,14 +72,14 @@ scene::SMesh CGUITTFont::shared_plane_; inline void checkFontBitmapSize(const FT_Bitmap &bits) { if ((s32)bits.rows < 0 || (s32)bits.width < 0) { - std::cout << "Insane font glyph size. File: " << __FILE__ << " Line " - << __LINE__ << std::endl; + std::cout << "Insane font glyph size. File: " + << __FILE__ << " Line " << __LINE__ + << std::endl; abort(); } } -video::IImage *SGUITTGlyph::createGlyphImage( - const FT_Bitmap &bits, video::IVideoDriver *driver) const +video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const { // Make sure our casts to s32 in the loops below will not cause problems checkFontBitmapSize(bits); @@ -88,83 +88,76 @@ video::IImage *SGUITTGlyph::createGlyphImage( // Add 1 because textures are inclusive-exclusive. core::dimension2du d(bits.width + 1, bits.rows + 1); core::dimension2du texture_size; - // core::dimension2du texture_size(bits.width + 1, bits.rows + 1); + //core::dimension2du texture_size(bits.width + 1, bits.rows + 1); // Create and load our image now. - video::IImage *image = 0; - switch (bits.pixel_mode) { - case FT_PIXEL_MODE_MONO: { - // Create a blank image and fill it with transparent pixels. - texture_size = d.getOptimalSize(true, true); - image = driver->createImage(video::ECF_A1R5G5B5, texture_size); - image->fill(video::SColor(0, 255, 255, 255)); - - // Load the monochrome data in. - const u32 image_pitch = image->getPitch() / sizeof(u16); - u16 *image_data = (u16 *)image->lock(); - u8 *glyph_data = bits.buffer; - - for (s32 y = 0; y < (s32)bits.rows; ++y) { - u16 *row = image_data; - for (s32 x = 0; x < (s32)bits.width; ++x) { - // Monochrome bitmaps store 8 pixels per byte. The - // left-most pixel is the bit 0x80. So, we go through the - // data each bit at a time. - if ((glyph_data[y * bits.pitch + (x / 8)] & - (0x80 >> (x % 8))) != 0) - *row = 0xFFFF; - ++row; + video::IImage* image = 0; + switch (bits.pixel_mode) + { + case FT_PIXEL_MODE_MONO: + { + // Create a blank image and fill it with transparent pixels. + texture_size = d.getOptimalSize(true, true); + image = driver->createImage(video::ECF_A1R5G5B5, texture_size); + image->fill(video::SColor(0, 255, 255, 255)); + + // Load the monochrome data in. + const u32 image_pitch = image->getPitch() / sizeof(u16); + u16* image_data = (u16*)image->lock(); + u8* glyph_data = bits.buffer; + + for (s32 y = 0; y < (s32)bits.rows; ++y) + { + u16* row = image_data; + for (s32 x = 0; x < (s32)bits.width; ++x) + { + // Monochrome bitmaps store 8 pixels per byte. The left-most pixel is the bit 0x80. + // So, we go through the data each bit at a time. + if ((glyph_data[y * bits.pitch + (x / 8)] & (0x80 >> (x % 8))) != 0) + *row = 0xFFFF; + ++row; + } + image_data += image_pitch; } - image_data += image_pitch; + image->unlock(); + break; } - image->unlock(); - break; - } - case FT_PIXEL_MODE_GRAY: { - // Create our blank image. - texture_size = d.getOptimalSize( - !driver->queryFeature(video::EVDF_TEXTURE_NPOT), - !driver->queryFeature(video::EVDF_TEXTURE_NSQUARE), true, - 0); - image = driver->createImage(video::ECF_A8R8G8B8, texture_size); - image->fill(video::SColor(0, 255, 255, 255)); - - // Load the grayscale data in. - const float gray_count = static_cast(bits.num_grays); - const u32 image_pitch = image->getPitch() / sizeof(u32); - u32 *image_data = (u32 *)image->lock(); - u8 *glyph_data = bits.buffer; - for (s32 y = 0; y < (s32)bits.rows; ++y) { - u8 *row = glyph_data; - for (s32 x = 0; x < (s32)bits.width; ++x) { - image_data[y * image_pitch + x] |= - static_cast( - 255.0f * - (static_cast( - *row++) / - gray_count)) - << 24; - // data[y * image_pitch + x] |= ((u32)(*bitsdata++) << - // 24); + case FT_PIXEL_MODE_GRAY: + { + // Create our blank image. + texture_size = d.getOptimalSize(!driver->queryFeature(video::EVDF_TEXTURE_NPOT), !driver->queryFeature(video::EVDF_TEXTURE_NSQUARE), true, 0); + image = driver->createImage(video::ECF_A8R8G8B8, texture_size); + image->fill(video::SColor(0, 255, 255, 255)); + + // Load the grayscale data in. + const float gray_count = static_cast(bits.num_grays); + const u32 image_pitch = image->getPitch() / sizeof(u32); + u32* image_data = (u32*)image->lock(); + u8* glyph_data = bits.buffer; + for (s32 y = 0; y < (s32)bits.rows; ++y) + { + u8* row = glyph_data; + for (s32 x = 0; x < (s32)bits.width; ++x) + { + image_data[y * image_pitch + x] |= static_cast(255.0f * (static_cast(*row++) / gray_count)) << 24; + //data[y * image_pitch + x] |= ((u32)(*bitsdata++) << 24); + } + glyph_data += bits.pitch; } - glyph_data += bits.pitch; + image->unlock(); + break; } - image->unlock(); - break; - } - default: - // TODO: error message? - return 0; + default: + // TODO: error message? + return 0; } return image; } -void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver *driver, - u32 font_size, const FT_Int32 loadFlags) +void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags) { - if (isLoaded) - return; + if (isLoaded) return; // Set the size of the glyph. FT_Set_Pixel_Sizes(face, 0, font_size); @@ -182,10 +175,11 @@ void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver *dri offset = core::vector2di(glyph->bitmap_left, glyph->bitmap_top); // Try to get the last page with available slots. - CGUITTGlyphPage *page = parent->getLastGlyphPage(); + CGUITTGlyphPage* page = parent->getLastGlyphPage(); // If we need to make a new page, do that now. - if (!page) { + if (!page) + { page = parent->createGlyphPage(bits.pixel_mode); if (!page) // TODO: add error message? @@ -195,20 +189,17 @@ void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver *dri glyph_page = parent->getLastGlyphPageIndex(); u32 texture_side_length = page->texture->getOriginalSize().Width; core::vector2di page_position( - (page->used_slots % (texture_side_length / font_size)) * - font_size, - (page->used_slots / (texture_side_length / font_size)) * - font_size); + (page->used_slots % (texture_side_length / font_size)) * font_size, + (page->used_slots / (texture_side_length / font_size)) * font_size + ); source_rect.UpperLeftCorner = page_position; - source_rect.LowerRightCorner = core::vector2di( - page_position.X + bits.width, page_position.Y + bits.rows); + source_rect.LowerRightCorner = core::vector2di(page_position.X + bits.width, page_position.Y + bits.rows); page->dirty = true; ++page->used_slots; --page->available_slots; - // We grab the glyph bitmap here so the data won't be removed when the next glyph - // is loaded. + // We grab the glyph bitmap here so the data won't be removed when the next glyph is loaded. surface = createGlyphImage(bits, driver); // Set our glyph as loaded. @@ -217,7 +208,8 @@ void SGUITTGlyph::preload(u32 char_index, FT_Face face, video::IVideoDriver *dri void SGUITTGlyph::unload() { - if (surface) { + if (surface) + { surface->drop(); surface = 0; } @@ -226,19 +218,19 @@ void SGUITTGlyph::unload() ////////////////////// -CGUITTFont *CGUITTFont::createTTFont(IGUIEnvironment *env, const io::path &filename, - const u32 size, const bool antialias, const bool transparency, - const u32 shadow, const u32 shadow_alpha) +CGUITTFont* CGUITTFont::createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias, const bool transparency, const u32 shadow, const u32 shadow_alpha) { - if (!c_libraryLoaded) { + if (!c_libraryLoaded) + { if (FT_Init_FreeType(&c_library)) return 0; c_libraryLoaded = true; } - CGUITTFont *font = new CGUITTFont(env); + CGUITTFont* font = new CGUITTFont(env); bool ret = font->load(filename, size, antialias, transparency); - if (!ret) { + if (!ret) + { font->drop(); return 0; } @@ -249,19 +241,20 @@ CGUITTFont *CGUITTFont::createTTFont(IGUIEnvironment *env, const io::path &filen return font; } -CGUITTFont *CGUITTFont::createTTFont(IrrlichtDevice *device, const io::path &filename, - const u32 size, const bool antialias, const bool transparency) +CGUITTFont* CGUITTFont::createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias, const bool transparency) { - if (!c_libraryLoaded) { + if (!c_libraryLoaded) + { if (FT_Init_FreeType(&c_library)) return 0; c_libraryLoaded = true; } - CGUITTFont *font = new CGUITTFont(device->getGUIEnvironment()); + CGUITTFont* font = new CGUITTFont(device->getGUIEnvironment()); font->Device = device; bool ret = font->load(filename, size, antialias, transparency); - if (!ret) { + if (!ret) + { font->drop(); return 0; } @@ -269,14 +262,12 @@ CGUITTFont *CGUITTFont::createTTFont(IrrlichtDevice *device, const io::path &fil return font; } -CGUITTFont *CGUITTFont::create(IGUIEnvironment *env, const io::path &filename, - const u32 size, const bool antialias, const bool transparency) +CGUITTFont* CGUITTFont::create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias, const bool transparency) { return CGUITTFont::createTTFont(env, filename, size, antialias, transparency); } -CGUITTFont *CGUITTFont::create(IrrlichtDevice *device, const io::path &filename, - const u32 size, const bool antialias, const bool transparency) +CGUITTFont* CGUITTFont::create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias, const bool transparency) { return CGUITTFont::createTTFont(device, filename, size, antialias, transparency); } @@ -284,16 +275,16 @@ CGUITTFont *CGUITTFont::create(IrrlichtDevice *device, const io::path &filename, ////////////////////// //! Constructor. -CGUITTFont::CGUITTFont(IGUIEnvironment *env) : - use_monochrome(false), use_transparency(true), use_hinting(true), - use_auto_hinting(true), batch_load_size(1), Device(0), Environment(env), - Driver(0), GlobalKerningWidth(0), GlobalKerningHeight(0) +CGUITTFont::CGUITTFont(IGUIEnvironment *env) +: use_monochrome(false), use_transparency(true), use_hinting(true), use_auto_hinting(true), +batch_load_size(1), Device(0), Environment(env), Driver(0), GlobalKerningWidth(0), GlobalKerningHeight(0) { -#ifdef _DEBUG + #ifdef _DEBUG setDebugName("CGUITTFont"); -#endif + #endif - if (Environment) { + if (Environment) + { // don't grab environment, to avoid circular references Driver = Environment->getVideoDriver(); } @@ -303,24 +294,19 @@ CGUITTFont::CGUITTFont(IGUIEnvironment *env) : setInvisibleCharacters(L" "); - // Glyphs aren't reference counted, so don't try to delete them when we free the - // array. + // Glyphs aren't reference counted, so don't try to delete them when we free the array. Glyphs.set_free_when_destroyed(false); } -bool CGUITTFont::load(const io::path &filename, const u32 size, const bool antialias, - const bool transparency) +bool CGUITTFont::load(const io::path& filename, const u32 size, const bool antialias, const bool transparency) { // Some sanity checks. - if (Environment == 0 || Driver == 0) - return false; - if (size == 0) - return false; - if (filename.size() == 0) - return false; - - io::IFileSystem *filesystem = Environment->getFileSystem(); - irr::ILogger *logger = (Device != 0 ? Device->getLogger() : 0); + if (Environment == 0 || Driver == 0) return false; + if (size == 0) return false; + if (filename.size() == 0) return false; + + io::IFileSystem* filesystem = Environment->getFileSystem(); + irr::ILogger* logger = (Device != 0 ? Device->getLogger() : 0); this->size = size; this->filename = filename; @@ -331,32 +317,23 @@ bool CGUITTFont::load(const io::path &filename, const u32 size, const bool antia // Log. if (logger) - logger->log(L"CGUITTFont", - core::stringw(core::stringw(L"Creating new font: ") + - core::ustring(filename).toWCHAR_s() + - L" " + core::stringc(size) + L"pt " + - (antialias ? L"+antialias " - : L"-antialias ") + - (transparency ? L"+transparency" - : L"-transparency")) - .c_str(), - irr::ELL_INFORMATION); + logger->log(L"CGUITTFont", core::stringw(core::stringw(L"Creating new font: ") + core::ustring(filename).toWCHAR_s() + L" " + core::stringc(size) + L"pt " + (antialias ? L"+antialias " : L"-antialias ") + (transparency ? L"+transparency" : L"-transparency")).c_str(), irr::ELL_INFORMATION); // Grab the face. - SGUITTFace *face = 0; - core::map::Node *node = c_faces.find(filename); - if (node == 0) { + SGUITTFace* face = 0; + core::map::Node* node = c_faces.find(filename); + if (node == 0) + { face = new SGUITTFace(); c_faces.set(filename, face); - if (filesystem) { + if (filesystem) + { // Read in the file data. - io::IReadFile *file = filesystem->createAndOpenFile(filename); - if (file == 0) { - if (logger) - logger->log(L"CGUITTFont", - L"Failed to open the file.", - irr::ELL_INFORMATION); + io::IReadFile* file = filesystem->createAndOpenFile(filename); + if (file == 0) + { + if (logger) logger->log(L"CGUITTFont", L"Failed to open the file.", irr::ELL_INFORMATION); c_faces.remove(filename); delete face; @@ -369,27 +346,22 @@ bool CGUITTFont::load(const io::path &filename, const u32 size, const bool antia file->drop(); // Create the face. - if (FT_New_Memory_Face(c_library, face->face_buffer, - face->face_buffer_size, 0, &face->face)) { - if (logger) - logger->log(L"CGUITTFont", - L"FT_New_Memory_Face failed.", - irr::ELL_INFORMATION); + if (FT_New_Memory_Face(c_library, face->face_buffer, face->face_buffer_size, 0, &face->face)) + { + if (logger) logger->log(L"CGUITTFont", L"FT_New_Memory_Face failed.", irr::ELL_INFORMATION); c_faces.remove(filename); delete face; face = 0; return false; } - } else { + } + else + { core::ustring converter(filename); - if (FT_New_Face(c_library, - reinterpret_cast( - converter.toUTF8_s().c_str()), - 0, &face->face)) { - if (logger) - logger->log(L"CGUITTFont", L"FT_New_Face failed.", - irr::ELL_INFORMATION); + if (FT_New_Face(c_library, reinterpret_cast(converter.toUTF8_s().c_str()), 0, &face->face)) + { + if (logger) logger->log(L"CGUITTFont", L"FT_New_Face failed.", irr::ELL_INFORMATION); c_faces.remove(filename); delete face; @@ -397,7 +369,9 @@ bool CGUITTFont::load(const io::path &filename, const u32 size, const bool antia return false; } } - } else { + } + else + { // Using another instance of this face. face = node->getValue(); face->grab(); @@ -414,7 +388,8 @@ bool CGUITTFont::load(const io::path &filename, const u32 size, const bool antia Glyphs.clear(); Glyphs.reallocate(tt_face->num_glyphs); Glyphs.set_used(tt_face->num_glyphs); - for (FT_Long i = 0; i < tt_face->num_glyphs; ++i) { + for (FT_Long i = 0; i < tt_face->num_glyphs; ++i) + { Glyphs[i].isLoaded = false; Glyphs[i].glyph_page = 0; Glyphs[i].source_rect = core::recti(); @@ -438,20 +413,21 @@ CGUITTFont::~CGUITTFont() // Delete the glyphs and glyph pages. reset_images(); CGUITTAssistDelete::Delete(Glyphs); - // Glyphs.clear(); + //Glyphs.clear(); // We aren't using this face anymore. - core::map::Node *n = c_faces.find(filename); - if (n) { - SGUITTFace *f = n->getValue(); + core::map::Node* n = c_faces.find(filename); + if (n) + { + SGUITTFace* f = n->getValue(); - // Drop our face. If this was the last face, the destructor will clean - // up. + // Drop our face. If this was the last face, the destructor will clean up. if (f->drop()) c_faces.remove(filename); // If there are no more faces referenced by FreeType, clean up. - if (c_faces.size() == 0) { + if (c_faces.size() == 0) + { FT_Done_FreeType(c_library); c_libraryLoaded = false; } @@ -479,18 +455,20 @@ void CGUITTFont::reset_images() void CGUITTFont::update_glyph_pages() const { - for (u32 i = 0; i != Glyph_Pages.size(); ++i) { + for (u32 i = 0; i != Glyph_Pages.size(); ++i) + { if (Glyph_Pages[i]->dirty) Glyph_Pages[i]->updateTexture(); } } -CGUITTGlyphPage *CGUITTFont::getLastGlyphPage() const +CGUITTGlyphPage* CGUITTFont::getLastGlyphPage() const { - CGUITTGlyphPage *page = 0; + CGUITTGlyphPage* page = 0; if (Glyph_Pages.empty()) return 0; - else { + else + { page = Glyph_Pages[getLastGlyphPageIndex()]; if (page->available_slots == 0) page = 0; @@ -498,10 +476,10 @@ CGUITTGlyphPage *CGUITTFont::getLastGlyphPage() const return page; } -CGUITTGlyphPage *CGUITTFont::createGlyphPage(const u8 &pixel_mode) +CGUITTGlyphPage* CGUITTFont::createGlyphPage(const u8& pixel_mode) { - CGUITTGlyphPage *page = 0; - + CGUITTGlyphPage* page = 0; + // Name of our page. io::path name("TTFontGlyphPage_"); name += tt_face->family_name; @@ -510,8 +488,7 @@ CGUITTGlyphPage *CGUITTFont::createGlyphPage(const u8 &pixel_mode) name += "."; name += size; name += "_"; - name += Glyph_Pages.size(); // The newly created page will be at the end of the - // collection. + name += Glyph_Pages.size(); // The newly created page will be at the end of the collection. // Create the new page. page = new CGUITTGlyphPage(Driver, name); @@ -526,19 +503,13 @@ CGUITTGlyphPage *CGUITTFont::createGlyphPage(const u8 &pixel_mode) // We want to try to put at least 144 glyphs on a single texture. core::dimension2du page_texture_size; - if (size <= 21) - page_texture_size = core::dimension2du(256, 256); - else if (size <= 42) - page_texture_size = core::dimension2du(512, 512); - else if (size <= 84) - page_texture_size = core::dimension2du(1024, 1024); - else if (size <= 168) - page_texture_size = core::dimension2du(2048, 2048); - else - page_texture_size = core::dimension2du(4096, 4096); + if (size <= 21) page_texture_size = core::dimension2du(256, 256); + else if (size <= 42) page_texture_size = core::dimension2du(512, 512); + else if (size <= 84) page_texture_size = core::dimension2du(1024, 1024); + else if (size <= 168) page_texture_size = core::dimension2du(2048, 2048); + else page_texture_size = core::dimension2du(4096, 4096); - if (page_texture_size.Width > max_texture_size.Width || - page_texture_size.Height > max_texture_size.Height) + if (page_texture_size.Width > max_texture_size.Width || page_texture_size.Height > max_texture_size.Height) page_texture_size = max_texture_size; if (!page->createPageTexture(pixel_mode, page_texture_size)) { @@ -547,11 +518,10 @@ CGUITTGlyphPage *CGUITTFont::createGlyphPage(const u8 &pixel_mode) return 0; } - if (page) { - // Determine the number of glyph slots on the page and add it to the list - // of pages. - page->available_slots = (page_texture_size.Width / size) * - (page_texture_size.Height / size); + if (page) + { + // Determine the number of glyph slots on the page and add it to the list of pages. + page->available_slots = (page_texture_size.Width / size) * (page_texture_size.Height / size); Glyph_Pages.push_back(page); } return page; @@ -576,17 +546,12 @@ void CGUITTFont::setFontHinting(const bool enable, const bool enable_auto_hintin reset_images(); } -void CGUITTFont::draw(const core::stringw &text, const core::rect &position, - video::SColor color, bool hcenter, bool vcenter, - const core::rect *clip) +void CGUITTFont::draw(const core::stringw& text, const core::rect& position, video::SColor color, bool hcenter, bool vcenter, const core::rect* clip) { - draw(EnrichedString(std::wstring(text.c_str()), color), position, color, hcenter, - vcenter, clip); + draw(EnrichedString(std::wstring(text.c_str()), color), position, color, hcenter, vcenter, clip); } -void CGUITTFont::draw(const EnrichedString &text, const core::rect &position, - video::SColor color, bool hcenter, bool vcenter, - const core::rect *clip) +void CGUITTFont::draw(const EnrichedString &text, const core::rect& position, video::SColor color, bool hcenter, bool vcenter, const core::rect* clip) { std::vector colors = text.getColors(); @@ -594,7 +559,8 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect &positio return; // Clear the glyph pages of their render information. - for (u32 i = 0; i < Glyph_Pages.size(); ++i) { + for (u32 i = 0; i < Glyph_Pages.size(); ++i) + { Glyph_Pages[i]->render_positions.clear(); Glyph_Pages[i]->render_source_rects.clear(); } @@ -604,60 +570,62 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect &positio core::position2d offset = position.UpperLeftCorner; // Determine offset positions. - if (hcenter || vcenter) { + if (hcenter || vcenter) + { textDimension = getDimension(text.c_str()); if (hcenter) - offset.X = ((position.getWidth() - textDimension.Width) >> 1) + - offset.X; + offset.X = ((position.getWidth() - textDimension.Width) >> 1) + offset.X; if (vcenter) - offset.Y = ((position.getHeight() - textDimension.Height) >> 1) + - offset.Y; + offset.Y = ((position.getHeight() - textDimension.Height) >> 1) + offset.Y; } // Convert to a unicode string. core::ustring utext = text.getString(); // Set up our render map. - core::map Render_Map; + core::map Render_Map; // Start parsing characters. u32 n; uchar32_t previousChar = 0; core::ustring::const_iterator iter(utext); std::vector applied_colors; - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t currentChar = *iter; n = getGlyphIndexByChar(currentChar); bool visible = (Invisible.findFirst(currentChar) == -1); - bool lineBreak = false; + bool lineBreak=false; if (currentChar == L'\r') // Mac or Windows breaks { lineBreak = true; - if (*(iter + 1) == (uchar32_t)'\n') // Windows line breaks. + if (*(iter + 1) == (uchar32_t)'\n') // Windows line breaks. currentChar = *(++iter); - } else if (currentChar == (uchar32_t)'\n') // Unix breaks + } + else if (currentChar == (uchar32_t)'\n') // Unix breaks { lineBreak = true; } - if (lineBreak) { + if (lineBreak) + { previousChar = 0; offset.Y += font_metrics.height / 64; offset.X = position.UpperLeftCorner.X; if (hcenter) - offset.X += (position.getWidth() - textDimension.Width) >> - 1; + offset.X += (position.getWidth() - textDimension.Width) >> 1; ++iter; continue; } - if (n > 0 && visible) { + if (n > 0 && visible) + { // Calculate the glyph offset. - s32 offx = Glyphs[n - 1].offset.X; - s32 offy = (font_metrics.ascender / 64) - Glyphs[n - 1].offset.Y; + s32 offx = Glyphs[n-1].offset.X; + s32 offy = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y; // Apply kerning. core::vector2di k = getKerning(currentChar, previousChar); @@ -665,10 +633,9 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect &positio offset.Y += k.Y; // Determine rendering information. - SGUITTGlyph &glyph = Glyphs[n - 1]; - CGUITTGlyphPage *const page = Glyph_Pages[glyph.glyph_page]; - page->render_positions.push_back(core::position2di( - offset.X + offx, offset.Y + offy)); + SGUITTGlyph& glyph = Glyphs[n-1]; + CGUITTGlyphPage* const page = Glyph_Pages[glyph.glyph_page]; + page->render_positions.push_back(core::position2di(offset.X + offx, offset.Y + offy)); page->render_source_rects.push_back(glyph.source_rect); Render_Map.set(glyph.glyph_page, page); u32 current_color = iter.getPos(); @@ -683,25 +650,21 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect &positio // Draw now. update_glyph_pages(); - core::map::Iterator j = Render_Map.getIterator(); - while (!j.atEnd()) { - core::map::Node *n = j.getNode(); + core::map::Iterator j = Render_Map.getIterator(); + while (!j.atEnd()) + { + core::map::Node* n = j.getNode(); j++; - if (n == 0) - continue; + if (n == 0) continue; - CGUITTGlyphPage *page = n->getValue(); + CGUITTGlyphPage* page = n->getValue(); if (shadow_offset) { for (size_t i = 0; i < page->render_positions.size(); ++i) - page->render_positions[i] += core::vector2di( - shadow_offset, shadow_offset); - Driver->draw2DImageBatch(page->texture, page->render_positions, - page->render_source_rects, clip, - video::SColor(shadow_alpha, 0, 0, 0), true); + page->render_positions[i] += core::vector2di(shadow_offset, shadow_offset); + Driver->draw2DImageBatch(page->texture, page->render_positions, page->render_source_rects, clip, video::SColor(shadow_alpha,0,0,0), true); for (size_t i = 0; i < page->render_positions.size(); ++i) - page->render_positions[i] -= core::vector2di( - shadow_offset, shadow_offset); + page->render_positions[i] -= core::vector2di(shadow_offset, shadow_offset); } for (size_t i = 0; i < page->render_positions.size(); ++i) { irr::video::SColor col; @@ -712,24 +675,22 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect &positio } if (!use_transparency) col.color |= 0xff000000; - Driver->draw2DImage(page->texture, page->render_positions[i], - page->render_source_rects[i], clip, col, true); + Driver->draw2DImage(page->texture, page->render_positions[i], page->render_source_rects[i], clip, col, true); } } } core::dimension2d CGUITTFont::getCharDimension(const wchar_t ch) const { - return core::dimension2d( - getWidthFromCharacter(ch), getHeightFromCharacter(ch)); + return core::dimension2d(getWidthFromCharacter(ch), getHeightFromCharacter(ch)); } -core::dimension2d CGUITTFont::getDimension(const wchar_t *text) const +core::dimension2d CGUITTFont::getDimension(const wchar_t* text) const { return getDimension(core::ustring(text)); } -core::dimension2d CGUITTFont::getDimension(const core::ustring &text) const +core::dimension2d CGUITTFont::getDimension(const core::ustring& text) const { // Get the maximum font height. Unfortunately, we have to do this hack as // Irrlicht will draw things wrong. In FreeType, the font size is the @@ -748,17 +709,20 @@ core::dimension2d CGUITTFont::getDimension(const core::ustring &text) const uchar32_t previousChar = 0; core::ustring::const_iterator iter = text.begin(); - for (; !iter.atEnd(); ++iter) { + for (; !iter.atEnd(); ++iter) + { uchar32_t p = *iter; bool lineBreak = false; - if (p == '\r') // Mac or Windows line breaks. + if (p == '\r') // Mac or Windows line breaks. { lineBreak = true; - if (*(iter + 1) == '\n') { + if (*(iter + 1) == '\n') + { ++iter; p = *iter; } - } else if (p == '\n') // Unix line breaks. + } + else if (p == '\n') // Unix line breaks. { lineBreak = true; } @@ -769,7 +733,8 @@ core::dimension2d CGUITTFont::getDimension(const core::ustring &text) const previousChar = p; // Check for linebreak. - if (lineBreak) { + if (lineBreak) + { previousChar = 0; text_dimension.Height += line.Height; if (text_dimension.Width < line.Width) @@ -794,19 +759,18 @@ inline u32 CGUITTFont::getWidthFromCharacter(wchar_t c) const inline u32 CGUITTFont::getWidthFromCharacter(uchar32_t c) const { // Set the size of the face. - // This is because we cache faces and the face may have been set to a different - // size. - // FT_Set_Pixel_Sizes(tt_face, 0, size); + // This is because we cache faces and the face may have been set to a different size. + //FT_Set_Pixel_Sizes(tt_face, 0, size); u32 n = getGlyphIndexByChar(c); - if (n > 0) { - int w = Glyphs[n - 1].advance.x / 64; + if (n > 0) + { + int w = Glyphs[n-1].advance.x / 64; return w; } if (c >= 0x2000) return (font_metrics.ascender / 64); - else - return (font_metrics.ascender / 64) / 2; + else return (font_metrics.ascender / 64) / 2; } inline u32 CGUITTFont::getHeightFromCharacter(wchar_t c) const @@ -817,22 +781,19 @@ inline u32 CGUITTFont::getHeightFromCharacter(wchar_t c) const inline u32 CGUITTFont::getHeightFromCharacter(uchar32_t c) const { // Set the size of the face. - // This is because we cache faces and the face may have been set to a different - // size. - // FT_Set_Pixel_Sizes(tt_face, 0, size); + // This is because we cache faces and the face may have been set to a different size. + //FT_Set_Pixel_Sizes(tt_face, 0, size); u32 n = getGlyphIndexByChar(c); - if (n > 0) { - // Grab the true height of the character, taking into account underhanging - // glyphs. - s32 height = (font_metrics.ascender / 64) - Glyphs[n - 1].offset.Y + - Glyphs[n - 1].source_rect.getHeight(); + if (n > 0) + { + // Grab the true height of the character, taking into account underhanging glyphs. + s32 height = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y + Glyphs[n-1].source_rect.getHeight(); return height; } if (c >= 0x2000) return (font_metrics.ascender / 64); - else - return (font_metrics.ascender / 64) / 2; + else return (font_metrics.ascender / 64) / 2; } u32 CGUITTFont::getGlyphIndexByChar(wchar_t c) const @@ -845,11 +806,9 @@ u32 CGUITTFont::getGlyphIndexByChar(uchar32_t c) const // Get the glyph. u32 glyph = FT_Get_Char_Index(tt_face, c); - // Check for a valid glyph. If it is invalid, attempt to use the replacement - // character. + // Check for a valid glyph. If it is invalid, attempt to use the replacement character. if (glyph == 0) - glyph = FT_Get_Char_Index( - tt_face, core::unicode::UTF_REPLACEMENT_CHARACTER); + glyph = FT_Get_Char_Index(tt_face, core::unicode::UTF_REPLACEMENT_CHARACTER); // If our glyph is already loaded, don't bother doing any batch loading code. if (glyph != 0 && Glyphs[glyph - 1].isLoaded) @@ -858,44 +817,47 @@ u32 CGUITTFont::getGlyphIndexByChar(uchar32_t c) const // Determine our batch loading positions. u32 half_size = (batch_load_size / 2); u32 start_pos = 0; - if (c > half_size) - start_pos = c - half_size; + if (c > half_size) start_pos = c - half_size; u32 end_pos = start_pos + batch_load_size; // Load all our characters. - do { + do + { // Get the character we are going to load. u32 char_index = FT_Get_Char_Index(tt_face, start_pos); // If the glyph hasn't been loaded yet, do it now. - if (char_index) { - SGUITTGlyph &glyph = Glyphs[char_index - 1]; - if (!glyph.isLoaded) { - glyph.preload(char_index, tt_face, Driver, size, - load_flags); + if (char_index) + { + SGUITTGlyph& glyph = Glyphs[char_index - 1]; + if (!glyph.isLoaded) + { + glyph.preload(char_index, tt_face, Driver, size, load_flags); Glyph_Pages[glyph.glyph_page]->pushGlyphToBePaged(&glyph); } } - } while (++start_pos < end_pos); + } + while (++start_pos < end_pos); // Return our original character. return glyph; } -s32 CGUITTFont::getCharacterFromPos(const wchar_t *text, s32 pixel_x) const +s32 CGUITTFont::getCharacterFromPos(const wchar_t* text, s32 pixel_x) const { return getCharacterFromPos(core::ustring(text), pixel_x); } -s32 CGUITTFont::getCharacterFromPos(const core::ustring &text, s32 pixel_x) const +s32 CGUITTFont::getCharacterFromPos(const core::ustring& text, s32 pixel_x) const { s32 x = 0; - // s32 idx = 0; + //s32 idx = 0; u32 character = 0; uchar32_t previousChar = 0; core::ustring::const_iterator iter = text.begin(); - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t c = *iter; x += getWidthFromCharacter(c); @@ -924,8 +886,7 @@ void CGUITTFont::setKerningHeight(s32 kerning) GlobalKerningHeight = kerning; } -s32 CGUITTFont::getKerningWidth( - const wchar_t *thisLetter, const wchar_t *previousLetter) const +s32 CGUITTFont::getKerningWidth(const wchar_t* thisLetter, const wchar_t* previousLetter) const { if (tt_face == 0) return GlobalKerningWidth; @@ -935,8 +896,7 @@ s32 CGUITTFont::getKerningWidth( return getKerningWidth((uchar32_t)*thisLetter, (uchar32_t)*previousLetter); } -s32 CGUITTFont::getKerningWidth( - const uchar32_t thisLetter, const uchar32_t previousLetter) const +s32 CGUITTFont::getKerningWidth(const uchar32_t thisLetter, const uchar32_t previousLetter) const { // Return only the kerning width. return getKerning(thisLetter, previousLetter).X; @@ -948,21 +908,18 @@ s32 CGUITTFont::getKerningHeight() const return GlobalKerningHeight; } -core::vector2di CGUITTFont::getKerning( - const wchar_t thisLetter, const wchar_t previousLetter) const +core::vector2di CGUITTFont::getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const { return getKerning((uchar32_t)thisLetter, (uchar32_t)previousLetter); } -core::vector2di CGUITTFont::getKerning( - const uchar32_t thisLetter, const uchar32_t previousLetter) const +core::vector2di CGUITTFont::getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const { if (tt_face == 0 || thisLetter == 0 || previousLetter == 0) return core::vector2di(); // Set the size of the face. - // This is because we cache faces and the face may have been set to a different - // size. + // This is because we cache faces and the face may have been set to a different size. FT_Set_Pixel_Sizes(tt_face, 0, size); core::vector2di ret(GlobalKerningWidth, GlobalKerningHeight); @@ -973,15 +930,17 @@ core::vector2di CGUITTFont::getKerning( // Get the kerning information. FT_Vector v; - FT_Get_Kerning(tt_face, getGlyphIndexByChar(previousLetter), - getGlyphIndexByChar(thisLetter), FT_KERNING_DEFAULT, &v); + FT_Get_Kerning(tt_face, getGlyphIndexByChar(previousLetter), getGlyphIndexByChar(thisLetter), FT_KERNING_DEFAULT, &v); // If we have a scalable font, the return value will be in font points. - if (FT_IS_SCALABLE(tt_face)) { + if (FT_IS_SCALABLE(tt_face)) + { // Font points, so divide by 64. ret.X += (v.x / 64); ret.Y += (v.y / 64); - } else { + } + else + { // Pixel units. ret.X += v.x; ret.Y += v.y; @@ -995,44 +954,43 @@ void CGUITTFont::setInvisibleCharacters(const wchar_t *s) Invisible = us; } -void CGUITTFont::setInvisibleCharacters(const core::ustring &s) +void CGUITTFont::setInvisibleCharacters(const core::ustring& s) { Invisible = s; } -video::IImage *CGUITTFont::createTextureFromChar(const uchar32_t &ch) +video::IImage* CGUITTFont::createTextureFromChar(const uchar32_t& ch) { u32 n = getGlyphIndexByChar(ch); - const SGUITTGlyph &glyph = Glyphs[n - 1]; - CGUITTGlyphPage *page = Glyph_Pages[glyph.glyph_page]; + const SGUITTGlyph& glyph = Glyphs[n-1]; + CGUITTGlyphPage* page = Glyph_Pages[glyph.glyph_page]; if (page->dirty) page->updateTexture(); - video::ITexture *tex = page->texture; + video::ITexture* tex = page->texture; -// Acquire a read-only lock of the corresponding page texture. -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8 - void *ptr = tex->lock(video::ETLM_READ_ONLY); -#else - void *ptr = tex->lock(true); -#endif + // Acquire a read-only lock of the corresponding page texture. + #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8 + void* ptr = tex->lock(video::ETLM_READ_ONLY); + #else + void* ptr = tex->lock(true); + #endif video::ECOLOR_FORMAT format = tex->getColorFormat(); core::dimension2du tex_size = tex->getOriginalSize(); - video::IImage *pageholder = - Driver->createImageFromData(format, tex_size, ptr, true, false); + video::IImage* pageholder = Driver->createImageFromData(format, tex_size, ptr, true, false); // Copy the image data out of the page texture. core::dimension2du glyph_size(glyph.source_rect.getSize()); - video::IImage *image = Driver->createImage(format, glyph_size); + video::IImage* image = Driver->createImage(format, glyph_size); pageholder->copyTo(image, core::position2di(0, 0), glyph.source_rect); tex->unlock(); return image; } -video::ITexture *CGUITTFont::getPageTextureByIndex(const u32 &page_index) const +video::ITexture* CGUITTFont::getPageTextureByIndex(const u32& page_index) const { if (page_index < Glyph_Pages.size()) return Glyph_Pages[page_index]->texture; @@ -1054,71 +1012,60 @@ void CGUITTFont::createSharedPlane() using namespace video; using namespace scene; S3DVertex vertices[4]; - u16 indices[6] = {0, 2, 3, 3, 1, 0}; - vertices[0] = S3DVertex(vector3df(0, -1, 0), vector3df(0, 0, -1), - SColor(255, 255, 255, 255), vector2df(0, 1)); - vertices[1] = S3DVertex(vector3df(1, -1, 0), vector3df(0, 0, -1), - SColor(255, 255, 255, 255), vector2df(1, 1)); - vertices[2] = S3DVertex(vector3df(0, 0, 0), vector3df(0, 0, -1), - SColor(255, 255, 255, 255), vector2df(0, 0)); - vertices[3] = S3DVertex(vector3df(1, 0, 0), vector3df(0, 0, -1), - SColor(255, 255, 255, 255), vector2df(1, 0)); - - SMeshBuffer *buf = new SMeshBuffer(); + u16 indices[6] = {0,2,3,3,1,0}; + vertices[0] = S3DVertex(vector3df(0,-1,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(0,1)); + vertices[1] = S3DVertex(vector3df(1,-1,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(1,1)); + vertices[2] = S3DVertex(vector3df(0, 0,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(0,0)); + vertices[3] = S3DVertex(vector3df(1, 0,0), vector3df(0,0,-1), SColor(255,255,255,255), vector2df(1,0)); + + SMeshBuffer* buf = new SMeshBuffer(); buf->append(vertices, 4, indices, 6); - shared_plane_.addMeshBuffer(buf); + shared_plane_.addMeshBuffer( buf ); shared_plane_ptr_ = &shared_plane_; - buf->drop(); // the addMeshBuffer method will grab it, so we can drop this ptr. + buf->drop(); //the addMeshBuffer method will grab it, so we can drop this ptr. } -core::dimension2d CGUITTFont::getDimensionUntilEndOfLine(const wchar_t *p) const +core::dimension2d CGUITTFont::getDimensionUntilEndOfLine(const wchar_t* p) const { core::stringw s; - for (const wchar_t *temp = p; - temp && *temp != '\0' && *temp != L'\r' && *temp != L'\n'; ++temp) + for (const wchar_t* temp = p; temp && *temp != '\0' && *temp != L'\r' && *temp != L'\n'; ++temp ) s.append(*temp); return getDimension(s.c_str()); } -core::array CGUITTFont::addTextSceneNode(const wchar_t *text, - scene::ISceneManager *smgr, scene::ISceneNode *parent, - const video::SColor &color, bool center) +core::array CGUITTFont::addTextSceneNode(const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent, const video::SColor& color, bool center) { using namespace core; using namespace video; using namespace scene; - array container; + array container; - if (!Driver || !smgr) - return container; + if (!Driver || !smgr) return container; if (!parent) parent = smgr->addEmptySceneNode(smgr->getRootSceneNode(), -1); // if you don't specify parent, then we add a empty node attached to the root node // this is generally undesirable. - if (!shared_plane_ptr_) // this points to a static mesh that contains the plane - createSharedPlane(); // if it's not initialized, we create one. + if (!shared_plane_ptr_) //this points to a static mesh that contains the plane + createSharedPlane(); //if it's not initialized, we create one. - dimension2d text_size(getDimension(text)); // convert from unsigned to - // signed. + dimension2d text_size(getDimension(text)); //convert from unsigned to signed. vector3df start_point(0, 0, 0), offset; /** NOTICE: - Because we are considering adding texts into 3D world, all Y axis vectors - are inverted. + Because we are considering adding texts into 3D world, all Y axis vectors are inverted. **/ - // There's currently no "vertical center" concept when you apply text scene node - // to the 3D world. - if (center) { + // There's currently no "vertical center" concept when you apply text scene node to the 3D world. + if (center) + { offset.X = start_point.X = -text_size.Width / 2.f; - offset.Y = start_point.Y = +text_size.Height / 2.f; - offset.X += (text_size.Width - getDimensionUntilEndOfLine(text).Width) >> - 1; + offset.Y = start_point.Y = +text_size.Height/ 2.f; + offset.X += (text_size.Width - getDimensionUntilEndOfLine(text).Width) >> 1; } // the default font material @@ -1127,8 +1074,7 @@ core::array CGUITTFont::addTextSceneNode(const wchar_t *tex mat.setFlag(video::EMF_ZWRITE_ENABLE, false); mat.setFlag(video::EMF_NORMALIZE_NORMALS, true); mat.ColorMaterial = video::ECM_NONE; - mat.MaterialType = use_transparency ? video::EMT_TRANSPARENT_ALPHA_CHANNEL - : video::EMT_SOLID; + mat.MaterialType = use_transparency ? video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_SOLID; mat.MaterialTypeParam = 0.01f; mat.DiffuseColor = color; @@ -1137,36 +1083,39 @@ core::array CGUITTFont::addTextSceneNode(const wchar_t *tex array glyph_indices; - while (*text) { + while (*text) + { current_char = *text; - bool line_break = false; + bool line_break=false; if (current_char == L'\r') // Mac or Windows breaks { line_break = true; if (*(text + 1) == L'\n') // Windows line breaks. current_char = *(++text); - } else if (current_char == L'\n') // Unix breaks + } + else if (current_char == L'\n') // Unix breaks { line_break = true; } - if (line_break) { + if (line_break) + { previous_char = 0; offset.Y -= tt_face->size->metrics.ascender / 64; offset.X = start_point.X; if (center) - offset.X += (text_size.Width - getDimensionUntilEndOfLine( - text + 1) - .Width) >> - 1; + offset.X += (text_size.Width - getDimensionUntilEndOfLine(text+1).Width) >> 1; ++text; - } else { + } + else + { n = getGlyphIndexByChar(current_char); - if (n > 0) { - glyph_indices.push_back(n); + if (n > 0) + { + glyph_indices.push_back( n ); // Store glyph size and offset informations. - SGUITTGlyph const &glyph = Glyphs[n - 1]; + SGUITTGlyph const& glyph = Glyphs[n-1]; u32 texw = glyph.source_rect.getWidth(); u32 texh = glyph.source_rect.getHeight(); s32 offx = glyph.offset.X; @@ -1177,37 +1126,25 @@ core::array CGUITTFont::addTextSceneNode(const wchar_t *tex offset.X += k.X; offset.Y += k.Y; - vector3df current_pos( - offset.X + offx, offset.Y - offy, 0); - dimension2d letter_size = - dimension2d(texw, texh); + vector3df current_pos(offset.X + offx, offset.Y - offy, 0); + dimension2d letter_size = dimension2d(texw, texh); // Now we copy planes corresponding to the letter size. - IMeshManipulator *mani = smgr->getMeshManipulator(); - IMesh *meshcopy = mani->createMeshCopy(shared_plane_ptr_); -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8 - mani->scale(meshcopy, - vector3df((f32)letter_size.Width, - (f32)letter_size.Height, - 1)); -#else - mani->scaleMesh(meshcopy, - vector3df((f32)letter_size.Width, - (f32)letter_size.Height, - 1)); -#endif - - ISceneNode *current_node = smgr->addMeshSceneNode( - meshcopy, parent, -1, current_pos); + IMeshManipulator* mani = smgr->getMeshManipulator(); + IMesh* meshcopy = mani->createMeshCopy(shared_plane_ptr_); + #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8 + mani->scale(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1)); + #else + mani->scaleMesh(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1)); + #endif + + ISceneNode* current_node = smgr->addMeshSceneNode(meshcopy, parent, -1, current_pos); meshcopy->drop(); current_node->getMaterial(0) = mat; current_node->setAutomaticCulling(EAC_OFF); - current_node->setIsDebugObject( - true); // so the picking won't have any - // effect on individual letter - // current_node->setDebugDataVisible(EDS_BBOX); - // //de-comment this when debugging + current_node->setIsDebugObject(true); //so the picking won't have any effect on individual letter + //current_node->setDebugDataVisible(EDS_BBOX); //de-comment this when debugging container.push_back(current_node); } @@ -1218,37 +1155,33 @@ core::array CGUITTFont::addTextSceneNode(const wchar_t *tex } update_glyph_pages(); - // only after we update the textures can we use the glyph page textures. + //only after we update the textures can we use the glyph page textures. - for (u32 i = 0; i < glyph_indices.size(); ++i) { + for (u32 i = 0; i < glyph_indices.size(); ++i) + { u32 n = glyph_indices[i]; - SGUITTGlyph const &glyph = Glyphs[n - 1]; - ITexture *current_tex = Glyph_Pages[glyph.glyph_page]->texture; + SGUITTGlyph const& glyph = Glyphs[n-1]; + ITexture* current_tex = Glyph_Pages[glyph.glyph_page]->texture; f32 page_texture_size = (f32)current_tex->getSize().Width; - // Now we calculate the UV position according to the texture size and the - // source rect. + //Now we calculate the UV position according to the texture size and the source rect. // // 2___3 // | /| - // | / | <-- plane mesh is like this, point 2 is (0,0), point 0 is (0, - // -1) - // |/ | <-- the texture coords of point 2 is (0,0, point 0 is (0, - // 1) 0---1 + // | / | <-- plane mesh is like this, point 2 is (0,0), point 0 is (0, -1) + // |/ | <-- the texture coords of point 2 is (0,0, point 0 is (0, 1) + // 0---1 // f32 u1 = glyph.source_rect.UpperLeftCorner.X / page_texture_size; f32 u2 = u1 + (glyph.source_rect.getWidth() / page_texture_size); f32 v1 = glyph.source_rect.UpperLeftCorner.Y / page_texture_size; f32 v2 = v1 + (glyph.source_rect.getHeight() / page_texture_size); - // we can be quite sure that this is IMeshSceneNode, because we just added - // them in the above loop. - IMeshSceneNode *node = static_cast(container[i]); + //we can be quite sure that this is IMeshSceneNode, because we just added them in the above loop. + IMeshSceneNode* node = static_cast(container[i]); - S3DVertex *pv = static_cast( - node->getMesh()->getMeshBuffer(0)->getVertices()); - // pv[0].TCoords.Y = pv[1].TCoords.Y = (letter_size.Height - 1) / - // static_cast(letter_size.Height); pv[1].TCoords.X = pv[3].TCoords.X - // = (letter_size.Width - 1) / static_cast(letter_size.Width); + S3DVertex* pv = static_cast(node->getMesh()->getMeshBuffer(0)->getVertices()); + //pv[0].TCoords.Y = pv[1].TCoords.Y = (letter_size.Height - 1) / static_cast(letter_size.Height); + //pv[1].TCoords.X = pv[3].TCoords.X = (letter_size.Width - 1) / static_cast(letter_size.Width); pv[0].TCoords = vector2df(u1, v2); pv[1].TCoords = vector2df(u2, v2); pv[2].TCoords = vector2df(u1, v1); diff --git a/src/irrlicht_changes/CGUITTFont.h b/src/irrlicht_changes/CGUITTFont.h index bccc5b2f8..cf64934a2 100644 --- a/src/irrlicht_changes/CGUITTFont.h +++ b/src/irrlicht_changes/CGUITTFont.h @@ -42,393 +42,352 @@ namespace irr { namespace gui { -struct SGUITTFace; -class CGUITTFont; + struct SGUITTFace; + class CGUITTFont; -//! Class to assist in deleting glyphs. -class CGUITTAssistDelete -{ -public: - template static void Delete(core::array &a) + //! Class to assist in deleting glyphs. + class CGUITTAssistDelete { - TAlloc allocator; - allocator.deallocate(a.pointer()); - } -}; + public: + template + static void Delete(core::array& a) + { + TAlloc allocator; + allocator.deallocate(a.pointer()); + } + }; -//! Structure representing a single TrueType glyph. -struct SGUITTGlyph -{ - //! Constructor. - SGUITTGlyph() : isLoaded(false), glyph_page(0), surface(0), parent(0) {} + //! Structure representing a single TrueType glyph. + struct SGUITTGlyph + { + //! Constructor. + SGUITTGlyph() : isLoaded(false), glyph_page(0), surface(0), parent(0) {} - //! Destructor. - ~SGUITTGlyph() { unload(); } + //! Destructor. + ~SGUITTGlyph() { unload(); } - //! Preload the glyph. - //! The preload process occurs when the program tries to cache the glyph from - //!FT_Library. - //! However, it simply defines the SGUITTGlyph's properties and will only create - //! the page textures if necessary. The actual creation of the textures should - //! only occur right before the batch draw call. - void preload(u32 char_index, FT_Face face, video::IVideoDriver *driver, - u32 font_size, const FT_Int32 loadFlags); + //! Preload the glyph. + //! The preload process occurs when the program tries to cache the glyph from FT_Library. + //! However, it simply defines the SGUITTGlyph's properties and will only create the page + //! textures if necessary. The actual creation of the textures should only occur right + //! before the batch draw call. + void preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags); - //! Unloads the glyph. - void unload(); + //! Unloads the glyph. + void unload(); - //! Creates the IImage object from the FT_Bitmap. - video::IImage *createGlyphImage( - const FT_Bitmap &bits, video::IVideoDriver *driver) const; + //! Creates the IImage object from the FT_Bitmap. + video::IImage* createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const; - //! If true, the glyph has been loaded. - bool isLoaded; + //! If true, the glyph has been loaded. + bool isLoaded; - //! The page the glyph is on. - u32 glyph_page; + //! The page the glyph is on. + u32 glyph_page; - //! The source rectangle for the glyph. - core::recti source_rect; + //! The source rectangle for the glyph. + core::recti source_rect; - //! The offset of glyph when drawn. - core::vector2di offset; + //! The offset of glyph when drawn. + core::vector2di offset; - //! Glyph advance information. - FT_Vector advance; + //! Glyph advance information. + FT_Vector advance; - //! This is just the temporary image holder. After this glyph is paged, - //! it will be dropped. - mutable video::IImage *surface; + //! This is just the temporary image holder. After this glyph is paged, + //! it will be dropped. + mutable video::IImage* surface; - //! The pointer pointing to the parent (CGUITTFont) - CGUITTFont *parent; -}; + //! The pointer pointing to the parent (CGUITTFont) + CGUITTFont* parent; + }; -//! Holds a sheet of glyphs. -class CGUITTGlyphPage -{ -public: - CGUITTGlyphPage(video::IVideoDriver *Driver, const io::path &texture_name) : - texture(0), available_slots(0), used_slots(0), dirty(false), - driver(Driver), name(texture_name) - { - } - ~CGUITTGlyphPage() + //! Holds a sheet of glyphs. + class CGUITTGlyphPage { - if (texture) { - if (driver) - driver->removeTexture(texture); - else - texture->drop(); - } - } - - //! Create the actual page texture, - bool createPageTexture( - const u8 &pixel_mode, const core::dimension2du &texture_size) - { - if (texture) - return false; + public: + CGUITTGlyphPage(video::IVideoDriver* Driver, const io::path& texture_name) :texture(0), available_slots(0), used_slots(0), dirty(false), driver(Driver), name(texture_name) {} + ~CGUITTGlyphPage() + { + if (texture) + { + if (driver) + driver->removeTexture(texture); + else texture->drop(); + } + } - bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS); - driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); + //! Create the actual page texture, + bool createPageTexture(const u8& pixel_mode, const core::dimension2du& texture_size) + { + if( texture ) + return false; + + bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS); + driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 - bool flgcpy = driver->getTextureCreationFlag( - video::ETCF_ALLOW_MEMORY_COPY); - driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, true); + bool flgcpy = driver->getTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY); + driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, true); #endif - // Set the texture color format. - switch (pixel_mode) { - case FT_PIXEL_MODE_MONO: - texture = driver->addTexture( - texture_size, name, video::ECF_A1R5G5B5); - break; - case FT_PIXEL_MODE_GRAY: - default: - texture = driver->addTexture( - texture_size, name, video::ECF_A8R8G8B8); - break; - } - - // Restore our texture creation flags. - driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip); + // Set the texture color format. + switch (pixel_mode) + { + case FT_PIXEL_MODE_MONO: + texture = driver->addTexture(texture_size, name, video::ECF_A1R5G5B5); + break; + case FT_PIXEL_MODE_GRAY: + default: + texture = driver->addTexture(texture_size, name, video::ECF_A8R8G8B8); + break; + } + + // Restore our texture creation flags. + driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip); #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 - driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, flgcpy); + driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, flgcpy); #endif - return texture ? true : false; - } + return texture ? true : false; + } - //! Add the glyph to a list of glyphs to be paged. - //! This collection will be cleared after updateTexture is called. - void pushGlyphToBePaged(const SGUITTGlyph *glyph) - { - glyph_to_be_paged.push_back(glyph); - } + //! Add the glyph to a list of glyphs to be paged. + //! This collection will be cleared after updateTexture is called. + void pushGlyphToBePaged(const SGUITTGlyph* glyph) + { + glyph_to_be_paged.push_back(glyph); + } - //! Updates the texture atlas with new glyphs. - void updateTexture() - { - if (!dirty) - return; - - void *ptr = texture->lock(); - video::ECOLOR_FORMAT format = texture->getColorFormat(); - core::dimension2du size = texture->getOriginalSize(); - video::IImage *pageholder = driver->createImageFromData( - format, size, ptr, true, false); - - for (u32 i = 0; i < glyph_to_be_paged.size(); ++i) { - const SGUITTGlyph *glyph = glyph_to_be_paged[i]; - if (glyph && glyph->isLoaded) { - if (glyph->surface) { - glyph->surface->copyTo(pageholder, - glyph->source_rect - .UpperLeftCorner); - glyph->surface->drop(); - glyph->surface = 0; - } else { - ; // TODO: add error message? - // currently, if we failed to create the image, - // just ignore this operation. + //! Updates the texture atlas with new glyphs. + void updateTexture() + { + if (!dirty) return; + + void* ptr = texture->lock(); + video::ECOLOR_FORMAT format = texture->getColorFormat(); + core::dimension2du size = texture->getOriginalSize(); + video::IImage* pageholder = driver->createImageFromData(format, size, ptr, true, false); + + for (u32 i = 0; i < glyph_to_be_paged.size(); ++i) + { + const SGUITTGlyph* glyph = glyph_to_be_paged[i]; + if (glyph && glyph->isLoaded) + { + if (glyph->surface) + { + glyph->surface->copyTo(pageholder, glyph->source_rect.UpperLeftCorner); + glyph->surface->drop(); + glyph->surface = 0; + } + else + { + ; // TODO: add error message? + //currently, if we failed to create the image, just ignore this operation. + } + } } + + pageholder->drop(); + texture->unlock(); + glyph_to_be_paged.clear(); + dirty = false; } - } - - pageholder->drop(); - texture->unlock(); - glyph_to_be_paged.clear(); - dirty = false; - } - - video::ITexture *texture; - u32 available_slots; - u32 used_slots; - bool dirty; - - core::array render_positions; - core::array render_source_rects; - -private: - core::array glyph_to_be_paged; - video::IVideoDriver *driver; - io::path name; -}; - -//! Class representing a TrueType font. -class CGUITTFont : public IGUIFont -{ -public: - //! Creates a new TrueType font and returns a pointer to it. The pointer must be - //! drop()'ed when finished. \param env The IGUIEnvironment the font loads out of. - //! \param filename The filename of the font. - //! \param size The size of the font glyphs in pixels. Since this is the size of - //! the individual glyphs, the true height of the font may change depending on the - //! characters used. \param antialias set the use_monochrome (opposite to - //! antialias) flag \param transparency set the use_transparency flag \return - //! Returns a pointer to a CGUITTFont. Will return 0 if the font failed to load. - static CGUITTFont *createTTFont(IGUIEnvironment *env, const io::path &filename, - const u32 size, const bool antialias = true, - const bool transparency = true, const u32 shadow = 0, - const u32 shadow_alpha = 255); - static CGUITTFont *createTTFont(IrrlichtDevice *device, const io::path &filename, - const u32 size, const bool antialias = true, - const bool transparency = true); - static CGUITTFont *create(IGUIEnvironment *env, const io::path &filename, - const u32 size, const bool antialias = true, - const bool transparency = true); - static CGUITTFont *create(IrrlichtDevice *device, const io::path &filename, - const u32 size, const bool antialias = true, - const bool transparency = true); - - //! Destructor - virtual ~CGUITTFont(); - - //! Sets the amount of glyphs to batch load. - virtual void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; } - - //! Sets the maximum texture size for a page of glyphs. - virtual void setMaxPageTextureSize(const core::dimension2du &texture_size) - { - max_page_texture_size = texture_size; - } - - //! Get the font size. - virtual u32 getFontSize() const { return size; } - - //! Check the font's transparency. - virtual bool isTransparent() const { return use_transparency; } - - //! Check if the font auto-hinting is enabled. - //! Auto-hinting is FreeType's built-in font hinting engine. - virtual bool useAutoHinting() const { return use_auto_hinting; } - - //! Check if the font hinting is enabled. - virtual bool useHinting() const { return use_hinting; } - - //! Check if the font is being loaded as a monochrome font. - //! The font can either be a 256 color grayscale font, or a 2 color monochrome - //! font. - virtual bool useMonochrome() const { return use_monochrome; } - - //! Tells the font to allow transparency when rendering. - //! Default: true. - //! \param flag If true, the font draws using transparency. - virtual void setTransparency(const bool flag); - - //! Tells the font to use monochrome rendering. - //! Default: false. - //! \param flag If true, the font draws using a monochrome image. If false, the - //! font uses a grayscale image. - virtual void setMonochrome(const bool flag); - - //! Enables or disables font hinting. - //! Default: Hinting and auto-hinting true. - //! \param enable If false, font hinting is turned off. If true, font hinting is - //! turned on. \param enable_auto_hinting If true, FreeType uses its own - //! auto-hinting algorithm. If false, it tries to use the algorithm specified by - //! the font. - virtual void setFontHinting( - const bool enable, const bool enable_auto_hinting = true); - - //! Draws some text and clips it to the specified rectangle if wanted. - virtual void draw(const core::stringw &text, const core::rect &position, - video::SColor color, bool hcenter = false, bool vcenter = false, - const core::rect *clip = 0); - - virtual void draw(const EnrichedString &text, const core::rect &position, - video::SColor color, bool hcenter = false, bool vcenter = false, - const core::rect *clip = 0); - - //! Returns the dimension of a character produced by this font. - virtual core::dimension2d getCharDimension(const wchar_t ch) const; - - //! Returns the dimension of a text string. - virtual core::dimension2d getDimension(const wchar_t *text) const; - virtual core::dimension2d getDimension(const core::ustring &text) const; - - //! Calculates the index of the character in the text which is on a specific - //! position. - virtual s32 getCharacterFromPos(const wchar_t *text, s32 pixel_x) const; - virtual s32 getCharacterFromPos(const core::ustring &text, s32 pixel_x) const; - - //! Sets global kerning width for the font. - virtual void setKerningWidth(s32 kerning); - - //! Sets global kerning height for the font. - virtual void setKerningHeight(s32 kerning); - - //! Gets kerning values (distance between letters) for the font. If no parameters - //! are provided, - virtual s32 getKerningWidth(const wchar_t *thisLetter = 0, - const wchar_t *previousLetter = 0) const; - virtual s32 getKerningWidth(const uchar32_t thisLetter = 0, - const uchar32_t previousLetter = 0) const; - - //! Returns the distance between letters - virtual s32 getKerningHeight() const; - - //! Define which characters should not be drawn by the font. - virtual void setInvisibleCharacters(const wchar_t *s); - virtual void setInvisibleCharacters(const core::ustring &s); - - //! Get the last glyph page if there's still available slots. - //! If not, it will return zero. - CGUITTGlyphPage *getLastGlyphPage() const; - - //! Create a new glyph page texture. - //! \param pixel_mode the pixel mode defined by FT_Pixel_Mode - // should be better typed. fix later. - CGUITTGlyphPage *createGlyphPage(const u8 &pixel_mode); - - //! Get the last glyph page's index. - u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; } - - //! Create corresponding character's software image copy from the font, - //! so you can use this data just like any ordinary video::IImage. - //! \param ch The character you need - virtual video::IImage *createTextureFromChar(const uchar32_t &ch); - - //! This function is for debugging mostly. If the page doesn't exist it returns - //! zero. \param page_index Simply return the texture handle of a given page - //! index. - virtual video::ITexture *getPageTextureByIndex(const u32 &page_index) const; - - //! Add a list of scene nodes generated by putting font textures on the 3D planes. - virtual core::array addTextSceneNode(const wchar_t *text, - scene::ISceneManager *smgr, scene::ISceneNode *parent = 0, - const video::SColor &color = video::SColor(255, 0, 0, 0), - bool center = false); - - inline s32 getAscender() const { return font_metrics.ascender; } - -protected: - bool use_monochrome; - bool use_transparency; - bool use_hinting; - bool use_auto_hinting; - u32 size; - u32 batch_load_size; - core::dimension2du max_page_texture_size; - -private: - // Manages the FreeType library. - static FT_Library c_library; - static core::map c_faces; - static bool c_libraryLoaded; - static scene::IMesh *shared_plane_ptr_; - static scene::SMesh shared_plane_; - - CGUITTFont(IGUIEnvironment *env); - bool load(const io::path &filename, const u32 size, const bool antialias, - const bool transparency); - void reset_images(); - void update_glyph_pages() const; - void update_load_flags() + + video::ITexture* texture; + u32 available_slots; + u32 used_slots; + bool dirty; + + core::array render_positions; + core::array render_source_rects; + + private: + core::array glyph_to_be_paged; + video::IVideoDriver* driver; + io::path name; + }; + + //! Class representing a TrueType font. + class CGUITTFont : public IGUIFont { - // Set up our loading flags. - load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER; - if (!useHinting()) - load_flags |= FT_LOAD_NO_HINTING; - if (!useAutoHinting()) - load_flags |= FT_LOAD_NO_AUTOHINT; - if (useMonochrome()) - load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO | - FT_RENDER_MODE_MONO; - else - load_flags |= FT_LOAD_TARGET_NORMAL; - } - u32 getWidthFromCharacter(wchar_t c) const; - u32 getWidthFromCharacter(uchar32_t c) const; - u32 getHeightFromCharacter(wchar_t c) const; - u32 getHeightFromCharacter(uchar32_t c) const; - u32 getGlyphIndexByChar(wchar_t c) const; - u32 getGlyphIndexByChar(uchar32_t c) const; - core::vector2di getKerning( - const wchar_t thisLetter, const wchar_t previousLetter) const; - core::vector2di getKerning( - const uchar32_t thisLetter, const uchar32_t previousLetter) const; - core::dimension2d getDimensionUntilEndOfLine(const wchar_t *p) const; - - void createSharedPlane(); - - irr::IrrlichtDevice *Device; - gui::IGUIEnvironment *Environment; - video::IVideoDriver *Driver; - io::path filename; - FT_Face tt_face; - FT_Size_Metrics font_metrics; - FT_Int32 load_flags; - - mutable core::array Glyph_Pages; - mutable core::array Glyphs; - - s32 GlobalKerningWidth; - s32 GlobalKerningHeight; - core::ustring Invisible; - u32 shadow_offset; - u32 shadow_alpha; -}; + public: + //! Creates a new TrueType font and returns a pointer to it. The pointer must be drop()'ed when finished. + //! \param env The IGUIEnvironment the font loads out of. + //! \param filename The filename of the font. + //! \param size The size of the font glyphs in pixels. Since this is the size of the individual glyphs, the true height of the font may change depending on the characters used. + //! \param antialias set the use_monochrome (opposite to antialias) flag + //! \param transparency set the use_transparency flag + //! \return Returns a pointer to a CGUITTFont. Will return 0 if the font failed to load. + static CGUITTFont* createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true, const u32 shadow = 0, const u32 shadow_alpha = 255); + static CGUITTFont* createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true); + static CGUITTFont* create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true); + static CGUITTFont* create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true); + + //! Destructor + virtual ~CGUITTFont(); + + //! Sets the amount of glyphs to batch load. + virtual void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; } + + //! Sets the maximum texture size for a page of glyphs. + virtual void setMaxPageTextureSize(const core::dimension2du& texture_size) { max_page_texture_size = texture_size; } + + //! Get the font size. + virtual u32 getFontSize() const { return size; } + + //! Check the font's transparency. + virtual bool isTransparent() const { return use_transparency; } + + //! Check if the font auto-hinting is enabled. + //! Auto-hinting is FreeType's built-in font hinting engine. + virtual bool useAutoHinting() const { return use_auto_hinting; } + + //! Check if the font hinting is enabled. + virtual bool useHinting() const { return use_hinting; } + + //! Check if the font is being loaded as a monochrome font. + //! The font can either be a 256 color grayscale font, or a 2 color monochrome font. + virtual bool useMonochrome() const { return use_monochrome; } + + //! Tells the font to allow transparency when rendering. + //! Default: true. + //! \param flag If true, the font draws using transparency. + virtual void setTransparency(const bool flag); + + //! Tells the font to use monochrome rendering. + //! Default: false. + //! \param flag If true, the font draws using a monochrome image. If false, the font uses a grayscale image. + virtual void setMonochrome(const bool flag); + + //! Enables or disables font hinting. + //! Default: Hinting and auto-hinting true. + //! \param enable If false, font hinting is turned off. If true, font hinting is turned on. + //! \param enable_auto_hinting If true, FreeType uses its own auto-hinting algorithm. If false, it tries to use the algorithm specified by the font. + virtual void setFontHinting(const bool enable, const bool enable_auto_hinting = true); + + //! Draws some text and clips it to the specified rectangle if wanted. + virtual void draw(const core::stringw& text, const core::rect& position, + video::SColor color, bool hcenter=false, bool vcenter=false, + const core::rect* clip=0); + + virtual void draw(const EnrichedString& text, const core::rect& position, + video::SColor color, bool hcenter=false, bool vcenter=false, + const core::rect* clip=0); + + //! Returns the dimension of a character produced by this font. + virtual core::dimension2d getCharDimension(const wchar_t ch) const; + + //! Returns the dimension of a text string. + virtual core::dimension2d getDimension(const wchar_t* text) const; + virtual core::dimension2d getDimension(const core::ustring& text) const; + + //! Calculates the index of the character in the text which is on a specific position. + virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const; + virtual s32 getCharacterFromPos(const core::ustring& text, s32 pixel_x) const; + + //! Sets global kerning width for the font. + virtual void setKerningWidth(s32 kerning); + + //! Sets global kerning height for the font. + virtual void setKerningHeight(s32 kerning); + + //! Gets kerning values (distance between letters) for the font. If no parameters are provided, + virtual s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const; + virtual s32 getKerningWidth(const uchar32_t thisLetter=0, const uchar32_t previousLetter=0) const; + + //! Returns the distance between letters + virtual s32 getKerningHeight() const; + + //! Define which characters should not be drawn by the font. + virtual void setInvisibleCharacters(const wchar_t *s); + virtual void setInvisibleCharacters(const core::ustring& s); + + //! Get the last glyph page if there's still available slots. + //! If not, it will return zero. + CGUITTGlyphPage* getLastGlyphPage() const; + + //! Create a new glyph page texture. + //! \param pixel_mode the pixel mode defined by FT_Pixel_Mode + //should be better typed. fix later. + CGUITTGlyphPage* createGlyphPage(const u8& pixel_mode); + + //! Get the last glyph page's index. + u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; } + + //! Create corresponding character's software image copy from the font, + //! so you can use this data just like any ordinary video::IImage. + //! \param ch The character you need + virtual video::IImage* createTextureFromChar(const uchar32_t& ch); + + //! This function is for debugging mostly. If the page doesn't exist it returns zero. + //! \param page_index Simply return the texture handle of a given page index. + virtual video::ITexture* getPageTextureByIndex(const u32& page_index) const; + + //! Add a list of scene nodes generated by putting font textures on the 3D planes. + virtual core::array addTextSceneNode + (const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent = 0, + const video::SColor& color = video::SColor(255, 0, 0, 0), bool center = false ); + + inline s32 getAscender() const { return font_metrics.ascender; } + + protected: + bool use_monochrome; + bool use_transparency; + bool use_hinting; + bool use_auto_hinting; + u32 size; + u32 batch_load_size; + core::dimension2du max_page_texture_size; + + private: + // Manages the FreeType library. + static FT_Library c_library; + static core::map c_faces; + static bool c_libraryLoaded; + static scene::IMesh* shared_plane_ptr_; + static scene::SMesh shared_plane_; + + CGUITTFont(IGUIEnvironment *env); + bool load(const io::path& filename, const u32 size, const bool antialias, const bool transparency); + void reset_images(); + void update_glyph_pages() const; + void update_load_flags() + { + // Set up our loading flags. + load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER; + if (!useHinting()) load_flags |= FT_LOAD_NO_HINTING; + if (!useAutoHinting()) load_flags |= FT_LOAD_NO_AUTOHINT; + if (useMonochrome()) load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO | FT_RENDER_MODE_MONO; + else load_flags |= FT_LOAD_TARGET_NORMAL; + } + u32 getWidthFromCharacter(wchar_t c) const; + u32 getWidthFromCharacter(uchar32_t c) const; + u32 getHeightFromCharacter(wchar_t c) const; + u32 getHeightFromCharacter(uchar32_t c) const; + u32 getGlyphIndexByChar(wchar_t c) const; + u32 getGlyphIndexByChar(uchar32_t c) const; + core::vector2di getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const; + core::vector2di getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const; + core::dimension2d getDimensionUntilEndOfLine(const wchar_t* p) const; + + void createSharedPlane(); + + irr::IrrlichtDevice* Device; + gui::IGUIEnvironment* Environment; + video::IVideoDriver* Driver; + io::path filename; + FT_Face tt_face; + FT_Size_Metrics font_metrics; + FT_Int32 load_flags; + + mutable core::array Glyph_Pages; + mutable core::array Glyphs; + + s32 GlobalKerningWidth; + s32 GlobalKerningHeight; + core::ustring Invisible; + u32 shadow_offset; + u32 shadow_alpha; + }; } // end namespace gui } // end namespace irr diff --git a/src/irrlicht_changes/irrUString.h b/src/irrlicht_changes/irrUString.h index 9ff3d1b4d..b628c092c 100644 --- a/src/irrlicht_changes/irrUString.h +++ b/src/irrlicht_changes/irrUString.h @@ -31,11 +31,10 @@ #pragma once #if (__cplusplus > 199711L) || (_MSC_VER >= 1600) || defined(__GXX_EXPERIMENTAL_CXX0X__) -#define USTRING_CPP0X -#if defined(__GXX_EXPERIMENTAL_CXX0X__) && \ - ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5))) -#define USTRING_CPP0X_NEWLITERALS -#endif +# define USTRING_CPP0X +# if defined(__GXX_EXPERIMENTAL_CXX0X__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5))) +# define USTRING_CPP0X_NEWLITERALS +# endif #endif #include @@ -56,13 +55,13 @@ #endif #ifdef USTRING_CPP0X -#include +# include #endif #ifndef USTRING_NO_STL -#include -#include -#include +# include +# include +# include #endif #include "irrTypes.h" @@ -77,22 +76,23 @@ static const irr::u16 UTF16_HI_SURROGATE = 0xD800; static const irr::u16 UTF16_LO_SURROGATE = 0xDC00; //! Is a UTF-16 code point a surrogate? -#define UTF16_IS_SURROGATE(c) (((c)&0xF800) == 0xD800) -#define UTF16_IS_SURROGATE_HI(c) (((c)&0xFC00) == 0xD800) -#define UTF16_IS_SURROGATE_LO(c) (((c)&0xFC00) == 0xDC00) +#define UTF16_IS_SURROGATE(c) (((c) & 0xF800) == 0xD800) +#define UTF16_IS_SURROGATE_HI(c) (((c) & 0xFC00) == 0xD800) +#define UTF16_IS_SURROGATE_LO(c) (((c) & 0xFC00) == 0xDC00) + namespace irr { -// Define our character types. -#ifdef USTRING_CPP0X_NEWLITERALS // C++0x -typedef char32_t uchar32_t; -typedef char16_t uchar16_t; -typedef char uchar8_t; + // Define our character types. +#ifdef USTRING_CPP0X_NEWLITERALS // C++0x + typedef char32_t uchar32_t; + typedef char16_t uchar16_t; + typedef char uchar8_t; #else -typedef u32 uchar32_t; -typedef u16 uchar16_t; -typedef u8 uchar8_t; + typedef u32 uchar32_t; + typedef u16 uchar16_t; + typedef u8 uchar8_t; #endif namespace core @@ -111,24 +111,26 @@ const irr::u16 UTF_REPLACEMENT_CHARACTER = 0xFFFD; inline uchar32_t toUTF32(uchar16_t high, uchar16_t low) { // Convert the surrogate pair into a single UTF-32 character. - uchar32_t x = ((high & ((1 << 6) - 1)) << 10) | (low & ((1 << 10) - 1)); + uchar32_t x = ((high & ((1 << 6) -1)) << 10) | (low & ((1 << 10) -1)); uchar32_t wu = ((high >> 6) & ((1 << 5) - 1)) + 1; return (wu << 16) | x; } //! Swaps the endianness of a 16-bit value. //! \return The new value. -inline uchar16_t swapEndian16(const uchar16_t &c) +inline uchar16_t swapEndian16(const uchar16_t& c) { return ((c >> 8) & 0x00FF) | ((c << 8) & 0xFF00); } //! Swaps the endianness of a 32-bit value. //! \return The new value. -inline uchar32_t swapEndian32(const uchar32_t &c) +inline uchar32_t swapEndian32(const uchar32_t& c) { - return ((c >> 24) & 0x000000FF) | ((c >> 8) & 0x0000FF00) | - ((c << 8) & 0x00FF0000) | ((c << 24) & 0xFF000000); + return ((c >> 24) & 0x000000FF) | + ((c >> 8) & 0x0000FF00) | + ((c << 8) & 0x00FF0000) | + ((c << 24) & 0xFF000000); } //! The Unicode byte order mark. @@ -140,11 +142,11 @@ const u8 BOM_UTF16_LEN = 1; const u8 BOM_UTF32_LEN = 1; //! Unicode byte order marks for file operations. -const u8 BOM_ENCODE_UTF8[3] = {0xEF, 0xBB, 0xBF}; -const u8 BOM_ENCODE_UTF16_BE[2] = {0xFE, 0xFF}; -const u8 BOM_ENCODE_UTF16_LE[2] = {0xFF, 0xFE}; -const u8 BOM_ENCODE_UTF32_BE[4] = {0x00, 0x00, 0xFE, 0xFF}; -const u8 BOM_ENCODE_UTF32_LE[4] = {0xFF, 0xFE, 0x00, 0x00}; +const u8 BOM_ENCODE_UTF8[3] = { 0xEF, 0xBB, 0xBF }; +const u8 BOM_ENCODE_UTF16_BE[2] = { 0xFE, 0xFF }; +const u8 BOM_ENCODE_UTF16_LE[2] = { 0xFF, 0xFE }; +const u8 BOM_ENCODE_UTF32_BE[4] = { 0x00, 0x00, 0xFE, 0xFF }; +const u8 BOM_ENCODE_UTF32_LE[4] = { 0xFF, 0xFE, 0x00, 0x00 }; //! The size in bytes of the Unicode byte marks for file operations. const u8 BOM_ENCODE_UTF8_LEN = 3; @@ -154,7 +156,7 @@ const u8 BOM_ENCODE_UTF32_LEN = 4; //! Unicode encoding type. enum EUTF_ENCODE { - EUTFE_NONE = 0, + EUTFE_NONE = 0, EUTFE_UTF8, EUTFE_UTF16, EUTFE_UTF16_LE, @@ -167,7 +169,7 @@ enum EUTF_ENCODE //! Unicode endianness. enum EUTF_ENDIAN { - EUTFEE_NATIVE = 0, + EUTFEE_NATIVE = 0, EUTFEE_LITTLE, EUTFEE_BIG }; @@ -175,50 +177,50 @@ enum EUTF_ENDIAN //! Returns the specified unicode byte order mark in a byte array. //! The byte order mark is the first few bytes in a text file that signifies its encoding. /** \param mode The Unicode encoding method that we want to get the byte order mark for. - If EUTFE_UTF16 or EUTFE_UTF32 is passed, it uses the native system - endianness. **/ + If EUTFE_UTF16 or EUTFE_UTF32 is passed, it uses the native system endianness. **/ //! \return An array that contains a byte order mark. inline core::array getUnicodeBOM(EUTF_ENCODE mode) { -#define COPY_ARRAY(source, size) \ - memcpy(ret.pointer(), source, size); \ +#define COPY_ARRAY(source, size) \ + memcpy(ret.pointer(), source, size); \ ret.set_used(size) core::array ret(4); - switch (mode) { - case EUTFE_UTF8: - COPY_ARRAY(BOM_ENCODE_UTF8, BOM_ENCODE_UTF8_LEN); - break; - case EUTFE_UTF16: -#ifdef __BIG_ENDIAN__ - COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); -#else - COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); -#endif - break; - case EUTFE_UTF16_BE: - COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); - break; - case EUTFE_UTF16_LE: - COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); - break; - case EUTFE_UTF32: -#ifdef __BIG_ENDIAN__ - COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); -#else - COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); -#endif - break; - case EUTFE_UTF32_BE: - COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); - break; - case EUTFE_UTF32_LE: - COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); - break; - case EUTFE_NONE: - // TODO sapier: fixed warning only, - // don't know if something needs to be done here - break; + switch (mode) + { + case EUTFE_UTF8: + COPY_ARRAY(BOM_ENCODE_UTF8, BOM_ENCODE_UTF8_LEN); + break; + case EUTFE_UTF16: + #ifdef __BIG_ENDIAN__ + COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); + #else + COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); + #endif + break; + case EUTFE_UTF16_BE: + COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); + break; + case EUTFE_UTF16_LE: + COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); + break; + case EUTFE_UTF32: + #ifdef __BIG_ENDIAN__ + COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); + #else + COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); + #endif + break; + case EUTFE_UTF32_BE: + COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); + break; + case EUTFE_UTF32_LE: + COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); + break; + case EUTFE_NONE: + // TODO sapier: fixed warning only, + // don't know if something needs to be done here + break; } return ret; @@ -227,29 +229,26 @@ inline core::array getUnicodeBOM(EUTF_ENCODE mode) //! Detects if the given data stream starts with a unicode BOM. //! \param data The data stream to check. -//! \return The unicode BOM associated with the data stream, or EUTFE_NONE if none was -//! found. -inline EUTF_ENCODE determineUnicodeBOM(const char *data) -{ - if (memcmp(data, BOM_ENCODE_UTF8, 3) == 0) - return EUTFE_UTF8; - if (memcmp(data, BOM_ENCODE_UTF16_BE, 2) == 0) - return EUTFE_UTF16_BE; - if (memcmp(data, BOM_ENCODE_UTF16_LE, 2) == 0) - return EUTFE_UTF16_LE; - if (memcmp(data, BOM_ENCODE_UTF32_BE, 4) == 0) - return EUTFE_UTF32_BE; - if (memcmp(data, BOM_ENCODE_UTF32_LE, 4) == 0) - return EUTFE_UTF32_LE; +//! \return The unicode BOM associated with the data stream, or EUTFE_NONE if none was found. +inline EUTF_ENCODE determineUnicodeBOM(const char* data) +{ + if (memcmp(data, BOM_ENCODE_UTF8, 3) == 0) return EUTFE_UTF8; + if (memcmp(data, BOM_ENCODE_UTF16_BE, 2) == 0) return EUTFE_UTF16_BE; + if (memcmp(data, BOM_ENCODE_UTF16_LE, 2) == 0) return EUTFE_UTF16_LE; + if (memcmp(data, BOM_ENCODE_UTF32_BE, 4) == 0) return EUTFE_UTF32_BE; + if (memcmp(data, BOM_ENCODE_UTF32_LE, 4) == 0) return EUTFE_UTF32_LE; return EUTFE_NONE; } } // end namespace unicode + //! UTF-16 string class. -template > class ustring16 +template > +class ustring16 { public: + ///------------------/// /// iterator classes /// ///------------------/// @@ -257,533 +256,555 @@ template > class ustring16 //! Access an element in a unicode string, allowing one to change it. class _ustring16_iterator_access { - public: - _ustring16_iterator_access(const ustring16 *s, u32 p) : - ref(s), pos(p) - { - } + public: + _ustring16_iterator_access(const ustring16* s, u32 p) : ref(s), pos(p) {} - //! Allow the class to be interpreted as a single UTF-32 character. - operator uchar32_t() const { return _get(); } + //! Allow the class to be interpreted as a single UTF-32 character. + operator uchar32_t() const + { + return _get(); + } - //! Allow one to change the character in the unicode string. - //! \param c The new character to use. - //! \return Myself. - _ustring16_iterator_access &operator=(const uchar32_t c) - { - _set(c); - return *this; - } + //! Allow one to change the character in the unicode string. + //! \param c The new character to use. + //! \return Myself. + _ustring16_iterator_access& operator=(const uchar32_t c) + { + _set(c); + return *this; + } - //! Increments the value by 1. - //! \return Myself. - _ustring16_iterator_access &operator++() - { - _set(_get() + 1); - return *this; - } + //! Increments the value by 1. + //! \return Myself. + _ustring16_iterator_access& operator++() + { + _set(_get() + 1); + return *this; + } - //! Increments the value by 1, returning the old value. - //! \return A unicode character. - uchar32_t operator++(int) - { - uchar32_t old = _get(); - _set(old + 1); - return old; - } + //! Increments the value by 1, returning the old value. + //! \return A unicode character. + uchar32_t operator++(int) + { + uchar32_t old = _get(); + _set(old + 1); + return old; + } - //! Decrements the value by 1. - //! \return Myself. - _ustring16_iterator_access &operator--() - { - _set(_get() - 1); - return *this; - } + //! Decrements the value by 1. + //! \return Myself. + _ustring16_iterator_access& operator--() + { + _set(_get() - 1); + return *this; + } - //! Decrements the value by 1, returning the old value. - //! \return A unicode character. - uchar32_t operator--(int) - { - uchar32_t old = _get(); - _set(old - 1); - return old; - } + //! Decrements the value by 1, returning the old value. + //! \return A unicode character. + uchar32_t operator--(int) + { + uchar32_t old = _get(); + _set(old - 1); + return old; + } - //! Adds to the value by a specified amount. - //! \param val The amount to add to this character. - //! \return Myself. - _ustring16_iterator_access &operator+=(int val) - { - _set(_get() + val); - return *this; - } + //! Adds to the value by a specified amount. + //! \param val The amount to add to this character. + //! \return Myself. + _ustring16_iterator_access& operator+=(int val) + { + _set(_get() + val); + return *this; + } - //! Subtracts from the value by a specified amount. - //! \param val The amount to subtract from this character. - //! \return Myself. - _ustring16_iterator_access &operator-=(int val) - { - _set(_get() - val); - return *this; - } + //! Subtracts from the value by a specified amount. + //! \param val The amount to subtract from this character. + //! \return Myself. + _ustring16_iterator_access& operator-=(int val) + { + _set(_get() - val); + return *this; + } - //! Multiples the value by a specified amount. - //! \param val The amount to multiply this character by. - //! \return Myself. - _ustring16_iterator_access &operator*=(int val) - { - _set(_get() * val); - return *this; - } + //! Multiples the value by a specified amount. + //! \param val The amount to multiply this character by. + //! \return Myself. + _ustring16_iterator_access& operator*=(int val) + { + _set(_get() * val); + return *this; + } - //! Divides the value by a specified amount. - //! \param val The amount to divide this character by. - //! \return Myself. - _ustring16_iterator_access &operator/=(int val) - { - _set(_get() / val); - return *this; - } + //! Divides the value by a specified amount. + //! \param val The amount to divide this character by. + //! \return Myself. + _ustring16_iterator_access& operator/=(int val) + { + _set(_get() / val); + return *this; + } - //! Modulos the value by a specified amount. - //! \param val The amount to modulo this character by. - //! \return Myself. - _ustring16_iterator_access &operator%=(int val) - { - _set(_get() % val); - return *this; - } + //! Modulos the value by a specified amount. + //! \param val The amount to modulo this character by. + //! \return Myself. + _ustring16_iterator_access& operator%=(int val) + { + _set(_get() % val); + return *this; + } - //! Adds to the value by a specified amount. - //! \param val The amount to add to this character. - //! \return A unicode character. - uchar32_t operator+(int val) const { return _get() + val; } + //! Adds to the value by a specified amount. + //! \param val The amount to add to this character. + //! \return A unicode character. + uchar32_t operator+(int val) const + { + return _get() + val; + } - //! Subtracts from the value by a specified amount. - //! \param val The amount to subtract from this character. - //! \return A unicode character. - uchar32_t operator-(int val) const { return _get() - val; } + //! Subtracts from the value by a specified amount. + //! \param val The amount to subtract from this character. + //! \return A unicode character. + uchar32_t operator-(int val) const + { + return _get() - val; + } - //! Multiplies the value by a specified amount. - //! \param val The amount to multiply this character by. - //! \return A unicode character. - uchar32_t operator*(int val) const { return _get() * val; } + //! Multiplies the value by a specified amount. + //! \param val The amount to multiply this character by. + //! \return A unicode character. + uchar32_t operator*(int val) const + { + return _get() * val; + } - //! Divides the value by a specified amount. - //! \param val The amount to divide this character by. - //! \return A unicode character. - uchar32_t operator/(int val) const { return _get() / val; } + //! Divides the value by a specified amount. + //! \param val The amount to divide this character by. + //! \return A unicode character. + uchar32_t operator/(int val) const + { + return _get() / val; + } - //! Modulos the value by a specified amount. - //! \param val The amount to modulo this character by. - //! \return A unicode character. - uchar32_t operator%(int val) const { return _get() % val; } + //! Modulos the value by a specified amount. + //! \param val The amount to modulo this character by. + //! \return A unicode character. + uchar32_t operator%(int val) const + { + return _get() % val; + } - private: - //! Gets a uchar32_t from our current position. - uchar32_t _get() const - { - const uchar16_t *a = ref->c_str(); - if (!UTF16_IS_SURROGATE(a[pos])) - return static_cast(a[pos]); - else { - if (pos + 1 >= ref->size_raw()) - return 0; + private: + //! Gets a uchar32_t from our current position. + uchar32_t _get() const + { + const uchar16_t* a = ref->c_str(); + if (!UTF16_IS_SURROGATE(a[pos])) + return static_cast(a[pos]); + else + { + if (pos + 1 >= ref->size_raw()) + return 0; - return unicode::toUTF32(a[pos], a[pos + 1]); + return unicode::toUTF32(a[pos], a[pos + 1]); + } } - } - //! Sets a uchar32_t at our current position. - void _set(uchar32_t c) - { - ustring16 *ref2 = const_cast *>(ref); - const uchar16_t *a = ref2->c_str(); - if (c > 0xFFFF) { - // c will be multibyte, so split it up into the high and - // low surrogate pairs. - uchar16_t x = static_cast(c); - uchar16_t vh = UTF16_HI_SURROGATE | - ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | - (x >> 10); - uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); + //! Sets a uchar32_t at our current position. + void _set(uchar32_t c) + { + ustring16* ref2 = const_cast*>(ref); + const uchar16_t* a = ref2->c_str(); + if (c > 0xFFFF) + { + // c will be multibyte, so split it up into the high and low surrogate pairs. + uchar16_t x = static_cast(c); + uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); + uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); + + // If the previous position was a surrogate pair, just replace them. Else, insert the low pair. + if (UTF16_IS_SURROGATE_HI(a[pos]) && pos + 1 != ref2->size_raw()) + ref2->replace_raw(vl, static_cast(pos) + 1); + else ref2->insert_raw(vl, static_cast(pos) + 1); - // If the previous position was a surrogate pair, just - // replace them. Else, insert the low pair. - if (UTF16_IS_SURROGATE_HI(a[pos]) && - pos + 1 != ref2->size_raw()) - ref2->replace_raw(vl, static_cast(pos) + 1); + ref2->replace_raw(vh, static_cast(pos)); + } else - ref2->insert_raw(vl, static_cast(pos) + 1); + { + // c will be a single byte. + uchar16_t vh = static_cast(c); - ref2->replace_raw(vh, static_cast(pos)); - } else { - // c will be a single byte. - uchar16_t vh = static_cast(c); + // If the previous position was a surrogate pair, remove the extra byte. + if (UTF16_IS_SURROGATE_HI(a[pos])) + ref2->erase_raw(static_cast(pos) + 1); - // If the previous position was a surrogate pair, remove - // the extra byte. - if (UTF16_IS_SURROGATE_HI(a[pos])) - ref2->erase_raw(static_cast(pos) + 1); - - ref2->replace_raw(vh, static_cast(pos)); + ref2->replace_raw(vh, static_cast(pos)); + } } - } - const ustring16 *ref; - u32 pos; + const ustring16* ref; + u32 pos; }; typedef typename ustring16::_ustring16_iterator_access access; + //! Iterator to iterate through a UTF-16 string. #ifndef USTRING_NO_STL - class _ustring16_const_iterator - : public std::iterator< - std::bidirectional_iterator_tag, // iterator_category - access, // value_type - ptrdiff_t, // difference_type - const access, // pointer - const access // reference - > + class _ustring16_const_iterator : public std::iterator< + std::bidirectional_iterator_tag, // iterator_category + access, // value_type + ptrdiff_t, // difference_type + const access, // pointer + const access // reference + > #else class _ustring16_const_iterator #endif { - public: - typedef _ustring16_const_iterator _Iter; - typedef std::iterator - _Base; - typedef const access const_pointer; - typedef const access const_reference; + public: + typedef _ustring16_const_iterator _Iter; + typedef std::iterator _Base; + typedef const access const_pointer; + typedef const access const_reference; #ifndef USTRING_NO_STL - typedef typename _Base::value_type value_type; - typedef typename _Base::difference_type difference_type; - typedef typename _Base::difference_type distance_type; - typedef typename _Base::pointer pointer; - typedef const_reference reference; + typedef typename _Base::value_type value_type; + typedef typename _Base::difference_type difference_type; + typedef typename _Base::difference_type distance_type; + typedef typename _Base::pointer pointer; + typedef const_reference reference; #else - typedef access value_type; - typedef u32 difference_type; - typedef u32 distance_type; - typedef const_pointer pointer; - typedef const_reference reference; + typedef access value_type; + typedef u32 difference_type; + typedef u32 distance_type; + typedef const_pointer pointer; + typedef const_reference reference; #endif - //! Constructors. - _ustring16_const_iterator(const _Iter &i) : ref(i.ref), pos(i.pos) {} - _ustring16_const_iterator(const ustring16 &s) : ref(&s), pos(0) {} - _ustring16_const_iterator(const ustring16 &s, const u32 p) : - ref(&s), pos(0) - { - if (ref->size_raw() == 0 || p == 0) - return; - - // Go to the appropriate position. - u32 i = p; - u32 sr = ref->size_raw(); - const uchar16_t *a = ref->c_str(); - while (i != 0 && pos < sr) { - if (UTF16_IS_SURROGATE_HI(a[pos])) - pos += 2; - else - ++pos; - --i; + //! Constructors. + _ustring16_const_iterator(const _Iter& i) : ref(i.ref), pos(i.pos) {} + _ustring16_const_iterator(const ustring16& s) : ref(&s), pos(0) {} + _ustring16_const_iterator(const ustring16& s, const u32 p) : ref(&s), pos(0) + { + if (ref->size_raw() == 0 || p == 0) + return; + + // Go to the appropriate position. + u32 i = p; + u32 sr = ref->size_raw(); + const uchar16_t* a = ref->c_str(); + while (i != 0 && pos < sr) + { + if (UTF16_IS_SURROGATE_HI(a[pos])) + pos += 2; + else ++pos; + --i; + } } - } - //! Test for equalness. - bool operator==(const _Iter &iter) const - { - if (ref == iter.ref && pos == iter.pos) - return true; - return false; - } + //! Test for equalness. + bool operator==(const _Iter& iter) const + { + if (ref == iter.ref && pos == iter.pos) + return true; + return false; + } - //! Test for unequalness. - bool operator!=(const _Iter &iter) const - { - if (ref != iter.ref || pos != iter.pos) - return true; - return false; - } + //! Test for unequalness. + bool operator!=(const _Iter& iter) const + { + if (ref != iter.ref || pos != iter.pos) + return true; + return false; + } - //! Switch to the next full character in the string. - _Iter &operator++() - { // ++iterator - if (pos == ref->size_raw()) + //! Switch to the next full character in the string. + _Iter& operator++() + { // ++iterator + if (pos == ref->size_raw()) return *this; + const uchar16_t* a = ref->c_str(); + if (UTF16_IS_SURROGATE_HI(a[pos])) + pos += 2; // TODO: check for valid low surrogate? + else ++pos; + if (pos > ref->size_raw()) pos = ref->size_raw(); return *this; - const uchar16_t *a = ref->c_str(); - if (UTF16_IS_SURROGATE_HI(a[pos])) - pos += 2; // TODO: check for valid low surrogate? - else - ++pos; - if (pos > ref->size_raw()) - pos = ref->size_raw(); - return *this; - } + } - //! Switch to the next full character in the string, returning the - //! previous position. - _Iter operator++(int) - { // iterator++ - _Iter _tmp(*this); - ++*this; - return _tmp; - } + //! Switch to the next full character in the string, returning the previous position. + _Iter operator++(int) + { // iterator++ + _Iter _tmp(*this); + ++*this; + return _tmp; + } - //! Switch to the previous full character in the string. - _Iter &operator--() - { // --iterator - if (pos == 0) - return *this; - const uchar16_t *a = ref->c_str(); - --pos; - if (UTF16_IS_SURROGATE_LO(a[pos]) && - pos != 0) // low surrogate, go back one more. + //! Switch to the previous full character in the string. + _Iter& operator--() + { // --iterator + if (pos == 0) return *this; + const uchar16_t* a = ref->c_str(); --pos; - return *this; - } - - //! Switch to the previous full character in the string, returning the - //! previous position. - _Iter operator--(int) - { // iterator-- - _Iter _tmp(*this); - --*this; - return _tmp; - } - - //! Advance a specified number of full characters in the string. - //! \return Myself. - _Iter &operator+=(const difference_type v) - { - if (v == 0) - return *this; - if (v < 0) - return operator-=(v * -1); - - if (pos >= ref->size_raw()) + if (UTF16_IS_SURROGATE_LO(a[pos]) && pos != 0) // low surrogate, go back one more. + --pos; return *this; - - // Go to the appropriate position. - // TODO: Don't force u32 on an x64 OS. Make it agnostic. - u32 i = (u32)v; - u32 sr = ref->size_raw(); - const uchar16_t *a = ref->c_str(); - while (i != 0 && pos < sr) { - if (UTF16_IS_SURROGATE_HI(a[pos])) - pos += 2; - else - ++pos; - --i; } - if (pos > sr) - pos = sr; - return *this; - } + //! Switch to the previous full character in the string, returning the previous position. + _Iter operator--(int) + { // iterator-- + _Iter _tmp(*this); + --*this; + return _tmp; + } - //! Go back a specified number of full characters in the string. - //! \return Myself. - _Iter &operator-=(const difference_type v) - { - if (v == 0) - return *this; - if (v > 0) - return operator+=(v * -1); + //! Advance a specified number of full characters in the string. + //! \return Myself. + _Iter& operator+=(const difference_type v) + { + if (v == 0) return *this; + if (v < 0) return operator-=(v * -1); + + if (pos >= ref->size_raw()) + return *this; + + // Go to the appropriate position. + // TODO: Don't force u32 on an x64 OS. Make it agnostic. + u32 i = (u32)v; + u32 sr = ref->size_raw(); + const uchar16_t* a = ref->c_str(); + while (i != 0 && pos < sr) + { + if (UTF16_IS_SURROGATE_HI(a[pos])) + pos += 2; + else ++pos; + --i; + } + if (pos > sr) + pos = sr; - if (pos == 0) return *this; + } - // Go to the appropriate position. - // TODO: Don't force u32 on an x64 OS. Make it agnostic. - u32 i = (u32)v; - const uchar16_t *a = ref->c_str(); - while (i != 0 && pos != 0) { - --pos; - if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0) + //! Go back a specified number of full characters in the string. + //! \return Myself. + _Iter& operator-=(const difference_type v) + { + if (v == 0) return *this; + if (v > 0) return operator+=(v * -1); + + if (pos == 0) + return *this; + + // Go to the appropriate position. + // TODO: Don't force u32 on an x64 OS. Make it agnostic. + u32 i = (u32)v; + const uchar16_t* a = ref->c_str(); + while (i != 0 && pos != 0) + { --pos; - --i; + if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0) + --pos; + --i; + } + + return *this; } - return *this; - } + //! Return a new iterator that is a variable number of full characters forward from the current position. + _Iter operator+(const difference_type v) const + { + _Iter ret(*this); + ret += v; + return ret; + } - //! Return a new iterator that is a variable number of full characters - //! forward from the current position. - _Iter operator+(const difference_type v) const - { - _Iter ret(*this); - ret += v; - return ret; - } + //! Return a new iterator that is a variable number of full characters backward from the current position. + _Iter operator-(const difference_type v) const + { + _Iter ret(*this); + ret -= v; + return ret; + } - //! Return a new iterator that is a variable number of full characters - //! backward from the current position. - _Iter operator-(const difference_type v) const - { - _Iter ret(*this); - ret -= v; - return ret; - } + //! Returns the distance between two iterators. + difference_type operator-(const _Iter& iter) const + { + // Make sure we reference the same object! + if (ref != iter.ref) + return difference_type(); - //! Returns the distance between two iterators. - difference_type operator-(const _Iter &iter) const - { - // Make sure we reference the same object! - if (ref != iter.ref) - return difference_type(); + _Iter i = iter; + difference_type ret; - _Iter i = iter; - difference_type ret; + // Walk up. + if (pos > i.pos) + { + while (pos > i.pos) + { + ++i; + ++ret; + } + return ret; + } - // Walk up. - if (pos > i.pos) { - while (pos > i.pos) { - ++i; - ++ret; + // Walk down. + while (pos < i.pos) + { + --i; + --ret; } return ret; } - // Walk down. - while (pos < i.pos) { - --i; - --ret; - } - return ret; - } - - //! Accesses the full character at the iterator's position. - const_reference operator*() const - { - if (pos >= ref->size_raw()) { - const uchar16_t *a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); + //! Accesses the full character at the iterator's position. + const_reference operator*() const + { + if (pos >= ref->size_raw()) + { + const uchar16_t* a = ref->c_str(); + u32 p = ref->size_raw(); + if (UTF16_IS_SURROGATE_LO(a[p])) + --p; + reference ret(ref, p); + return ret; + } + const_reference ret(ref, pos); return ret; } - const_reference ret(ref, pos); - return ret; - } - //! Accesses the full character at the iterator's position. - reference operator*() - { - if (pos >= ref->size_raw()) { - const uchar16_t *a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); + //! Accesses the full character at the iterator's position. + reference operator*() + { + if (pos >= ref->size_raw()) + { + const uchar16_t* a = ref->c_str(); + u32 p = ref->size_raw(); + if (UTF16_IS_SURROGATE_LO(a[p])) + --p; + reference ret(ref, p); + return ret; + } + reference ret(ref, pos); return ret; } - reference ret(ref, pos); - return ret; - } - //! Accesses the full character at the iterator's position. - const_pointer operator->() const { return operator*(); } + //! Accesses the full character at the iterator's position. + const_pointer operator->() const + { + return operator*(); + } - //! Accesses the full character at the iterator's position. - pointer operator->() { return operator*(); } + //! Accesses the full character at the iterator's position. + pointer operator->() + { + return operator*(); + } - //! Is the iterator at the start of the string? - bool atStart() const { return pos == 0; } + //! Is the iterator at the start of the string? + bool atStart() const + { + return pos == 0; + } - //! Is the iterator at the end of the string? - bool atEnd() const - { - const uchar16_t *a = ref->c_str(); - if (UTF16_IS_SURROGATE(a[pos])) - return (pos + 1) >= ref->size_raw(); - else - return pos >= ref->size_raw(); - } + //! Is the iterator at the end of the string? + bool atEnd() const + { + const uchar16_t* a = ref->c_str(); + if (UTF16_IS_SURROGATE(a[pos])) + return (pos + 1) >= ref->size_raw(); + else return pos >= ref->size_raw(); + } - //! Moves the iterator to the start of the string. - void toStart() { pos = 0; } + //! Moves the iterator to the start of the string. + void toStart() + { + pos = 0; + } - //! Moves the iterator to the end of the string. - void toEnd() { pos = ref->size_raw(); } + //! Moves the iterator to the end of the string. + void toEnd() + { + pos = ref->size_raw(); + } - //! Returns the iterator's position. - //! \return The iterator's position. - u32 getPos() const { return pos; } + //! Returns the iterator's position. + //! \return The iterator's position. + u32 getPos() const + { + return pos; + } - protected: - const ustring16 *ref; - u32 pos; + protected: + const ustring16* ref; + u32 pos; }; //! Iterator to iterate through a UTF-16 string. class _ustring16_iterator : public _ustring16_const_iterator { - public: - typedef _ustring16_iterator _Iter; - typedef _ustring16_const_iterator _Base; - typedef typename _Base::const_pointer const_pointer; - typedef typename _Base::const_reference const_reference; + public: + typedef _ustring16_iterator _Iter; + typedef _ustring16_const_iterator _Base; + typedef typename _Base::const_pointer const_pointer; + typedef typename _Base::const_reference const_reference; - typedef typename _Base::value_type value_type; - typedef typename _Base::difference_type difference_type; - typedef typename _Base::distance_type distance_type; - typedef access pointer; - typedef access reference; - using _Base::pos; - using _Base::ref; + typedef typename _Base::value_type value_type; + typedef typename _Base::difference_type difference_type; + typedef typename _Base::distance_type distance_type; + typedef access pointer; + typedef access reference; - //! Constructors. - _ustring16_iterator(const _Iter &i) : _ustring16_const_iterator(i) {} - _ustring16_iterator(const ustring16 &s) : - _ustring16_const_iterator(s) - { - } - _ustring16_iterator(const ustring16 &s, const u32 p) : - _ustring16_const_iterator(s, p) - { - } + using _Base::pos; + using _Base::ref; - //! Accesses the full character at the iterator's position. - reference operator*() const - { - if (pos >= ref->size_raw()) { - const uchar16_t *a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); + //! Constructors. + _ustring16_iterator(const _Iter& i) : _ustring16_const_iterator(i) {} + _ustring16_iterator(const ustring16& s) : _ustring16_const_iterator(s) {} + _ustring16_iterator(const ustring16& s, const u32 p) : _ustring16_const_iterator(s, p) {} + + //! Accesses the full character at the iterator's position. + reference operator*() const + { + if (pos >= ref->size_raw()) + { + const uchar16_t* a = ref->c_str(); + u32 p = ref->size_raw(); + if (UTF16_IS_SURROGATE_LO(a[p])) + --p; + reference ret(ref, p); + return ret; + } + reference ret(ref, pos); return ret; } - reference ret(ref, pos); - return ret; - } - //! Accesses the full character at the iterator's position. - reference operator*() - { - if (pos >= ref->size_raw()) { - const uchar16_t *a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); + //! Accesses the full character at the iterator's position. + reference operator*() + { + if (pos >= ref->size_raw()) + { + const uchar16_t* a = ref->c_str(); + u32 p = ref->size_raw(); + if (UTF16_IS_SURROGATE_LO(a[p])) + --p; + reference ret(ref, p); + return ret; + } + reference ret(ref, pos); return ret; } - reference ret(ref, pos); - return ret; - } - //! Accesses the full character at the iterator's position. - pointer operator->() const { return operator*(); } + //! Accesses the full character at the iterator's position. + pointer operator->() const + { + return operator*(); + } - //! Accesses the full character at the iterator's position. - pointer operator->() { return operator*(); } + //! Accesses the full character at the iterator's position. + pointer operator->() + { + return operator*(); + } }; typedef typename ustring16::_ustring16_iterator iterator; @@ -794,7 +815,8 @@ template > class ustring16 ///----------------------/// //! Default constructor - ustring16() : array(0), allocated(1), used(0) + ustring16() + : array(0), allocated(1), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -805,8 +827,10 @@ template > class ustring16 array[0] = 0x0; } + //! Constructor - ustring16(const ustring16 &other) : array(0), allocated(0), used(0) + ustring16(const ustring16& other) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -816,9 +840,11 @@ template > class ustring16 *this = other; } + //! Constructor from other string types template - ustring16(const string &other) : array(0), allocated(0), used(0) + ustring16(const string& other) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -828,11 +854,12 @@ template > class ustring16 *this = other; } + #ifndef USTRING_NO_STL //! Constructor from std::string template - ustring16(const std::basic_string &other) : - array(0), allocated(0), used(0) + ustring16(const std::basic_string& other) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -842,9 +869,11 @@ template > class ustring16 *this = other.c_str(); } + //! Constructor from iterator. template - ustring16(Itr first, Itr last) : array(0), allocated(0), used(0) + ustring16(Itr first, Itr last) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -859,9 +888,11 @@ template > class ustring16 } #endif + #ifndef USTRING_CPP0X_NEWLITERALS //! Constructor for copying a character string from a pointer. - ustring16(const char *const c) : array(0), allocated(0), used(0) + ustring16(const char* const c) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -870,11 +901,13 @@ template > class ustring16 #endif loadDataStream(c, strlen(c)); - // append((uchar8_t*)c); + //append((uchar8_t*)c); } + //! Constructor for copying a character string from a pointer with a given length. - ustring16(const char *const c, u32 length) : array(0), allocated(0), used(0) + ustring16(const char* const c, u32 length) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -886,8 +919,10 @@ template > class ustring16 } #endif + //! Constructor for copying a UTF-8 string from a pointer. - ustring16(const uchar8_t *const c) : array(0), allocated(0), used(0) + ustring16(const uchar8_t* const c) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -898,8 +933,10 @@ template > class ustring16 append(c); } + //! Constructor for copying a UTF-8 string from a single char. - ustring16(const char c) : array(0), allocated(0), used(0) + ustring16(const char c) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -910,8 +947,10 @@ template > class ustring16 append((uchar32_t)c); } + //! Constructor for copying a UTF-8 string from a pointer with a given length. - ustring16(const uchar8_t *const c, u32 length) : array(0), allocated(0), used(0) + ustring16(const uchar8_t* const c, u32 length) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -922,8 +961,10 @@ template > class ustring16 append(c, length); } + //! Constructor for copying a UTF-16 string from a pointer. - ustring16(const uchar16_t *const c) : array(0), allocated(0), used(0) + ustring16(const uchar16_t* const c) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -934,8 +975,10 @@ template > class ustring16 append(c); } + //! Constructor for copying a UTF-16 string from a pointer with a given length - ustring16(const uchar16_t *const c, u32 length) : array(0), allocated(0), used(0) + ustring16(const uchar16_t* const c, u32 length) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -946,8 +989,10 @@ template > class ustring16 append(c, length); } + //! Constructor for copying a UTF-32 string from a pointer. - ustring16(const uchar32_t *const c) : array(0), allocated(0), used(0) + ustring16(const uchar32_t* const c) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -958,8 +1003,10 @@ template > class ustring16 append(c); } + //! Constructor for copying a UTF-32 from a pointer with a given length. - ustring16(const uchar32_t *const c, u32 length) : array(0), allocated(0), used(0) + ustring16(const uchar32_t* const c, u32 length) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -970,8 +1017,10 @@ template > class ustring16 append(c, length); } + //! Constructor for copying a wchar_t string from a pointer. - ustring16(const wchar_t *const c) : array(0), allocated(0), used(0) + ustring16(const wchar_t* const c) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -980,15 +1029,17 @@ template > class ustring16 #endif if (sizeof(wchar_t) == 4) - append(reinterpret_cast(c)); + append(reinterpret_cast(c)); else if (sizeof(wchar_t) == 2) - append(reinterpret_cast(c)); + append(reinterpret_cast(c)); else if (sizeof(wchar_t) == 1) - append(reinterpret_cast(c)); + append(reinterpret_cast(c)); } + //! Constructor for copying a wchar_t string from a pointer with a given length. - ustring16(const wchar_t *const c, u32 length) : array(0), allocated(0), used(0) + ustring16(const wchar_t* const c, u32 length) + : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; @@ -997,47 +1048,50 @@ template > class ustring16 #endif if (sizeof(wchar_t) == 4) - append(reinterpret_cast(c), length); + append(reinterpret_cast(c), length); else if (sizeof(wchar_t) == 2) - append(reinterpret_cast(c), length); + append(reinterpret_cast(c), length); else if (sizeof(wchar_t) == 1) - append(reinterpret_cast(c), length); + append(reinterpret_cast(c), length); } + #ifdef USTRING_CPP0X //! Constructor for moving a ustring16 - ustring16(ustring16 &&other) : - array(other.array), encoding(other.encoding), - allocated(other.allocated), used(other.used) + ustring16(ustring16&& other) + : array(other.array), encoding(other.encoding), allocated(other.allocated), used(other.used) { - // std::cout << "MOVE constructor" << std::endl; + //std::cout << "MOVE constructor" << std::endl; other.array = 0; other.allocated = 0; other.used = 0; } #endif + //! Destructor ~ustring16() { allocator.deallocate(array); // delete [] array; } + //! Assignment operator - ustring16 &operator=(const ustring16 &other) + ustring16& operator=(const ustring16& other) { if (this == &other) return *this; used = other.size_raw(); - if (used >= allocated) { + if (used >= allocated) + { allocator.deallocate(array); // delete [] array; allocated = used + 1; - array = allocator.allocate(used + 1); // new u16[used]; + array = allocator.allocate(used + 1); //new u16[used]; } - const uchar16_t *p = other.c_str(); - for (u32 i = 0; i <= used; ++i, ++p) + const uchar16_t* p = other.c_str(); + for (u32 i=0; i<=used; ++i, ++p) array[i] = *p; array[used] = 0; @@ -1048,12 +1102,14 @@ template > class ustring16 return *this; } + #ifdef USTRING_CPP0X //! Move assignment operator - ustring16 &operator=(ustring16 &&other) + ustring16& operator=(ustring16&& other) { - if (this != &other) { - // std::cout << "MOVE operator=" << std::endl; + if (this != &other) + { + //std::cout << "MOVE operator=" << std::endl; allocator.deallocate(array); array = other.array; @@ -1067,188 +1123,215 @@ template > class ustring16 } #endif + //! Assignment operator for other string types template - ustring16 &operator=(const string &other) + ustring16& operator=(const string& other) { *this = other.c_str(); return *this; } + //! Assignment operator for UTF-8 strings - ustring16 &operator=(const uchar8_t *const c) + ustring16& operator=(const uchar8_t* const c) { - if (!array) { - array = allocator.allocate(1); // new u16[1]; + if (!array) + { + array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; - if (!c) - return *this; + if (!c) return *this; //! Append our string now. append(c); return *this; } + //! Assignment operator for UTF-16 strings - ustring16 &operator=(const uchar16_t *const c) + ustring16& operator=(const uchar16_t* const c) { - if (!array) { - array = allocator.allocate(1); // new u16[1]; + if (!array) + { + array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; - if (!c) - return *this; + if (!c) return *this; //! Append our string now. append(c); return *this; } + //! Assignment operator for UTF-32 strings - ustring16 &operator=(const uchar32_t *const c) + ustring16& operator=(const uchar32_t* const c) { - if (!array) { - array = allocator.allocate(1); // new u16[1]; + if (!array) + { + array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; - if (!c) - return *this; + if (!c) return *this; //! Append our string now. append(c); return *this; } + //! Assignment operator for wchar_t strings. - /** Note that this assumes that a correct unicode string is stored in the wchar_t - string. Since wchar_t changes depending on its platform, it could either be a - UTF-8, -16, or -32 string. This function assumes you are storing the correct - unicode encoding inside the wchar_t string. **/ - ustring16 &operator=(const wchar_t *const c) + /** Note that this assumes that a correct unicode string is stored in the wchar_t string. + Since wchar_t changes depending on its platform, it could either be a UTF-8, -16, or -32 string. + This function assumes you are storing the correct unicode encoding inside the wchar_t string. **/ + ustring16& operator=(const wchar_t* const c) { if (sizeof(wchar_t) == 4) - *this = reinterpret_cast(c); + *this = reinterpret_cast(c); else if (sizeof(wchar_t) == 2) - *this = reinterpret_cast(c); + *this = reinterpret_cast(c); else if (sizeof(wchar_t) == 1) - *this = reinterpret_cast(c); + *this = reinterpret_cast(c); return *this; } + //! Assignment operator for other strings. - /** Note that this assumes that a correct unicode string is stored in the string. - * **/ - template ustring16 &operator=(const B *const c) + /** Note that this assumes that a correct unicode string is stored in the string. **/ + template + ustring16& operator=(const B* const c) { if (sizeof(B) == 4) - *this = reinterpret_cast(c); + *this = reinterpret_cast(c); else if (sizeof(B) == 2) - *this = reinterpret_cast(c); + *this = reinterpret_cast(c); else if (sizeof(B) == 1) - *this = reinterpret_cast(c); + *this = reinterpret_cast(c); return *this; } + //! Direct access operator - access operator[](const u32 index) + access operator [](const u32 index) { - _IRR_DEBUG_BREAK_IF(index >= size()) // bad index + _IRR_DEBUG_BREAK_IF(index>=size()) // bad index iterator iter(*this, index); return iter.operator*(); } + //! Direct access operator - const access operator[](const u32 index) const + const access operator [](const u32 index) const { - _IRR_DEBUG_BREAK_IF(index >= size()) // bad index + _IRR_DEBUG_BREAK_IF(index>=size()) // bad index const_iterator iter(*this, index); return iter.operator*(); } + //! Equality operator - bool operator==(const uchar16_t *const str) const + bool operator ==(const uchar16_t* const str) const { if (!str) return false; u32 i; - for (i = 0; array[i] && str[i]; ++i) + for(i=0; array[i] && str[i]; ++i) if (array[i] != str[i]) return false; return !array[i] && !str[i]; } + //! Equality operator - bool operator==(const ustring16 &other) const + bool operator ==(const ustring16& other) const { - for (u32 i = 0; array[i] && other.array[i]; ++i) + for(u32 i=0; array[i] && other.array[i]; ++i) if (array[i] != other.array[i]) return false; return used == other.used; } + //! Is smaller comparator - bool operator<(const ustring16 &other) const + bool operator <(const ustring16& other) const { - for (u32 i = 0; array[i] && other.array[i]; ++i) { + for(u32 i=0; array[i] && other.array[i]; ++i) + { s32 diff = array[i] - other.array[i]; - if (diff) + if ( diff ) return diff < 0; } return used < other.used; } + //! Inequality operator - bool operator!=(const uchar16_t *const str) const { return !(*this == str); } + bool operator !=(const uchar16_t* const str) const + { + return !(*this == str); + } + //! Inequality operator - bool operator!=(const ustring16 &other) const + bool operator !=(const ustring16& other) const { return !(*this == other); } + //! Returns the length of a ustring16 in full characters. //! \return Length of a ustring16 in full characters. u32 size() const { const_iterator i(*this, 0); u32 pos = 0; - while (!i.atEnd()) { + while (!i.atEnd()) + { ++i; ++pos; } return pos; } + //! Informs if the ustring is empty or not. //! \return True if the ustring is empty, false if not. - bool empty() const { return (size_raw() == 0); } + bool empty() const + { + return (size_raw() == 0); + } + //! Returns a pointer to the raw UTF-16 string data. //! \return pointer to C-style NUL terminated array of UTF-16 code points. - const uchar16_t *c_str() const { return array; } + const uchar16_t* c_str() const + { + return array; + } + //! Compares the first n characters of this string with another. //! \param other Other string to compare to. //! \param n Number of characters to compare. //! \return True if the n first characters of both strings are equal. - bool equalsn(const ustring16 &other, u32 n) const + bool equalsn(const ustring16& other, u32 n) const { u32 i; - const uchar16_t *oa = other.c_str(); - for (i = 0; array[i] && oa[i] && i < n; ++i) + const uchar16_t* oa = other.c_str(); + for(i=0; array[i] && oa[i] && i < n; ++i) if (array[i] != oa[i]) return false; @@ -1257,16 +1340,17 @@ template > class ustring16 return (i == n) || (used == other.used); } + //! Compares the first n characters of this string with another. //! \param str Other string to compare to. //! \param n Number of characters to compare. //! \return True if the n first characters of both strings are equal. - bool equalsn(const uchar16_t *const str, u32 n) const + bool equalsn(const uchar16_t* const str, u32 n) const { if (!str) return false; u32 i; - for (i = 0; array[i] && str[i] && i < n; ++i) + for(i=0; array[i] && str[i] && i < n; ++i) if (array[i] != str[i]) return false; @@ -1275,62 +1359,66 @@ template > class ustring16 return (i == n) || (array[i] == 0 && str[i] == 0); } + //! Appends a character to this ustring16 //! \param character The character to append. //! \return A reference to our current string. - ustring16 &append(uchar32_t character) + ustring16& append(uchar32_t character) { if (used + 2 >= allocated) reallocate(used + 2); - if (character > 0xFFFF) { + if (character > 0xFFFF) + { used += 2; - // character will be multibyte, so split it up into a surrogate - // pair. + // character will be multibyte, so split it up into a surrogate pair. uchar16_t x = static_cast(character); - uchar16_t vh = UTF16_HI_SURROGATE | - ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | - (x >> 10); + uchar16_t vh = UTF16_HI_SURROGATE | ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); - array[used - 2] = vh; - array[used - 1] = vl; - } else { + array[used-2] = vh; + array[used-1] = vl; + } + else + { ++used; - array[used - 1] = character; + array[used-1] = character; } array[used] = 0; return *this; } + //! Appends a UTF-8 string to this ustring16 //! \param other The UTF-8 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. - ustring16 &append(const uchar8_t *const other, u32 length = 0xffffffff) + ustring16& append(const uchar8_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Determine if the string is long enough for a BOM. u32 len = 0; - const uchar8_t *p = other; - do { + const uchar8_t* p = other; + do + { ++len; } while (*p++ && len < unicode::BOM_ENCODE_UTF8_LEN); // Check for BOM. unicode::EUTF_ENCODE c_bom = unicode::EUTFE_NONE; - if (len == unicode::BOM_ENCODE_UTF8_LEN) { - if (memcmp(other, unicode::BOM_ENCODE_UTF8, - unicode::BOM_ENCODE_UTF8_LEN) == 0) + if (len == unicode::BOM_ENCODE_UTF8_LEN) + { + if (memcmp(other, unicode::BOM_ENCODE_UTF8, unicode::BOM_ENCODE_UTF8_LEN) == 0) c_bom = unicode::EUTFE_UTF8; } // If a BOM was found, don't include it in the string. - const uchar8_t *c2 = other; - if (c_bom != unicode::EUTFE_NONE) { + const uchar8_t* c2 = other; + if (c_bom != unicode::EUTFE_NONE) + { c2 = other + unicode::BOM_UTF8_LEN; length -= unicode::BOM_UTF8_LEN; } @@ -1338,9 +1426,10 @@ template > class ustring16 // Calculate the size of the string to read in. len = 0; p = c2; - do { + do + { ++len; - } while (*p++ && len < length); + } while(*p++ && len < length); if (len > length) len = length; @@ -1351,19 +1440,24 @@ template > class ustring16 // Convert UTF-8 to UTF-16. u32 pos = start; - for (u32 l = 0; l < len;) { + for (u32 l = 0; l> 6) & 0x03) == 0x02) { // Invalid continuation byte. + if (((c2[l] >> 6) & 0x03) == 0x02) + { // Invalid continuation byte. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; - } else if (c2[l] == 0xC0 || c2[l] == 0xC1) { // Invalid byte - - // overlong encoding. + } + else if (c2[l] == 0xC0 || c2[l] == 0xC1) + { // Invalid byte - overlong encoding. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; - } else if ((c2[l] & 0xF8) == - 0xF0) { // 4 bytes UTF-8, 2 bytes UTF-16. + } + else if ((c2[l] & 0xF8) == 0xF0) + { // 4 bytes UTF-8, 2 bytes UTF-16. // Check for a full string. - if ((l + 3) >= len) { + if ((l + 3) >= len) + { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 3; break; @@ -1372,50 +1466,37 @@ template > class ustring16 // Validate. bool valid = true; u8 l2 = 0; - if (valid && (((c2[l + 1] >> 6) & 0x03) == 0x02)) - ++l2; - else - valid = false; - if (valid && (((c2[l + 2] >> 6) & 0x03) == 0x02)) - ++l2; - else - valid = false; - if (valid && (((c2[l + 3] >> 6) & 0x03) == 0x02)) - ++l2; - else - valid = false; - if (!valid) { + if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; + if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; + if (valid && (((c2[l+3] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; + if (!valid) + { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += l2; continue; } // Decode. - uchar8_t b1 = ((c2[l] & 0x7) << 2) | - ((c2[l + 1] >> 4) & 0x3); - uchar8_t b2 = ((c2[l + 1] & 0xF) << 4) | - ((c2[l + 2] >> 2) & 0xF); - uchar8_t b3 = ((c2[l + 2] & 0x3) << 6) | - (c2[l + 3] & 0x3F); - uchar32_t v = b3 | ((uchar32_t)b2 << 8) | - ((uchar32_t)b1 << 16); + uchar8_t b1 = ((c2[l] & 0x7) << 2) | ((c2[l+1] >> 4) & 0x3); + uchar8_t b2 = ((c2[l+1] & 0xF) << 4) | ((c2[l+2] >> 2) & 0xF); + uchar8_t b3 = ((c2[l+2] & 0x3) << 6) | (c2[l+3] & 0x3F); + uchar32_t v = b3 | ((uchar32_t)b2 << 8) | ((uchar32_t)b1 << 16); // Split v up into a surrogate pair. uchar16_t x = static_cast(v); - uchar16_t vh = UTF16_HI_SURROGATE | - ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | - (x >> 10); + uchar16_t vh = UTF16_HI_SURROGATE | ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[pos++] = vh; array[pos++] = vl; l += 4; - ++used; // Using two shorts this time, so increase used - // by 1. - } else if ((c2[l] & 0xF0) == - 0xE0) { // 3 bytes UTF-8, 1 byte UTF-16. + ++used; // Using two shorts this time, so increase used by 1. + } + else if ((c2[l] & 0xF0) == 0xE0) + { // 3 bytes UTF-8, 1 byte UTF-16. // Check for a full string. - if ((l + 2) >= len) { + if ((l + 2) >= len) + { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 2; break; @@ -1424,39 +1505,35 @@ template > class ustring16 // Validate. bool valid = true; u8 l2 = 0; - if (valid && (((c2[l + 1] >> 6) & 0x03) == 0x02)) - ++l2; - else - valid = false; - if (valid && (((c2[l + 2] >> 6) & 0x03) == 0x02)) - ++l2; - else - valid = false; - if (!valid) { + if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; + if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; + if (!valid) + { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += l2; continue; } // Decode. - uchar8_t b1 = ((c2[l] & 0xF) << 4) | - ((c2[l + 1] >> 2) & 0xF); - uchar8_t b2 = ((c2[l + 1] & 0x3) << 6) | - (c2[l + 2] & 0x3F); + uchar8_t b1 = ((c2[l] & 0xF) << 4) | ((c2[l+1] >> 2) & 0xF); + uchar8_t b2 = ((c2[l+1] & 0x3) << 6) | (c2[l+2] & 0x3F); uchar16_t ch = b2 | ((uchar16_t)b1 << 8); array[pos++] = ch; l += 3; - } else if ((c2[l] & 0xE0) == - 0xC0) { // 2 bytes UTF-8, 1 byte UTF-16. + } + else if ((c2[l] & 0xE0) == 0xC0) + { // 2 bytes UTF-8, 1 byte UTF-16. // Check for a full string. - if ((l + 1) >= len) { + if ((l + 1) >= len) + { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 1; break; } // Validate. - if (((c2[l + 1] >> 6) & 0x03) != 0x02) { + if (((c2[l+1] >> 6) & 0x03) != 0x02) + { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; continue; @@ -1464,18 +1541,19 @@ template > class ustring16 // Decode. uchar8_t b1 = (c2[l] >> 2) & 0x7; - uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l + 1] & 0x3F); + uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l+1] & 0x3F); uchar16_t ch = b2 | ((uchar16_t)b1 << 8); array[pos++] = ch; l += 2; - } else { // 1 byte UTF-8, 1 byte UTF-16. + } + else + { // 1 byte UTF-8, 1 byte UTF-16. // Validate. - if (c2[l] > 0x7F) { // Values above 0xF4 are restricted - // and aren't used. By now, anything - // above 0x7F is invalid. + if (c2[l] > 0x7F) + { // Values above 0xF4 are restricted and aren't used. By now, anything above 0x7F is invalid. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - } else - array[pos++] = static_cast(c2[l]); + } + else array[pos++] = static_cast(c2[l]); ++l; } } @@ -1487,34 +1565,35 @@ template > class ustring16 return *this; } + //! Appends a UTF-16 string to this ustring16 //! \param other The UTF-16 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. - ustring16 &append(const uchar16_t *const other, u32 length = 0xffffffff) + ustring16& append(const uchar16_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Determine if the string is long enough for a BOM. u32 len = 0; - const uchar16_t *p = other; - do { + const uchar16_t* p = other; + do + { ++len; } while (*p++ && len < unicode::BOM_ENCODE_UTF16_LEN); // Check for the BOM to determine the string's endianness. unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; - if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, - unicode::BOM_ENCODE_UTF16_LEN) == 0) + if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, unicode::BOM_ENCODE_UTF16_LEN) == 0) c_end = unicode::EUTFEE_LITTLE; - else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, - unicode::BOM_ENCODE_UTF16_LEN) == 0) + else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, unicode::BOM_ENCODE_UTF16_LEN) == 0) c_end = unicode::EUTFEE_BIG; // If a BOM was found, don't include it in the string. - const uchar16_t *c2 = other; - if (c_end != unicode::EUTFEE_NATIVE) { + const uchar16_t* c2 = other; + if (c_end != unicode::EUTFEE_NATIVE) + { c2 = other + unicode::BOM_UTF16_LEN; length -= unicode::BOM_UTF16_LEN; } @@ -1522,9 +1601,10 @@ template > class ustring16 // Calculate the size of the string to read in. len = 0; p = c2; - do { + do + { ++len; - } while (*p++ && len < length); + } while(*p++ && len < length); if (len > length) len = length; @@ -1536,7 +1616,8 @@ template > class ustring16 // Copy the string now. unicode::EUTF_ENDIAN m_end = getEndianness(); - for (u32 l = start; l < start + len; ++l) { + for (u32 l = start; l < start + len; ++l) + { array[l] = (uchar16_t)c2[l]; if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) array[l] = unicode::swapEndian16(array[l]); @@ -1549,43 +1630,43 @@ template > class ustring16 return *this; } + //! Appends a UTF-32 string to this ustring16 //! \param other The UTF-32 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. - ustring16 &append(const uchar32_t *const other, u32 length = 0xffffffff) + ustring16& append(const uchar32_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Check for the BOM to determine the string's endianness. unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; - if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, - unicode::BOM_ENCODE_UTF32_LEN) == 0) + if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, unicode::BOM_ENCODE_UTF32_LEN) == 0) c_end = unicode::EUTFEE_LITTLE; - else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, - unicode::BOM_ENCODE_UTF32_LEN) == 0) + else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, unicode::BOM_ENCODE_UTF32_LEN) == 0) c_end = unicode::EUTFEE_BIG; // If a BOM was found, don't include it in the string. - const uchar32_t *c2 = other; - if (c_end != unicode::EUTFEE_NATIVE) { + const uchar32_t* c2 = other; + if (c_end != unicode::EUTFEE_NATIVE) + { c2 = other + unicode::BOM_UTF32_LEN; length -= unicode::BOM_UTF32_LEN; } // Calculate the size of the string to read in. u32 len = 0; - const uchar32_t *p = c2; - do { + const uchar32_t* p = c2; + do + { ++len; - } while (*p++ && len < length); + } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the size of the array, do it now. - // In case all of the UTF-32 string is split into surrogate pairs, do len - // * 2. + // In case all of the UTF-32 string is split into surrogate pairs, do len * 2. if (used + (len * 2) >= allocated) reallocate(used + ((len * 2) * 2)); u32 start = used; @@ -1593,30 +1674,30 @@ template > class ustring16 // Convert UTF-32 to UTF-16. unicode::EUTF_ENDIAN m_end = getEndianness(); u32 pos = start; - for (u32 l = 0; l < len; ++l) { + for (u32 l = 0; l 0xFFFF) { - // Split ch up into a surrogate pair as it is over 16 bits - // long. + if (ch > 0xFFFF) + { + // Split ch up into a surrogate pair as it is over 16 bits long. uchar16_t x = static_cast(ch); - uchar16_t vh = UTF16_HI_SURROGATE | - ((((ch >> 16) & ((1 << 5) - 1)) - 1) - << 6) | - (x >> 10); + uchar16_t vh = UTF16_HI_SURROGATE | ((((ch >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[pos++] = vh; array[pos++] = vl; - ++used; // Using two shorts, so increased used again. - } else if (ch >= 0xD800 && ch <= 0xDFFF) { + ++used; // Using two shorts, so increased used again. + } + else if (ch >= 0xD800 && ch <= 0xDFFF) + { // Between possible UTF-16 surrogates (invalid!) array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - } else - array[pos++] = static_cast(ch); + } + else array[pos++] = static_cast(ch); } array[used] = 0; @@ -1626,20 +1707,21 @@ template > class ustring16 return *this; } + //! Appends a ustring16 to this ustring16 //! \param other The string to append to this one. //! \return A reference to our current string. - ustring16 &append(const ustring16 &other) + ustring16& append(const ustring16& other) { - const uchar16_t *oa = other.c_str(); + const uchar16_t* oa = other.c_str(); u32 len = other.size_raw(); if (used + len >= allocated) reallocate(used + len); - for (u32 l = 0; l < len; ++l) - array[used + l] = oa[l]; + for (u32 l=0; l> class ustring16 return *this; } + //! Appends a certain amount of characters of a ustring16 to this ustring16. //! \param other The string to append to this one. //! \param length How many characters of the other string to add to this one. //! \return A reference to our current string. - ustring16 &append(const ustring16 &other, u32 length) + ustring16& append(const ustring16& other, u32 length) { if (other.size() == 0) return *this; - if (other.size() < length) { + if (other.size() < length) + { append(other); return *this; } @@ -1666,7 +1750,8 @@ template > class ustring16 const_iterator iter(other, 0); u32 l = length; - while (!iter.atEnd() && l) { + while (!iter.atEnd() && l) + { uchar32_t c = *iter; append(c); ++iter; @@ -1676,6 +1761,7 @@ template > class ustring16 return *this; } + //! Reserves some memory. //! \param count The amount of characters to reserve. void reserve(u32 count) @@ -1686,6 +1772,7 @@ template > class ustring16 reallocate(count); } + //! Finds first occurrence of character. //! \param c The character to search for. //! \return Position where the character has been found, or -1 if not found. @@ -1694,7 +1781,8 @@ template > class ustring16 const_iterator i(*this, 0); s32 pos = 0; - while (!i.atEnd()) { + while (!i.atEnd()) + { uchar32_t t = *i; if (c == t) return pos; @@ -1706,12 +1794,10 @@ template > class ustring16 } //! Finds first occurrence of a character of a list. - //! \param c A list of characters to find. For example if the method should find - //! the first occurrence of 'a' or 'b', this parameter should be "ab". \param - //! count The amount of characters in the list. Usually, this should be strlen(c). - //! \return Position where one of the characters has been found, or -1 if not - //! found. - s32 findFirstChar(const uchar32_t *const c, u32 count = 1) const + //! \param c A list of characters to find. For example if the method should find the first occurrence of 'a' or 'b', this parameter should be "ab". + //! \param count The amount of characters in the list. Usually, this should be strlen(c). + //! \return Position where one of the characters has been found, or -1 if not found. + s32 findFirstChar(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; @@ -1719,9 +1805,10 @@ template > class ustring16 const_iterator i(*this, 0); s32 pos = 0; - while (!i.atEnd()) { + while (!i.atEnd()) + { uchar32_t t = *i; - for (u32 j = 0; j < count; ++j) + for (u32 j=0; j> class ustring16 return -1; } + //! Finds first position of a character not in a given list. - //! \param c A list of characters to NOT find. For example if the method should - //! find the first occurrence of a character not 'a' or 'b', this parameter should - //! be "ab". \param count The amount of characters in the list. Usually, this - //! should be strlen(c). \return Position where the character has been found, or - //! -1 if not found. - s32 findFirstCharNotInList(const uchar32_t *const c, u32 count = 1) const + //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". + //! \param count The amount of characters in the list. Usually, this should be strlen(c). + //! \return Position where the character has been found, or -1 if not found. + s32 findFirstCharNotInList(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; @@ -1745,14 +1831,15 @@ template > class ustring16 const_iterator i(*this, 0); s32 pos = 0; - while (!i.atEnd()) { + while (!i.atEnd()) + { uchar32_t t = *i; u32 j; - for (j = 0; j < count; ++j) + for (j=0; j> class ustring16 } //! Finds last position of a character not in a given list. - //! \param c A list of characters to NOT find. For example if the method should - //! find the first occurrence of a character not 'a' or 'b', this parameter should - //! be "ab". \param count The amount of characters in the list. Usually, this - //! should be strlen(c). \return Position where the character has been found, or - //! -1 if not found. - s32 findLastCharNotInList(const uchar32_t *const c, u32 count = 1) const + //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". + //! \param count The amount of characters in the list. Usually, this should be strlen(c). + //! \return Position where the character has been found, or -1 if not found. + s32 findLastCharNotInList(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; @@ -1776,14 +1861,15 @@ template > class ustring16 --i; s32 pos = size() - 1; - while (!i.atStart()) { + while (!i.atStart()) + { uchar32_t t = *i; u32 j; - for (j = 0; j < count; ++j) + for (j=0; j> class ustring16 const_iterator i(*this, startPos); s32 pos = startPos; - while (!i.atEnd()) { + while (!i.atEnd()) + { uchar32_t t = *i; if (t == c) return pos; @@ -1812,18 +1899,20 @@ template > class ustring16 return -1; } + //! Finds last occurrence of character. //! \param c The character to search for. - //! \param start The start position of the reverse search ( default = -1, on end - //! ). \return Position where the character has been found, or -1 if not found. + //! \param start The start position of the reverse search ( default = -1, on end ). + //! \return Position where the character has been found, or -1 if not found. s32 findLast(uchar32_t c, s32 start = -1) const { u32 s = size(); - start = core::clamp(start < 0 ? (s32)s : start, 0, (s32)s) - 1; + start = core::clamp ( start < 0 ? (s32)s : start, 0, (s32)s ) - 1; const_iterator i(*this, start); u32 pos = start; - while (!i.atStart()) { + while (!i.atStart()) + { uchar32_t t = *i; if (t == c) return pos; @@ -1835,11 +1924,10 @@ template > class ustring16 } //! Finds last occurrence of a character in a list. - //! \param c A list of strings to find. For example if the method should find the - //! last occurrence of 'a' or 'b', this parameter should be "ab". \param count The - //! amount of characters in the list. Usually, this should be strlen(c). \return - //! Position where one of the characters has been found, or -1 if not found. - s32 findLastChar(const uchar32_t *const c, u32 count = 1) const + //! \param c A list of strings to find. For example if the method should find the last occurrence of 'a' or 'b', this parameter should be "ab". + //! \param count The amount of characters in the list. Usually, this should be strlen(c). + //! \return Position where one of the characters has been found, or -1 if not found. + s32 findLastChar(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; @@ -1848,9 +1936,10 @@ template > class ustring16 --i; s32 pos = size(); - while (!i.atStart()) { + while (!i.atStart()) + { uchar32_t t = *i; - for (u32 j = 0; j < count; ++j) + for (u32 j=0; j> class ustring16 return -1; } + //! Finds another ustring16 in this ustring16. //! \param str The string to find. //! \param start The start position of the search. //! \return Positions where the ustring16 has been found, or -1 if not found. - s32 find(const ustring16 &str, const u32 start = 0) const + s32 find(const ustring16& str, const u32 start = 0) const { u32 my_size = size(); u32 their_size = str.size(); @@ -1875,12 +1965,14 @@ template > class ustring16 const_iterator i(*this, start); s32 pos = start; - while (!i.atEnd()) { + while (!i.atEnd()) + { const_iterator i2(i); const_iterator j(str, 0); uchar32_t t1 = (uchar32_t)*i2; uchar32_t t2 = (uchar32_t)*j; - while (t1 == t2) { + while (t1 == t2) + { ++i2; ++j; if (j.atEnd()) @@ -1895,14 +1987,16 @@ template > class ustring16 return -1; } + //! Finds another ustring16 in this ustring16. //! \param str The string to find. //! \param start The start position of the search. //! \return Positions where the string has been found, or -1 if not found. - s32 find_raw(const ustring16 &str, const u32 start = 0) const + s32 find_raw(const ustring16& str, const u32 start = 0) const { - const uchar16_t *data = str.c_str(); - if (data && *data) { + const uchar16_t* data = str.c_str(); + if (data && *data) + { u32 len = 0; while (data[len]) @@ -1911,10 +2005,11 @@ template > class ustring16 if (len > used) return -1; - for (u32 i = start; i <= used - len; ++i) { - u32 j = 0; + for (u32 i=start; i<=used-len; ++i) + { + u32 j=0; - while (data[j] && array[i + j] == data[j]) + while(data[j] && array[i+j] == data[j]) ++j; if (!data[j]) @@ -1925,6 +2020,7 @@ template > class ustring16 return -1; } + //! Returns a substring. //! \param begin: Start of substring. //! \param length: Length of substring. @@ -1934,17 +2030,18 @@ template > class ustring16 u32 len = size(); // if start after ustring16 // or no proper substring length - if ((length <= 0) || (begin >= len)) + if ((length <= 0) || (begin>=len)) return ustring16(""); // clamp length to maximal value - if ((length + begin) > len) - length = len - begin; + if ((length+begin) > len) + length = len-begin; ustring16 o; - o.reserve((length + 1) * 2); + o.reserve((length+1) * 2); const_iterator i(*this, begin); - while (!i.atEnd() && length) { + while (!i.atEnd() && length) + { o.append(*i); ++i; --length; @@ -1953,115 +2050,128 @@ template > class ustring16 return o; } + //! Appends a character to this ustring16. //! \param c Character to append. //! \return A reference to our current string. - ustring16 &operator+=(char c) + ustring16& operator += (char c) { append((uchar32_t)c); return *this; } + //! Appends a character to this ustring16. //! \param c Character to append. //! \return A reference to our current string. - ustring16 &operator+=(uchar32_t c) + ustring16& operator += (uchar32_t c) { append(c); return *this; } + //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(short c) + ustring16& operator += (short c) { append(core::stringc(c)); return *this; } + //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(unsigned short c) + ustring16& operator += (unsigned short c) { append(core::stringc(c)); return *this; } + #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(int c) + ustring16& operator += (int c) { append(core::stringc(c)); return *this; } + //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(unsigned int c) + ustring16& operator += (unsigned int c) { append(core::stringc(c)); return *this; } #endif + //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(long c) + ustring16& operator += (long c) { append(core::stringc(c)); return *this; } + //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(unsigned long c) + ustring16& operator += (unsigned long c) { append(core::stringc(c)); return *this; } + //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. - ustring16 &operator+=(double c) + ustring16& operator += (double c) { append(core::stringc(c)); return *this; } + //! Appends a char ustring16 to this ustring16. //! \param c Char ustring16 to append. //! \return A reference to our current string. - ustring16 &operator+=(const uchar16_t *const c) + ustring16& operator += (const uchar16_t* const c) { append(c); return *this; } + //! Appends a ustring16 to this ustring16. //! \param other ustring16 to append. //! \return A reference to our current string. - ustring16 &operator+=(const ustring16 &other) + ustring16& operator += (const ustring16& other) { append(other); return *this; } + //! Replaces all characters of a given type with another one. //! \param toReplace Character to replace. //! \param replaceWith Character replacing the old one. //! \return A reference to our current string. - ustring16 &replace(uchar32_t toReplace, uchar32_t replaceWith) + ustring16& replace(uchar32_t toReplace, uchar32_t replaceWith) { iterator i(*this, 0); - while (!i.atEnd()) { + while (!i.atEnd()) + { typename ustring16::access a = *i; if ((uchar32_t)a == toReplace) a = replaceWith; @@ -2070,18 +2180,18 @@ template > class ustring16 return *this; } + //! Replaces all instances of a string with another one. //! \param toReplace The string to replace. //! \param replaceWith The string replacing the old one. //! \return A reference to our current string. - ustring16 &replace(const ustring16 &toReplace, - const ustring16 &replaceWith) + ustring16& replace(const ustring16& toReplace, const ustring16& replaceWith) { if (toReplace.size() == 0) return *this; - const uchar16_t *other = toReplace.c_str(); - const uchar16_t *replace = replaceWith.c_str(); + const uchar16_t* other = toReplace.c_str(); + const uchar16_t* replace = replaceWith.c_str(); const u32 other_size = toReplace.size_raw(); const u32 replace_size = replaceWith.size_raw(); @@ -2089,9 +2199,11 @@ template > class ustring16 s32 delta = replace_size - other_size; // A character for character replace. The string will not shrink or grow. - if (delta == 0) { + if (delta == 0) + { s32 pos = 0; - while ((pos = find_raw(other, pos)) != -1) { + while ((pos = find_raw(other, pos)) != -1) + { for (u32 i = 0; i < replace_size; ++i) array[pos + i] = replace[i]; ++pos; @@ -2100,20 +2212,25 @@ template > class ustring16 } // We are going to be removing some characters. The string will shrink. - if (delta < 0) { + if (delta < 0) + { u32 i = 0; - for (u32 pos = 0; pos <= used; ++i, ++pos) { + for (u32 pos = 0; pos <= used; ++i, ++pos) + { // Is this potentially a match? - if (array[pos] == *other) { + if (array[pos] == *other) + { // Check to see if we have a match. u32 j; - for (j = 0; j < other_size; ++j) { + for (j = 0; j < other_size; ++j) + { if (array[pos + j] != other[j]) break; } // If we have a match, replace characters. - if (j == other_size) { + if (j == other_size) + { for (j = 0; j < replace_size; ++j) array[i + j] = replace[j]; i += replace_size - 1; @@ -2132,11 +2249,11 @@ template > class ustring16 } // We are going to be adding characters, so the string size will increase. - // Count the number of times toReplace exists in the string so we can - // allocate the new size. + // Count the number of times toReplace exists in the string so we can allocate the new size. u32 find_count = 0; s32 pos = 0; - while ((pos = find_raw(other, pos)) != -1) { + while ((pos = find_raw(other, pos)) != -1) + { ++find_count; ++pos; } @@ -2148,13 +2265,15 @@ template > class ustring16 // Start replacing. pos = 0; - while ((pos = find_raw(other, pos)) != -1) { - uchar16_t *start = array + pos + other_size - 1; - uchar16_t *ptr = array + used; - uchar16_t *end = array + used + delta; + while ((pos = find_raw(other, pos)) != -1) + { + uchar16_t* start = array + pos + other_size - 1; + uchar16_t* ptr = array + used; + uchar16_t* end = array + used + delta; // Shift characters to make room for the string. - while (ptr != start) { + while (ptr != start) + { *end = *ptr; --ptr; --end; @@ -2173,27 +2292,29 @@ template > class ustring16 return *this; } + //! Removes characters from a ustring16.. //! \param c The character to remove. //! \return A reference to our current string. - ustring16 &remove(uchar32_t c) + ustring16& remove(uchar32_t c) { u32 pos = 0; u32 found = 0; - u32 len = (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of - // c as a UTF-16 character. - for (u32 i = 0; i <= used; ++i) { + u32 len = (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. + for (u32 i=0; i<=used; ++i) + { uchar32_t uc32 = 0; if (!UTF16_IS_SURROGATE_HI(array[i])) uc32 |= array[i]; - else if (i + 1 <= used) { - // Convert the surrogate pair into a single UTF-32 - // character. + else if (i + 1 <= used) + { + // Convert the surrogate pair into a single UTF-32 character. uc32 = unicode::toUTF32(array[i], array[i + 1]); } u32 len2 = (uc32 > 0xFFFF ? 2 : 1); - if (uc32 == c) { + if (uc32 == c) + { found += len; continue; } @@ -2207,26 +2328,29 @@ template > class ustring16 return *this; } + //! Removes a ustring16 from the ustring16. //! \param toRemove The string to remove. //! \return A reference to our current string. - ustring16 &remove(const ustring16 &toRemove) + ustring16& remove(const ustring16& toRemove) { u32 size = toRemove.size_raw(); - if (size == 0) - return *this; + if (size == 0) return *this; - const uchar16_t *tra = toRemove.c_str(); + const uchar16_t* tra = toRemove.c_str(); u32 pos = 0; u32 found = 0; - for (u32 i = 0; i <= used; ++i) { + for (u32 i=0; i<=used; ++i) + { u32 j = 0; - while (j < size) { + while (j < size) + { if (array[i + j] != tra[j]) break; ++j; } - if (j == size) { + if (j == size) + { found += size; i += size - 1; continue; @@ -2239,10 +2363,11 @@ template > class ustring16 return *this; } + //! Removes characters from the ustring16. //! \param characters The characters to remove. //! \return A reference to our current string. - ustring16 &removeChars(const ustring16 &characters) + ustring16& removeChars(const ustring16& characters) { if (characters.size_raw() == 0) return *this; @@ -2250,35 +2375,33 @@ template > class ustring16 u32 pos = 0; u32 found = 0; const_iterator iter(characters); - for (u32 i = 0; i <= used; ++i) { + for (u32 i=0; i<=used; ++i) + { uchar32_t uc32 = 0; if (!UTF16_IS_SURROGATE_HI(array[i])) uc32 |= array[i]; - else if (i + 1 <= used) { - // Convert the surrogate pair into a single UTF-32 - // character. - uc32 = unicode::toUTF32(array[i], array[i + 1]); + else if (i + 1 <= used) + { + // Convert the surrogate pair into a single UTF-32 character. + uc32 = unicode::toUTF32(array[i], array[i+1]); } u32 len2 = (uc32 > 0xFFFF ? 2 : 1); bool cont = false; iter.toStart(); - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t c = *iter; - if (uc32 == c) { - found += (c > 0xFFFF ? 2 - : 1); // Remove characters - // equal to the size of - // c as a UTF-16 - // character. + if (uc32 == c) + { + found += (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. ++i; cont = true; break; } ++iter; } - if (cont) - continue; + if (cont) continue; array[pos++] = array[i]; if (len2 == 2) @@ -2289,33 +2412,33 @@ template > class ustring16 return *this; } + //! Trims the ustring16. - //! Removes the specified characters (by default, Latin-1 whitespace) from the - //! begining and the end of the ustring16. \param whitespace The characters that - //! are to be considered as whitespace. \return A reference to our current string. - ustring16 &trim(const ustring16 &whitespace = " \t\n\r") + //! Removes the specified characters (by default, Latin-1 whitespace) from the begining and the end of the ustring16. + //! \param whitespace The characters that are to be considered as whitespace. + //! \return A reference to our current string. + ustring16& trim(const ustring16& whitespace = " \t\n\r") { core::array utf32white = whitespace.toUTF32(); // find start and end of the substring without the specified characters - const s32 begin = findFirstCharNotInList( - utf32white.const_pointer(), whitespace.used + 1); + const s32 begin = findFirstCharNotInList(utf32white.const_pointer(), whitespace.used + 1); if (begin == -1) - return (*this = ""); + return (*this=""); - const s32 end = findLastCharNotInList( - utf32white.const_pointer(), whitespace.used + 1); + const s32 end = findLastCharNotInList(utf32white.const_pointer(), whitespace.used + 1); - return (*this = subString(begin, (end + 1) - begin)); + return (*this = subString(begin, (end +1) - begin)); } + //! Erases a character from the ustring16. - //! May be slow, because all elements following after the erased element have to - //! be copied. \param index Index of element to be erased. \return A reference to - //! our current string. - ustring16 &erase(u32 index) + //! May be slow, because all elements following after the erased element have to be copied. + //! \param index Index of element to be erased. + //! \return A reference to our current string. + ustring16& erase(u32 index) { - _IRR_DEBUG_BREAK_IF(index > used) // access violation + _IRR_DEBUG_BREAK_IF(index>used) // access violation iterator i(*this, index); @@ -2331,23 +2454,25 @@ template > class ustring16 return *this; } - //! Validate the existing ustring16, checking for valid surrogate pairs and - //! checking for proper termination. \return A reference to our current string. - ustring16 &validate() + + //! Validate the existing ustring16, checking for valid surrogate pairs and checking for proper termination. + //! \return A reference to our current string. + ustring16& validate() { // Validate all unicode characters. - for (u32 i = 0; i < allocated; ++i) { + for (u32 i=0; i= allocated) || - UTF16_IS_SURROGATE_LO(array[i])) + if (UTF16_IS_SURROGATE(array[i])) + { + if (((i+1) >= allocated) || UTF16_IS_SURROGATE_LO(array[i])) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; - else if (UTF16_IS_SURROGATE_HI(array[i]) && - !UTF16_IS_SURROGATE_LO(array[i + 1])) + else if (UTF16_IS_SURROGATE_HI(array[i]) && !UTF16_IS_SURROGATE_LO(array[i+1])) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; ++i; } @@ -2357,13 +2482,15 @@ template > class ustring16 // terminate used = 0; - if (allocated > 0) { + if (allocated > 0) + { used = allocated - 1; array[used] = 0; } return *this; } + //! Gets the last char of the ustring16, or 0. //! \return The last char of the ustring16, or 0. uchar32_t lastChar() const @@ -2371,22 +2498,26 @@ template > class ustring16 if (used < 1) return 0; - if (UTF16_IS_SURROGATE_LO(array[used - 1])) { + if (UTF16_IS_SURROGATE_LO(array[used-1])) + { // Make sure we have a paired surrogate. if (used < 2) return 0; // Check for an invalid surrogate. - if (!UTF16_IS_SURROGATE_HI(array[used - 2])) + if (!UTF16_IS_SURROGATE_HI(array[used-2])) return 0; // Convert the surrogate pair into a single UTF-32 character. - return unicode::toUTF32(array[used - 2], array[used - 1]); - } else { - return array[used - 1]; + return unicode::toUTF32(array[used-2], array[used-1]); + } + else + { + return array[used-1]; } } + //! Split the ustring16 into parts. /** This method will split a ustring16 at certain delimiter characters into the container passed in as reference. The type of the container @@ -2405,33 +2536,32 @@ template > class ustring16 characters between the delimiters are returned. \return The number of resulting substrings */ - template - u32 split(container &ret, const uchar32_t *const c, u32 count = 1, - bool ignoreEmptyTokens = true, bool keepSeparators = false) const + template + u32 split(container& ret, const uchar32_t* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const { if (!c) return 0; const_iterator i(*this); - const u32 oldSize = ret.size(); + const u32 oldSize=ret.size(); u32 pos = 0; u32 lastpos = 0; u32 lastpospos = 0; bool lastWasSeparator = false; - while (!i.atEnd()) { + while (!i.atEnd()) + { uchar32_t ch = *i; bool foundSeparator = false; - for (u32 j = 0; j < count; ++j) { - if (ch == c[j]) { + for (u32 j=0; j( - &array[lastpospos], - pos - lastpos)); + ret.push_back(ustring16(&array[lastpospos], pos - lastpos)); foundSeparator = true; lastpos = (keepSeparators ? pos : pos + 1); - lastpospos = (keepSeparators ? i.getPos() - : i.getPos() + 1); + lastpospos = (keepSeparators ? i.getPos() : i.getPos() + 1); break; } } @@ -2442,9 +2572,10 @@ template > class ustring16 u32 s = size() + 1; if (s > lastpos) ret.push_back(ustring16(&array[lastpospos], s - lastpos)); - return ret.size() - oldSize; + return ret.size()-oldSize; } + //! Split the ustring16 into parts. /** This method will split a ustring16 at certain delimiter characters into the container passed in as reference. The type of the container @@ -2462,29 +2593,35 @@ template > class ustring16 characters between the delimiters are returned. \return The number of resulting substrings */ - template - u32 split(container &ret, const ustring16 &c, - bool ignoreEmptyTokens = true, bool keepSeparators = false) const + template + u32 split(container& ret, const ustring16& c, bool ignoreEmptyTokens=true, bool keepSeparators=false) const { core::array v = c.toUTF32(); - return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, - keepSeparators); + return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, keepSeparators); } + //! Gets the size of the allocated memory buffer for the string. //! \return The size of the allocated memory buffer. - u32 capacity() const { return allocated; } + u32 capacity() const + { + return allocated; + } + + + //! Returns the raw number of UTF-16 code points in the string which includes the individual surrogates. + //! \return The raw number of UTF-16 code points, excluding the trialing NUL. + u32 size_raw() const + { + return used; + } - //! Returns the raw number of UTF-16 code points in the string which includes the - //! individual surrogates. \return The raw number of UTF-16 code points, excluding - //! the trialing NUL. - u32 size_raw() const { return used; } //! Inserts a character into the string. //! \param c The character to insert. //! \param pos The position to insert the character. //! \return A reference to our current string. - ustring16 &insert(uchar32_t c, u32 pos) + ustring16& insert(uchar32_t c, u32 pos) { u8 len = (c > 0xFFFF ? 2 : 1); @@ -2497,31 +2634,32 @@ template > class ustring16 for (u32 i = used - 2; i > iter.getPos(); --i) array[i] = array[i - len]; - if (c > 0xFFFF) { + if (c > 0xFFFF) + { // c will be multibyte, so split it up into a surrogate pair. uchar16_t x = static_cast(c); - uchar16_t vh = UTF16_HI_SURROGATE | - ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | - (x >> 10); + uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[iter.getPos()] = vh; - array[iter.getPos() + 1] = vl; - } else { + array[iter.getPos()+1] = vl; + } + else + { array[iter.getPos()] = static_cast(c); } array[used] = 0; return *this; } + //! Inserts a string into the string. //! \param c The string to insert. //! \param pos The position to insert the string. //! \return A reference to our current string. - ustring16 &insert(const ustring16 &c, u32 pos) + ustring16& insert(const ustring16& c, u32 pos) { u32 len = c.size_raw(); - if (len == 0) - return *this; + if (len == 0) return *this; if (used + len >= allocated) reallocate(used + len); @@ -2532,8 +2670,9 @@ template > class ustring16 for (u32 i = used - 2; i > iter.getPos() + len; --i) array[i] = array[i - len]; - const uchar16_t *s = c.c_str(); - for (u32 i = 0; i < len; ++i) { + const uchar16_t* s = c.c_str(); + for (u32 i = 0; i < len; ++i) + { array[pos++] = *s; ++s; } @@ -2542,11 +2681,12 @@ template > class ustring16 return *this; } + //! Inserts a character into the string. //! \param c The character to insert. //! \param pos The position to insert the character. //! \return A reference to our current string. - ustring16 &insert_raw(uchar16_t c, u32 pos) + ustring16& insert_raw(uchar16_t c, u32 pos) { if (used + 1 >= allocated) reallocate(used + 1); @@ -2561,12 +2701,14 @@ template > class ustring16 return *this; } + //! Removes a character from string. //! \param pos Position of the character to remove. //! \return A reference to our current string. - ustring16 &erase_raw(u32 pos) + ustring16& erase_raw(u32 pos) { - for (u32 i = pos; i <= used; ++i) { + for (u32 i=pos; i<=used; ++i) + { array[i] = array[i + 1]; } --used; @@ -2574,16 +2716,18 @@ template > class ustring16 return *this; } + //! Replaces a character in the string. //! \param c The new character. //! \param pos The position of the character to replace. //! \return A reference to our current string. - ustring16 &replace_raw(uchar16_t c, u32 pos) + ustring16& replace_raw(uchar16_t c, u32 pos) { array[pos] = c; return *this; } + //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. iterator begin() @@ -2592,6 +2736,7 @@ template > class ustring16 return i; } + //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. const_iterator begin() const @@ -2600,6 +2745,7 @@ template > class ustring16 return i; } + //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. const_iterator cbegin() const @@ -2608,6 +2754,7 @@ template > class ustring16 return i; } + //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. iterator end() @@ -2617,6 +2764,7 @@ template > class ustring16 return i; } + //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. const_iterator end() const @@ -2626,6 +2774,7 @@ template > class ustring16 return i; } + //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. const_iterator cend() const @@ -2635,9 +2784,10 @@ template > class ustring16 return i; } + //! Converts the string to a UTF-8 encoded string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return A string containing the UTF-8 encoded string. + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return A string containing the UTF-8 encoded string. core::string toUTF8_s(const bool addBOM = false) const { core::string ret; @@ -2645,15 +2795,18 @@ template > class ustring16 const_iterator iter(*this, 0); // Add the byte order mark if the user wants it. - if (addBOM) { + if (addBOM) + { ret.append(unicode::BOM_ENCODE_UTF8[0]); ret.append(unicode::BOM_ENCODE_UTF8[1]); ret.append(unicode::BOM_ENCODE_UTF8[2]); } - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t c = *iter; - if (c > 0xFFFF) { // 4 bytes + if (c > 0xFFFF) + { // 4 bytes uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); @@ -2662,19 +2815,25 @@ template > class ustring16 ret.append(b2); ret.append(b3); ret.append(b4); - } else if (c > 0x7FF) { // 3 bytes + } + else if (c > 0x7FF) + { // 3 bytes uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b3 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); ret.append(b3); - } else if (c > 0x7F) { // 2 bytes + } + else if (c > 0x7F) + { // 2 bytes uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); uchar8_t b2 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); - } else { // 1 byte + } + else + { // 1 byte ret.append(static_cast(c)); } ++iter; @@ -2682,25 +2841,28 @@ template > class ustring16 return ret; } + //! Converts the string to a UTF-8 encoded string array. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return An array containing the UTF-8 encoded string. + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return An array containing the UTF-8 encoded string. core::array toUTF8(const bool addBOM = false) const { - core::array ret( - used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); + core::array ret(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the byte order mark if the user wants it. - if (addBOM) { + if (addBOM) + { ret.push_back(unicode::BOM_ENCODE_UTF8[0]); ret.push_back(unicode::BOM_ENCODE_UTF8[1]); ret.push_back(unicode::BOM_ENCODE_UTF8[2]); } - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t c = *iter; - if (c > 0xFFFF) { // 4 bytes + if (c > 0xFFFF) + { // 4 bytes uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); @@ -2709,19 +2871,25 @@ template > class ustring16 ret.push_back(b2); ret.push_back(b3); ret.push_back(b4); - } else if (c > 0x7FF) { // 3 bytes + } + else if (c > 0x7FF) + { // 3 bytes uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b3 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); ret.push_back(b3); - } else if (c > 0x7F) { // 2 bytes + } + else if (c > 0x7F) + { // 2 bytes uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); uchar8_t b2 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); - } else { // 1 byte + } + else + { // 1 byte ret.push_back(static_cast(c)); } ++iter; @@ -2730,36 +2898,40 @@ template > class ustring16 return ret; } -#ifdef USTRING_CPP0X_NEWLITERALS // C++0x + +#ifdef USTRING_CPP0X_NEWLITERALS // C++0x //! Converts the string to a UTF-16 encoded string. //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return A string containing the UTF-16 encoded string. - core::string toUTF16_s( - const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return A string containing the UTF-16 encoded string. + core::string toUTF16_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::string ret; ret.reserve(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); // Add the BOM if specified. - if (addBOM) { + if (addBOM) + { if (endian == unicode::EUTFEE_NATIVE) ret[0] = unicode::BOM; - else if (endian == unicode::EUTFEE_LITTLE) { - uchar8_t *ptr8 = reinterpret_cast(&ret[0]); + else if (endian == unicode::EUTFEE_LITTLE) + { + uchar8_t* ptr8 = reinterpret_cast(&ret[0]); *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; - } else { - uchar8_t *ptr8 = reinterpret_cast(&ret[0]); + } + else + { + uchar8_t* ptr8 = reinterpret_cast(&ret[0]); *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; } } ret.append(array); - if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) { - char16_t *ptr = ret.c_str(); + if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) + { + char16_t* ptr = ret.c_str(); for (u32 i = 0; i < ret.size(); ++i) *ptr++ = unicode::swapEndian16(*ptr); } @@ -2767,37 +2939,40 @@ template > class ustring16 } #endif + //! Converts the string to a UTF-16 encoded string array. - //! Unfortunately, no toUTF16_s() version exists due to limitations with - //! Irrlicht's string class. \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return An array containing the UTF-16 encoded string. - core::array toUTF16( - const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const - { - core::array ret( - used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); - uchar16_t *ptr = ret.pointer(); + //! Unfortunately, no toUTF16_s() version exists due to limitations with Irrlicht's string class. + //! \param endian The desired endianness of the string. + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return An array containing the UTF-16 encoded string. + core::array toUTF16(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const + { + core::array ret(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); + uchar16_t* ptr = ret.pointer(); // Add the BOM if specified. - if (addBOM) { + if (addBOM) + { if (endian == unicode::EUTFEE_NATIVE) *ptr = unicode::BOM; - else if (endian == unicode::EUTFEE_LITTLE) { - uchar8_t *ptr8 = reinterpret_cast(ptr); + else if (endian == unicode::EUTFEE_LITTLE) + { + uchar8_t* ptr8 = reinterpret_cast(ptr); *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; - } else { - uchar8_t *ptr8 = reinterpret_cast(ptr); + } + else + { + uchar8_t* ptr8 = reinterpret_cast(ptr); *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; } ++ptr; } - memcpy((void *)ptr, (void *)array, used * sizeof(uchar16_t)); - if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) { + memcpy((void*)ptr, (void*)array, used * sizeof(uchar16_t)); + if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) + { for (u32 i = 0; i <= used; ++i) ptr[i] = unicode::swapEndian16(ptr[i]); } @@ -2806,36 +2981,40 @@ template > class ustring16 return ret; } -#ifdef USTRING_CPP0X_NEWLITERALS // C++0x + +#ifdef USTRING_CPP0X_NEWLITERALS // C++0x //! Converts the string to a UTF-32 encoded string. //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return A string containing the UTF-32 encoded string. - core::string toUTF32_s( - const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return A string containing the UTF-32 encoded string. + core::string toUTF32_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::string ret; ret.reserve(size() + 1 + (addBOM ? unicode::BOM_UTF32_LEN : 0)); const_iterator iter(*this, 0); // Add the BOM if specified. - if (addBOM) { + if (addBOM) + { if (endian == unicode::EUTFEE_NATIVE) ret.append(unicode::BOM); - else { + else + { union { uchar32_t full; u8 chunk[4]; } t; - if (endian == unicode::EUTFEE_LITTLE) { + if (endian == unicode::EUTFEE_LITTLE) + { t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; - } else { + } + else + { t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; @@ -2845,7 +3024,8 @@ template > class ustring16 } } - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t c = *iter; if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) c = unicode::swapEndian32(c); @@ -2856,36 +3036,39 @@ template > class ustring16 } #endif + //! Converts the string to a UTF-32 encoded string array. - //! Unfortunately, no toUTF32_s() version exists due to limitations with - //! Irrlicht's string class. \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return An array containing the UTF-32 encoded string. - core::array toUTF32( - const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const - { - core::array ret( - size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1); + //! Unfortunately, no toUTF32_s() version exists due to limitations with Irrlicht's string class. + //! \param endian The desired endianness of the string. + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return An array containing the UTF-32 encoded string. + core::array toUTF32(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const + { + core::array ret(size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the BOM if specified. - if (addBOM) { + if (addBOM) + { if (endian == unicode::EUTFEE_NATIVE) ret.push_back(unicode::BOM); - else { + else + { union { uchar32_t full; u8 chunk[4]; } t; - if (endian == unicode::EUTFEE_LITTLE) { + if (endian == unicode::EUTFEE_LITTLE) + { t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; - } else { + } + else + { t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; @@ -2896,7 +3079,8 @@ template > class ustring16 } ret.push_back(0); - while (!iter.atEnd()) { + while (!iter.atEnd()) + { uchar32_t c = *iter; if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) c = unicode::swapEndian32(c); @@ -2906,31 +3090,37 @@ template > class ustring16 return ret; } + //! Converts the string to a wchar_t encoded string. - /** The size of a wchar_t changes depending on the platform. This function will - store a correct UTF-8, -16, or -32 encoded string depending on the size of a - wchar_t. **/ + /** The size of a wchar_t changes depending on the platform. This function will store a + correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return A string containing the wchar_t encoded string. - core::string toWCHAR_s( - const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return A string containing the wchar_t encoded string. + core::string toWCHAR_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { - if (sizeof(wchar_t) == 4) { + if (sizeof(wchar_t) == 4) + { core::array a(toUTF32(endian, addBOM)); core::stringw ret(a.pointer()); return ret; - } else if (sizeof(wchar_t) == 2) { - if (endian == unicode::EUTFEE_NATIVE && addBOM == false) { + } + else if (sizeof(wchar_t) == 2) + { + if (endian == unicode::EUTFEE_NATIVE && addBOM == false) + { core::stringw ret(array); return ret; - } else { + } + else + { core::array a(toUTF16(endian, addBOM)); core::stringw ret(a.pointer()); return ret; } - } else if (sizeof(wchar_t) == 1) { + } + else if (sizeof(wchar_t) == 1) + { core::array a(toUTF8(addBOM)); core::stringw ret(a.pointer()); return ret; @@ -2940,47 +3130,47 @@ template > class ustring16 return core::stringw(); } + //! Converts the string to a wchar_t encoded string array. - /** The size of a wchar_t changes depending on the platform. This function will - store a correct UTF-8, -16, or -32 encoded string depending on the size of a - wchar_t. **/ + /** The size of a wchar_t changes depending on the platform. This function will store a + correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return An array containing the wchar_t encoded string. - core::array toWCHAR( - const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return An array containing the wchar_t encoded string. + core::array toWCHAR(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { - if (sizeof(wchar_t) == 4) { + if (sizeof(wchar_t) == 4) + { core::array a(toUTF32(endian, addBOM)); core::array ret(a.size()); ret.set_used(a.size()); - memcpy((void *)ret.pointer(), (void *)a.pointer(), - a.size() * sizeof(uchar32_t)); + memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar32_t)); return ret; } - if (sizeof(wchar_t) == 2) { - if (endian == unicode::EUTFEE_NATIVE && addBOM == false) { + if (sizeof(wchar_t) == 2) + { + if (endian == unicode::EUTFEE_NATIVE && addBOM == false) + { core::array ret(used); ret.set_used(used); - memcpy((void *)ret.pointer(), (void *)array, - used * sizeof(uchar16_t)); + memcpy((void*)ret.pointer(), (void*)array, used * sizeof(uchar16_t)); return ret; - } else { + } + else + { core::array a(toUTF16(endian, addBOM)); core::array ret(a.size()); ret.set_used(a.size()); - memcpy((void *)ret.pointer(), (void *)a.pointer(), - a.size() * sizeof(uchar16_t)); + memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar16_t)); return ret; } } - if (sizeof(wchar_t) == 1) { + if (sizeof(wchar_t) == 1) + { core::array a(toUTF8(addBOM)); core::array ret(a.size()); ret.set_used(a.size()); - memcpy((void *)ret.pointer(), (void *)a.pointer(), - a.size() * sizeof(uchar8_t)); + memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar8_t)); return ret; } @@ -2990,10 +3180,9 @@ template > class ustring16 //! Converts the string to a properly encoded io::path string. //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to - //! the string. \return An io::path string containing the properly encoded string. - io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, - const bool addBOM = false) const + //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. + //! \return An io::path string containing the properly encoded string. + io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { #if defined(_IRR_WCHAR_FILESYSTEM) return toWCHAR_s(endian, addBOM); @@ -3003,10 +3192,11 @@ template > class ustring16 } //! Loads an unknown stream of data. - //! Will attempt to determine if the stream is unicode data. Useful for loading - //! from files. \param data The data stream to load from. \param data_size The - //! length of the data string. \return A reference to our current string. - ustring16 &loadDataStream(const char *data, size_t data_size) + //! Will attempt to determine if the stream is unicode data. Useful for loading from files. + //! \param data The data stream to load from. + //! \param data_size The length of the data string. + //! \return A reference to our current string. + ustring16& loadDataStream(const char* data, size_t data_size) { // Clear our string. *this = ""; @@ -3014,23 +3204,24 @@ template > class ustring16 return *this; unicode::EUTF_ENCODE e = unicode::determineUnicodeBOM(data); - switch (e) { - default: - case unicode::EUTFE_UTF8: - append((uchar8_t *)data, data_size); - break; + switch (e) + { + default: + case unicode::EUTFE_UTF8: + append((uchar8_t*)data, data_size); + break; - case unicode::EUTFE_UTF16: - case unicode::EUTFE_UTF16_BE: - case unicode::EUTFE_UTF16_LE: - append((uchar16_t *)data, data_size / 2); - break; + case unicode::EUTFE_UTF16: + case unicode::EUTFE_UTF16_BE: + case unicode::EUTFE_UTF16_LE: + append((uchar16_t*)data, data_size / 2); + break; - case unicode::EUTFE_UTF32: - case unicode::EUTFE_UTF32_BE: - case unicode::EUTFE_UTF32_LE: - append((uchar32_t *)data, data_size / 4); - break; + case unicode::EUTFE_UTF32: + case unicode::EUTFE_UTF32_BE: + case unicode::EUTFE_UTF32_LE: + append((uchar32_t*)data, data_size / 4); + break; } return *this; @@ -3038,33 +3229,35 @@ template > class ustring16 //! Gets the encoding of the Unicode string this class contains. //! \return An enum describing the current encoding of this string. - const unicode::EUTF_ENCODE getEncoding() const { return encoding; } + const unicode::EUTF_ENCODE getEncoding() const + { + return encoding; + } //! Gets the endianness of the Unicode string this class contains. //! \return An enum describing the endianness of this string. const unicode::EUTF_ENDIAN getEndianness() const { if (encoding == unicode::EUTFE_UTF16_LE || - encoding == unicode::EUTFE_UTF32_LE) + encoding == unicode::EUTFE_UTF32_LE) return unicode::EUTFEE_LITTLE; - else - return unicode::EUTFEE_BIG; + else return unicode::EUTFEE_BIG; } private: + //! Reallocate the string, making it bigger or smaller. //! \param new_size The new size of the string. void reallocate(u32 new_size) { - uchar16_t *old_array = array; + uchar16_t* old_array = array; - array = allocator.allocate(new_size + 1); // new u16[new_size]; + array = allocator.allocate(new_size + 1); //new u16[new_size]; allocated = new_size + 1; - if (old_array == 0) - return; + if (old_array == 0) return; u32 amount = used < new_size ? used : new_size; - for (u32 i = 0; i <= amount; ++i) + for (u32 i=0; i<=amount; ++i) array[i] = old_array[i]; if (allocated <= used) @@ -3077,115 +3270,121 @@ template > class ustring16 //--- member variables - uchar16_t *array; + uchar16_t* array; unicode::EUTF_ENCODE encoding; u32 allocated; u32 used; TAlloc allocator; - // irrAllocator allocator; + //irrAllocator allocator; }; -typedef ustring16> ustring; +typedef ustring16 > ustring; + //! Appends two ustring16s. template -inline ustring16 operator+( - const ustring16 &left, const ustring16 &right) +inline ustring16 operator+(const ustring16& left, const ustring16& right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a null-terminated unicode string. template -inline ustring16 operator+(const ustring16 &left, const B *const right) +inline ustring16 operator+(const ustring16& left, const B* const right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a null-terminated unicode string. template -inline ustring16 operator+(const B *const left, const ustring16 &right) +inline ustring16 operator+(const B* const left, const ustring16& right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and an Irrlicht string. template -inline ustring16 operator+( - const ustring16 &left, const string &right) +inline ustring16 operator+(const ustring16& left, const string& right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and an Irrlicht string. template -inline ustring16 operator+( - const string &left, const ustring16 &right) +inline ustring16 operator+(const string& left, const ustring16& right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a std::basic_string. template -inline ustring16 operator+(const ustring16 &left, - const std::basic_string &right) +inline ustring16 operator+(const ustring16& left, const std::basic_string& right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a std::basic_string. template -inline ustring16 operator+(const std::basic_string &left, - const ustring16 &right) +inline ustring16 operator+(const std::basic_string& left, const ustring16& right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a char. template -inline ustring16 operator+(const ustring16 &left, const char right) +inline ustring16 operator+(const ustring16& left, const char right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a char. template -inline ustring16 operator+(const char left, const ustring16 &right) +inline ustring16 operator+(const char left, const ustring16& right) { ustring16 ret(left); ret += right; return ret; } + #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a ustring16 and a uchar32_t. template -inline ustring16 operator+(const ustring16 &left, const uchar32_t right) +inline ustring16 operator+(const ustring16& left, const uchar32_t right) { ustring16 ret(left); ret += right; return ret; } + //! Appends a ustring16 and a uchar32_t. template -inline ustring16 operator+(const uchar32_t left, const ustring16 &right) +inline ustring16 operator+(const uchar32_t left, const ustring16& right) { ustring16 ret(left); ret += right; @@ -3193,417 +3392,454 @@ inline ustring16 operator+(const uchar32_t left, const ustring16 } #endif + //! Appends a ustring16 and a short. template -inline ustring16 operator+(const ustring16 &left, const short right) +inline ustring16 operator+(const ustring16& left, const short right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and a short. template -inline ustring16 operator+(const short left, const ustring16 &right) +inline ustring16 operator+(const short left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and an unsigned short. template -inline ustring16 operator+( - const ustring16 &left, const unsigned short right) +inline ustring16 operator+(const ustring16& left, const unsigned short right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and an unsigned short. template -inline ustring16 operator+( - const unsigned short left, const ustring16 &right) +inline ustring16 operator+(const unsigned short left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and an int. template -inline ustring16 operator+(const ustring16 &left, const int right) +inline ustring16 operator+(const ustring16& left, const int right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and an int. template -inline ustring16 operator+(const int left, const ustring16 &right) +inline ustring16 operator+(const int left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and an unsigned int. template -inline ustring16 operator+( - const ustring16 &left, const unsigned int right) +inline ustring16 operator+(const ustring16& left, const unsigned int right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and an unsigned int. template -inline ustring16 operator+( - const unsigned int left, const ustring16 &right) +inline ustring16 operator+(const unsigned int left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and a long. template -inline ustring16 operator+(const ustring16 &left, const long right) +inline ustring16 operator+(const ustring16& left, const long right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and a long. template -inline ustring16 operator+(const long left, const ustring16 &right) +inline ustring16 operator+(const long left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and an unsigned long. template -inline ustring16 operator+( - const ustring16 &left, const unsigned long right) +inline ustring16 operator+(const ustring16& left, const unsigned long right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and an unsigned long. template -inline ustring16 operator+( - const unsigned long left, const ustring16 &right) +inline ustring16 operator+(const unsigned long left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and a float. template -inline ustring16 operator+(const ustring16 &left, const float right) +inline ustring16 operator+(const ustring16& left, const float right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and a float. template -inline ustring16 operator+(const float left, const ustring16 &right) +inline ustring16 operator+(const float left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + //! Appends a ustring16 and a double. template -inline ustring16 operator+(const ustring16 &left, const double right) +inline ustring16 operator+(const ustring16& left, const double right) { ustring16 ret(left); ret += core::stringc(right); return ret; } + //! Appends a ustring16 and a double. template -inline ustring16 operator+(const double left, const ustring16 &right) +inline ustring16 operator+(const double left, const ustring16& right) { ustring16 ret((core::stringc(left))); ret += right; return ret; } + #ifdef USTRING_CPP0X //! Appends two ustring16s. template -inline ustring16 &&operator+( - const ustring16 &left, ustring16 &&right) +inline ustring16&& operator+(const ustring16& left, ustring16&& right) { - // std::cout << "MOVE operator+(&, &&)" << std::endl; + //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(left, 0); return std::move(right); } + //! Appends two ustring16s. template -inline ustring16 &&operator+( - ustring16 &&left, const ustring16 &right) +inline ustring16&& operator+(ustring16&& left, const ustring16& right) { - // std::cout << "MOVE operator+(&&, &)" << std::endl; + //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } + //! Appends two ustring16s. template -inline ustring16 &&operator+(ustring16 &&left, ustring16 &&right) +inline ustring16&& operator+(ustring16&& left, ustring16&& right) { - // std::cout << "MOVE operator+(&&, &&)" << std::endl; + //std::cout << "MOVE operator+(&&, &&)" << std::endl; if ((right.size_raw() <= left.capacity() - left.size_raw()) || - (right.capacity() - right.size_raw() < left.size_raw())) { + (right.capacity() - right.size_raw() < left.size_raw())) + { left.append(right); return std::move(left); - } else { + } + else + { right.insert(left, 0); return std::move(right); } } + //! Appends a ustring16 and a null-terminated unicode string. template -inline ustring16 &&operator+(ustring16 &&left, const B *const right) +inline ustring16&& operator+(ustring16&& left, const B* const right) { - // std::cout << "MOVE operator+(&&, B*)" << std::endl; + //std::cout << "MOVE operator+(&&, B*)" << std::endl; left.append(right); return std::move(left); } + //! Appends a ustring16 and a null-terminated unicode string. template -inline ustring16 &&operator+(const B *const left, ustring16 &&right) +inline ustring16&& operator+(const B* const left, ustring16&& right) { - // std::cout << "MOVE operator+(B*, &&)" << std::endl; + //std::cout << "MOVE operator+(B*, &&)" << std::endl; right.insert(left, 0); return std::move(right); } + //! Appends a ustring16 and an Irrlicht string. template -inline ustring16 &&operator+( - const string &left, ustring16 &&right) +inline ustring16&& operator+(const string& left, ustring16&& right) { - // std::cout << "MOVE operator+(&, &&)" << std::endl; + //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(left, 0); return std::move(right); } + //! Appends a ustring16 and an Irrlicht string. template -inline ustring16 &&operator+( - ustring16 &&left, const string &right) +inline ustring16&& operator+(ustring16&& left, const string& right) { - // std::cout << "MOVE operator+(&&, &)" << std::endl; + //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } + //! Appends a ustring16 and a std::basic_string. template -inline ustring16 &&operator+( - const std::basic_string &left, ustring16 &&right) +inline ustring16&& operator+(const std::basic_string& left, ustring16&& right) { - // std::cout << "MOVE operator+(&, &&)" << std::endl; + //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(core::ustring16(left), 0); return std::move(right); } + //! Appends a ustring16 and a std::basic_string. template -inline ustring16 &&operator+( - ustring16 &&left, const std::basic_string &right) +inline ustring16&& operator+(ustring16&& left, const std::basic_string& right) { - // std::cout << "MOVE operator+(&&, &)" << std::endl; + //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } + //! Appends a ustring16 and a char. template -inline ustring16 operator+(ustring16 &&left, const char right) +inline ustring16 operator+(ustring16&& left, const char right) { left.append((uchar32_t)right); return std::move(left); } + //! Appends a ustring16 and a char. template -inline ustring16 operator+(const char left, ustring16 &&right) +inline ustring16 operator+(const char left, ustring16&& right) { right.insert((uchar32_t)left, 0); return std::move(right); } + #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a ustring16 and a uchar32_t. template -inline ustring16 operator+(ustring16 &&left, const uchar32_t right) +inline ustring16 operator+(ustring16&& left, const uchar32_t right) { left.append(right); return std::move(left); } + //! Appends a ustring16 and a uchar32_t. template -inline ustring16 operator+(const uchar32_t left, ustring16 &&right) +inline ustring16 operator+(const uchar32_t left, ustring16&& right) { right.insert(left, 0); return std::move(right); } #endif + //! Appends a ustring16 and a short. template -inline ustring16 operator+(ustring16 &&left, const short right) +inline ustring16 operator+(ustring16&& left, const short right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and a short. template -inline ustring16 operator+(const short left, ustring16 &&right) +inline ustring16 operator+(const short left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and an unsigned short. template -inline ustring16 operator+(ustring16 &&left, const unsigned short right) +inline ustring16 operator+(ustring16&& left, const unsigned short right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and an unsigned short. template -inline ustring16 operator+(const unsigned short left, ustring16 &&right) +inline ustring16 operator+(const unsigned short left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and an int. template -inline ustring16 operator+(ustring16 &&left, const int right) +inline ustring16 operator+(ustring16&& left, const int right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and an int. template -inline ustring16 operator+(const int left, ustring16 &&right) +inline ustring16 operator+(const int left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and an unsigned int. template -inline ustring16 operator+(ustring16 &&left, const unsigned int right) +inline ustring16 operator+(ustring16&& left, const unsigned int right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and an unsigned int. template -inline ustring16 operator+(const unsigned int left, ustring16 &&right) +inline ustring16 operator+(const unsigned int left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and a long. template -inline ustring16 operator+(ustring16 &&left, const long right) +inline ustring16 operator+(ustring16&& left, const long right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and a long. template -inline ustring16 operator+(const long left, ustring16 &&right) +inline ustring16 operator+(const long left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and an unsigned long. template -inline ustring16 operator+(ustring16 &&left, const unsigned long right) +inline ustring16 operator+(ustring16&& left, const unsigned long right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and an unsigned long. template -inline ustring16 operator+(const unsigned long left, ustring16 &&right) +inline ustring16 operator+(const unsigned long left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and a float. template -inline ustring16 operator+(ustring16 &&left, const float right) +inline ustring16 operator+(ustring16&& left, const float right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and a float. template -inline ustring16 operator+(const float left, ustring16 &&right) +inline ustring16 operator+(const float left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } + //! Appends a ustring16 and a double. template -inline ustring16 operator+(ustring16 &&left, const double right) +inline ustring16 operator+(ustring16&& left, const double right) { left.append(core::stringc(right)); return std::move(left); } + //! Appends a ustring16 and a double. template -inline ustring16 operator+(const double left, ustring16 &&right) +inline ustring16 operator+(const double left, ustring16&& right) { right.insert(core::stringc(left), 0); return std::move(right); } #endif + #ifndef USTRING_NO_STL //! Writes a ustring16 to an ostream. template -inline std::ostream &operator<<(std::ostream &out, const ustring16 &in) +inline std::ostream& operator<<(std::ostream& out, const ustring16& in) { out << in.toUTF8_s().c_str(); return out; @@ -3611,13 +3847,14 @@ inline std::ostream &operator<<(std::ostream &out, const ustring16 &in) //! Writes a ustring16 to a wostream. template -inline std::wostream &operator<<(std::wostream &out, const ustring16 &in) +inline std::wostream& operator<<(std::wostream& out, const ustring16& in) { out << in.toWCHAR_s().c_str(); return out; } #endif + #ifndef USTRING_NO_STL namespace unicode @@ -3627,22 +3864,23 @@ namespace unicode //! Algorithm taken from std::hash. class hash : public std::unary_function { -public: - size_t operator()(const core::ustring &s) const - { - size_t ret = 2166136261U; - size_t index = 0; - size_t stride = 1 + s.size_raw() / 10; - - core::ustring::const_iterator i = s.begin(); - while (i != s.end()) { - // TODO: Don't force u32 on an x64 OS. Make it agnostic. - ret = 16777619U * ret ^ (size_t)s[(u32)index]; - index += stride; - i += stride; + public: + size_t operator()(const core::ustring& s) const + { + size_t ret = 2166136261U; + size_t index = 0; + size_t stride = 1 + s.size_raw() / 10; + + core::ustring::const_iterator i = s.begin(); + while (i != s.end()) + { + // TODO: Don't force u32 on an x64 OS. Make it agnostic. + ret = 16777619U * ret ^ (size_t)s[(u32)index]; + index += stride; + i += stride; + } + return (ret); } - return (ret); - } }; } // end namespace unicode diff --git a/src/irrlicht_changes/static_text.cpp b/src/irrlicht_changes/static_text.cpp index eb1d338dc..bf61cd64e 100644 --- a/src/irrlicht_changes/static_text.cpp +++ b/src/irrlicht_changes/static_text.cpp @@ -13,7 +13,7 @@ #include #if USE_FREETYPE -#include "CGUITTFont.h" + #include "CGUITTFont.h" #endif #include "util/string.h" @@ -27,20 +27,23 @@ namespace gui { //! constructor StaticText::StaticText(const EnrichedString &text, bool border, - IGUIEnvironment *environment, IGUIElement *parent, s32 id, - const core::rect &rectangle, bool background) : - IGUIStaticText(environment, parent, id, rectangle), - HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), Border(border), - WordWrap(false), Background(background), RestrainTextInside(true), - RightToLeft(false), OverrideFont(0), LastBreakFont(0) -{ -#ifdef _DEBUG + IGUIEnvironment* environment, IGUIElement* parent, + s32 id, const core::rect& rectangle, + bool background) +: IGUIStaticText(environment, parent, id, rectangle), + HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT), + Border(border), WordWrap(false), Background(background), + RestrainTextInside(true), RightToLeft(false), + OverrideFont(0), LastBreakFont(0) +{ + #ifdef _DEBUG setDebugName("StaticText"); -#endif + #endif setText(text); } + //! destructor StaticText::~StaticText() { @@ -54,24 +57,23 @@ void StaticText::draw() if (!IsVisible) return; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (!skin) return; - video::IVideoDriver *driver = Environment->getVideoDriver(); + video::IVideoDriver* driver = Environment->getVideoDriver(); core::rect frameRect(AbsoluteRect); // draw background if (Background) - driver->draw2DRectangle( - getBackgroundColor(), frameRect, &AbsoluteClippingRect); + driver->draw2DRectangle(getBackgroundColor(), frameRect, &AbsoluteClippingRect); // draw the border - if (Border) { - skin->draw3DSunkenPane( - this, 0, true, false, frameRect, &AbsoluteClippingRect); + if (Border) + { + skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect); frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X); } @@ -82,52 +84,52 @@ void StaticText::draw() updateText(); core::rect r = frameRect; - s32 height_line = font->getDimension(L"A").Height + - font->getKerningHeight(); + s32 height_line = font->getDimension(L"A").Height + font->getKerningHeight(); s32 height_total = height_line * BrokenText.size(); - if (VAlign == EGUIA_CENTER && WordWrap) { + if (VAlign == EGUIA_CENTER && WordWrap) + { r.UpperLeftCorner.Y = r.getCenter().Y - (height_total / 2); - } else if (VAlign == EGUIA_LOWERRIGHT) { + } + else if (VAlign == EGUIA_LOWERRIGHT) + { r.UpperLeftCorner.Y = r.LowerRightCorner.Y - height_total; } - if (HAlign == EGUIA_LOWERRIGHT) { - r.UpperLeftCorner.X = r.LowerRightCorner.X - getTextWidth(); + if (HAlign == EGUIA_LOWERRIGHT) + { + r.UpperLeftCorner.X = r.LowerRightCorner.X - + getTextWidth(); } irr::video::SColor previous_color(255, 255, 255, 255); for (const EnrichedString &str : BrokenText) { - if (HAlign == EGUIA_LOWERRIGHT) { - r.UpperLeftCorner.X = - frameRect.LowerRightCorner.X - - font->getDimension(str.c_str()).Width; + if (HAlign == EGUIA_LOWERRIGHT) + { + r.UpperLeftCorner.X = frameRect.LowerRightCorner.X - + font->getDimension(str.c_str()).Width; } - // str = colorizeText(BrokenText[i].c_str(), colors, - // previous_color); if (!colors.empty()) previous_color = - //colors[colors.size() - 1]; + //str = colorizeText(BrokenText[i].c_str(), colors, previous_color); + //if (!colors.empty()) + // previous_color = colors[colors.size() - 1]; #if USE_FREETYPE if (font->getType() == irr::gui::EGFT_CUSTOM) { - irr::gui::CGUITTFont *tmp = - static_cast(font); - tmp->draw(str, r, previous_color, // FIXME - HAlign == EGUIA_CENTER, - VAlign == EGUIA_CENTER, - (RestrainTextInside ? &AbsoluteClippingRect - : NULL)); + irr::gui::CGUITTFont *tmp = static_cast(font); + tmp->draw(str, + r, previous_color, // FIXME + HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, + (RestrainTextInside ? &AbsoluteClippingRect : NULL)); } else #endif { // Draw non-colored text - font->draw(str.c_str(), r, - str.getDefaultColor(), // TODO: Implement - // colorization - HAlign == EGUIA_CENTER, - VAlign == EGUIA_CENTER, - (RestrainTextInside ? &AbsoluteClippingRect - : NULL)); + font->draw(str.c_str(), + r, str.getDefaultColor(), // TODO: Implement colorization + HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, + (RestrainTextInside ? &AbsoluteClippingRect : NULL)); } + r.LowerRightCorner.Y += height_line; r.UpperLeftCorner.Y += height_line; } @@ -136,8 +138,9 @@ void StaticText::draw() IGUIElement::draw(); } + //! Sets another skin independent font. -void StaticText::setOverrideFont(IGUIFont *font) +void StaticText::setOverrideFont(IGUIFont* font) { if (OverrideFont == font) return; @@ -154,17 +157,17 @@ void StaticText::setOverrideFont(IGUIFont *font) } //! Gets the override font (if any) -IGUIFont *StaticText::getOverrideFont() const +IGUIFont * StaticText::getOverrideFont() const { return OverrideFont; } //! Get the font which is used right now for drawing -IGUIFont *StaticText::getActiveFont() const +IGUIFont* StaticText::getActiveFont() const { - if (OverrideFont) + if ( OverrideFont ) return OverrideFont; - IGUISkin *skin = Environment->getSkin(); + IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; @@ -177,6 +180,7 @@ void StaticText::setOverrideColor(video::SColor color) updateText(); } + //! Sets another color for the text. void StaticText::setBackgroundColor(video::SColor color) { @@ -184,57 +188,66 @@ void StaticText::setBackgroundColor(video::SColor color) Background = true; } + //! Sets whether to draw the background void StaticText::setDrawBackground(bool draw) { Background = draw; } + //! Gets the background color video::SColor StaticText::getBackgroundColor() const { IGUISkin *skin = Environment->getSkin(); - return (ColoredText.hasBackground() || !skin) ? ColoredText.getBackground() - : skin->getColor(gui::EGDC_3D_FACE); + return (ColoredText.hasBackground() || !skin) ? + ColoredText.getBackground() : skin->getColor(gui::EGDC_3D_FACE); } + //! Checks if background drawing is enabled bool StaticText::isDrawBackgroundEnabled() const { return Background; } + //! Sets whether to draw the border void StaticText::setDrawBorder(bool draw) { Border = draw; } + //! Checks if border drawing is enabled bool StaticText::isDrawBorderEnabled() const { return Border; } + void StaticText::setTextRestrainedInside(bool restrainTextInside) { RestrainTextInside = restrainTextInside; } + bool StaticText::isTextRestrainedInside() const { return RestrainTextInside; } + void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { HAlign = horizontal; VAlign = vertical; } + #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 -const video::SColor &StaticText::getOverrideColor() const +const video::SColor& StaticText::getOverrideColor() const #else video::SColor StaticText::getOverrideColor() const #endif @@ -242,6 +255,7 @@ video::SColor StaticText::getOverrideColor() const return ColoredText.getDefaultColor(); } + //! Sets if the static text should use the overide color or the //! color in the gui skin. void StaticText::enableOverrideColor(bool enable) @@ -249,11 +263,13 @@ void StaticText::enableOverrideColor(bool enable) // TODO } + bool StaticText::isOverrideColorEnabled() const { return true; } + //! Enables or disables word wrap for using the static text as //! multiline text control. void StaticText::setWordWrap(bool enable) @@ -262,24 +278,29 @@ void StaticText::setWordWrap(bool enable) updateText(); } + bool StaticText::isWordWrapEnabled() const { return WordWrap; } + void StaticText::setRightToLeft(bool rtl) { - if (RightToLeft != rtl) { + if (RightToLeft != rtl) + { RightToLeft = rtl; updateText(); } } + bool StaticText::isRightToLeft() const { return RightToLeft; } + //! Breaks the single text line. // Updates the font colors void StaticText::updateText() @@ -299,8 +320,8 @@ void StaticText::updateText() // Update word wrap - IGUISkin *skin = Environment->getSkin(); - IGUIFont *font = getActiveFont(); + IGUISkin* skin = Environment->getSkin(); + IGUIFont* font = getActiveFont(); if (!font) return; @@ -313,96 +334,92 @@ void StaticText::updateText() s32 length = 0; s32 elWidth = RelativeRect.getWidth(); if (Border) - elWidth -= 2 * skin->getSize(EGDS_TEXT_DISTANCE_X); + elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X); wchar_t c; - // std::vector colors; + //std::vector colors; // We have to deal with right-to-left and left-to-right differently // However, most parts of the following code is the same, it's just // some order and boundaries which change. - if (!RightToLeft) { + if (!RightToLeft) + { // regular (left-to-right) - for (s32 i = 0; i < size; ++i) { + for (s32 i=0; igetDimension(whitespace.c_str()) - .Width; - // const std::wstring sanitized = - // removeEscapes(word.c_str()); - const s32 wordlgth = - font->getDimension(word.c_str()) - .Width; - - if (wordlgth > elWidth) { - // This word is too long to fit in the - // available space, look for the Unicode - // Soft HYphen (SHY / 00AD) character for - // a place to break the word at - int where = core::stringw(word.c_str()) - .findFirst(wchar_t( - 0x00AD)); - if (where != -1) { - EnrichedString first = word.substr( - 0, where); - EnrichedString second = word.substr( - where, - word.size() - where); + const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; + //const std::wstring sanitized = removeEscapes(word.c_str()); + const s32 wordlgth = font->getDimension(word.c_str()).Width; + + if (wordlgth > elWidth) + { + // This word is too long to fit in the available space, look for + // the Unicode Soft HYphen (SHY / 00AD) character for a place to + // break the word at + int where = core::stringw(word.c_str()).findFirst( wchar_t(0x00AD) ); + if (where != -1) + { + EnrichedString first = word.substr(0, where); + EnrichedString second = word.substr(where, word.size() - where); first.addCharNoColor(L'-'); - BrokenText.push_back( - line + first); - const s32 secondLength = - font->getDimension(second.c_str()) - .Width; + BrokenText.push_back(line + first); + const s32 secondLength = font->getDimension(second.c_str()).Width; length = secondLength; line = second; - } else { - // No soft hyphen found, so - // there's nothing more we can do + } + else + { + // No soft hyphen found, so there's nothing more we can do // break to next line if (length) - BrokenText.push_back( - line); + BrokenText.push_back(line); length = wordlgth; line = word; } - } else if (length && - (length + wordlgth + whitelgth > - elWidth)) { + } + else if (length && (length + wordlgth + whitelgth > elWidth)) + { // break to next line BrokenText.push_back(line); length = wordlgth; line = word; - } else { + } + else + { // add word to line line += whitespace; line += word; @@ -413,12 +430,14 @@ void StaticText::updateText() whitespace.clear(); } - if (isWhitespace && c != 0) { + if ( isWhitespace && c != 0) + { whitespace.addChar(cText, i); } // compute line break - if (lineBreak) { + if (lineBreak) + { line += whitespace; line += word; BrokenText.push_back(line); @@ -433,45 +452,49 @@ void StaticText::updateText() line += whitespace; line += word; BrokenText.push_back(line); - } else { + } + else + { // right-to-left - for (s32 i = size; i >= 0; --i) { + for (s32 i=size; i>=0; --i) + { c = cText.getString()[i]; bool lineBreak = false; if (c == L'\r') // Mac or Windows breaks { lineBreak = true; - // if ((i>0) && Text[i-1] == L'\n') // Windows breaks + //if ((i>0) && Text[i-1] == L'\n') // Windows breaks //{ // Text.erase(i-1); // --size; //} c = '\0'; - } else if (c == L'\n') // Unix breaks + } + else if (c == L'\n') // Unix breaks { lineBreak = true; c = '\0'; } - if (c == L' ' || c == 0 || i == 0) { - if (word.size()) { + if (c==L' ' || c==0 || i==0) + { + if (word.size()) + { // here comes the next whitespace, look if // we must break the last word to the next line. - const s32 whitelgth = - font->getDimension(whitespace.c_str()) - .Width; - const s32 wordlgth = - font->getDimension(word.c_str()) - .Width; - - if (length && (length + wordlgth + whitelgth > - elWidth)) { + const s32 whitelgth = font->getDimension(whitespace.c_str()).Width; + const s32 wordlgth = font->getDimension(word.c_str()).Width; + + if (length && (length + wordlgth + whitelgth > elWidth)) + { // break to next line BrokenText.push_back(line); length = wordlgth; line = word; - } else { + } + else + { // add word to line line = whitespace + line; line = word + line; @@ -483,12 +506,12 @@ void StaticText::updateText() } if (c != 0) - // whitespace = core::stringw(&c, 1) + - //whitespace; - whitespace = cText.substr(i, 1) + whitespace; + // whitespace = core::stringw(&c, 1) + whitespace; + whitespace = cText.substr(i, 1) + whitespace; // compute line break - if (lineBreak) { + if (lineBreak) + { line = whitespace + line; line = word + line; BrokenText.push_back(line); @@ -497,9 +520,11 @@ void StaticText::updateText() whitespace.clear(); length = 0; } - } else { + } + else + { // yippee this is a word.. - // word = core::stringw(&c, 1) + word; + //word = core::stringw(&c, 1) + word; word = cText.substr(i, 1) + word; } } @@ -510,8 +535,9 @@ void StaticText::updateText() } } + //! Sets the new caption of this element. -void StaticText::setText(const wchar_t *text) +void StaticText::setText(const wchar_t* text) { setText(EnrichedString(text, getOverrideColor())); } @@ -529,10 +555,11 @@ void StaticText::updateAbsolutePosition() updateText(); } + //! Returns the height of the text in pixels when it is drawn. s32 StaticText::getTextHeight() const { - IGUIFont *font = getActiveFont(); + IGUIFont* font = getActiveFont(); if (!font) return 0; @@ -544,6 +571,7 @@ s32 StaticText::getTextHeight() const return font->getDimension(BrokenText[0].c_str()).Height; } + s32 StaticText::getTextWidth() const { IGUIFont *font = getActiveFont(); @@ -562,34 +590,34 @@ s32 StaticText::getTextWidth() const return widest; } + //! Writes attributes of the element. //! Implement this to expose the attributes of your element for //! scripting languages, editors, debuggers or xml serialization purposes. -void StaticText::serializeAttributes( - io::IAttributes *out, io::SAttributeReadWriteOptions *options = 0) const -{ - IGUIStaticText::serializeAttributes(out, options); - - out->addBool("Border", Border); - out->addBool("OverrideColorEnabled", true); - out->addBool("OverrideBGColorEnabled", ColoredText.hasBackground()); - out->addBool("WordWrap", WordWrap); - out->addBool("Background", Background); - out->addBool("RightToLeft", RightToLeft); - out->addBool("RestrainTextInside", RestrainTextInside); - out->addColor("OverrideColor", ColoredText.getDefaultColor()); - out->addColor("BGColor", ColoredText.getBackground()); - out->addEnum("HTextAlign", HAlign, GUIAlignmentNames); - out->addEnum("VTextAlign", VAlign, GUIAlignmentNames); +void StaticText::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const +{ + IGUIStaticText::serializeAttributes(out,options); + + out->addBool ("Border", Border); + out->addBool ("OverrideColorEnabled",true); + out->addBool ("OverrideBGColorEnabled",ColoredText.hasBackground()); + out->addBool ("WordWrap", WordWrap); + out->addBool ("Background", Background); + out->addBool ("RightToLeft", RightToLeft); + out->addBool ("RestrainTextInside", RestrainTextInside); + out->addColor ("OverrideColor", ColoredText.getDefaultColor()); + out->addColor ("BGColor", ColoredText.getBackground()); + out->addEnum ("HTextAlign", HAlign, GUIAlignmentNames); + out->addEnum ("VTextAlign", VAlign, GUIAlignmentNames); // out->addFont ("OverrideFont", OverrideFont); } + //! Reads attributes of the element -void StaticText::deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0) +void StaticText::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { - IGUIStaticText::deserializeAttributes(in, options); + IGUIStaticText::deserializeAttributes(in,options); Border = in->getAttributeAsBool("Border"); setWordWrap(in->getAttributeAsBool("WordWrap")); @@ -601,10 +629,8 @@ void StaticText::deserializeAttributes( if (in->getAttributeAsBool("OverrideBGColorEnabled")) ColoredText.setBackground(in->getAttributeAsColor("BGColor")); - setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration( - "HTextAlign", GUIAlignmentNames), - (EGUI_ALIGNMENT)in->getAttributeAsEnumeration( - "VTextAlign", GUIAlignmentNames)); + setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), + (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); // OverrideFont = in->getAttributeAsFont("OverrideFont"); } @@ -615,4 +641,5 @@ void StaticText::deserializeAttributes( } // end namespace irr + #endif // _IRR_COMPILE_WITH_GUI_ diff --git a/src/irrlicht_changes/static_text.h b/src/irrlicht_changes/static_text.h index 5c4db3e95..1f111ea56 100644 --- a/src/irrlicht_changes/static_text.h +++ b/src/irrlicht_changes/static_text.h @@ -28,202 +28,207 @@ namespace irr namespace gui { -const EGUI_ELEMENT_TYPE EGUIET_ENRICHED_STATIC_TEXT = (EGUI_ELEMENT_TYPE)(0x1000); + const EGUI_ELEMENT_TYPE EGUIET_ENRICHED_STATIC_TEXT = (EGUI_ELEMENT_TYPE)(0x1000); -class StaticText : public IGUIStaticText -{ -public: - // StaticText is translated by EnrichedString. - // No need to use translate_string() - StaticText(const EnrichedString &text, bool border, IGUIEnvironment *environment, - IGUIElement *parent, s32 id, const core::rect &rectangle, + class StaticText : public IGUIStaticText + { + public: + + // StaticText is translated by EnrichedString. + // No need to use translate_string() + StaticText(const EnrichedString &text, bool border, IGUIEnvironment* environment, + IGUIElement* parent, s32 id, const core::rect& rectangle, bool background = false); - //! destructor - virtual ~StaticText(); + //! destructor + virtual ~StaticText(); + + 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) + { + if (parent == NULL) { + // parent is NULL, so we must find one, or we need not to drop + // result, but then there will be a memory leak. + // + // What Irrlicht does is to use guienv as a parent, but the problem + // is that guienv is here only an IGUIEnvironment, while it is a + // CGUIEnvironment in Irrlicht, which inherits from both IGUIElement + // and IGUIEnvironment. + // + // A solution would be to dynamic_cast guienv to a + // IGUIElement*, but Irrlicht is shipped without rtti support + // in some distributions, causing the dymanic_cast to segfault. + // + // Thus, to find the parent, we create a dummy StaticText and ask + // for its parent, and then remove it. + irr::gui::IGUIStaticText *dummy_text = + guienv->addStaticText(L"", rectangle, border, wordWrap, + parent, id, fillBackground); + parent = dummy_text->getParent(); + dummy_text->remove(); + } + irr::gui::IGUIStaticText *result = new irr::gui::StaticText( + text, border, guienv, parent, + id, rectangle, fillBackground); + + result->setWordWrap(wordWrap); + result->drop(); + return result; + } - static irr::gui::IGUIStaticText *add(irr::gui::IGUIEnvironment *guienv, - const EnrichedString &text, const core::rect &rectangle, - bool border = false, bool wordWrap = true, - irr::gui::IGUIElement *parent = NULL, s32 id = -1, + static irr::gui::IGUIStaticText *add( + irr::gui::IGUIEnvironment *guienv, + const wchar_t *text, + const core::rect< s32 > &rectangle, + bool border = false, + bool wordWrap = true, + irr::gui::IGUIElement *parent = NULL, + s32 id = -1, bool fillBackground = false) - { - if (parent == NULL) { - // parent is NULL, so we must find one, or we need not to drop - // result, but then there will be a memory leak. - // - // What Irrlicht does is to use guienv as a parent, but the - // problem is that guienv is here only an IGUIEnvironment, while - // it is a CGUIEnvironment in Irrlicht, which inherits from both - // IGUIElement and IGUIEnvironment. - // - // A solution would be to dynamic_cast guienv to a - // IGUIElement*, but Irrlicht is shipped without rtti support - // in some distributions, causing the dymanic_cast to segfault. - // - // Thus, to find the parent, we create a dummy StaticText and ask - // for its parent, and then remove it. - irr::gui::IGUIStaticText *dummy_text = guienv->addStaticText(L"", - rectangle, border, wordWrap, parent, id, - fillBackground); - parent = dummy_text->getParent(); - dummy_text->remove(); + { + return add(guienv, EnrichedString(text), rectangle, border, wordWrap, parent, + id, fillBackground); } - irr::gui::IGUIStaticText *result = new irr::gui::StaticText(text, border, - guienv, parent, id, rectangle, fillBackground); - result->setWordWrap(wordWrap); - result->drop(); - return result; - } + //! draws the element and its children + virtual void draw(); - static irr::gui::IGUIStaticText *add(irr::gui::IGUIEnvironment *guienv, - const wchar_t *text, const core::rect &rectangle, - bool border = false, bool wordWrap = true, - irr::gui::IGUIElement *parent = NULL, s32 id = -1, - bool fillBackground = false) - { - return add(guienv, EnrichedString(text), rectangle, border, wordWrap, - parent, id, fillBackground); - } + //! Sets another skin independent font. + virtual void setOverrideFont(IGUIFont* font=0); - //! draws the element and its children - virtual void draw(); + //! Gets the override font (if any) + virtual IGUIFont* getOverrideFont() const; - //! Sets another skin independent font. - virtual void setOverrideFont(IGUIFont *font = 0); + //! Get the font which is used right now for drawing + virtual IGUIFont* getActiveFont() const; - //! Gets the override font (if any) - virtual IGUIFont *getOverrideFont() const; + //! Sets another color for the text. + virtual void setOverrideColor(video::SColor color); - //! Get the font which is used right now for drawing - virtual IGUIFont *getActiveFont() const; + //! Sets another color for the background. + virtual void setBackgroundColor(video::SColor color); - //! Sets another color for the text. - virtual void setOverrideColor(video::SColor color); + //! Sets whether to draw the background + virtual void setDrawBackground(bool draw); - //! Sets another color for the background. - virtual void setBackgroundColor(video::SColor color); + //! Gets the background color + virtual video::SColor getBackgroundColor() const; - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw); + //! Checks if background drawing is enabled + virtual bool isDrawBackgroundEnabled() const; - //! Gets the background color - virtual video::SColor getBackgroundColor() const; + //! Sets whether to draw the border + virtual void setDrawBorder(bool draw); - //! Checks if background drawing is enabled - virtual bool isDrawBackgroundEnabled() const; + //! Checks if border drawing is enabled + virtual bool isDrawBorderEnabled() const; - //! Sets whether to draw the border - virtual void setDrawBorder(bool draw); + //! Sets alignment mode for text + virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); - //! Checks if border drawing is enabled - virtual bool isDrawBorderEnabled() const; + //! Gets the override color + #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 + virtual const video::SColor& getOverrideColor() const; + #else + virtual video::SColor getOverrideColor() const; + #endif - //! Sets alignment mode for text - virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); + //! Sets if the static text should use the overide color or the + //! color in the gui skin. + virtual void enableOverrideColor(bool enable); -//! Gets the override color -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 - virtual const video::SColor &getOverrideColor() const; -#else - virtual video::SColor getOverrideColor() const; -#endif + //! Checks if an override color is enabled + virtual bool isOverrideColorEnabled() const; - //! Sets if the static text should use the overide color or the - //! color in the gui skin. - virtual void enableOverrideColor(bool enable); + //! Set whether the text in this label should be clipped if it goes outside bounds + virtual void setTextRestrainedInside(bool restrainedInside); - //! Checks if an override color is enabled - virtual bool isOverrideColorEnabled() const; + //! Checks if the text in this label should be clipped if it goes outside bounds + virtual bool isTextRestrainedInside() const; - //! Set whether the text in this label should be clipped if it goes outside bounds - virtual void setTextRestrainedInside(bool restrainedInside); + //! Enables or disables word wrap for using the static text as + //! multiline text control. + virtual void setWordWrap(bool enable); - //! Checks if the text in this label should be clipped if it goes outside bounds - virtual bool isTextRestrainedInside() const; + //! Checks if word wrap is enabled + virtual bool isWordWrapEnabled() const; - //! Enables or disables word wrap for using the static text as - //! multiline text control. - virtual void setWordWrap(bool enable); + //! Sets the new caption of this element. + virtual void setText(const wchar_t* text); - //! Checks if word wrap is enabled - virtual bool isWordWrapEnabled() const; + //! Returns the height of the text in pixels when it is drawn. + virtual s32 getTextHeight() const; - //! Sets the new caption of this element. - virtual void setText(const wchar_t *text); + //! Returns the width of the current text, in the current font + virtual s32 getTextWidth() const; - //! Returns the height of the text in pixels when it is drawn. - virtual s32 getTextHeight() const; + //! Updates the absolute position, splits text if word wrap is enabled + virtual void updateAbsolutePosition(); - //! Returns the width of the current text, in the current font - virtual s32 getTextWidth() const; + //! Set whether the string should be interpreted as right-to-left (RTL) text + /** \note This component does not implement the Unicode bidi standard, the + text of the component should be already RTL if you call this. The + main difference when RTL is enabled is that the linebreaks for multiline + elements are performed starting from the end. + */ + virtual void setRightToLeft(bool rtl); - //! Updates the absolute position, splits text if word wrap is enabled - virtual void updateAbsolutePosition(); + //! Checks if the text should be interpreted as right-to-left text + virtual bool isRightToLeft() const; - //! Set whether the string should be interpreted as right-to-left (RTL) text - /** \note This component does not implement the Unicode bidi standard, the - text of the component should be already RTL if you call this. The - main difference when RTL is enabled is that the linebreaks for multiline - elements are performed starting from the end. - */ - virtual void setRightToLeft(bool rtl); + //! Writes attributes of the element. + virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; - //! Checks if the text should be interpreted as right-to-left text - virtual bool isRightToLeft() const; + //! Reads attributes of the element + virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); - //! Writes attributes of the element. - virtual void serializeAttributes(io::IAttributes *out, - io::SAttributeReadWriteOptions *options) const; + virtual bool hasType(EGUI_ELEMENT_TYPE t) const { + return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); + }; - //! Reads attributes of the element - virtual void deserializeAttributes( - io::IAttributes *in, io::SAttributeReadWriteOptions *options); + virtual bool hasType(EGUI_ELEMENT_TYPE t) { + return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); + }; - virtual bool hasType(EGUI_ELEMENT_TYPE t) const - { - return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); - }; + void setText(const EnrichedString &text); - virtual bool hasType(EGUI_ELEMENT_TYPE t) - { - return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT); - }; + private: - void setText(const EnrichedString &text); + //! Breaks the single text line. + void updateText(); -private: - //! Breaks the single text line. - void updateText(); + EGUI_ALIGNMENT HAlign, VAlign; + bool Border; + bool WordWrap; + bool Background; + bool RestrainTextInside; + bool RightToLeft; - EGUI_ALIGNMENT HAlign, VAlign; - bool Border; - bool WordWrap; - bool Background; - bool RestrainTextInside; - bool RightToLeft; + gui::IGUIFont* OverrideFont; + gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated. - gui::IGUIFont *OverrideFont; - gui::IGUIFont *LastBreakFont; // stored because: if skin changes, line break must - // be recalculated. + EnrichedString ColoredText; + std::vector BrokenText; + }; - EnrichedString ColoredText; - std::vector BrokenText; -}; } // end namespace gui } // end namespace irr -inline void setStaticText( - irr::gui::IGUIStaticText *static_text, const EnrichedString &text) +inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) { // dynamic_cast not possible due to some distributions shipped // without rtti support in irrlicht if (static_text->hasType(irr::gui::EGUIET_ENRICHED_STATIC_TEXT)) { - irr::gui::StaticText *stext = - static_cast(static_text); + irr::gui::StaticText* stext = static_cast(static_text); stext->setText(text); } else { static_text->setText(text.c_str()); @@ -240,14 +245,17 @@ namespace gui class StaticText { public: - static irr::gui::IGUIStaticText *add(irr::gui::IGUIEnvironment *guienv, - const EnrichedString &text, const core::rect &rectangle, - bool border = false, bool wordWrap = true, - irr::gui::IGUIElement *parent = NULL, s32 id = -1, - bool fillBackground = false) + 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); + return guienv->addStaticText(text.c_str(), rectangle, border, wordWrap, parent, id, fillBackground); } }; @@ -255,8 +263,7 @@ class StaticText } // end namespace irr -inline void setStaticText( - irr::gui::IGUIStaticText *static_text, const EnrichedString &text) +inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text) { static_text->setText(text.c_str()); } diff --git a/src/irrlichttypes.h b/src/irrlichttypes.h index a00b75adf..794776b26 100644 --- a/src/irrlichttypes.h +++ b/src/irrlichttypes.h @@ -27,54 +27,54 @@ with this program; if not, write to the Free Software Foundation, Inc., * regardless of the compiler. */ #ifndef _MSC_VER -#include +# include #endif #include using namespace irr; -namespace irr -{ +namespace irr { // Irrlicht 1.8+ defines 64bit unsigned symbol in irrTypes.h #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) #ifdef _MSC_VER -// Windows -typedef long long s64; -typedef unsigned long long u64; + // Windows + typedef long long s64; + typedef unsigned long long u64; #else -// Posix -typedef int64_t s64; -typedef uint64_t u64; + // Posix + typedef int64_t s64; + typedef uint64_t u64; #endif #endif #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 9) -namespace core -{ -template inline T roundingError(); +namespace core { + template + inline T roundingError(); -template <> inline s16 roundingError() -{ - return 0; -} + template <> + inline s16 roundingError() + { + return 0; + } } #endif } -#define S8_MIN (-0x7F - 1) +#define S8_MIN (-0x7F - 1) #define S16_MIN (-0x7FFF - 1) #define S32_MIN (-0x7FFFFFFF - 1) #define S64_MIN (-0x7FFFFFFFFFFFFFFF - 1) -#define S8_MAX 0x7F +#define S8_MAX 0x7F #define S16_MAX 0x7FFF #define S32_MAX 0x7FFFFFFF #define S64_MAX 0x7FFFFFFFFFFFFFFF -#define U8_MAX 0xFF +#define U8_MAX 0xFF #define U16_MAX 0xFFFF #define U32_MAX 0xFFFFFFFF #define U64_MAX 0xFFFFFFFFFFFFFFFF diff --git a/src/itemdef.cpp b/src/itemdef.cpp index ad4eafe81..8e0492827 100644 --- a/src/itemdef.cpp +++ b/src/itemdef.cpp @@ -52,9 +52,9 @@ ItemDefinition::ItemDefinition(const ItemDefinition &def) *this = def; } -ItemDefinition &ItemDefinition::operator=(const ItemDefinition &def) +ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def) { - if (this == &def) + if(this == &def) return *this; reset(); @@ -70,8 +70,10 @@ ItemDefinition &ItemDefinition::operator=(const ItemDefinition &def) stack_max = def.stack_max; usable = def.usable; liquids_pointable = def.liquids_pointable; - if (def.tool_capabilities) { - tool_capabilities = new ToolCapabilities(*def.tool_capabilities); + if(def.tool_capabilities) + { + tool_capabilities = new ToolCapabilities( + *def.tool_capabilities); } groups = def.groups; node_placement_prediction = def.node_placement_prediction; @@ -191,7 +193,7 @@ void ItemDefinition::deSerialize(std::istream &is) groups.clear(); u32 groups_size = readU16(is); - for (u32 i = 0; i < groups_size; i++) { + for(u32 i=0; i &values = m_clientcached.getValues(); + const std::vector &values = m_clientcached.getValues(); for (ClientCached *cc : values) { if (cc->wield_mesh.mesh) cc->wield_mesh.mesh->drop(); @@ -259,7 +265,7 @@ class CItemDefManager : public IWritableItemDefManager } m_item_definitions.clear(); } - virtual const ItemDefinition &get(const std::string &name_) const + virtual const ItemDefinition& get(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); @@ -297,11 +303,11 @@ class CItemDefManager : public IWritableItemDefManager } #ifndef SERVER public: - ClientCached *createClientCachedDirect( - const std::string &name, Client *client) const + ClientCached* createClientCachedDirect(const std::string &name, + Client *client) const { - infostream << "Lazily creating item texture and mesh for \"" << name - << "\"" << std::endl; + infostream<<"Lazily creating item texture and mesh for \"" + <getTextureSource(); @@ -335,7 +341,8 @@ class CItemDefManager : public IWritableItemDefManager return cc; } - ClientCached *getClientCached(const std::string &name, Client *client) const + ClientCached* getClientCached(const std::string &name, + Client *client) const { ClientCached *cc = NULL; m_clientcached.get(name, &cc); @@ -347,61 +354,62 @@ class CItemDefManager : public IWritableItemDefManager } // We're gonna ask the result to be put into here - static ResultQueue result_queue; + static ResultQueue result_queue; // Throw a request in m_get_clientcached_queue.add(name, 0, 0, &result_queue); try { - while (true) { + while(true) { // Wait result for a second - GetResult result = - result_queue.pop_front(1000); + GetResult + result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } - } catch (ItemNotFoundException &e) { + } catch(ItemNotFoundException &e) { errorstream << "Waiting for clientcached " << name - << " timed out." << std::endl; + << " timed out." << std::endl; return &m_dummy_clientcached; } } // Get item inventory texture - virtual video::ITexture *getInventoryTexture( - const std::string &name, Client *client) const + virtual video::ITexture* getInventoryTexture(const std::string &name, + Client *client) const { ClientCached *cc = getClientCached(name, client); - if (!cc) + if(!cc) return NULL; return cc->inventory_texture; } // Get item wield mesh - virtual ItemMesh *getWieldMesh(const std::string &name, Client *client) const + virtual ItemMesh* getWieldMesh(const std::string &name, + Client *client) const { ClientCached *cc = getClientCached(name, client); - if (!cc) + if(!cc) return NULL; return &(cc->wield_mesh); } // Get item palette - virtual Palette *getPalette(const std::string &name, Client *client) const + virtual Palette* getPalette(const std::string &name, + Client *client) const { ClientCached *cc = getClientCached(name, client); - if (!cc) + if(!cc) return NULL; return cc->palette; } - virtual video::SColor getItemstackColor( - const ItemStack &stack, Client *client) const + virtual video::SColor getItemstackColor(const ItemStack &stack, + Client *client) const { // Look for direct color definition const std::string &colorstring = stack.metadata.getString("color", 0); video::SColor directcolor; - if (!colorstring.empty() && - parseColorString(colorstring, directcolor, true)) + if (!colorstring.empty() && parseColorString(colorstring, directcolor, true)) return directcolor; // See if there is a palette Palette *palette = getPalette(stack.name, client); @@ -415,16 +423,14 @@ class CItemDefManager : public IWritableItemDefManager void applyTextureOverrides(const std::vector &overrides) { infostream << "ItemDefManager::applyTextureOverrides(): Applying " - "overrides to textures" - << std::endl; + "overrides to textures" << std::endl; - for (const TextureOverride &texture_override : overrides) { - if (m_item_definitions.find(texture_override.id) == - m_item_definitions.end()) { + for (const TextureOverride& texture_override : overrides) { + if (m_item_definitions.find(texture_override.id) == m_item_definitions.end()) { continue; // Ignore unknown item } - ItemDefinition *itemdef = m_item_definitions[texture_override.id]; + ItemDefinition* itemdef = m_item_definitions[texture_override.id]; if (texture_override.hasTarget(OverrideTarget::INVENTORY)) itemdef->inventory_image = texture_override.texture; @@ -435,7 +441,8 @@ class CItemDefManager : public IWritableItemDefManager } void clear() { - for (auto &i : m_item_definitions) { + for (auto &i : m_item_definitions) + { delete i.second; } m_item_definitions.clear(); @@ -448,23 +455,23 @@ class CItemDefManager : public IWritableItemDefManager // "air" is the air node // "ignore" is the ignore node - ItemDefinition *hand_def = new ItemDefinition; + ItemDefinition* hand_def = new ItemDefinition; hand_def->name = ""; hand_def->wield_image = "wieldhand.png"; hand_def->tool_capabilities = new ToolCapabilities; m_item_definitions.insert(std::make_pair("", hand_def)); - ItemDefinition *unknown_def = new ItemDefinition; + ItemDefinition* unknown_def = new ItemDefinition; unknown_def->type = ITEM_NODE; unknown_def->name = "unknown"; m_item_definitions.insert(std::make_pair("unknown", unknown_def)); - ItemDefinition *air_def = new ItemDefinition; + ItemDefinition* air_def = new ItemDefinition; air_def->type = ITEM_NODE; air_def->name = "air"; m_item_definitions.insert(std::make_pair("air", air_def)); - ItemDefinition *ignore_def = new ItemDefinition; + ItemDefinition* ignore_def = new ItemDefinition; ignore_def->type = ITEM_NODE; ignore_def->name = "ignore"; m_item_definitions.insert(std::make_pair("ignore", ignore_def)); @@ -474,33 +481,32 @@ class CItemDefManager : public IWritableItemDefManager TRACESTREAM(<< "ItemDefManager: registering " << def.name << std::endl); // Ensure that the "" item (the hand) always has ToolCapabilities if (def.name.empty()) - FATAL_ERROR_IF(!def.tool_capabilities, - "Hand does not have ToolCapabilities"); + FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities"); - if (m_item_definitions.count(def.name) == 0) + if(m_item_definitions.count(def.name) == 0) m_item_definitions[def.name] = new ItemDefinition(def); else *(m_item_definitions[def.name]) = def; // Remove conflicting alias if it exists bool alias_removed = (m_aliases.erase(def.name) != 0); - if (alias_removed) - infostream << "ItemDefManager: erased alias " << def.name - << " because item was defined" << std::endl; + if(alias_removed) + infostream<<"ItemDefManager: erased alias "< " - << convert_to << std::endl); + TRACESTREAM(<< "ItemDefManager: setting alias " << name + << " -> " << convert_to << std::endl); m_aliases[name] = convert_to; } } @@ -531,20 +537,21 @@ class CItemDefManager : public IWritableItemDefManager clear(); // Deserialize int version = readU8(is); - if (version != 0) + if(version != 0) throw SerializationError("unsupported ItemDefManager version"); u16 count = readU16(is); - for (u16 i = 0; i < count; i++) { + for(u16 i=0; i request = - m_get_clientcached_queue.pop(); - - m_get_clientcached_queue.pushResult( - request, createClientCachedDirect(request.key, - (Client *)gamedef)); + //NOTE this is only thread safe for ONE consumer thread! + while(!m_get_clientcached_queue.empty()) + { + GetRequest + request = m_get_clientcached_queue.pop(); + + m_get_clientcached_queue.pushResult(request, + createClientCachedDirect(request.key, (Client *)gamedef)); } #endif } - private: // Key is name - std::map m_item_definitions; + std::map m_item_definitions; // Aliases StringMap m_aliases; #ifndef SERVER @@ -576,14 +582,13 @@ class CItemDefManager : public IWritableItemDefManager // A reference to this can be returned when nothing is found, to avoid NULLs mutable ClientCached m_dummy_clientcached; // Cached textures and meshes - mutable MutexedMap m_clientcached; + mutable MutexedMap m_clientcached; // Queued clientcached fetches (to be processed by the main thread) - mutable RequestQueue - m_get_clientcached_queue; + mutable RequestQueue m_get_clientcached_queue; #endif }; -IWritableItemDefManager *createItemDefManager() +IWritableItemDefManager* createItemDefManager() { return new CItemDefManager(); } diff --git a/src/itemdef.h b/src/itemdef.h index e6170d150..f47e6cbe7 100644 --- a/src/itemdef.h +++ b/src/itemdef.h @@ -54,7 +54,7 @@ struct ItemDefinition Basic item properties */ ItemType type; - std::string name; // "" = hand + std::string name; // "" = hand std::string description; // Shown in tooltip. /* @@ -64,9 +64,8 @@ struct ItemDefinition std::string inventory_overlay; // Overlay of inventory_image. std::string wield_image; // If empty, inventory_image or mesh (only nodes) is used std::string wield_overlay; // Overlay of wield_image. - std::string palette_image; // If specified, the item will be colorized based on - // this - video::SColor color; // The fallback color of the node. + std::string palette_image; // If specified, the item will be colorized based on this + video::SColor color; // The fallback color of the node. v3f wield_scale; /* @@ -92,12 +91,11 @@ struct ItemDefinition */ ItemDefinition(); ItemDefinition(const ItemDefinition &def); - ItemDefinition &operator=(const ItemDefinition &def); + ItemDefinition& operator=(const ItemDefinition &def); ~ItemDefinition(); void reset(); void serialize(std::ostream &os, u16 protocol_version) const; void deSerialize(std::istream &is); - private: void resetInitial(); }; @@ -110,28 +108,30 @@ class IItemDefManager virtual ~IItemDefManager() = default; // Get item definition - virtual const ItemDefinition &get(const std::string &name) const = 0; + virtual const ItemDefinition& get(const std::string &name) const=0; // Get alias definition - virtual const std::string &getAlias(const std::string &name) const = 0; + virtual const std::string &getAlias(const std::string &name) const=0; // Get set of all defined item names and aliases - virtual void getAll(std::set &result) const = 0; + virtual void getAll(std::set &result) const=0; // Check if item is known - virtual bool isKnown(const std::string &name) const = 0; + virtual bool isKnown(const std::string &name) const=0; #ifndef SERVER // Get item inventory texture - virtual video::ITexture *getInventoryTexture( - const std::string &name, Client *client) const = 0; + virtual video::ITexture* getInventoryTexture(const std::string &name, + Client *client) const=0; // Get item wield mesh - virtual ItemMesh *getWieldMesh(const std::string &name, Client *client) const = 0; + virtual ItemMesh* getWieldMesh(const std::string &name, + Client *client) const=0; // Get item palette - virtual Palette *getPalette(const std::string &name, Client *client) const = 0; + virtual Palette* getPalette(const std::string &name, + Client *client) const = 0; // Returns the base color of an item stack: the color of all // tiles that do not define their own color. - virtual video::SColor getItemstackColor( - const ItemStack &stack, Client *client) const = 0; + virtual video::SColor getItemstackColor(const ItemStack &stack, + Client *client) const = 0; #endif - virtual void serialize(std::ostream &os, u16 protocol_version) = 0; + virtual void serialize(std::ostream &os, u16 protocol_version)=0; }; class IWritableItemDefManager : public IItemDefManager @@ -142,43 +142,43 @@ class IWritableItemDefManager : public IItemDefManager virtual ~IWritableItemDefManager() = default; // Get item definition - virtual const ItemDefinition &get(const std::string &name) const = 0; + virtual const ItemDefinition& get(const std::string &name) const=0; // Get alias definition - virtual const std::string &getAlias(const std::string &name) const = 0; + virtual const std::string &getAlias(const std::string &name) const=0; // Get set of all defined item names and aliases - virtual void getAll(std::set &result) const = 0; + virtual void getAll(std::set &result) const=0; // Check if item is known - virtual bool isKnown(const std::string &name) const = 0; + virtual bool isKnown(const std::string &name) const=0; #ifndef SERVER // Get item inventory texture - virtual video::ITexture *getInventoryTexture( - const std::string &name, Client *client) const = 0; + virtual video::ITexture* getInventoryTexture(const std::string &name, + Client *client) const=0; // Get item wield mesh - virtual ItemMesh *getWieldMesh(const std::string &name, Client *client) const = 0; + virtual ItemMesh* getWieldMesh(const std::string &name, + Client *client) const=0; #endif // Replace the textures of registered nodes with the ones specified in // the texture pack's override.txt files - virtual void applyTextureOverrides( - const std::vector &overrides) = 0; + virtual void applyTextureOverrides(const std::vector &overrides)=0; // Remove all registered item and node definitions and aliases // Then re-add the builtin item definitions - virtual void clear() = 0; + virtual void clear()=0; // Register item definition - virtual void registerItem(const ItemDefinition &def) = 0; - virtual void unregisterItem(const std::string &name) = 0; + virtual void registerItem(const ItemDefinition &def)=0; + virtual void unregisterItem(const std::string &name)=0; // Set an alias so that items named will load as . // Alias is not set if has already been defined. // Alias will be removed if is defined at a later point of time. - virtual void registerAlias( - const std::string &name, const std::string &convert_to) = 0; + virtual void registerAlias(const std::string &name, + const std::string &convert_to)=0; - virtual void serialize(std::ostream &os, u16 protocol_version) = 0; - virtual void deSerialize(std::istream &is) = 0; + virtual void serialize(std::ostream &os, u16 protocol_version)=0; + virtual void deSerialize(std::istream &is)=0; // Do stuff asked by threads that can only be done in the main thread - virtual void processQueue(IGameDef *gamedef) = 0; + virtual void processQueue(IGameDef *gamedef)=0; }; -IWritableItemDefManager *createItemDefManager(); +IWritableItemDefManager* createItemDefManager(); diff --git a/src/itemstackmetadata.cpp b/src/itemstackmetadata.cpp index 66dd71947..4aa1a0903 100644 --- a/src/itemstackmetadata.cpp +++ b/src/itemstackmetadata.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "itemstackmetadata.h" #include "util/serialize.h" #include "util/strfnd.h" @@ -50,8 +51,8 @@ void ItemStackMetadata::serialize(std::ostream &os) const os2 << DESERIALIZE_START; for (const auto &stringvar : m_stringvars) { if (!stringvar.first.empty() || !stringvar.second.empty()) - os2 << stringvar.first << DESERIALIZE_KV_DELIM << stringvar.second - << DESERIALIZE_PAIR_DELIM; + os2 << stringvar.first << DESERIALIZE_KV_DELIM + << stringvar.second << DESERIALIZE_PAIR_DELIM; } os << serializeJsonStringIfNeeded(os2.str()); } @@ -68,7 +69,7 @@ void ItemStackMetadata::deSerialize(std::istream &is) fnd.to(1); while (!fnd.at_end()) { std::string name = fnd.next(DESERIALIZE_KV_DELIM_STR); - std::string var = fnd.next(DESERIALIZE_PAIR_DELIM_STR); + std::string var = fnd.next(DESERIALIZE_PAIR_DELIM_STR); m_stringvars[name] = var; } } else { diff --git a/src/light.cpp b/src/light.cpp index af8666e5d..8196fedff 100644 --- a/src/light.cpp +++ b/src/light.cpp @@ -29,15 +29,16 @@ static u8 light_LUT[LIGHT_SUN + 1]; // The const ref to light_LUT is what is actually used in the code const u8 *light_decode_table = light_LUT; -struct LightingParams -{ - float a, b, c; // Lighting curve polynomial coefficients + +struct LightingParams { + float a, b, c; // Lighting curve polynomial coefficients float boost, center, sigma; // Lighting curve parametric boost - float gamma; // Lighting curve gamma correction + float gamma; // Lighting curve gamma correction }; static LightingParams params; + float decode_light_f(float x) { if (x >= 1.0f) // x is often 1.0f @@ -45,7 +46,7 @@ float decode_light_f(float x) x = std::fmax(x, 0.0f); float brightness = ((params.a * x + params.b) * x + params.c) * x; brightness += params.boost * - std::exp(-0.5f * sqr((x - params.center) / params.sigma)); + std::exp(-0.5f * sqr((x - params.center) / params.sigma)); if (brightness <= 0.0f) // May happen if parameters are extreme return 0.0f; if (brightness >= 1.0f) @@ -53,26 +54,25 @@ float decode_light_f(float x) return powf(brightness, 1.0f / params.gamma); } + // Initialize or update the light value tables using the specified gamma void set_light_table(float gamma) { - // Lighting curve bounding gradients +// Lighting curve bounding gradients const float alpha = rangelim(g_settings->getFloat("lighting_alpha"), 0.0f, 3.0f); - const float beta = rangelim(g_settings->getFloat("lighting_beta"), 0.0f, 3.0f); - // Lighting curve polynomial coefficients + const float beta = rangelim(g_settings->getFloat("lighting_beta"), 0.0f, 3.0f); +// Lighting curve polynomial coefficients params.a = alpha + beta - 2.0f; params.b = 3.0f - 2.0f * alpha - beta; params.c = alpha; - // Lighting curve parametric boost +// Lighting curve parametric boost params.boost = rangelim(g_settings->getFloat("lighting_boost"), 0.0f, 0.4f); - params.center = rangelim( - g_settings->getFloat("lighting_boost_center"), 0.0f, 1.0f); - params.sigma = rangelim( - g_settings->getFloat("lighting_boost_spread"), 0.0f, 0.4f); - // Lighting curve gamma correction + params.center = rangelim(g_settings->getFloat("lighting_boost_center"), 0.0f, 1.0f); + params.sigma = rangelim(g_settings->getFloat("lighting_boost_spread"), 0.0f, 0.4f); +// Lighting curve gamma correction params.gamma = rangelim(gamma, 0.33f, 3.0f); - // Boundary values should be fixed +// Boundary values should be fixed light_LUT[0] = 0; light_LUT[LIGHT_SUN] = 255; diff --git a/src/log.cpp b/src/log.cpp index 0fd4dc01c..54442c39b 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -37,10 +37,11 @@ with this program; if not, write to the Free Software Foundation, Inc., const int BUFFER_LENGTH = 256; -class StringBuffer : public std::streambuf -{ +class StringBuffer : public std::streambuf { public: - StringBuffer() { buffer_index = 0; } + StringBuffer() { + buffer_index = 0; + } int overflow(int c); virtual void flush(const std::string &buf) = 0; @@ -52,10 +53,13 @@ class StringBuffer : public std::streambuf int buffer_index; }; -class LogBuffer : public StringBuffer -{ + +class LogBuffer : public StringBuffer { public: - LogBuffer(Logger &logger, LogLevel lev) : logger(logger), level(lev) {} + LogBuffer(Logger &logger, LogLevel lev) : + logger(logger), + level(lev) + {} void flush(const std::string &buffer); @@ -64,8 +68,8 @@ class LogBuffer : public StringBuffer LogLevel level; }; -class RawLogBuffer : public StringBuffer -{ + +class RawLogBuffer : public StringBuffer { public: void flush(const std::string &buffer); }; @@ -115,28 +119,33 @@ std::ostream verbosestream(&verbose_buf); #ifdef __ANDROID__ static unsigned int g_level_to_android[] = { - ANDROID_LOG_INFO, // LL_NONE - // ANDROID_LOG_FATAL, - ANDROID_LOG_ERROR, // LL_ERROR - ANDROID_LOG_WARN, // LL_WARNING - ANDROID_LOG_WARN, // LL_ACTION - // ANDROID_LOG_INFO, - ANDROID_LOG_DEBUG, // LL_INFO - ANDROID_LOG_VERBOSE, // LL_VERBOSE + ANDROID_LOG_INFO, // LL_NONE + //ANDROID_LOG_FATAL, + ANDROID_LOG_ERROR, // LL_ERROR + ANDROID_LOG_WARN, // LL_WARNING + ANDROID_LOG_WARN, // LL_ACTION + //ANDROID_LOG_INFO, + ANDROID_LOG_DEBUG, // LL_INFO + ANDROID_LOG_VERBOSE, // LL_VERBOSE }; -class AndroidSystemLogOutput : public ICombinedLogOutput -{ -public: - AndroidSystemLogOutput() { g_logger.addOutput(this); } - ~AndroidSystemLogOutput() { g_logger.removeOutput(this); } - void logRaw(LogLevel lev, const std::string &line) - { - STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX, +class AndroidSystemLogOutput : public ICombinedLogOutput { + public: + AndroidSystemLogOutput() + { + g_logger.addOutput(this); + } + ~AndroidSystemLogOutput() + { + g_logger.removeOutput(this); + } + void logRaw(LogLevel lev, const std::string &line) + { + STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX, mismatch_between_android_and_internal_loglevels); - __android_log_print(g_level_to_android[lev], PROJECT_NAME_C, "%s", - line.c_str()); - } + __android_log_print(g_level_to_android[lev], + PROJECT_NAME_C, "%s", line.c_str()); + } }; AndroidSystemLogOutput g_android_log_output; @@ -145,6 +154,7 @@ AndroidSystemLogOutput g_android_log_output; /////////////////////////////////////////////////////////////////////////////// + //// //// Logger //// @@ -229,15 +239,16 @@ void Logger::deregisterThread() const std::string Logger::getLevelLabel(LogLevel lev) { static const std::string names[] = { - "", - "ERROR", - "WARNING", - "ACTION", - "INFO", - "VERBOSE", + "", + "ERROR", + "WARNING", + "ACTION", + "INFO", + "VERBOSE", }; assert(lev < LL_MAX && lev >= 0); - STATIC_ASSERT(ARRLEN(names) == LL_MAX, mismatch_between_loglevel_names_and_enum); + STATIC_ASSERT(ARRLEN(names) == LL_MAX, + mismatch_between_loglevel_names_and_enum); return names[lev]; } @@ -287,14 +298,15 @@ void Logger::logToOutputsRaw(LogLevel lev, const std::string &line) } void Logger::logToOutputs(LogLevel lev, const std::string &combined, - const std::string &time, const std::string &thread_name, - const std::string &payload_text) + const std::string &time, const std::string &thread_name, + const std::string &payload_text) { MutexAutoLock lock(m_mutex); for (size_t i = 0; i != m_outputs[lev].size(); i++) m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text); } + //// //// *LogOutput methods //// @@ -311,28 +323,26 @@ void FileLogOutput::setFile(const std::string &filename, s64 file_size_max) if (is_too_large) { std::string filename_secondary = filename + ".1"; - actionstream << "The log file grew too big; it is moved to " - << filename_secondary << std::endl; + actionstream << "The log file grew too big; it is moved to " << + filename_secondary << std::endl; remove(filename_secondary.c_str()); rename(filename.c_str(), filename_secondary.c_str()); } m_stream.open(filename, std::ios::app | std::ios::ate); if (!m_stream.good()) - throw FileNotGoodException("Failed to open log file " + filename + ": " + - strerror(errno)); + throw FileNotGoodException("Failed to open log file " + + filename + ": " + strerror(errno)); m_stream << "\n\n" - "-------------" - << std::endl - << " Separator" << std::endl - << "-------------\n" - << std::endl; + "-------------" << std::endl << + " Separator" << std::endl << + "-------------\n" << std::endl; } void StreamLogOutput::logRaw(LogLevel lev, const std::string &line) { bool colored_message = (Logger::color_mode == LOG_COLOR_ALWAYS) || - (Logger::color_mode == LOG_COLOR_AUTO && is_tty); + (Logger::color_mode == LOG_COLOR_AUTO && is_tty); if (colored_message) { switch (lev) { case LL_ERROR: @@ -371,8 +381,7 @@ void LogOutputBuffer::updateLogLevel() LogLevel log_level = Logger::stringToLevel(conf_loglev); if (log_level == LL_MAX) { warningstream << "Supplied unrecognized chat_log_level; " - "showing none." - << std::endl; + "showing none." << std::endl; log_level = LL_NONE; } @@ -398,8 +407,7 @@ void LogOutputBuffer::logRaw(LogLevel lev, const std::string &line) case LL_VERBOSE: // dark grey color = "\x1b(c@#888)"; break; - default: - break; + default: break; } } @@ -416,6 +424,7 @@ int StringBuffer::overflow(int c) return c; } + std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n) { for (int i = 0; i < n; ++i) @@ -438,6 +447,7 @@ void StringBuffer::push_back(char c) } } + void LogBuffer::flush(const std::string &buffer) { logger.log(level, buffer); diff --git a/src/log.h b/src/log.h index 9fe5aa291..856d3479b 100644 --- a/src/log.h +++ b/src/log.h @@ -25,26 +25,24 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include -#if !defined(_WIN32) // POSIX -#include +#if !defined(_WIN32) // POSIX + #include #endif #include "irrlichttypes.h" class ILogOutput; -enum LogLevel -{ +enum LogLevel { LL_NONE, // Special level that is always printed LL_ERROR, LL_WARNING, - LL_ACTION, // In-game actions + LL_ACTION, // In-game actions LL_INFO, LL_VERBOSE, LL_MAX, }; -enum LogColor -{ +enum LogColor { LOG_COLOR_NEVER, LOG_COLOR_ALWAYS, LOG_COLOR_AUTO, @@ -53,8 +51,7 @@ enum LogColor typedef u8 LogLevelMask; #define LOGLEVEL_TO_MASKLEVEL(x) (1 << x) -class Logger -{ +class Logger { public: void addOutput(ILogOutput *out); void addOutput(ILogOutput *out, LogLevel lev); @@ -80,8 +77,9 @@ class Logger private: void logToOutputsRaw(LogLevel, const std::string &line); - void logToOutputs(LogLevel, const std::string &combined, const std::string &time, - const std::string &thread_name, const std::string &payload_text); + void logToOutputs(LogLevel, const std::string &combined, + const std::string &time, const std::string &thread_name, + const std::string &payload_text); const std::string getThreadName(); @@ -96,29 +94,28 @@ class Logger bool m_trace_enabled; }; -class ILogOutput -{ +class ILogOutput { public: virtual void logRaw(LogLevel, const std::string &line) = 0; - virtual void log(LogLevel, const std::string &combined, const std::string &time, - const std::string &thread_name, - const std::string &payload_text) = 0; + virtual void log(LogLevel, const std::string &combined, + const std::string &time, const std::string &thread_name, + const std::string &payload_text) = 0; }; -class ICombinedLogOutput : public ILogOutput -{ +class ICombinedLogOutput : public ILogOutput { public: - void log(LogLevel lev, const std::string &combined, const std::string &time, - const std::string &thread_name, const std::string &payload_text) + void log(LogLevel lev, const std::string &combined, + const std::string &time, const std::string &thread_name, + const std::string &payload_text) { logRaw(lev, combined); } }; -class StreamLogOutput : public ICombinedLogOutput -{ +class StreamLogOutput : public ICombinedLogOutput { public: - StreamLogOutput(std::ostream &stream) : m_stream(stream) + StreamLogOutput(std::ostream &stream) : + m_stream(stream) { #if !defined(_WIN32) is_tty = isatty(fileno(stdout)); @@ -134,8 +131,7 @@ class StreamLogOutput : public ICombinedLogOutput bool is_tty; }; -class FileLogOutput : public ICombinedLogOutput -{ +class FileLogOutput : public ICombinedLogOutput { public: void setFile(const std::string &filename, s64 file_size_max); @@ -148,20 +144,32 @@ class FileLogOutput : public ICombinedLogOutput std::ofstream m_stream; }; -class LogOutputBuffer : public ICombinedLogOutput -{ +class LogOutputBuffer : public ICombinedLogOutput { public: - LogOutputBuffer(Logger &logger) : m_logger(logger) { updateLogLevel(); }; + LogOutputBuffer(Logger &logger) : + m_logger(logger) + { + updateLogLevel(); + }; - virtual ~LogOutputBuffer() { m_logger.removeOutput(this); } + virtual ~LogOutputBuffer() + { + m_logger.removeOutput(this); + } void updateLogLevel(); void logRaw(LogLevel lev, const std::string &line); - void clear() { m_buffer = std::queue(); } + void clear() + { + m_buffer = std::queue(); + } - bool empty() const { return m_buffer.empty(); } + bool empty() const + { + return m_buffer.empty(); + } std::string get() { @@ -177,6 +185,7 @@ class LogOutputBuffer : public ICombinedLogOutput Logger &m_logger; }; + extern StreamLogOutput stdout_output; extern StreamLogOutput stderr_output; extern std::ostream null_stream; @@ -203,12 +212,11 @@ extern std::ostream infostream; extern std::ostream verbosestream; extern std::ostream dstream; -#define TRACEDO(x) \ - do { \ - if (g_logger.getTraceEnabled()) { \ - x; \ - } \ - } while (0) +#define TRACEDO(x) do { \ + if (g_logger.getTraceEnabled()) { \ + x; \ + } \ +} while (0) #define TRACESTREAM(x) TRACEDO(verbosestream x) @@ -217,5 +225,5 @@ extern std::ostream dstream; #define dout_server (*dout_server_ptr) #ifndef SERVER -#define dout_client (*dout_client_ptr) + #define dout_client (*dout_client_ptr) #endif diff --git a/src/main.cpp b/src/main.cpp index d49cda59d..af6d307dc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -39,7 +39,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "porting.h" #include "network/socket.h" #if USE_CURSES -#include "terminal_chat_console.h" + #include "terminal_chat_console.h" #endif #ifndef SERVER #include "gui/guiMainMenu.h" @@ -49,12 +49,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #endif #ifdef HAVE_TOUCHSCREENGUI -#include "gui/touchscreengui.h" + #include "gui/touchscreengui.h" #endif -#if !defined(SERVER) && (IRRLICHT_VERSION_MAJOR == 1) && \ - (IRRLICHT_VERSION_MINOR == 8) && (IRRLICHT_VERSION_REVISION == 2) -#error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3" +#if !defined(SERVER) && \ + (IRRLICHT_VERSION_MAJOR == 1) && \ + (IRRLICHT_VERSION_MINOR == 8) && \ + (IRRLICHT_VERSION_REVISION == 2) + #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3" #endif #define DEBUGFILE "debug.txt" @@ -72,8 +74,8 @@ static void set_allowed_options(OptionList *allowed_options); static void print_help(const OptionList &allowed_options); static void print_allowed_options(const OptionList &allowed_options); static void print_version(); -static void print_worldspecs(const std::vector &worldspecs, std::ostream &os, - bool print_name = true, bool print_path = true); +static void print_worldspecs(const std::vector &worldspecs, + std::ostream &os, bool print_name = true, bool print_path = true); static void print_modified_quicktune_values(); static void list_game_ids(); @@ -103,6 +105,7 @@ static bool migrate_map_database(const GameParams &game_params, const Settings & /**********************************************************************/ + FileLogOutput file_log_output; static OptionList allowed_options; @@ -117,7 +120,9 @@ int main(int argc, char *argv[]) Settings cmd_args; bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args); - if (!cmd_args_ok || cmd_args.getFlag("help") || cmd_args.exists("nonopt1")) { + if (!cmd_args_ok + || cmd_args.getFlag("help") + || cmd_args.exists("nonopt1")) { porting::attachOrCreateConsole(); print_help(allowed_options); return cmd_args_ok ? 0 : 1; @@ -167,7 +172,7 @@ int main(int argc, char *argv[]) list_worlds(true, true); } else { errorstream << "Invalid --worldlist value: " - << cmd_args.get("worldlist") << std::endl; + << cmd_args.get("worldlist") << std::endl; return 1; } return 0; @@ -186,9 +191,8 @@ int main(int argc, char *argv[]) return run_tests(); #else errorstream << "Unittest support is not enabled in this binary. " - << "If you want to enable it, compile project with " - "BUILD_UNITTESTS=1 flag." - << std::endl; + << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag." + << std::endl; #endif } #endif @@ -233,10 +237,12 @@ int main(int argc, char *argv[]) return retval; } + /***************************************************************************** * Startup / Init *****************************************************************************/ + static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args) { set_allowed_options(&allowed_options); @@ -248,98 +254,71 @@ static void set_allowed_options(OptionList *allowed_options) { allowed_options->clear(); - allowed_options->insert(std::make_pair( - "help", ValueSpec(VALUETYPE_FLAG, _("Show allowed options")))); - allowed_options->insert(std::make_pair("version", - ValueSpec(VALUETYPE_FLAG, _("Show version information")))); - allowed_options->insert(std::make_pair("config", - ValueSpec(VALUETYPE_STRING, - _("Load configuration from specified file")))); - allowed_options->insert(std::make_pair("port", - ValueSpec(VALUETYPE_STRING, _("Set network port (UDP)")))); - allowed_options->insert(std::make_pair("run-unittests", - ValueSpec(VALUETYPE_FLAG, _("Run the unit tests and exit")))); - allowed_options->insert(std::make_pair("map-dir", - ValueSpec(VALUETYPE_STRING, _("Same as --world (deprecated)")))); - allowed_options->insert(std::make_pair( - "world", ValueSpec(VALUETYPE_STRING, - _("Set world path (implies local game " - "if used with option --go)")))); - allowed_options->insert(std::make_pair("worldname", - ValueSpec(VALUETYPE_STRING, - _("Set world by name (implies local game if used " - "with option --go)")))); - allowed_options->insert(std::make_pair("worldlist", - ValueSpec(VALUETYPE_STRING, - _("Get list of worlds ('path' lists paths, " - "'name' lists names, 'both' lists both)")))); - allowed_options->insert(std::make_pair("quiet", - ValueSpec(VALUETYPE_FLAG, _("Print to console errors only")))); - allowed_options->insert(std::make_pair( - "color", ValueSpec(VALUETYPE_STRING, - _("Coloured logs ('always', 'never' or " - "'auto'), defaults to 'auto'")))); - allowed_options->insert(std::make_pair( - "info", ValueSpec(VALUETYPE_FLAG, - _("Print more information to console")))); - allowed_options->insert(std::make_pair("verbose", - ValueSpec(VALUETYPE_FLAG, - _("Print even more information to console")))); - allowed_options->insert(std::make_pair("trace", - ValueSpec(VALUETYPE_FLAG, _("Print enormous amounts of " - "information to log and console")))); - allowed_options->insert(std::make_pair("logfile", - ValueSpec(VALUETYPE_STRING, - _("Set logfile path ('' = no logging)")))); - allowed_options->insert(std::make_pair("gameid", - ValueSpec(VALUETYPE_STRING, _("Set gameid (\"--gameid list\" " - "prints available ones)")))); - allowed_options->insert(std::make_pair("migrate", - ValueSpec(VALUETYPE_STRING, - _("Migrate from current map backend to another " - "(Only works when using minetestserver or with " - "--server)")))); - allowed_options->insert(std::make_pair("migrate-players", - ValueSpec(VALUETYPE_STRING, - _("Migrate from current players backend to " - "another (Only works when using minetestserver " - "or with --server)")))); - allowed_options->insert(std::make_pair("migrate-auth", - ValueSpec(VALUETYPE_STRING, - _("Migrate from current auth backend to another " - "(Only works when using minetestserver or with " - "--server)")))); - allowed_options->insert(std::make_pair("terminal", - ValueSpec(VALUETYPE_FLAG, - _("Feature an interactive terminal (Only works " - "when using minetestserver or with " - "--server)")))); + allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG, + _("Show allowed options")))); + allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG, + _("Show version information")))); + allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING, + _("Load configuration from specified file")))); + allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING, + _("Set network port (UDP)")))); + allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG, + _("Run the unit tests and exit")))); + allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING, + _("Same as --world (deprecated)")))); + allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING, + _("Set world path (implies local game if used with option --go)")))); + allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING, + _("Set world by name (implies local game if used with option --go)")))); + allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING, + _("Get list of worlds ('path' lists paths, " + "'name' lists names, 'both' lists both)")))); + allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG, + _("Print to console errors only")))); + allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING, + _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'" + )))); + allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG, + _("Print more information to console")))); + allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG, + _("Print even more information to console")))); + allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG, + _("Print enormous amounts of information to log and console")))); + allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING, + _("Set logfile path ('' = no logging)")))); + allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING, + _("Set gameid (\"--gameid list\" prints available ones)")))); + allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING, + _("Migrate from current map backend to another (Only works when using minetestserver or with --server)")))); + allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING, + _("Migrate from current players backend to another (Only works when using minetestserver or with --server)")))); + allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING, + _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)")))); + allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG, + _("Feature an interactive terminal (Only works when using minetestserver or with --server)")))); #ifndef SERVER - allowed_options->insert(std::make_pair("videomodes", - ValueSpec(VALUETYPE_FLAG, _("Show available video modes")))); - allowed_options->insert(std::make_pair( - "speedtests", ValueSpec(VALUETYPE_FLAG, _("Run speed tests")))); - allowed_options->insert(std::make_pair("address", - ValueSpec(VALUETYPE_STRING, - _("Address to connect to. ('' = local game)")))); - allowed_options->insert(std::make_pair("random-input", - ValueSpec(VALUETYPE_FLAG, - _("Enable random user input, for testing")))); - allowed_options->insert(std::make_pair( - "server", ValueSpec(VALUETYPE_FLAG, _("Run dedicated server")))); - allowed_options->insert(std::make_pair( - "name", ValueSpec(VALUETYPE_STRING, _("Set player name")))); - allowed_options->insert(std::make_pair( - "password", ValueSpec(VALUETYPE_STRING, _("Set password")))); - allowed_options->insert(std::make_pair("password-file", - ValueSpec(VALUETYPE_STRING, - _("Set password from contents of file")))); - allowed_options->insert(std::make_pair( - "go", ValueSpec(VALUETYPE_FLAG, _("Disable main menu")))); - allowed_options->insert(std::make_pair("console", - ValueSpec(VALUETYPE_FLAG, - _("Starts with the console (Windows only)")))); + allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG, + _("Show available video modes")))); + allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG, + _("Run speed tests")))); + allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING, + _("Address to connect to. ('' = local game)")))); + allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG, + _("Enable random user input, for testing")))); + allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG, + _("Run dedicated server")))); + allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING, + _("Set player name")))); + allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING, + _("Set password")))); + allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING, + _("Set password from contents of file")))); + allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG, + _("Disable main menu")))); + allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG, + _("Starts with the console (Windows only)")))); #endif + } static void print_help(const OptionList &allowed_options) @@ -367,8 +346,8 @@ static void print_allowed_options(const OptionList &allowed_options) static void print_version() { - std::cout << PROJECT_NAME_C " " << g_version_hash << " (" - << porting::getPlatformName() << ")" << std::endl; + std::cout << PROJECT_NAME_C " " << g_version_hash + << " (" << porting::getPlatformName() << ")" << std::endl; #ifndef SERVER std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl; #endif @@ -379,7 +358,7 @@ static void list_game_ids() { std::set gameids = getAvailableGameIds(); for (const std::string &gameid : gameids) - std::cout << gameid << std::endl; + std::cout << gameid < &worldspecs, std::ostream &os, - bool print_name, bool print_path) +static void print_worldspecs(const std::vector &worldspecs, + std::ostream &os, bool print_name, bool print_path) { for (const WorldSpec &worldspec : worldspecs) { std::string name = worldspec.name; @@ -458,7 +437,7 @@ static bool setup_log_params(const Settings &cmd_args) if (cmd_args.getFlag("trace")) { dstream << _("Enabling trace level debug output") << std::endl; g_logger.setTraceEnabled(true); - dout_con_ptr = &verbosestream; // This is somewhat old + dout_con_ptr = &verbosestream; // This is somewhat old socket_enable_debug_output = true; // Sockets doesn't use log.h } @@ -513,8 +492,8 @@ static bool init_common(const Settings &cmd_args, int argc, char *argv[]) // Initialize HTTP fetcher httpfetch_init(g_settings->getS32("curl_parallel_limit")); - init_gettext(porting::path_locale.c_str(), g_settings->get("language"), argc, - argv); + init_gettext(porting::path_locale.c_str(), + g_settings->get("language"), argc, argv); return true; } @@ -522,20 +501,21 @@ static bool init_common(const Settings &cmd_args, int argc, char *argv[]) static void startup_message() { infostream << PROJECT_NAME << " " << _("with") - << " SER_FMT_VER_HIGHEST_READ=" << (int)SER_FMT_VER_HIGHEST_READ - << ", " << g_build_info << std::endl; + << " SER_FMT_VER_HIGHEST_READ=" + << (int)SER_FMT_VER_HIGHEST_READ << ", " + << g_build_info << std::endl; } static bool read_config_file(const Settings &cmd_args) { // Path of configuration file in use - sanity_check(g_settings_path == ""); // Sanity check + sanity_check(g_settings_path == ""); // Sanity check if (cmd_args.exists("config")) { bool r = g_settings->readConfigFile(cmd_args.get("config").c_str()); if (!r) { errorstream << "Could not read configuration from \"" - << cmd_args.get("config") << "\"" << std::endl; + << cmd_args.get("config") << "\"" << std::endl; return false; } g_settings_path = cmd_args.get("config"); @@ -543,14 +523,14 @@ static bool read_config_file(const Settings &cmd_args) std::vector filenames; filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf"); // Legacy configuration file location - filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + - "minetest.conf"); + filenames.push_back(porting::path_user + + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #if RUN_IN_PLACE // Try also from a lower level (to aid having the same configuration // for many RUN_IN_PLACE installs) - filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + - ".." + DIR_DELIM + "minetest.conf"); + filenames.push_back(porting::path_user + + DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #endif for (const std::string &filename : filenames) { @@ -582,32 +562,29 @@ static void init_log_streams(const Settings &cmd_args) // Old integer format if (std::isdigit(conf_loglev[0])) { warningstream << "Deprecated use of debug_log_level with an " - "integer value; please update your configuration." - << std::endl; - static const char *lev_name[] = { - "", "error", "action", "info", "verbose"}; + "integer value; please update your configuration." << std::endl; + static const char *lev_name[] = + {"", "error", "action", "info", "verbose"}; int lev_i = atoi(conf_loglev.c_str()); if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) { warningstream << "Supplied invalid debug_log_level!" - " Assuming action level." - << std::endl; + " Assuming action level." << std::endl; lev_i = 2; } conf_loglev = lev_name[lev_i]; } - if (log_filename.empty() || conf_loglev.empty()) // No logging + if (log_filename.empty() || conf_loglev.empty()) // No logging return; LogLevel log_level = Logger::stringToLevel(conf_loglev); if (log_level == LL_MAX) { warningstream << "Supplied unrecognized debug_log_level; " - "using maximum." - << std::endl; + "using maximum." << std::endl; } - file_log_output.setFile( - log_filename, g_settings->getU64("debug_log_size_max") * 1000000); + file_log_output.setFile(log_filename, + g_settings->getU64("debug_log_size_max") * 1000000); g_logger.addOutputMaxLevel(&file_log_output, log_level); } @@ -668,10 +645,8 @@ static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_ for (const WorldSpec &worldspec : worldspecs) { std::string name = worldspec.name; if (name == commanded_worldname) { - dstream << _("Using world specified by --worldname on " - "the " - "command line") - << std::endl; + dstream << _("Using world specified by --worldname on the " + "command line") << std::endl; commanded_world = worldspec.path; found = true; break; @@ -679,7 +654,7 @@ static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_ } if (!found) { dstream << _("World") << " '" << commanded_worldname - << _("' not available. Available worlds:") << std::endl; + << _("' not available. Available worlds:") << std::endl; print_worldspecs(worldspecs, dstream); return false; } @@ -723,26 +698,25 @@ static bool auto_select_world(GameParams *game_params) // If there is only a single world, use it if (worldspecs.size() == 1) { world_path = worldspecs[0].path; - dstream << _("Automatically selecting world at") << " [" << world_path - << "]" << std::endl; - // If there are multiple worlds, list them + dstream <<_("Automatically selecting world at") << " [" + << world_path << "]" << std::endl; + // If there are multiple worlds, list them } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) { std::cerr << _("Multiple worlds are available.") << std::endl; std::cerr << _("Please select one using --worldname " - " or --world ") - << std::endl; + " or --world ") << std::endl; print_worldspecs(worldspecs, std::cerr); return false; - // If there are no worlds, automatically create a new one + // If there are no worlds, automatically create a new one } else { // This is the ultimate default world path - world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + - "world"; - infostream << "Using default world at [" << world_path << "]" - << std::endl; + world_path = porting::path_user + DIR_DELIM + "worlds" + + DIR_DELIM + "world"; + infostream << "Using default world at [" + << world_path << "]" << std::endl; } - assert(world_path != ""); // Post-condition + assert(world_path != ""); // Post-condition game_params->world_path = world_path; return true; } @@ -752,8 +726,8 @@ static std::string get_clean_world_path(const std::string &path) const std::string worldmt = "world.mt"; std::string clean_path; - if (path.size() > worldmt.size() && - path.substr(path.size() - worldmt.size()) == worldmt) { + if (path.size() > worldmt.size() + && path.substr(path.size() - worldmt.size()) == worldmt) { dstream << _("Supplied world.mt file - stripping it off.") << std::endl; clean_path = path.substr(0, path.size() - worldmt.size()); } else { @@ -762,6 +736,7 @@ static std::string get_clean_world_path(const std::string &path) return path; } + static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args) { bool success; @@ -785,7 +760,7 @@ static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_a return false; } dstream << _("Using game specified by --gameid on the command line") - << std::endl; + << std::endl; game_params->game_spec = commanded_gamespec; return true; } @@ -797,24 +772,22 @@ static bool determine_subgame(GameParams *game_params) { SubgameSpec gamespec; - assert(game_params->world_path != ""); // Pre-condition + assert(game_params->world_path != ""); // Pre-condition // If world doesn't exist - if (!game_params->world_path.empty() && - !getWorldExists(game_params->world_path)) { + if (!game_params->world_path.empty() + && !getWorldExists(game_params->world_path)) { // Try to take gamespec from command line if (game_params->game_spec.isValid()) { gamespec = game_params->game_spec; - infostream << "Using commanded gameid [" << gamespec.id << "]" - << std::endl; + infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl; } else { // Otherwise we will be using "minetest" gamespec = findSubgame(g_settings->get("default_game")); - infostream << "Using default gameid [" << gamespec.id << "]" - << std::endl; + infostream << "Using default gameid [" << gamespec.id << "]" << std::endl; if (!gamespec.isValid()) { errorstream << "Game specified in default_game [" - << g_settings->get("default_game") - << "] is invalid." << std::endl; + << g_settings->get("default_game") + << "] is invalid." << std::endl; return false; } } @@ -824,23 +797,21 @@ static bool determine_subgame(GameParams *game_params) if (game_params->game_spec.isValid()) { gamespec = game_params->game_spec; if (game_params->game_spec.id != world_gameid) { - warningstream << "Using commanded gameid [" << gamespec.id - << "]" - << " instead of world gameid [" - << world_gameid << "]" << std::endl; + warningstream << "Using commanded gameid [" + << gamespec.id << "]" << " instead of world gameid [" + << world_gameid << "]" << std::endl; } } else { // If world contains an embedded game, use it; // Otherwise find world from local system. gamespec = findWorldSubgame(game_params->world_path); - infostream << "Using world gameid [" << gamespec.id << "]" - << std::endl; + infostream << "Using world gameid [" << gamespec.id << "]" << std::endl; } } if (!gamespec.isValid()) { errorstream << "Game [" << gamespec.id << "] could not be found." - << std::endl; + << std::endl; return false; } @@ -848,33 +819,35 @@ static bool determine_subgame(GameParams *game_params) return true; } + /***************************************************************************** * Dedicated server *****************************************************************************/ static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args) { - verbosestream << _("Using world path") << " [" << game_params.world_path << "]" - << std::endl; - verbosestream << _("Using gameid") << " [" << game_params.game_spec.id << "]" - << std::endl; + verbosestream << _("Using world path") << " [" + << game_params.world_path << "]" << std::endl; + verbosestream << _("Using gameid") << " [" + << game_params.game_spec.id << "]" << std::endl; // Bind address std::string bind_str = g_settings->get("bind_address"); Address bind_addr(0, 0, 0, 0, game_params.socket_port); if (g_settings->getBool("ipv6_server")) { - bind_addr.setAddress((IPv6AddressBytes *)NULL); + bind_addr.setAddress((IPv6AddressBytes*) NULL); } try { bind_addr.Resolve(bind_str.c_str()); } catch (ResolveError &e) { infostream << "Resolving bind address \"" << bind_str - << "\" failed: " << e.what() - << " -- Listening on all addresses." << std::endl; + << "\" failed: " << e.what() + << " -- Listening on all addresses." << std::endl; } if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) { - errorstream << "Unable to listen on " << bind_addr.serializeString() - << L" because IPv6 is disabled" << std::endl; + errorstream << "Unable to listen on " + << bind_addr.serializeString() + << L" because IPv6 is disabled" << std::endl; return false; } @@ -899,18 +872,15 @@ static bool run_dedicated_server(const GameParams &game_params, const Settings & if (!name_ok) { if (admin_nick.empty()) { errorstream << "No name given for admin. " - << "Please check your minetest.conf that it " - << "contains a 'name = ' to your main admin " - "account." - << std::endl; + << "Please check your minetest.conf that it " + << "contains a 'name = ' to your main admin account." + << std::endl; } else { - errorstream << "Name for admin '" << admin_nick - << "' is not valid. " - << "Please check that it only contains " - "allowed characters. " - << "Valid characters are: " - << PLAYERNAME_ALLOWED_CHARS_USER_EXPL - << std::endl; + errorstream << "Name for admin '" + << admin_nick << "' is not valid. " + << "Please check that it only contains allowed characters. " + << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL + << std::endl; } return false; } @@ -948,14 +918,13 @@ static bool run_dedicated_server(const GameParams &game_params, const Settings & } else { #else errorstream << "Cmd arg --terminal passed, but " - << "compiled without ncurses. Ignoring." << std::endl; - } - { + << "compiled without ncurses. Ignoring." << std::endl; + } { #endif try { // Create server - Server server(game_params.world_path, game_params.game_spec, - false, bind_addr, true); + Server server(game_params.world_path, game_params.game_spec, false, + bind_addr, true); server.start(); // Run server @@ -986,24 +955,21 @@ static bool migrate_map_database(const GameParams &game_params, const Settings & if (!world_mt.exists("backend")) { errorstream << "Please specify your current backend in world.mt:" - << std::endl - << " backend = " - "{sqlite3|leveldb|redis|dummy|postgresql}" - << std::endl; + << std::endl + << " backend = {sqlite3|leveldb|redis|dummy|postgresql}" + << std::endl; return false; } std::string backend = world_mt.get("backend"); if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" - << " as the old one" << std::endl; + << " as the old one" << std::endl; return false; } - MapDatabase *old_db = ServerMap::createDatabase( - backend, game_params.world_path, world_mt), - *new_db = ServerMap::createDatabase( - migrate_to, game_params.world_path, world_mt); + MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt), + *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt); u32 count = 0; time_t last_update_time = 0; @@ -1012,22 +978,19 @@ static bool migrate_map_database(const GameParams &game_params, const Settings & std::vector blocks; old_db->listAllLoadableBlocks(blocks); new_db->beginSave(); - for (std::vector::const_iterator it = blocks.begin(); it != blocks.end(); - ++it) { - if (kill) - return false; + for (std::vector::const_iterator it = blocks.begin(); it != blocks.end(); ++it) { + if (kill) return false; std::string data; old_db->loadBlock(*it, &data); if (!data.empty()) { new_db->saveBlock(*it, data); } else { - errorstream << "Failed to load block " << PP(*it) - << ", skipping it." << std::endl; + errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl; } if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) { std::cerr << " Migrated " << count << " blocks, " - << (100.0 * count / blocks.size()) << "% completed.\r"; + << (100.0 * count / blocks.size()) << "% completed.\r"; new_db->endSave(); new_db->beginSave(); last_update_time = time(NULL); diff --git a/src/map.cpp b/src/map.cpp index fc284dcee..b9ab7c066 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -57,12 +57,15 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database/database-postgresql.h" #endif + /* Map */ -Map::Map(std::ostream &dout, IGameDef *gamedef) : - m_dout(dout), m_gamedef(gamedef), m_nodedef(gamedef->ndef()) +Map::Map(std::ostream &dout, IGameDef *gamedef): + m_dout(dout), + m_gamedef(gamedef), + m_nodedef(gamedef->ndef()) { } @@ -93,14 +96,14 @@ void Map::dispatchEvent(const MapEditEvent &event) } } -MapSector *Map::getSectorNoGenerateNoLock(v2s16 p) +MapSector * Map::getSectorNoGenerateNoLock(v2s16 p) { - if (m_sector_cache != NULL && p == m_sector_cache_p) { - MapSector *sector = m_sector_cache; + if(m_sector_cache != NULL && p == m_sector_cache_p){ + MapSector * sector = m_sector_cache; return sector; } - std::map::iterator n = m_sectors.find(p); + std::map::iterator n = m_sectors.find(p); if (n == m_sectors.end()) return NULL; @@ -114,25 +117,25 @@ MapSector *Map::getSectorNoGenerateNoLock(v2s16 p) return sector; } -MapSector *Map::getSectorNoGenerate(v2s16 p) +MapSector * Map::getSectorNoGenerate(v2s16 p) { return getSectorNoGenerateNoLock(p); } -MapBlock *Map::getBlockNoCreateNoEx(v3s16 p3d) +MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d) { v2s16 p2d(p3d.X, p3d.Z); - MapSector *sector = getSectorNoGenerate(p2d); - if (sector == NULL) + MapSector * sector = getSectorNoGenerate(p2d); + if(sector == NULL) return NULL; MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y); return block; } -MapBlock *Map::getBlockNoCreate(v3s16 p3d) +MapBlock * Map::getBlockNoCreate(v3s16 p3d) { MapBlock *block = getBlockNoCreateNoEx(p3d); - if (block == NULL) + if(block == NULL) throw InvalidPositionException(); return block; } @@ -162,7 +165,7 @@ MapNode Map::getNode(v3s16 p, bool *is_valid_position) return {CONTENT_IGNORE}; } - v3s16 relpos = p - blockpos * MAP_BLOCKSIZE; + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; bool is_valid_p; MapNode node = block->getNodeNoCheck(relpos, &is_valid_p); if (is_valid_position != NULL) @@ -171,27 +174,26 @@ MapNode Map::getNode(v3s16 p, bool *is_valid_position) } // throws InvalidPositionException if not found -void Map::setNode(v3s16 p, MapNode &n) +void Map::setNode(v3s16 p, MapNode & n) { v3s16 blockpos = getNodeBlockPos(p); MapBlock *block = getBlockNoCreate(blockpos); - v3s16 relpos = p - blockpos * MAP_BLOCKSIZE; + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; // Never allow placing CONTENT_IGNORE, it causes problems - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ bool temp_bool; - errorstream << "Map::setNode(): Not allowing to place CONTENT_IGNORE" - << " while trying to replace \"" - << m_nodedef->get(block->getNodeNoCheck(relpos, &temp_bool)) - .name - << "\" at " << PP(p) << " (block " << PP(blockpos) << ")" - << std::endl; + errorstream<<"Map::setNode(): Not allowing to place CONTENT_IGNORE" + <<" while trying to replace \"" + <get(block->getNodeNoCheck(relpos, &temp_bool)).name + <<"\" at "<setNodeNoCheck(relpos, n); } void Map::addNodeAndUpdate(v3s16 p, MapNode n, - std::map &modified_blocks, bool remove_metadata) + std::map &modified_blocks, + bool remove_metadata) { // Collect old node for rollback RollbackNode rollback_oldnode(this, p, m_gamedef); @@ -211,7 +213,7 @@ void Map::addNodeAndUpdate(v3s16 p, MapNode n, setNode(p, n); // Update lighting - std::vector> oldnodes; + std::vector > oldnodes; oldnodes.emplace_back(p, oldnode); voxalgo::update_lighting_nodes(this, oldnodes, modified_blocks); @@ -220,7 +222,8 @@ void Map::addNodeAndUpdate(v3s16 p, MapNode n, } // Report for rollback - if (m_gamedef->rollback()) { + if(m_gamedef->rollback()) + { RollbackNode rollback_newnode(this, p, m_gamedef); RollbackAction action; action.setSetNode(p, rollback_oldnode, rollback_newnode); @@ -237,13 +240,15 @@ void Map::addNodeAndUpdate(v3s16 p, MapNode n, bool is_valid_position; MapNode n2 = getNode(p2, &is_valid_position); - if (is_valid_position && (m_nodedef->get(n2).isLiquid() || - n2.getContent() == CONTENT_AIR)) + if(is_valid_position && + (m_nodedef->get(n2).isLiquid() || + n2.getContent() == CONTENT_AIR)) m_transforming_liquid.push_back(p2); } } -void Map::removeNodeAndUpdate(v3s16 p, std::map &modified_blocks) +void Map::removeNodeAndUpdate(v3s16 p, + std::map &modified_blocks) { addNodeAndUpdate(p, MapNode(CONTENT_AIR), modified_blocks, true); } @@ -256,15 +261,16 @@ bool Map::addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata) event.n = n; bool succeeded = true; - try { - std::map modified_blocks; + try{ + std::map modified_blocks; addNodeAndUpdate(p, n, modified_blocks, remove_metadata); // Copy modified_blocks to event for (auto &modified_block : modified_blocks) { event.modified_blocks.insert(modified_block.first); } - } catch (InvalidPositionException &e) { + } + catch(InvalidPositionException &e){ succeeded = false; } @@ -280,15 +286,16 @@ bool Map::removeNodeWithEvent(v3s16 p) event.p = p; bool succeeded = true; - try { - std::map modified_blocks; + try{ + std::map modified_blocks; removeNodeAndUpdate(p, modified_blocks); // Copy modified_blocks to event for (auto &modified_block : modified_blocks) { event.modified_blocks.insert(modified_block.first); } - } catch (InvalidPositionException &e) { + } + catch(InvalidPositionException &e){ succeeded = false; } @@ -297,14 +304,14 @@ bool Map::removeNodeWithEvent(v3s16 p) return succeeded; } -struct TimeOrderedMapBlock -{ +struct TimeOrderedMapBlock { MapSector *sect; MapBlock *block; - TimeOrderedMapBlock(MapSector *sect, MapBlock *block) : sect(sect), block(block) - { - } + TimeOrderedMapBlock(MapSector *sect, MapBlock *block) : + sect(sect), + block(block) + {} bool operator<(const TimeOrderedMapBlock &b) const { @@ -343,15 +350,14 @@ void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, for (MapBlock *block : blocks) { block->incrementUsageTimer(dtime); - if (block->refGet() == 0 && - block->getUsageTimer() > unload_timeout) { + if (block->refGet() == 0 + && block->getUsageTimer() > unload_timeout) { v3s16 p = block->getPos(); // Save if modified - if (block->getModified() != MOD_STATE_CLEAN && - save_before_unloading) { - modprofiler.add(block->getModifiedReasonString(), - 1); + if (block->getModified() != MOD_STATE_CLEAN + && save_before_unloading) { + modprofiler.add(block->getModifiedReasonString(), 1); if (!saveBlock(block)) continue; saved_blocks_count++; @@ -389,10 +395,8 @@ void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, } block_count_all = mapblock_queue.size(); // Delete old blocks, and blocks over the limit from the memory - while (!mapblock_queue.empty() && - (mapblock_queue.size() > max_loaded_blocks || - mapblock_queue.top().block->getUsageTimer() > - unload_timeout)) { + while (!mapblock_queue.empty() && (mapblock_queue.size() > max_loaded_blocks + || mapblock_queue.top().block->getUsageTimer() > unload_timeout)) { TimeOrderedMapBlock b = mapblock_queue.top(); mapblock_queue.pop(); @@ -404,8 +408,7 @@ void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, v3s16 p = block->getPos(); // Save if modified - if (block->getModified() != MOD_STATE_CLEAN && - save_before_unloading) { + if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) { modprofiler.add(block->getModifiedReasonString(), 1); if (!saveBlock(block)) continue; @@ -433,18 +436,18 @@ void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, // Finally delete the empty sectors deleteSectors(sector_deletion_queue); - if (deleted_blocks_count != 0) { + if(deleted_blocks_count != 0) + { PrintInfo(infostream); // ServerMap/ClientMap: - infostream << "Unloaded " << deleted_blocks_count - << " blocks from memory"; - if (save_before_unloading) - infostream << ", of which " << saved_blocks_count - << " were written"; - infostream << ", " << block_count_all << " blocks in memory"; - infostream << "." << std::endl; - if (saved_blocks_count != 0) { + infostream<<"Unloaded "< §orList) for (v2s16 j : sectorList) { MapSector *sector = m_sectors[j]; // If sector is in sector cache, remove it from there - if (m_sector_cache == sector) + if(m_sector_cache == sector) m_sector_cache = NULL; // Remove from map and delete m_sectors.erase(j); @@ -470,56 +473,60 @@ void Map::deleteSectors(std::vector §orList) void Map::PrintInfo(std::ostream &out) { - out << "Map: "; + out<<"Map: "; } #define WATER_DROP_BOOST 4 const static v3s16 liquid_6dirs[6] = { - // order: upper before same level before lower - v3s16(0, 1, 0), v3s16(0, 0, 1), v3s16(1, 0, 0), v3s16(0, 0, -1), - v3s16(-1, 0, 0), v3s16(0, -1, 0)}; + // order: upper before same level before lower + v3s16( 0, 1, 0), + v3s16( 0, 0, 1), + v3s16( 1, 0, 0), + v3s16( 0, 0,-1), + v3s16(-1, 0, 0), + v3s16( 0,-1, 0) +}; -enum NeighborType : u8 -{ +enum NeighborType : u8 { NEIGHBOR_UPPER, NEIGHBOR_SAME_LEVEL, NEIGHBOR_LOWER }; -struct NodeNeighbor -{ +struct NodeNeighbor { MapNode n; NeighborType t; v3s16 p; - NodeNeighbor() : n(CONTENT_AIR), t(NEIGHBOR_SAME_LEVEL) {} + NodeNeighbor() + : n(CONTENT_AIR), t(NEIGHBOR_SAME_LEVEL) + { } - NodeNeighbor(const MapNode &node, NeighborType n_type, const v3s16 &pos) : - n(node), t(n_type), p(pos) - { - } + NodeNeighbor(const MapNode &node, NeighborType n_type, const v3s16 &pos) + : n(node), + t(n_type), + p(pos) + { } }; -void Map::transforming_liquid_add(v3s16 p) -{ - m_transforming_liquid.push_back(p); +void Map::transforming_liquid_add(v3s16 p) { + m_transforming_liquid.push_back(p); } -void Map::transformLiquids( - std::map &modified_blocks, ServerEnvironment *env) +void Map::transformLiquids(std::map &modified_blocks, + ServerEnvironment *env) { u32 loopcount = 0; u32 initial_size = m_transforming_liquid.size(); /*if(initial_size != 0) - infostream<<"transformLiquids(): - initial_size="<= initial_size || loopcount >= loop_max) break; @@ -568,22 +576,22 @@ void Map::transformLiquids( const ContentFeatures &cf = m_nodedef->get(n0); LiquidType liquid_type = cf.liquid_type; switch (liquid_type) { - case LIQUID_SOURCE: - liquid_level = LIQUID_LEVEL_SOURCE; - liquid_kind = cf.liquid_alternative_flowing_id; - break; - case LIQUID_FLOWING: - liquid_level = (n0.param2 & LIQUID_LEVEL_MASK); - liquid_kind = n0.getContent(); - break; - case LIQUID_NONE: - // if this node is 'floodable', it *could* be transformed - // into a liquid, otherwise, continue with the next node. - if (!cf.floodable) - continue; - floodable_node = n0.getContent(); - liquid_kind = CONTENT_AIR; - break; + case LIQUID_SOURCE: + liquid_level = LIQUID_LEVEL_SOURCE; + liquid_kind = cf.liquid_alternative_flowing_id; + break; + case LIQUID_FLOWING: + liquid_level = (n0.param2 & LIQUID_LEVEL_MASK); + liquid_kind = n0.getContent(); + break; + case LIQUID_NONE: + // if this node is 'floodable', it *could* be transformed + // into a liquid, otherwise, continue with the next node. + if (!cf.floodable) + continue; + floodable_node = n0.getContent(); + liquid_kind = CONTENT_AIR; + break; } /* @@ -595,88 +603,78 @@ void Map::transformLiquids( int num_flows = 0; NodeNeighbor airs[6]; // surrounding air int num_airs = 0; - NodeNeighbor neutrals[6]; // nodes that are solid or another kind of - // liquid + NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid int num_neutrals = 0; bool flowing_down = false; bool ignored_sources = false; for (u16 i = 0; i < 6; i++) { NeighborType nt = NEIGHBOR_SAME_LEVEL; switch (i) { - case 0: - nt = NEIGHBOR_UPPER; - break; - case 5: - nt = NEIGHBOR_LOWER; - break; - default: - break; + case 0: + nt = NEIGHBOR_UPPER; + break; + case 5: + nt = NEIGHBOR_LOWER; + break; + default: + break; } v3s16 npos = p0 + liquid_6dirs[i]; NodeNeighbor nb(getNode(npos), nt, npos); const ContentFeatures &cfnb = m_nodedef->get(nb.n); switch (m_nodedef->get(nb.n.getContent()).liquid_type) { - case LIQUID_NONE: - if (cfnb.floodable) { - airs[num_airs++] = nb; - // if the current node is a water source the - // neighbor should be enqueded for transformation - // regardless of whether the current node changes - // or not. - if (nb.t != NEIGHBOR_UPPER && - liquid_type != LIQUID_NONE) - m_transforming_liquid.push_back(npos); - // if the current node happens to be a flowing - // node, it will start to flow down here. - if (nb.t == NEIGHBOR_LOWER) - flowing_down = true; - } else { - neutrals[num_neutrals++] = nb; - if (nb.n.getContent() == CONTENT_IGNORE) { - // If node below is ignore prevent water - // from spreading outwards and otherwise - // prevent from flowing away as ignore - // node might be the source + case LIQUID_NONE: + if (cfnb.floodable) { + airs[num_airs++] = nb; + // if the current node is a water source the neighbor + // should be enqueded for transformation regardless of whether the + // current node changes or not. + if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE) + m_transforming_liquid.push_back(npos); + // if the current node happens to be a flowing node, it will start to flow down here. if (nb.t == NEIGHBOR_LOWER) flowing_down = true; - else - ignored_sources = true; + } else { + neutrals[num_neutrals++] = nb; + if (nb.n.getContent() == CONTENT_IGNORE) { + // If node below is ignore prevent water from + // spreading outwards and otherwise prevent from + // flowing away as ignore node might be the source + if (nb.t == NEIGHBOR_LOWER) + flowing_down = true; + else + ignored_sources = true; + } } - } - break; - case LIQUID_SOURCE: - // if this node is not (yet) of a liquid type, choose the - // first liquid type we encounter - if (liquid_kind == CONTENT_AIR) - liquid_kind = cfnb.liquid_alternative_flowing_id; - if (cfnb.liquid_alternative_flowing_id != liquid_kind) { - neutrals[num_neutrals++] = nb; - } else { - // Do not count bottom source, it will screw - // things up - if (nt != NEIGHBOR_LOWER) - sources[num_sources++] = nb; - } - break; - case LIQUID_FLOWING: - if (nb.t != NEIGHBOR_SAME_LEVEL || - (nb.n.param2 & LIQUID_FLOW_DOWN_MASK) != - LIQUID_FLOW_DOWN_MASK) { - // if this node is not (yet) of a liquid type, - // choose the first liquid type we encounter but - // exclude falling liquids on the same level, they - // cannot flow here anyway + break; + case LIQUID_SOURCE: + // if this node is not (yet) of a liquid type, choose the first liquid type we encounter if (liquid_kind == CONTENT_AIR) liquid_kind = cfnb.liquid_alternative_flowing_id; - } - if (cfnb.liquid_alternative_flowing_id != liquid_kind) { - neutrals[num_neutrals++] = nb; - } else { - flows[num_flows++] = nb; - if (nb.t == NEIGHBOR_LOWER) - flowing_down = true; - } - break; + if (cfnb.liquid_alternative_flowing_id != liquid_kind) { + neutrals[num_neutrals++] = nb; + } else { + // Do not count bottom source, it will screw things up + if(nt != NEIGHBOR_LOWER) + sources[num_sources++] = nb; + } + break; + case LIQUID_FLOWING: + if (nb.t != NEIGHBOR_SAME_LEVEL || + (nb.n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK) { + // if this node is not (yet) of a liquid type, choose the first liquid type we encounter + // but exclude falling liquids on the same level, they cannot flow here anyway + if (liquid_kind == CONTENT_AIR) + liquid_kind = cfnb.liquid_alternative_flowing_id; + } + if (cfnb.liquid_alternative_flowing_id != liquid_kind) { + neutrals[num_neutrals++] = nb; + } else { + flows[num_flows++] = nb; + if (nb.t == NEIGHBOR_LOWER) + flowing_down = true; + } + break; } } @@ -691,15 +689,11 @@ void Map::transformLiquids( if (range > LIQUID_LEVEL_MAX + 1) range = LIQUID_LEVEL_MAX + 1; - if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || - liquid_type == LIQUID_SOURCE) { - // liquid_kind will be set to either the flowing alternative of - // the node (if it's a liquid) or the flowing alternative of the - // first of the surrounding sources (if it's air), so it's - // perfectly safe to use liquid_kind here to determine the new - // node content. - new_node_content = m_nodedef->get(liquid_kind) - .liquid_alternative_source_id; + if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) { + // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid) + // or the flowing alternative of the first of the surrounding sources (if it's air), so + // it's perfectly safe to use liquid_kind here to determine the new node content. + new_node_content = m_nodedef->get(liquid_kind).liquid_alternative_source_id; } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) { // liquid_kind is set properly, see above max_node_level = new_node_level = LIQUID_LEVEL_MAX; @@ -713,34 +707,26 @@ void Map::transformLiquids( new_node_level = liquid_level; new_node_content = liquid_kind; } else { - // no surrounding sources, so get the maximum level that can flow - // into this node + // no surrounding sources, so get the maximum level that can flow into this node for (u16 i = 0; i < num_flows; i++) { - u8 nb_liquid_level = - (flows[i].n.param2 & LIQUID_LEVEL_MASK); + u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK); switch (flows[i].t) { - case NEIGHBOR_UPPER: - if (nb_liquid_level + WATER_DROP_BOOST > - max_node_level) { - max_node_level = LIQUID_LEVEL_MAX; - if (nb_liquid_level + WATER_DROP_BOOST < - LIQUID_LEVEL_MAX) - max_node_level = nb_liquid_level + - WATER_DROP_BOOST; - } else if (nb_liquid_level > max_node_level) { - max_node_level = nb_liquid_level; - } - break; - case NEIGHBOR_LOWER: - break; - case NEIGHBOR_SAME_LEVEL: - if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != - LIQUID_FLOW_DOWN_MASK && - nb_liquid_level > 0 && - nb_liquid_level - 1 > - max_node_level) - max_node_level = nb_liquid_level - 1; - break; + case NEIGHBOR_UPPER: + if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) { + max_node_level = LIQUID_LEVEL_MAX; + if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX) + max_node_level = nb_liquid_level + WATER_DROP_BOOST; + } else if (nb_liquid_level > max_node_level) { + max_node_level = nb_liquid_level; + } + break; + case NEIGHBOR_LOWER: + break; + case NEIGHBOR_SAME_LEVEL: + if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK && + nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level) + max_node_level = nb_liquid_level - 1; + break; } } @@ -750,8 +736,7 @@ void Map::transformLiquids( // must be at least 1 in absolute value s8 level_inc = max_node_level - liquid_level; if (level_inc < -viscosity || level_inc > viscosity) - new_node_level = liquid_level + - level_inc / viscosity; + new_node_level = liquid_level + level_inc/viscosity; else if (level_inc < 0) new_node_level = liquid_level - 1; else if (level_inc > 0) @@ -766,32 +751,28 @@ void Map::transformLiquids( new_node_content = liquid_kind; else new_node_content = floodable_node; + } /* - check if anything has changed. if not, just continue with the next - node. + check if anything has changed. if not, just continue with the next node. */ if (new_node_content == n0.getContent() && - (m_nodedef->get(n0.getContent()).liquid_type != - LIQUID_FLOWING || - ((n0.param2 & LIQUID_LEVEL_MASK) == - (u8)new_node_level && - ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == - LIQUID_FLOW_DOWN_MASK) == - flowing_down))) + (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING || + ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level && + ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK) + == flowing_down))) continue; + /* update the current node */ MapNode n00 = n0; - // bool flow_down_enabled = (flowing_down && ((n0.param2 & - // LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK)); + //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK)); if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) { // set level to last 3 bits, flowing down bit to 4th bit - n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | - (new_node_level & LIQUID_LEVEL_MASK); + n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK); } else { // set the liquid level and flow bits to 0 n0.param2 &= ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK); @@ -817,8 +798,7 @@ void Map::transformLiquids( if (m_gamedef->rollback() && !suspect.empty()) { // Blame suspect - RollbackScopeActor rollback_scope( - m_gamedef->rollback(), suspect, true); + RollbackScopeActor rollback_scope(m_gamedef->rollback(), suspect, true); // Get old node for rollback RollbackNode rollback_oldnode(this, p0, m_gamedef); // Set node @@ -836,7 +816,7 @@ void Map::transformLiquids( v3s16 blockpos = getNodeBlockPos(p0); MapBlock *block = getBlockNoCreateNoEx(blockpos); if (block != NULL) { - modified_blocks[blockpos] = block; + modified_blocks[blockpos] = block; changed_nodes.emplace_back(p0, n00); } @@ -844,31 +824,31 @@ void Map::transformLiquids( enqueue neighbors for update if neccessary */ switch (m_nodedef->get(n0.getContent()).liquid_type) { - case LIQUID_SOURCE: - case LIQUID_FLOWING: - // make sure source flows into all neighboring nodes - for (u16 i = 0; i < num_flows; i++) - if (flows[i].t != NEIGHBOR_UPPER) + case LIQUID_SOURCE: + case LIQUID_FLOWING: + // make sure source flows into all neighboring nodes + for (u16 i = 0; i < num_flows; i++) + if (flows[i].t != NEIGHBOR_UPPER) + m_transforming_liquid.push_back(flows[i].p); + for (u16 i = 0; i < num_airs; i++) + if (airs[i].t != NEIGHBOR_UPPER) + m_transforming_liquid.push_back(airs[i].p); + break; + case LIQUID_NONE: + // this flow has turned to air; neighboring flows might need to do the same + for (u16 i = 0; i < num_flows; i++) m_transforming_liquid.push_back(flows[i].p); - for (u16 i = 0; i < num_airs; i++) - if (airs[i].t != NEIGHBOR_UPPER) - m_transforming_liquid.push_back(airs[i].p); - break; - case LIQUID_NONE: - // this flow has turned to air; neighboring flows might need to do - // the same - for (u16 i = 0; i < num_flows; i++) - m_transforming_liquid.push_back(flows[i].p); - break; + break; } } - // infostream<<"Map::transformLiquids(): loopcount="< Map::findNodesWithMetadata(v3s16 p1, v3s16 p2) VoxelArea area(p1, p2); for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - v3s16 blockpos(x, y, z); - - MapBlock *block = getBlockNoCreateNoEx(blockpos); - if (!block) { - verbosestream << "Map::getNodeMetadata(): Need " - "to emerge " - << PP(blockpos) << std::endl; - block = emergeBlock(blockpos, false); - } - if (!block) { - infostream << "WARNING: Map::getNodeMetadata(): " - "Block not found" - << std::endl; - continue; - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + v3s16 blockpos(x, y, z); + + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if (!block) { + verbosestream << "Map::getNodeMetadata(): Need to emerge " + << PP(blockpos) << std::endl; + block = emergeBlock(blockpos, false); + } + if (!block) { + infostream << "WARNING: Map::getNodeMetadata(): Block not found" + << std::endl; + continue; + } - v3s16 p_base = blockpos * MAP_BLOCKSIZE; - std::vector keys = - block->m_node_metadata.getAllKeys(); - for (size_t i = 0; i != keys.size(); i++) { - v3s16 p(keys[i] + p_base); - if (!area.contains(p)) - continue; + v3s16 p_base = blockpos * MAP_BLOCKSIZE; + std::vector keys = block->m_node_metadata.getAllKeys(); + for (size_t i = 0; i != keys.size(); i++) { + v3s16 p(keys[i] + p_base); + if (!area.contains(p)) + continue; - positions_with_meta.push_back(p); - } - } + positions_with_meta.push_back(p); + } + } return positions_with_meta; } @@ -966,15 +942,16 @@ std::vector Map::findNodesWithMetadata(v3s16 p1, v3s16 p2) NodeMetadata *Map::getNodeMetadata(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); - v3s16 p_rel = p - blockpos * MAP_BLOCKSIZE; + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); - if (!block) { - infostream << "Map::getNodeMetadata(): Need to emerge " << PP(blockpos) - << std::endl; + if(!block){ + infostream<<"Map::getNodeMetadata(): Need to emerge " + <m_node_metadata.get(p_rel); @@ -984,15 +961,16 @@ NodeMetadata *Map::getNodeMetadata(v3s16 p) bool Map::setNodeMetadata(v3s16 p, NodeMetadata *meta) { v3s16 blockpos = getNodeBlockPos(p); - v3s16 p_rel = p - blockpos * MAP_BLOCKSIZE; + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); - if (!block) { - infostream << "Map::setNodeMetadata(): Need to emerge " << PP(blockpos) - << std::endl; + if(!block){ + infostream<<"Map::setNodeMetadata(): Need to emerge " + <m_node_metadata.set(p_rel, meta); @@ -1002,11 +980,12 @@ bool Map::setNodeMetadata(v3s16 p, NodeMetadata *meta) void Map::removeNodeMetadata(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); - v3s16 p_rel = p - blockpos * MAP_BLOCKSIZE; + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); - if (block == NULL) { - warningstream << "Map::removeNodeMetadata(): Block not found" - << std::endl; + if(block == NULL) + { + warningstream<<"Map::removeNodeMetadata(): Block not found" + <m_node_metadata.remove(p_rel); @@ -1015,15 +994,16 @@ void Map::removeNodeMetadata(v3s16 p) NodeTimer Map::getNodeTimer(v3s16 p) { v3s16 blockpos = getNodeBlockPos(p); - v3s16 p_rel = p - blockpos * MAP_BLOCKSIZE; + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); - if (!block) { - infostream << "Map::getNodeTimer(): Need to emerge " << PP(blockpos) - << std::endl; + if(!block){ + infostream<<"Map::getNodeTimer(): Need to emerge " + <m_node_timers.get(p_rel); @@ -1035,15 +1015,16 @@ void Map::setNodeTimer(const NodeTimer &t) { v3s16 p = t.position; v3s16 blockpos = getNodeBlockPos(p); - v3s16 p_rel = p - blockpos * MAP_BLOCKSIZE; + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; MapBlock *block = getBlockNoCreateNoEx(blockpos); - if (!block) { - infostream << "Map::setNodeTimer(): Need to emerge " << PP(blockpos) - << std::endl; + if(!block){ + infostream<<"Map::setNodeTimer(): Need to emerge " + <m_node_timers.remove(p_rel); } bool Map::determineAdditionalOcclusionCheck(const v3s16 &pos_camera, - const core::aabbox3d &block_bounds, v3s16 &check) + const core::aabbox3d &block_bounds, v3s16 &check) { /* This functions determines the node inside the target block that is @@ -1075,9 +1058,9 @@ bool Map::determineAdditionalOcclusionCheck(const v3s16 &pos_camera, - the closest node is a corner, corners are checked anyway. - the camera is inside the target block, it will never be occluded. */ -#define CLOSEST_EDGE(pos, bounds, axis) \ - ((pos).axis <= (bounds).MinEdge.axis) ? (bounds).MinEdge.axis \ - : (bounds).MaxEdge.axis +#define CLOSEST_EDGE(pos, bounds, axis) \ + ((pos).axis <= (bounds).MinEdge.axis) ? (bounds).MinEdge.axis : \ + (bounds).MaxEdge.axis bool x_inside = (block_bounds.MinEdge.X <= pos_camera.X) && (pos_camera.X <= block_bounds.MaxEdge.X); @@ -1126,8 +1109,8 @@ bool Map::determineAdditionalOcclusionCheck(const v3s16 &pos_camera, return false; } -bool Map::isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target, float step, - float stepfac, float offset, float end_offset, u32 needed_count) +bool Map::isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target, + float step, float stepfac, float offset, float end_offset, u32 needed_count) { v3f direction = intToFloat(pos_target - pos_camera, BS); float distance = direction.getLength(); @@ -1146,7 +1129,8 @@ bool Map::isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target, float ste MapNode node = getNode(pos_node, &is_valid_position); - if (is_valid_position && !m_nodedef->get(node).light_propagates) { + if (is_valid_position && + !m_nodedef->get(node).light_propagates) { // Cannot see through light-blocking nodes --> occluded count++; if (count >= needed_count) @@ -1163,15 +1147,15 @@ bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) // Overshoot a little for less flickering static const s16 bs2 = MAP_BLOCKSIZE / 2 + 1; static const v3s16 dir9[9] = { - v3s16(0, 0, 0), - v3s16(1, 1, 1) * bs2, - v3s16(1, 1, -1) * bs2, - v3s16(1, -1, 1) * bs2, - v3s16(1, -1, -1) * bs2, - v3s16(-1, 1, 1) * bs2, - v3s16(-1, 1, -1) * bs2, - v3s16(-1, -1, 1) * bs2, - v3s16(-1, -1, -1) * bs2, + v3s16( 0, 0, 0), + v3s16( 1, 1, 1) * bs2, + v3s16( 1, 1, -1) * bs2, + v3s16( 1, -1, 1) * bs2, + v3s16( 1, -1, -1) * bs2, + v3s16(-1, 1, 1) * bs2, + v3s16(-1, 1, -1) * bs2, + v3s16(-1, -1, 1) * bs2, + v3s16(-1, -1, -1) * bs2, }; v3s16 pos_blockcenter = block->getPosRelative() + (MAP_BLOCKSIZE / 2); @@ -1199,14 +1183,14 @@ bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) v3s16 check; if (determineAdditionalOcclusionCheck(cam_pos_nodes, block->getBox(), check)) { // node is always on a side facing the camera, end_offset can be lower - if (!isOccluded(cam_pos_nodes, check, step, stepfac, start_offset, -1.0f, - needed_count)) + if (!isOccluded(cam_pos_nodes, check, step, stepfac, start_offset, + -1.0f, needed_count)) return false; } for (const v3s16 &dir : dir9) { if (!isOccluded(cam_pos_nodes, pos_blockcenter + dir, step, stepfac, - start_offset, end_offset, needed_count)) + start_offset, end_offset, needed_count)) return false; } return true; @@ -1215,13 +1199,13 @@ bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) /* ServerMap */ -ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, - MetricsBackend *mb) : - Map(dout_server, gamedef), - settings_mgr(g_settings, savedir + DIR_DELIM + "map_meta.txt"), - m_emerge(emerge) +ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef, + EmergeManager *emerge, MetricsBackend *mb): + Map(dout_server, gamedef), + settings_mgr(g_settings, savedir + DIR_DELIM + "map_meta.txt"), + m_emerge(emerge) { - verbosestream << FUNCTION_NAME << std::endl; + verbosestream<map_settings_mgr = &settings_mgr; @@ -1242,40 +1226,35 @@ ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManage dbase = createDatabase(backend, savedir, conf); if (conf.exists("readonly_backend")) { std::string readonly_dir = savedir + DIR_DELIM + "readonly"; - dbase_ro = createDatabase( - conf.get("readonly_backend"), readonly_dir, conf); + dbase_ro = createDatabase(conf.get("readonly_backend"), readonly_dir, conf); } if (!conf.updateConfigFile(conf_path.c_str())) - errorstream << "ServerMap::ServerMap(): Failed to update world.mt!" - << std::endl; + errorstream << "ServerMap::ServerMap(): Failed to update world.mt!" << std::endl; m_savedir = savedir; m_map_saving_enabled = false; - m_save_time_counter = mb->addCounter( - "minetest_core_map_save_time", "Map save time (in nanoseconds)"); + m_save_time_counter = mb->addCounter("minetest_core_map_save_time", "Map save time (in nanoseconds)"); try { // If directory exists, check contents and load if possible if (fs::PathExists(m_savedir)) { // If directory is empty, it is safe to save into it. if (fs::GetDirListing(m_savedir).empty()) { - infostream << "ServerMap: Empty save directory is valid." - << std::endl; + infostream<<"ServerMap: Empty save directory is valid." + <mapgen_limit, 0, - MAX_MAP_GENERATION_LIMIT) / - MAP_BLOCKSIZE; - return p.X < -mapgen_limit_bp || p.X > mapgen_limit_bp || - p.Y < -mapgen_limit_bp || p.Y > mapgen_limit_bp || - p.Z < -mapgen_limit_bp || p.Z > mapgen_limit_bp; + const s16 mapgen_limit_bp = rangelim( + getMapgenParams()->mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) / + MAP_BLOCKSIZE; + return p.X < -mapgen_limit_bp || + p.X > mapgen_limit_bp || + p.Y < -mapgen_limit_bp || + p.Y > mapgen_limit_bp || + p.Z < -mapgen_limit_bp || + p.Z > mapgen_limit_bp; } bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data) @@ -1387,26 +1373,26 @@ bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data) Create the whole area of this and the neighboring blocks */ for (s16 x = full_bpmin.X; x <= full_bpmax.X; x++) - for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) { - v2s16 sectorpos(x, z); - // Sector metadata is loaded from disk if not already loaded. - MapSector *sector = createSector(sectorpos); - FATAL_ERROR_IF(sector == NULL, "createSector() failed"); - - for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) { - v3s16 p(x, y, z); - - MapBlock *block = emergeBlock(p, false); - if (block == NULL) { - block = createBlock(p); - - // Block gets sunlight if this is true. - // Refer to the map generator heuristics. - bool ug = m_emerge->isBlockUnderground(p); - block->setIsUnderground(ug); - } + for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) { + v2s16 sectorpos(x, z); + // Sector metadata is loaded from disk if not already loaded. + MapSector *sector = createSector(sectorpos); + FATAL_ERROR_IF(sector == NULL, "createSector() failed"); + + for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) { + v3s16 p(x, y, z); + + MapBlock *block = emergeBlock(p, false); + if (block == NULL) { + block = createBlock(p); + + // Block gets sunlight if this is true. + // Refer to the map generator heuristics. + bool ug = m_emerge->isBlockUnderground(p); + block->setIsUnderground(ug); } } + } /* Now we have a big empty area. @@ -1441,8 +1427,8 @@ bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data) return true; } -void ServerMap::finishBlockMake( - BlockMakeData *data, std::map *changed_blocks) +void ServerMap::finishBlockMake(BlockMakeData *data, + std::map *changed_blocks) { v3s16 bpmin = data->blockpos_min; v3s16 bpmax = data->blockpos_max; @@ -1459,7 +1445,7 @@ void ServerMap::finishBlockMake( data->vmanip->blitBackAll(changed_blocks); EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()=" - << changed_blocks->size()); + << changed_blocks->size()); /* Copy transforming liquid information @@ -1480,28 +1466,28 @@ void ServerMap::finishBlockMake( /* Set block as modified */ - block->raiseModified( - MOD_STATE_WRITE_NEEDED, MOD_REASON_EXPIRE_DAYNIGHTDIFF); + block->raiseModified(MOD_STATE_WRITE_NEEDED, + MOD_REASON_EXPIRE_DAYNIGHTDIFF); } /* Set central blocks as generated */ for (s16 x = bpmin.X; x <= bpmax.X; x++) - for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) { - MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z)); - if (!block) - continue; + for (s16 z = bpmin.Z; z <= bpmax.Z; z++) + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) { + MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z)); + if (!block) + continue; - block->setGenerated(true); - } + block->setGenerated(true); + } /* Save changed parts of map NOTE: Will be saved later. */ - // save(MOD_STATE_WRITE_AT_UNLOAD); + //save(MOD_STATE_WRITE_AT_UNLOAD); } MapSector *ServerMap::createSector(v2s16 p2d) @@ -1517,10 +1503,11 @@ 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) - throw InvalidPositionException( - "createSector(): pos. over max mapgen limit"); + if (p2d.X < -max_limit_bp || + p2d.X > max_limit_bp || + p2d.Y < -max_limit_bp || + p2d.Y > max_limit_bp) + throw InvalidPositionException("createSector(): pos. over max mapgen limit"); /* Generate blank sector @@ -1529,7 +1516,7 @@ MapSector *ServerMap::createSector(v2s16 p2d) sector = new MapSector(this, p2d, m_gamedef); // Sector position on map in nodes - // v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; + //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; /* Insert to container @@ -1649,14 +1636,13 @@ MapBlock * ServerMap::generateBlock( } #endif -MapBlock *ServerMap::createBlock(v3s16 p) +MapBlock * ServerMap::createBlock(v3s16 p) { /* Do not create over max mapgen limit */ if (blockpos_over_max_limit(p)) - throw InvalidPositionException( - "createBlock(): pos. over max mapgen limit"); + throw InvalidPositionException("createBlock(): pos. over max mapgen limit"); v2s16 p2d(p.X, p.Z); s16 block_y = p.Y; @@ -1671,7 +1657,7 @@ MapBlock *ServerMap::createBlock(v3s16 p) try { sector = createSector(p2d); } catch (InvalidPositionException &e) { - infostream << "createBlock: createSector() failed" << std::endl; + infostream<<"createBlock: createSector() failed"<getBlockNoCreateNoEx(block_y); if (block) { - if (block->isDummy()) + if(block->isDummy()) block->unDummify(); return block; } @@ -1691,7 +1677,7 @@ MapBlock *ServerMap::createBlock(v3s16 p) return block; } -MapBlock *ServerMap::emergeBlock(v3s16 p, bool create_blank) +MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank) { { MapBlock *block = getBlockNoCreateNoEx(p); @@ -1701,7 +1687,7 @@ MapBlock *ServerMap::emergeBlock(v3s16 p, bool create_blank) { MapBlock *block = loadBlock(p); - if (block) + if(block) return block; } @@ -1786,15 +1772,15 @@ s16 ServerMap::findGroundLevel(v2s16 p2d) s16 level = m_emerge->getGroundLevelAtPoint(p2d); return level; - // double level = base_rock_level_2d(m_seed, p2d) + AVERAGE_MUD_AMOUNT; - // return (s16)level; + //double level = base_rock_level_2d(m_seed, p2d) + AVERAGE_MUD_AMOUNT; + //return (s16)level; } void ServerMap::createDirs(const std::string &path) { if (!fs::CreateAllDirs(path)) { - m_dout << "ServerMap: Failed to create directory " - << "\"" << path << "\"" << std::endl; + m_dout<<"ServerMap: Failed to create directory " + <<"\""<getModified() >= (u32)save_level) { + if(block->getModified() >= (u32)save_level) { // Lazy beginSave() - if (!save_started) { + if(!save_started) { beginSave(); save_started = true; } @@ -1850,18 +1836,20 @@ void ServerMap::save(ModifiedState save_level) } } - if (save_started) + if(save_started) endSave(); /* Only print if something happened or saved whole map */ - if (save_level == MOD_STATE_CLEAN || block_count != 0) { - infostream << "ServerMap: Written: " << block_count << " blocks" - << ", " << block_count_all << " blocks in memory." - << std::endl; + if(save_level == MOD_STATE_CLEAN + || block_count != 0) { + infostream << "ServerMap: Written: " + << block_count << " blocks" + << ", " << block_count_all << " blocks in memory." + << std::endl; PrintInfo(infostream); // ServerMap/ClientMap: - infostream << "Blocks modified by: " << std::endl; + infostream<<"Blocks modified by: "< &dst) } MapDatabase *ServerMap::createDatabase( - const std::string &name, const std::string &savedir, Settings &conf) + const std::string &name, + const std::string &savedir, + Settings &conf) { if (name == "sqlite3") return new MapDatabaseSQLite3(savedir); if (name == "dummy") return new Database_Dummy(); -#if USE_LEVELDB + #if USE_LEVELDB if (name == "leveldb") return new Database_LevelDB(savedir); -#endif -#if USE_REDIS + #endif + #if USE_REDIS if (name == "redis") return new Database_Redis(conf); -#endif -#if USE_POSTGRESQL + #endif + #if USE_POSTGRESQL if (name == "postgresql") { std::string connect_string; conf.getNoEx("pgsql_connection", connect_string); return new MapDatabasePostgreSQL(connect_string); } -#endif + #endif throw BaseException(std::string("Database backend ") + name + " not supported."); } @@ -1938,8 +1928,8 @@ bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db) // Dummy blocks are not written if (block->isDummy()) { - warningstream << "saveBlock: Not writing dummy block " << PP(p3d) - << std::endl; + warningstream << "saveBlock: Not writing dummy block " + << PP(p3d) << std::endl; return true; } @@ -1951,7 +1941,7 @@ bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db) [1] data */ std::ostringstream o(std::ios_base::binary); - o.write((char *)&version, 1); + o.write((char*) &version, 1); block->serialize(o, version, true); bool ret = db->saveBlock(p3d, o.str()); @@ -1962,23 +1952,23 @@ bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db) return ret; } -void ServerMap::loadBlock( - std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load) +void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load) { try { std::istringstream is(*blob, std::ios_base::binary); u8 version = SER_FMT_VER_INVALID; - is.read((char *)&version, 1); + is.read((char*)&version, 1); - if (is.fail()) + if(is.fail()) throw SerializationError("ServerMap::loadBlock(): Failed" - " to read MapBlock version"); + " to read MapBlock version"); MapBlock *block = NULL; bool created_new = false; block = sector->getBlockNoCreateNoEx(p3d.Y); - if (block == NULL) { + if(block == NULL) + { block = sector->createBlankBlockNoInsert(p3d.Y); created_new = true; } @@ -1997,31 +1987,33 @@ void ServerMap::loadBlock( Save blocks loaded in old format in new format */ - // if(version < SER_FMT_VER_HIGHEST_READ || save_after_load) + //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load) // Only save if asked to; no need to update version - if (save_after_load) + if(save_after_load) saveBlock(block); // We just loaded it from, so it's up-to-date. block->resetModified(); - } catch (SerializationError &e) { - errorstream << "Invalid block data in database" - << " (" << p3d.X << "," << p3d.Y << "," << p3d.Z << ")" - << " (SerializationError): " << e.what() << std::endl; + } + catch(SerializationError &e) + { + errorstream<<"Invalid block data in database" + <<" ("<getBool("ignore_world_load_errors")) { - errorstream << "Ignoring block load error. Duck and cover! " - << "(ignore_world_load_errors)" << std::endl; + if(g_settings->getBool("ignore_world_load_errors")){ + errorstream<<"Ignoring block load error. Duck and cover! " + <<"(ignore_world_load_errors)"< modified_blocks; + std::map modified_blocks; // Fix lighting if necessary voxalgo::update_block_border_lighting(this, block, modified_blocks); if (!modified_blocks.empty()) { - // Modified lighting, send event + //Modified lighting, send event MapEditEvent event; event.type = MEET_OTHER; std::map::iterator it; - for (it = modified_blocks.begin(); it != modified_blocks.end(); - ++it) + for (it = modified_blocks.begin(); + it != modified_blocks.end(); ++it) event.modified_blocks.insert(it->first); dispatchEvent(event); } @@ -2078,11 +2070,11 @@ bool ServerMap::deleteBlock(v3s16 blockpos) void ServerMap::PrintInfo(std::ostream &out) { - out << "ServerMap: "; + out<<"ServerMap: "; } -bool ServerMap::repairBlockLight( - v3s16 blockpos, std::map *modified_blocks) +bool ServerMap::repairBlockLight(v3s16 blockpos, + std::map *modified_blocks) { MapBlock *block = emergeBlock(blockpos, false); if (!block || !block->isGenerated()) @@ -2091,12 +2083,14 @@ bool ServerMap::repairBlockLight( return true; } -MMVManip::MMVManip(Map *map) : VoxelManipulator(), m_map(map) +MMVManip::MMVManip(Map *map): + VoxelManipulator(), + m_map(map) { } -void MMVManip::initialEmerge( - v3s16 blockpos_min, v3s16 blockpos_max, bool load_if_inexistent) +void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max, + bool load_if_inexistent) { TimeTaker timer1("initialEmerge", &emerge_time); @@ -2104,92 +2098,84 @@ void MMVManip::initialEmerge( v3s16 p_min = blockpos_min; v3s16 p_max = blockpos_max; - VoxelArea block_area_nodes(p_min * MAP_BLOCKSIZE, - (p_max + 1) * MAP_BLOCKSIZE - v3s16(1, 1, 1)); + VoxelArea block_area_nodes + (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); - u32 size_MB = block_area_nodes.getVolume() * 4 / 1000000; - if (size_MB >= 1) { - infostream << "initialEmerge: area: "; + u32 size_MB = block_area_nodes.getVolume()*4/1000000; + if(size_MB >= 1) + { + infostream<<"initialEmerge: area: "; block_area_nodes.print(infostream); - infostream << " (" << size_MB << "MB)"; - infostream << std::endl; + infostream<<" ("<::iterator n; - n = m_loaded_blocks.find(p); - if (n != m_loaded_blocks.end()) - continue; + for(s32 z=p_min.Z; z<=p_max.Z; z++) + for(s32 y=p_min.Y; y<=p_max.Y; y++) + for(s32 x=p_min.X; x<=p_max.X; x++) + { + u8 flags = 0; + MapBlock *block; + v3s16 p(x,y,z); + std::map::iterator n; + n = m_loaded_blocks.find(p); + if(n != m_loaded_blocks.end()) + continue; - bool block_data_inexistent = false; - { - TimeTaker timer2( - "emerge load", &emerge_load_time); - - block = m_map->getBlockNoCreateNoEx(p); - if (!block || block->isDummy()) - block_data_inexistent = true; - else - block->copyTo(*this); - } + bool block_data_inexistent = false; + { + TimeTaker timer2("emerge load", &emerge_load_time); - if (block_data_inexistent) { + block = m_map->getBlockNoCreateNoEx(p); + if (!block || block->isDummy()) + block_data_inexistent = true; + else + block->copyTo(*this); + } - if (load_if_inexistent && - !blockpos_over_max_limit(p)) { - ServerMap *svrmap = (ServerMap *)m_map; - block = svrmap->emergeBlock(p, false); - if (block == NULL) - block = svrmap->createBlock(p); - block->copyTo(*this); - } else { - flags |= VMANIP_BLOCK_DATA_INEXIST; - - /* - Mark area inexistent - */ - VoxelArea a(p * MAP_BLOCKSIZE, - (p + 1) * MAP_BLOCKSIZE - - v3s16(1, 1, 1)); - // Fill with VOXELFLAG_NO_DATA - for (s32 z = a.MinEdge.Z; - z <= a.MaxEdge.Z; z++) - for (s32 y = a.MinEdge.Y; - y <= a.MaxEdge.Y; - y++) { - s32 i = m_area.index( - a.MinEdge.X, - y, z); - memset(&m_flags[i], - VOXELFLAG_NO_DATA, - MAP_BLOCKSIZE); - } - } - } - /*else if (block->getNode(0, 0, 0).getContent() == - CONTENT_IGNORE) - { - // Mark that block was loaded as blank - flags |= VMANIP_BLOCK_CONTAINS_CIGNORE; - }*/ + if(block_data_inexistent) + { - m_loaded_blocks[p] = flags; + if (load_if_inexistent && !blockpos_over_max_limit(p)) { + ServerMap *svrmap = (ServerMap *)m_map; + block = svrmap->emergeBlock(p, false); + if (block == NULL) + block = svrmap->createBlock(p); + block->copyTo(*this); + } else { + flags |= VMANIP_BLOCK_DATA_INEXIST; + + /* + Mark area inexistent + */ + VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + // Fill with VOXELFLAG_NO_DATA + for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) + for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) + { + s32 i = m_area.index(a.MinEdge.X,y,z); + memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE); + } } + } + /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE) + { + // Mark that block was loaded as blank + flags |= VMANIP_BLOCK_CONTAINS_CIGNORE; + }*/ + + m_loaded_blocks[p] = flags; + } m_is_dirty = false; } -void MMVManip::blitBackAll( - std::map *modified_blocks, bool overwrite_generated) +void MMVManip::blitBackAll(std::map *modified_blocks, + bool overwrite_generated) { - if (m_area.getExtent() == v3s16(0, 0, 0)) + if(m_area.getExtent() == v3s16(0,0,0)) return; /* @@ -2200,15 +2186,15 @@ void MMVManip::blitBackAll( MapBlock *block = m_map->getBlockNoCreateNoEx(p); bool existed = !(loaded_block.second & VMANIP_BLOCK_DATA_INEXIST); if (!existed || (block == NULL) || - (!overwrite_generated && block->isGenerated())) + (!overwrite_generated && block->isGenerated())) continue; block->copyFrom(*this); block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_VMANIP); - if (modified_blocks) + if(modified_blocks) (*modified_blocks)[p] = block; } } -// END +//END diff --git a/src/map.h b/src/map.h index d3df05f7f..4d9847063 100644 --- a/src/map.h +++ b/src/map.h @@ -58,8 +58,7 @@ struct BlockMakeData; #define MAPTYPE_SERVER 1 #define MAPTYPE_CLIENT 2 -enum MapEditEventType -{ +enum MapEditEventType{ // Node added (changed from air or something else to something) MEET_ADDNODE, // Node removed (changed to air) @@ -84,24 +83,25 @@ struct MapEditEvent VoxelArea getArea() const { - switch (type) { + switch(type){ case MEET_ADDNODE: return VoxelArea(p); case MEET_REMOVENODE: return VoxelArea(p); case MEET_SWAPNODE: return VoxelArea(p); - case MEET_BLOCK_NODE_METADATA_CHANGED: { - v3s16 np1 = p * MAP_BLOCKSIZE; - v3s16 np2 = np1 + v3s16(1, 1, 1) * MAP_BLOCKSIZE - v3s16(1, 1, 1); + case MEET_BLOCK_NODE_METADATA_CHANGED: + { + v3s16 np1 = p*MAP_BLOCKSIZE; + v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1); return VoxelArea(np1, np2); } - case MEET_OTHER: { + case MEET_OTHER: + { VoxelArea a; for (v3s16 p : modified_blocks) { - v3s16 np1 = p * MAP_BLOCKSIZE; - v3s16 np2 = np1 + v3s16(1, 1, 1) * MAP_BLOCKSIZE - - v3s16(1, 1, 1); + v3s16 np1 = p*MAP_BLOCKSIZE; + v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1); a.addPoint(np1); a.addPoint(np2); } @@ -122,16 +122,23 @@ class MapEventReceiver class Map /*: public NodeContainer*/ { public: + Map(std::ostream &dout, IGameDef *gamedef); virtual ~Map(); DISABLE_CLASS_COPY(Map); - virtual s32 mapType() const { return MAPTYPE_BASE; } + virtual s32 mapType() const + { + return MAPTYPE_BASE; + } /* Drop (client) or delete (server) the map. */ - virtual void drop() { delete this; } + virtual void drop() + { + delete this; + } void addEventReceiver(MapEventReceiver *event_receiver); void removeEventReceiver(MapEventReceiver *event_receiver); @@ -139,30 +146,28 @@ class Map /*: public NodeContainer*/ void dispatchEvent(const MapEditEvent &event); // On failure returns NULL - MapSector *getSectorNoGenerateNoLock(v2s16 p2d); + MapSector * getSectorNoGenerateNoLock(v2s16 p2d); // Same as the above (there exists no lock anymore) - MapSector *getSectorNoGenerate(v2s16 p2d); + MapSector * getSectorNoGenerate(v2s16 p2d); // Gets an existing sector or creates an empty one - // MapSector * getSectorCreate(v2s16 p2d); + //MapSector * getSectorCreate(v2s16 p2d); /* This is overloaded by ClientMap and ServerMap to allow their differing fetch methods. */ - virtual MapSector *emergeSector(v2s16 p) { return NULL; } + virtual MapSector * emergeSector(v2s16 p){ return NULL; } // Returns InvalidPositionException if not found - MapBlock *getBlockNoCreate(v3s16 p); + MapBlock * getBlockNoCreate(v3s16 p); // Returns NULL if not found - MapBlock *getBlockNoCreateNoEx(v3s16 p); + MapBlock * getBlockNoCreateNoEx(v3s16 p); /* Server overrides */ - virtual MapBlock *emergeBlock(v3s16 p, bool create_blank = true) - { - return getBlockNoCreateNoEx(p); - } + virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true) + { return getBlockNoCreateNoEx(p); } - inline const NodeDefManager *getNodeDefManager() { return m_nodedef; } + inline const NodeDefManager * getNodeDefManager() { return m_nodedef; } // Returns InvalidPositionException if not found bool isNodeUnderground(v3s16 p); @@ -170,7 +175,7 @@ class Map /*: public NodeContainer*/ bool isValidPosition(v3s16 p); // throws InvalidPositionException if not found - void setNode(v3s16 p, MapNode &n); + void setNode(v3s16 p, MapNode & n); // Returns a CONTENT_IGNORE node if not found // If is_valid_position is not NULL then this will be set to true if the @@ -181,9 +186,10 @@ class Map /*: public NodeContainer*/ These handle lighting but not faces. */ void addNodeAndUpdate(v3s16 p, MapNode n, - std::map &modified_blocks, + std::map &modified_blocks, bool remove_metadata = true); - void removeNodeAndUpdate(v3s16 p, std::map &modified_blocks); + void removeNodeAndUpdate(v3s16 p, + std::map &modified_blocks); /* Wrappers for the latter ones. @@ -209,13 +215,13 @@ class Map /*: public NodeContainer*/ Saves modified blocks before unloading on MAPTYPE_SERVER. */ void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks, - std::vector *unloaded_blocks = NULL); + std::vector *unloaded_blocks=NULL); /* Unloads all blocks with a zero refCount(). Saves modified blocks before unloading on MAPTYPE_SERVER. */ - void unloadUnreferencedBlocks(std::vector *unloaded_blocks = NULL); + void unloadUnreferencedBlocks(std::vector *unloaded_blocks=NULL); // Deletes sectors and their blocks from memory // Takes cache into account @@ -225,7 +231,7 @@ class Map /*: public NodeContainer*/ // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: " virtual void PrintInfo(std::ostream &out); - void transformLiquids(std::map &modified_blocks, + void transformLiquids(std::map & modified_blocks, ServerEnvironment *env); /* @@ -265,7 +271,7 @@ class Map /*: public NodeContainer*/ /* Misc. */ - std::map *getSectorsPtr() { return &m_sectors; } + std::map *getSectorsPtr(){return &m_sectors;} /* Variables @@ -274,7 +280,6 @@ class Map /*: public NodeContainer*/ void transforming_liquid_add(v3s16 p); bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes); - protected: friend class LuaVoxelManip; @@ -282,9 +287,9 @@ class Map /*: public NodeContainer*/ IGameDef *m_gamedef; - std::set m_event_receivers; + std::set m_event_receivers; - std::map m_sectors; + std::map m_sectors; // Be sure to set this to NULL when the cached sector is deleted MapSector *m_sector_cache = nullptr; @@ -297,10 +302,10 @@ class Map /*: public NodeContainer*/ const NodeDefManager *m_nodedef; bool determineAdditionalOcclusionCheck(const v3s16 &pos_camera, - const core::aabbox3d &block_bounds, v3s16 &check); - bool isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target, float step, - float stepfac, float start_offset, float end_offset, - u32 needed_count); + const core::aabbox3d &block_bounds, v3s16 &check); + bool isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target, + float step, float stepfac, float start_offset, float end_offset, + u32 needed_count); private: f32 m_transforming_liquid_loop_count_multiplier = 1.0f; @@ -321,11 +326,13 @@ class ServerMap : public Map /* savedir: directory to which map data should be saved */ - ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, - MetricsBackend *mb); + ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, MetricsBackend *mb); ~ServerMap(); - s32 mapType() const { return MAPTYPE_SERVER; } + s32 mapType() const + { + return MAPTYPE_SERVER; + } /* Get a sector from somewhere. @@ -340,8 +347,8 @@ class ServerMap : public Map */ bool blockpos_over_mapgen_limit(v3s16 p); bool initBlockMake(v3s16 blockpos, BlockMakeData *data); - void finishBlockMake( - BlockMakeData *data, std::map *changed_blocks); + void finishBlockMake(BlockMakeData *data, + std::map *changed_blocks); /* Get a block from somewhere. @@ -357,7 +364,7 @@ class ServerMap : public Map - Create blank filled with CONTENT_IGNORE */ - MapBlock *emergeBlock(v3s16 p, bool create_blank = true); + MapBlock *emergeBlock(v3s16 p, bool create_blank=true); /* Try to get a block. @@ -379,8 +386,7 @@ class ServerMap : public Map /* Database functions */ - static MapDatabase *createDatabase(const std::string &name, - const std::string &savedir, Settings &conf); + static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf); // Call these before and after saving of blocks void beginSave(); @@ -394,10 +400,9 @@ class ServerMap : public Map bool saveBlock(MapBlock *block); static bool saveBlock(MapBlock *block, MapDatabase *db); - MapBlock *loadBlock(v3s16 p); + MapBlock* loadBlock(v3s16 p); // Database version - void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, - bool save_after_load = false); + void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false); bool deleteBlock(v3s16 blockpos); @@ -406,7 +411,7 @@ class ServerMap : public Map // For debug printing virtual void PrintInfo(std::ostream &out); - bool isSavingEnabled() { return m_map_saving_enabled; } + bool isSavingEnabled(){ return m_map_saving_enabled; } u64 getSeed(); s16 getWaterLevel(); @@ -418,8 +423,8 @@ class ServerMap : public Map * Returns false if the block is not generated (so nothing * changed), true otherwise. */ - bool repairBlockLight( - v3s16 blockpos, std::map *modified_blocks); + bool repairBlockLight(v3s16 blockpos, + std::map *modified_blocks); MapSettingsManager settings_mgr; @@ -449,7 +454,8 @@ class ServerMap : public Map MetricCounterPtr m_save_time_counter; }; -#define VMANIP_BLOCK_DATA_INEXIST 1 + +#define VMANIP_BLOCK_DATA_INEXIST 1 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2 class MMVManip : public VoxelManipulator @@ -465,11 +471,11 @@ class MMVManip : public VoxelManipulator } void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max, - bool load_if_inexistent = true); + bool load_if_inexistent = true); // This is much faster with big chunks of generated data - void blitBackAll(std::map *modified_blocks, - bool overwrite_generated = true); + void blitBackAll(std::map * modified_blocks, + bool overwrite_generated = true); bool m_is_dirty = false; diff --git a/src/map_settings_manager.cpp b/src/map_settings_manager.cpp index 9be9194bc..4f070e910 100644 --- a/src/map_settings_manager.cpp +++ b/src/map_settings_manager.cpp @@ -25,21 +25,25 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "map_settings_manager.h" -MapSettingsManager::MapSettingsManager( - Settings *user_settings, const std::string &map_meta_path) : - m_map_meta_path(map_meta_path), - m_map_settings(new Settings()), m_user_settings(user_settings) +MapSettingsManager::MapSettingsManager(Settings *user_settings, + const std::string &map_meta_path): + m_map_meta_path(map_meta_path), + m_map_settings(new Settings()), + m_user_settings(user_settings) { assert(m_user_settings != NULL); } + MapSettingsManager::~MapSettingsManager() { delete m_map_settings; delete mapgen_params; } -bool MapSettingsManager::getMapSetting(const std::string &name, std::string *value_out) + +bool MapSettingsManager::getMapSetting( + const std::string &name, std::string *value_out) { if (m_map_settings->getNoEx(name, *value_out)) return true; @@ -51,15 +55,17 @@ bool MapSettingsManager::getMapSetting(const std::string &name, std::string *val return m_user_settings->getNoEx(name, *value_out); } + bool MapSettingsManager::getMapSettingNoiseParams( - const std::string &name, NoiseParams *value_out) + const std::string &name, NoiseParams *value_out) { return m_map_settings->getNoiseParams(name, *value_out) || - m_user_settings->getNoiseParams(name, *value_out); + m_user_settings->getNoiseParams(name, *value_out); } + bool MapSettingsManager::setMapSetting( - const std::string &name, const std::string &value, bool override_meta) + const std::string &name, const std::string &value, bool override_meta) { if (mapgen_params) return false; @@ -72,8 +78,9 @@ bool MapSettingsManager::setMapSetting( return true; } + bool MapSettingsManager::setMapSettingNoiseParams( - const std::string &name, const NoiseParams *value, bool override_meta) + const std::string &name, const NoiseParams *value, bool override_meta) { if (mapgen_params) return false; @@ -82,13 +89,14 @@ bool MapSettingsManager::setMapSettingNoiseParams( return true; } + bool MapSettingsManager::loadMapMeta() { std::ifstream is(m_map_meta_path.c_str(), std::ios_base::binary); if (!is.good()) { - errorstream << "loadMapMeta: could not open " << m_map_meta_path - << std::endl; + errorstream << "loadMapMeta: could not open " + << m_map_meta_path << std::endl; return false; } @@ -100,6 +108,7 @@ bool MapSettingsManager::loadMapMeta() return true; } + bool MapSettingsManager::saveMapMeta() { // If mapgen params haven't been created yet; abort @@ -108,7 +117,7 @@ bool MapSettingsManager::saveMapMeta() if (!fs::CreateAllDirs(fs::RemoveLastPathComponent(m_map_meta_path))) { errorstream << "saveMapMeta: could not create dirs to " - << m_map_meta_path; + << m_map_meta_path; return false; } @@ -125,14 +134,15 @@ bool MapSettingsManager::saveMapMeta() oss << "[end_of_params]\n"; if (!fs::safeWriteToFile(m_map_meta_path, oss.str())) { - errorstream << "saveMapMeta: could not write " << m_map_meta_path - << std::endl; + errorstream << "saveMapMeta: could not write " + << m_map_meta_path << std::endl; return false; } return true; } + MapgenParams *MapSettingsManager::makeMapgenParams() { if (mapgen_params) @@ -153,13 +163,12 @@ MapgenParams *MapSettingsManager::makeMapgenParams() // Now, get the mapgen type so we can create the appropriate MapgenParams std::string mg_name; - MapgenType mgtype = getMapSetting("mg_name", &mg_name) - ? Mapgen::getMapgenType(mg_name) - : MAPGEN_DEFAULT; + MapgenType mgtype = getMapSetting("mg_name", &mg_name) ? + Mapgen::getMapgenType(mg_name) : MAPGEN_DEFAULT; if (mgtype == MAPGEN_INVALID) { - errorstream << "EmergeManager: mapgen '" << mg_name - << "' not valid; falling back to " - << Mapgen::getMapgenName(MAPGEN_DEFAULT) << std::endl; + errorstream << "EmergeManager: mapgen '" << mg_name << + "' not valid; falling back to " << + Mapgen::getMapgenName(MAPGEN_DEFAULT) << std::endl; mgtype = MAPGEN_DEFAULT; } diff --git a/src/map_settings_manager.h b/src/map_settings_manager.h index e7383cec5..5baa38455 100644 --- a/src/map_settings_manager.h +++ b/src/map_settings_manager.h @@ -42,10 +42,10 @@ struct MapgenParams; to whichever Map-related objects that may require it. - Save these active settings to the metadata file when requested */ -class MapSettingsManager -{ +class MapSettingsManager { public: - MapSettingsManager(Settings *user_settings, const std::string &map_meta_path); + MapSettingsManager(Settings *user_settings, + const std::string &map_meta_path); ~MapSettingsManager(); // Finalized map generation parameters @@ -53,16 +53,17 @@ class MapSettingsManager bool getMapSetting(const std::string &name, std::string *value_out); - bool getMapSettingNoiseParams(const std::string &name, NoiseParams *value_out); + bool getMapSettingNoiseParams( + const std::string &name, NoiseParams *value_out); // Note: Map config becomes read-only after makeMapgenParams() gets called // (i.e. mapgen_params is non-NULL). Attempts to set map config after // params have been finalized will result in failure. - bool setMapSetting(const std::string &name, const std::string &value, - bool override_meta = false); + bool setMapSetting(const std::string &name, + const std::string &value, bool override_meta = false); - bool setMapSettingNoiseParams(const std::string &name, const NoiseParams *value, - bool override_meta = false); + bool setMapSettingNoiseParams(const std::string &name, + const NoiseParams *value, bool override_meta = false); bool loadMapMeta(); bool saveMapMeta(); diff --git a/src/mapblock.cpp b/src/mapblock.cpp index ccee71a7e..5b755b7a6 100644 --- a/src/mapblock.cpp +++ b/src/mapblock.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gamedef.h" #include "log.h" #include "nameidmapping.h" -#include "content_mapnode.h" // For legacy name-id mapping +#include "content_mapnode.h" // For legacy name-id mapping #include "content_nodemeta.h" // For legacy deserialization #include "serialization.h" #ifndef SERVER @@ -39,34 +39,37 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/basic_macros.h" static const char *modified_reason_strings[] = { - "initial", - "reallocate", - "setIsUnderground", - "setLightingExpired", - "setGenerated", - "setNode", - "setNodeNoCheck", - "setTimestamp", - "NodeMetaRef::reportMetadataChange", - "clearAllObjects", - "Timestamp expired (step)", - "addActiveObjectRaw", - "removeRemovedObjects/remove", - "removeRemovedObjects/deactivate", - "Stored list cleared in activateObjects due to overflow", - "deactivateFarObjects: Static data moved in", - "deactivateFarObjects: Static data moved out", - "deactivateFarObjects: Static data changed considerably", - "finishBlockMake: expireDayNightDiff", - "unknown", + "initial", + "reallocate", + "setIsUnderground", + "setLightingExpired", + "setGenerated", + "setNode", + "setNodeNoCheck", + "setTimestamp", + "NodeMetaRef::reportMetadataChange", + "clearAllObjects", + "Timestamp expired (step)", + "addActiveObjectRaw", + "removeRemovedObjects/remove", + "removeRemovedObjects/deactivate", + "Stored list cleared in activateObjects due to overflow", + "deactivateFarObjects: Static data moved in", + "deactivateFarObjects: Static data moved out", + "deactivateFarObjects: Static data changed considerably", + "finishBlockMake: expireDayNightDiff", + "unknown", }; + /* MapBlock */ -MapBlock::MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy) : - m_parent(parent), m_pos(pos), m_pos_relative(pos * MAP_BLOCKSIZE), +MapBlock::MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy): + m_parent(parent), + m_pos(pos), + m_pos_relative(pos * MAP_BLOCKSIZE), m_gamedef(gamedef) { if (!dummy) @@ -114,7 +117,7 @@ std::string MapBlock::getModifiedReasonString() std::string reason; const u32 ubound = MYMIN(sizeof(m_modified_reason) * CHAR_BIT, - ARRLEN(modified_reason_strings)); + ARRLEN(modified_reason_strings)); for (u32 i = 0; i != ubound; i++) { if ((m_modified_reason & (1 << i)) == 0) @@ -130,22 +133,25 @@ std::string MapBlock::getModifiedReasonString() return reason; } + void MapBlock::copyTo(VoxelManipulator &dst) { v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); - VoxelArea data_area(v3s16(0, 0, 0), data_size - v3s16(1, 1, 1)); + VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1)); // Copy from data to VoxelManipulator - dst.copyFrom(data, data_area, v3s16(0, 0, 0), getPosRelative(), data_size); + dst.copyFrom(data, data_area, v3s16(0,0,0), + getPosRelative(), data_size); } void MapBlock::copyFrom(VoxelManipulator &dst) { v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); - VoxelArea data_area(v3s16(0, 0, 0), data_size - v3s16(1, 1, 1)); + VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1)); // Copy from VoxelManipulator to data - dst.copyTo(data, data_area, v3s16(0, 0, 0), getPosRelative(), data_size); + dst.copyTo(data, data_area, v3s16(0,0,0), + getPosRelative(), data_size); } void MapBlock::actuallyUpdateDayNightDiff() @@ -214,21 +220,25 @@ void MapBlock::expireDayNightDiff() s16 MapBlock::getGroundLevel(v2s16 p2d) { - if (isDummy()) + if(isDummy()) return -3; - try { - s16 y = MAP_BLOCKSIZE - 1; - for (; y >= 0; y--) { + try + { + s16 y = MAP_BLOCKSIZE-1; + for(; y>=0; y--) + { MapNode n = getNodeRef(p2d.X, y, p2d.Y); if (m_gamedef->ndef()->get(n).walkable) { - if (y == MAP_BLOCKSIZE - 1) + if(y == MAP_BLOCKSIZE-1) return -2; return y; } } return -1; - } catch (InvalidPositionException &e) { + } + catch(InvalidPositionException &e) + { return -3; } } @@ -243,8 +253,8 @@ s16 MapBlock::getGroundLevel(v2s16 p2d) // a speedup of 4 for one of the major time consuming functions on storing // mapblocks. static content_t getBlockNodeIdMapping_mapping[USHRT_MAX + 1]; -static void getBlockNodeIdMapping( - NameIdMapping *nimap, MapNode *nodes, const NodeDefManager *nodedef) +static void getBlockNodeIdMapping(NameIdMapping *nimap, MapNode *nodes, + const NodeDefManager *nodedef) { memset(getBlockNodeIdMapping_mapping, 0xFF, (USHRT_MAX + 1) * sizeof(content_t)); @@ -257,7 +267,9 @@ static void getBlockNodeIdMapping( // Try to find an existing mapping if (getBlockNodeIdMapping_mapping[global_id] != 0xFFFF) { id = getBlockNodeIdMapping_mapping[global_id]; - } else { + } + else + { // We have to assign a new mapping id = id_counter++; getBlockNodeIdMapping_mapping[global_id] = id; @@ -275,15 +287,14 @@ static void getBlockNodeIdMapping( } for (u16 unknown_content : unknown_contents) { errorstream << "getBlockNodeIdMapping(): IGNORING ERROR: " - << "Name for node id " << unknown_content << " not known" - << std::endl; + << "Name for node id " << unknown_content << " not known" << std::endl; } } // Correct ids in the block to match nodedef based on names. // Unknown ones are added to nodedef. // Will not update itself to match id-name pairs in nodedef. -static void correctBlockNodeIds( - const NameIdMapping *nimap, MapNode *nodes, IGameDef *gamedef) +static void correctBlockNodeIds(const NameIdMapping *nimap, MapNode *nodes, + IGameDef *gamedef) { const NodeDefManager *nodedef = gamedef->ndef(); // This means the block contains incorrect ids, and we contain @@ -299,10 +310,10 @@ static void correctBlockNodeIds( for (u32 i = 0; i < MapBlock::nodecount; i++) { content_t local_id = nodes[i].getContent(); - // If previous node local_id was found and same than before, don't lookup - // maps apply directly previous resolved id This permits to massively - // improve loading performance when nodes are similar example: - // default:air, default:stone are massively present + // If previous node local_id was found and same than before, don't lookup maps + // apply directly previous resolved id + // This permits to massively improve loading performance when nodes are similar + // example: default:air, default:stone are massively present if (previous_exists && local_id == previous_local_id) { nodes[i].setContent(previous_global_id); continue; @@ -332,21 +343,21 @@ static void correctBlockNodeIds( previous_exists = true; } - for (const content_t c : unnamed_contents) { + for (const content_t c: unnamed_contents) { errorstream << "correctBlockNodeIds(): IGNORING ERROR: " - << "Block contains id " << c << " with no name mapping" - << std::endl; + << "Block contains id " << c + << " with no name mapping" << std::endl; } - for (const std::string &node_name : unallocatable_contents) { + for (const std::string &node_name: unallocatable_contents) { errorstream << "correctBlockNodeIds(): IGNORING ERROR: " - << "Could not allocate global id for node name \"" - << node_name << "\"" << std::endl; + << "Could not allocate global id for node name \"" + << node_name << "\"" << std::endl; } } void MapBlock::serialize(std::ostream &os, u8 version, bool disk) { - if (!ser_ver_supported(version)) + if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapBlock format not supported"); if (!data) @@ -356,9 +367,9 @@ void MapBlock::serialize(std::ostream &os, u8 version, bool disk) // First byte u8 flags = 0; - if (is_underground) + if(is_underground) flags |= 0x01; - if (getDayNightDiff()) + if(getDayNightDiff()) flags |= 0x02; if (!m_generated) flags |= 0x08; @@ -371,9 +382,10 @@ void MapBlock::serialize(std::ostream &os, u8 version, bool disk) Bulk node data */ NameIdMapping nimap; - if (disk) { + if(disk) + { MapNode *tmp_nodes = new MapNode[nodecount]; - for (u32 i = 0; i < nodecount; i++) + for(u32 i=0; indef()); @@ -381,16 +393,18 @@ void MapBlock::serialize(std::ostream &os, u8 version, bool disk) u8 params_width = 2; writeU8(os, content_width); writeU8(os, params_width); - MapNode::serializeBulk(os, version, tmp_nodes, nodecount, content_width, - params_width, true); + MapNode::serializeBulk(os, version, tmp_nodes, nodecount, + content_width, params_width, true); delete[] tmp_nodes; - } else { + } + else + { u8 content_width = 2; u8 params_width = 2; writeU8(os, content_width); writeU8(os, params_width); - MapNode::serializeBulk(os, version, data, nodecount, content_width, - params_width, true); + MapNode::serializeBulk(os, version, data, nodecount, + content_width, params_width, true); } /* @@ -403,8 +417,9 @@ void MapBlock::serialize(std::ostream &os, u8 version, bool disk) /* Data that goes to disk, but not the network */ - if (disk) { - if (version <= 24) { + if(disk) + { + if(version <= 24){ // Node timers m_node_timers.serialize(os, version); } @@ -418,7 +433,7 @@ void MapBlock::serialize(std::ostream &os, u8 version, bool disk) // Write block-specific node definition id mapping nimap.serialize(os); - if (version >= 25) { + if(version >= 25){ // Node timers m_node_timers.serialize(os, version); } @@ -436,14 +451,15 @@ void MapBlock::serializeNetworkSpecific(std::ostream &os) void MapBlock::deSerialize(std::istream &is, u8 version, bool disk) { - if (!ser_ver_supported(version)) + if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapBlock format not supported"); - TRACESTREAM(<< "MapBlock::deSerialize " << PP(getPos()) << std::endl); + TRACESTREAM(<<"MapBlock::deSerialize "<= 23) m_node_metadata.deSerialize(iss, m_gamedef->idef()); else - content_nodemeta_deserialize_legacy(iss, &m_node_metadata, - &m_node_timers, m_gamedef->idef()); - } catch (SerializationError &e) { - warningstream << "MapBlock::deSerialize(): Ignoring an error" - << " while deserializing node metadata at (" << PP(getPos()) - << ": " << e.what() << std::endl; + content_nodemeta_deserialize_legacy(iss, + &m_node_metadata, &m_node_timers, + m_gamedef->idef()); + } catch(SerializationError &e) { + warningstream<<"MapBlock::deSerialize(): Ignoring an error" + <<" while deserializing node metadata at (" + <= 25) { - TRACESTREAM(<< "MapBlock::deSerialize " << PP(getPos()) - << ": Node timers (ver>=25)" << std::endl); + if(version >= 25){ + TRACESTREAM(<<"MapBlock::deSerialize "<=25)"<= 18) + if(version >= 18) m_generated = (flags & 0x08) == 0; // Uncompress data @@ -635,15 +651,14 @@ void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk) decompress(is, os, version); std::string s = os.str(); if (s.size() != nodecount * 3) - throw SerializationError(std::string(FUNCTION_NAME) + - ": decompress resulted in size other " - "than nodecount*3"); + throw SerializationError(std::string(FUNCTION_NAME) + + ": decompress resulted in size other than nodecount*3"); // deserialize nodes from buffer for (u32 i = 0; i < nodecount; i++) { - databuf_nodelist[i * ser_length] = s[i]; - databuf_nodelist[i * ser_length + 1] = s[i + nodecount]; - databuf_nodelist[i * ser_length + 2] = s[i + nodecount * 2]; + databuf_nodelist[i*ser_length] = s[i]; + databuf_nodelist[i*ser_length + 1] = s[i+nodecount]; + databuf_nodelist[i*ser_length + 2] = s[i+nodecount*2]; } /* @@ -654,26 +669,22 @@ void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk) try { if (version <= 15) { std::string data = deSerializeString(is); - std::istringstream iss( - data, std::ios_base::binary); + std::istringstream iss(data, std::ios_base::binary); content_nodemeta_deserialize_legacy(iss, - &m_node_metadata, &m_node_timers, - m_gamedef->idef()); + &m_node_metadata, &m_node_timers, + m_gamedef->idef()); } else { - // std::string data = deSerializeLongString(is); + //std::string data = deSerializeLongString(is); std::ostringstream oss(std::ios_base::binary); decompressZlib(is, oss); - std::istringstream iss( - oss.str(), std::ios_base::binary); + std::istringstream iss(oss.str(), std::ios_base::binary); content_nodemeta_deserialize_legacy(iss, - &m_node_metadata, &m_node_timers, - m_gamedef->idef()); + &m_node_metadata, &m_node_timers, + m_gamedef->idef()); } - } catch (SerializationError &e) { - warningstream << "MapBlock::deSerialize(): Ignoring an " - "error" - << " while deserializing node metadata" - << std::endl; + } catch(SerializationError &e) { + warningstream<<"MapBlock::deSerialize(): Ignoring an error" + <<" while deserializing node metadata"<= 9) { u16 count = readU16(is); // Not supported and length not known if count is not 0 - if (count != 0) { - warningstream << "MapBlock::deSerialize_pre22(): " - << "Ignoring stuff coming at and after MBOs" - << std::endl; + if(count != 0){ + warningstream<<"MapBlock::deSerialize_pre22(): " + <<"Ignoring stuff coming at and after MBOs"<= 21) { nimap.deSerialize(is); - // Else set the legacy mapping + // Else set the legacy mapping } else { content_mapnode_get_name_id_mapping(&nimap); } correctBlockNodeIds(&nimap, data, m_gamedef); } + // Legacy data changes // This code has to convert from pre-22 to post-22 format. const NodeDefManager *nodedef = m_gamedef->ndef(); - for (u32 i = 0; i < nodecount; i++) { + for(u32 i=0; iget(data[i].getContent()); // Mineral - if (nodedef->getId("default:stone") == data[i].getContent() && - data[i].getParam1() == 1) { + if(nodedef->getId("default:stone") == data[i].getContent() + && data[i].getParam1() == 1) + { data[i].setContent(nodedef->getId("default:stone_with_coal")); data[i].setParam1(0); - } else if (nodedef->getId("default:stone") == data[i].getContent() && - data[i].getParam1() == 2) { + } + else if(nodedef->getId("default:stone") == data[i].getContent() + && data[i].getParam1() == 2) + { data[i].setContent(nodedef->getId("default:stone_with_iron")); data[i].setParam1(0); } // facedir_simple - if (f.legacy_facedir_simple) { + if(f.legacy_facedir_simple) + { data[i].setParam2(data[i].getParam1()); data[i].setParam1(0); } // wall_mounted - if (f.legacy_wallmounted) { - u8 wallmounted_new_to_old[8] = { - 0x04, 0x08, 0x01, 0x02, 0x10, 0x20, 0, 0}; + if(f.legacy_wallmounted) + { + u8 wallmounted_new_to_old[8] = {0x04, 0x08, 0x01, 0x02, 0x10, 0x20, 0, 0}; u8 dir_old_format = data[i].getParam2(); u8 dir_new_format = 0; - for (u8 j = 0; j < 8; j++) { - if ((dir_old_format & wallmounted_new_to_old[j]) != 0) { + for(u8 j=0; j<8; j++) + { + if((dir_old_format & wallmounted_new_to_old[j]) != 0) + { dir_new_format = j; break; } @@ -759,6 +777,7 @@ void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk) data[i].setParam2(dir_new_format); } } + } /* @@ -766,7 +785,7 @@ void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk) */ std::string analyze_block(MapBlock *block) { - if (block == NULL) + if(block == NULL) return "NULL"; std::ostringstream desc; @@ -774,78 +793,84 @@ std::string analyze_block(MapBlock *block) v3s16 p = block->getPos(); char spos[25]; porting::mt_snprintf(spos, sizeof(spos), "(%2d,%2d,%2d), ", p.X, p.Y, p.Z); - desc << spos; + desc<getModified()) { + switch(block->getModified()) + { case MOD_STATE_CLEAN: - desc << "CLEAN, "; + desc<<"CLEAN, "; break; case MOD_STATE_WRITE_AT_UNLOAD: - desc << "WRITE_AT_UNLOAD, "; + desc<<"WRITE_AT_UNLOAD, "; break; case MOD_STATE_WRITE_NEEDED: - desc << "WRITE_NEEDED, "; + desc<<"WRITE_NEEDED, "; break; default: - desc << "unknown getModified()=" + itos(block->getModified()) + ", "; + desc<<"unknown getModified()="+itos(block->getModified())+", "; } - if (block->isGenerated()) - desc << "is_gen [X], "; + if(block->isGenerated()) + desc<<"is_gen [X], "; else - desc << "is_gen [ ], "; + desc<<"is_gen [ ], "; - if (block->getIsUnderground()) - desc << "is_ug [X], "; + if(block->getIsUnderground()) + desc<<"is_ug [X], "; else - desc << "is_ug [ ], "; + desc<<"is_ug [ ], "; - desc << "lighting_complete: " << block->getLightingComplete() << ", "; + desc<<"lighting_complete: "<getLightingComplete()<<", "; - if (block->isDummy()) { - desc << "Dummy, "; - } else { + if(block->isDummy()) + { + desc<<"Dummy, "; + } + else + { bool full_ignore = true; bool some_ignore = false; bool full_air = true; bool some_air = false; - for (s16 z0 = 0; z0 < MAP_BLOCKSIZE; z0++) - for (s16 y0 = 0; y0 < MAP_BLOCKSIZE; y0++) - for (s16 x0 = 0; x0 < MAP_BLOCKSIZE; x0++) { - v3s16 p(x0, y0, z0); - MapNode n = block->getNodeNoEx(p); - content_t c = n.getContent(); - if (c == CONTENT_IGNORE) - some_ignore = true; - else - full_ignore = false; - if (c == CONTENT_AIR) - some_air = true; - else - full_air = false; - } + for(s16 z0=0; z0getNodeNoEx(p); + content_t c = n.getContent(); + if(c == CONTENT_IGNORE) + some_ignore = true; + else + full_ignore = false; + if(c == CONTENT_AIR) + some_air = true; + else + full_air = false; + } - desc << "content {"; + desc<<"content {"; std::ostringstream ss; - if (full_ignore) - ss << "IGNORE (full), "; - else if (some_ignore) - ss << "IGNORE, "; + if(full_ignore) + ss<<"IGNORE (full), "; + else if(some_ignore) + ss<<"IGNORE, "; - if (full_air) - ss << "AIR (full), "; - else if (some_air) - ss << "AIR, "; + if(full_air) + ss<<"AIR (full), "; + else if(some_air) + ss<<"AIR, "; - if (ss.str().size() >= 2) - desc << ss.str().substr(0, ss.str().size() - 2); + if(ss.str().size()>=2) + desc< m_modified) { m_modified = mod; @@ -112,9 +118,15 @@ class MapBlock contents_cached = false; } - inline u32 getModified() { return m_modified; } + inline u32 getModified() + { + return m_modified; + } - inline u32 getModifiedReason() { return m_modified_reason; } + inline u32 getModifiedReason() + { + return m_modified_reason; + } std::string getModifiedReasonString(); @@ -128,7 +140,10 @@ class MapBlock //// Flags //// - inline bool isDummy() { return !data; } + inline bool isDummy() + { + return !data; + } inline void unDummify() { @@ -137,7 +152,10 @@ class MapBlock } // is_underground getter/setter - inline bool getIsUnderground() { return is_underground; } + inline bool getIsUnderground() + { + return is_underground; + } inline void setIsUnderground(bool a_is_underground) { @@ -149,14 +167,17 @@ class MapBlock { if (newflags != m_lighting_complete) { m_lighting_complete = newflags; - raiseModified(MOD_STATE_WRITE_NEEDED, - MOD_REASON_SET_LIGHTING_COMPLETE); + raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_LIGHTING_COMPLETE); } } - inline u16 getLightingComplete() { return m_lighting_complete; } + inline u16 getLightingComplete() + { + return m_lighting_complete; + } - inline void setLightingComplete(LightBank bank, u8 direction, bool is_complete) + inline void setLightingComplete(LightBank bank, u8 direction, + bool is_complete) { assert(direction >= 0 && direction <= 5); if (bank == LIGHTBANK_NIGHT) { @@ -180,7 +201,10 @@ class MapBlock return (m_lighting_complete & (1 << direction)) != 0; } - inline bool isGenerated() { return m_generated; } + inline bool isGenerated() + { + return m_generated; + } inline void setGenerated(bool b) { @@ -194,17 +218,22 @@ class MapBlock //// Position stuff //// - inline v3s16 getPos() { return m_pos; } + inline v3s16 getPos() + { + return m_pos; + } - inline v3s16 getPosRelative() { return m_pos_relative; } + inline v3s16 getPosRelative() + { + return m_pos_relative; + } inline core::aabbox3d getBox() { return core::aabbox3d(getPosRelative(), - getPosRelative() + - v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, - MAP_BLOCKSIZE) - - v3s16(1, 1, 1)); + getPosRelative() + + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE) + - v3s16(1,1,1)); } //// @@ -213,11 +242,16 @@ class MapBlock inline bool isValidPosition(s16 x, s16 y, s16 z) { - return data && x >= 0 && x < MAP_BLOCKSIZE && y >= 0 && - y < MAP_BLOCKSIZE && z >= 0 && z < MAP_BLOCKSIZE; + return data + && x >= 0 && x < MAP_BLOCKSIZE + && y >= 0 && y < MAP_BLOCKSIZE + && z >= 0 && z < MAP_BLOCKSIZE; } - inline bool isValidPosition(v3s16 p) { return isValidPosition(p.X, p.Y, p.Z); } + inline bool isValidPosition(v3s16 p) + { + return isValidPosition(p.X, p.Y, p.Z); + } inline MapNode getNode(s16 x, s16 y, s16 z, bool *valid_position) { @@ -240,7 +274,7 @@ class MapBlock return getNode(p.X, p.Y, p.Z, &is_valid); } - inline void setNode(s16 x, s16 y, s16 z, MapNode &n) + inline void setNode(s16 x, s16 y, s16 z, MapNode & n) { if (!isValidPosition(x, y, z)) throw InvalidPositionException(); @@ -249,7 +283,10 @@ class MapBlock raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE); } - inline void setNode(v3s16 p, MapNode &n) { setNode(p.X, p.Y, p.Z, n); } + inline void setNode(v3s16 p, MapNode & n) + { + setNode(p.X, p.Y, p.Z, n); + } //// //// Non-checking variants of the above @@ -285,7 +322,7 @@ class MapBlock return getNodeUnsafe(p.X, p.Y, p.Z); } - inline void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode &n) + inline void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n) { if (!data) throw InvalidPositionException(); @@ -294,7 +331,7 @@ class MapBlock raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE_NO_CHECK); } - inline void setNodeNoCheck(v3s16 p, MapNode &n) + inline void setNodeNoCheck(v3s16 p, MapNode & n) { setNodeNoCheck(p.X, p.Y, p.Z, n); } @@ -303,14 +340,14 @@ class MapBlock // is not valid on this MapBlock. bool isValidPositionParent(v3s16 p); MapNode getNodeParent(v3s16 p, bool *is_valid_position = NULL); - void setNodeParent(v3s16 p, MapNode &n); + void setNodeParent(v3s16 p, MapNode & n); inline void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node) { for (u16 z = 0; z < d; z++) - for (u16 y = 0; y < h; y++) - for (u16 x = 0; x < w; x++) - setNode(x0 + x, y0 + y, z0 + z, node); + for (u16 y = 0; y < h; y++) + for (u16 x = 0; x < w; x++) + setNode(x0 + x, y0 + y, z0 + z, node); } // Copies data to VoxelManipulator to getPosRelative() @@ -361,43 +398,82 @@ class MapBlock raiseModified(MOD_STATE_WRITE_AT_UNLOAD, MOD_REASON_SET_TIMESTAMP); } - inline void setTimestampNoChangedFlag(u32 time) { m_timestamp = time; } + inline void setTimestampNoChangedFlag(u32 time) + { + m_timestamp = time; + } - inline u32 getTimestamp() { return m_timestamp; } + inline u32 getTimestamp() + { + return m_timestamp; + } - inline u32 getDiskTimestamp() { return m_disk_timestamp; } + inline u32 getDiskTimestamp() + { + return m_disk_timestamp; + } //// //// Usage timer (see m_usage_timer) //// - inline void resetUsageTimer() { m_usage_timer = 0; } + inline void resetUsageTimer() + { + m_usage_timer = 0; + } - inline void incrementUsageTimer(float dtime) { m_usage_timer += dtime; } + inline void incrementUsageTimer(float dtime) + { + m_usage_timer += dtime; + } - inline float getUsageTimer() { return m_usage_timer; } + inline float getUsageTimer() + { + return m_usage_timer; + } //// //// Reference counting (see m_refcount) //// - inline void refGrab() { m_refcount++; } + inline void refGrab() + { + m_refcount++; + } - inline void refDrop() { m_refcount--; } + inline void refDrop() + { + m_refcount--; + } - inline int refGet() { return m_refcount; } + inline int refGet() + { + return m_refcount; + } //// //// Node Timers //// - inline NodeTimer getNodeTimer(const v3s16 &p) { return m_node_timers.get(p); } + inline NodeTimer getNodeTimer(const v3s16 &p) + { + return m_node_timers.get(p); + } - inline void removeNodeTimer(const v3s16 &p) { m_node_timers.remove(p); } + inline void removeNodeTimer(const v3s16 &p) + { + m_node_timers.remove(p); + } - inline void setNodeTimer(const NodeTimer &t) { m_node_timers.set(t); } + inline void setNodeTimer(const NodeTimer &t) + { + m_node_timers.set(t); + } - inline void clearNodeTimers() { m_node_timers.clear(); } + inline void clearNodeTimers() + { + m_node_timers.clear(); + } //// //// Serialization @@ -413,7 +489,6 @@ class MapBlock void serializeNetworkSpecific(std::ostream &os); void deSerializeNetworkSpecific(std::istream &is); - private: /* Private methods @@ -433,7 +508,10 @@ class MapBlock return data[z * zstride + y * ystride + x]; } - inline MapNode &getNodeRef(v3s16 &p) { return getNodeRef(p.X, p.Y, p.Z); } + inline MapNode &getNodeRef(v3s16 &p) + { + return getNodeRef(p.X, p.Y, p.Z); + } public: /* @@ -472,12 +550,11 @@ class MapBlock v3s16 m_pos; /* This is the precalculated m_pos_relative value - * This caches the value, improving performance by removing 3 s16 multiplications - * at runtime on each getPosRelative call - * For a 5 minutes runtime with valgrind this removes 3 * 19M s16 multiplications - * The gain can be estimated in Release Build to 3 * 100M multiply operations for - * 5 mins - */ + * This caches the value, improving performance by removing 3 s16 multiplications + * at runtime on each getPosRelative call + * For a 5 minutes runtime with valgrind this removes 3 * 19M s16 multiplications + * The gain can be estimated in Release Build to 3 * 100M multiply operations for 5 mins + */ v3s16 m_pos_relative; IGameDef *m_gamedef; @@ -513,7 +590,7 @@ class MapBlock * nothing, nothing, nothing, nothing, * night X-, night Y-, night Z-, night Z+, night Y+, night X+, * day X-, day Y-, day Z-, day Z+, day Y+, day X+. - */ + */ u16 m_lighting_complete = 0xFFFF; // Whether day and night lighting differs @@ -543,20 +620,28 @@ class MapBlock int m_refcount = 0; }; -typedef std::vector MapBlockVect; +typedef std::vector MapBlockVect; inline bool objectpos_over_limit(v3f p) { const float max_limit_bs = MAX_MAP_GENERATION_LIMIT * BS; - return p.X < -max_limit_bs || p.X > max_limit_bs || p.Y < -max_limit_bs || - p.Y > max_limit_bs || p.Z < -max_limit_bs || p.Z > max_limit_bs; + return p.X < -max_limit_bs || + p.X > max_limit_bs || + p.Y < -max_limit_bs || + p.Y > max_limit_bs || + p.Z < -max_limit_bs || + p.Z > max_limit_bs; } inline bool blockpos_over_max_limit(v3s16 p) { const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE; - return p.X < -max_limit_bp || p.X > max_limit_bp || p.Y < -max_limit_bp || - p.Y > max_limit_bp || p.Z < -max_limit_bp || p.Z > max_limit_bp; + return p.X < -max_limit_bp || + p.X > max_limit_bp || + p.Y < -max_limit_bp || + p.Y > max_limit_bp || + p.Z < -max_limit_bp || + p.Z > max_limit_bp; } /* diff --git a/src/mapgen/cavegen.cpp b/src/mapgen/cavegen.cpp index a51476135..340079821 100644 --- a/src/mapgen/cavegen.cpp +++ b/src/mapgen/cavegen.cpp @@ -32,13 +32,14 @@ with this program; if not, write to the Free Software Foundation, Inc., // TODO Remove this. Cave liquids are now defined and located using biome definitions static NoiseParams nparams_caveliquids(0, 1, v3f(150.0, 150.0, 150.0), 776, 3, 0.6, 2.0); + //// //// CavesNoiseIntersection //// -CavesNoiseIntersection::CavesNoiseIntersection(const NodeDefManager *nodedef, - BiomeManager *biomemgr, v3s16 chunksize, NoiseParams *np_cave1, - NoiseParams *np_cave2, s32 seed, float cave_width) +CavesNoiseIntersection::CavesNoiseIntersection( + const NodeDefManager *nodedef, BiomeManager *biomemgr, v3s16 chunksize, + NoiseParams *np_cave1, NoiseParams *np_cave2, s32 seed, float cave_width) { assert(nodedef); assert(biomemgr); @@ -49,7 +50,7 @@ CavesNoiseIntersection::CavesNoiseIntersection(const NodeDefManager *nodedef, m_csize = chunksize; m_cave_width = cave_width; - m_ystride = m_csize.X; + m_ystride = m_csize.X; m_zstride_1d = m_csize.X * (m_csize.Y + 1); // Noises are created using 1-down overgeneration @@ -59,14 +60,16 @@ CavesNoiseIntersection::CavesNoiseIntersection(const NodeDefManager *nodedef, noise_cave2 = new Noise(np_cave2, seed, m_csize.X, m_csize.Y + 1, m_csize.Z); } + CavesNoiseIntersection::~CavesNoiseIntersection() { delete noise_cave1; delete noise_cave2; } -void CavesNoiseIntersection::generateCaves( - MMVManip *vm, v3s16 nmin, v3s16 nmax, biome_t *biomemap) + +void CavesNoiseIntersection::generateCaves(MMVManip *vm, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { assert(vm); assert(biomemap); @@ -75,120 +78,114 @@ void CavesNoiseIntersection::generateCaves( noise_cave2->perlinMap3D(nmin.X, nmin.Y - 1, nmin.Z); const v3s16 &em = vm->m_area.getExtent(); - u32 index2d = 0; // Biomemap index + u32 index2d = 0; // Biomemap index for (s16 z = nmin.Z; z <= nmax.Z; z++) - for (s16 x = nmin.X; x <= nmax.X; x++, index2d++) { - bool column_is_open = false; // Is column open to overground - bool is_under_river = false; // Is column under river water - bool is_under_tunnel = false; // Is tunnel or is under tunnel - bool is_top_filler_above = false; // Is top or filler above node - // Indexes at column top - u32 vi = vm->m_area.index(x, nmax.Y, z); - u32 index3d = (z - nmin.Z) * m_zstride_1d + - m_csize.Y * m_ystride + - (x - nmin.X); // 3D noise index - // Biome of column - Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index2d]); - u16 depth_top = biome->depth_top; - u16 base_filler = depth_top + biome->depth_filler; - u16 depth_riverbed = biome->depth_riverbed; - u16 nplaced = 0; - // Don't excavate the overgenerated stone at nmax.Y + 1, - // this creates a 'roof' over the tunnel, preventing light in - // tunnels at mapchunk borders when generating mapchunks upwards. - // This 'roof' is removed when the mapchunk above is generated. - for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, index3d -= m_ystride, - VoxelArea::add_y(em, vi, -1)) { - content_t c = vm->m_data[vi].getContent(); - - if (c == CONTENT_AIR || c == biome->c_water_top || - c == biome->c_water) { - column_is_open = true; - is_top_filler_above = false; - continue; - } - - if (c == biome->c_river_water) { - column_is_open = true; - is_under_river = true; - is_top_filler_above = false; - continue; - } + for (s16 x = nmin.X; x <= nmax.X; x++, index2d++) { + bool column_is_open = false; // Is column open to overground + bool is_under_river = false; // Is column under river water + bool is_under_tunnel = false; // Is tunnel or is under tunnel + bool is_top_filler_above = false; // Is top or filler above node + // Indexes at column top + u32 vi = vm->m_area.index(x, nmax.Y, z); + u32 index3d = (z - nmin.Z) * m_zstride_1d + m_csize.Y * m_ystride + + (x - nmin.X); // 3D noise index + // Biome of column + Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index2d]); + u16 depth_top = biome->depth_top; + u16 base_filler = depth_top + biome->depth_filler; + u16 depth_riverbed = biome->depth_riverbed; + u16 nplaced = 0; + // Don't excavate the overgenerated stone at nmax.Y + 1, + // this creates a 'roof' over the tunnel, preventing light in + // tunnels at mapchunk borders when generating mapchunks upwards. + // This 'roof' is removed when the mapchunk above is generated. + for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, + index3d -= m_ystride, + VoxelArea::add_y(em, vi, -1)) { + content_t c = vm->m_data[vi].getContent(); + + if (c == CONTENT_AIR || c == biome->c_water_top || + c == biome->c_water) { + column_is_open = true; + is_top_filler_above = false; + continue; + } - // Ground - float d1 = contour(noise_cave1->result[index3d]); - float d2 = contour(noise_cave2->result[index3d]); + if (c == biome->c_river_water) { + column_is_open = true; + is_under_river = true; + is_top_filler_above = false; + continue; + } - if (d1 * d2 > m_cave_width && - m_ndef->get(c).is_ground_content) { - // In tunnel and ground content, excavate - vm->m_data[vi] = MapNode(CONTENT_AIR); - is_under_tunnel = true; - // If tunnel roof is top or filler, replace with - // stone - if (is_top_filler_above) - vm->m_data[vi + em.X] = - MapNode(biome->c_stone); - is_top_filler_above = false; - } else if (column_is_open && is_under_tunnel && - (c == biome->c_stone || - c == biome->c_filler)) { - // Tunnel entrance floor, place biome surface - // nodes - if (is_under_river) { - if (nplaced < depth_riverbed) { - vm->m_data[vi] = MapNode( - biome->c_riverbed); - is_top_filler_above = true; - nplaced++; - } else { - // Disable top/filler placement - column_is_open = false; - is_under_river = false; - is_under_tunnel = false; - } - } else if (nplaced < depth_top) { - vm->m_data[vi] = MapNode(biome->c_top); - is_top_filler_above = true; - nplaced++; - } else if (nplaced < base_filler) { - vm->m_data[vi] = MapNode(biome->c_filler); + // Ground + float d1 = contour(noise_cave1->result[index3d]); + float d2 = contour(noise_cave2->result[index3d]); + + if (d1 * d2 > m_cave_width && m_ndef->get(c).is_ground_content) { + // In tunnel and ground content, excavate + vm->m_data[vi] = MapNode(CONTENT_AIR); + is_under_tunnel = true; + // If tunnel roof is top or filler, replace with stone + if (is_top_filler_above) + vm->m_data[vi + em.X] = MapNode(biome->c_stone); + is_top_filler_above = false; + } else if (column_is_open && is_under_tunnel && + (c == biome->c_stone || c == biome->c_filler)) { + // Tunnel entrance floor, place biome surface nodes + if (is_under_river) { + if (nplaced < depth_riverbed) { + vm->m_data[vi] = MapNode(biome->c_riverbed); is_top_filler_above = true; nplaced++; } else { // Disable top/filler placement column_is_open = false; + is_under_river = false; is_under_tunnel = false; } + } else if (nplaced < depth_top) { + vm->m_data[vi] = MapNode(biome->c_top); + is_top_filler_above = true; + nplaced++; + } else if (nplaced < base_filler) { + vm->m_data[vi] = MapNode(biome->c_filler); + is_top_filler_above = true; + nplaced++; } else { - // Not tunnel or tunnel entrance floor - // Check node for possible replacing with stone - // for tunnel roof - if (c == biome->c_top || c == biome->c_filler) - is_top_filler_above = true; - + // Disable top/filler placement column_is_open = false; + is_under_tunnel = false; } + } else { + // Not tunnel or tunnel entrance floor + // Check node for possible replacing with stone for tunnel roof + if (c == biome->c_top || c == biome->c_filler) + is_top_filler_above = true; + + column_is_open = false; } } + } } + //// //// CavernsNoise //// -CavernsNoise::CavernsNoise(const NodeDefManager *nodedef, v3s16 chunksize, - NoiseParams *np_cavern, s32 seed, float cavern_limit, float cavern_taper, - float cavern_threshold) +CavernsNoise::CavernsNoise( + const NodeDefManager *nodedef, v3s16 chunksize, NoiseParams *np_cavern, + s32 seed, float cavern_limit, float cavern_taper, float cavern_threshold) { assert(nodedef); - m_ndef = nodedef; + m_ndef = nodedef; - m_csize = chunksize; - m_cavern_limit = cavern_limit; - m_cavern_taper = cavern_taper; + m_csize = chunksize; + m_cavern_limit = cavern_limit; + m_cavern_taper = cavern_taper; m_cavern_threshold = cavern_threshold; m_ystride = m_csize.X; @@ -208,11 +205,13 @@ CavernsNoise::CavernsNoise(const NodeDefManager *nodedef, v3s16 chunksize, c_lava_source = CONTENT_AIR; } + CavernsNoise::~CavernsNoise() { delete noise_cavern; } + bool CavernsNoise::generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax) { assert(vm); @@ -222,10 +221,10 @@ bool CavernsNoise::generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax) // Cache cavern_amp values float *cavern_amp = new float[m_csize.Y + 1]; - u8 cavern_amp_index = 0; // Index zero at column top + u8 cavern_amp_index = 0; // Index zero at column top for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, cavern_amp_index++) { cavern_amp[cavern_amp_index] = - MYMIN((m_cavern_limit - y) / (float)m_cavern_taper, 1.0f); + MYMIN((m_cavern_limit - y) / (float)m_cavern_taper, 1.0f); } //// Place nodes @@ -234,57 +233,65 @@ bool CavernsNoise::generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax) u32 index2d = 0; for (s16 z = nmin.Z; z <= nmax.Z; z++) - for (s16 x = nmin.X; x <= nmax.X; x++, index2d++) { - // Reset cave_amp index to column top - cavern_amp_index = 0; - // Initial voxelmanip index at column top - u32 vi = vm->m_area.index(x, nmax.Y, z); - // Initial 3D noise index at column top - u32 index3d = (z - nmin.Z) * m_zstride_1d + - m_csize.Y * m_ystride + (x - nmin.X); - // Don't excavate the overgenerated stone at node_max.Y + 1, - // this creates a 'roof' over the cavern, preventing light in - // caverns at mapchunk borders when generating mapchunks upwards. - // This 'roof' is excavated when the mapchunk above is generated. - for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, index3d -= m_ystride, - VoxelArea::add_y(em, vi, -1), cavern_amp_index++) { - content_t c = vm->m_data[vi].getContent(); - float n_absamp_cavern = - std::fabs(noise_cavern->result[index3d]) * - cavern_amp[cavern_amp_index]; - // Disable CavesRandomWalk at a safe distance from caverns - // to avoid excessively spreading liquids in caverns. - if (n_absamp_cavern > m_cavern_threshold - 0.1f) { - near_cavern = true; - if (n_absamp_cavern > m_cavern_threshold && - m_ndef->get(c).is_ground_content) - vm->m_data[vi] = MapNode(CONTENT_AIR); - } + for (s16 x = nmin.X; x <= nmax.X; x++, index2d++) { + // Reset cave_amp index to column top + cavern_amp_index = 0; + // Initial voxelmanip index at column top + u32 vi = vm->m_area.index(x, nmax.Y, z); + // Initial 3D noise index at column top + u32 index3d = (z - nmin.Z) * m_zstride_1d + m_csize.Y * m_ystride + + (x - nmin.X); + // Don't excavate the overgenerated stone at node_max.Y + 1, + // this creates a 'roof' over the cavern, preventing light in + // caverns at mapchunk borders when generating mapchunks upwards. + // This 'roof' is excavated when the mapchunk above is generated. + for (s16 y = nmax.Y; y >= nmin.Y - 1; y--, + index3d -= m_ystride, + VoxelArea::add_y(em, vi, -1), + cavern_amp_index++) { + content_t c = vm->m_data[vi].getContent(); + float n_absamp_cavern = std::fabs(noise_cavern->result[index3d]) * + cavern_amp[cavern_amp_index]; + // Disable CavesRandomWalk at a safe distance from caverns + // to avoid excessively spreading liquids in caverns. + if (n_absamp_cavern > m_cavern_threshold - 0.1f) { + near_cavern = true; + if (n_absamp_cavern > m_cavern_threshold && + m_ndef->get(c).is_ground_content) + vm->m_data[vi] = MapNode(CONTENT_AIR); } } + } delete[] cavern_amp; return near_cavern; } + //// //// CavesRandomWalk //// -CavesRandomWalk::CavesRandomWalk(const NodeDefManager *ndef, GenerateNotifier *gennotify, - s32 seed, int water_level, content_t water_source, content_t lava_source, - float large_cave_flooded, BiomeGen *biomegen) +CavesRandomWalk::CavesRandomWalk( + const NodeDefManager *ndef, + GenerateNotifier *gennotify, + s32 seed, + int water_level, + content_t water_source, + content_t lava_source, + float large_cave_flooded, + BiomeGen *biomegen) { assert(ndef); - this->ndef = ndef; - this->gennotify = gennotify; - this->seed = seed; - this->water_level = water_level; - this->np_caveliquids = &nparams_caveliquids; + this->ndef = ndef; + this->gennotify = gennotify; + this->seed = seed; + this->water_level = water_level; + this->np_caveliquids = &nparams_caveliquids; this->large_cave_flooded = large_cave_flooded; - this->bmgn = biomegen; + this->bmgn = biomegen; c_water_source = water_source; if (c_water_source == CONTENT_IGNORE) @@ -299,17 +306,18 @@ CavesRandomWalk::CavesRandomWalk(const NodeDefManager *ndef, GenerateNotifier *g c_lava_source = CONTENT_AIR; } -void CavesRandomWalk::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, - bool is_large_cave, int max_stone_height, s16 *heightmap) + +void CavesRandomWalk::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, + PseudoRandom *ps, bool is_large_cave, int max_stone_height, s16 *heightmap) { assert(vm); assert(ps); - this->vm = vm; - this->ps = ps; - this->node_min = nmin; - this->node_max = nmax; - this->heightmap = heightmap; + this->vm = vm; + this->ps = ps; + this->node_min = nmin; + this->node_max = nmax; + this->heightmap = heightmap; this->large_cave = is_large_cave; this->ystride = nmax.X - nmin.X + 1; @@ -325,8 +333,8 @@ void CavesRandomWalk::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRando Biome *biome = (Biome *)bmgn->getBiomeAtPoint(midp); if (biome->c_cave_liquid[0] != CONTENT_IGNORE) { use_biome_liquid = true; - c_biome_liquid = biome->c_cave_liquid[ps->range( - 0, biome->c_cave_liquid.size() - 1)]; + c_biome_liquid = + biome->c_cave_liquid[ps->range(0, biome->c_cave_liquid.size() - 1)]; if (c_biome_liquid == CONTENT_AIR) flooded = false; } @@ -395,8 +403,8 @@ void CavesRandomWalk::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRando // Add generation notify begin event if (gennotify) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); - GenNotifyType notifytype = large_cave ? GENNOTIFY_LARGECAVE_BEGIN - : GENNOTIFY_CAVE_BEGIN; + GenNotifyType notifytype = large_cave ? + GENNOTIFY_LARGECAVE_BEGIN : GENNOTIFY_CAVE_BEGIN; gennotify->addEvent(notifytype, abs_pos); } @@ -407,12 +415,13 @@ void CavesRandomWalk::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRando // Add generation notify end event if (gennotify) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); - GenNotifyType notifytype = - large_cave ? GENNOTIFY_LARGECAVE_END : GENNOTIFY_CAVE_END; + GenNotifyType notifytype = large_cave ? + GENNOTIFY_LARGECAVE_END : GENNOTIFY_CAVE_END; gennotify->addEvent(notifytype, abs_pos); } } + void CavesRandomWalk::makeTunnel(bool dirswitch) { if (dirswitch && !large_cave) { @@ -431,11 +440,17 @@ void CavesRandomWalk::makeTunnel(bool dirswitch) v3s16 maxlen; if (large_cave) { - maxlen = v3s16(rs_part_max_length_rs, rs_part_max_length_rs / 2, - rs_part_max_length_rs); + maxlen = v3s16( + rs_part_max_length_rs, + rs_part_max_length_rs / 2, + rs_part_max_length_rs + ); } else { - maxlen = v3s16(rs_part_max_length_rs, ps->range(1, rs_part_max_length_rs), - rs_part_max_length_rs); + maxlen = v3s16( + rs_part_max_length_rs, + ps->range(1, rs_part_max_length_rs), + rs_part_max_length_rs + ); } v3f vec; @@ -491,6 +506,7 @@ void CavesRandomWalk::makeTunnel(bool dirswitch) orp = rp; } + void CavesRandomWalk::carveRoute(v3f vec, float f, bool randomize_xz) { MapNode airnode(CONTENT_AIR); @@ -512,16 +528,13 @@ void CavesRandomWalk::carveRoute(v3f vec, float f, bool randomize_xz) if (use_biome_liquid) { liquidnode = c_biome_liquid; } else { - // If cave liquid not defined by biome, fallback to old hardcoded - // behaviour. - // TODO 'np_caveliquids' is deprecated and should eventually be - // removed. Cave liquids are now defined and located using biome - // definitions. - float nval = NoisePerlin3D(np_caveliquids, startp.X, startp.Y, - startp.Z, seed); - liquidnode = (nval < 0.40f && node_max.Y < water_level - 256) - ? lavanode - : waternode; + // If cave liquid not defined by biome, fallback to old hardcoded behaviour. + // TODO 'np_caveliquids' is deprecated and should eventually be removed. + // Cave liquids are now defined and located using biome definitions. + float nval = NoisePerlin3D(np_caveliquids, startp.X, + startp.Y, startp.Z, seed); + liquidnode = (nval < 0.40f && node_max.Y < water_level - 256) ? + lavanode : waternode; } } @@ -536,8 +549,7 @@ void CavesRandomWalk::carveRoute(v3f vec, float f, bool randomize_xz) for (s16 z0 = d0; z0 <= d1; z0++) { s16 si = rs / 2 - MYMAX(0, abs(z0) - rs / 7 - 1); - for (s16 x0 = -si - ps->range(0, 1); x0 <= si - 1 + ps->range(0, 1); - x0++) { + for (s16 x0 = -si - ps->range(0,1); x0 <= si - 1 + ps->range(0,1); x0++) { s16 maxabsxz = MYMAX(abs(x0), abs(z0)); s16 si2 = rs / 2 - MYMAX(0, maxabsxz - rs / 7 - 1); @@ -568,15 +580,10 @@ void CavesRandomWalk::carveRoute(v3f vec, float f, bool randomize_xz) int full_ymin = node_min.Y - MAP_BLOCKSIZE; int full_ymax = node_max.Y + MAP_BLOCKSIZE; - if (flooded && full_ymin < water_level && - full_ymax > water_level) - vm->m_data[i] = (p.Y <= water_level) - ? waternode - : airnode; + if (flooded && full_ymin < water_level && full_ymax > water_level) + vm->m_data[i] = (p.Y <= water_level) ? waternode : airnode; else if (flooded && full_ymax < water_level) - vm->m_data[i] = (p.Y < startp.Y - 4) - ? liquidnode - : airnode; + vm->m_data[i] = (p.Y < startp.Y - 4) ? liquidnode : airnode; else vm->m_data[i] = airnode; } else { @@ -588,9 +595,11 @@ void CavesRandomWalk::carveRoute(v3f vec, float f, bool randomize_xz) } } + inline bool CavesRandomWalk::isPosAboveSurface(v3s16 p) { - if (heightmap != NULL && p.Z >= node_min.Z && p.Z <= node_max.Z && + if (heightmap != NULL && + p.Z >= node_min.Z && p.Z <= node_max.Z && p.X >= node_min.X && p.X <= node_max.X) { u32 index = (p.Z - node_min.Z) * ystride + (p.X - node_min.X); if (heightmap[index] < p.Y) @@ -602,17 +611,18 @@ inline bool CavesRandomWalk::isPosAboveSurface(v3s16 p) return false; } + //// //// CavesV6 //// -CavesV6::CavesV6(const NodeDefManager *ndef, GenerateNotifier *gennotify, int water_level, - content_t water_source, content_t lava_source) +CavesV6::CavesV6(const NodeDefManager *ndef, GenerateNotifier *gennotify, + int water_level, content_t water_source, content_t lava_source) { assert(ndef); - this->ndef = ndef; - this->gennotify = gennotify; + this->ndef = ndef; + this->gennotify = gennotify; this->water_level = water_level; c_water_source = water_source; @@ -628,20 +638,21 @@ CavesV6::CavesV6(const NodeDefManager *ndef, GenerateNotifier *gennotify, int wa c_lava_source = CONTENT_AIR; } -void CavesV6::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, - PseudoRandom *ps2, bool is_large_cave, int max_stone_height, - s16 *heightmap) + +void CavesV6::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, + PseudoRandom *ps, PseudoRandom *ps2, + bool is_large_cave, int max_stone_height, s16 *heightmap) { assert(vm); assert(ps); assert(ps2); - this->vm = vm; - this->ps = ps; - this->ps2 = ps2; - this->node_min = nmin; - this->node_max = nmax; - this->heightmap = heightmap; + this->vm = vm; + this->ps = ps; + this->ps2 = ps2; + this->node_min = nmin; + this->node_max = nmax; + this->heightmap = heightmap; this->large_cave = is_large_cave; this->ystride = nmax.X - nmin.X + 1; @@ -649,10 +660,10 @@ void CavesV6::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, // Set initial parameters from randomness min_tunnel_diameter = 2; max_tunnel_diameter = ps->range(2, 6); - int dswitchint = ps->range(1, 14); + int dswitchint = ps->range(1, 14); if (large_cave) { - part_max_length_rs = ps->range(2, 4); - tunnel_routepoints = ps->range(5, ps->range(15, 30)); + part_max_length_rs = ps->range(2, 4); + tunnel_routepoints = ps->range(5, ps->range(15, 30)); min_tunnel_diameter = 5; max_tunnel_diameter = ps->range(7, ps->range(8, 24)); } else { @@ -707,8 +718,8 @@ void CavesV6::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, // Add generation notify begin event if (gennotify != NULL) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); - GenNotifyType notifytype = large_cave ? GENNOTIFY_LARGECAVE_BEGIN - : GENNOTIFY_CAVE_BEGIN; + GenNotifyType notifytype = large_cave ? + GENNOTIFY_LARGECAVE_BEGIN : GENNOTIFY_CAVE_BEGIN; gennotify->addEvent(notifytype, abs_pos); } @@ -719,12 +730,13 @@ void CavesV6::makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, // Add generation notify end event if (gennotify != NULL) { v3s16 abs_pos(of.X + orp.X, of.Y + orp.Y, of.Z + orp.Z); - GenNotifyType notifytype = - large_cave ? GENNOTIFY_LARGECAVE_END : GENNOTIFY_CAVE_END; + GenNotifyType notifytype = large_cave ? + GENNOTIFY_LARGECAVE_END : GENNOTIFY_CAVE_END; gennotify->addEvent(notifytype, abs_pos); } } + void CavesV6::makeTunnel(bool dirswitch) { if (dirswitch && !large_cave) { @@ -743,11 +755,17 @@ void CavesV6::makeTunnel(bool dirswitch) v3s16 maxlen; if (large_cave) { - maxlen = v3s16(rs_part_max_length_rs, rs_part_max_length_rs / 2, - rs_part_max_length_rs); + maxlen = v3s16( + rs_part_max_length_rs, + rs_part_max_length_rs / 2, + rs_part_max_length_rs + ); } else { - maxlen = v3s16(rs_part_max_length_rs, ps->range(1, rs_part_max_length_rs), - rs_part_max_length_rs); + maxlen = v3s16( + rs_part_max_length_rs, + ps->range(1, rs_part_max_length_rs), + rs_part_max_length_rs + ); } v3f vec; @@ -771,8 +789,9 @@ void CavesV6::makeTunnel(bool dirswitch) // If startpoint and endpoint are above ground, disable placement of nodes // in carveRoute while still running all PseudoRandom calls to ensure caves // are consistent with existing worlds. - bool tunnel_above_ground = p1.Y > getSurfaceFromHeightmap(p1) && - p2.Y > getSurfaceFromHeightmap(p2); + bool tunnel_above_ground = + p1.Y > getSurfaceFromHeightmap(p1) && + p2.Y > getSurfaceFromHeightmap(p2); vec += main_direction; @@ -809,7 +828,9 @@ void CavesV6::makeTunnel(bool dirswitch) orp = rp; } -void CavesV6::carveRoute(v3f vec, float f, bool randomize_xz, bool tunnel_above_ground) + +void CavesV6::carveRoute(v3f vec, float f, bool randomize_xz, + bool tunnel_above_ground) { MapNode airnode(CONTENT_AIR); MapNode waternode(c_water_source); @@ -832,8 +853,7 @@ void CavesV6::carveRoute(v3f vec, float f, bool randomize_xz, bool tunnel_above_ for (s16 z0 = d0; z0 <= d1; z0++) { s16 si = rs / 2 - MYMAX(0, abs(z0) - rs / 7 - 1); - for (s16 x0 = -si - ps->range(0, 1); x0 <= si - 1 + ps->range(0, 1); - x0++) { + for (s16 x0 = -si - ps->range(0,1); x0 <= si - 1 + ps->range(0,1); x0++) { if (tunnel_above_ground) continue; @@ -861,15 +881,10 @@ void CavesV6::carveRoute(v3f vec, float f, bool randomize_xz, bool tunnel_above_ int full_ymin = node_min.Y - MAP_BLOCKSIZE; int full_ymax = node_max.Y + MAP_BLOCKSIZE; - if (full_ymin < water_level && - full_ymax > water_level) { - vm->m_data[i] = (p.Y <= water_level) - ? waternode - : airnode; + if (full_ymin < water_level && full_ymax > water_level) { + vm->m_data[i] = (p.Y <= water_level) ? waternode : airnode; } else if (full_ymax < water_level) { - vm->m_data[i] = (p.Y < startp.Y - 2) - ? lavanode - : airnode; + vm->m_data[i] = (p.Y < startp.Y - 2) ? lavanode : airnode; } else { vm->m_data[i] = airnode; } @@ -885,13 +900,16 @@ void CavesV6::carveRoute(v3f vec, float f, bool randomize_xz, bool tunnel_above_ } } + inline s16 CavesV6::getSurfaceFromHeightmap(v3s16 p) { - if (heightmap != NULL && p.Z >= node_min.Z && p.Z <= node_max.Z && + if (heightmap != NULL && + p.Z >= node_min.Z && p.Z <= node_max.Z && p.X >= node_min.X && p.X <= node_max.X) { u32 index = (p.Z - node_min.Z) * ystride + (p.X - node_min.X); return heightmap[index]; } return water_level; + } diff --git a/src/mapgen/cavegen.h b/src/mapgen/cavegen.h index 876c45936..d678d365b 100644 --- a/src/mapgen/cavegen.h +++ b/src/mapgen/cavegen.h @@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #define VMANIP_FLAG_CAVE VOXELFLAG_CHECKED1 -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class GenerateNotifier; @@ -41,9 +41,9 @@ class GenerateNotifier; class CavesNoiseIntersection { public: - CavesNoiseIntersection(const NodeDefManager *nodedef, BiomeManager *biomemgr, - v3s16 chunksize, NoiseParams *np_cave1, NoiseParams *np_cave2, - s32 seed, float cave_width); + CavesNoiseIntersection(const NodeDefManager *nodedef, + BiomeManager *biomemgr, v3s16 chunksize, NoiseParams *np_cave1, + NoiseParams *np_cave2, s32 seed, float cave_width); ~CavesNoiseIntersection(); void generateCaves(MMVManip *vm, v3s16 nmin, v3s16 nmax, biome_t *biomemap); @@ -71,8 +71,8 @@ class CavernsNoise { public: CavernsNoise(const NodeDefManager *nodedef, v3s16 chunksize, - NoiseParams *np_cavern, s32 seed, float cavern_limit, - float cavern_taper, float cavern_threshold); + NoiseParams *np_cavern, s32 seed, float cavern_limit, + float cavern_taper, float cavern_threshold); ~CavernsNoise(); bool generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax); @@ -143,7 +143,7 @@ class CavesRandomWalk v3f orp; // starting point, relative to caved space v3s16 of; // absolute coordinates of caved space v3s16 ar; // allowed route area - s16 rs; // tunnel radius size + s16 rs; // tunnel radius size v3f main_direction; s16 route_y_min; @@ -158,11 +158,10 @@ class CavesRandomWalk // ndef is a mandatory parameter. // If gennotify is NULL, generation events are not logged. // If biomegen is NULL, cave liquids have classic behaviour. - CavesRandomWalk(const NodeDefManager *ndef, GenerateNotifier *gennotify = NULL, - s32 seed = 0, int water_level = 1, - content_t water_source = CONTENT_IGNORE, - content_t lava_source = CONTENT_IGNORE, - float large_cave_flooded = 0.5f, BiomeGen *biomegen = NULL); + CavesRandomWalk(const NodeDefManager *ndef, GenerateNotifier *gennotify = + NULL, s32 seed = 0, int water_level = 1, content_t water_source = + CONTENT_IGNORE, content_t lava_source = CONTENT_IGNORE, + float large_cave_flooded = 0.5f, BiomeGen *biomegen = NULL); // vm and ps are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to @@ -222,7 +221,7 @@ class CavesV6 v3f orp; // starting point, relative to caved space v3s16 of; // absolute coordinates of caved space v3s16 ar; // allowed route area - s16 rs; // tunnel radius size + s16 rs; // tunnel radius size v3f main_direction; s16 route_y_min; diff --git a/src/mapgen/dungeongen.cpp b/src/mapgen/dungeongen.cpp index 521eb7f7b..acdb1a0f0 100644 --- a/src/mapgen/dungeongen.cpp +++ b/src/mapgen/dungeongen.cpp @@ -31,18 +31,20 @@ with this program; if not, write to the Free Software Foundation, Inc., //#define DGEN_USE_TORCHES + /////////////////////////////////////////////////////////////////////////////// -DungeonGen::DungeonGen(const NodeDefManager *ndef, GenerateNotifier *gennotify, - DungeonParams *dparams) + +DungeonGen::DungeonGen(const NodeDefManager *ndef, + GenerateNotifier *gennotify, DungeonParams *dparams) { assert(ndef); - this->ndef = ndef; + this->ndef = ndef; this->gennotify = gennotify; #ifdef DGEN_USE_TORCHES - c_torch = ndef->getId("default:torch"); + c_torch = ndef->getId("default:torch"); #endif if (dparams) { @@ -51,29 +53,30 @@ DungeonGen::DungeonGen(const NodeDefManager *ndef, GenerateNotifier *gennotify, // Default dungeon parameters dp.seed = 0; - dp.c_wall = ndef->getId("mapgen_cobble"); + dp.c_wall = ndef->getId("mapgen_cobble"); dp.c_alt_wall = ndef->getId("mapgen_mossycobble"); - dp.c_stair = ndef->getId("mapgen_stair_cobble"); - - dp.diagonal_dirs = false; - dp.only_in_ground = true; - dp.holesize = v3s16(1, 2, 1); - dp.corridor_len_min = 1; - dp.corridor_len_max = 13; - dp.room_size_min = v3s16(4, 4, 4); - dp.room_size_max = v3s16(8, 6, 8); + dp.c_stair = ndef->getId("mapgen_stair_cobble"); + + dp.diagonal_dirs = false; + dp.only_in_ground = true; + dp.holesize = v3s16(1, 2, 1); + dp.corridor_len_min = 1; + dp.corridor_len_max = 13; + dp.room_size_min = v3s16(4, 4, 4); + dp.room_size_max = v3s16(8, 6, 8); dp.room_size_large_min = v3s16(8, 8, 8); dp.room_size_large_max = v3s16(16, 16, 16); - dp.large_room_chance = 1; - dp.num_rooms = 8; - dp.num_dungeons = 1; - dp.notifytype = GENNOTIFY_DUNGEON; + dp.large_room_chance = 1; + dp.num_rooms = 8; + dp.num_dungeons = 1; + dp.notifytype = GENNOTIFY_DUNGEON; - dp.np_alt_wall = NoiseParams( - -0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); + dp.np_alt_wall = + NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); } } + void DungeonGen::generate(MMVManip *vm, u32 bseed, v3s16 nmin, v3s16 nmax) { if (dp.num_dungeons == 0) @@ -81,7 +84,7 @@ void DungeonGen::generate(MMVManip *vm, u32 bseed, v3s16 nmin, v3s16 nmax) assert(vm); - // TimeTaker t("gen dungeons"); + //TimeTaker t("gen dungeons"); this->vm = vm; this->blockseed = bseed; @@ -91,13 +94,13 @@ void DungeonGen::generate(MMVManip *vm, u32 bseed, v3s16 nmin, v3s16 nmax) vm->clearFlag(VMANIP_FLAG_DUNGEON_INSIDE | VMANIP_FLAG_DUNGEON_PRESERVE); if (dp.only_in_ground) { - // Set all air and liquid drawtypes to be untouchable to make dungeons - // generate in ground only. Set 'ignore' to be untouchable to prevent - // generation in ungenerated neighbor mapchunks, to avoid dungeon rooms - // generating outside ground. Like randomwalk caves, preserve nodes that - // have 'is_ground_content = false', to avoid dungeons that generate out - // beyond the edge of a mapchunk destroying nodes added by mods in - // 'register_on_generated()'. + // Set all air and liquid drawtypes to be untouchable to make dungeons generate + // in ground only. + // Set 'ignore' to be untouchable to prevent generation in ungenerated neighbor + // mapchunks, to avoid dungeon rooms generating outside ground. + // Like randomwalk caves, preserve nodes that have 'is_ground_content = false', + // to avoid dungeons that generate out beyond the edge of a mapchunk destroying + // nodes added by mods in 'register_on_generated()'. for (s16 z = nmin.Z; z <= nmax.Z; z++) { for (s16 y = nmin.Y; y <= nmax.Y; y++) { u32 i = vm->m_area.index(nmin.X, y, z); @@ -105,10 +108,8 @@ void DungeonGen::generate(MMVManip *vm, u32 bseed, v3s16 nmin, v3s16 nmax) content_t c = vm->m_data[i].getContent(); NodeDrawType dtype = ndef->get(c).drawtype; if (dtype == NDT_AIRLIKE || dtype == NDT_LIQUID || - c == CONTENT_IGNORE || - !ndef->get(c).is_ground_content) - vm->m_flags[i] |= - VMANIP_FLAG_DUNGEON_PRESERVE; + c == CONTENT_IGNORE || !ndef->get(c).is_ground_content) + vm->m_flags[i] |= VMANIP_FLAG_DUNGEON_PRESERVE; i++; } } @@ -124,21 +125,21 @@ void DungeonGen::generate(MMVManip *vm, u32 bseed, v3s16 nmin, v3s16 nmax) return; for (s16 z = nmin.Z; z <= nmax.Z; z++) - for (s16 y = nmin.Y; y <= nmax.Y; y++) { - u32 i = vm->m_area.index(nmin.X, y, z); - for (s16 x = nmin.X; x <= nmax.X; x++) { - if (vm->m_data[i].getContent() == dp.c_wall) { - if (NoisePerlin3D(&dp.np_alt_wall, x, y, z, - blockseed) > 0.0f) - vm->m_data[i].setContent(dp.c_alt_wall); - } - i++; + for (s16 y = nmin.Y; y <= nmax.Y; y++) { + u32 i = vm->m_area.index(nmin.X, y, z); + for (s16 x = nmin.X; x <= nmax.X; x++) { + if (vm->m_data[i].getContent() == dp.c_wall) { + if (NoisePerlin3D(&dp.np_alt_wall, x, y, z, blockseed) > 0.0f) + vm->m_data[i].setContent(dp.c_alt_wall); } + i++; } + } - // printf("== gen dungeons: %dms\n", t.stop()); + //printf("== gen dungeons: %dms\n", t.stop()); } + void DungeonGen::makeDungeon(v3s16 start_padding) { const v3s16 &areasize = vm->m_area.getExtent(); @@ -151,12 +152,9 @@ void DungeonGen::makeDungeon(v3s16 start_padding) bool fits = false; for (u32 i = 0; i < 100 && !fits; i++) { if (dp.large_room_chance >= 1) { - roomsize.Z = random.range(dp.room_size_large_min.Z, - dp.room_size_large_max.Z); - roomsize.Y = random.range(dp.room_size_large_min.Y, - dp.room_size_large_max.Y); - roomsize.X = random.range(dp.room_size_large_min.X, - dp.room_size_large_max.X); + roomsize.Z = random.range(dp.room_size_large_min.Z, dp.room_size_large_max.Z); + roomsize.Y = random.range(dp.room_size_large_min.Y, dp.room_size_large_max.Y); + roomsize.X = random.range(dp.room_size_large_min.X, dp.room_size_large_max.X); } else { roomsize.Z = random.range(dp.room_size_min.Z, dp.room_size_max.Z); roomsize.Y = random.range(dp.room_size_min.Y, dp.room_size_max.Y); @@ -176,18 +174,16 @@ void DungeonGen::makeDungeon(v3s16 start_padding) */ fits = true; for (s16 z = 0; z < roomsize.Z; z++) - for (s16 y = 0; y < roomsize.Y; y++) - for (s16 x = 0; x < roomsize.X; x++) { - v3s16 p = roomplace + v3s16(x, y, z); - u32 vi = vm->m_area.index(p); - if ((vm->m_flags[vi] & - VMANIP_FLAG_DUNGEON_UNTOUCHABLE) || - vm->m_data[vi].getContent() == - CONTENT_IGNORE) { - fits = false; - break; - } - } + for (s16 y = 0; y < roomsize.Y; y++) + for (s16 x = 0; x < roomsize.X; x++) { + v3s16 p = roomplace + v3s16(x, y, z); + u32 vi = vm->m_area.index(p); + if ((vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) || + vm->m_data[vi].getContent() == CONTENT_IGNORE) { + fits = false; + break; + } + } } // No place found if (!fits) @@ -252,15 +248,11 @@ void DungeonGen::makeDungeon(v3s16 start_padding) makeCorridor(doorplace, doordir, corridor_end, corridor_end_dir); // Find a place for a random sized room - if (dp.large_room_chance > 1 && - random.range(1, dp.large_room_chance) == 1) { + if (dp.large_room_chance > 1 && random.range(1, dp.large_room_chance) == 1) { // Large room - roomsize.Z = random.range(dp.room_size_large_min.Z, - dp.room_size_large_max.Z); - roomsize.Y = random.range(dp.room_size_large_min.Y, - dp.room_size_large_max.Y); - roomsize.X = random.range(dp.room_size_large_min.X, - dp.room_size_large_max.X); + roomsize.Z = random.range(dp.room_size_large_min.Z, dp.room_size_large_max.Z); + roomsize.Y = random.range(dp.room_size_large_min.Y, dp.room_size_large_max.Y); + roomsize.X = random.range(dp.room_size_large_min.X, dp.room_size_large_max.X); } else { roomsize.Z = random.range(dp.room_size_min.Z, dp.room_size_max.Z); roomsize.Y = random.range(dp.room_size_min.Y, dp.room_size_max.Y); @@ -281,6 +273,7 @@ void DungeonGen::makeDungeon(v3s16 start_padding) } } + void DungeonGen::makeRoom(v3s16 roomsize, v3s16 roomplace) { MapNode n_wall(dp.c_wall); @@ -288,107 +281,112 @@ void DungeonGen::makeRoom(v3s16 roomsize, v3s16 roomplace) // Make +-X walls for (s16 z = 0; z < roomsize.Z; z++) - for (s16 y = 0; y < roomsize.Y; y++) { - { - v3s16 p = roomplace + v3s16(0, y, z); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) - continue; - vm->m_data[vi] = n_wall; - } - { - v3s16 p = roomplace + v3s16(roomsize.X - 1, y, z); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) - continue; - vm->m_data[vi] = n_wall; - } + for (s16 y = 0; y < roomsize.Y; y++) { + { + v3s16 p = roomplace + v3s16(0, y, z); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) + continue; + vm->m_data[vi] = n_wall; + } + { + v3s16 p = roomplace + v3s16(roomsize.X - 1, y, z); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) + continue; + vm->m_data[vi] = n_wall; } + } // Make +-Z walls for (s16 x = 0; x < roomsize.X; x++) - for (s16 y = 0; y < roomsize.Y; y++) { - { - v3s16 p = roomplace + v3s16(x, y, 0); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) - continue; - vm->m_data[vi] = n_wall; - } - { - v3s16 p = roomplace + v3s16(x, y, roomsize.Z - 1); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) - continue; - vm->m_data[vi] = n_wall; - } + for (s16 y = 0; y < roomsize.Y; y++) { + { + v3s16 p = roomplace + v3s16(x, y, 0); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) + continue; + vm->m_data[vi] = n_wall; + } + { + v3s16 p = roomplace + v3s16(x, y, roomsize.Z - 1); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) + continue; + vm->m_data[vi] = n_wall; } + } // Make +-Y walls (floor and ceiling) for (s16 z = 0; z < roomsize.Z; z++) - for (s16 x = 0; x < roomsize.X; x++) { - { - v3s16 p = roomplace + v3s16(x, 0, z); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) - continue; - vm->m_data[vi] = n_wall; - } - { - v3s16 p = roomplace + v3s16(x, roomsize.Y - 1, z); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) - continue; - vm->m_data[vi] = n_wall; - } + for (s16 x = 0; x < roomsize.X; x++) { + { + v3s16 p = roomplace + v3s16(x, 0, z); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) + continue; + vm->m_data[vi] = n_wall; } + { + v3s16 p = roomplace + v3s16(x,roomsize. Y - 1, z); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & VMANIP_FLAG_DUNGEON_UNTOUCHABLE) + continue; + vm->m_data[vi] = n_wall; + } + } // Fill with air for (s16 z = 1; z < roomsize.Z - 1; z++) - for (s16 y = 1; y < roomsize.Y - 1; y++) - for (s16 x = 1; x < roomsize.X - 1; x++) { - v3s16 p = roomplace + v3s16(x, y, z); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; - vm->m_data[vi] = n_air; - } + for (s16 y = 1; y < roomsize.Y - 1; y++) + for (s16 x = 1; x < roomsize.X - 1; x++) { + v3s16 p = roomplace + v3s16(x, y, z); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; + vm->m_data[vi] = n_air; + } } -void DungeonGen::makeFill(v3s16 place, v3s16 size, u8 avoid_flags, MapNode n, u8 or_flags) + +void DungeonGen::makeFill(v3s16 place, v3s16 size, + u8 avoid_flags, MapNode n, u8 or_flags) { for (s16 z = 0; z < size.Z; z++) - for (s16 y = 0; y < size.Y; y++) - for (s16 x = 0; x < size.X; x++) { - v3s16 p = place + v3s16(x, y, z); - if (!vm->m_area.contains(p)) - continue; - u32 vi = vm->m_area.index(p); - if (vm->m_flags[vi] & avoid_flags) - continue; - vm->m_flags[vi] |= or_flags; - vm->m_data[vi] = n; - } + for (s16 y = 0; y < size.Y; y++) + for (s16 x = 0; x < size.X; x++) { + v3s16 p = place + v3s16(x, y, z); + if (!vm->m_area.contains(p)) + continue; + u32 vi = vm->m_area.index(p); + if (vm->m_flags[vi] & avoid_flags) + continue; + vm->m_flags[vi] |= or_flags; + vm->m_data[vi] = n; + } } + void DungeonGen::makeHole(v3s16 place) { - makeFill(place, dp.holesize, 0, MapNode(CONTENT_AIR), VMANIP_FLAG_DUNGEON_INSIDE); + makeFill(place, dp.holesize, 0, MapNode(CONTENT_AIR), + VMANIP_FLAG_DUNGEON_INSIDE); } + void DungeonGen::makeDoor(v3s16 doorplace, v3s16 doordir) { makeHole(doorplace); @@ -399,8 +397,9 @@ void DungeonGen::makeDoor(v3s16 doorplace, v3s16 doordir) #endif } -void DungeonGen::makeCorridor( - v3s16 doorplace, v3s16 doordir, v3s16 &result_place, v3s16 &result_dir) + +void DungeonGen::makeCorridor(v3s16 doorplace, v3s16 doordir, + v3s16 &result_place, v3s16 &result_dir) { makeHole(doorplace); v3s16 p0 = doorplace; @@ -422,16 +421,14 @@ void DungeonGen::makeCorridor( if (vm->m_area.contains(p) && vm->m_area.contains(p + v3s16(0, 1, 0))) { if (make_stairs) { makeFill(p + v3s16(-1, -1, -1), - dp.holesize + v3s16(2, 3, 2), - VMANIP_FLAG_DUNGEON_UNTOUCHABLE, - MapNode(dp.c_wall), 0); + dp.holesize + v3s16(2, 3, 2), + VMANIP_FLAG_DUNGEON_UNTOUCHABLE, + MapNode(dp.c_wall), + 0); makeFill(p, dp.holesize, VMANIP_FLAG_DUNGEON_UNTOUCHABLE, - MapNode(CONTENT_AIR), - VMANIP_FLAG_DUNGEON_INSIDE); - makeFill(p - dir, dp.holesize, - VMANIP_FLAG_DUNGEON_UNTOUCHABLE, - MapNode(CONTENT_AIR), - VMANIP_FLAG_DUNGEON_INSIDE); + MapNode(CONTENT_AIR), VMANIP_FLAG_DUNGEON_INSIDE); + makeFill(p - dir, dp.holesize, VMANIP_FLAG_DUNGEON_UNTOUCHABLE, + MapNode(CONTENT_AIR), VMANIP_FLAG_DUNGEON_INSIDE); // TODO: fix stairs code so it works 100% // (quite difficult) @@ -439,52 +436,30 @@ void DungeonGen::makeCorridor( // exclude stairs from the bottom step // exclude stairs from diagonal steps if (((dir.X ^ dir.Z) & 1) && - (((make_stairs == 1) && i != 0) || - ((make_stairs == -1) && - i != length - 1))) { + (((make_stairs == 1) && i != 0) || + ((make_stairs == -1) && i != length - 1))) { // rotate face 180 deg if // making stairs backwards int facedir = dir_to_facedir(dir * make_stairs); v3s16 ps = p; - u16 stair_width = (dir.Z != 0) ? dp.holesize.X - : dp.holesize.Z; + u16 stair_width = (dir.Z != 0) ? dp.holesize.X : dp.holesize.Z; // Stair width direction vector - v3s16 swv = (dir.Z != 0) ? v3s16(1, 0, 0) - : v3s16(0, 0, 1); + v3s16 swv = (dir.Z != 0) ? v3s16(1, 0, 0) : v3s16(0, 0, 1); for (u16 st = 0; st < stair_width; st++) { if (make_stairs == -1) { - u32 vi = vm->m_area.index( - ps.X - dir.X, - ps.Y - 1, - ps.Z - dir.Z); - if (vm->m_area.contains( - ps + - v3s16(-dir.X, -1, - -dir.Z)) && - vm->m_data[vi].getContent() == - dp.c_wall) { - vm->m_flags[vi] |= - VMANIP_FLAG_DUNGEON_UNTOUCHABLE; - vm->m_data[vi] = MapNode( - dp.c_stair, - 0, - facedir); + u32 vi = vm->m_area.index(ps.X - dir.X, ps.Y - 1, ps.Z - dir.Z); + if (vm->m_area.contains(ps + v3s16(-dir.X, -1, -dir.Z)) && + vm->m_data[vi].getContent() == dp.c_wall) { + vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; + vm->m_data[vi] = MapNode(dp.c_stair, 0, facedir); } } else if (make_stairs == 1) { - u32 vi = vm->m_area.index(ps.X, - ps.Y - 1, ps.Z); - if (vm->m_area.contains( - ps + - v3s16(0, -1, 0)) && - vm->m_data[vi].getContent() == - dp.c_wall) { - vm->m_flags[vi] |= - VMANIP_FLAG_DUNGEON_UNTOUCHABLE; - vm->m_data[vi] = MapNode( - dp.c_stair, - 0, - facedir); + u32 vi = vm->m_area.index(ps.X, ps.Y - 1, ps.Z); + if (vm->m_area.contains(ps + v3s16(0, -1, 0)) && + vm->m_data[vi].getContent() == dp.c_wall) { + vm->m_flags[vi] |= VMANIP_FLAG_DUNGEON_UNTOUCHABLE; + vm->m_data[vi] = MapNode(dp.c_stair, 0, facedir); } } ps += swv; @@ -492,9 +467,10 @@ void DungeonGen::makeCorridor( } } else { makeFill(p + v3s16(-1, -1, -1), - dp.holesize + v3s16(2, 2, 2), - VMANIP_FLAG_DUNGEON_UNTOUCHABLE, - MapNode(dp.c_wall), 0); + dp.holesize + v3s16(2, 2, 2), + VMANIP_FLAG_DUNGEON_UNTOUCHABLE, + MapNode(dp.c_wall), + 0); makeHole(p); } @@ -525,6 +501,7 @@ void DungeonGen::makeCorridor( result_dir = dir; } + bool DungeonGen::findPlaceForDoor(v3s16 &result_place, v3s16 &result_dir) { for (u32 i = 0; i < 100; i++) { @@ -547,30 +524,25 @@ bool DungeonGen::findPlaceForDoor(v3s16 &result_place, v3s16 &result_dir) Determine where to move next */ // Jump one up if the actual space is there - if (vm->getNodeNoExNoEmerge(p + v3s16(0, 0, 0)).getContent() == - dp.c_wall && - vm->getNodeNoExNoEmerge(p + v3s16(0, 1, 0)) - .getContent() == - CONTENT_AIR && - vm->getNodeNoExNoEmerge(p + v3s16(0, 2, 0)) - .getContent() == - CONTENT_AIR) - p += v3s16(0, 1, 0); + if (vm->getNodeNoExNoEmerge(p + + v3s16(0, 0, 0)).getContent() == dp.c_wall && + vm->getNodeNoExNoEmerge(p + + v3s16(0, 1, 0)).getContent() == CONTENT_AIR && + vm->getNodeNoExNoEmerge(p + + v3s16(0, 2, 0)).getContent() == CONTENT_AIR) + p += v3s16(0,1,0); // Jump one down if the actual space is there - if (vm->getNodeNoExNoEmerge(p + v3s16(0, 1, 0)).getContent() == - dp.c_wall && - vm->getNodeNoExNoEmerge(p + v3s16(0, 0, 0)) - .getContent() == - CONTENT_AIR && - vm->getNodeNoExNoEmerge(p + v3s16(0, -1, 0)) - .getContent() == - CONTENT_AIR) + if (vm->getNodeNoExNoEmerge(p + + v3s16(0, 1, 0)).getContent() == dp.c_wall && + vm->getNodeNoExNoEmerge(p + + v3s16(0, 0, 0)).getContent() == CONTENT_AIR && + vm->getNodeNoExNoEmerge(p + + v3s16(0, -1, 0)).getContent() == CONTENT_AIR) p += v3s16(0, -1, 0); // Check if walking is now possible if (vm->getNodeNoExNoEmerge(p).getContent() != CONTENT_AIR || - vm->getNodeNoExNoEmerge(p + v3s16(0, 1, 0)) - .getContent() != - CONTENT_AIR) { + vm->getNodeNoExNoEmerge(p + + v3s16(0, 1, 0)).getContent() != CONTENT_AIR) { // Cannot continue walking here randomizeDir(); continue; @@ -581,8 +553,9 @@ bool DungeonGen::findPlaceForDoor(v3s16 &result_place, v3s16 &result_dir) return false; } + bool DungeonGen::findPlaceForRoomDoor(v3s16 roomsize, v3s16 &result_doorplace, - v3s16 &result_doordir, v3s16 &result_roomplace) + v3s16 &result_doordir, v3s16 &result_roomplace) { for (s16 trycount = 0; trycount < 30; trycount++) { v3s16 doorplace; @@ -594,46 +567,45 @@ bool DungeonGen::findPlaceForRoomDoor(v3s16 roomsize, v3s16 &result_doorplace, // X east, Z north, Y up if (doordir == v3s16(1, 0, 0)) // X+ roomplace = doorplace + - v3s16(0, -1, random.range(-roomsize.Z + 2, -2)); + v3s16(0, -1, random.range(-roomsize.Z + 2, -2)); if (doordir == v3s16(-1, 0, 0)) // X- roomplace = doorplace + - v3s16(-roomsize.X + 1, -1, - random.range(-roomsize.Z + 2, -2)); + v3s16(-roomsize.X + 1, -1, random.range(-roomsize.Z + 2, -2)); if (doordir == v3s16(0, 0, 1)) // Z+ roomplace = doorplace + - v3s16(random.range(-roomsize.X + 2, -2), -1, 0); + v3s16(random.range(-roomsize.X + 2, -2), -1, 0); if (doordir == v3s16(0, 0, -1)) // Z- - roomplace = doorplace + v3s16(random.range(-roomsize.X + 2, -2), - -1, -roomsize.Z + 1); + roomplace = doorplace + + v3s16(random.range(-roomsize.X + 2, -2), -1, -roomsize.Z + 1); // Check fit bool fits = true; for (s16 z = 1; z < roomsize.Z - 1; z++) - for (s16 y = 1; y < roomsize.Y - 1; y++) - for (s16 x = 1; x < roomsize.X - 1; x++) { - v3s16 p = roomplace + v3s16(x, y, z); - if (!vm->m_area.contains(p)) { - fits = false; - break; - } - if (vm->m_flags[vm->m_area.index(p)] & - VMANIP_FLAG_DUNGEON_INSIDE) { - fits = false; - break; - } - } + for (s16 y = 1; y < roomsize.Y - 1; y++) + for (s16 x = 1; x < roomsize.X - 1; x++) { + v3s16 p = roomplace + v3s16(x, y, z); + if (!vm->m_area.contains(p)) { + fits = false; + break; + } + if (vm->m_flags[vm->m_area.index(p)] & VMANIP_FLAG_DUNGEON_INSIDE) { + fits = false; + break; + } + } if (!fits) { // Find new place continue; } result_doorplace = doorplace; - result_doordir = doordir; + result_doordir = doordir; result_roomplace = roomplace; return true; } return false; } + v3s16 rand_ortho_dir(PseudoRandom &random, bool diagonal_dirs) { // Make diagonal directions somewhat rare @@ -658,6 +630,7 @@ v3s16 rand_ortho_dir(PseudoRandom &random, bool diagonal_dirs) return random.next() % 2 ? v3s16(0, 0, -1) : v3s16(0, 0, 1); } + v3s16 turn_xz(v3s16 olddir, int t) { v3s16 dir; @@ -675,6 +648,7 @@ v3s16 turn_xz(v3s16 olddir, int t) return dir; } + void random_turn(PseudoRandom &random, v3s16 &dir) { int turn = random.range(0, 2); @@ -690,6 +664,7 @@ void random_turn(PseudoRandom &random, v3s16 &dir) } } + int dir_to_facedir(v3s16 d) { if (abs(d.X) > abs(d.Z)) diff --git a/src/mapgen/dungeongen.h b/src/mapgen/dungeongen.h index f70fedb5e..35e6beef5 100644 --- a/src/mapgen/dungeongen.h +++ b/src/mapgen/dungeongen.h @@ -26,8 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #define VMANIP_FLAG_DUNGEON_INSIDE VOXELFLAG_CHECKED1 #define VMANIP_FLAG_DUNGEON_PRESERVE VOXELFLAG_CHECKED2 -#define VMANIP_FLAG_DUNGEON_UNTOUCHABLE \ - (VMANIP_FLAG_DUNGEON_INSIDE | VMANIP_FLAG_DUNGEON_PRESERVE) +#define VMANIP_FLAG_DUNGEON_UNTOUCHABLE (\ + VMANIP_FLAG_DUNGEON_INSIDE|VMANIP_FLAG_DUNGEON_PRESERVE) class MMVManip; class NodeDefManager; @@ -37,8 +37,8 @@ v3s16 turn_xz(v3s16 olddir, int t); void random_turn(PseudoRandom &random, v3s16 &dir); int dir_to_facedir(v3s16 d); -struct DungeonParams -{ + +struct DungeonParams { s32 seed; content_t c_wall; @@ -82,8 +82,7 @@ struct DungeonParams GenNotifyType notifytype; }; -class DungeonGen -{ +class DungeonGen { public: MMVManip *vm = nullptr; const NodeDefManager *ndef; @@ -100,15 +99,15 @@ class DungeonGen v3s16 m_pos; v3s16 m_dir; - DungeonGen(const NodeDefManager *ndef, GenerateNotifier *gennotify, - DungeonParams *dparams); + DungeonGen(const NodeDefManager *ndef, + GenerateNotifier *gennotify, DungeonParams *dparams); void generate(MMVManip *vm, u32 bseed, v3s16 full_node_min, v3s16 full_node_max); void makeDungeon(v3s16 start_padding); void makeRoom(v3s16 roomsize, v3s16 roomplace); - void makeCorridor(v3s16 doorplace, v3s16 doordir, v3s16 &result_place, - v3s16 &result_dir); + void makeCorridor(v3s16 doorplace, v3s16 doordir, + v3s16 &result_place, v3s16 &result_dir); void makeDoor(v3s16 doorplace, v3s16 doordir); void makeFill(v3s16 place, v3s16 size, u8 avoid_flags, MapNode n, u8 or_flags); void makeHole(v3s16 place); @@ -117,7 +116,10 @@ class DungeonGen bool findPlaceForRoomDoor(v3s16 roomsize, v3s16 &result_doorplace, v3s16 &result_doordir, v3s16 &result_roomplace); - inline void randomizeDir() { m_dir = rand_ortho_dir(random, dp.diagonal_dirs); } + inline void randomizeDir() + { + m_dir = rand_ortho_dir(random, dp.diagonal_dirs); + } }; extern NoiseParams nparams_dungeon_density; diff --git a/src/mapgen/mapgen.cpp b/src/mapgen/mapgen.cpp index 84cb79400..f57529082 100644 --- a/src/mapgen/mapgen.cpp +++ b/src/mapgen/mapgen.cpp @@ -52,20 +52,27 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cavegen.h" #include "dungeongen.h" -FlagDesc flagdesc_mapgen[] = {{"caves", MG_CAVES}, {"dungeons", MG_DUNGEONS}, - {"light", MG_LIGHT}, {"decorations", MG_DECORATIONS}, - {"biomes", MG_BIOMES}, {NULL, 0}}; - -FlagDesc flagdesc_gennotify[] = {{"dungeon", 1 << GENNOTIFY_DUNGEON}, - {"temple", 1 << GENNOTIFY_TEMPLE}, - {"cave_begin", 1 << GENNOTIFY_CAVE_BEGIN}, - {"cave_end", 1 << GENNOTIFY_CAVE_END}, - {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN}, - {"large_cave_end", 1 << GENNOTIFY_LARGECAVE_END}, - {"decoration", 1 << GENNOTIFY_DECORATION}, {NULL, 0}}; - -struct MapgenDesc -{ +FlagDesc flagdesc_mapgen[] = { + {"caves", MG_CAVES}, + {"dungeons", MG_DUNGEONS}, + {"light", MG_LIGHT}, + {"decorations", MG_DECORATIONS}, + {"biomes", MG_BIOMES}, + {NULL, 0} +}; + +FlagDesc flagdesc_gennotify[] = { + {"dungeon", 1 << GENNOTIFY_DUNGEON}, + {"temple", 1 << GENNOTIFY_TEMPLE}, + {"cave_begin", 1 << GENNOTIFY_CAVE_BEGIN}, + {"cave_end", 1 << GENNOTIFY_CAVE_END}, + {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN}, + {"large_cave_end", 1 << GENNOTIFY_LARGECAVE_END}, + {"decoration", 1 << GENNOTIFY_DECORATION}, + {NULL, 0} +}; + +struct MapgenDesc { const char *name; bool is_user_visible; }; @@ -81,30 +88,32 @@ struct MapgenDesc // Of the remaining, v5 last due to age, v7 first due to being the default. // The order of 'enum MapgenType' in mapgen.h must match this order. static MapgenDesc g_reg_mapgens[] = { - {"v7", true}, - {"valleys", true}, - {"carpathian", true}, - {"v5", true}, - {"flat", true}, - {"fractal", true}, - {"singlenode", true}, - {"v6", true}, + {"v7", true}, + {"valleys", true}, + {"carpathian", true}, + {"v5", true}, + {"flat", true}, + {"fractal", true}, + {"singlenode", true}, + {"v6", true}, }; -STATIC_ASSERT(ARRLEN(g_reg_mapgens) == MAPGEN_INVALID, registered_mapgens_is_wrong_size); +STATIC_ASSERT( + ARRLEN(g_reg_mapgens) == MAPGEN_INVALID, + registered_mapgens_is_wrong_size); //// //// Mapgen //// Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeParams *emerge) : - gennotify(emerge->gen_notify_on, emerge->gen_notify_on_deco_ids) + gennotify(emerge->gen_notify_on, emerge->gen_notify_on_deco_ids) { - id = mapgenid; - water_level = params->water_level; + id = mapgenid; + water_level = params->water_level; mapgen_limit = params->mapgen_limit; - flags = params->flags; - csize = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE); + flags = params->flags; + csize = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE); /* We are losing half our entropy by doing this, but it is necessary to @@ -121,9 +130,10 @@ Mapgen::Mapgen(int mapgenid, MapgenParams *params, EmergeParams *emerge) : */ seed = (s32)params->seed; - ndef = emerge->ndef; + ndef = emerge->ndef; } + MapgenType Mapgen::getMapgenType(const std::string &mgname) { for (size_t i = 0; i != ARRLEN(g_reg_mapgens); i++) { @@ -134,6 +144,7 @@ MapgenType Mapgen::getMapgenType(const std::string &mgname) return MAPGEN_INVALID; } + const char *Mapgen::getMapgenName(MapgenType mgtype) { size_t index = (size_t)mgtype; @@ -143,8 +154,9 @@ const char *Mapgen::getMapgenName(MapgenType mgtype) return g_reg_mapgens[index].name; } -Mapgen *Mapgen::createMapgen( - MapgenType mgtype, MapgenParams *params, EmergeParams *emerge) + +Mapgen *Mapgen::createMapgen(MapgenType mgtype, MapgenParams *params, + EmergeParams *emerge) { switch (mgtype) { case MAPGEN_CARPATHIAN: @@ -168,6 +180,7 @@ Mapgen *Mapgen::createMapgen( } } + MapgenParams *Mapgen::createMapgenParams(MapgenType mgtype) { switch (mgtype) { @@ -192,6 +205,7 @@ MapgenParams *Mapgen::createMapgenParams(MapgenType mgtype) } } + void Mapgen::getMapgenNames(std::vector *mgnames, bool include_hidden) { for (u32 i = 0; i != ARRLEN(g_reg_mapgens); i++) { @@ -203,7 +217,7 @@ void Mapgen::getMapgenNames(std::vector *mgnames, bool include_hid void Mapgen::setDefaultSettings(Settings *settings) { settings->setDefault("mg_flags", flagdesc_mapgen, - MG_CAVES | MG_DUNGEONS | MG_LIGHT | MG_DECORATIONS | MG_BIOMES); + MG_CAVES | MG_DUNGEONS | MG_LIGHT | MG_DECORATIONS | MG_BIOMES); for (int i = 0; i < (int)MAPGEN_INVALID; ++i) { MapgenParams *params = createMapgenParams((MapgenType)i); @@ -214,9 +228,13 @@ void Mapgen::setDefaultSettings(Settings *settings) u32 Mapgen::getBlockSeed(v3s16 p, s32 seed) { - return (u32)seed + p.Z * 38134234 + p.Y * 42123 + p.X * 23; + return (u32)seed + + p.Z * 38134234 + + p.Y * 42123 + + p.X * 23; } + u32 Mapgen::getBlockSeed2(v3s16 p, s32 seed) { u32 n = 1619 * p.X + 31337 * p.Y + 52591 * p.Z + 1013 * seed; @@ -224,6 +242,7 @@ u32 Mapgen::getBlockSeed2(v3s16 p, s32 seed) return (n * (n * n * 60493 + 19990303) + 1376312589); } + // Returns Y one under area minimum if not found s16 Mapgen::findGroundLevelFull(v2s16 p2d) { @@ -243,6 +262,7 @@ s16 Mapgen::findGroundLevelFull(v2s16 p2d) return (y >= y_nodes_min) ? y : y_nodes_min - 1; } + // Returns -MAX_MAP_GENERATION_LIMIT if not found s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) { @@ -260,6 +280,7 @@ s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT; } + // Returns -MAX_MAP_GENERATION_LIMIT if not found or if ground is found first s16 Mapgen::findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax) { @@ -280,12 +301,13 @@ s16 Mapgen::findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax) return (y >= ymin) ? y : -MAX_MAP_GENERATION_LIMIT; } + void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) { if (!heightmap) return; - // TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO); + //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO); int index = 0; for (s16 z = nmin.Z; z <= nmax.Z; z++) { for (s16 x = nmin.X; x <= nmax.X; x++, index++) { @@ -296,8 +318,9 @@ void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) } } -void Mapgen::getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, std::vector &floors, - std::vector &ceilings) + +void Mapgen::getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, + std::vector &floors, std::vector &ceilings) { const v3s16 &em = vm->m_area.getExtent(); @@ -322,6 +345,7 @@ void Mapgen::getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, std::vector &floors } } + inline bool Mapgen::isLiquidHorizontallyFlowable(u32 vi, v3s16 em) { u32 vi_neg_x = vi; @@ -358,60 +382,55 @@ inline bool Mapgen::isLiquidHorizontallyFlowable(u32 vi, v3s16 em) void Mapgen::updateLiquid(UniqueQueue *trans_liquid, v3s16 nmin, v3s16 nmax) { bool isignored, isliquid, wasignored, wasliquid, waschecked, waspushed; - const v3s16 &em = vm->m_area.getExtent(); + const v3s16 &em = vm->m_area.getExtent(); for (s16 z = nmin.Z + 1; z <= nmax.Z - 1; z++) - for (s16 x = nmin.X + 1; x <= nmax.X - 1; x++) { - wasignored = true; - wasliquid = false; - waschecked = false; - waspushed = false; - - u32 vi = vm->m_area.index(x, nmax.Y, z); - for (s16 y = nmax.Y; y >= nmin.Y; y--) { - isignored = vm->m_data[vi].getContent() == CONTENT_IGNORE; - isliquid = ndef->get(vm->m_data[vi]).isLiquid(); - - if (isignored || wasignored || isliquid == wasliquid) { - // Neither topmost node of liquid column nor - // topmost node below column - waschecked = false; - waspushed = false; - } else if (isliquid) { - // This is the topmost node in the column - bool ispushed = false; - if (isLiquidHorizontallyFlowable(vi, em)) { - trans_liquid->push_back(v3s16(x, y, z)); - ispushed = true; - } - // Remember waschecked and waspushed to avoid - // repeated checks/pushes in case the column - // consists of only this node - waschecked = true; - waspushed = ispushed; - } else { - // This is the topmost node below a liquid column - u32 vi_above = vi; - VoxelArea::add_y(em, vi_above, 1); - if (!waspushed && - (ndef->get(vm->m_data[vi]).floodable || - (!waschecked && isLiquidHorizontallyFlowable( - vi_above, - em)))) { - // Push back the lowest node in the column - // which is one node above this one - trans_liquid->push_back( - v3s16(x, y + 1, z)); - } + for (s16 x = nmin.X + 1; x <= nmax.X - 1; x++) { + wasignored = true; + wasliquid = false; + waschecked = false; + waspushed = false; + + u32 vi = vm->m_area.index(x, nmax.Y, z); + for (s16 y = nmax.Y; y >= nmin.Y; y--) { + isignored = vm->m_data[vi].getContent() == CONTENT_IGNORE; + isliquid = ndef->get(vm->m_data[vi]).isLiquid(); + + if (isignored || wasignored || isliquid == wasliquid) { + // Neither topmost node of liquid column nor topmost node below column + waschecked = false; + waspushed = false; + } else if (isliquid) { + // This is the topmost node in the column + bool ispushed = false; + if (isLiquidHorizontallyFlowable(vi, em)) { + trans_liquid->push_back(v3s16(x, y, z)); + ispushed = true; + } + // Remember waschecked and waspushed to avoid repeated + // checks/pushes in case the column consists of only this node + waschecked = true; + waspushed = ispushed; + } else { + // This is the topmost node below a liquid column + u32 vi_above = vi; + VoxelArea::add_y(em, vi_above, 1); + if (!waspushed && (ndef->get(vm->m_data[vi]).floodable || + (!waschecked && isLiquidHorizontallyFlowable(vi_above, em)))) { + // Push back the lowest node in the column which is one + // node above this one + trans_liquid->push_back(v3s16(x, y + 1, z)); } - - wasliquid = isliquid; - wasignored = isignored; - VoxelArea::add_y(em, vi, -1); } + + wasliquid = isliquid; + wasignored = isignored; + VoxelArea::add_y(em, vi, -1); } + } } + void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax) { ScopeProfiler sp(g_profiler, "EmergeThread: update lighting", SPT_AVG); @@ -426,8 +445,9 @@ void Mapgen::setLighting(u8 light, v3s16 nmin, v3s16 nmax) } } + void Mapgen::lightSpread(VoxelArea &a, std::queue> &queue, - const v3s16 &p, u8 light) + const v3s16 &p, u8 light) { if (light <= 1 || !a.contains(p)) return; @@ -446,14 +466,16 @@ void Mapgen::lightSpread(VoxelArea &a, std::queue> &queue, // Bail out only if we have no more light from either bank to propogate, or // we hit a solid block that light cannot pass through. - if ((light_day <= (n.param1 & 0x0F) && light_night <= (n.param1 & 0xF0)) || + if ((light_day <= (n.param1 & 0x0F) && + light_night <= (n.param1 & 0xF0)) || !ndef->get(n).light_propagates) return; // Since this recursive function only terminates when there is no light from // either bank left, we need to take the max of both banks into account for // the case where spreading has stopped for one light bank but not the other. - light = MYMAX(light_day, n.param1 & 0x0F) | MYMAX(light_night, n.param1 & 0xF0); + light = MYMAX(light_day, n.param1 & 0x0F) | + MYMAX(light_night, n.param1 & 0xF0); n.param1 = light; @@ -461,21 +483,23 @@ void Mapgen::lightSpread(VoxelArea &a, std::queue> &queue, queue.emplace(p, light); } + void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax, - bool propagate_shadow) + bool propagate_shadow) { ScopeProfiler sp(g_profiler, "EmergeThread: update lighting", SPT_AVG); - // TimeTaker t("updateLighting"); + //TimeTaker t("updateLighting"); propagateSunlight(nmin, nmax, propagate_shadow); spreadLight(full_nmin, full_nmax); - // printf("updateLighting: %dms\n", t.stop()); + //printf("updateLighting: %dms\n", t.stop()); } + void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow) { - // TimeTaker t("propagateSunlight"); + //TimeTaker t("propagateSunlight"); VoxelArea a(nmin, nmax); bool block_is_underground = (water_level >= nmax.Y); const v3s16 &em = vm->m_area.getExtent(); @@ -505,12 +529,13 @@ void Mapgen::propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow) } } } - // printf("propagateSunlight: %dms\n", t.stop()); + //printf("propagateSunlight: %dms\n", t.stop()); } + void Mapgen::spreadLight(const v3s16 &nmin, const v3s16 &nmax) { - // TimeTaker t("spreadLight"); + //TimeTaker t("spreadLight"); std::queue> queue; VoxelArea a(nmin, nmax); @@ -526,9 +551,8 @@ void Mapgen::spreadLight(const v3s16 &nmin, const v3s16 &nmax) if (!cf.light_propagates) continue; - // TODO(hmmmmm): Abstract away direct param1 accesses with - // a wrapper, but something lighter than - // MapNode::get/setLight + // TODO(hmmmmm): Abstract away direct param1 accesses with a + // wrapper, but something lighter than MapNode::get/setLight u8 light_produced = cf.light_source; if (light_produced) @@ -553,18 +577,19 @@ void Mapgen::spreadLight(const v3s16 &nmin, const v3s16 &nmax) queue.pop(); } - // printf("spreadLight: %lums\n", t.stop()); + //printf("spreadLight: %lums\n", t.stop()); } + //// //// MapgenBasic //// -MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerge) : - Mapgen(mapgenid, params, emerge) +MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerge) + : Mapgen(mapgenid, params, emerge) { this->m_emerge = emerge; - this->m_bmgr = emerge->biomemgr; + this->m_bmgr = emerge->biomemgr; //// Here, 'stride' refers to the number of elements needed to skip to index //// an adjacent element for that coordinate in noise/height/biome maps @@ -593,11 +618,11 @@ MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerg biomemap = biomegen->biomemap; //// Look up some commonly used content - c_stone = ndef->getId("mapgen_stone"); - c_water_source = ndef->getId("mapgen_water_source"); + c_stone = ndef->getId("mapgen_stone"); + c_water_source = ndef->getId("mapgen_water_source"); c_river_water_source = ndef->getId("mapgen_river_water_source"); - c_lava_source = ndef->getId("mapgen_lava_source"); - c_cobble = ndef->getId("mapgen_cobble"); + c_lava_source = ndef->getId("mapgen_lava_source"); + c_cobble = ndef->getId("mapgen_cobble"); // Fall back to more basic content if not defined. // Lava falls back to water as both are suitable as cave liquids. @@ -605,25 +630,23 @@ MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerg c_lava_source = c_water_source; if (c_stone == CONTENT_IGNORE) - errorstream << "Mapgen: Mapgen alias 'mapgen_stone' is invalid!" - << std::endl; + errorstream << "Mapgen: Mapgen alias 'mapgen_stone' is invalid!" << std::endl; if (c_water_source == CONTENT_IGNORE) - errorstream << "Mapgen: Mapgen alias 'mapgen_water_source' is invalid!" - << std::endl; + errorstream << "Mapgen: Mapgen alias 'mapgen_water_source' is invalid!" << std::endl; if (c_river_water_source == CONTENT_IGNORE) - warningstream << "Mapgen: Mapgen alias 'mapgen_river_water_source' is " - "invalid!" - << std::endl; + warningstream << "Mapgen: Mapgen alias 'mapgen_river_water_source' is invalid!" << std::endl; } + MapgenBasic::~MapgenBasic() { delete biomegen; - delete[] heightmap; + delete []heightmap; delete m_emerge; // destroying EmergeParams is our responsibility } + void MapgenBasic::generateBiomes() { // can't generate biomes without a biome generator! @@ -636,158 +659,131 @@ void MapgenBasic::generateBiomes() noise_filler_depth->perlinMap2D(node_min.X, node_min.Z); for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index++) { - Biome *biome = NULL; - biome_t water_biome_index = 0; - u16 depth_top = 0; - u16 base_filler = 0; - u16 depth_water_top = 0; - u16 depth_riverbed = 0; - s16 biome_y_min = -MAX_MAP_GENERATION_LIMIT; - u32 vi = vm->m_area.index(x, node_max.Y, z); - - // Check node at base of mapchunk above, either a node of a - // previously generated mapchunk or if not, a node of - // overgenerated base terrain. - content_t c_above = vm->m_data[vi + em.X].getContent(); - bool air_above = c_above == CONTENT_AIR; - bool river_water_above = c_above == c_river_water_source; - bool water_above = c_above == c_water_source || river_water_above; - - biomemap[index] = BIOME_NONE; - - // If there is air or water above enable top/filler placement, - // otherwise force nplaced to stone level by setting a number - // exceeding any possible filler depth. - u16 nplaced = (air_above || water_above) ? 0 : U16_MAX; - - for (s16 y = node_max.Y; y >= node_min.Y; y--) { - content_t c = vm->m_data[vi].getContent(); - // Biome is (re)calculated: - // 1. At the surface of stone below air or water. - // 2. At the surface of water below air. - // 3. When stone or water is detected but biome has not - // yet been calculated. - // 4. When stone or water is detected just below a biome's - // lower limit. - bool is_stone_surface = - (c == c_stone) && - (air_above || water_above || !biome || - y < biome_y_min); // 1, 3, - // 4 - - bool is_water_surface = - (c == c_water_source || - c == c_river_water_source) && - (air_above || !biome || - y < biome_y_min); // 2, 3, - // 4 - - if (is_stone_surface || is_water_surface) { - // (Re)calculate biome - biome = biomegen->getBiomeAtIndex( - index, v3s16(x, y, z)); - - // Add biome to biomemap at first stone surface - // detected - if (biomemap[index] == BIOME_NONE && - is_stone_surface) - biomemap[index] = biome->index; - - // Store biome of first water surface detected, as - // a fallback entry for the biomemap. - if (water_biome_index == 0 && is_water_surface) - water_biome_index = biome->index; - - depth_top = biome->depth_top; - base_filler = MYMAX( - depth_top + biome->depth_filler + - noise_filler_depth->result - [index], - 0.0f); - depth_water_top = biome->depth_water_top; - depth_riverbed = biome->depth_riverbed; - biome_y_min = biome->min_pos.Y; - } + for (s16 x = node_min.X; x <= node_max.X; x++, index++) { + Biome *biome = NULL; + biome_t water_biome_index = 0; + u16 depth_top = 0; + u16 base_filler = 0; + u16 depth_water_top = 0; + u16 depth_riverbed = 0; + s16 biome_y_min = -MAX_MAP_GENERATION_LIMIT; + u32 vi = vm->m_area.index(x, node_max.Y, z); + + // Check node at base of mapchunk above, either a node of a previously + // generated mapchunk or if not, a node of overgenerated base terrain. + content_t c_above = vm->m_data[vi + em.X].getContent(); + bool air_above = c_above == CONTENT_AIR; + bool river_water_above = c_above == c_river_water_source; + bool water_above = c_above == c_water_source || river_water_above; + + biomemap[index] = BIOME_NONE; + + // If there is air or water above enable top/filler placement, otherwise force + // nplaced to stone level by setting a number exceeding any possible filler depth. + u16 nplaced = (air_above || water_above) ? 0 : U16_MAX; + + for (s16 y = node_max.Y; y >= node_min.Y; y--) { + content_t c = vm->m_data[vi].getContent(); + // Biome is (re)calculated: + // 1. At the surface of stone below air or water. + // 2. At the surface of water below air. + // 3. When stone or water is detected but biome has not yet been calculated. + // 4. When stone or water is detected just below a biome's lower limit. + bool is_stone_surface = (c == c_stone) && + (air_above || water_above || !biome || y < biome_y_min); // 1, 3, 4 + + bool is_water_surface = + (c == c_water_source || c == c_river_water_source) && + (air_above || !biome || y < biome_y_min); // 2, 3, 4 + + if (is_stone_surface || is_water_surface) { + // (Re)calculate biome + biome = biomegen->getBiomeAtIndex(index, v3s16(x, y, z)); + + // Add biome to biomemap at first stone surface detected + if (biomemap[index] == BIOME_NONE && is_stone_surface) + biomemap[index] = biome->index; + + // Store biome of first water surface detected, as a fallback + // entry for the biomemap. + if (water_biome_index == 0 && is_water_surface) + water_biome_index = biome->index; + + depth_top = biome->depth_top; + base_filler = MYMAX(depth_top + + biome->depth_filler + + noise_filler_depth->result[index], 0.0f); + depth_water_top = biome->depth_water_top; + depth_riverbed = biome->depth_riverbed; + biome_y_min = biome->min_pos.Y; + } - if (c == c_stone) { - content_t c_below = vm->m_data[vi - em.X] - .getContent(); - - // If the node below isn't solid, make this node - // stone, so that any top/filler nodes above are - // structurally supported. This is done by - // aborting the cycle of top/filler placement - // immediately by forcing nplaced to stone level. - if (c_below == CONTENT_AIR || - c_below == c_water_source || - c_below == c_river_water_source) - nplaced = U16_MAX; - - if (river_water_above) { - if (nplaced < depth_riverbed) { - vm->m_data[vi] = MapNode( - biome->c_riverbed); - nplaced++; - } else { - nplaced = U16_MAX; // Disable - // top/filler - // placement - river_water_above = false; - } - } else if (nplaced < depth_top) { - vm->m_data[vi] = MapNode(biome->c_top); - nplaced++; - } else if (nplaced < base_filler) { - vm->m_data[vi] = MapNode(biome->c_filler); + if (c == c_stone) { + content_t c_below = vm->m_data[vi - em.X].getContent(); + + // If the node below isn't solid, make this node stone, so that + // any top/filler nodes above are structurally supported. + // This is done by aborting the cycle of top/filler placement + // immediately by forcing nplaced to stone level. + if (c_below == CONTENT_AIR + || c_below == c_water_source + || c_below == c_river_water_source) + nplaced = U16_MAX; + + if (river_water_above) { + if (nplaced < depth_riverbed) { + vm->m_data[vi] = MapNode(biome->c_riverbed); nplaced++; } else { - vm->m_data[vi] = MapNode(biome->c_stone); - nplaced = U16_MAX; // Disable top/filler - // placement + nplaced = U16_MAX; // Disable top/filler placement + river_water_above = false; } - - air_above = false; - water_above = false; - } else if (c == c_water_source) { - vm->m_data[vi] = MapNode( - (y > (s32)(water_level - - depth_water_top)) - ? biome->c_water_top - : biome->c_water); - nplaced = 0; // Enable top/filler placement for - // next surface - air_above = false; - water_above = true; - } else if (c == c_river_water_source) { - vm->m_data[vi] = MapNode(biome->c_river_water); - nplaced = 0; // Enable riverbed placement for next - // surface - air_above = false; - water_above = true; - river_water_above = true; - } else if (c == CONTENT_AIR) { - nplaced = 0; // Enable top/filler placement for - // next surface - air_above = true; - water_above = false; - } else { // Possible various nodes overgenerated from - // neighbouring mapchunks - nplaced = U16_MAX; // Disable top/filler placement - air_above = false; - water_above = false; + } else if (nplaced < depth_top) { + vm->m_data[vi] = MapNode(biome->c_top); + nplaced++; + } else if (nplaced < base_filler) { + vm->m_data[vi] = MapNode(biome->c_filler); + nplaced++; + } else { + vm->m_data[vi] = MapNode(biome->c_stone); + nplaced = U16_MAX; // Disable top/filler placement } - VoxelArea::add_y(em, vi, -1); + air_above = false; + water_above = false; + } else if (c == c_water_source) { + vm->m_data[vi] = MapNode((y > (s32)(water_level - depth_water_top)) + ? biome->c_water_top : biome->c_water); + nplaced = 0; // Enable top/filler placement for next surface + air_above = false; + water_above = true; + } else if (c == c_river_water_source) { + vm->m_data[vi] = MapNode(biome->c_river_water); + nplaced = 0; // Enable riverbed placement for next surface + air_above = false; + water_above = true; + river_water_above = true; + } else if (c == CONTENT_AIR) { + nplaced = 0; // Enable top/filler placement for next surface + air_above = true; + water_above = false; + } else { // Possible various nodes overgenerated from neighbouring mapchunks + nplaced = U16_MAX; // Disable top/filler placement + air_above = false; + water_above = false; } - // If no stone surface detected in mapchunk column and a water - // surface biome fallback exists, add it to the biomemap. This - // avoids water surface decorations failing in deep water. - if (biomemap[index] == BIOME_NONE && water_biome_index != 0) - biomemap[index] = water_biome_index; + + VoxelArea::add_y(em, vi, -1); } + // If no stone surface detected in mapchunk column and a water surface + // biome fallback exists, add it to the biomemap. This avoids water + // surface decorations failing in deep water. + if (biomemap[index] == BIOME_NONE && water_biome_index != 0) + biomemap[index] = water_biome_index; + } } + void MapgenBasic::dustTopNodes() { if (node_max.Y < water_level) @@ -797,59 +793,61 @@ void MapgenBasic::dustTopNodes() u32 index = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index++) { - Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index]); - - if (biome->c_dust == CONTENT_IGNORE) - continue; - - // Check if mapchunk above has generated, if so, drop dust from 16 - // nodes above current mapchunk top, above decorations that will - // extend above the current mapchunk. If the mapchunk above has - // not generated, it will provide this required dust when it does. - u32 vi = vm->m_area.index(x, full_node_max.Y, z); - content_t c_full_max = vm->m_data[vi].getContent(); - s16 y_start; - - if (c_full_max == CONTENT_AIR) { - y_start = full_node_max.Y - 1; - } else if (c_full_max == CONTENT_IGNORE) { - vi = vm->m_area.index(x, node_max.Y + 1, z); - content_t c_max = vm->m_data[vi].getContent(); - - if (c_max == CONTENT_AIR) - y_start = node_max.Y; - else - continue; - } else { + for (s16 x = node_min.X; x <= node_max.X; x++, index++) { + Biome *biome = (Biome *)m_bmgr->getRaw(biomemap[index]); + + if (biome->c_dust == CONTENT_IGNORE) + continue; + + // Check if mapchunk above has generated, if so, drop dust from 16 nodes + // above current mapchunk top, above decorations that will extend above + // the current mapchunk. If the mapchunk above has not generated, it + // will provide this required dust when it does. + u32 vi = vm->m_area.index(x, full_node_max.Y, z); + content_t c_full_max = vm->m_data[vi].getContent(); + s16 y_start; + + if (c_full_max == CONTENT_AIR) { + y_start = full_node_max.Y - 1; + } else if (c_full_max == CONTENT_IGNORE) { + vi = vm->m_area.index(x, node_max.Y + 1, z); + content_t c_max = vm->m_data[vi].getContent(); + + if (c_max == CONTENT_AIR) + y_start = node_max.Y; + else continue; - } + } else { + continue; + } - vi = vm->m_area.index(x, y_start, z); - for (s16 y = y_start; y >= node_min.Y - 1; y--) { - if (vm->m_data[vi].getContent() != CONTENT_AIR) - break; + vi = vm->m_area.index(x, y_start, z); + for (s16 y = y_start; y >= node_min.Y - 1; y--) { + if (vm->m_data[vi].getContent() != CONTENT_AIR) + break; - VoxelArea::add_y(em, vi, -1); - } + VoxelArea::add_y(em, vi, -1); + } - content_t c = vm->m_data[vi].getContent(); - NodeDrawType dtype = ndef->get(c).drawtype; - // Only place on cubic, walkable, non-dust nodes. - // Dust check needed due to avoid double layer of dust caused by - // dropping dust from 16 nodes above mapchunk top. - if ((dtype == NDT_NORMAL || dtype == NDT_ALLFACES || - dtype == NDT_ALLFACES_OPTIONAL || - dtype == NDT_GLASSLIKE || - dtype == NDT_GLASSLIKE_FRAMED || - dtype == NDT_GLASSLIKE_FRAMED_OPTIONAL) && - ndef->get(c).walkable && c != biome->c_dust) { - VoxelArea::add_y(em, vi, 1); - vm->m_data[vi] = MapNode(biome->c_dust); - } + content_t c = vm->m_data[vi].getContent(); + NodeDrawType dtype = ndef->get(c).drawtype; + // Only place on cubic, walkable, non-dust nodes. + // Dust check needed due to avoid double layer of dust caused by + // dropping dust from 16 nodes above mapchunk top. + if ((dtype == NDT_NORMAL || + dtype == NDT_ALLFACES || + dtype == NDT_ALLFACES_OPTIONAL || + dtype == NDT_GLASSLIKE || + dtype == NDT_GLASSLIKE_FRAMED || + dtype == NDT_GLASSLIKE_FRAMED_OPTIONAL) && + ndef->get(c).walkable && c != biome->c_dust) { + VoxelArea::add_y(em, vi, 1); + vm->m_data[vi] = MapNode(biome->c_dust); } + } } + void MapgenBasic::generateCavesNoiseIntersection(s16 max_stone_y) { // cave_width >= 10 is used to disable generation and avoid the intensive @@ -857,12 +855,13 @@ void MapgenBasic::generateCavesNoiseIntersection(s16 max_stone_y) if (node_min.Y > max_stone_y || cave_width >= 10.0f) return; - CavesNoiseIntersection caves_noise( - ndef, m_bmgr, csize, &np_cave1, &np_cave2, seed, cave_width); + CavesNoiseIntersection caves_noise(ndef, m_bmgr, csize, + &np_cave1, &np_cave2, seed, cave_width); caves_noise.generateCaves(vm, node_min, node_max, biomemap); } + void MapgenBasic::generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_ymax) { if (node_min.Y > max_stone_y) @@ -873,8 +872,8 @@ void MapgenBasic::generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_ymax) u32 num_small_caves = ps.range(small_cave_num_min, small_cave_num_max); for (u32 i = 0; i < num_small_caves; i++) { - CavesRandomWalk cave(ndef, &gennotify, seed, water_level, c_water_source, - c_lava_source, large_cave_flooded, biomegen); + CavesRandomWalk cave(ndef, &gennotify, seed, water_level, + c_water_source, c_lava_source, large_cave_flooded, biomegen); cave.makeCave(vm, node_min, node_max, &ps, false, max_stone_y, heightmap); } @@ -887,32 +886,33 @@ void MapgenBasic::generateCavesRandomWalk(s16 max_stone_y, s16 large_cave_ymax) u32 num_large_caves = ps.range(large_cave_num_min, large_cave_num_max); for (u32 i = 0; i < num_large_caves; i++) { - CavesRandomWalk cave(ndef, &gennotify, seed, water_level, c_water_source, - c_lava_source, large_cave_flooded, biomegen); + CavesRandomWalk cave(ndef, &gennotify, seed, water_level, + c_water_source, c_lava_source, large_cave_flooded, biomegen); cave.makeCave(vm, node_min, node_max, &ps, true, max_stone_y, heightmap); } } + bool MapgenBasic::generateCavernsNoise(s16 max_stone_y) { if (node_min.Y > max_stone_y || node_min.Y > cavern_limit) return false; - CavernsNoise caverns_noise(ndef, csize, &np_cavern, seed, cavern_limit, - cavern_taper, cavern_threshold); + CavernsNoise caverns_noise(ndef, csize, &np_cavern, + seed, cavern_limit, cavern_taper, cavern_threshold); return caverns_noise.generateCaverns(vm, node_min, node_max); } + void MapgenBasic::generateDungeons(s16 max_stone_y) { if (node_min.Y > max_stone_y || node_min.Y > dungeon_ymax || node_max.Y < dungeon_ymin) return; - u16 num_dungeons = std::fmax(std::floor(NoisePerlin3D(&np_dungeons, node_min.X, - node_min.Y, node_min.Z, seed)), - 0.0f); + u16 num_dungeons = std::fmax(std::floor( + NoisePerlin3D(&np_dungeons, node_min.X, node_min.Y, node_min.Z, seed)), 0.0f); if (num_dungeons == 0) return; @@ -921,24 +921,24 @@ void MapgenBasic::generateDungeons(s16 max_stone_y) DungeonParams dp; dp.np_alt_wall = - NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); - - dp.seed = seed; - dp.only_in_ground = true; - dp.num_dungeons = num_dungeons; - dp.notifytype = GENNOTIFY_DUNGEON; - dp.num_rooms = ps.range(2, 16); - dp.room_size_min = v3s16(5, 5, 5); - dp.room_size_max = v3s16(12, 6, 12); + NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); + + dp.seed = seed; + dp.only_in_ground = true; + dp.num_dungeons = num_dungeons; + dp.notifytype = GENNOTIFY_DUNGEON; + dp.num_rooms = ps.range(2, 16); + dp.room_size_min = v3s16(5, 5, 5); + dp.room_size_max = v3s16(12, 6, 12); dp.room_size_large_min = v3s16(12, 6, 12); dp.room_size_large_max = v3s16(16, 16, 16); - dp.large_room_chance = (ps.range(1, 4) == 1) ? 8 : 0; - dp.diagonal_dirs = ps.range(1, 8) == 1; + dp.large_room_chance = (ps.range(1, 4) == 1) ? 8 : 0; + dp.diagonal_dirs = ps.range(1, 8) == 1; // Diagonal corridors must have 'hole' width >=2 to be passable - u8 holewidth = (dp.diagonal_dirs) ? 2 : ps.range(1, 2); - dp.holesize = v3s16(holewidth, 3, holewidth); - dp.corridor_len_min = 1; - dp.corridor_len_max = 13; + u8 holewidth = (dp.diagonal_dirs) ? 2 : ps.range(1, 2); + dp.holesize = v3s16(holewidth, 3, holewidth); + dp.corridor_len_min = 1; + dp.corridor_len_max = 13; // Get biome at mapchunk midpoint v3s16 chunk_mid = node_min + (node_max - node_min) / v3s16(2, 2, 2); @@ -952,91 +952,102 @@ void MapgenBasic::generateDungeons(s16 max_stone_y) // dungeongen.cpp. dp.c_alt_wall = biome->c_dungeon_alt; // Stairs fall back to 'c_dungeon' if not defined by biome - dp.c_stair = (biome->c_dungeon_stair != CONTENT_IGNORE) - ? biome->c_dungeon_stair - : biome->c_dungeon; - // Fallback to using cobble mapgen alias if defined + dp.c_stair = (biome->c_dungeon_stair != CONTENT_IGNORE) ? + biome->c_dungeon_stair : biome->c_dungeon; + // Fallback to using cobble mapgen alias if defined } else if (c_cobble != CONTENT_IGNORE) { - dp.c_wall = c_cobble; + dp.c_wall = c_cobble; dp.c_alt_wall = CONTENT_IGNORE; - dp.c_stair = c_cobble; - // Fallback to using biome-defined stone + dp.c_stair = c_cobble; + // Fallback to using biome-defined stone } else { - dp.c_wall = biome->c_stone; + dp.c_wall = biome->c_stone; dp.c_alt_wall = CONTENT_IGNORE; - dp.c_stair = biome->c_stone; + dp.c_stair = biome->c_stone; } DungeonGen dgen(ndef, &gennotify, &dp); dgen.generate(vm, blockseed, full_node_min, full_node_max); } + //// //// GenerateNotifier //// -GenerateNotifier::GenerateNotifier(u32 notify_on, const std::set *notify_on_deco_ids) +GenerateNotifier::GenerateNotifier(u32 notify_on, + const std::set *notify_on_deco_ids) { m_notify_on = notify_on; m_notify_on_deco_ids = notify_on_deco_ids; } + void GenerateNotifier::setNotifyOn(u32 notify_on) { m_notify_on = notify_on; } -void GenerateNotifier::setNotifyOnDecoIds(const std::set *notify_on_deco_ids) + +void GenerateNotifier::setNotifyOnDecoIds( + const std::set *notify_on_deco_ids) { m_notify_on_deco_ids = notify_on_deco_ids; } + bool GenerateNotifier::addEvent(GenNotifyType type, v3s16 pos, u32 id) { if (!(m_notify_on & (1 << type))) return false; if (type == GENNOTIFY_DECORATION && - m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->cend()) + m_notify_on_deco_ids->find(id) == m_notify_on_deco_ids->cend()) return false; GenNotifyEvent gne; gne.type = type; - gne.pos = pos; - gne.id = id; + gne.pos = pos; + gne.id = id; m_notify_events.push_back(gne); return true; } -void GenerateNotifier::getEvents(std::map> &event_map) + +void GenerateNotifier::getEvents( + std::map > &event_map) { std::list::iterator it; for (it = m_notify_events.begin(); it != m_notify_events.end(); ++it) { GenNotifyEvent &gn = *it; - std::string name = (gn.type == GENNOTIFY_DECORATION) - ? "decoration#" + itos(gn.id) - : flagdesc_gennotify[gn.type].name; + std::string name = (gn.type == GENNOTIFY_DECORATION) ? + "decoration#"+ itos(gn.id) : + flagdesc_gennotify[gn.type].name; event_map[name].push_back(gn.pos); } } + void GenerateNotifier::clearEvents() { m_notify_events.clear(); } + //// //// MapgenParams //// + MapgenParams::~MapgenParams() { delete bparams; } + void MapgenParams::readParams(const Settings *settings) { std::string seed_str; @@ -1069,6 +1080,7 @@ void MapgenParams::readParams(const Settings *settings) } } + void MapgenParams::writeParams(Settings *settings) const { settings->set("mg_name", Mapgen::getMapgenName(mgtype)); @@ -1082,6 +1094,7 @@ void MapgenParams::writeParams(Settings *settings) const bparams->writeParams(settings); } + // Calculate exact edges of the outermost mapchunks that are within the // set 'mapgen_limit'. void MapgenParams::calcMapgenEdges() @@ -1098,8 +1111,8 @@ void MapgenParams::calcMapgenEdges() s16 ccfmax = ccmax + MAP_BLOCKSIZE; // Effective mapgen limit, in blocks // Uses same calculation as ServerMap::blockpos_over_mapgen_limit(v3s16 p) - s16 mapgen_limit_b = rangelim(mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) / - MAP_BLOCKSIZE; + s16 mapgen_limit_b = rangelim(mapgen_limit, + 0, MAX_MAP_GENERATION_LIMIT) / MAP_BLOCKSIZE; // Effective mapgen limits, in nodes s16 mapgen_limit_min = -mapgen_limit_b * MAP_BLOCKSIZE; s16 mapgen_limit_max = (mapgen_limit_b + 1) * MAP_BLOCKSIZE - 1; @@ -1114,6 +1127,7 @@ void MapgenParams::calcMapgenEdges() m_mapgen_edges_calculated = true; } + s32 MapgenParams::getSpawnRangeMax() { if (!m_mapgen_edges_calculated) diff --git a/src/mapgen/mapgen.h b/src/mapgen/mapgen.h index 7ab797658..a92b3b0d0 100644 --- a/src/mapgen/mapgen.h +++ b/src/mapgen/mapgen.h @@ -30,15 +30,15 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MAPGEN_DEFAULT_NAME "v7" /////////////////// Mapgen flags -#define MG_TREES 0x01 // Obsolete. Moved into mgv6 flags -#define MG_CAVES 0x02 -#define MG_DUNGEONS 0x04 -#define MG_FLAT 0x08 // Obsolete. Moved into mgv6 flags -#define MG_LIGHT 0x10 +#define MG_TREES 0x01 // Obsolete. Moved into mgv6 flags +#define MG_CAVES 0x02 +#define MG_DUNGEONS 0x04 +#define MG_FLAT 0x08 // Obsolete. Moved into mgv6 flags +#define MG_LIGHT 0x10 #define MG_DECORATIONS 0x20 -#define MG_BIOMES 0x40 +#define MG_BIOMES 0x40 -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class Settings; class MMVManip; @@ -59,8 +59,7 @@ struct BlockMakeData; class VoxelArea; class Map; -enum MapgenObject -{ +enum MapgenObject { MGOBJ_VMANIP, MGOBJ_HEIGHTMAP, MGOBJ_BIOMEMAP, @@ -69,8 +68,7 @@ enum MapgenObject MGOBJ_GENNOTIFY }; -enum GenNotifyType -{ +enum GenNotifyType { GENNOTIFY_DUNGEON, GENNOTIFY_TEMPLE, GENNOTIFY_CAVE_BEGIN, @@ -81,15 +79,13 @@ enum GenNotifyType NUM_GENNOTIFY_TYPES }; -struct GenNotifyEvent -{ +struct GenNotifyEvent { GenNotifyType type; v3s16 pos; u32 id; }; -class GenerateNotifier -{ +class GenerateNotifier { public: GenerateNotifier() = default; GenerateNotifier(u32 notify_on, const std::set *notify_on_deco_ids); @@ -97,8 +93,8 @@ class GenerateNotifier void setNotifyOn(u32 notify_on); void setNotifyOnDecoIds(const std::set *notify_on_deco_ids); - bool addEvent(GenNotifyType type, v3s16 pos, u32 id = 0); - void getEvents(std::map> &event_map); + bool addEvent(GenNotifyType type, v3s16 pos, u32 id=0); + void getEvents(std::map > &event_map); void clearEvents(); private: @@ -108,8 +104,7 @@ class GenerateNotifier }; // Order must match the order of 'static MapgenDesc g_reg_mapgens[]' in mapgen.cpp -enum MapgenType -{ +enum MapgenType { MAPGEN_V7, MAPGEN_VALLEYS, MAPGEN_CARPATHIAN, @@ -121,8 +116,7 @@ enum MapgenType MAPGEN_INVALID, }; -struct MapgenParams -{ +struct MapgenParams { MapgenParams() = default; virtual ~MapgenParams(); @@ -143,7 +137,7 @@ struct MapgenParams virtual void readParams(const Settings *settings); virtual void writeParams(Settings *settings) const; // Default settings for g_settings such as flags - virtual void setDefaultSettings(Settings *settings){}; + virtual void setDefaultSettings(Settings *settings) {}; s32 getSpawnRangeMax(); @@ -152,6 +146,7 @@ struct MapgenParams bool m_mapgen_edges_calculated = false; }; + /* Generic interface for map generators. All mapgens must inherit this class. If a feature exposed by a public member pointer is not supported by a @@ -161,8 +156,7 @@ struct MapgenParams methods can be used by constructing a Mapgen base class and setting the appropriate public members (e.g. vm, ndef, and so on). */ -class Mapgen -{ +class Mapgen { public: s32 seed = 0; int water_level = 0; @@ -195,16 +189,16 @@ class Mapgen s16 findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax); s16 findLiquidSurface(v2s16 p2d, s16 ymin, s16 ymax); void updateHeightmap(v3s16 nmin, v3s16 nmax); - void getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, std::vector &floors, - std::vector &ceilings); + void getSurfaces(v2s16 p2d, s16 ymin, s16 ymax, + std::vector &floors, std::vector &ceilings); void updateLiquid(UniqueQueue *trans_liquid, v3s16 nmin, v3s16 nmax); void setLighting(u8 light, v3s16 nmin, v3s16 nmax); void lightSpread(VoxelArea &a, std::queue> &queue, - const v3s16 &p, u8 light); + const v3s16 &p, u8 light); void calcLighting(v3s16 nmin, v3s16 nmax, v3s16 full_nmin, v3s16 full_nmax, - bool propagate_shadow = true); + bool propagate_shadow = true); void propagateSunlight(v3s16 nmin, v3s16 nmax, bool propagate_shadow); void spreadLight(const v3s16 &nmin, const v3s16 &nmax); @@ -221,11 +215,10 @@ class Mapgen // Mapgen management functions static MapgenType getMapgenType(const std::string &mgname); static const char *getMapgenName(MapgenType mgtype); - static Mapgen *createMapgen( - MapgenType mgtype, MapgenParams *params, EmergeParams *emerge); + static Mapgen *createMapgen(MapgenType mgtype, MapgenParams *params, + EmergeParams *emerge); static MapgenParams *createMapgenParams(MapgenType mgtype); - static void getMapgenNames( - std::vector *mgnames, bool include_hidden); + static void getMapgenNames(std::vector *mgnames, bool include_hidden); static void setDefaultSettings(Settings *settings); private: @@ -249,8 +242,7 @@ class Mapgen Note that you must still create your own generateTerrain implementation when inheriting MapgenBasic. */ -class MapgenBasic : public Mapgen -{ +class MapgenBasic : public Mapgen { public: MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerge); virtual ~MapgenBasic(); diff --git a/src/mapgen/mapgen_carpathian.cpp b/src/mapgen/mapgen_carpathian.cpp index 47e33bde9..feb9b428c 100644 --- a/src/mapgen/mapgen_carpathian.cpp +++ b/src/mapgen/mapgen_carpathian.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include #include "mapgen.h" #include "voxel.h" @@ -37,64 +38,68 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_decoration.h" #include "mapgen_carpathian.h" -FlagDesc flagdesc_mapgen_carpathian[] = {{"caverns", MGCARPATHIAN_CAVERNS}, - {"rivers", MGCARPATHIAN_RIVERS}, {NULL, 0}}; + +FlagDesc flagdesc_mapgen_carpathian[] = { + {"caverns", MGCARPATHIAN_CAVERNS}, + {"rivers", MGCARPATHIAN_RIVERS}, + {NULL, 0} +}; + /////////////////////////////////////////////////////////////////////////////// -MapgenCarpathian::MapgenCarpathian(MapgenCarpathianParams *params, EmergeParams *emerge) : - MapgenBasic(MAPGEN_CARPATHIAN, params, emerge) + +MapgenCarpathian::MapgenCarpathian(MapgenCarpathianParams *params, EmergeParams *emerge) + : MapgenBasic(MAPGEN_CARPATHIAN, params, emerge) { - base_level = params->base_level; - river_width = params->river_width; - river_depth = params->river_depth; - valley_width = params->valley_width; - - spflags = params->spflags; - cave_width = params->cave_width; - large_cave_depth = params->large_cave_depth; + base_level = params->base_level; + river_width = params->river_width; + river_depth = params->river_depth; + valley_width = params->valley_width; + + spflags = params->spflags; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; small_cave_num_min = params->small_cave_num_min; small_cave_num_max = params->small_cave_num_max; large_cave_num_min = params->large_cave_num_min; large_cave_num_max = params->large_cave_num_max; large_cave_flooded = params->large_cave_flooded; - cavern_limit = params->cavern_limit; - cavern_taper = params->cavern_taper; - cavern_threshold = params->cavern_threshold; - dungeon_ymin = params->dungeon_ymin; - dungeon_ymax = params->dungeon_ymax; + cavern_limit = params->cavern_limit; + cavern_taper = params->cavern_taper; + cavern_threshold = params->cavern_threshold; + dungeon_ymin = params->dungeon_ymin; + dungeon_ymax = params->dungeon_ymax; grad_wl = 1 - water_level; //// 2D Terrain noise - noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); - noise_height1 = new Noise(¶ms->np_height1, seed, csize.X, csize.Z); - noise_height2 = new Noise(¶ms->np_height2, seed, csize.X, csize.Z); - noise_height3 = new Noise(¶ms->np_height3, seed, csize.X, csize.Z); - noise_height4 = new Noise(¶ms->np_height4, seed, csize.X, csize.Z); - noise_hills_terrain = - new Noise(¶ms->np_hills_terrain, seed, csize.X, csize.Z); - noise_ridge_terrain = - new Noise(¶ms->np_ridge_terrain, seed, csize.X, csize.Z); - noise_step_terrain = new Noise(¶ms->np_step_terrain, seed, csize.X, csize.Z); - noise_hills = new Noise(¶ms->np_hills, seed, csize.X, csize.Z); - noise_ridge_mnt = new Noise(¶ms->np_ridge_mnt, seed, csize.X, csize.Z); - noise_step_mnt = new Noise(¶ms->np_step_mnt, seed, csize.X, csize.Z); + noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); + noise_height1 = new Noise(¶ms->np_height1, seed, csize.X, csize.Z); + noise_height2 = new Noise(¶ms->np_height2, seed, csize.X, csize.Z); + noise_height3 = new Noise(¶ms->np_height3, seed, csize.X, csize.Z); + noise_height4 = new Noise(¶ms->np_height4, seed, csize.X, csize.Z); + noise_hills_terrain = new Noise(¶ms->np_hills_terrain, seed, csize.X, csize.Z); + noise_ridge_terrain = new Noise(¶ms->np_ridge_terrain, seed, csize.X, csize.Z); + noise_step_terrain = new Noise(¶ms->np_step_terrain, seed, csize.X, csize.Z); + noise_hills = new Noise(¶ms->np_hills, seed, csize.X, csize.Z); + noise_ridge_mnt = new Noise(¶ms->np_ridge_mnt, seed, csize.X, csize.Z); + noise_step_mnt = new Noise(¶ms->np_step_mnt, seed, csize.X, csize.Z); if (spflags & MGCARPATHIAN_RIVERS) - noise_rivers = new Noise(¶ms->np_rivers, seed, csize.X, csize.Z); + noise_rivers = new Noise(¶ms->np_rivers, seed, csize.X, csize.Z); //// 3D terrain noise // 1 up 1 down overgeneration - noise_mnt_var = new Noise( - ¶ms->np_mnt_var, seed, csize.X, csize.Y + 2, csize.Z); + noise_mnt_var = new Noise(¶ms->np_mnt_var, seed, csize.X, csize.Y + 2, csize.Z); //// Cave noise - MapgenBasic::np_cave1 = params->np_cave1; - MapgenBasic::np_cave2 = params->np_cave2; + MapgenBasic::np_cave1 = params->np_cave1; + MapgenBasic::np_cave2 = params->np_cave2; MapgenBasic::np_cavern = params->np_cavern; MapgenBasic::np_dungeons = params->np_dungeons; } + MapgenCarpathian::~MapgenCarpathian() { delete noise_filler_depth; @@ -114,118 +119,122 @@ MapgenCarpathian::~MapgenCarpathian() delete noise_mnt_var; } -MapgenCarpathianParams::MapgenCarpathianParams() : - np_filler_depth(0, 1, v3f(128, 128, 128), 261, 3, 0.7, 2.0), - np_height1(0, 5, v3f(251, 251, 251), 9613, 5, 0.5, 2.0), - np_height2(0, 5, v3f(383, 383, 383), 1949, 5, 0.5, 2.0), - np_height3(0, 5, v3f(509, 509, 509), 3211, 5, 0.5, 2.0), - np_height4(0, 5, v3f(631, 631, 631), 1583, 5, 0.5, 2.0), - np_hills_terrain(1, 1, v3f(1301, 1301, 1301), 1692, 5, 0.5, 2.0), - np_ridge_terrain(1, 1, v3f(1889, 1889, 1889), 3568, 5, 0.5, 2.0), - np_step_terrain(1, 1, v3f(1889, 1889, 1889), 4157, 5, 0.5, 2.0), - np_hills(0, 3, v3f(257, 257, 257), 6604, 6, 0.5, 2.0), - np_ridge_mnt(0, 12, v3f(743, 743, 743), 5520, 6, 0.7, 2.0), - np_step_mnt(0, 8, v3f(509, 509, 509), 2590, 6, 0.6, 2.0), - np_rivers(0, 1, v3f(1000, 1000, 1000), 85039, 5, 0.6, 2.0), - np_mnt_var(0, 1, v3f(499, 499, 499), 2490, 5, 0.55, 2.0), - np_cave1(0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), - np_cave2(0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), - np_cavern(0, 1, v3f(384, 128, 384), 723, 5, 0.63, 2.0), - np_dungeons(0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) + +MapgenCarpathianParams::MapgenCarpathianParams(): + np_filler_depth (0, 1, v3f(128, 128, 128), 261, 3, 0.7, 2.0), + np_height1 (0, 5, v3f(251, 251, 251), 9613, 5, 0.5, 2.0), + np_height2 (0, 5, v3f(383, 383, 383), 1949, 5, 0.5, 2.0), + np_height3 (0, 5, v3f(509, 509, 509), 3211, 5, 0.5, 2.0), + np_height4 (0, 5, v3f(631, 631, 631), 1583, 5, 0.5, 2.0), + np_hills_terrain (1, 1, v3f(1301, 1301, 1301), 1692, 5, 0.5, 2.0), + np_ridge_terrain (1, 1, v3f(1889, 1889, 1889), 3568, 5, 0.5, 2.0), + np_step_terrain (1, 1, v3f(1889, 1889, 1889), 4157, 5, 0.5, 2.0), + np_hills (0, 3, v3f(257, 257, 257), 6604, 6, 0.5, 2.0), + np_ridge_mnt (0, 12, v3f(743, 743, 743), 5520, 6, 0.7, 2.0), + np_step_mnt (0, 8, v3f(509, 509, 509), 2590, 6, 0.6, 2.0), + np_rivers (0, 1, v3f(1000, 1000, 1000), 85039, 5, 0.6, 2.0), + np_mnt_var (0, 1, v3f(499, 499, 499), 2490, 5, 0.55, 2.0), + np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), + np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), + np_cavern (0, 1, v3f(384, 128, 384), 723, 5, 0.63, 2.0), + np_dungeons (0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) { } + void MapgenCarpathianParams::readParams(const Settings *settings) { - settings->getFlagStrNoEx( - "mgcarpathian_spflags", spflags, flagdesc_mapgen_carpathian); + settings->getFlagStrNoEx("mgcarpathian_spflags", spflags, flagdesc_mapgen_carpathian); - settings->getFloatNoEx("mgcarpathian_base_level", base_level); - settings->getFloatNoEx("mgcarpathian_river_width", river_width); - settings->getFloatNoEx("mgcarpathian_river_depth", river_depth); + settings->getFloatNoEx("mgcarpathian_base_level", base_level); + settings->getFloatNoEx("mgcarpathian_river_width", river_width); + settings->getFloatNoEx("mgcarpathian_river_depth", river_depth); settings->getFloatNoEx("mgcarpathian_valley_width", valley_width); - settings->getFloatNoEx("mgcarpathian_cave_width", cave_width); - settings->getS16NoEx("mgcarpathian_large_cave_depth", large_cave_depth); - settings->getU16NoEx("mgcarpathian_small_cave_num_min", small_cave_num_min); - settings->getU16NoEx("mgcarpathian_small_cave_num_max", small_cave_num_max); - settings->getU16NoEx("mgcarpathian_large_cave_num_min", large_cave_num_min); - settings->getU16NoEx("mgcarpathian_large_cave_num_max", large_cave_num_max); + settings->getFloatNoEx("mgcarpathian_cave_width", cave_width); + settings->getS16NoEx("mgcarpathian_large_cave_depth", large_cave_depth); + settings->getU16NoEx("mgcarpathian_small_cave_num_min", small_cave_num_min); + settings->getU16NoEx("mgcarpathian_small_cave_num_max", small_cave_num_max); + settings->getU16NoEx("mgcarpathian_large_cave_num_min", large_cave_num_min); + settings->getU16NoEx("mgcarpathian_large_cave_num_max", large_cave_num_max); settings->getFloatNoEx("mgcarpathian_large_cave_flooded", large_cave_flooded); - settings->getS16NoEx("mgcarpathian_cavern_limit", cavern_limit); - settings->getS16NoEx("mgcarpathian_cavern_taper", cavern_taper); - settings->getFloatNoEx("mgcarpathian_cavern_threshold", cavern_threshold); - settings->getS16NoEx("mgcarpathian_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgcarpathian_dungeon_ymax", dungeon_ymax); - - settings->getNoiseParams("mgcarpathian_np_filler_depth", np_filler_depth); - settings->getNoiseParams("mgcarpathian_np_height1", np_height1); - settings->getNoiseParams("mgcarpathian_np_height2", np_height2); - settings->getNoiseParams("mgcarpathian_np_height3", np_height3); - settings->getNoiseParams("mgcarpathian_np_height4", np_height4); + settings->getS16NoEx("mgcarpathian_cavern_limit", cavern_limit); + settings->getS16NoEx("mgcarpathian_cavern_taper", cavern_taper); + settings->getFloatNoEx("mgcarpathian_cavern_threshold", cavern_threshold); + settings->getS16NoEx("mgcarpathian_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgcarpathian_dungeon_ymax", dungeon_ymax); + + settings->getNoiseParams("mgcarpathian_np_filler_depth", np_filler_depth); + settings->getNoiseParams("mgcarpathian_np_height1", np_height1); + settings->getNoiseParams("mgcarpathian_np_height2", np_height2); + settings->getNoiseParams("mgcarpathian_np_height3", np_height3); + settings->getNoiseParams("mgcarpathian_np_height4", np_height4); settings->getNoiseParams("mgcarpathian_np_hills_terrain", np_hills_terrain); settings->getNoiseParams("mgcarpathian_np_ridge_terrain", np_ridge_terrain); - settings->getNoiseParams("mgcarpathian_np_step_terrain", np_step_terrain); - settings->getNoiseParams("mgcarpathian_np_hills", np_hills); - settings->getNoiseParams("mgcarpathian_np_ridge_mnt", np_ridge_mnt); - settings->getNoiseParams("mgcarpathian_np_step_mnt", np_step_mnt); - settings->getNoiseParams("mgcarpathian_np_rivers", np_rivers); - settings->getNoiseParams("mgcarpathian_np_mnt_var", np_mnt_var); - settings->getNoiseParams("mgcarpathian_np_cave1", np_cave1); - settings->getNoiseParams("mgcarpathian_np_cave2", np_cave2); - settings->getNoiseParams("mgcarpathian_np_cavern", np_cavern); - settings->getNoiseParams("mgcarpathian_np_dungeons", np_dungeons); + settings->getNoiseParams("mgcarpathian_np_step_terrain", np_step_terrain); + settings->getNoiseParams("mgcarpathian_np_hills", np_hills); + settings->getNoiseParams("mgcarpathian_np_ridge_mnt", np_ridge_mnt); + settings->getNoiseParams("mgcarpathian_np_step_mnt", np_step_mnt); + settings->getNoiseParams("mgcarpathian_np_rivers", np_rivers); + settings->getNoiseParams("mgcarpathian_np_mnt_var", np_mnt_var); + settings->getNoiseParams("mgcarpathian_np_cave1", np_cave1); + settings->getNoiseParams("mgcarpathian_np_cave2", np_cave2); + settings->getNoiseParams("mgcarpathian_np_cavern", np_cavern); + settings->getNoiseParams("mgcarpathian_np_dungeons", np_dungeons); } + void MapgenCarpathianParams::writeParams(Settings *settings) const { settings->setFlagStr("mgcarpathian_spflags", spflags, flagdesc_mapgen_carpathian); - settings->setFloat("mgcarpathian_base_level", base_level); - settings->setFloat("mgcarpathian_river_width", river_width); - settings->setFloat("mgcarpathian_river_depth", river_depth); + settings->setFloat("mgcarpathian_base_level", base_level); + settings->setFloat("mgcarpathian_river_width", river_width); + settings->setFloat("mgcarpathian_river_depth", river_depth); settings->setFloat("mgcarpathian_valley_width", valley_width); - settings->setFloat("mgcarpathian_cave_width", cave_width); - settings->setS16("mgcarpathian_large_cave_depth", large_cave_depth); - settings->setU16("mgcarpathian_small_cave_num_min", small_cave_num_min); - settings->setU16("mgcarpathian_small_cave_num_max", small_cave_num_max); - settings->setU16("mgcarpathian_large_cave_num_min", large_cave_num_min); - settings->setU16("mgcarpathian_large_cave_num_max", large_cave_num_max); + settings->setFloat("mgcarpathian_cave_width", cave_width); + settings->setS16("mgcarpathian_large_cave_depth", large_cave_depth); + settings->setU16("mgcarpathian_small_cave_num_min", small_cave_num_min); + settings->setU16("mgcarpathian_small_cave_num_max", small_cave_num_max); + settings->setU16("mgcarpathian_large_cave_num_min", large_cave_num_min); + settings->setU16("mgcarpathian_large_cave_num_max", large_cave_num_max); settings->setFloat("mgcarpathian_large_cave_flooded", large_cave_flooded); - settings->setS16("mgcarpathian_cavern_limit", cavern_limit); - settings->setS16("mgcarpathian_cavern_taper", cavern_taper); - settings->setFloat("mgcarpathian_cavern_threshold", cavern_threshold); - settings->setS16("mgcarpathian_dungeon_ymin", dungeon_ymin); - settings->setS16("mgcarpathian_dungeon_ymax", dungeon_ymax); - - settings->setNoiseParams("mgcarpathian_np_filler_depth", np_filler_depth); - settings->setNoiseParams("mgcarpathian_np_height1", np_height1); - settings->setNoiseParams("mgcarpathian_np_height2", np_height2); - settings->setNoiseParams("mgcarpathian_np_height3", np_height3); - settings->setNoiseParams("mgcarpathian_np_height4", np_height4); + settings->setS16("mgcarpathian_cavern_limit", cavern_limit); + settings->setS16("mgcarpathian_cavern_taper", cavern_taper); + settings->setFloat("mgcarpathian_cavern_threshold", cavern_threshold); + settings->setS16("mgcarpathian_dungeon_ymin", dungeon_ymin); + settings->setS16("mgcarpathian_dungeon_ymax", dungeon_ymax); + + settings->setNoiseParams("mgcarpathian_np_filler_depth", np_filler_depth); + settings->setNoiseParams("mgcarpathian_np_height1", np_height1); + settings->setNoiseParams("mgcarpathian_np_height2", np_height2); + settings->setNoiseParams("mgcarpathian_np_height3", np_height3); + settings->setNoiseParams("mgcarpathian_np_height4", np_height4); settings->setNoiseParams("mgcarpathian_np_hills_terrain", np_hills_terrain); settings->setNoiseParams("mgcarpathian_np_ridge_terrain", np_ridge_terrain); - settings->setNoiseParams("mgcarpathian_np_step_terrain", np_step_terrain); - settings->setNoiseParams("mgcarpathian_np_hills", np_hills); - settings->setNoiseParams("mgcarpathian_np_ridge_mnt", np_ridge_mnt); - settings->setNoiseParams("mgcarpathian_np_step_mnt", np_step_mnt); - settings->setNoiseParams("mgcarpathian_np_rivers", np_rivers); - settings->setNoiseParams("mgcarpathian_np_mnt_var", np_mnt_var); - settings->setNoiseParams("mgcarpathian_np_cave1", np_cave1); - settings->setNoiseParams("mgcarpathian_np_cave2", np_cave2); - settings->setNoiseParams("mgcarpathian_np_cavern", np_cavern); - settings->setNoiseParams("mgcarpathian_np_dungeons", np_dungeons); + settings->setNoiseParams("mgcarpathian_np_step_terrain", np_step_terrain); + settings->setNoiseParams("mgcarpathian_np_hills", np_hills); + settings->setNoiseParams("mgcarpathian_np_ridge_mnt", np_ridge_mnt); + settings->setNoiseParams("mgcarpathian_np_step_mnt", np_step_mnt); + settings->setNoiseParams("mgcarpathian_np_rivers", np_rivers); + settings->setNoiseParams("mgcarpathian_np_mnt_var", np_mnt_var); + settings->setNoiseParams("mgcarpathian_np_cave1", np_cave1); + settings->setNoiseParams("mgcarpathian_np_cave2", np_cave2); + settings->setNoiseParams("mgcarpathian_np_cavern", np_cavern); + settings->setNoiseParams("mgcarpathian_np_dungeons", np_dungeons); } + void MapgenCarpathianParams::setDefaultSettings(Settings *settings) { settings->setDefault("mgcarpathian_spflags", flagdesc_mapgen_carpathian, - MGCARPATHIAN_CAVERNS); + MGCARPATHIAN_CAVERNS); } //////////////////////////////////////////////////////////////////////////////// + // Lerp function inline float MapgenCarpathian::getLerp(float noise1, float noise2, float mod) { @@ -242,8 +251,10 @@ float MapgenCarpathian::getSteps(float noise) return (k + s) * w; } + //////////////////////////////////////////////////////////////////////////////// + void MapgenCarpathian::makeChunk(BlockMakeData *data) { // Pre-conditions @@ -297,8 +308,8 @@ void MapgenCarpathian::makeChunk(BlockMakeData *data) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. - generateCavesRandomWalk( - stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); + generateCavesRandomWalk(stone_surface_max_y, + -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } @@ -330,15 +341,16 @@ void MapgenCarpathian::makeChunk(BlockMakeData *data) this->generating = false; } + //////////////////////////////////////////////////////////////////////////////// + int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) { // If rivers are enabled, first check if in a river channel if (spflags & MGCARPATHIAN_RIVERS) { - float river = std::fabs(NoisePerlin2D( - &noise_rivers->np, p.X, p.Y, seed)) - - river_width; + float river = std::fabs(NoisePerlin2D(&noise_rivers->np, p.X, p.Y, seed)) - + river_width; if (river < 0.0f) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } @@ -348,13 +360,11 @@ int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) float height3 = NoisePerlin2D(&noise_height3->np, p.X, p.Y, seed); float height4 = NoisePerlin2D(&noise_height4->np, p.X, p.Y, seed); - float hterabs = std::fabs( - NoisePerlin2D(&noise_hills_terrain->np, p.X, p.Y, seed)); + float hterabs = std::fabs(NoisePerlin2D(&noise_hills_terrain->np, p.X, p.Y, seed)); float n_hills = NoisePerlin2D(&noise_hills->np, p.X, p.Y, seed); float hill_mnt = hterabs * hterabs * hterabs * n_hills * n_hills; - float rterabs = std::fabs( - NoisePerlin2D(&noise_ridge_terrain->np, p.X, p.Y, seed)); + float rterabs = std::fabs(NoisePerlin2D(&noise_ridge_terrain->np, p.X, p.Y, seed)); float n_ridge_mnt = NoisePerlin2D(&noise_ridge_mnt->np, p.X, p.Y, seed); float ridge_mnt = rterabs * rterabs * rterabs * (1.0f - std::fabs(n_ridge_mnt)); @@ -366,8 +376,7 @@ int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) float river = 0.0f; if ((spflags & MGCARPATHIAN_RIVERS) && node_max.Y >= water_level - 16) { - river = std::fabs(NoisePerlin2D(&noise_rivers->np, p.X, p.Y, seed)) - - river_width; + river = std::fabs(NoisePerlin2D(&noise_rivers->np, p.X, p.Y, seed)) - river_width; if (river <= valley_width) { // Within river valley if (river < 0.0f) { @@ -393,8 +402,7 @@ int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) float hill3 = getLerp(height3, height2, mnt_var); float hill4 = getLerp(height1, height4, mnt_var); - float hilliness = std::fmax( - std::fmin(hill1, hill2), std::fmin(hill3, hill4)); + float hilliness = std::fmax(std::fmin(hill1, hill2), std::fmin(hill3, hill4)); float hills = hill_mnt * hilliness; float ridged_mountains = ridge_mnt * hilliness; float step_mountains = step_mnt * hilliness; @@ -408,16 +416,14 @@ int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) if (valley < 0.0f) { // River channel surface_level = std::fmin(surface_level, - water_level - std::sqrt(-valley) * - river_depth); + water_level - std::sqrt(-valley) * river_depth); } else if (surface_level > water_level) { // Valley slopes - surface_level = water_level + - (surface_level - water_level) * valley; + surface_level = water_level + (surface_level - water_level) * valley; } } - if (y < surface_level) { // TODO '<=' fix from generateTerrain() + if (y < surface_level) { //TODO '<=' fix from generateTerrain() // solid node solid_below = true; cons_non_solid = 0; @@ -432,8 +438,10 @@ int MapgenCarpathian::getSpawnLevelAtPoint(v2s16 p) return MAX_MAP_GENERATION_LIMIT; // No suitable spawn point found } + //////////////////////////////////////////////////////////////////////////////// + int MapgenCarpathian::generateTerrain() { MapNode mn_air(CONTENT_AIR); @@ -462,117 +470,108 @@ int MapgenCarpathian::generateTerrain() u32 index2d = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index2d++) { - // Hill/Mountain height (hilliness) - float height1 = noise_height1->result[index2d]; - float height2 = noise_height2->result[index2d]; - float height3 = noise_height3->result[index2d]; - float height4 = noise_height4->result[index2d]; - - // Rolling hills - float hterabs = std::fabs(noise_hills_terrain->result[index2d]); - float n_hills = noise_hills->result[index2d]; - float hill_mnt = hterabs * hterabs * hterabs * n_hills * n_hills; - - // Ridged mountains - float rterabs = std::fabs(noise_ridge_terrain->result[index2d]); - float n_ridge_mnt = noise_ridge_mnt->result[index2d]; - float ridge_mnt = rterabs * rterabs * rterabs * - (1.0f - std::fabs(n_ridge_mnt)); - - // Step (terraced) mountains - float sterabs = std::fabs(noise_step_terrain->result[index2d]); - float n_step_mnt = noise_step_mnt->result[index2d]; - float step_mnt = sterabs * sterabs * sterabs * - getSteps(n_step_mnt); - - // Rivers - float valley = 1.0f; - float river = 0.0f; - - if ((spflags & MGCARPATHIAN_RIVERS) && - node_max.Y >= water_level - 16) { - river = std::fabs(noise_rivers->result[index2d]) - - river_width; - if (river <= valley_width) { - // Within river valley - if (river < 0.0f) { - // River channel - valley = river; - } else { - // Valley slopes. - // 0 at river edge, 1 at valley edge. - float riversc = river / valley_width; - // Smoothstep - valley = riversc * riversc * - (3.0f - 2.0f * riversc); - } + for (s16 x = node_min.X; x <= node_max.X; x++, index2d++) { + // Hill/Mountain height (hilliness) + float height1 = noise_height1->result[index2d]; + float height2 = noise_height2->result[index2d]; + float height3 = noise_height3->result[index2d]; + float height4 = noise_height4->result[index2d]; + + // Rolling hills + float hterabs = std::fabs(noise_hills_terrain->result[index2d]); + float n_hills = noise_hills->result[index2d]; + float hill_mnt = hterabs * hterabs * hterabs * n_hills * n_hills; + + // Ridged mountains + float rterabs = std::fabs(noise_ridge_terrain->result[index2d]); + float n_ridge_mnt = noise_ridge_mnt->result[index2d]; + float ridge_mnt = rterabs * rterabs * rterabs * + (1.0f - std::fabs(n_ridge_mnt)); + + // Step (terraced) mountains + float sterabs = std::fabs(noise_step_terrain->result[index2d]); + float n_step_mnt = noise_step_mnt->result[index2d]; + float step_mnt = sterabs * sterabs * sterabs * getSteps(n_step_mnt); + + // Rivers + float valley = 1.0f; + float river = 0.0f; + + if ((spflags & MGCARPATHIAN_RIVERS) && node_max.Y >= water_level - 16) { + river = std::fabs(noise_rivers->result[index2d]) - river_width; + if (river <= valley_width) { + // Within river valley + if (river < 0.0f) { + // River channel + valley = river; + } else { + // Valley slopes. + // 0 at river edge, 1 at valley edge. + float riversc = river / valley_width; + // Smoothstep + valley = riversc * riversc * (3.0f - 2.0f * riversc); } } + } - // Initialise 3D noise index and voxelmanip index to column base - u32 index3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); - u32 vi = vm->m_area.index(x, node_min.Y - 1, z); - - for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++, - index3d += ystride, VoxelArea::add_y(em, vi, 1)) { - if (vm->m_data[vi].getContent() != CONTENT_IGNORE) - continue; - - // Combine height noises and apply 3D variation - float mnt_var = noise_mnt_var->result[index3d]; - float hill1 = getLerp(height1, height2, mnt_var); - float hill2 = getLerp(height3, height4, mnt_var); - float hill3 = getLerp(height3, height2, mnt_var); - float hill4 = getLerp(height1, height4, mnt_var); - - // 'hilliness' determines whether hills/mountains are - // small or large - float hilliness = std::fmax(std::fmin(hill1, hill2), - std::fmin(hill3, hill4)); - float hills = hill_mnt * hilliness; - float ridged_mountains = ridge_mnt * hilliness; - float step_mountains = step_mnt * hilliness; - - // Gradient & shallow seabed - s32 grad = (y < water_level) - ? grad_wl + (water_level - y) * 3 - : 1 - y; - - // Final terrain level - float mountains = - hills + ridged_mountains + step_mountains; - float surface_level = base_level + mountains + grad; - - // Rivers - if ((spflags & MGCARPATHIAN_RIVERS) && - node_max.Y >= water_level - 16 && - river <= valley_width) { - if (valley < 0.0f) { - // River channel - surface_level = std::fmin(surface_level, - water_level - std::sqrt(-valley) * - river_depth); - } else if (surface_level > water_level) { - // Valley slopes - surface_level = water_level + - (surface_level - - water_level) * - valley; - } - } + // Initialise 3D noise index and voxelmanip index to column base + u32 index3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); + u32 vi = vm->m_area.index(x, node_min.Y - 1, z); + + for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; + y++, + index3d += ystride, + VoxelArea::add_y(em, vi, 1)) { + if (vm->m_data[vi].getContent() != CONTENT_IGNORE) + continue; + + // Combine height noises and apply 3D variation + float mnt_var = noise_mnt_var->result[index3d]; + float hill1 = getLerp(height1, height2, mnt_var); + float hill2 = getLerp(height3, height4, mnt_var); + float hill3 = getLerp(height3, height2, mnt_var); + float hill4 = getLerp(height1, height4, mnt_var); + + // 'hilliness' determines whether hills/mountains are + // small or large + float hilliness = + std::fmax(std::fmin(hill1, hill2), std::fmin(hill3, hill4)); + float hills = hill_mnt * hilliness; + float ridged_mountains = ridge_mnt * hilliness; + float step_mountains = step_mnt * hilliness; + + // Gradient & shallow seabed + s32 grad = (y < water_level) ? grad_wl + (water_level - y) * 3 : + 1 - y; + + // Final terrain level + float mountains = hills + ridged_mountains + step_mountains; + float surface_level = base_level + mountains + grad; - if (y < surface_level) { // TODO '<=' - vm->m_data[vi] = mn_stone; // Stone - if (y > stone_surface_max_y) - stone_surface_max_y = y; - } else if (y <= water_level) { - vm->m_data[vi] = mn_water; // Sea water - } else { - vm->m_data[vi] = mn_air; // Air + // Rivers + if ((spflags & MGCARPATHIAN_RIVERS) && node_max.Y >= water_level - 16 && + river <= valley_width) { + if (valley < 0.0f) { + // River channel + surface_level = std::fmin(surface_level, + water_level - std::sqrt(-valley) * river_depth); + } else if (surface_level > water_level) { + // Valley slopes + surface_level = water_level + (surface_level - water_level) * valley; } } + + if (y < surface_level) { //TODO '<=' + vm->m_data[vi] = mn_stone; // Stone + if (y > stone_surface_max_y) + stone_surface_max_y = y; + } else if (y <= water_level) { + vm->m_data[vi] = mn_water; // Sea water + } else { + vm->m_data[vi] = mn_air; // Air + } } + } return stone_surface_max_y; } diff --git a/src/mapgen/mapgen_carpathian.h b/src/mapgen/mapgen_carpathian.h index 5c44c16e3..31b2b91d8 100644 --- a/src/mapgen/mapgen_carpathian.h +++ b/src/mapgen/mapgen_carpathian.h @@ -23,31 +23,32 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen.h" #define MGCARPATHIAN_CAVERNS 0x01 -#define MGCARPATHIAN_RIVERS 0x02 +#define MGCARPATHIAN_RIVERS 0x02 class BiomeManager; extern FlagDesc flagdesc_mapgen_carpathian[]; + struct MapgenCarpathianParams : public MapgenParams { - float base_level = 12.0f; - float river_width = 0.05f; - float river_depth = 24.0f; - float valley_width = 0.25f; - - float cave_width = 0.09f; - s16 large_cave_depth = -33; - u16 small_cave_num_min = 0; - u16 small_cave_num_max = 0; - u16 large_cave_num_min = 0; - u16 large_cave_num_max = 2; + float base_level = 12.0f; + float river_width = 0.05f; + float river_depth = 24.0f; + float valley_width = 0.25f; + + float cave_width = 0.09f; + s16 large_cave_depth = -33; + u16 small_cave_num_min = 0; + u16 small_cave_num_max = 0; + u16 large_cave_num_min = 0; + u16 large_cave_num_max = 2; float large_cave_flooded = 0.5f; - s16 cavern_limit = -256; - s16 cavern_taper = 256; - float cavern_threshold = 0.7f; - s16 dungeon_ymin = -31000; - s16 dungeon_ymax = 31000; + s16 cavern_limit = -256; + s16 cavern_taper = 256; + float cavern_threshold = 0.7f; + s16 dungeon_ymin = -31000; + s16 dungeon_ymax = 31000; NoiseParams np_filler_depth; NoiseParams np_height1; diff --git a/src/mapgen/mapgen_flat.cpp b/src/mapgen/mapgen_flat.cpp index e24f1e4a1..369777ad2 100644 --- a/src/mapgen/mapgen_flat.cpp +++ b/src/mapgen/mapgen_flat.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "mapgen.h" #include "voxel.h" #include "noise.h" @@ -36,29 +37,34 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_decoration.h" #include "mapgen_flat.h" + FlagDesc flagdesc_mapgen_flat[] = { - {"lakes", MGFLAT_LAKES}, {"hills", MGFLAT_HILLS}, {NULL, 0}}; + {"lakes", MGFLAT_LAKES}, + {"hills", MGFLAT_HILLS}, + {NULL, 0} +}; /////////////////////////////////////////////////////////////////////////////////////// -MapgenFlat::MapgenFlat(MapgenFlatParams *params, EmergeParams *emerge) : - MapgenBasic(MAPGEN_FLAT, params, emerge) + +MapgenFlat::MapgenFlat(MapgenFlatParams *params, EmergeParams *emerge) + : MapgenBasic(MAPGEN_FLAT, params, emerge) { - spflags = params->spflags; - ground_level = params->ground_level; - large_cave_depth = params->large_cave_depth; + spflags = params->spflags; + ground_level = params->ground_level; + large_cave_depth = params->large_cave_depth; small_cave_num_min = params->small_cave_num_min; small_cave_num_max = params->small_cave_num_max; large_cave_num_min = params->large_cave_num_min; large_cave_num_max = params->large_cave_num_max; large_cave_flooded = params->large_cave_flooded; - cave_width = params->cave_width; - lake_threshold = params->lake_threshold; - lake_steepness = params->lake_steepness; - hill_threshold = params->hill_threshold; - hill_steepness = params->hill_steepness; - dungeon_ymin = params->dungeon_ymin; - dungeon_ymax = params->dungeon_ymax; + cave_width = params->cave_width; + lake_threshold = params->lake_threshold; + lake_steepness = params->lake_steepness; + hill_threshold = params->hill_threshold; + hill_steepness = params->hill_steepness; + dungeon_ymin = params->dungeon_ymin; + dungeon_ymax = params->dungeon_ymax; // 2D noise noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); @@ -66,11 +72,12 @@ MapgenFlat::MapgenFlat(MapgenFlatParams *params, EmergeParams *emerge) : if ((spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS)) noise_terrain = new Noise(¶ms->np_terrain, seed, csize.X, csize.Z); // 3D noise - MapgenBasic::np_cave1 = params->np_cave1; - MapgenBasic::np_cave2 = params->np_cave2; + MapgenBasic::np_cave1 = params->np_cave1; + MapgenBasic::np_cave2 = params->np_cave2; MapgenBasic::np_dungeons = params->np_dungeons; } + MapgenFlat::~MapgenFlat() { delete noise_filler_depth; @@ -79,86 +86,92 @@ MapgenFlat::~MapgenFlat() delete noise_terrain; } -MapgenFlatParams::MapgenFlatParams() : - np_terrain(0, 1, v3f(600, 600, 600), 7244, 5, 0.6, 2.0), - np_filler_depth(0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), - np_cave1(0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), - np_cave2(0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), - np_dungeons(0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) + +MapgenFlatParams::MapgenFlatParams(): + np_terrain (0, 1, v3f(600, 600, 600), 7244, 5, 0.6, 2.0), + np_filler_depth (0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), + np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), + np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), + np_dungeons (0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) { } + void MapgenFlatParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgflat_spflags", spflags, flagdesc_mapgen_flat); - settings->getS16NoEx("mgflat_ground_level", ground_level); - settings->getS16NoEx("mgflat_large_cave_depth", large_cave_depth); - settings->getU16NoEx("mgflat_small_cave_num_min", small_cave_num_min); - settings->getU16NoEx("mgflat_small_cave_num_max", small_cave_num_max); - settings->getU16NoEx("mgflat_large_cave_num_min", large_cave_num_min); - settings->getU16NoEx("mgflat_large_cave_num_max", large_cave_num_max); + settings->getS16NoEx("mgflat_ground_level", ground_level); + settings->getS16NoEx("mgflat_large_cave_depth", large_cave_depth); + settings->getU16NoEx("mgflat_small_cave_num_min", small_cave_num_min); + settings->getU16NoEx("mgflat_small_cave_num_max", small_cave_num_max); + settings->getU16NoEx("mgflat_large_cave_num_min", large_cave_num_min); + settings->getU16NoEx("mgflat_large_cave_num_max", large_cave_num_max); settings->getFloatNoEx("mgflat_large_cave_flooded", large_cave_flooded); - settings->getFloatNoEx("mgflat_cave_width", cave_width); - settings->getFloatNoEx("mgflat_lake_threshold", lake_threshold); - settings->getFloatNoEx("mgflat_lake_steepness", lake_steepness); - settings->getFloatNoEx("mgflat_hill_threshold", hill_threshold); - settings->getFloatNoEx("mgflat_hill_steepness", hill_steepness); - settings->getS16NoEx("mgflat_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgflat_dungeon_ymax", dungeon_ymax); - - settings->getNoiseParams("mgflat_np_terrain", np_terrain); + settings->getFloatNoEx("mgflat_cave_width", cave_width); + settings->getFloatNoEx("mgflat_lake_threshold", lake_threshold); + settings->getFloatNoEx("mgflat_lake_steepness", lake_steepness); + settings->getFloatNoEx("mgflat_hill_threshold", hill_threshold); + settings->getFloatNoEx("mgflat_hill_steepness", hill_steepness); + settings->getS16NoEx("mgflat_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgflat_dungeon_ymax", dungeon_ymax); + + settings->getNoiseParams("mgflat_np_terrain", np_terrain); settings->getNoiseParams("mgflat_np_filler_depth", np_filler_depth); - settings->getNoiseParams("mgflat_np_cave1", np_cave1); - settings->getNoiseParams("mgflat_np_cave2", np_cave2); - settings->getNoiseParams("mgflat_np_dungeons", np_dungeons); + settings->getNoiseParams("mgflat_np_cave1", np_cave1); + settings->getNoiseParams("mgflat_np_cave2", np_cave2); + settings->getNoiseParams("mgflat_np_dungeons", np_dungeons); } + void MapgenFlatParams::writeParams(Settings *settings) const { settings->setFlagStr("mgflat_spflags", spflags, flagdesc_mapgen_flat); - settings->setS16("mgflat_ground_level", ground_level); - settings->setS16("mgflat_large_cave_depth", large_cave_depth); - settings->setU16("mgflat_small_cave_num_min", small_cave_num_min); - settings->setU16("mgflat_small_cave_num_max", small_cave_num_max); - settings->setU16("mgflat_large_cave_num_min", large_cave_num_min); - settings->setU16("mgflat_large_cave_num_max", large_cave_num_max); + settings->setS16("mgflat_ground_level", ground_level); + settings->setS16("mgflat_large_cave_depth", large_cave_depth); + settings->setU16("mgflat_small_cave_num_min", small_cave_num_min); + settings->setU16("mgflat_small_cave_num_max", small_cave_num_max); + settings->setU16("mgflat_large_cave_num_min", large_cave_num_min); + settings->setU16("mgflat_large_cave_num_max", large_cave_num_max); settings->setFloat("mgflat_large_cave_flooded", large_cave_flooded); - settings->setFloat("mgflat_cave_width", cave_width); - settings->setFloat("mgflat_lake_threshold", lake_threshold); - settings->setFloat("mgflat_lake_steepness", lake_steepness); - settings->setFloat("mgflat_hill_threshold", hill_threshold); - settings->setFloat("mgflat_hill_steepness", hill_steepness); - settings->setS16("mgflat_dungeon_ymin", dungeon_ymin); - settings->setS16("mgflat_dungeon_ymax", dungeon_ymax); - - settings->setNoiseParams("mgflat_np_terrain", np_terrain); + settings->setFloat("mgflat_cave_width", cave_width); + settings->setFloat("mgflat_lake_threshold", lake_threshold); + settings->setFloat("mgflat_lake_steepness", lake_steepness); + settings->setFloat("mgflat_hill_threshold", hill_threshold); + settings->setFloat("mgflat_hill_steepness", hill_steepness); + settings->setS16("mgflat_dungeon_ymin", dungeon_ymin); + settings->setS16("mgflat_dungeon_ymax", dungeon_ymax); + + settings->setNoiseParams("mgflat_np_terrain", np_terrain); settings->setNoiseParams("mgflat_np_filler_depth", np_filler_depth); - settings->setNoiseParams("mgflat_np_cave1", np_cave1); - settings->setNoiseParams("mgflat_np_cave2", np_cave2); - settings->setNoiseParams("mgflat_np_dungeons", np_dungeons); + settings->setNoiseParams("mgflat_np_cave1", np_cave1); + settings->setNoiseParams("mgflat_np_cave2", np_cave2); + settings->setNoiseParams("mgflat_np_dungeons", np_dungeons); } + void MapgenFlatParams::setDefaultSettings(Settings *settings) { settings->setDefault("mgflat_spflags", flagdesc_mapgen_flat, 0); } + ///////////////////////////////////////////////////////////////// + int MapgenFlat::getSpawnLevelAtPoint(v2s16 p) { s16 stone_level = ground_level; - float n_terrain = ((spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS)) - ? NoisePerlin2D(&noise_terrain->np, p.X, p.Y, - seed) - : 0.0f; + float n_terrain = + ((spflags & MGFLAT_LAKES) || (spflags & MGFLAT_HILLS)) ? + NoisePerlin2D(&noise_terrain->np, p.X, p.Y, seed) : + 0.0f; if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) { s16 depress = (lake_threshold - n_terrain) * lake_steepness; stone_level = ground_level - depress; } else if ((spflags & MGFLAT_HILLS) && n_terrain > hill_threshold) { s16 rise = (n_terrain - hill_threshold) * hill_steepness; - stone_level = ground_level + rise; + stone_level = ground_level + rise; } if (ground_level < water_level) @@ -174,22 +187,23 @@ int MapgenFlat::getSpawnLevelAtPoint(v2s16 p) return MAX_MAP_GENERATION_LIMIT; } + void MapgenFlat::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; - this->vm = data->vmanip; + this->vm = data->vmanip; this->ndef = data->nodedef; - // TimeTaker t("makeChunk"); + //TimeTaker t("makeChunk"); v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; @@ -233,20 +247,21 @@ void MapgenFlat::makeChunk(BlockMakeData *data) if (flags & MG_BIOMES) dustTopNodes(); - // printf("makeChunk: %dms\n", t.stop()); + //printf("makeChunk: %dms\n", t.stop()); updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), - full_node_min, full_node_max); + full_node_min, full_node_max); - // setLighting(node_min - v3s16(1, 0, 1) * MAP_BLOCKSIZE, + //setLighting(node_min - v3s16(1, 0, 1) * MAP_BLOCKSIZE, // node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, 0xFF); this->generating = false; } + s16 MapgenFlat::generateTerrain() { MapNode n_air(CONTENT_AIR); @@ -262,36 +277,34 @@ s16 MapgenFlat::generateTerrain() noise_terrain->perlinMap2D(node_min.X, node_min.Z); for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, ni2d++) { - s16 stone_level = ground_level; - float n_terrain = use_noise ? noise_terrain->result[ni2d] : 0.0f; - - if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) { - s16 depress = (lake_threshold - n_terrain) * - lake_steepness; - stone_level = ground_level - depress; - } else if ((spflags & MGFLAT_HILLS) && - n_terrain > hill_threshold) { - s16 rise = (n_terrain - hill_threshold) * hill_steepness; - stone_level = ground_level + rise; - } + for (s16 x = node_min.X; x <= node_max.X; x++, ni2d++) { + s16 stone_level = ground_level; + float n_terrain = use_noise ? noise_terrain->result[ni2d] : 0.0f; + + if ((spflags & MGFLAT_LAKES) && n_terrain < lake_threshold) { + s16 depress = (lake_threshold - n_terrain) * lake_steepness; + stone_level = ground_level - depress; + } else if ((spflags & MGFLAT_HILLS) && n_terrain > hill_threshold) { + s16 rise = (n_terrain - hill_threshold) * hill_steepness; + stone_level = ground_level + rise; + } - u32 vi = vm->m_area.index(x, node_min.Y - 1, z); - for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { - if (vm->m_data[vi].getContent() == CONTENT_IGNORE) { - if (y <= stone_level) { - vm->m_data[vi] = n_stone; - if (y > stone_surface_max_y) - stone_surface_max_y = y; - } else if (y <= water_level) { - vm->m_data[vi] = n_water; - } else { - vm->m_data[vi] = n_air; - } + u32 vi = vm->m_area.index(x, node_min.Y - 1, z); + for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { + if (vm->m_data[vi].getContent() == CONTENT_IGNORE) { + if (y <= stone_level) { + vm->m_data[vi] = n_stone; + if (y > stone_surface_max_y) + stone_surface_max_y = y; + } else if (y <= water_level) { + vm->m_data[vi] = n_water; + } else { + vm->m_data[vi] = n_air; } - VoxelArea::add_y(em, vi, 1); } + VoxelArea::add_y(em, vi, 1); } + } return stone_surface_max_y; } diff --git a/src/mapgen/mapgen_fractal.cpp b/src/mapgen/mapgen_fractal.cpp index fca8c9196..cb55bc288 100644 --- a/src/mapgen/mapgen_fractal.cpp +++ b/src/mapgen/mapgen_fractal.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "mapgen.h" #include #include "voxel.h" @@ -37,32 +38,37 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_decoration.h" #include "mapgen_fractal.h" -FlagDesc flagdesc_mapgen_fractal[] = {{"terrain", MGFRACTAL_TERRAIN}, {NULL, 0}}; + +FlagDesc flagdesc_mapgen_fractal[] = { + {"terrain", MGFRACTAL_TERRAIN}, + {NULL, 0} +}; /////////////////////////////////////////////////////////////////////////////////////// -MapgenFractal::MapgenFractal(MapgenFractalParams *params, EmergeParams *emerge) : - MapgenBasic(MAPGEN_FRACTAL, params, emerge) + +MapgenFractal::MapgenFractal(MapgenFractalParams *params, EmergeParams *emerge) + : MapgenBasic(MAPGEN_FRACTAL, params, emerge) { - spflags = params->spflags; - cave_width = params->cave_width; - large_cave_depth = params->large_cave_depth; + spflags = params->spflags; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; small_cave_num_min = params->small_cave_num_min; small_cave_num_max = params->small_cave_num_max; large_cave_num_min = params->large_cave_num_min; large_cave_num_max = params->large_cave_num_max; large_cave_flooded = params->large_cave_flooded; - dungeon_ymin = params->dungeon_ymin; - dungeon_ymax = params->dungeon_ymax; - fractal = params->fractal; - iterations = params->iterations; - scale = params->scale; - offset = params->offset; - slice_w = params->slice_w; - julia_x = params->julia_x; - julia_y = params->julia_y; - julia_z = params->julia_z; - julia_w = params->julia_w; + dungeon_ymin = params->dungeon_ymin; + dungeon_ymax = params->dungeon_ymax; + fractal = params->fractal; + iterations = params->iterations; + scale = params->scale; + offset = params->offset; + slice_w = params->slice_w; + julia_x = params->julia_x; + julia_y = params->julia_y; + julia_z = params->julia_z; + julia_w = params->julia_w; //// 2D noise if (spflags & MGFRACTAL_TERRAIN) @@ -73,99 +79,106 @@ MapgenFractal::MapgenFractal(MapgenFractalParams *params, EmergeParams *emerge) //// 3D noise MapgenBasic::np_dungeons = params->np_dungeons; // Overgeneration to node_min.Y - 1 - MapgenBasic::np_cave1 = params->np_cave1; - MapgenBasic::np_cave2 = params->np_cave2; + MapgenBasic::np_cave1 = params->np_cave1; + MapgenBasic::np_cave2 = params->np_cave2; formula = fractal / 2 + fractal % 2; - julia = fractal % 2 == 0; + julia = fractal % 2 == 0; } + MapgenFractal::~MapgenFractal() { delete noise_seabed; delete noise_filler_depth; } -MapgenFractalParams::MapgenFractalParams() : - np_seabed(-14, 9, v3f(600, 600, 600), 41900, 5, 0.6, 2.0), - np_filler_depth(0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), - np_cave1(0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), - np_cave2(0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), - np_dungeons(0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) + +MapgenFractalParams::MapgenFractalParams(): + np_seabed (-14, 9, v3f(600, 600, 600), 41900, 5, 0.6, 2.0), + np_filler_depth (0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), + np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), + np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), + np_dungeons (0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) { } + void MapgenFractalParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgfractal_spflags", spflags, flagdesc_mapgen_fractal); - settings->getFloatNoEx("mgfractal_cave_width", cave_width); - settings->getS16NoEx("mgfractal_large_cave_depth", large_cave_depth); - settings->getU16NoEx("mgfractal_small_cave_num_min", small_cave_num_min); - settings->getU16NoEx("mgfractal_small_cave_num_max", small_cave_num_max); - settings->getU16NoEx("mgfractal_large_cave_num_min", large_cave_num_min); - settings->getU16NoEx("mgfractal_large_cave_num_max", large_cave_num_max); + settings->getFloatNoEx("mgfractal_cave_width", cave_width); + settings->getS16NoEx("mgfractal_large_cave_depth", large_cave_depth); + settings->getU16NoEx("mgfractal_small_cave_num_min", small_cave_num_min); + settings->getU16NoEx("mgfractal_small_cave_num_max", small_cave_num_max); + settings->getU16NoEx("mgfractal_large_cave_num_min", large_cave_num_min); + settings->getU16NoEx("mgfractal_large_cave_num_max", large_cave_num_max); settings->getFloatNoEx("mgfractal_large_cave_flooded", large_cave_flooded); - settings->getS16NoEx("mgfractal_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgfractal_dungeon_ymax", dungeon_ymax); - settings->getU16NoEx("mgfractal_fractal", fractal); - settings->getU16NoEx("mgfractal_iterations", iterations); - settings->getV3FNoEx("mgfractal_scale", scale); - settings->getV3FNoEx("mgfractal_offset", offset); - settings->getFloatNoEx("mgfractal_slice_w", slice_w); - settings->getFloatNoEx("mgfractal_julia_x", julia_x); - settings->getFloatNoEx("mgfractal_julia_y", julia_y); - settings->getFloatNoEx("mgfractal_julia_z", julia_z); - settings->getFloatNoEx("mgfractal_julia_w", julia_w); - - settings->getNoiseParams("mgfractal_np_seabed", np_seabed); + settings->getS16NoEx("mgfractal_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgfractal_dungeon_ymax", dungeon_ymax); + settings->getU16NoEx("mgfractal_fractal", fractal); + settings->getU16NoEx("mgfractal_iterations", iterations); + settings->getV3FNoEx("mgfractal_scale", scale); + settings->getV3FNoEx("mgfractal_offset", offset); + settings->getFloatNoEx("mgfractal_slice_w", slice_w); + settings->getFloatNoEx("mgfractal_julia_x", julia_x); + settings->getFloatNoEx("mgfractal_julia_y", julia_y); + settings->getFloatNoEx("mgfractal_julia_z", julia_z); + settings->getFloatNoEx("mgfractal_julia_w", julia_w); + + settings->getNoiseParams("mgfractal_np_seabed", np_seabed); settings->getNoiseParams("mgfractal_np_filler_depth", np_filler_depth); - settings->getNoiseParams("mgfractal_np_cave1", np_cave1); - settings->getNoiseParams("mgfractal_np_cave2", np_cave2); - settings->getNoiseParams("mgfractal_np_dungeons", np_dungeons); + settings->getNoiseParams("mgfractal_np_cave1", np_cave1); + settings->getNoiseParams("mgfractal_np_cave2", np_cave2); + settings->getNoiseParams("mgfractal_np_dungeons", np_dungeons); } + void MapgenFractalParams::writeParams(Settings *settings) const { settings->setFlagStr("mgfractal_spflags", spflags, flagdesc_mapgen_fractal); - settings->setFloat("mgfractal_cave_width", cave_width); - settings->setS16("mgfractal_large_cave_depth", large_cave_depth); - settings->setU16("mgfractal_small_cave_num_min", small_cave_num_min); - settings->setU16("mgfractal_small_cave_num_max", small_cave_num_max); - settings->setU16("mgfractal_large_cave_num_min", large_cave_num_min); - settings->setU16("mgfractal_large_cave_num_max", large_cave_num_max); + settings->setFloat("mgfractal_cave_width", cave_width); + settings->setS16("mgfractal_large_cave_depth", large_cave_depth); + settings->setU16("mgfractal_small_cave_num_min", small_cave_num_min); + settings->setU16("mgfractal_small_cave_num_max", small_cave_num_max); + settings->setU16("mgfractal_large_cave_num_min", large_cave_num_min); + settings->setU16("mgfractal_large_cave_num_max", large_cave_num_max); settings->setFloat("mgfractal_large_cave_flooded", large_cave_flooded); - settings->setS16("mgfractal_dungeon_ymin", dungeon_ymin); - settings->setS16("mgfractal_dungeon_ymax", dungeon_ymax); - settings->setU16("mgfractal_fractal", fractal); - settings->setU16("mgfractal_iterations", iterations); - settings->setV3F("mgfractal_scale", scale); - settings->setV3F("mgfractal_offset", offset); - settings->setFloat("mgfractal_slice_w", slice_w); - settings->setFloat("mgfractal_julia_x", julia_x); - settings->setFloat("mgfractal_julia_y", julia_y); - settings->setFloat("mgfractal_julia_z", julia_z); - settings->setFloat("mgfractal_julia_w", julia_w); - - settings->setNoiseParams("mgfractal_np_seabed", np_seabed); + settings->setS16("mgfractal_dungeon_ymin", dungeon_ymin); + settings->setS16("mgfractal_dungeon_ymax", dungeon_ymax); + settings->setU16("mgfractal_fractal", fractal); + settings->setU16("mgfractal_iterations", iterations); + settings->setV3F("mgfractal_scale", scale); + settings->setV3F("mgfractal_offset", offset); + settings->setFloat("mgfractal_slice_w", slice_w); + settings->setFloat("mgfractal_julia_x", julia_x); + settings->setFloat("mgfractal_julia_y", julia_y); + settings->setFloat("mgfractal_julia_z", julia_z); + settings->setFloat("mgfractal_julia_w", julia_w); + + settings->setNoiseParams("mgfractal_np_seabed", np_seabed); settings->setNoiseParams("mgfractal_np_filler_depth", np_filler_depth); - settings->setNoiseParams("mgfractal_np_cave1", np_cave1); - settings->setNoiseParams("mgfractal_np_cave2", np_cave2); - settings->setNoiseParams("mgfractal_np_dungeons", np_dungeons); + settings->setNoiseParams("mgfractal_np_cave1", np_cave1); + settings->setNoiseParams("mgfractal_np_cave2", np_cave2); + settings->setNoiseParams("mgfractal_np_dungeons", np_dungeons); } + void MapgenFractalParams::setDefaultSettings(Settings *settings) { - settings->setDefault( - "mgfractal_spflags", flagdesc_mapgen_fractal, MGFRACTAL_TERRAIN); + settings->setDefault("mgfractal_spflags", flagdesc_mapgen_fractal, + MGFRACTAL_TERRAIN); } + ///////////////////////////////////////////////////////////////// + int MapgenFractal::getSpawnLevelAtPoint(v2s16 p) { bool solid_below = false; // Fractal node is present below to spawn on - u8 air_count = 0; // Consecutive air nodes above a fractal node - s16 search_start = 0; // No terrain search start + u8 air_count = 0; // Consecutive air nodes above a fractal node + s16 search_start = 0; // No terrain search start // If terrain present, don't start search below terrain or water level if (noise_seabed) { @@ -187,22 +200,23 @@ int MapgenFractal::getSpawnLevelAtPoint(v2s16 p) } } - return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point + return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } + void MapgenFractal::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); - // TimeTaker t("makeChunk"); + //TimeTaker t("makeChunk"); this->generating = true; this->vm = data->vmanip; @@ -257,18 +271,19 @@ void MapgenFractal::makeChunk(BlockMakeData *data) // Calculate lighting if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), - full_node_min, full_node_max); + full_node_min, full_node_max); this->generating = false; - // printf("makeChunk: %lums\n", t.stop()); + //printf("makeChunk: %lums\n", t.stop()); } + bool MapgenFractal::getFractalAtPoint(s16 x, s16 y, s16 z) { float cx, cy, cz, cw, ox, oy, oz, ow; - if (julia) { // Julia set + if (julia) { // Julia set cx = julia_x; cy = julia_y; cz = julia_z; @@ -277,7 +292,7 @@ bool MapgenFractal::getFractalAtPoint(s16 x, s16 y, s16 z) oy = (float)y / scale.Y - offset.Y; oz = (float)z / scale.Z - offset.Z; ow = slice_w; - } else { // Mandelbrot set + } else { // Mandelbrot set cx = (float)x / scale.X - offset.X; cy = (float)y / scale.Y - offset.Y; cz = (float)z / scale.Z - offset.Z; @@ -326,8 +341,7 @@ bool MapgenFractal::getFractalAtPoint(s16 x, s16 y, s16 z) nz = -2.0f * ox * oz + cz; break; case 6: // 3D "Christmas Tree" - // Altering the formula here is necessary to avoid division by - // zero + // Altering the formula here is necessary to avoid division by zero if (std::fabs(oz) < 0.000000001f) { nx = ox * ox - oy * oy - oz * oz + cx; ny = 2.0f * oy * ox + cy; @@ -366,8 +380,7 @@ bool MapgenFractal::getFractalAtPoint(s16 x, s16 y, s16 z) case 9: // 4D "Mandelbulb" float rxy = std::sqrt(ox * ox + oy * oy); float rxyz = std::sqrt(ox * ox + oy * oy + oz * oz); - if (std::fabs(ow) < 0.000000001f && - std::fabs(oz) < 0.000000001f) { + if (std::fabs(ow) < 0.000000001f && std::fabs(oz) < 0.000000001f) { nx = (ox * ox - oy * oy) + cx; ny = 2.0f * ox * oy + cy; nz = -2.0f * rxy * oz + cz; @@ -395,6 +408,7 @@ bool MapgenFractal::getFractalAtPoint(s16 x, s16 y, s16 z) return true; } + s16 MapgenFractal::generateTerrain() { MapNode n_air(CONTENT_AIR); @@ -418,14 +432,12 @@ s16 MapgenFractal::generateTerrain() if (noise_seabed) seabed_height = noise_seabed->result[index2d]; - if (((spflags & MGFRACTAL_TERRAIN) && - y <= seabed_height) || + if (((spflags & MGFRACTAL_TERRAIN) && y <= seabed_height) || getFractalAtPoint(x, y, z)) { vm->m_data[vi] = n_stone; if (y > stone_surface_max_y) stone_surface_max_y = y; - } else if ((spflags & MGFRACTAL_TERRAIN) && - y <= water_level) { + } else if ((spflags & MGFRACTAL_TERRAIN) && y <= water_level) { vm->m_data[vi] = n_water; } else { vm->m_data[vi] = n_air; diff --git a/src/mapgen/mapgen_fractal.h b/src/mapgen/mapgen_fractal.h index a1d8b890c..23af925bc 100644 --- a/src/mapgen/mapgen_fractal.h +++ b/src/mapgen/mapgen_fractal.h @@ -26,12 +26,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen.h" ///////////// Mapgen Fractal flags -#define MGFRACTAL_TERRAIN 0x01 +#define MGFRACTAL_TERRAIN 0x01 class BiomeManager; extern FlagDesc flagdesc_mapgen_fractal[]; + struct MapgenFractalParams : public MapgenParams { float cave_width = 0.09f; @@ -67,6 +68,7 @@ struct MapgenFractalParams : public MapgenParams void setDefaultSettings(Settings *settings); }; + class MapgenFractal : public MapgenBasic { public: diff --git a/src/mapgen/mapgen_singlenode.cpp b/src/mapgen/mapgen_singlenode.cpp index 6724e5fe7..cade9e7a8 100644 --- a/src/mapgen/mapgen_singlenode.cpp +++ b/src/mapgen/mapgen_singlenode.cpp @@ -28,8 +28,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "voxelalgorithms.h" #include "emerge.h" -MapgenSinglenode::MapgenSinglenode(MapgenParams *params, EmergeParams *emerge) : - Mapgen(MAPGEN_SINGLENODE, params, emerge) + +MapgenSinglenode::MapgenSinglenode(MapgenParams *params, EmergeParams *emerge) + : Mapgen(MAPGEN_SINGLENODE, params, emerge) { const NodeDefManager *ndef = emerge->ndef; @@ -41,6 +42,7 @@ MapgenSinglenode::MapgenSinglenode(MapgenParams *params, EmergeParams *emerge) : set_light = (ndef->get(n_node).sunlight_propagates) ? LIGHT_SUN : 0x00; } + //////////////////////// Map generator void MapgenSinglenode::makeChunk(BlockMakeData *data) @@ -49,14 +51,14 @@ void MapgenSinglenode::makeChunk(BlockMakeData *data) assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; - this->vm = data->vmanip; + this->vm = data->vmanip; this->ndef = data->nodedef; v3s16 blockpos_min = data->blockpos_min; @@ -71,14 +73,14 @@ void MapgenSinglenode::makeChunk(BlockMakeData *data) MapNode n_node(c_node); for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 y = node_min.Y; y <= node_max.Y; y++) { - u32 i = vm->m_area.index(node_min.X, y, z); - for (s16 x = node_min.X; x <= node_max.X; x++) { - if (vm->m_data[i].getContent() == CONTENT_IGNORE) - vm->m_data[i] = n_node; - i++; - } + for (s16 y = node_min.Y; y <= node_max.Y; y++) { + u32 i = vm->m_area.index(node_min.X, y, z); + for (s16 x = node_min.X; x <= node_max.X; x++) { + if (vm->m_data[i].getContent() == CONTENT_IGNORE) + vm->m_data[i] = n_node; + i++; } + } // Add top and bottom side of water to transforming_liquid queue updateLiquid(&data->transforming_liquid, node_min, node_max); @@ -90,6 +92,7 @@ void MapgenSinglenode::makeChunk(BlockMakeData *data) this->generating = false; } + int MapgenSinglenode::getSpawnLevelAtPoint(v2s16 p) { return 0; diff --git a/src/mapgen/mapgen_v5.cpp b/src/mapgen/mapgen_v5.cpp index 950e23f86..124667e5d 100644 --- a/src/mapgen/mapgen_v5.cpp +++ b/src/mapgen/mapgen_v5.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "mapgen.h" #include "voxel.h" #include "noise.h" @@ -36,40 +37,46 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_decoration.h" #include "mapgen_v5.h" -FlagDesc flagdesc_mapgen_v5[] = {{"caverns", MGV5_CAVERNS}, {NULL, 0}}; -MapgenV5::MapgenV5(MapgenV5Params *params, EmergeParams *emerge) : - MapgenBasic(MAPGEN_V5, params, emerge) +FlagDesc flagdesc_mapgen_v5[] = { + {"caverns", MGV5_CAVERNS}, + {NULL, 0} +}; + + +MapgenV5::MapgenV5(MapgenV5Params *params, EmergeParams *emerge) + : MapgenBasic(MAPGEN_V5, params, emerge) { - spflags = params->spflags; - cave_width = params->cave_width; - large_cave_depth = params->large_cave_depth; + spflags = params->spflags; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; small_cave_num_min = params->small_cave_num_min; small_cave_num_max = params->small_cave_num_max; large_cave_num_min = params->large_cave_num_min; large_cave_num_max = params->large_cave_num_max; large_cave_flooded = params->large_cave_flooded; - cavern_limit = params->cavern_limit; - cavern_taper = params->cavern_taper; - cavern_threshold = params->cavern_threshold; - dungeon_ymin = params->dungeon_ymin; - dungeon_ymax = params->dungeon_ymax; + cavern_limit = params->cavern_limit; + cavern_taper = params->cavern_taper; + cavern_threshold = params->cavern_threshold; + dungeon_ymin = params->dungeon_ymin; + dungeon_ymax = params->dungeon_ymax; // Terrain noise noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); - noise_factor = new Noise(¶ms->np_factor, seed, csize.X, csize.Z); - noise_height = new Noise(¶ms->np_height, seed, csize.X, csize.Z); + noise_factor = new Noise(¶ms->np_factor, seed, csize.X, csize.Z); + noise_height = new Noise(¶ms->np_height, seed, csize.X, csize.Z); // 3D terrain noise // 1-up 1-down overgeneration noise_ground = new Noise(¶ms->np_ground, seed, csize.X, csize.Y + 2, csize.Z); // 1 down overgeneration - MapgenBasic::np_cave1 = params->np_cave1; - MapgenBasic::np_cave2 = params->np_cave2; - MapgenBasic::np_cavern = params->np_cavern; + MapgenBasic::np_cave1 = params->np_cave1; + MapgenBasic::np_cave2 = params->np_cave2; + MapgenBasic::np_cavern = params->np_cavern; MapgenBasic::np_dungeons = params->np_dungeons; } + MapgenV5::~MapgenV5() { delete noise_filler_depth; @@ -78,77 +85,83 @@ MapgenV5::~MapgenV5() delete noise_ground; } -MapgenV5Params::MapgenV5Params() : - np_filler_depth(0, 1, v3f(150, 150, 150), 261, 4, 0.7, 2.0), - np_factor(0, 1, v3f(250, 250, 250), 920381, 3, 0.45, 2.0), - np_height(0, 10, v3f(250, 250, 250), 84174, 4, 0.5, 2.0), - np_ground(0, 40, v3f(80, 80, 80), 983240, 4, 0.55, 2.0, NOISE_FLAG_EASED), - np_cave1(0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), - np_cave2(0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), - np_cavern(0, 1, v3f(384, 128, 384), 723, 5, 0.63, 2.0), - np_dungeons(0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) + +MapgenV5Params::MapgenV5Params(): + np_filler_depth (0, 1, v3f(150, 150, 150), 261, 4, 0.7, 2.0), + np_factor (0, 1, v3f(250, 250, 250), 920381, 3, 0.45, 2.0), + np_height (0, 10, v3f(250, 250, 250), 84174, 4, 0.5, 2.0), + np_ground (0, 40, v3f(80, 80, 80), 983240, 4, 0.55, 2.0, NOISE_FLAG_EASED), + np_cave1 (0, 12, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), + np_cave2 (0, 12, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), + np_cavern (0, 1, v3f(384, 128, 384), 723, 5, 0.63, 2.0), + np_dungeons (0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) { } + void MapgenV5Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv5_spflags", spflags, flagdesc_mapgen_v5); - settings->getFloatNoEx("mgv5_cave_width", cave_width); - settings->getS16NoEx("mgv5_large_cave_depth", large_cave_depth); - settings->getU16NoEx("mgv5_small_cave_num_min", small_cave_num_min); - settings->getU16NoEx("mgv5_small_cave_num_max", small_cave_num_max); - settings->getU16NoEx("mgv5_large_cave_num_min", large_cave_num_min); - settings->getU16NoEx("mgv5_large_cave_num_max", large_cave_num_max); + settings->getFloatNoEx("mgv5_cave_width", cave_width); + settings->getS16NoEx("mgv5_large_cave_depth", large_cave_depth); + settings->getU16NoEx("mgv5_small_cave_num_min", small_cave_num_min); + settings->getU16NoEx("mgv5_small_cave_num_max", small_cave_num_max); + settings->getU16NoEx("mgv5_large_cave_num_min", large_cave_num_min); + settings->getU16NoEx("mgv5_large_cave_num_max", large_cave_num_max); settings->getFloatNoEx("mgv5_large_cave_flooded", large_cave_flooded); - settings->getS16NoEx("mgv5_cavern_limit", cavern_limit); - settings->getS16NoEx("mgv5_cavern_taper", cavern_taper); - settings->getFloatNoEx("mgv5_cavern_threshold", cavern_threshold); - settings->getS16NoEx("mgv5_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgv5_dungeon_ymax", dungeon_ymax); + settings->getS16NoEx("mgv5_cavern_limit", cavern_limit); + settings->getS16NoEx("mgv5_cavern_taper", cavern_taper); + settings->getFloatNoEx("mgv5_cavern_threshold", cavern_threshold); + settings->getS16NoEx("mgv5_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgv5_dungeon_ymax", dungeon_ymax); settings->getNoiseParams("mgv5_np_filler_depth", np_filler_depth); - settings->getNoiseParams("mgv5_np_factor", np_factor); - settings->getNoiseParams("mgv5_np_height", np_height); - settings->getNoiseParams("mgv5_np_ground", np_ground); - settings->getNoiseParams("mgv5_np_cave1", np_cave1); - settings->getNoiseParams("mgv5_np_cave2", np_cave2); - settings->getNoiseParams("mgv5_np_cavern", np_cavern); - settings->getNoiseParams("mgv5_np_dungeons", np_dungeons); + settings->getNoiseParams("mgv5_np_factor", np_factor); + settings->getNoiseParams("mgv5_np_height", np_height); + settings->getNoiseParams("mgv5_np_ground", np_ground); + settings->getNoiseParams("mgv5_np_cave1", np_cave1); + settings->getNoiseParams("mgv5_np_cave2", np_cave2); + settings->getNoiseParams("mgv5_np_cavern", np_cavern); + settings->getNoiseParams("mgv5_np_dungeons", np_dungeons); } + void MapgenV5Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv5_spflags", spflags, flagdesc_mapgen_v5); - settings->setFloat("mgv5_cave_width", cave_width); - settings->setS16("mgv5_large_cave_depth", large_cave_depth); - settings->setU16("mgv5_small_cave_num_min", small_cave_num_min); - settings->setU16("mgv5_small_cave_num_max", small_cave_num_max); - settings->setU16("mgv5_large_cave_num_min", large_cave_num_min); - settings->setU16("mgv5_large_cave_num_max", large_cave_num_max); + settings->setFloat("mgv5_cave_width", cave_width); + settings->setS16("mgv5_large_cave_depth", large_cave_depth); + settings->setU16("mgv5_small_cave_num_min", small_cave_num_min); + settings->setU16("mgv5_small_cave_num_max", small_cave_num_max); + settings->setU16("mgv5_large_cave_num_min", large_cave_num_min); + settings->setU16("mgv5_large_cave_num_max", large_cave_num_max); settings->setFloat("mgv5_large_cave_flooded", large_cave_flooded); - settings->setS16("mgv5_cavern_limit", cavern_limit); - settings->setS16("mgv5_cavern_taper", cavern_taper); - settings->setFloat("mgv5_cavern_threshold", cavern_threshold); - settings->setS16("mgv5_dungeon_ymin", dungeon_ymin); - settings->setS16("mgv5_dungeon_ymax", dungeon_ymax); + settings->setS16("mgv5_cavern_limit", cavern_limit); + settings->setS16("mgv5_cavern_taper", cavern_taper); + settings->setFloat("mgv5_cavern_threshold", cavern_threshold); + settings->setS16("mgv5_dungeon_ymin", dungeon_ymin); + settings->setS16("mgv5_dungeon_ymax", dungeon_ymax); settings->setNoiseParams("mgv5_np_filler_depth", np_filler_depth); - settings->setNoiseParams("mgv5_np_factor", np_factor); - settings->setNoiseParams("mgv5_np_height", np_height); - settings->setNoiseParams("mgv5_np_ground", np_ground); - settings->setNoiseParams("mgv5_np_cave1", np_cave1); - settings->setNoiseParams("mgv5_np_cave2", np_cave2); - settings->setNoiseParams("mgv5_np_cavern", np_cavern); - settings->setNoiseParams("mgv5_np_dungeons", np_dungeons); + settings->setNoiseParams("mgv5_np_factor", np_factor); + settings->setNoiseParams("mgv5_np_height", np_height); + settings->setNoiseParams("mgv5_np_ground", np_ground); + settings->setNoiseParams("mgv5_np_cave1", np_cave1); + settings->setNoiseParams("mgv5_np_cave2", np_cave2); + settings->setNoiseParams("mgv5_np_cavern", np_cavern); + settings->setNoiseParams("mgv5_np_dungeons", np_dungeons); } + void MapgenV5Params::setDefaultSettings(Settings *settings) { settings->setDefault("mgv5_spflags", flagdesc_mapgen_v5, MGV5_CAVERNS); } + ///////////////////////////////////////////////////////////////// + int MapgenV5::getSpawnLevelAtPoint(v2s16 p) { @@ -170,9 +183,9 @@ int MapgenV5::getSpawnLevelAtPoint(v2s16 p) for (s16 y = max_spawn_y + 128; y >= water_level; y--) { float n_ground = NoisePerlin3D(&noise_ground->np, p.X, y, p.Y, seed); - if (n_ground * f > y - h) { // If solid + if (n_ground * f > y - h) { // If solid if (y < water_level || y > max_spawn_y) - return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point + return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point // y + 2 because y is surface and due to biome 'dust' nodes. return y + 2; @@ -182,22 +195,23 @@ int MapgenV5::getSpawnLevelAtPoint(v2s16 p) return MAX_MAP_GENERATION_LIMIT; } + void MapgenV5::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; - this->vm = data->vmanip; + this->vm = data->vmanip; this->ndef = data->nodedef; - // TimeTaker t("makeChunk"); + //TimeTaker t("makeChunk"); v3s16 blockpos_min = data->blockpos_min; v3s16 blockpos_max = data->blockpos_max; @@ -236,8 +250,8 @@ void MapgenV5::makeChunk(BlockMakeData *data) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. - generateCavesRandomWalk( - stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); + generateCavesRandomWalk(stone_surface_max_y, + -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } @@ -257,7 +271,7 @@ void MapgenV5::makeChunk(BlockMakeData *data) if (flags & MG_BIOMES) dustTopNodes(); - // printf("makeChunk: %dms\n", t.stop()); + //printf("makeChunk: %dms\n", t.stop()); // Add top and bottom side of water to transforming_liquid queue updateLiquid(&data->transforming_liquid, full_node_min, full_node_max); @@ -265,12 +279,13 @@ void MapgenV5::makeChunk(BlockMakeData *data) // Calculate lighting if (flags & MG_LIGHT) { calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), - full_node_min, full_node_max); + full_node_min, full_node_max); } this->generating = false; } + int MapgenV5::generateBaseTerrain() { u32 index = 0; @@ -281,11 +296,10 @@ int MapgenV5::generateBaseTerrain() noise_height->perlinMap2D(node_min.X, node_min.Z); noise_ground->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); - for (s16 z = node_min.Z; z <= node_max.Z; z++) { - for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { + for (s16 z=node_min.Z; z<=node_max.Z; z++) { + for (s16 y=node_min.Y - 1; y<=node_max.Y + 1; y++) { u32 vi = vm->m_area.index(node_min.X, y, z); - for (s16 x = node_min.X; x <= node_max.X; - x++, vi++, index++, index2d++) { + for (s16 x=node_min.X; x<=node_max.X; x++, vi++, index++, index2d++) { if (vm->m_data[vi].getContent() != CONTENT_IGNORE) continue; diff --git a/src/mapgen/mapgen_v6.cpp b/src/mapgen/mapgen_v6.cpp index 8a0f01409..e9692246c 100644 --- a/src/mapgen/mapgen_v6.cpp +++ b/src/mapgen/mapgen_v6.cpp @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include #include "mapgen.h" #include "voxel.h" @@ -38,64 +39,70 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_decoration.h" #include "mapgen_v6.h" -FlagDesc flagdesc_mapgen_v6[] = {{"jungles", MGV6_JUNGLES}, - {"biomeblend", MGV6_BIOMEBLEND}, {"mudflow", MGV6_MUDFLOW}, - {"snowbiomes", MGV6_SNOWBIOMES}, {"flat", MGV6_FLAT}, - {"trees", MGV6_TREES}, {NULL, 0}}; + +FlagDesc flagdesc_mapgen_v6[] = { + {"jungles", MGV6_JUNGLES}, + {"biomeblend", MGV6_BIOMEBLEND}, + {"mudflow", MGV6_MUDFLOW}, + {"snowbiomes", MGV6_SNOWBIOMES}, + {"flat", MGV6_FLAT}, + {"trees", MGV6_TREES}, + {NULL, 0} +}; + ///////////////////////////////////////////////////////////////////////////// -MapgenV6::MapgenV6(MapgenV6Params *params, EmergeParams *emerge) : - Mapgen(MAPGEN_V6, params, emerge) + +MapgenV6::MapgenV6(MapgenV6Params *params, EmergeParams *emerge) + : Mapgen(MAPGEN_V6, params, emerge) { m_emerge = emerge; ystride = csize.X; heightmap = new s16[csize.X * csize.Z]; - spflags = params->spflags; - freq_desert = params->freq_desert; - freq_beach = params->freq_beach; + spflags = params->spflags; + freq_desert = params->freq_desert; + freq_beach = params->freq_beach; dungeon_ymin = params->dungeon_ymin; dungeon_ymax = params->dungeon_ymax; - np_cave = ¶ms->np_cave; - np_humidity = ¶ms->np_humidity; - np_trees = ¶ms->np_trees; + np_cave = ¶ms->np_cave; + np_humidity = ¶ms->np_humidity; + np_trees = ¶ms->np_trees; np_apple_trees = ¶ms->np_apple_trees; np_dungeons = NoiseParams(0.9, 0.5, v3f(500.0, 500.0, 500.0), 0, 2, 0.8, 2.0); //// Create noise objects - noise_terrain_base = new Noise(¶ms->np_terrain_base, seed, csize.X, csize.Y); - noise_terrain_higher = - new Noise(¶ms->np_terrain_higher, seed, csize.X, csize.Y); - noise_steepness = new Noise(¶ms->np_steepness, seed, csize.X, csize.Y); - noise_height_select = - new Noise(¶ms->np_height_select, seed, csize.X, csize.Y); - noise_mud = new Noise(¶ms->np_mud, seed, csize.X, csize.Y); - noise_beach = new Noise(¶ms->np_beach, seed, csize.X, csize.Y); - noise_biome = new Noise(¶ms->np_biome, seed, csize.X + 2 * MAP_BLOCKSIZE, - csize.Y + 2 * MAP_BLOCKSIZE); - noise_humidity = new Noise(¶ms->np_humidity, seed, + noise_terrain_base = new Noise(¶ms->np_terrain_base, seed, csize.X, csize.Y); + noise_terrain_higher = new Noise(¶ms->np_terrain_higher, seed, csize.X, csize.Y); + noise_steepness = new Noise(¶ms->np_steepness, seed, csize.X, csize.Y); + noise_height_select = new Noise(¶ms->np_height_select, seed, csize.X, csize.Y); + noise_mud = new Noise(¶ms->np_mud, seed, csize.X, csize.Y); + noise_beach = new Noise(¶ms->np_beach, seed, csize.X, csize.Y); + noise_biome = new Noise(¶ms->np_biome, seed, + csize.X + 2 * MAP_BLOCKSIZE, csize.Y + 2 * MAP_BLOCKSIZE); + noise_humidity = new Noise(¶ms->np_humidity, seed, csize.X + 2 * MAP_BLOCKSIZE, csize.Y + 2 * MAP_BLOCKSIZE); //// Resolve nodes to be used const NodeDefManager *ndef = emerge->ndef; - c_stone = ndef->getId("mapgen_stone"); - c_dirt = ndef->getId("mapgen_dirt"); + c_stone = ndef->getId("mapgen_stone"); + c_dirt = ndef->getId("mapgen_dirt"); c_dirt_with_grass = ndef->getId("mapgen_dirt_with_grass"); - c_sand = ndef->getId("mapgen_sand"); - c_water_source = ndef->getId("mapgen_water_source"); - c_lava_source = ndef->getId("mapgen_lava_source"); - c_gravel = ndef->getId("mapgen_gravel"); - c_desert_stone = ndef->getId("mapgen_desert_stone"); - c_desert_sand = ndef->getId("mapgen_desert_sand"); - c_dirt_with_snow = ndef->getId("mapgen_dirt_with_snow"); - c_snow = ndef->getId("mapgen_snow"); - c_snowblock = ndef->getId("mapgen_snowblock"); - c_ice = ndef->getId("mapgen_ice"); + c_sand = ndef->getId("mapgen_sand"); + c_water_source = ndef->getId("mapgen_water_source"); + c_lava_source = ndef->getId("mapgen_lava_source"); + c_gravel = ndef->getId("mapgen_gravel"); + c_desert_stone = ndef->getId("mapgen_desert_stone"); + c_desert_sand = ndef->getId("mapgen_desert_sand"); + c_dirt_with_snow = ndef->getId("mapgen_dirt_with_snow"); + c_snow = ndef->getId("mapgen_snow"); + c_snowblock = ndef->getId("mapgen_snowblock"); + c_ice = ndef->getId("mapgen_ice"); if (c_gravel == CONTENT_IGNORE) c_gravel = c_stone; @@ -112,9 +119,9 @@ MapgenV6::MapgenV6(MapgenV6Params *params, EmergeParams *emerge) : if (c_ice == CONTENT_IGNORE) c_ice = c_water_source; - c_cobble = ndef->getId("mapgen_cobble"); - c_mossycobble = ndef->getId("mapgen_mossycobble"); - c_stair_cobble = ndef->getId("mapgen_stair_cobble"); + c_cobble = ndef->getId("mapgen_cobble"); + c_mossycobble = ndef->getId("mapgen_mossycobble"); + c_stair_cobble = ndef->getId("mapgen_stair_cobble"); c_stair_desert_stone = ndef->getId("mapgen_stair_desert_stone"); if (c_mossycobble == CONTENT_IGNORE) @@ -125,29 +132,22 @@ MapgenV6::MapgenV6(MapgenV6Params *params, EmergeParams *emerge) : c_stair_desert_stone = c_desert_stone; if (c_stone == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_stone' is invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_stone' is invalid!" << std::endl; if (c_dirt == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_dirt' is invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_dirt' is invalid!" << std::endl; if (c_dirt_with_grass == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_dirt_with_grass' is " - "invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_dirt_with_grass' is invalid!" << std::endl; if (c_sand == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_sand' is invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_sand' is invalid!" << std::endl; if (c_water_source == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_water_source' is invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_water_source' is invalid!" << std::endl; if (c_lava_source == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_lava_source' is invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_lava_source' is invalid!" << std::endl; if (c_cobble == CONTENT_IGNORE) - errorstream << "Mapgen v6: Mapgen alias 'mapgen_cobble' is invalid!" - << std::endl; + errorstream << "Mapgen v6: Mapgen alias 'mapgen_cobble' is invalid!" << std::endl; } + MapgenV6::~MapgenV6() { delete noise_terrain_base; @@ -164,72 +164,77 @@ MapgenV6::~MapgenV6() delete m_emerge; // our responsibility } -MapgenV6Params::MapgenV6Params() : - np_terrain_base(-4, 20.0, v3f(250.0, 250.0, 250.0), 82341, 5, 0.6, 2.0), - np_terrain_higher(20, 16.0, v3f(500.0, 500.0, 500.0), 85039, 5, 0.6, 2.0), - np_steepness(0.85, 0.5, v3f(125.0, 125.0, 125.0), -932, 5, 0.7, 2.0), - np_height_select(0, 1.0, v3f(250.0, 250.0, 250.0), 4213, 5, 0.69, 2.0), - np_mud(4, 2.0, v3f(200.0, 200.0, 200.0), 91013, 3, 0.55, 2.0), - np_beach(0, 1.0, v3f(250.0, 250.0, 250.0), 59420, 3, 0.50, 2.0), - np_biome(0, 1.0, v3f(500.0, 500.0, 500.0), 9130, 3, 0.50, 2.0), - np_cave(6, 6.0, v3f(250.0, 250.0, 250.0), 34329, 3, 0.50, 2.0), - np_humidity(0.5, 0.5, v3f(500.0, 500.0, 500.0), 72384, 3, 0.50, 2.0), - np_trees(0, 1.0, v3f(125.0, 125.0, 125.0), 2, 4, 0.66, 2.0), - np_apple_trees(0, 1.0, v3f(100.0, 100.0, 100.0), 342902, 3, 0.45, 2.0) + +MapgenV6Params::MapgenV6Params(): + np_terrain_base (-4, 20.0, v3f(250.0, 250.0, 250.0), 82341, 5, 0.6, 2.0), + np_terrain_higher (20, 16.0, v3f(500.0, 500.0, 500.0), 85039, 5, 0.6, 2.0), + np_steepness (0.85, 0.5, v3f(125.0, 125.0, 125.0), -932, 5, 0.7, 2.0), + np_height_select (0, 1.0, v3f(250.0, 250.0, 250.0), 4213, 5, 0.69, 2.0), + np_mud (4, 2.0, v3f(200.0, 200.0, 200.0), 91013, 3, 0.55, 2.0), + np_beach (0, 1.0, v3f(250.0, 250.0, 250.0), 59420, 3, 0.50, 2.0), + np_biome (0, 1.0, v3f(500.0, 500.0, 500.0), 9130, 3, 0.50, 2.0), + np_cave (6, 6.0, v3f(250.0, 250.0, 250.0), 34329, 3, 0.50, 2.0), + np_humidity (0.5, 0.5, v3f(500.0, 500.0, 500.0), 72384, 3, 0.50, 2.0), + np_trees (0, 1.0, v3f(125.0, 125.0, 125.0), 2, 4, 0.66, 2.0), + np_apple_trees (0, 1.0, v3f(100.0, 100.0, 100.0), 342902, 3, 0.45, 2.0) { } + void MapgenV6Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv6_spflags", spflags, flagdesc_mapgen_v6); settings->getFloatNoEx("mgv6_freq_desert", freq_desert); - settings->getFloatNoEx("mgv6_freq_beach", freq_beach); - settings->getS16NoEx("mgv6_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgv6_dungeon_ymax", dungeon_ymax); + settings->getFloatNoEx("mgv6_freq_beach", freq_beach); + settings->getS16NoEx("mgv6_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgv6_dungeon_ymax", dungeon_ymax); - settings->getNoiseParams("mgv6_np_terrain_base", np_terrain_base); + settings->getNoiseParams("mgv6_np_terrain_base", np_terrain_base); settings->getNoiseParams("mgv6_np_terrain_higher", np_terrain_higher); - settings->getNoiseParams("mgv6_np_steepness", np_steepness); - settings->getNoiseParams("mgv6_np_height_select", np_height_select); - settings->getNoiseParams("mgv6_np_mud", np_mud); - settings->getNoiseParams("mgv6_np_beach", np_beach); - settings->getNoiseParams("mgv6_np_biome", np_biome); - settings->getNoiseParams("mgv6_np_cave", np_cave); - settings->getNoiseParams("mgv6_np_humidity", np_humidity); - settings->getNoiseParams("mgv6_np_trees", np_trees); - settings->getNoiseParams("mgv6_np_apple_trees", np_apple_trees); + settings->getNoiseParams("mgv6_np_steepness", np_steepness); + settings->getNoiseParams("mgv6_np_height_select", np_height_select); + settings->getNoiseParams("mgv6_np_mud", np_mud); + settings->getNoiseParams("mgv6_np_beach", np_beach); + settings->getNoiseParams("mgv6_np_biome", np_biome); + settings->getNoiseParams("mgv6_np_cave", np_cave); + settings->getNoiseParams("mgv6_np_humidity", np_humidity); + settings->getNoiseParams("mgv6_np_trees", np_trees); + settings->getNoiseParams("mgv6_np_apple_trees", np_apple_trees); } + void MapgenV6Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv6_spflags", spflags, flagdesc_mapgen_v6); settings->setFloat("mgv6_freq_desert", freq_desert); - settings->setFloat("mgv6_freq_beach", freq_beach); - settings->setS16("mgv6_dungeon_ymin", dungeon_ymin); - settings->setS16("mgv6_dungeon_ymax", dungeon_ymax); + settings->setFloat("mgv6_freq_beach", freq_beach); + settings->setS16("mgv6_dungeon_ymin", dungeon_ymin); + settings->setS16("mgv6_dungeon_ymax", dungeon_ymax); - settings->setNoiseParams("mgv6_np_terrain_base", np_terrain_base); + settings->setNoiseParams("mgv6_np_terrain_base", np_terrain_base); settings->setNoiseParams("mgv6_np_terrain_higher", np_terrain_higher); - settings->setNoiseParams("mgv6_np_steepness", np_steepness); - settings->setNoiseParams("mgv6_np_height_select", np_height_select); - settings->setNoiseParams("mgv6_np_mud", np_mud); - settings->setNoiseParams("mgv6_np_beach", np_beach); - settings->setNoiseParams("mgv6_np_biome", np_biome); - settings->setNoiseParams("mgv6_np_cave", np_cave); - settings->setNoiseParams("mgv6_np_humidity", np_humidity); - settings->setNoiseParams("mgv6_np_trees", np_trees); - settings->setNoiseParams("mgv6_np_apple_trees", np_apple_trees); + settings->setNoiseParams("mgv6_np_steepness", np_steepness); + settings->setNoiseParams("mgv6_np_height_select", np_height_select); + settings->setNoiseParams("mgv6_np_mud", np_mud); + settings->setNoiseParams("mgv6_np_beach", np_beach); + settings->setNoiseParams("mgv6_np_biome", np_biome); + settings->setNoiseParams("mgv6_np_cave", np_cave); + settings->setNoiseParams("mgv6_np_humidity", np_humidity); + settings->setNoiseParams("mgv6_np_trees", np_trees); + settings->setNoiseParams("mgv6_np_apple_trees", np_apple_trees); } + void MapgenV6Params::setDefaultSettings(Settings *settings) { - settings->setDefault("mgv6_spflags", flagdesc_mapgen_v6, - MGV6_JUNGLES | MGV6_SNOWBIOMES | MGV6_TREES | MGV6_BIOMEBLEND | - MGV6_MUDFLOW); + settings->setDefault("mgv6_spflags", flagdesc_mapgen_v6, MGV6_JUNGLES | + MGV6_SNOWBIOMES | MGV6_TREES | MGV6_BIOMEBLEND | MGV6_MUDFLOW); } + //////////////////////// Some helper functions for the map generator + // Returns Y one under area minimum if not found s16 MapgenV6::find_stone_level(v2s16 p2d) { @@ -249,6 +254,7 @@ s16 MapgenV6::find_stone_level(v2s16 p2d) return (y >= y_nodes_min) ? y : y_nodes_min - 1; } + // Required by mapgen.h bool MapgenV6::block_is_underground(u64 seed, v3s16 blockpos) { @@ -257,22 +263,23 @@ bool MapgenV6::block_is_underground(u64 seed, v3s16 blockpos) // Nah, this is just a heuristic, just return something s16 minimum_groundlevel = water_level; - if (blockpos.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE <= minimum_groundlevel) + if(blockpos.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE <= minimum_groundlevel) return true; return false; } + //////////////////////// Base terrain height functions float MapgenV6::baseTerrainLevel(float terrain_base, float terrain_higher, - float steepness, float height_select) + float steepness, float height_select) { - float base = 1 + terrain_base; + float base = 1 + terrain_base; float higher = 1 + terrain_higher; // Limit higher ground level to at least base - if (higher < base) + if(higher < base) higher = base; // Steepness factor of cliffs @@ -292,61 +299,71 @@ float MapgenV6::baseTerrainLevel(float terrain_base, float terrain_higher, return base * (1.0 - a) + higher * a; } + float MapgenV6::baseTerrainLevelFromNoise(v2s16 p) { if (spflags & MGV6_FLAT) return water_level; - float terrain_base = NoisePerlin2D_PO( - &noise_terrain_base->np, p.X, 0.5, p.Y, 0.5, seed); - float terrain_higher = NoisePerlin2D_PO( - &noise_terrain_higher->np, p.X, 0.5, p.Y, 0.5, seed); - float steepness = - NoisePerlin2D_PO(&noise_steepness->np, p.X, 0.5, p.Y, 0.5, seed); - float height_select = NoisePerlin2D_PO( - &noise_height_select->np, p.X, 0.5, p.Y, 0.5, seed); - - return baseTerrainLevel(terrain_base, terrain_higher, steepness, height_select); + float terrain_base = NoisePerlin2D_PO(&noise_terrain_base->np, + p.X, 0.5, p.Y, 0.5, seed); + float terrain_higher = NoisePerlin2D_PO(&noise_terrain_higher->np, + p.X, 0.5, p.Y, 0.5, seed); + float steepness = NoisePerlin2D_PO(&noise_steepness->np, + p.X, 0.5, p.Y, 0.5, seed); + float height_select = NoisePerlin2D_PO(&noise_height_select->np, + p.X, 0.5, p.Y, 0.5, seed); + + return baseTerrainLevel(terrain_base, terrain_higher, + steepness, height_select); } + float MapgenV6::baseTerrainLevelFromMap(v2s16 p) { int index = (p.Y - node_min.Z) * ystride + (p.X - node_min.X); return baseTerrainLevelFromMap(index); } + float MapgenV6::baseTerrainLevelFromMap(int index) { if (spflags & MGV6_FLAT) return water_level; - float terrain_base = noise_terrain_base->result[index]; + float terrain_base = noise_terrain_base->result[index]; float terrain_higher = noise_terrain_higher->result[index]; - float steepness = noise_steepness->result[index]; - float height_select = noise_height_select->result[index]; + float steepness = noise_steepness->result[index]; + float height_select = noise_height_select->result[index]; - return baseTerrainLevel(terrain_base, terrain_higher, steepness, height_select); + return baseTerrainLevel(terrain_base, terrain_higher, + steepness, height_select); } + s16 MapgenV6::find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision) { return baseTerrainLevelFromNoise(p2d) + MGV6_AVERAGE_MUD_AMOUNT; } + int MapgenV6::getGroundLevelAtPoint(v2s16 p) { return baseTerrainLevelFromNoise(p) + MGV6_AVERAGE_MUD_AMOUNT; } + int MapgenV6::getSpawnLevelAtPoint(v2s16 p) { s16 level_at_point = baseTerrainLevelFromNoise(p) + MGV6_AVERAGE_MUD_AMOUNT; - if (level_at_point <= water_level || level_at_point > water_level + 16) - return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point + if (level_at_point <= water_level || + level_at_point > water_level + 16) + return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point return level_at_point; } + //////////////////////// Noise functions float MapgenV6::getMudAmount(v2s16 p) @@ -355,19 +372,22 @@ float MapgenV6::getMudAmount(v2s16 p) return getMudAmount(index); } + bool MapgenV6::getHaveBeach(v2s16 p) { int index = (p.Y - node_min.Z) * ystride + (p.X - node_min.X); return getHaveBeach(index); } + BiomeV6Type MapgenV6::getBiome(v2s16 p) { - int index = (p.Y - full_node_min.Z) * (ystride + 2 * MAP_BLOCKSIZE) + - (p.X - full_node_min.X); + int index = (p.Y - full_node_min.Z) * (ystride + 2 * MAP_BLOCKSIZE) + + (p.X - full_node_min.X); return getBiome(index, p); } + float MapgenV6::getHumidity(v2s16 p) { /*double noise = noise2d_perlin( @@ -375,8 +395,8 @@ float MapgenV6::getHumidity(v2s16 p) seed+72384, 4, 0.66); noise = (noise + 1.0)/2.0;*/ - int index = (p.Y - full_node_min.Z) * (ystride + 2 * MAP_BLOCKSIZE) + - (p.X - full_node_min.X); + int index = (p.Y - full_node_min.Z) * (ystride + 2 * MAP_BLOCKSIZE) + + (p.X - full_node_min.X); float noise = noise_humidity->result[index]; if (noise < 0.0) @@ -386,6 +406,7 @@ float MapgenV6::getHumidity(v2s16 p) return noise; } + float MapgenV6::getTreeAmount(v2s16 p) { /*double noise = noise2d_perlin( @@ -400,6 +421,7 @@ float MapgenV6::getTreeAmount(v2s16 p) return 0.04 * (noise - zeroval) / (1.0 - zeroval); } + bool MapgenV6::getHaveAppleTree(v2s16 p) { /*is_apple_tree = noise2d_perlin( @@ -411,6 +433,7 @@ bool MapgenV6::getHaveAppleTree(v2s16 p) return noise > 0.2; } + float MapgenV6::getMudAmount(int index) { if (spflags & MGV6_FLAT) @@ -423,6 +446,7 @@ float MapgenV6::getMudAmount(int index) return noise_mud->result[index]; } + bool MapgenV6::getHaveBeach(int index) { // Determine whether to have sand here @@ -434,6 +458,7 @@ bool MapgenV6::getHaveBeach(int index) return (sandnoise > freq_beach); } + BiomeV6Type MapgenV6::getBiome(int index, v2s16 p) { // Just do something very simple as for now @@ -445,8 +470,7 @@ BiomeV6Type MapgenV6::getBiome(int index, v2s16 p) float h = noise_humidity->result[index]; if (spflags & MGV6_SNOWBIOMES) { - float blend = (spflags & MGV6_BIOMEBLEND) ? noise2d(p.X, p.Y, seed) / 40 - : 0; + float blend = (spflags & MGV6_BIOMEBLEND) ? noise2d(p.X, p.Y, seed) / 40 : 0; if (d > MGV6_FREQ_HOT + blend) { if (h > MGV6_FREQ_JUNGLE + blend) @@ -476,14 +500,17 @@ BiomeV6Type MapgenV6::getBiome(int index, v2s16 p) return BT_JUNGLE; return BT_NORMAL; + } + u32 MapgenV6::get_blockseed(u64 seed, v3s16 p) { s32 x = p.X, y = p.Y, z = p.Z; return (u32)(seed % 0x100000000ULL) + z * 38134234 + y * 42123 + x * 23; } + //////////////////////// Map generator void MapgenV6::makeChunk(BlockMakeData *data) @@ -492,14 +519,14 @@ void MapgenV6::makeChunk(BlockMakeData *data) assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); this->generating = true; - this->vm = data->vmanip; + this->vm = data->vmanip; this->ndef = data->nodedef; // Hack: use minimum block coords for old code that assumes a single block @@ -551,6 +578,7 @@ void MapgenV6::makeChunk(BlockMakeData *data) // Flow mud away from steep edges if (spflags & MGV6_MUDFLOW) flowMud(mudflow_minpos, mudflow_maxpos); + } // Update heightmap after mudflow @@ -558,53 +586,50 @@ void MapgenV6::makeChunk(BlockMakeData *data) // Add dungeons if ((flags & MG_DUNGEONS) && stone_surface_max_y >= node_min.Y && - full_node_min.Y >= dungeon_ymin && - full_node_max.Y <= dungeon_ymax) { - u16 num_dungeons = std::fmax( - std::floor(NoisePerlin3D(&np_dungeons, node_min.X, - node_min.Y, node_min.Z, seed)), - 0.0f); + full_node_min.Y >= dungeon_ymin && full_node_max.Y <= dungeon_ymax) { + u16 num_dungeons = std::fmax(std::floor( + NoisePerlin3D(&np_dungeons, node_min.X, node_min.Y, node_min.Z, seed)), 0.0f); if (num_dungeons >= 1) { PseudoRandom ps(blockseed + 4713); DungeonParams dp; - dp.seed = seed; - dp.num_dungeons = num_dungeons; - dp.only_in_ground = true; - dp.corridor_len_min = 1; - dp.corridor_len_max = 13; - dp.num_rooms = ps.range(2, 16); + dp.seed = seed; + dp.num_dungeons = num_dungeons; + dp.only_in_ground = true; + dp.corridor_len_min = 1; + dp.corridor_len_max = 13; + dp.num_rooms = ps.range(2, 16); dp.large_room_chance = (ps.range(1, 4) == 1) ? 1 : 0; - dp.np_alt_wall = NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), - 32474, 6, 1.1, 2.0); + dp.np_alt_wall + = NoiseParams(-0.4, 1.0, v3f(40.0, 40.0, 40.0), 32474, 6, 1.1, 2.0); if (getBiome(0, v2s16(node_min.X, node_min.Z)) == BT_DESERT) { - dp.c_wall = c_desert_stone; - dp.c_alt_wall = CONTENT_IGNORE; - dp.c_stair = c_stair_desert_stone; - - dp.diagonal_dirs = true; - dp.holesize = v3s16(2, 3, 2); - dp.room_size_min = v3s16(6, 9, 6); - dp.room_size_max = v3s16(10, 11, 10); + dp.c_wall = c_desert_stone; + dp.c_alt_wall = CONTENT_IGNORE; + dp.c_stair = c_stair_desert_stone; + + dp.diagonal_dirs = true; + dp.holesize = v3s16(2, 3, 2); + dp.room_size_min = v3s16(6, 9, 6); + dp.room_size_max = v3s16(10, 11, 10); dp.room_size_large_min = v3s16(10, 13, 10); dp.room_size_large_max = v3s16(18, 21, 18); - dp.notifytype = GENNOTIFY_TEMPLE; + dp.notifytype = GENNOTIFY_TEMPLE; } else { - dp.c_wall = c_cobble; - dp.c_alt_wall = c_mossycobble; - dp.c_stair = c_stair_cobble; - - dp.diagonal_dirs = false; - dp.holesize = v3s16(1, 2, 1); - dp.room_size_min = v3s16(4, 4, 4); - dp.room_size_max = v3s16(8, 6, 8); + dp.c_wall = c_cobble; + dp.c_alt_wall = c_mossycobble; + dp.c_stair = c_stair_cobble; + + dp.diagonal_dirs = false; + dp.holesize = v3s16(1, 2, 1); + dp.room_size_min = v3s16(4, 4, 4); + dp.room_size_max = v3s16(8, 6, 8); dp.room_size_large_min = v3s16(8, 8, 8); dp.room_size_large_max = v3s16(16, 16, 16); - dp.notifytype = GENNOTIFY_DUNGEON; + dp.notifytype = GENNOTIFY_DUNGEON; } DungeonGen dgen(ndef, &gennotify, &dp); @@ -632,12 +657,13 @@ void MapgenV6::makeChunk(BlockMakeData *data) // Calculate lighting if (flags & MG_LIGHT) calcLighting(node_min - v3s16(1, 1, 1) * MAP_BLOCKSIZE, - node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, full_node_min, - full_node_max); + node_max + v3s16(1, 0, 1) * MAP_BLOCKSIZE, + full_node_min, full_node_max); this->generating = false; } + void MapgenV6::calculateNoise() { int x = node_min.X; @@ -661,9 +687,10 @@ void MapgenV6::calculateNoise() // only humidity at point does } + int MapgenV6::generateGround() { - // TimeTaker timer1("Generating ground level"); + //TimeTaker timer1("Generating ground level"); MapNode n_air(CONTENT_AIR), n_water_source(c_water_source); MapNode n_stone(c_stone), n_desert_stone(c_desert_stone); MapNode n_ice(c_ice); @@ -671,242 +698,218 @@ int MapgenV6::generateGround() u32 index = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index++) { - // Surface height - s16 surface_y = (s16)baseTerrainLevelFromMap(index); - - // Log it - if (surface_y > stone_surface_max_y) - stone_surface_max_y = surface_y; - - BiomeV6Type bt = getBiome(v2s16(x, z)); - - // Fill ground with stone - const v3s16 &em = vm->m_area.getExtent(); - u32 i = vm->m_area.index(x, node_min.Y, z); - for (s16 y = node_min.Y; y <= node_max.Y; y++) { - if (vm->m_data[i].getContent() == CONTENT_IGNORE) { - if (y <= surface_y) { - vm->m_data[i] = (y >= MGV6_DESERT_STONE_BASE && - bt == BT_DESERT) - ? n_desert_stone - : n_stone; - } else if (y <= water_level) { - vm->m_data[i] = (y >= MGV6_ICE_BASE && - bt == BT_TUNDRA) - ? n_ice - : n_water_source; - } else { - vm->m_data[i] = n_air; - } + for (s16 x = node_min.X; x <= node_max.X; x++, index++) { + // Surface height + s16 surface_y = (s16)baseTerrainLevelFromMap(index); + + // Log it + if (surface_y > stone_surface_max_y) + stone_surface_max_y = surface_y; + + BiomeV6Type bt = getBiome(v2s16(x, z)); + + // Fill ground with stone + const v3s16 &em = vm->m_area.getExtent(); + u32 i = vm->m_area.index(x, node_min.Y, z); + for (s16 y = node_min.Y; y <= node_max.Y; y++) { + if (vm->m_data[i].getContent() == CONTENT_IGNORE) { + if (y <= surface_y) { + vm->m_data[i] = (y >= MGV6_DESERT_STONE_BASE + && bt == BT_DESERT) ? + n_desert_stone : n_stone; + } else if (y <= water_level) { + vm->m_data[i] = (y >= MGV6_ICE_BASE + && bt == BT_TUNDRA) ? + n_ice : n_water_source; + } else { + vm->m_data[i] = n_air; } - VoxelArea::add_y(em, i, 1); } + VoxelArea::add_y(em, i, 1); } + } return stone_surface_max_y; } + void MapgenV6::addMud() { // 15ms @cs=8 - // TimeTaker timer1("add mud"); + //TimeTaker timer1("add mud"); MapNode n_dirt(c_dirt), n_gravel(c_gravel); MapNode n_sand(c_sand), n_desert_sand(c_desert_sand); MapNode addnode; u32 index = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index++) { - // Randomize mud amount - s16 mud_add_amount = getMudAmount(index) / 2.0 + 0.5; + for (s16 x = node_min.X; x <= node_max.X; x++, index++) { + // Randomize mud amount + s16 mud_add_amount = getMudAmount(index) / 2.0 + 0.5; + + // Find ground level + s16 surface_y = find_stone_level(v2s16(x, z)); /////////////////optimize this! + + // Handle area not found + if (surface_y == vm->m_area.MinEdge.Y - 1) + continue; + + BiomeV6Type bt = getBiome(v2s16(x, z)); + addnode = (bt == BT_DESERT) ? n_desert_sand : n_dirt; + + if (bt == BT_DESERT && surface_y + mud_add_amount <= water_level + 1) { + addnode = n_sand; + } else if (mud_add_amount <= 0) { + mud_add_amount = 1 - mud_add_amount; + addnode = n_gravel; + } else if (bt != BT_DESERT && getHaveBeach(index) && + surface_y + mud_add_amount <= water_level + 2) { + addnode = n_sand; + } - // Find ground level - s16 surface_y = find_stone_level( - v2s16(x, z)); /////////////////optimize this! + if ((bt == BT_DESERT || bt == BT_TUNDRA) && surface_y > 20) + mud_add_amount = MYMAX(0, mud_add_amount - (surface_y - 20) / 5); - // Handle area not found - if (surface_y == vm->m_area.MinEdge.Y - 1) - continue; + /* If topmost node is grass, change it to mud. It might be if it was + // flown to there from a neighboring chunk and then converted. + u32 i = vm->m_area.index(x, surface_y, z); + if (vm->m_data[i].getContent() == c_dirt_with_grass) + vm->m_data[i] = n_dirt;*/ - BiomeV6Type bt = getBiome(v2s16(x, z)); - addnode = (bt == BT_DESERT) ? n_desert_sand : n_dirt; - - if (bt == BT_DESERT && - surface_y + mud_add_amount <= water_level + 1) { - addnode = n_sand; - } else if (mud_add_amount <= 0) { - mud_add_amount = 1 - mud_add_amount; - addnode = n_gravel; - } else if (bt != BT_DESERT && getHaveBeach(index) && - surface_y + mud_add_amount <= water_level + 2) { - addnode = n_sand; - } + // Add mud on ground + s16 mudcount = 0; + const v3s16 &em = vm->m_area.getExtent(); + s16 y_start = surface_y + 1; + u32 i = vm->m_area.index(x, y_start, z); + for (s16 y = y_start; y <= node_max.Y; y++) { + if (mudcount >= mud_add_amount) + break; - if ((bt == BT_DESERT || bt == BT_TUNDRA) && surface_y > 20) - mud_add_amount = MYMAX( - 0, mud_add_amount - (surface_y - 20) / 5); - - /* If topmost node is grass, change it to mud. It might be if it - was - // flown to there from a neighboring chunk and then converted. - u32 i = vm->m_area.index(x, surface_y, z); - if (vm->m_data[i].getContent() == c_dirt_with_grass) - vm->m_data[i] = n_dirt;*/ - - // Add mud on ground - s16 mudcount = 0; - const v3s16 &em = vm->m_area.getExtent(); - s16 y_start = surface_y + 1; - u32 i = vm->m_area.index(x, y_start, z); - for (s16 y = y_start; y <= node_max.Y; y++) { - if (mudcount >= mud_add_amount) - break; + vm->m_data[i] = addnode; + mudcount++; - vm->m_data[i] = addnode; - mudcount++; - - VoxelArea::add_y(em, i, 1); - } + VoxelArea::add_y(em, i, 1); } + } } + void MapgenV6::flowMud(s16 &mudflow_minpos, s16 &mudflow_maxpos) { const v3s16 &em = vm->m_area.getExtent(); static const v3s16 dirs4[4] = { - v3s16(0, 0, 1), // Back - v3s16(1, 0, 0), // Right - v3s16(0, 0, -1), // Front - v3s16(-1, 0, 0), // Left + v3s16(0, 0, 1), // Back + v3s16(1, 0, 0), // Right + v3s16(0, 0, -1), // Front + v3s16(-1, 0, 0), // Left }; - + // Iterate twice for (s16 k = 0; k < 2; k++) { for (s16 z = mudflow_minpos; z <= mudflow_maxpos; z++) - for (s16 x = mudflow_minpos; x <= mudflow_maxpos; x++) { - // Node column position - v2s16 p2d; - // Invert coordinates on second iteration to process - // columns in opposite order, to avoid a directional bias. - if (k == 1) - p2d = v2s16(node_max.X, node_max.Z) - v2s16(x, z); - else - p2d = v2s16(node_min.X, node_min.Z) + v2s16(x, z); - - s16 y = node_max.Y; - - while (y >= node_min.Y) { - for (;; y--) { - u32 i = vm->m_area.index(p2d.X, y, p2d.Y); - MapNode *n = nullptr; - - // Find next mud node in mapchunk column - for (; y >= node_min.Y; y--) { - n = &vm->m_data[i]; - if (n->getContent() == c_dirt || - n->getContent() == - c_dirt_with_grass || - n->getContent() == - c_gravel) - break; - - VoxelArea::add_y(em, i, -1); - } - if (y < node_min.Y) - // No mud found in mapchunk - // column, process the next column + for (s16 x = mudflow_minpos; x <= mudflow_maxpos; x++) { + // Node column position + v2s16 p2d; + // Invert coordinates on second iteration to process columns in + // opposite order, to avoid a directional bias. + if (k == 1) + p2d = v2s16(node_max.X, node_max.Z) - v2s16(x, z); + else + p2d = v2s16(node_min.X, node_min.Z) + v2s16(x, z); + + s16 y = node_max.Y; + + while (y >= node_min.Y) { + for (;; y--) { + u32 i = vm->m_area.index(p2d.X, y, p2d.Y); + MapNode *n = nullptr; + + // Find next mud node in mapchunk column + for (; y >= node_min.Y; y--) { + n = &vm->m_data[i]; + if (n->getContent() == c_dirt || + n->getContent() == c_dirt_with_grass || + n->getContent() == c_gravel) break; - if (n->getContent() == c_dirt || - n->getContent() == - c_dirt_with_grass) { - // Convert dirt_with_grass to dirt - n->setContent(c_dirt); - // Don't flow mud if the stuff - // under it is not mud, to leave - // at least 1 node of mud. - u32 i2 = i; - VoxelArea::add_y(em, i2, -1); - MapNode *n2 = &vm->m_data[i2]; - if (n2->getContent() != c_dirt && - n2->getContent() != - c_dirt_with_grass) - // Find next mud node in - // column - continue; - } + VoxelArea::add_y(em, i, -1); + } + if (y < node_min.Y) + // No mud found in mapchunk column, process the next column + break; - // Check if node above is walkable. If so, - // cancel flowing as if node above keeps - // it in place. - u32 i3 = i; - VoxelArea::add_y(em, i3, 1); - MapNode *n3 = &vm->m_data[i3]; - if (ndef->get(*n3).walkable) + if (n->getContent() == c_dirt || n->getContent() == c_dirt_with_grass) { + // Convert dirt_with_grass to dirt + n->setContent(c_dirt); + // Don't flow mud if the stuff under it is not mud, + // to leave at least 1 node of mud. + u32 i2 = i; + VoxelArea::add_y(em, i2, -1); + MapNode *n2 = &vm->m_data[i2]; + if (n2->getContent() != c_dirt && + n2->getContent() != c_dirt_with_grass) // Find next mud node in column continue; + } + + // Check if node above is walkable. If so, cancel + // flowing as if node above keeps it in place. + u32 i3 = i; + VoxelArea::add_y(em, i3, 1); + MapNode *n3 = &vm->m_data[i3]; + if (ndef->get(*n3).walkable) + // Find next mud node in column + continue; + + // Drop mud on one side + for (const v3s16 &dirp : dirs4) { + u32 i2 = i; + // Move to side + VoxelArea::add_p(em, i2, dirp); + // Check that side is air + MapNode *n2 = &vm->m_data[i2]; + if (ndef->get(*n2).walkable) + continue; + + // Check that under side is air + VoxelArea::add_y(em, i2, -1); + n2 = &vm->m_data[i2]; + if (ndef->get(*n2).walkable) + continue; - // Drop mud on one side - for (const v3s16 &dirp : dirs4) { - u32 i2 = i; - // Move to side - VoxelArea::add_p(em, i2, dirp); - // Check that side is air - MapNode *n2 = &vm->m_data[i2]; - if (ndef->get(*n2).walkable) - continue; - - // Check that under side is air + // Loop further down until not air + s16 y2 = y - 1; // y of i2 + bool dropped_to_unknown = false; + do { + y2--; VoxelArea::add_y(em, i2, -1); n2 = &vm->m_data[i2]; - if (ndef->get(*n2).walkable) - continue; - - // Loop further down until not air - s16 y2 = y - 1; // y of i2 - bool dropped_to_unknown = false; - do { - y2--; - VoxelArea::add_y(em, i2, - -1); - n2 = &vm->m_data[i2]; - // If out of area or in - // ungenerated world - if (y2 < full_node_min.Y || - n2->getContent() == - CONTENT_IGNORE) { - dropped_to_unknown = - true; - break; - } - } while (!ndef->get(*n2).walkable); - - if (!dropped_to_unknown) { - // Move up one so that - // we're in air - VoxelArea::add_y(em, i2, - 1); - // Move mud to new place, - // and if outside mapchunk - // remove any decorations - // above removed or placed - // mud. - moveMud(i, i2, i3, p2d, - em); + // If out of area or in ungenerated world + if (y2 < full_node_min.Y || n2->getContent() == CONTENT_IGNORE) { + dropped_to_unknown = true; + break; } - // Done, find next mud node in - // column - break; + } while (!ndef->get(*n2).walkable); + + if (!dropped_to_unknown) { + // Move up one so that we're in air + VoxelArea::add_y(em, i2, 1); + // Move mud to new place, and if outside mapchunk remove + // any decorations above removed or placed mud. + moveMud(i, i2, i3, p2d, em); } + // Done, find next mud node in column + break; } } } + } } } -void MapgenV6::moveMud(u32 remove_index, u32 place_index, u32 above_remove_index, - v2s16 pos, v3s16 em) + +void MapgenV6::moveMud(u32 remove_index, u32 place_index, + u32 above_remove_index, v2s16 pos, v3s16 em) { MapNode n_air(CONTENT_AIR); // Copy mud from old place to new place @@ -916,20 +919,17 @@ void MapgenV6::moveMud(u32 remove_index, u32 place_index, u32 above_remove_index // Outside the mapchunk decorations may need to be removed if above removed // mud or if half-buried in placed mud. Placed mud is to the side of pos so // use 'pos.X >= node_max.X' etc. - if (pos.X >= node_max.X || pos.X <= node_min.X || pos.Y >= node_max.Z || - pos.Y <= node_min.Z) { + if (pos.X >= node_max.X || pos.X <= node_min.X || + pos.Y >= node_max.Z || pos.Y <= node_min.Z) { // 'above remove' node is above removed mud. If it is not air, water or // 'ignore' it is a decoration that needs removing. Also search upwards // to remove a possible stacked decoration. // Check for 'ignore' because stacked decorations can penetrate into // 'ignore' nodes above the mapchunk. while (vm->m_area.contains(above_remove_index) && - vm->m_data[above_remove_index].getContent() != - CONTENT_AIR && - vm->m_data[above_remove_index].getContent() != - c_water_source && - vm->m_data[above_remove_index].getContent() != - CONTENT_IGNORE) { + vm->m_data[above_remove_index].getContent() != CONTENT_AIR && + vm->m_data[above_remove_index].getContent() != c_water_source && + vm->m_data[above_remove_index].getContent() != CONTENT_IGNORE) { vm->m_data[above_remove_index] = n_air; VoxelArea::add_y(em, above_remove_index, 1); } @@ -946,9 +946,10 @@ void MapgenV6::moveMud(u32 remove_index, u32 place_index, u32 above_remove_index } } + void MapgenV6::placeTreesAndJungleGrass() { - // TimeTaker t("placeTrees"); + //TimeTaker t("placeTrees"); if (node_max.Y < water_level) return; @@ -968,96 +969,98 @@ void MapgenV6::placeTreesAndJungleGrass() // N.B. We must add jungle grass first, since tree leaves will // obstruct the ground, giving us a false ground level for (s16 z0 = 0; z0 < div; z0++) - for (s16 x0 = 0; x0 < div; x0++) { - // Center position of part of division - v2s16 p2d_center(node_min.X + sidelen / 2 + sidelen * x0, - node_min.Z + sidelen / 2 + sidelen * z0); - // Minimum edge of part of division - v2s16 p2d_min(node_min.X + sidelen * x0, - node_min.Z + sidelen * z0); - // Maximum edge of part of division - v2s16 p2d_max(node_min.X + sidelen + sidelen * x0 - 1, - node_min.Z + sidelen + sidelen * z0 - 1); - - // Get biome at center position of part of division - BiomeV6Type bt = getBiome(p2d_center); - - // Amount of trees - u32 tree_count; - if (bt == BT_JUNGLE || bt == BT_TAIGA || bt == BT_NORMAL) { - tree_count = area * getTreeAmount(p2d_center); - if (bt == BT_JUNGLE) - tree_count *= 4; - } else { - tree_count = 0; - } + for (s16 x0 = 0; x0 < div; x0++) { + // Center position of part of division + v2s16 p2d_center( + node_min.X + sidelen / 2 + sidelen * x0, + node_min.Z + sidelen / 2 + sidelen * z0 + ); + // Minimum edge of part of division + v2s16 p2d_min( + node_min.X + sidelen * x0, + node_min.Z + sidelen * z0 + ); + // Maximum edge of part of division + v2s16 p2d_max( + node_min.X + sidelen + sidelen * x0 - 1, + node_min.Z + sidelen + sidelen * z0 - 1 + ); + + // Get biome at center position of part of division + BiomeV6Type bt = getBiome(p2d_center); + + // Amount of trees + u32 tree_count; + if (bt == BT_JUNGLE || bt == BT_TAIGA || bt == BT_NORMAL) { + tree_count = area * getTreeAmount(p2d_center); + if (bt == BT_JUNGLE) + tree_count *= 4; + } else { + tree_count = 0; + } - // Add jungle grass - if (bt == BT_JUNGLE) { - float humidity = getHumidity(p2d_center); - u32 grass_count = 5 * humidity * tree_count; - for (u32 i = 0; i < grass_count; i++) { - s16 x = grassrandom.range(p2d_min.X, p2d_max.X); - s16 z = grassrandom.range(p2d_min.Y, p2d_max.Y); - int mapindex = central_area_size.X * - (z - node_min.Z) + - (x - node_min.X); - s16 y = heightmap[mapindex]; - if (y < water_level) - continue; + // Add jungle grass + if (bt == BT_JUNGLE) { + float humidity = getHumidity(p2d_center); + u32 grass_count = 5 * humidity * tree_count; + for (u32 i = 0; i < grass_count; i++) { + s16 x = grassrandom.range(p2d_min.X, p2d_max.X); + s16 z = grassrandom.range(p2d_min.Y, p2d_max.Y); + int mapindex = central_area_size.X * (z - node_min.Z) + + (x - node_min.X); + s16 y = heightmap[mapindex]; + if (y < water_level) + continue; - u32 vi = vm->m_area.index(x, y, z); - // place on dirt_with_grass, since we know it is - // exposed to sunlight - if (vm->m_data[vi].getContent() == - c_dirt_with_grass) { - VoxelArea::add_y(em, vi, 1); - vm->m_data[vi] = n_junglegrass; - } + u32 vi = vm->m_area.index(x, y, z); + // place on dirt_with_grass, since we know it is exposed to sunlight + if (vm->m_data[vi].getContent() == c_dirt_with_grass) { + VoxelArea::add_y(em, vi, 1); + vm->m_data[vi] = n_junglegrass; } } + } - // Put trees in random places on part of division - for (u32 i = 0; i < tree_count; i++) { - s16 x = myrand_range(p2d_min.X, p2d_max.X); - s16 z = myrand_range(p2d_min.Y, p2d_max.Y); - int mapindex = central_area_size.X * (z - node_min.Z) + - (x - node_min.X); - s16 y = heightmap[mapindex]; - // Don't make a tree under water level - // Don't make a tree so high that it doesn't fit - if (y < water_level || y > node_max.Y - 6) + // Put trees in random places on part of division + for (u32 i = 0; i < tree_count; i++) { + s16 x = myrand_range(p2d_min.X, p2d_max.X); + s16 z = myrand_range(p2d_min.Y, p2d_max.Y); + int mapindex = central_area_size.X * (z - node_min.Z) + + (x - node_min.X); + s16 y = heightmap[mapindex]; + // Don't make a tree under water level + // Don't make a tree so high that it doesn't fit + if (y < water_level || y > node_max.Y - 6) + continue; + + v3s16 p(x, y, z); + // Trees grow only on mud and grass + { + u32 i = vm->m_area.index(p); + content_t c = vm->m_data[i].getContent(); + if (c != c_dirt && + c != c_dirt_with_grass && + c != c_dirt_with_snow) continue; + } + p.Y++; - v3s16 p(x, y, z); - // Trees grow only on mud and grass - { - u32 i = vm->m_area.index(p); - content_t c = vm->m_data[i].getContent(); - if (c != c_dirt && c != c_dirt_with_grass && - c != c_dirt_with_snow) - continue; - } - p.Y++; - - // Make a tree - if (bt == BT_JUNGLE) { - treegen::make_jungletree(*vm, p, ndef, myrand()); - } else if (bt == BT_TAIGA) { - treegen::make_pine_tree(*vm, p - v3s16(0, 1, 0), - ndef, myrand()); - } else if (bt == BT_NORMAL) { - bool is_apple_tree = - (myrand_range(0, 3) == 0) && + // Make a tree + if (bt == BT_JUNGLE) { + treegen::make_jungletree(*vm, p, ndef, myrand()); + } else if (bt == BT_TAIGA) { + treegen::make_pine_tree(*vm, p - v3s16(0, 1, 0), ndef, myrand()); + } else if (bt == BT_NORMAL) { + bool is_apple_tree = (myrand_range(0, 3) == 0) && getHaveAppleTree(v2s16(x, z)); - treegen::make_tree(*vm, p, is_apple_tree, ndef, - myrand()); - } + treegen::make_tree(*vm, p, is_apple_tree, ndef, myrand()); } } - // printf("placeTreesAndJungleGrass: %dms\n", t.stop()); + } + //printf("placeTreesAndJungleGrass: %dms\n", t.stop()); } + void MapgenV6::growGrass() // Add surface nodes { MapNode n_dirt_with_grass(c_dirt_with_grass); @@ -1068,54 +1071,53 @@ void MapgenV6::growGrass() // Add surface nodes u32 index = 0; for (s16 z = full_node_min.Z; z <= full_node_max.Z; z++) - for (s16 x = full_node_min.X; x <= full_node_max.X; x++, index++) { - // Find the lowest surface to which enough light ends up to make - // grass grow. Basically just wait until not air and not leaves. - s16 surface_y = 0; - { - u32 i = vm->m_area.index(x, node_max.Y, z); - s16 y; - // Go to ground level - for (y = node_max.Y; y >= full_node_min.Y; y--) { - MapNode &n = vm->m_data[i]; - if (ndef->get(n).param_type != CPT_LIGHT || - ndef->get(n).liquid_type != - LIQUID_NONE || - n.getContent() == c_ice) - break; - VoxelArea::add_y(em, i, -1); - } - surface_y = (y >= full_node_min.Y) ? y : full_node_min.Y; + for (s16 x = full_node_min.X; x <= full_node_max.X; x++, index++) { + // Find the lowest surface to which enough light ends up to make + // grass grow. Basically just wait until not air and not leaves. + s16 surface_y = 0; + { + u32 i = vm->m_area.index(x, node_max.Y, z); + s16 y; + // Go to ground level + for (y = node_max.Y; y >= full_node_min.Y; y--) { + MapNode &n = vm->m_data[i]; + if (ndef->get(n).param_type != CPT_LIGHT || + ndef->get(n).liquid_type != LIQUID_NONE || + n.getContent() == c_ice) + break; + VoxelArea::add_y(em, i, -1); } + surface_y = (y >= full_node_min.Y) ? y : full_node_min.Y; + } - BiomeV6Type bt = getBiome(index, v2s16(x, z)); - u32 i = vm->m_area.index(x, surface_y, z); - content_t c = vm->m_data[i].getContent(); - if (surface_y >= water_level - 20) { - if (bt == BT_TAIGA && c == c_dirt) { + BiomeV6Type bt = getBiome(index, v2s16(x, z)); + u32 i = vm->m_area.index(x, surface_y, z); + content_t c = vm->m_data[i].getContent(); + if (surface_y >= water_level - 20) { + if (bt == BT_TAIGA && c == c_dirt) { + vm->m_data[i] = n_dirt_with_snow; + } else if (bt == BT_TUNDRA) { + if (c == c_dirt) { + vm->m_data[i] = n_snowblock; + VoxelArea::add_y(em, i, -1); vm->m_data[i] = n_dirt_with_snow; - } else if (bt == BT_TUNDRA) { - if (c == c_dirt) { - vm->m_data[i] = n_snowblock; - VoxelArea::add_y(em, i, -1); - vm->m_data[i] = n_dirt_with_snow; - } else if (c == c_stone && - surface_y < node_max.Y) { - VoxelArea::add_y(em, i, 1); - vm->m_data[i] = n_snowblock; - } - } else if (c == c_dirt) { - vm->m_data[i] = n_dirt_with_grass; + } else if (c == c_stone && surface_y < node_max.Y) { + VoxelArea::add_y(em, i, 1); + vm->m_data[i] = n_snowblock; } + } else if (c == c_dirt) { + vm->m_data[i] = n_dirt_with_grass; } } + } } + void MapgenV6::generateCaves(int max_stone_y) { float cave_amount = NoisePerlin2D(np_cave, node_min.X, node_min.Y, seed); - int volume_nodes = (node_max.X - node_min.X + 1) * (node_max.Y - node_min.Y + 1) * - MAP_BLOCKSIZE; + int volume_nodes = (node_max.X - node_min.X + 1) * + (node_max.Y - node_min.Y + 1) * MAP_BLOCKSIZE; cave_amount = MYMAX(0.0, cave_amount); u32 caves_count = cave_amount * volume_nodes / 50000; u32 bruises_count = 1; @@ -1126,16 +1128,15 @@ void MapgenV6::generateCaves(int max_stone_y) bruises_count = ps.range(0, ps.range(0, 2)); if (getBiome(v2s16(node_min.X, node_min.Z)) == BT_DESERT) { - caves_count /= 3; + caves_count /= 3; bruises_count /= 3; } for (u32 i = 0; i < caves_count + bruises_count; i++) { - CavesV6 cave(ndef, &gennotify, water_level, c_water_source, - c_lava_source); + CavesV6 cave(ndef, &gennotify, water_level, c_water_source, c_lava_source); bool large_cave = (i >= caves_count); - cave.makeCave(vm, node_min, node_max, &ps, &ps2, large_cave, max_stone_y, - heightmap); + cave.makeCave(vm, node_min, node_max, &ps, &ps2, + large_cave, max_stone_y, heightmap); } } diff --git a/src/mapgen/mapgen_v6.h b/src/mapgen/mapgen_v6.h index a0abbb010..ff565edec 100644 --- a/src/mapgen/mapgen_v6.h +++ b/src/mapgen/mapgen_v6.h @@ -33,15 +33,17 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MGV6_FREQ_JUNGLE 0.5 //////////// Mapgen V6 flags -#define MGV6_JUNGLES 0x01 +#define MGV6_JUNGLES 0x01 #define MGV6_BIOMEBLEND 0x02 -#define MGV6_MUDFLOW 0x04 +#define MGV6_MUDFLOW 0x04 #define MGV6_SNOWBIOMES 0x08 -#define MGV6_FLAT 0x10 -#define MGV6_TREES 0x20 +#define MGV6_FLAT 0x10 +#define MGV6_TREES 0x20 + extern FlagDesc flagdesc_mapgen_v6[]; + enum BiomeV6Type { BT_NORMAL, @@ -51,8 +53,8 @@ enum BiomeV6Type BT_TAIGA, }; -struct MapgenV6Params : public MapgenParams -{ + +struct MapgenV6Params : public MapgenParams { float freq_desert = 0.45f; float freq_beach = 0.15f; s16 dungeon_ymin = -31000; @@ -78,8 +80,8 @@ struct MapgenV6Params : public MapgenParams void setDefaultSettings(Settings *settings); }; -class MapgenV6 : public Mapgen -{ + +class MapgenV6 : public Mapgen { public: EmergeParams *m_emerge; @@ -140,8 +142,8 @@ class MapgenV6 : public Mapgen int getGroundLevelAtPoint(v2s16 p); int getSpawnLevelAtPoint(v2s16 p); - float baseTerrainLevel(float terrain_base, float terrain_higher, float steepness, - float height_select); + float baseTerrainLevel(float terrain_base, float terrain_higher, + float steepness, float height_select); virtual float baseTerrainLevelFromNoise(v2s16 p); virtual float baseTerrainLevelFromMap(v2s16 p); virtual float baseTerrainLevelFromMap(int index); @@ -166,8 +168,8 @@ class MapgenV6 : public Mapgen int generateGround(); void addMud(); void flowMud(s16 &mudflow_minpos, s16 &mudflow_maxpos); - void moveMud(u32 remove_index, u32 place_index, u32 above_remove_index, v2s16 pos, - v3s16 em); + void moveMud(u32 remove_index, u32 place_index, + u32 above_remove_index, v2s16 pos, v3s16 em); void growGrass(); void placeTreesAndJungleGrass(); virtual void generateCaves(int max_stone_y); diff --git a/src/mapgen/mapgen_v7.cpp b/src/mapgen/mapgen_v7.cpp index c1ce55348..e93dc9140 100644 --- a/src/mapgen/mapgen_v7.cpp +++ b/src/mapgen/mapgen_v7.cpp @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "mapgen.h" #include #include "voxel.h" @@ -37,80 +38,92 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_decoration.h" #include "mapgen_v7.h" -FlagDesc flagdesc_mapgen_v7[] = {{"mountains", MGV7_MOUNTAINS}, {"ridges", MGV7_RIDGES}, - {"floatlands", MGV7_FLOATLANDS}, {"caverns", MGV7_CAVERNS}, {NULL, 0}}; + +FlagDesc flagdesc_mapgen_v7[] = { + {"mountains", MGV7_MOUNTAINS}, + {"ridges", MGV7_RIDGES}, + {"floatlands", MGV7_FLOATLANDS}, + {"caverns", MGV7_CAVERNS}, + {NULL, 0} +}; + //////////////////////////////////////////////////////////////////////////////// -MapgenV7::MapgenV7(MapgenV7Params *params, EmergeParams *emerge) : - MapgenBasic(MAPGEN_V7, params, emerge) + +MapgenV7::MapgenV7(MapgenV7Params *params, EmergeParams *emerge) + : MapgenBasic(MAPGEN_V7, params, emerge) { - spflags = params->spflags; - mount_zero_level = params->mount_zero_level; - floatland_ymin = params->floatland_ymin; - floatland_ymax = params->floatland_ymax; - floatland_taper = params->floatland_taper; - float_taper_exp = params->float_taper_exp; - floatland_density = params->floatland_density; - floatland_ywater = params->floatland_ywater; - - cave_width = params->cave_width; - large_cave_depth = params->large_cave_depth; + spflags = params->spflags; + mount_zero_level = params->mount_zero_level; + floatland_ymin = params->floatland_ymin; + floatland_ymax = params->floatland_ymax; + floatland_taper = params->floatland_taper; + float_taper_exp = params->float_taper_exp; + floatland_density = params->floatland_density; + floatland_ywater = params->floatland_ywater; + + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; small_cave_num_min = params->small_cave_num_min; small_cave_num_max = params->small_cave_num_max; large_cave_num_min = params->large_cave_num_min; large_cave_num_max = params->large_cave_num_max; large_cave_flooded = params->large_cave_flooded; - cavern_limit = params->cavern_limit; - cavern_taper = params->cavern_taper; - cavern_threshold = params->cavern_threshold; - dungeon_ymin = params->dungeon_ymin; - dungeon_ymax = params->dungeon_ymax; + cavern_limit = params->cavern_limit; + cavern_taper = params->cavern_taper; + cavern_threshold = params->cavern_threshold; + dungeon_ymin = params->dungeon_ymin; + dungeon_ymax = params->dungeon_ymax; // Allocate floatland noise offset cache this->float_offset_cache = new float[csize.Y + 2]; // 2D noise - noise_terrain_base = new Noise(¶ms->np_terrain_base, seed, csize.X, csize.Z); - noise_terrain_alt = new Noise(¶ms->np_terrain_alt, seed, csize.X, csize.Z); + noise_terrain_base = + new Noise(¶ms->np_terrain_base, seed, csize.X, csize.Z); + noise_terrain_alt = + new Noise(¶ms->np_terrain_alt, seed, csize.X, csize.Z); noise_terrain_persist = - new Noise(¶ms->np_terrain_persist, seed, csize.X, csize.Z); + new Noise(¶ms->np_terrain_persist, seed, csize.X, csize.Z); noise_height_select = - new Noise(¶ms->np_height_select, seed, csize.X, csize.Z); - noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); + new Noise(¶ms->np_height_select, seed, csize.X, csize.Z); + noise_filler_depth = + new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); if (spflags & MGV7_MOUNTAINS) { // 2D noise - noise_mount_height = new Noise( - ¶ms->np_mount_height, seed, csize.X, csize.Z); + noise_mount_height = + new Noise(¶ms->np_mount_height, seed, csize.X, csize.Z); // 3D noise, 1 up, 1 down overgeneration - noise_mountain = new Noise(¶ms->np_mountain, seed, csize.X, - csize.Y + 2, csize.Z); + noise_mountain = + new Noise(¶ms->np_mountain, seed, csize.X, csize.Y + 2, csize.Z); } if (spflags & MGV7_RIDGES) { // 2D noise - noise_ridge_uwater = new Noise( - ¶ms->np_ridge_uwater, seed, csize.X, csize.Z); + noise_ridge_uwater = + new Noise(¶ms->np_ridge_uwater, seed, csize.X, csize.Z); // 3D noise, 1 up, 1 down overgeneration - noise_ridge = new Noise( - ¶ms->np_ridge, seed, csize.X, csize.Y + 2, csize.Z); + noise_ridge = + new Noise(¶ms->np_ridge, seed, csize.X, csize.Y + 2, csize.Z); } if (spflags & MGV7_FLOATLANDS) { // 3D noise, 1 up, 1 down overgeneration - noise_floatland = new Noise(¶ms->np_floatland, seed, csize.X, - csize.Y + 2, csize.Z); + noise_floatland = + new Noise(¶ms->np_floatland, seed, csize.X, csize.Y + 2, csize.Z); } // 3D noise, 1 down overgeneration - MapgenBasic::np_cave1 = params->np_cave1; - MapgenBasic::np_cave2 = params->np_cave2; - MapgenBasic::np_cavern = params->np_cavern; + MapgenBasic::np_cave1 = params->np_cave1; + MapgenBasic::np_cave2 = params->np_cave2; + MapgenBasic::np_cavern = params->np_cavern; // 3D noise MapgenBasic::np_dungeons = params->np_dungeons; } + MapgenV7::~MapgenV7() { delete noise_terrain_base; @@ -133,122 +146,128 @@ MapgenV7::~MapgenV7() delete noise_floatland; } - delete[] float_offset_cache; + delete []float_offset_cache; } -MapgenV7Params::MapgenV7Params() : - np_terrain_base(4.0, 70.0, v3f(600, 600, 600), 82341, 5, 0.6, 2.0), - np_terrain_alt(4.0, 25.0, v3f(600, 600, 600), 5934, 5, 0.6, 2.0), - np_terrain_persist(0.6, 0.1, v3f(2000, 2000, 2000), 539, 3, 0.6, 2.0), - np_height_select(-8.0, 16.0, v3f(500, 500, 500), 4213, 6, 0.7, 2.0), - np_filler_depth(0.0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), - np_mount_height(256.0, 112.0, v3f(1000, 1000, 1000), 72449, 3, 0.6, 2.0), - np_ridge_uwater(0.0, 1.0, v3f(1000, 1000, 1000), 85039, 5, 0.6, 2.0), - np_mountain(-0.6, 1.0, v3f(250, 350, 250), 5333, 5, 0.63, 2.0), - np_ridge(0.0, 1.0, v3f(100, 100, 100), 6467, 4, 0.75, 2.0), - np_floatland(0.0, 0.7, v3f(384, 96, 384), 1009, 4, 0.75, 1.618), - np_cavern(0.0, 1.0, v3f(384, 128, 384), 723, 5, 0.63, 2.0), - np_cave1(0.0, 12.0, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), - np_cave2(0.0, 12.0, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), - np_dungeons(0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) + +MapgenV7Params::MapgenV7Params(): + np_terrain_base (4.0, 70.0, v3f(600, 600, 600), 82341, 5, 0.6, 2.0), + np_terrain_alt (4.0, 25.0, v3f(600, 600, 600), 5934, 5, 0.6, 2.0), + np_terrain_persist (0.6, 0.1, v3f(2000, 2000, 2000), 539, 3, 0.6, 2.0), + np_height_select (-8.0, 16.0, v3f(500, 500, 500), 4213, 6, 0.7, 2.0), + np_filler_depth (0.0, 1.2, v3f(150, 150, 150), 261, 3, 0.7, 2.0), + np_mount_height (256.0, 112.0, v3f(1000, 1000, 1000), 72449, 3, 0.6, 2.0), + np_ridge_uwater (0.0, 1.0, v3f(1000, 1000, 1000), 85039, 5, 0.6, 2.0), + np_mountain (-0.6, 1.0, v3f(250, 350, 250), 5333, 5, 0.63, 2.0), + np_ridge (0.0, 1.0, v3f(100, 100, 100), 6467, 4, 0.75, 2.0), + np_floatland (0.0, 0.7, v3f(384, 96, 384), 1009, 4, 0.75, 1.618), + np_cavern (0.0, 1.0, v3f(384, 128, 384), 723, 5, 0.63, 2.0), + np_cave1 (0.0, 12.0, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), + np_cave2 (0.0, 12.0, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), + np_dungeons (0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) { } + void MapgenV7Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv7_spflags", spflags, flagdesc_mapgen_v7); - settings->getS16NoEx("mgv7_mount_zero_level", mount_zero_level); - settings->getS16NoEx("mgv7_floatland_ymin", floatland_ymin); - settings->getS16NoEx("mgv7_floatland_ymax", floatland_ymax); - settings->getS16NoEx("mgv7_floatland_taper", floatland_taper); - settings->getFloatNoEx("mgv7_float_taper_exp", float_taper_exp); - settings->getFloatNoEx("mgv7_floatland_density", floatland_density); - settings->getS16NoEx("mgv7_floatland_ywater", floatland_ywater); - - settings->getFloatNoEx("mgv7_cave_width", cave_width); - settings->getS16NoEx("mgv7_large_cave_depth", large_cave_depth); - settings->getU16NoEx("mgv7_small_cave_num_min", small_cave_num_min); - settings->getU16NoEx("mgv7_small_cave_num_max", small_cave_num_max); - settings->getU16NoEx("mgv7_large_cave_num_min", large_cave_num_min); - settings->getU16NoEx("mgv7_large_cave_num_max", large_cave_num_max); - settings->getFloatNoEx("mgv7_large_cave_flooded", large_cave_flooded); - settings->getS16NoEx("mgv7_cavern_limit", cavern_limit); - settings->getS16NoEx("mgv7_cavern_taper", cavern_taper); - settings->getFloatNoEx("mgv7_cavern_threshold", cavern_threshold); - settings->getS16NoEx("mgv7_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgv7_dungeon_ymax", dungeon_ymax); - - settings->getNoiseParams("mgv7_np_terrain_base", np_terrain_base); - settings->getNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); + settings->getS16NoEx("mgv7_mount_zero_level", mount_zero_level); + settings->getS16NoEx("mgv7_floatland_ymin", floatland_ymin); + settings->getS16NoEx("mgv7_floatland_ymax", floatland_ymax); + settings->getS16NoEx("mgv7_floatland_taper", floatland_taper); + settings->getFloatNoEx("mgv7_float_taper_exp", float_taper_exp); + settings->getFloatNoEx("mgv7_floatland_density", floatland_density); + settings->getS16NoEx("mgv7_floatland_ywater", floatland_ywater); + + settings->getFloatNoEx("mgv7_cave_width", cave_width); + settings->getS16NoEx("mgv7_large_cave_depth", large_cave_depth); + settings->getU16NoEx("mgv7_small_cave_num_min", small_cave_num_min); + settings->getU16NoEx("mgv7_small_cave_num_max", small_cave_num_max); + settings->getU16NoEx("mgv7_large_cave_num_min", large_cave_num_min); + settings->getU16NoEx("mgv7_large_cave_num_max", large_cave_num_max); + settings->getFloatNoEx("mgv7_large_cave_flooded", large_cave_flooded); + settings->getS16NoEx("mgv7_cavern_limit", cavern_limit); + settings->getS16NoEx("mgv7_cavern_taper", cavern_taper); + settings->getFloatNoEx("mgv7_cavern_threshold", cavern_threshold); + settings->getS16NoEx("mgv7_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgv7_dungeon_ymax", dungeon_ymax); + + settings->getNoiseParams("mgv7_np_terrain_base", np_terrain_base); + settings->getNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); settings->getNoiseParams("mgv7_np_terrain_persist", np_terrain_persist); - settings->getNoiseParams("mgv7_np_height_select", np_height_select); - settings->getNoiseParams("mgv7_np_filler_depth", np_filler_depth); - settings->getNoiseParams("mgv7_np_mount_height", np_mount_height); - settings->getNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); - settings->getNoiseParams("mgv7_np_mountain", np_mountain); - settings->getNoiseParams("mgv7_np_ridge", np_ridge); - settings->getNoiseParams("mgv7_np_floatland", np_floatland); - settings->getNoiseParams("mgv7_np_cavern", np_cavern); - settings->getNoiseParams("mgv7_np_cave1", np_cave1); - settings->getNoiseParams("mgv7_np_cave2", np_cave2); - settings->getNoiseParams("mgv7_np_dungeons", np_dungeons); + settings->getNoiseParams("mgv7_np_height_select", np_height_select); + settings->getNoiseParams("mgv7_np_filler_depth", np_filler_depth); + settings->getNoiseParams("mgv7_np_mount_height", np_mount_height); + settings->getNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); + settings->getNoiseParams("mgv7_np_mountain", np_mountain); + settings->getNoiseParams("mgv7_np_ridge", np_ridge); + settings->getNoiseParams("mgv7_np_floatland", np_floatland); + settings->getNoiseParams("mgv7_np_cavern", np_cavern); + settings->getNoiseParams("mgv7_np_cave1", np_cave1); + settings->getNoiseParams("mgv7_np_cave2", np_cave2); + settings->getNoiseParams("mgv7_np_dungeons", np_dungeons); } + void MapgenV7Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv7_spflags", spflags, flagdesc_mapgen_v7); - settings->setS16("mgv7_mount_zero_level", mount_zero_level); - settings->setS16("mgv7_floatland_ymin", floatland_ymin); - settings->setS16("mgv7_floatland_ymax", floatland_ymax); - settings->setS16("mgv7_floatland_taper", floatland_taper); - settings->setFloat("mgv7_float_taper_exp", float_taper_exp); - settings->setFloat("mgv7_floatland_density", floatland_density); - settings->setS16("mgv7_floatland_ywater", floatland_ywater); - - settings->setFloat("mgv7_cave_width", cave_width); - settings->setS16("mgv7_large_cave_depth", large_cave_depth); - settings->setU16("mgv7_small_cave_num_min", small_cave_num_min); - settings->setU16("mgv7_small_cave_num_max", small_cave_num_max); - settings->setU16("mgv7_large_cave_num_min", large_cave_num_min); - settings->setU16("mgv7_large_cave_num_max", large_cave_num_max); - settings->setFloat("mgv7_large_cave_flooded", large_cave_flooded); - settings->setS16("mgv7_cavern_limit", cavern_limit); - settings->setS16("mgv7_cavern_taper", cavern_taper); - settings->setFloat("mgv7_cavern_threshold", cavern_threshold); - settings->setS16("mgv7_dungeon_ymin", dungeon_ymin); - settings->setS16("mgv7_dungeon_ymax", dungeon_ymax); - - settings->setNoiseParams("mgv7_np_terrain_base", np_terrain_base); - settings->setNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); + settings->setS16("mgv7_mount_zero_level", mount_zero_level); + settings->setS16("mgv7_floatland_ymin", floatland_ymin); + settings->setS16("mgv7_floatland_ymax", floatland_ymax); + settings->setS16("mgv7_floatland_taper", floatland_taper); + settings->setFloat("mgv7_float_taper_exp", float_taper_exp); + settings->setFloat("mgv7_floatland_density", floatland_density); + settings->setS16("mgv7_floatland_ywater", floatland_ywater); + + settings->setFloat("mgv7_cave_width", cave_width); + settings->setS16("mgv7_large_cave_depth", large_cave_depth); + settings->setU16("mgv7_small_cave_num_min", small_cave_num_min); + settings->setU16("mgv7_small_cave_num_max", small_cave_num_max); + settings->setU16("mgv7_large_cave_num_min", large_cave_num_min); + settings->setU16("mgv7_large_cave_num_max", large_cave_num_max); + settings->setFloat("mgv7_large_cave_flooded", large_cave_flooded); + settings->setS16("mgv7_cavern_limit", cavern_limit); + settings->setS16("mgv7_cavern_taper", cavern_taper); + settings->setFloat("mgv7_cavern_threshold", cavern_threshold); + settings->setS16("mgv7_dungeon_ymin", dungeon_ymin); + settings->setS16("mgv7_dungeon_ymax", dungeon_ymax); + + settings->setNoiseParams("mgv7_np_terrain_base", np_terrain_base); + settings->setNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); settings->setNoiseParams("mgv7_np_terrain_persist", np_terrain_persist); - settings->setNoiseParams("mgv7_np_height_select", np_height_select); - settings->setNoiseParams("mgv7_np_filler_depth", np_filler_depth); - settings->setNoiseParams("mgv7_np_mount_height", np_mount_height); - settings->setNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); - settings->setNoiseParams("mgv7_np_mountain", np_mountain); - settings->setNoiseParams("mgv7_np_ridge", np_ridge); - settings->setNoiseParams("mgv7_np_floatland", np_floatland); - settings->setNoiseParams("mgv7_np_cavern", np_cavern); - settings->setNoiseParams("mgv7_np_cave1", np_cave1); - settings->setNoiseParams("mgv7_np_cave2", np_cave2); - settings->setNoiseParams("mgv7_np_dungeons", np_dungeons); + settings->setNoiseParams("mgv7_np_height_select", np_height_select); + settings->setNoiseParams("mgv7_np_filler_depth", np_filler_depth); + settings->setNoiseParams("mgv7_np_mount_height", np_mount_height); + settings->setNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); + settings->setNoiseParams("mgv7_np_mountain", np_mountain); + settings->setNoiseParams("mgv7_np_ridge", np_ridge); + settings->setNoiseParams("mgv7_np_floatland", np_floatland); + settings->setNoiseParams("mgv7_np_cavern", np_cavern); + settings->setNoiseParams("mgv7_np_cave1", np_cave1); + settings->setNoiseParams("mgv7_np_cave2", np_cave2); + settings->setNoiseParams("mgv7_np_dungeons", np_dungeons); } + void MapgenV7Params::setDefaultSettings(Settings *settings) { settings->setDefault("mgv7_spflags", flagdesc_mapgen_v7, - MGV7_MOUNTAINS | MGV7_RIDGES | MGV7_CAVERNS); + MGV7_MOUNTAINS | MGV7_RIDGES | MGV7_CAVERNS); } + //////////////////////////////////////////////////////////////////////////////// + int MapgenV7::getSpawnLevelAtPoint(v2s16 p) { // If rivers are enabled, first check if in a river if (spflags & MGV7_RIDGES) { float width = 0.2f; float uwatern = NoisePerlin2D(&noise_ridge_uwater->np, p.X, p.Y, seed) * - 2.0f; + 2.0f; if (std::fabs(uwatern) <= width) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } @@ -259,7 +278,7 @@ int MapgenV7::getSpawnLevelAtPoint(v2s16 p) // Raising the maximum spawn level above 'water_level + 16' is necessary // for when terrain 'offset's are set much higher than water_level. s16 max_spawn_y = std::fmax(std::fmax(noise_terrain_alt->np.offset, - noise_terrain_base->np.offset), + noise_terrain_base->np.offset), water_level + 16); // Base terrain calculation s16 y = baseTerrainLevelAtPoint(p.X, p.Y); @@ -292,19 +311,20 @@ int MapgenV7::getSpawnLevelAtPoint(v2s16 p) return MAX_MAP_GENERATION_LIMIT; } + void MapgenV7::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); - // TimeTaker t("makeChunk"); + //TimeTaker t("makeChunk"); this->generating = true; this->vm = data->vmanip; @@ -350,8 +370,8 @@ void MapgenV7::makeChunk(BlockMakeData *data) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. - generateCavesRandomWalk( - stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); + generateCavesRandomWalk(stone_surface_max_y, + -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } @@ -377,20 +397,21 @@ void MapgenV7::makeChunk(BlockMakeData *data) // Calculate lighting // Limit floatland shadows bool propagate_shadow = !((spflags & MGV7_FLOATLANDS) && - node_max.Y >= floatland_ymin - csize.Y * 2 && - node_min.Y <= floatland_ymax); + node_max.Y >= floatland_ymin - csize.Y * 2 && node_min.Y <= floatland_ymax); if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), - full_node_min, full_node_max, propagate_shadow); + full_node_min, full_node_max, propagate_shadow); this->generating = false; - // printf("makeChunk: %lums\n", t.stop()); + //printf("makeChunk: %lums\n", t.stop()); } + //////////////////////////////////////////////////////////////////////////////// + float MapgenV7::baseTerrainLevelAtPoint(s16 x, s16 z) { float hselect = NoisePerlin2D(&noise_height_select->np, x, z, seed); @@ -410,6 +431,7 @@ float MapgenV7::baseTerrainLevelAtPoint(s16 x, s16 z) return (height_base * hselect) + (height_alt * (1.0f - hselect)); } + float MapgenV7::baseTerrainLevelFromMap(int index) { float hselect = rangelim(noise_height_select->result[index], 0.0f, 1.0f); @@ -422,16 +444,18 @@ float MapgenV7::baseTerrainLevelFromMap(int index) return (height_base * hselect) + (height_alt * (1.0f - hselect)); } + bool MapgenV7::getMountainTerrainAtPoint(s16 x, s16 y, s16 z) { - float mnt_h_n = std::fmax( - NoisePerlin2D(&noise_mount_height->np, x, z, seed), 1.0f); + float mnt_h_n = + std::fmax(NoisePerlin2D(&noise_mount_height->np, x, z, seed), 1.0f); float density_gradient = -((float)(y - mount_zero_level) / mnt_h_n); float mnt_n = NoisePerlin3D(&noise_mountain->np, x, y, z, seed); return mnt_n + density_gradient >= 0.0f; } + bool MapgenV7::getMountainTerrainFromMap(int idx_xyz, int idx_xz, s16 y) { float mounthn = std::fmax(noise_mount_height->result[idx_xz], 1.0f); @@ -441,12 +465,13 @@ bool MapgenV7::getMountainTerrainFromMap(int idx_xyz, int idx_xz, s16 y) return mountn + density_gradient >= 0.0f; } + bool MapgenV7::getFloatlandTerrainFromMap(int idx_xyz, float float_offset) { - return noise_floatland->result[idx_xyz] + floatland_density - float_offset >= - 0.0f; + return noise_floatland->result[idx_xyz] + floatland_density - float_offset >= 0.0f; } + int MapgenV7::generateTerrain() { MapNode n_air(CONTENT_AIR); @@ -475,8 +500,8 @@ int MapgenV7::generateTerrain() s16 float_taper_ymax = floatland_ymax - floatland_taper; s16 float_taper_ymin = floatland_ymin + floatland_taper; - if ((spflags & MGV7_FLOATLANDS) && node_max.Y >= floatland_ymin && - node_min.Y <= floatland_ymax) { + if ((spflags & MGV7_FLOATLANDS) && + node_max.Y >= floatland_ymin && node_min.Y <= floatland_ymax) { gen_floatlands = true; // Calculate noise for floatland generation noise_floatland->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); @@ -485,15 +510,11 @@ int MapgenV7::generateTerrain() for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++, cache_index++) { float float_offset = 0.0f; if (y > float_taper_ymax) { - float_offset = std::pow((y - float_taper_ymax) / - (float)floatland_taper, - float_taper_exp) * - 4.0f; + float_offset = std::pow((y - float_taper_ymax) / (float)floatland_taper, + float_taper_exp) * 4.0f; } else if (y < float_taper_ymin) { - float_offset = std::pow((float_taper_ymin - - y) / (float)floatland_taper, - float_taper_exp) * - 4.0f; + float_offset = std::pow((float_taper_ymin - y) / (float)floatland_taper, + float_taper_exp) * 4.0f; } float_offset_cache[cache_index] = float_offset; } @@ -505,51 +526,50 @@ int MapgenV7::generateTerrain() u32 index2d = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index2d++) { - s16 surface_y = baseTerrainLevelFromMap(index2d); - if (surface_y > stone_surface_max_y) - stone_surface_max_y = surface_y; - - cache_index = 0; - u32 vi = vm->m_area.index(x, node_min.Y - 1, z); - u32 index3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); - - for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++, - index3d += ystride, VoxelArea::add_y(em, vi, 1), - cache_index++) { - if (vm->m_data[vi].getContent() != CONTENT_IGNORE) - continue; - - if (y <= surface_y) { - vm->m_data[vi] = n_stone; // Base terrain - } else if ((spflags & MGV7_MOUNTAINS) && - getMountainTerrainFromMap( - index3d, index2d, y)) { - vm->m_data[vi] = n_stone; // Mountain terrain - if (y > stone_surface_max_y) - stone_surface_max_y = y; - } else if (gen_floatlands && - getFloatlandTerrainFromMap(index3d, - float_offset_cache - [cache_index])) { - vm->m_data[vi] = n_stone; // Floatland terrain - if (y > stone_surface_max_y) - stone_surface_max_y = y; - } else if (y <= water_level) { // Surface water - vm->m_data[vi] = n_water; - } else if (gen_floatlands && y >= float_taper_ymax && - y <= floatland_ywater) { - vm->m_data[vi] = n_water; // Water for solid - // floatland layer only - } else { - vm->m_data[vi] = n_air; // Air - } + for (s16 x = node_min.X; x <= node_max.X; x++, index2d++) { + s16 surface_y = baseTerrainLevelFromMap(index2d); + if (surface_y > stone_surface_max_y) + stone_surface_max_y = surface_y; + + cache_index = 0; + u32 vi = vm->m_area.index(x, node_min.Y - 1, z); + u32 index3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); + + for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; + y++, + index3d += ystride, + VoxelArea::add_y(em, vi, 1), + cache_index++) { + if (vm->m_data[vi].getContent() != CONTENT_IGNORE) + continue; + + if (y <= surface_y) { + vm->m_data[vi] = n_stone; // Base terrain + } else if ((spflags & MGV7_MOUNTAINS) && + getMountainTerrainFromMap(index3d, index2d, y)) { + vm->m_data[vi] = n_stone; // Mountain terrain + if (y > stone_surface_max_y) + stone_surface_max_y = y; + } else if (gen_floatlands && + getFloatlandTerrainFromMap(index3d, + float_offset_cache[cache_index])) { + vm->m_data[vi] = n_stone; // Floatland terrain + if (y > stone_surface_max_y) + stone_surface_max_y = y; + } else if (y <= water_level) { // Surface water + vm->m_data[vi] = n_water; + } else if (gen_floatlands && y >= float_taper_ymax && y <= floatland_ywater) { + vm->m_data[vi] = n_water; // Water for solid floatland layer only + } else { + vm->m_data[vi] = n_air; // Air } } + } return stone_surface_max_y; } + void MapgenV7::generateRidgeTerrain() { if (node_max.Y < water_level - 16 || @@ -565,31 +585,28 @@ void MapgenV7::generateRidgeTerrain() float width = 0.2f; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { - u32 vi = vm->m_area.index(node_min.X, y, z); - for (s16 x = node_min.X; x <= node_max.X; x++, index3d++, vi++) { - u32 index2d = (z - node_min.Z) * csize.X + - (x - node_min.X); - float uwatern = noise_ridge_uwater->result[index2d] * - 2.0f; - if (std::fabs(uwatern) > width) - continue; - // Optimises, but also avoids removing nodes placed by - // mods in 'on-generated', when generating outside - // mapchunk. - content_t c = vm->m_data[vi].getContent(); - if (c != c_stone) - continue; - - float altitude = y - water_level; - float height_mod = (altitude + 17.0f) / 2.5f; - float width_mod = width - std::fabs(uwatern); - float nridge = noise_ridge->result[index3d] * - std::fmax(altitude, 0.0f) / 7.0f; - if (nridge + width_mod * height_mod < 0.6f) - continue; - - vm->m_data[vi] = (y > water_level) ? n_air : n_water; - } + for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { + u32 vi = vm->m_area.index(node_min.X, y, z); + for (s16 x = node_min.X; x <= node_max.X; x++, index3d++, vi++) { + u32 index2d = (z - node_min.Z) * csize.X + (x - node_min.X); + float uwatern = noise_ridge_uwater->result[index2d] * 2.0f; + if (std::fabs(uwatern) > width) + continue; + // Optimises, but also avoids removing nodes placed by mods in + // 'on-generated', when generating outside mapchunk. + content_t c = vm->m_data[vi].getContent(); + if (c != c_stone) + continue; + + float altitude = y - water_level; + float height_mod = (altitude + 17.0f) / 2.5f; + float width_mod = width - std::fabs(uwatern); + float nridge = noise_ridge->result[index3d] * + std::fmax(altitude, 0.0f) / 7.0f; + if (nridge + width_mod * height_mod < 0.6f) + continue; + + vm->m_data[vi] = (y > water_level) ? n_air : n_water; } + } } diff --git a/src/mapgen/mapgen_v7.h b/src/mapgen/mapgen_v7.h index b51ff10ce..4020cd935 100644 --- a/src/mapgen/mapgen_v7.h +++ b/src/mapgen/mapgen_v7.h @@ -23,18 +23,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen.h" ///////////// Mapgen V7 flags -#define MGV7_MOUNTAINS 0x01 -#define MGV7_RIDGES 0x02 -#define MGV7_FLOATLANDS 0x04 -#define MGV7_CAVERNS 0x08 +#define MGV7_MOUNTAINS 0x01 +#define MGV7_RIDGES 0x02 +#define MGV7_FLOATLANDS 0x04 +#define MGV7_CAVERNS 0x08 #define MGV7_BIOMEREPEAT 0x10 // Now unused class BiomeManager; extern FlagDesc flagdesc_mapgen_v7[]; -struct MapgenV7Params : public MapgenParams -{ + +struct MapgenV7Params : public MapgenParams { s16 mount_zero_level = 0; s16 floatland_ymin = 1024; s16 floatland_ymax = 4096; @@ -79,8 +79,8 @@ struct MapgenV7Params : public MapgenParams void setDefaultSettings(Settings *settings); }; -class MapgenV7 : public MapgenBasic -{ + +class MapgenV7 : public MapgenBasic { public: MapgenV7(MapgenV7Params *params, EmergeParams *emerge); ~MapgenV7(); diff --git a/src/mapgen/mapgen_valleys.cpp b/src/mapgen/mapgen_valleys.cpp index d06b05990..efcc8ee85 100644 --- a/src/mapgen/mapgen_valleys.cpp +++ b/src/mapgen/mapgen_valleys.cpp @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "mapgen.h" #include "voxel.h" #include "noise.h" @@ -43,57 +44,60 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cavegen.h" #include -FlagDesc flagdesc_mapgen_valleys[] = {{"altitude_chill", MGVALLEYS_ALT_CHILL}, - {"humid_rivers", MGVALLEYS_HUMID_RIVERS}, - {"vary_river_depth", MGVALLEYS_VARY_RIVER_DEPTH}, - {"altitude_dry", MGVALLEYS_ALT_DRY}, {NULL, 0}}; -MapgenValleys::MapgenValleys(MapgenValleysParams *params, EmergeParams *emerge) : - MapgenBasic(MAPGEN_VALLEYS, params, emerge) +FlagDesc flagdesc_mapgen_valleys[] = { + {"altitude_chill", MGVALLEYS_ALT_CHILL}, + {"humid_rivers", MGVALLEYS_HUMID_RIVERS}, + {"vary_river_depth", MGVALLEYS_VARY_RIVER_DEPTH}, + {"altitude_dry", MGVALLEYS_ALT_DRY}, + {NULL, 0} +}; + + +MapgenValleys::MapgenValleys(MapgenValleysParams *params, EmergeParams *emerge) + : MapgenBasic(MAPGEN_VALLEYS, params, emerge) { // NOTE: MapgenValleys has a hard dependency on BiomeGenOriginal m_bgen = (BiomeGenOriginal *)biomegen; - spflags = params->spflags; - altitude_chill = params->altitude_chill; - river_depth_bed = params->river_depth + 1.0f; - river_size_factor = params->river_size / 100.0f; + spflags = params->spflags; + altitude_chill = params->altitude_chill; + river_depth_bed = params->river_depth + 1.0f; + river_size_factor = params->river_size / 100.0f; - cave_width = params->cave_width; - large_cave_depth = params->large_cave_depth; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; small_cave_num_min = params->small_cave_num_min; small_cave_num_max = params->small_cave_num_max; large_cave_num_min = params->large_cave_num_min; large_cave_num_max = params->large_cave_num_max; large_cave_flooded = params->large_cave_flooded; - cavern_limit = params->cavern_limit; - cavern_taper = params->cavern_taper; - cavern_threshold = params->cavern_threshold; - dungeon_ymin = params->dungeon_ymin; - dungeon_ymax = params->dungeon_ymax; + cavern_limit = params->cavern_limit; + cavern_taper = params->cavern_taper; + cavern_threshold = params->cavern_threshold; + dungeon_ymin = params->dungeon_ymin; + dungeon_ymax = params->dungeon_ymax; //// 2D Terrain noise - noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); - noise_inter_valley_slope = - new Noise(¶ms->np_inter_valley_slope, seed, csize.X, csize.Z); - noise_rivers = new Noise(¶ms->np_rivers, seed, csize.X, csize.Z); - noise_terrain_height = - new Noise(¶ms->np_terrain_height, seed, csize.X, csize.Z); - noise_valley_depth = new Noise(¶ms->np_valley_depth, seed, csize.X, csize.Z); - noise_valley_profile = - new Noise(¶ms->np_valley_profile, seed, csize.X, csize.Z); + noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); + noise_inter_valley_slope = new Noise(¶ms->np_inter_valley_slope, seed, csize.X, csize.Z); + noise_rivers = new Noise(¶ms->np_rivers, seed, csize.X, csize.Z); + noise_terrain_height = new Noise(¶ms->np_terrain_height, seed, csize.X, csize.Z); + noise_valley_depth = new Noise(¶ms->np_valley_depth, seed, csize.X, csize.Z); + noise_valley_profile = new Noise(¶ms->np_valley_profile, seed, csize.X, csize.Z); //// 3D Terrain noise // 1-up 1-down overgeneration - noise_inter_valley_fill = new Noise(¶ms->np_inter_valley_fill, seed, csize.X, - csize.Y + 2, csize.Z); + noise_inter_valley_fill = new Noise(¶ms->np_inter_valley_fill, + seed, csize.X, csize.Y + 2, csize.Z); // 1-down overgeneraion - MapgenBasic::np_cave1 = params->np_cave1; - MapgenBasic::np_cave2 = params->np_cave2; - MapgenBasic::np_cavern = params->np_cavern; + MapgenBasic::np_cave1 = params->np_cave1; + MapgenBasic::np_cave2 = params->np_cave2; + MapgenBasic::np_cavern = params->np_cavern; MapgenBasic::np_dungeons = params->np_dungeons; } + MapgenValleys::~MapgenValleys() { delete noise_filler_depth; @@ -105,111 +109,115 @@ MapgenValleys::~MapgenValleys() delete noise_valley_profile; } -MapgenValleysParams::MapgenValleysParams() : - np_filler_depth(0.0, 1.2, v3f(256, 256, 256), 1605, 3, 0.5, 2.0), - np_inter_valley_fill(0.0, 1.0, v3f(256, 512, 256), 1993, 6, 0.8, 2.0), - np_inter_valley_slope(0.5, 0.5, v3f(128, 128, 128), 746, 1, 1.0, 2.0), - np_rivers(0.0, 1.0, v3f(256, 256, 256), -6050, 5, 0.6, 2.0), - np_terrain_height(-10.0, 50.0, v3f(1024, 1024, 1024), 5202, 6, 0.4, 2.0), - np_valley_depth(5.0, 4.0, v3f(512, 512, 512), -1914, 1, 1.0, 2.0), - np_valley_profile(0.6, 0.50, v3f(512, 512, 512), 777, 1, 1.0, 2.0), - np_cave1(0.0, 12.0, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), - np_cave2(0.0, 12.0, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), - np_cavern(0.0, 1.0, v3f(768, 256, 768), 59033, 6, 0.63, 2.0), - np_dungeons(0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) + +MapgenValleysParams::MapgenValleysParams(): + np_filler_depth (0.0, 1.2, v3f(256, 256, 256), 1605, 3, 0.5, 2.0), + np_inter_valley_fill (0.0, 1.0, v3f(256, 512, 256), 1993, 6, 0.8, 2.0), + np_inter_valley_slope (0.5, 0.5, v3f(128, 128, 128), 746, 1, 1.0, 2.0), + np_rivers (0.0, 1.0, v3f(256, 256, 256), -6050, 5, 0.6, 2.0), + np_terrain_height (-10.0, 50.0, v3f(1024, 1024, 1024), 5202, 6, 0.4, 2.0), + np_valley_depth (5.0, 4.0, v3f(512, 512, 512), -1914, 1, 1.0, 2.0), + np_valley_profile (0.6, 0.50, v3f(512, 512, 512), 777, 1, 1.0, 2.0), + np_cave1 (0.0, 12.0, v3f(61, 61, 61), 52534, 3, 0.5, 2.0), + np_cave2 (0.0, 12.0, v3f(67, 67, 67), 10325, 3, 0.5, 2.0), + np_cavern (0.0, 1.0, v3f(768, 256, 768), 59033, 6, 0.63, 2.0), + np_dungeons (0.9, 0.5, v3f(500, 500, 500), 0, 2, 0.8, 2.0) { } + void MapgenValleysParams::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgvalleys_spflags", spflags, flagdesc_mapgen_valleys); - settings->getU16NoEx("mgvalleys_altitude_chill", altitude_chill); - settings->getS16NoEx("mgvalleys_large_cave_depth", large_cave_depth); - settings->getU16NoEx("mgvalleys_small_cave_num_min", small_cave_num_min); - settings->getU16NoEx("mgvalleys_small_cave_num_max", small_cave_num_max); - settings->getU16NoEx("mgvalleys_large_cave_num_min", large_cave_num_min); - settings->getU16NoEx("mgvalleys_large_cave_num_max", large_cave_num_max); + settings->getU16NoEx("mgvalleys_altitude_chill", altitude_chill); + settings->getS16NoEx("mgvalleys_large_cave_depth", large_cave_depth); + settings->getU16NoEx("mgvalleys_small_cave_num_min", small_cave_num_min); + settings->getU16NoEx("mgvalleys_small_cave_num_max", small_cave_num_max); + settings->getU16NoEx("mgvalleys_large_cave_num_min", large_cave_num_min); + settings->getU16NoEx("mgvalleys_large_cave_num_max", large_cave_num_max); settings->getFloatNoEx("mgvalleys_large_cave_flooded", large_cave_flooded); - settings->getU16NoEx("mgvalleys_river_depth", river_depth); - settings->getU16NoEx("mgvalleys_river_size", river_size); - settings->getFloatNoEx("mgvalleys_cave_width", cave_width); - settings->getS16NoEx("mgvalleys_cavern_limit", cavern_limit); - settings->getS16NoEx("mgvalleys_cavern_taper", cavern_taper); - settings->getFloatNoEx("mgvalleys_cavern_threshold", cavern_threshold); - settings->getS16NoEx("mgvalleys_dungeon_ymin", dungeon_ymin); - settings->getS16NoEx("mgvalleys_dungeon_ymax", dungeon_ymax); - - settings->getNoiseParams("mgvalleys_np_filler_depth", np_filler_depth); - settings->getNoiseParams("mgvalleys_np_inter_valley_fill", np_inter_valley_fill); - settings->getNoiseParams( - "mgvalleys_np_inter_valley_slope", np_inter_valley_slope); - settings->getNoiseParams("mgvalleys_np_rivers", np_rivers); - settings->getNoiseParams("mgvalleys_np_terrain_height", np_terrain_height); - settings->getNoiseParams("mgvalleys_np_valley_depth", np_valley_depth); - settings->getNoiseParams("mgvalleys_np_valley_profile", np_valley_profile); - - settings->getNoiseParams("mgvalleys_np_cave1", np_cave1); - settings->getNoiseParams("mgvalleys_np_cave2", np_cave2); - settings->getNoiseParams("mgvalleys_np_cavern", np_cavern); - settings->getNoiseParams("mgvalleys_np_dungeons", np_dungeons); + settings->getU16NoEx("mgvalleys_river_depth", river_depth); + settings->getU16NoEx("mgvalleys_river_size", river_size); + settings->getFloatNoEx("mgvalleys_cave_width", cave_width); + settings->getS16NoEx("mgvalleys_cavern_limit", cavern_limit); + settings->getS16NoEx("mgvalleys_cavern_taper", cavern_taper); + settings->getFloatNoEx("mgvalleys_cavern_threshold", cavern_threshold); + settings->getS16NoEx("mgvalleys_dungeon_ymin", dungeon_ymin); + settings->getS16NoEx("mgvalleys_dungeon_ymax", dungeon_ymax); + + settings->getNoiseParams("mgvalleys_np_filler_depth", np_filler_depth); + settings->getNoiseParams("mgvalleys_np_inter_valley_fill", np_inter_valley_fill); + settings->getNoiseParams("mgvalleys_np_inter_valley_slope", np_inter_valley_slope); + settings->getNoiseParams("mgvalleys_np_rivers", np_rivers); + settings->getNoiseParams("mgvalleys_np_terrain_height", np_terrain_height); + settings->getNoiseParams("mgvalleys_np_valley_depth", np_valley_depth); + settings->getNoiseParams("mgvalleys_np_valley_profile", np_valley_profile); + + settings->getNoiseParams("mgvalleys_np_cave1", np_cave1); + settings->getNoiseParams("mgvalleys_np_cave2", np_cave2); + settings->getNoiseParams("mgvalleys_np_cavern", np_cavern); + settings->getNoiseParams("mgvalleys_np_dungeons", np_dungeons); } + void MapgenValleysParams::writeParams(Settings *settings) const { settings->setFlagStr("mgvalleys_spflags", spflags, flagdesc_mapgen_valleys); - settings->setU16("mgvalleys_altitude_chill", altitude_chill); - settings->setS16("mgvalleys_large_cave_depth", large_cave_depth); - settings->setU16("mgvalleys_small_cave_num_min", small_cave_num_min); - settings->setU16("mgvalleys_small_cave_num_max", small_cave_num_max); - settings->setU16("mgvalleys_large_cave_num_min", large_cave_num_min); - settings->setU16("mgvalleys_large_cave_num_max", large_cave_num_max); + settings->setU16("mgvalleys_altitude_chill", altitude_chill); + settings->setS16("mgvalleys_large_cave_depth", large_cave_depth); + settings->setU16("mgvalleys_small_cave_num_min", small_cave_num_min); + settings->setU16("mgvalleys_small_cave_num_max", small_cave_num_max); + settings->setU16("mgvalleys_large_cave_num_min", large_cave_num_min); + settings->setU16("mgvalleys_large_cave_num_max", large_cave_num_max); settings->setFloat("mgvalleys_large_cave_flooded", large_cave_flooded); - settings->setU16("mgvalleys_river_depth", river_depth); - settings->setU16("mgvalleys_river_size", river_size); - settings->setFloat("mgvalleys_cave_width", cave_width); - settings->setS16("mgvalleys_cavern_limit", cavern_limit); - settings->setS16("mgvalleys_cavern_taper", cavern_taper); - settings->setFloat("mgvalleys_cavern_threshold", cavern_threshold); - settings->setS16("mgvalleys_dungeon_ymin", dungeon_ymin); - settings->setS16("mgvalleys_dungeon_ymax", dungeon_ymax); - - settings->setNoiseParams("mgvalleys_np_filler_depth", np_filler_depth); - settings->setNoiseParams("mgvalleys_np_inter_valley_fill", np_inter_valley_fill); - settings->setNoiseParams( - "mgvalleys_np_inter_valley_slope", np_inter_valley_slope); - settings->setNoiseParams("mgvalleys_np_rivers", np_rivers); - settings->setNoiseParams("mgvalleys_np_terrain_height", np_terrain_height); - settings->setNoiseParams("mgvalleys_np_valley_depth", np_valley_depth); - settings->setNoiseParams("mgvalleys_np_valley_profile", np_valley_profile); - - settings->setNoiseParams("mgvalleys_np_cave1", np_cave1); - settings->setNoiseParams("mgvalleys_np_cave2", np_cave2); - settings->setNoiseParams("mgvalleys_np_cavern", np_cavern); - settings->setNoiseParams("mgvalleys_np_dungeons", np_dungeons); + settings->setU16("mgvalleys_river_depth", river_depth); + settings->setU16("mgvalleys_river_size", river_size); + settings->setFloat("mgvalleys_cave_width", cave_width); + settings->setS16("mgvalleys_cavern_limit", cavern_limit); + settings->setS16("mgvalleys_cavern_taper", cavern_taper); + settings->setFloat("mgvalleys_cavern_threshold", cavern_threshold); + settings->setS16("mgvalleys_dungeon_ymin", dungeon_ymin); + settings->setS16("mgvalleys_dungeon_ymax", dungeon_ymax); + + settings->setNoiseParams("mgvalleys_np_filler_depth", np_filler_depth); + settings->setNoiseParams("mgvalleys_np_inter_valley_fill", np_inter_valley_fill); + settings->setNoiseParams("mgvalleys_np_inter_valley_slope", np_inter_valley_slope); + settings->setNoiseParams("mgvalleys_np_rivers", np_rivers); + settings->setNoiseParams("mgvalleys_np_terrain_height", np_terrain_height); + settings->setNoiseParams("mgvalleys_np_valley_depth", np_valley_depth); + settings->setNoiseParams("mgvalleys_np_valley_profile", np_valley_profile); + + settings->setNoiseParams("mgvalleys_np_cave1", np_cave1); + settings->setNoiseParams("mgvalleys_np_cave2", np_cave2); + settings->setNoiseParams("mgvalleys_np_cavern", np_cavern); + settings->setNoiseParams("mgvalleys_np_dungeons", np_dungeons); } + void MapgenValleysParams::setDefaultSettings(Settings *settings) { settings->setDefault("mgvalleys_spflags", flagdesc_mapgen_valleys, - MGVALLEYS_ALT_CHILL | MGVALLEYS_HUMID_RIVERS | - MGVALLEYS_VARY_RIVER_DEPTH | MGVALLEYS_ALT_DRY); + MGVALLEYS_ALT_CHILL | MGVALLEYS_HUMID_RIVERS | + MGVALLEYS_VARY_RIVER_DEPTH | MGVALLEYS_ALT_DRY); } + ///////////////////////////////////////////////////////////////// + void MapgenValleys::makeChunk(BlockMakeData *data) { // Pre-conditions assert(data->vmanip); assert(data->nodedef); assert(data->blockpos_requested.X >= data->blockpos_min.X && - data->blockpos_requested.Y >= data->blockpos_min.Y && - data->blockpos_requested.Z >= data->blockpos_min.Z); + data->blockpos_requested.Y >= data->blockpos_min.Y && + data->blockpos_requested.Z >= data->blockpos_min.Z); assert(data->blockpos_requested.X <= data->blockpos_max.X && - data->blockpos_requested.Y <= data->blockpos_max.Y && - data->blockpos_requested.Z <= data->blockpos_max.Z); + data->blockpos_requested.Y <= data->blockpos_max.Y && + data->blockpos_requested.Z <= data->blockpos_max.Z); - // TimeTaker t("makeChunk"); + //TimeTaker t("makeChunk"); this->generating = true; this->vm = data->vmanip; @@ -253,8 +261,8 @@ void MapgenValleys::makeChunk(BlockMakeData *data) // Disable large randomwalk caves in this mapchunk by setting // 'large cave depth' to world base. Avoids excessive liquid in // large caverns and floating blobs of overgenerated liquid. - generateCavesRandomWalk( - stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); + generateCavesRandomWalk(stone_surface_max_y, + -MAX_MAP_GENERATION_LIMIT); else generateCavesRandomWalk(stone_surface_max_y, large_cave_depth); } @@ -278,13 +286,14 @@ void MapgenValleys::makeChunk(BlockMakeData *data) if (flags & MG_LIGHT) calcLighting(node_min - v3s16(0, 1, 0), node_max + v3s16(0, 1, 0), - full_node_min, full_node_max); + full_node_min, full_node_max); this->generating = false; - // printf("makeChunk: %lums\n", t.stop()); + //printf("makeChunk: %lums\n", t.stop()); } + int MapgenValleys::getSpawnLevelAtPoint(v2s16 p) { // Check if in a river channel @@ -293,9 +302,9 @@ int MapgenValleys::getSpawnLevelAtPoint(v2s16 p) // Unsuitable spawn point return MAX_MAP_GENERATION_LIMIT; - float n_slope = NoisePerlin2D(&noise_inter_valley_slope->np, p.X, p.Y, seed); + float n_slope = NoisePerlin2D(&noise_inter_valley_slope->np, p.X, p.Y, seed); float n_terrain_height = NoisePerlin2D(&noise_terrain_height->np, p.X, p.Y, seed); - float n_valley = NoisePerlin2D(&noise_valley_depth->np, p.X, p.Y, seed); + float n_valley = NoisePerlin2D(&noise_valley_depth->np, p.X, p.Y, seed); float n_valley_profile = NoisePerlin2D(&noise_valley_profile->np, p.X, p.Y, seed); float valley_d = n_valley * n_valley; @@ -307,25 +316,23 @@ int MapgenValleys::getSpawnLevelAtPoint(v2s16 p) float slope = n_slope * valley_h; float river_y = base - 1.0f; - // Raising the maximum spawn level above 'water_level + 16' is necessary for - // custom parameters that set average terrain level much higher than water_level. + // Raising the maximum spawn level above 'water_level + 16' is necessary for custom + // parameters that set average terrain level much higher than water_level. s16 max_spawn_y = std::fmax( - noise_terrain_height->np.offset + - noise_valley_depth->np.offset * - noise_valley_depth->np.offset, - water_level + 16); + noise_terrain_height->np.offset + + noise_valley_depth->np.offset * noise_valley_depth->np.offset, + water_level + 16); // Starting spawn search at max_spawn_y + 128 ensures 128 nodes of open // space above spawn position. Avoids spawning in possibly sealed voids. for (s16 y = max_spawn_y + 128; y >= water_level; y--) { - float n_fill = NoisePerlin3D( - &noise_inter_valley_fill->np, p.X, y, p.Y, seed); + float n_fill = NoisePerlin3D(&noise_inter_valley_fill->np, p.X, y, p.Y, seed); float surface_delta = (float)y - surface_y; float density = slope * n_fill - surface_delta; - if (density > 0.0f) { // If solid - // Sometimes surface level is below river water level in places - // that are not river channels. + if (density > 0.0f) { // If solid + // Sometimes surface level is below river water level in places that are not + // river channels. if (y < water_level || y > max_spawn_y || y < (s16)river_y) // Unsuitable spawn point return MAX_MAP_GENERATION_LIMIT; @@ -338,6 +345,7 @@ int MapgenValleys::getSpawnLevelAtPoint(v2s16 p) return MAX_MAP_GENERATION_LIMIT; } + int MapgenValleys::generateTerrain() { MapNode n_air(CONTENT_AIR); @@ -358,142 +366,122 @@ int MapgenValleys::generateTerrain() u32 index_2d = 0; for (s16 z = node_min.Z; z <= node_max.Z; z++) - for (s16 x = node_min.X; x <= node_max.X; x++, index_2d++) { - float n_slope = noise_inter_valley_slope->result[index_2d]; - float n_rivers = noise_rivers->result[index_2d]; - float n_terrain_height = noise_terrain_height->result[index_2d]; - float n_valley = noise_valley_depth->result[index_2d]; - float n_valley_profile = noise_valley_profile->result[index_2d]; - - float valley_d = n_valley * n_valley; - // 'base' represents the level of the river banks - float base = n_terrain_height + valley_d; - // 'river' represents the distance from the river edge - float river = std::fabs(n_rivers) - river_size_factor; - // Use the curve of the function 1-exp(-(x/a)^2) to model valleys. - // 'valley_h' represents the height of the terrain, from the - // rivers. - float tv = std::fmax(river / n_valley_profile, 0.0f); - float valley_h = valley_d * (1.0f - std::exp(-tv * tv)); - // Approximate height of the terrain - float surface_y = base + valley_h; - float slope = n_slope * valley_h; - // River water surface is 1 node below river banks - float river_y = base - 1.0f; - - // Rivers are placed where 'river' is negative - if (river < 0.0f) { - // Use the function -sqrt(1-x^2) which models a circle - float tr = river / river_size_factor + 1.0f; - float depth = (river_depth_bed * - std::sqrt(std::fmax( - 0.0f, 1.0f - tr * tr))); - // There is no logical equivalent to this using rangelim - surface_y = std::fmin( - std::fmax(base - depth, - (float)(water_level - 3)), - surface_y); - slope = 0.0f; - } + for (s16 x = node_min.X; x <= node_max.X; x++, index_2d++) { + float n_slope = noise_inter_valley_slope->result[index_2d]; + float n_rivers = noise_rivers->result[index_2d]; + float n_terrain_height = noise_terrain_height->result[index_2d]; + float n_valley = noise_valley_depth->result[index_2d]; + float n_valley_profile = noise_valley_profile->result[index_2d]; + + float valley_d = n_valley * n_valley; + // 'base' represents the level of the river banks + float base = n_terrain_height + valley_d; + // 'river' represents the distance from the river edge + float river = std::fabs(n_rivers) - river_size_factor; + // Use the curve of the function 1-exp(-(x/a)^2) to model valleys. + // 'valley_h' represents the height of the terrain, from the rivers. + float tv = std::fmax(river / n_valley_profile, 0.0f); + float valley_h = valley_d * (1.0f - std::exp(-tv * tv)); + // Approximate height of the terrain + float surface_y = base + valley_h; + float slope = n_slope * valley_h; + // River water surface is 1 node below river banks + float river_y = base - 1.0f; + + // Rivers are placed where 'river' is negative + if (river < 0.0f) { + // Use the function -sqrt(1-x^2) which models a circle + float tr = river / river_size_factor + 1.0f; + float depth = (river_depth_bed * + std::sqrt(std::fmax(0.0f, 1.0f - tr * tr))); + // There is no logical equivalent to this using rangelim + surface_y = std::fmin( + std::fmax(base - depth, (float)(water_level - 3)), + surface_y); + slope = 0.0f; + } - // Optionally vary river depth according to heat and humidity - if (spflags & MGVALLEYS_VARY_RIVER_DEPTH) { - float t_heat = m_bgen->heatmap[index_2d]; - float heat = (spflags & MGVALLEYS_ALT_CHILL) - ? - // Match heat value - // calculated below in - // 'Optionally decrease heat - // with altitude'. In rivers, - // 'ground height ignoring - // riverbeds' is 'base'. As - // this only affects river - // water we can assume y > - // water_level. - t_heat + 5.0f - - (base - water_level) * - 20.0f / - altitude_chill - : t_heat; - float delta = m_bgen->humidmap[index_2d] - 50.0f; - if (delta < 0.0f) { - float t_evap = (heat - 32.0f) / 300.0f; - river_y += delta * std::fmax(t_evap, 0.08f); - } + // Optionally vary river depth according to heat and humidity + if (spflags & MGVALLEYS_VARY_RIVER_DEPTH) { + float t_heat = m_bgen->heatmap[index_2d]; + float heat = (spflags & MGVALLEYS_ALT_CHILL) ? + // Match heat value calculated below in + // 'Optionally decrease heat with altitude'. + // In rivers, 'ground height ignoring riverbeds' is 'base'. + // As this only affects river water we can assume y > water_level. + t_heat + 5.0f - (base - water_level) * 20.0f / altitude_chill : + t_heat; + float delta = m_bgen->humidmap[index_2d] - 50.0f; + if (delta < 0.0f) { + float t_evap = (heat - 32.0f) / 300.0f; + river_y += delta * std::fmax(t_evap, 0.08f); } + } - // Highest solid node in column - s16 column_max_y = surface_y; - u32 index_3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); - u32 index_data = vm->m_area.index(x, node_min.Y - 1, z); - - for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { - if (vm->m_data[index_data].getContent() == - CONTENT_IGNORE) { - float n_fill = noise_inter_valley_fill - ->result[index_3d]; - float surface_delta = (float)y - surface_y; - // Density = density noise + density gradient - float density = slope * n_fill - surface_delta; - - if (density > 0.0f) { - vm->m_data[index_data] = n_stone; // Stone - if (y > surface_max_y) - surface_max_y = y; - if (y > column_max_y) - column_max_y = y; - } else if (y <= water_level) { - vm->m_data[index_data] = n_water; // Water - } else if (y <= (s16)river_y) { - vm->m_data[index_data] = - n_river_water; // River - // water - } else { - vm->m_data[index_data] = n_air; // Air - } + // Highest solid node in column + s16 column_max_y = surface_y; + u32 index_3d = (z - node_min.Z) * zstride_1u1d + (x - node_min.X); + u32 index_data = vm->m_area.index(x, node_min.Y - 1, z); + + for (s16 y = node_min.Y - 1; y <= node_max.Y + 1; y++) { + if (vm->m_data[index_data].getContent() == CONTENT_IGNORE) { + float n_fill = noise_inter_valley_fill->result[index_3d]; + float surface_delta = (float)y - surface_y; + // Density = density noise + density gradient + float density = slope * n_fill - surface_delta; + + if (density > 0.0f) { + vm->m_data[index_data] = n_stone; // Stone + if (y > surface_max_y) + surface_max_y = y; + if (y > column_max_y) + column_max_y = y; + } else if (y <= water_level) { + vm->m_data[index_data] = n_water; // Water + } else if (y <= (s16)river_y) { + vm->m_data[index_data] = n_river_water; // River water + } else { + vm->m_data[index_data] = n_air; // Air } - - VoxelArea::add_y(em, index_data, 1); - index_3d += ystride; } - // Optionally increase humidity around rivers - if (spflags & MGVALLEYS_HUMID_RIVERS) { - // Compensate to avoid increasing average humidity - m_bgen->humidmap[index_2d] *= 0.8f; - // Ground height ignoring riverbeds - float t_alt = std::fmax(base, (float)column_max_y); - float water_depth = (t_alt - base) / 4.0f; - m_bgen->humidmap[index_2d] *= - 1.0f + - std::pow(0.5f, std::fmax(water_depth, - 1.0f)); - } + VoxelArea::add_y(em, index_data, 1); + index_3d += ystride; + } - // Optionally decrease humidity with altitude - if (spflags & MGVALLEYS_ALT_DRY) { - // Ground height ignoring riverbeds - float t_alt = std::fmax(base, (float)column_max_y); - // Only decrease above water_level - if (t_alt > water_level) - m_bgen->humidmap[index_2d] -= - (t_alt - water_level) * 10.0f / - altitude_chill; - } + // Optionally increase humidity around rivers + if (spflags & MGVALLEYS_HUMID_RIVERS) { + // Compensate to avoid increasing average humidity + m_bgen->humidmap[index_2d] *= 0.8f; + // Ground height ignoring riverbeds + float t_alt = std::fmax(base, (float)column_max_y); + float water_depth = (t_alt - base) / 4.0f; + m_bgen->humidmap[index_2d] *= + 1.0f + std::pow(0.5f, std::fmax(water_depth, 1.0f)); + } - // Optionally decrease heat with altitude - if (spflags & MGVALLEYS_ALT_CHILL) { - // Compensate to avoid reducing the average heat - m_bgen->heatmap[index_2d] += 5.0f; - // Ground height ignoring riverbeds - float t_alt = std::fmax(base, (float)column_max_y); - // Only decrease above water_level - if (t_alt > water_level) - m_bgen->heatmap[index_2d] -= - (t_alt - water_level) * 20.0f / - altitude_chill; - } + // Optionally decrease humidity with altitude + if (spflags & MGVALLEYS_ALT_DRY) { + // Ground height ignoring riverbeds + float t_alt = std::fmax(base, (float)column_max_y); + // Only decrease above water_level + if (t_alt > water_level) + m_bgen->humidmap[index_2d] -= + (t_alt - water_level) * 10.0f / altitude_chill; } + // Optionally decrease heat with altitude + if (spflags & MGVALLEYS_ALT_CHILL) { + // Compensate to avoid reducing the average heat + m_bgen->heatmap[index_2d] += 5.0f; + // Ground height ignoring riverbeds + float t_alt = std::fmax(base, (float)column_max_y); + // Only decrease above water_level + if (t_alt > water_level) + m_bgen->heatmap[index_2d] -= + (t_alt - water_level) * 20.0f / altitude_chill; + } + } + return surface_max_y; } diff --git a/src/mapgen/mapgen_valleys.h b/src/mapgen/mapgen_valleys.h index fb544e51b..34a923dfa 100644 --- a/src/mapgen/mapgen_valleys.h +++ b/src/mapgen/mapgen_valleys.h @@ -24,22 +24,23 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #pragma once #include "mapgen.h" -#define MGVALLEYS_ALT_CHILL 0x01 -#define MGVALLEYS_HUMID_RIVERS 0x02 +#define MGVALLEYS_ALT_CHILL 0x01 +#define MGVALLEYS_HUMID_RIVERS 0x02 #define MGVALLEYS_VARY_RIVER_DEPTH 0x04 -#define MGVALLEYS_ALT_DRY 0x08 +#define MGVALLEYS_ALT_DRY 0x08 class BiomeManager; class BiomeGenOriginal; extern FlagDesc flagdesc_mapgen_valleys[]; -struct MapgenValleysParams : public MapgenParams -{ + +struct MapgenValleysParams : public MapgenParams { u16 altitude_chill = 90; u16 river_depth = 4; u16 river_size = 5; @@ -78,10 +79,12 @@ struct MapgenValleysParams : public MapgenParams void setDefaultSettings(Settings *settings); }; -class MapgenValleys : public MapgenBasic -{ + +class MapgenValleys : public MapgenBasic { public: - MapgenValleys(MapgenValleysParams *params, EmergeParams *emerge); + + MapgenValleys(MapgenValleysParams *params, + EmergeParams *emerge); ~MapgenValleys(); virtual MapgenType getType() const { return MAPGEN_VALLEYS; } diff --git a/src/mapgen/mg_biome.cpp b/src/mapgen/mg_biome.cpp index ea7c24721..610c38594 100644 --- a/src/mapgen/mg_biome.cpp +++ b/src/mapgen/mg_biome.cpp @@ -28,28 +28,31 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "porting.h" #include "settings.h" + /////////////////////////////////////////////////////////////////////////////// -BiomeManager::BiomeManager(Server *server) : ObjDefManager(server, OBJDEF_BIOME) + +BiomeManager::BiomeManager(Server *server) : + ObjDefManager(server, OBJDEF_BIOME) { m_server = server; // Create default biome to be used in case none exist Biome *b = new Biome; - b->name = "default"; - b->flags = 0; - b->depth_top = 0; - b->depth_filler = -MAX_MAP_GENERATION_LIMIT; + b->name = "default"; + b->flags = 0; + b->depth_top = 0; + b->depth_filler = -MAX_MAP_GENERATION_LIMIT; b->depth_water_top = 0; - b->depth_riverbed = 0; - b->min_pos = v3s16(-MAX_MAP_GENERATION_LIMIT, -MAX_MAP_GENERATION_LIMIT, - -MAX_MAP_GENERATION_LIMIT); - b->max_pos = v3s16(MAX_MAP_GENERATION_LIMIT, MAX_MAP_GENERATION_LIMIT, - MAX_MAP_GENERATION_LIMIT); - b->heat_point = 0.0; - b->humidity_point = 0.0; - b->vertical_blend = 0; + b->depth_riverbed = 0; + b->min_pos = v3s16(-MAX_MAP_GENERATION_LIMIT, + -MAX_MAP_GENERATION_LIMIT, -MAX_MAP_GENERATION_LIMIT); + b->max_pos = v3s16(MAX_MAP_GENERATION_LIMIT, + MAX_MAP_GENERATION_LIMIT, MAX_MAP_GENERATION_LIMIT); + b->heat_point = 0.0; + b->humidity_point = 0.0; + b->vertical_blend = 0; b->m_nodenames.emplace_back("mapgen_stone"); b->m_nodenames.emplace_back("mapgen_stone"); @@ -69,6 +72,7 @@ BiomeManager::BiomeManager(Server *server) : ObjDefManager(server, OBJDEF_BIOME) add(b); } + void BiomeManager::clear() { EmergeManager *emerge = m_server->getEmergeManager(); @@ -87,6 +91,7 @@ void BiomeManager::clear() m_objects.resize(1); } + BiomeManager *BiomeManager::clone() const { auto mgr = new BiomeManager(); @@ -96,25 +101,30 @@ BiomeManager *BiomeManager::clone() const return mgr; } + // For BiomeGen type 'BiomeGenOriginal' float BiomeManager::getHeatAtPosOriginal(v3s16 pos, NoiseParams &np_heat, - NoiseParams &np_heat_blend, u64 seed) const + NoiseParams &np_heat_blend, u64 seed) const { - return NoisePerlin2D(&np_heat, pos.X, pos.Z, seed) + - NoisePerlin2D(&np_heat_blend, pos.X, pos.Z, seed); + return + NoisePerlin2D(&np_heat, pos.X, pos.Z, seed) + + NoisePerlin2D(&np_heat_blend, pos.X, pos.Z, seed); } + // For BiomeGen type 'BiomeGenOriginal' float BiomeManager::getHumidityAtPosOriginal(v3s16 pos, NoiseParams &np_humidity, - NoiseParams &np_humidity_blend, u64 seed) const + NoiseParams &np_humidity_blend, u64 seed) const { - return NoisePerlin2D(&np_humidity, pos.X, pos.Z, seed) + - NoisePerlin2D(&np_humidity_blend, pos.X, pos.Z, seed); + return + NoisePerlin2D(&np_humidity, pos.X, pos.Z, seed) + + NoisePerlin2D(&np_humidity_blend, pos.X, pos.Z, seed); } + // For BiomeGen type 'BiomeGenOriginal' -const Biome *BiomeManager::getBiomeFromNoiseOriginal( - float heat, float humidity, v3s16 pos) const +const Biome *BiomeManager::getBiomeFromNoiseOriginal(float heat, + float humidity, v3s16 pos) const { Biome *biome_closest = nullptr; Biome *biome_closest_blend = nullptr; @@ -123,8 +133,8 @@ const Biome *BiomeManager::getBiomeFromNoiseOriginal( for (size_t i = 1; i < getNumObjects(); i++) { Biome *b = (Biome *)getRaw(i); - if (!b || pos.Y < b->min_pos.Y || - pos.Y > b->max_pos.Y + b->vertical_blend || + if (!b || + pos.Y < b->min_pos.Y || pos.Y > b->max_pos.Y + b->vertical_blend || pos.X < b->min_pos.X || pos.X > b->max_pos.X || pos.Z < b->min_pos.Z || pos.Z > b->max_pos.Z) continue; @@ -149,48 +159,52 @@ const Biome *BiomeManager::getBiomeFromNoiseOriginal( if (biome_closest_blend && dist_min_blend <= dist_min && rng.range(0, biome_closest_blend->vertical_blend) >= - pos.Y - biome_closest_blend->max_pos.Y) + pos.Y - biome_closest_blend->max_pos.Y) return biome_closest_blend; return (biome_closest) ? biome_closest : (Biome *)getRaw(BIOME_NONE); } + //////////////////////////////////////////////////////////////////////////////// void BiomeParamsOriginal::readParams(const Settings *settings) { - settings->getNoiseParams("mg_biome_np_heat", np_heat); - settings->getNoiseParams("mg_biome_np_heat_blend", np_heat_blend); - settings->getNoiseParams("mg_biome_np_humidity", np_humidity); + settings->getNoiseParams("mg_biome_np_heat", np_heat); + settings->getNoiseParams("mg_biome_np_heat_blend", np_heat_blend); + settings->getNoiseParams("mg_biome_np_humidity", np_humidity); settings->getNoiseParams("mg_biome_np_humidity_blend", np_humidity_blend); } + void BiomeParamsOriginal::writeParams(Settings *settings) const { - settings->setNoiseParams("mg_biome_np_heat", np_heat); - settings->setNoiseParams("mg_biome_np_heat_blend", np_heat_blend); - settings->setNoiseParams("mg_biome_np_humidity", np_humidity); + settings->setNoiseParams("mg_biome_np_heat", np_heat); + settings->setNoiseParams("mg_biome_np_heat_blend", np_heat_blend); + settings->setNoiseParams("mg_biome_np_humidity", np_humidity); settings->setNoiseParams("mg_biome_np_humidity_blend", np_humidity_blend); } + //////////////////////////////////////////////////////////////////////////////// -BiomeGenOriginal::BiomeGenOriginal( - BiomeManager *biomemgr, BiomeParamsOriginal *params, v3s16 chunksize) +BiomeGenOriginal::BiomeGenOriginal(BiomeManager *biomemgr, + BiomeParamsOriginal *params, v3s16 chunksize) { - m_bmgr = biomemgr; + m_bmgr = biomemgr; m_params = params; - m_csize = chunksize; - - noise_heat = new Noise(¶ms->np_heat, params->seed, m_csize.X, m_csize.Z); - noise_humidity = new Noise( - ¶ms->np_humidity, params->seed, m_csize.X, m_csize.Z); - noise_heat_blend = new Noise( - ¶ms->np_heat_blend, params->seed, m_csize.X, m_csize.Z); - noise_humidity_blend = new Noise( - ¶ms->np_humidity_blend, params->seed, m_csize.X, m_csize.Z); - - heatmap = noise_heat->result; + m_csize = chunksize; + + noise_heat = new Noise(¶ms->np_heat, + params->seed, m_csize.X, m_csize.Z); + noise_humidity = new Noise(¶ms->np_humidity, + params->seed, m_csize.X, m_csize.Z); + noise_heat_blend = new Noise(¶ms->np_heat_blend, + params->seed, m_csize.X, m_csize.Z); + noise_humidity_blend = new Noise(¶ms->np_humidity_blend, + params->seed, m_csize.X, m_csize.Z); + + heatmap = noise_heat->result; humidmap = noise_humidity->result; biomemap = new biome_t[m_csize.X * m_csize.Z]; @@ -202,7 +216,7 @@ BiomeGenOriginal::BiomeGenOriginal( BiomeGenOriginal::~BiomeGenOriginal() { - delete[] biomemap; + delete []biomemap; delete noise_heat; delete noise_humidity; @@ -213,17 +227,17 @@ BiomeGenOriginal::~BiomeGenOriginal() // Only usable in a mapgen thread Biome *BiomeGenOriginal::calcBiomeAtPoint(v3s16 pos) const { - float heat = NoisePerlin2D(&m_params->np_heat, pos.X, pos.Z, m_params->seed) + - NoisePerlin2D(&m_params->np_heat_blend, pos.X, pos.Z, - m_params->seed); - float humidity = NoisePerlin2D(&m_params->np_humidity, pos.X, pos.Z, - m_params->seed) + - NoisePerlin2D(&m_params->np_humidity_blend, pos.X, pos.Z, - m_params->seed); + float heat = + NoisePerlin2D(&m_params->np_heat, pos.X, pos.Z, m_params->seed) + + NoisePerlin2D(&m_params->np_heat_blend, pos.X, pos.Z, m_params->seed); + float humidity = + NoisePerlin2D(&m_params->np_humidity, pos.X, pos.Z, m_params->seed) + + NoisePerlin2D(&m_params->np_humidity_blend, pos.X, pos.Z, m_params->seed); return calcBiomeFromNoise(heat, humidity, pos); } + void BiomeGenOriginal::calcBiomeNoise(v3s16 pmin) { m_pmin = pmin; @@ -234,37 +248,46 @@ void BiomeGenOriginal::calcBiomeNoise(v3s16 pmin) noise_humidity_blend->perlinMap2D(pmin.X, pmin.Z); for (s32 i = 0; i < m_csize.X * m_csize.Z; i++) { - noise_heat->result[i] += noise_heat_blend->result[i]; + noise_heat->result[i] += noise_heat_blend->result[i]; noise_humidity->result[i] += noise_humidity_blend->result[i]; } } + biome_t *BiomeGenOriginal::getBiomes(s16 *heightmap, v3s16 pmin) { for (s16 zr = 0; zr < m_csize.Z; zr++) - for (s16 xr = 0; xr < m_csize.X; xr++) { - s32 i = zr * m_csize.X + xr; - Biome *biome = calcBiomeFromNoise(noise_heat->result[i], - noise_humidity->result[i], - v3s16(pmin.X + xr, heightmap[i], pmin.Z + zr)); - - biomemap[i] = biome->index; - } + for (s16 xr = 0; xr < m_csize.X; xr++) { + s32 i = zr * m_csize.X + xr; + Biome *biome = calcBiomeFromNoise( + noise_heat->result[i], + noise_humidity->result[i], + v3s16(pmin.X + xr, heightmap[i], pmin.Z + zr)); + + biomemap[i] = biome->index; + } return biomemap; } + Biome *BiomeGenOriginal::getBiomeAtPoint(v3s16 pos) const { - return getBiomeAtIndex((pos.Z - m_pmin.Z) * m_csize.X + (pos.X - m_pmin.X), pos); + return getBiomeAtIndex( + (pos.Z - m_pmin.Z) * m_csize.X + (pos.X - m_pmin.X), + pos); } + Biome *BiomeGenOriginal::getBiomeAtIndex(size_t index, v3s16 pos) const { return calcBiomeFromNoise( - noise_heat->result[index], noise_humidity->result[index], pos); + noise_heat->result[index], + noise_humidity->result[index], + pos); } + Biome *BiomeGenOriginal::calcBiomeFromNoise(float heat, float humidity, v3s16 pos) const { Biome *biome_closest = nullptr; @@ -274,8 +297,8 @@ Biome *BiomeGenOriginal::calcBiomeFromNoise(float heat, float humidity, v3s16 po for (size_t i = 1; i < m_bmgr->getNumObjects(); i++) { Biome *b = (Biome *)m_bmgr->getRaw(i); - if (!b || pos.Y < b->min_pos.Y || - pos.Y > b->max_pos.Y + b->vertical_blend || + if (!b || + pos.Y < b->min_pos.Y || pos.Y > b->max_pos.Y + b->vertical_blend || pos.X < b->min_pos.X || pos.X > b->max_pos.X || pos.Z < b->min_pos.Z || pos.Z > b->max_pos.Z) continue; @@ -303,12 +326,13 @@ Biome *BiomeGenOriginal::calcBiomeFromNoise(float heat, float humidity, v3s16 po if (biome_closest_blend && dist_min_blend <= dist_min && rng.range(0, biome_closest_blend->vertical_blend) >= - pos.Y - biome_closest_blend->max_pos.Y) + pos.Y - biome_closest_blend->max_pos.Y) return biome_closest_blend; - return (biome_closest) ? biome_closest : (Biome *)m_bmgr->getRaw(BIOME_NONE); + return (biome_closest) ? biome_closest : (Biome *)m_bmgr->getRaw(BIOME_NONE); } + //////////////////////////////////////////////////////////////////////////////// ObjDef *Biome::clone() const @@ -348,17 +372,16 @@ ObjDef *Biome::clone() const void Biome::resolveNodeNames() { - getIdFromNrBacklog(&c_top, "mapgen_stone", CONTENT_AIR, false); - getIdFromNrBacklog(&c_filler, "mapgen_stone", CONTENT_AIR, false); - getIdFromNrBacklog(&c_stone, "mapgen_stone", CONTENT_AIR, false); - getIdFromNrBacklog(&c_water_top, "mapgen_water_source", CONTENT_AIR, false); - getIdFromNrBacklog(&c_water, "mapgen_water_source", CONTENT_AIR, false); - getIdFromNrBacklog( - &c_river_water, "mapgen_river_water_source", CONTENT_AIR, false); - getIdFromNrBacklog(&c_riverbed, "mapgen_stone", CONTENT_AIR, false); - getIdFromNrBacklog(&c_dust, "ignore", CONTENT_IGNORE, false); + getIdFromNrBacklog(&c_top, "mapgen_stone", CONTENT_AIR, false); + getIdFromNrBacklog(&c_filler, "mapgen_stone", CONTENT_AIR, false); + getIdFromNrBacklog(&c_stone, "mapgen_stone", CONTENT_AIR, false); + getIdFromNrBacklog(&c_water_top, "mapgen_water_source", CONTENT_AIR, false); + getIdFromNrBacklog(&c_water, "mapgen_water_source", CONTENT_AIR, false); + getIdFromNrBacklog(&c_river_water, "mapgen_river_water_source", CONTENT_AIR, false); + getIdFromNrBacklog(&c_riverbed, "mapgen_stone", CONTENT_AIR, false); + getIdFromNrBacklog(&c_dust, "ignore", CONTENT_IGNORE, false); getIdsFromNrBacklog(&c_cave_liquid); - getIdFromNrBacklog(&c_dungeon, "ignore", CONTENT_IGNORE, false); - getIdFromNrBacklog(&c_dungeon_alt, "ignore", CONTENT_IGNORE, false); - getIdFromNrBacklog(&c_dungeon_stair, "ignore", CONTENT_IGNORE, false); + getIdFromNrBacklog(&c_dungeon, "ignore", CONTENT_IGNORE, false); + getIdFromNrBacklog(&c_dungeon_alt, "ignore", CONTENT_IGNORE, false); + getIdFromNrBacklog(&c_dungeon_stair, "ignore", CONTENT_IGNORE, false); } diff --git a/src/mapgen/mg_biome.h b/src/mapgen/mg_biome.h index ba3319976..be4cfea4d 100644 --- a/src/mapgen/mg_biome.h +++ b/src/mapgen/mg_biome.h @@ -36,13 +36,11 @@ typedef u16 biome_t; #define BIOME_NONE ((biome_t)0) -enum BiomeType -{ +enum BiomeType { BIOMETYPE_NORMAL, }; -class Biome : public ObjDef, public NodeResolver -{ +class Biome : public ObjDef, public NodeResolver { public: ObjDef *clone() const; @@ -75,17 +73,16 @@ class Biome : public ObjDef, public NodeResolver virtual void resolveNodeNames(); }; + //// //// BiomeGen //// -enum BiomeGenType -{ +enum BiomeGenType { BIOMEGEN_ORIGINAL, }; -struct BiomeParams -{ +struct BiomeParams { virtual void readParams(const Settings *settings) = 0; virtual void writeParams(Settings *settings) const = 0; virtual ~BiomeParams() = default; @@ -94,8 +91,7 @@ struct BiomeParams }; // WARNING: this class is not thread-safe -class BiomeGen -{ +class BiomeGen { public: virtual ~BiomeGen() = default; @@ -132,6 +128,7 @@ class BiomeGen v3s16 m_csize; }; + //// //// BiomeGen implementations //// @@ -140,14 +137,12 @@ class BiomeGen // Original biome algorithm (Whittaker's classification + surface height) // -struct BiomeParamsOriginal : public BiomeParams -{ +struct BiomeParamsOriginal : public BiomeParams { BiomeParamsOriginal() : - np_heat(50, 50, v3f(1000.0, 1000.0, 1000.0), 5349, 3, 0.5, 2.0), - np_humidity(50, 50, v3f(1000.0, 1000.0, 1000.0), 842, 3, 0.5, - 2.0), - np_heat_blend(0, 1.5, v3f(8.0, 8.0, 8.0), 13, 2, 1.0, 2.0), - np_humidity_blend(0, 1.5, v3f(8.0, 8.0, 8.0), 90003, 2, 1.0, 2.0) + np_heat(50, 50, v3f(1000.0, 1000.0, 1000.0), 5349, 3, 0.5, 2.0), + np_humidity(50, 50, v3f(1000.0, 1000.0, 1000.0), 842, 3, 0.5, 2.0), + np_heat_blend(0, 1.5, v3f(8.0, 8.0, 8.0), 13, 2, 1.0, 2.0), + np_humidity_blend(0, 1.5, v3f(8.0, 8.0, 8.0), 90003, 2, 1.0, 2.0) { } @@ -160,11 +155,10 @@ struct BiomeParamsOriginal : public BiomeParams NoiseParams np_humidity_blend; }; -class BiomeGenOriginal : public BiomeGen -{ +class BiomeGenOriginal : public BiomeGen { public: - BiomeGenOriginal(BiomeManager *biomemgr, BiomeParamsOriginal *params, - v3s16 chunksize); + BiomeGenOriginal(BiomeManager *biomemgr, + BiomeParamsOriginal *params, v3s16 chunksize); virtual ~BiomeGenOriginal(); BiomeGenType getType() const { return BIOMEGEN_ORIGINAL; } @@ -190,28 +184,34 @@ class BiomeGenOriginal : public BiomeGen Noise *noise_humidity_blend; }; + //// //// BiomeManager //// -class BiomeManager : public ObjDefManager -{ +class BiomeManager : public ObjDefManager { public: BiomeManager(Server *server); virtual ~BiomeManager() = default; BiomeManager *clone() const; - const char *getObjectTitle() const { return "biome"; } + const char *getObjectTitle() const + { + return "biome"; + } - static Biome *create(BiomeType type) { return new Biome; } + static Biome *create(BiomeType type) + { + return new Biome; + } BiomeGen *createBiomeGen(BiomeGenType type, BiomeParams *params, v3s16 chunksize) { switch (type) { case BIOMEGEN_ORIGINAL: - return new BiomeGenOriginal( - this, (BiomeParamsOriginal *)params, chunksize); + return new BiomeGenOriginal(this, + (BiomeParamsOriginal *)params, chunksize); default: return NULL; } @@ -231,14 +231,15 @@ class BiomeManager : public ObjDefManager // For BiomeGen type 'BiomeGenOriginal' float getHeatAtPosOriginal(v3s16 pos, NoiseParams &np_heat, - NoiseParams &np_heat_blend, u64 seed) const; + NoiseParams &np_heat_blend, u64 seed) const; float getHumidityAtPosOriginal(v3s16 pos, NoiseParams &np_humidity, - NoiseParams &np_humidity_blend, u64 seed) const; - const Biome *getBiomeFromNoiseOriginal( - float heat, float humidity, v3s16 pos) const; + NoiseParams &np_humidity_blend, u64 seed) const; + const Biome *getBiomeFromNoiseOriginal(float heat, float humidity, + v3s16 pos) const; private: - BiomeManager(){}; + BiomeManager() {}; Server *m_server; + }; diff --git a/src/mapgen/mg_decoration.cpp b/src/mapgen/mg_decoration.cpp index 6aa003a3f..a4cada396 100644 --- a/src/mapgen/mg_decoration.cpp +++ b/src/mapgen/mg_decoration.cpp @@ -28,21 +28,30 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -FlagDesc flagdesc_deco[] = {{"place_center_x", DECO_PLACE_CENTER_X}, - {"place_center_y", DECO_PLACE_CENTER_Y}, - {"place_center_z", DECO_PLACE_CENTER_Z}, - {"force_placement", DECO_FORCE_PLACEMENT}, - {"liquid_surface", DECO_LIQUID_SURFACE}, {"all_floors", DECO_ALL_FLOORS}, - {"all_ceilings", DECO_ALL_CEILINGS}, {NULL, 0}}; + +FlagDesc flagdesc_deco[] = { + {"place_center_x", DECO_PLACE_CENTER_X}, + {"place_center_y", DECO_PLACE_CENTER_Y}, + {"place_center_z", DECO_PLACE_CENTER_Z}, + {"force_placement", DECO_FORCE_PLACEMENT}, + {"liquid_surface", DECO_LIQUID_SURFACE}, + {"all_floors", DECO_ALL_FLOORS}, + {"all_ceilings", DECO_ALL_CEILINGS}, + {NULL, 0} +}; + /////////////////////////////////////////////////////////////////////////////// + DecorationManager::DecorationManager(IGameDef *gamedef) : - ObjDefManager(gamedef, OBJDEF_DECORATION) + ObjDefManager(gamedef, OBJDEF_DECORATION) { } -size_t DecorationManager::placeAllDecos(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) + +size_t DecorationManager::placeAllDecos(Mapgen *mg, u32 blockseed, + v3s16 nmin, v3s16 nmax) { size_t nplaced = 0; @@ -65,14 +74,17 @@ DecorationManager *DecorationManager::clone() const return mgr; } + /////////////////////////////////////////////////////////////////////////////// + void Decoration::resolveNodeNames() { getIdsFromNrBacklog(&c_place_on); getIdsFromNrBacklog(&c_spawnby); } + bool Decoration::canPlaceDecoration(MMVManip *vm, v3s16 p) { // Check if the decoration can be placed on this node @@ -85,13 +97,25 @@ bool Decoration::canPlaceDecoration(MMVManip *vm, v3s16 p) return true; int nneighs = 0; - static const v3s16 dirs[16] = {v3s16(0, 0, 1), v3s16(0, 0, -1), v3s16(1, 0, 0), - v3s16(-1, 0, 0), v3s16(1, 0, 1), v3s16(-1, 0, 1), - v3s16(-1, 0, -1), v3s16(1, 0, -1), - - v3s16(0, 1, 1), v3s16(0, 1, -1), v3s16(1, 1, 0), v3s16(-1, 1, 0), - v3s16(1, 1, 1), v3s16(-1, 1, 1), v3s16(-1, 1, -1), - v3s16(1, 1, -1)}; + static const v3s16 dirs[16] = { + v3s16( 0, 0, 1), + v3s16( 0, 0, -1), + v3s16( 1, 0, 0), + v3s16(-1, 0, 0), + v3s16( 1, 0, 1), + v3s16(-1, 0, 1), + v3s16(-1, 0, -1), + v3s16( 1, 0, -1), + + v3s16( 0, 1, 1), + v3s16( 0, 1, -1), + v3s16( 1, 1, 0), + v3s16(-1, 1, 0), + v3s16( 1, 1, 1), + v3s16(-1, 1, 1), + v3s16(-1, 1, -1), + v3s16( 1, 1, -1) + }; // Check these 16 neighbouring nodes for enough spawnby nodes for (size_t i = 0; i != ARRLEN(dirs); i++) { @@ -109,6 +133,7 @@ bool Decoration::canPlaceDecoration(MMVManip *vm, v3s16 p) return true; } + size_t Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { PcgRandom ps(blockseed + 53); @@ -123,144 +148,132 @@ size_t Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) int area = sidelen * sidelen; for (s16 z0 = 0; z0 < divlen; z0++) - for (s16 x0 = 0; x0 < divlen; x0++) { - v2s16 p2d_center( // Center position of part of division - nmin.X + sidelen / 2 + sidelen * x0, - nmin.Z + sidelen / 2 + sidelen * z0); - v2s16 p2d_min( // Minimum edge of part of division - nmin.X + sidelen * x0, nmin.Z + sidelen * z0); - v2s16 p2d_max( // Maximum edge of part of division - nmin.X + sidelen + sidelen * x0 - 1, - nmin.Z + sidelen + sidelen * z0 - 1); - - bool cover = false; - // Amount of decorations - float nval = (flags & DECO_USE_NOISE) - ? NoisePerlin2D(&np, p2d_center.X, - p2d_center.Y, - mapseed) - : fill_ratio; - u32 deco_count = 0; - - if (nval >= 10.0f) { - // Complete coverage. Disable random placement to avoid - // redundant multiple placements at one position. - cover = true; - deco_count = area; + for (s16 x0 = 0; x0 < divlen; x0++) { + v2s16 p2d_center( // Center position of part of division + nmin.X + sidelen / 2 + sidelen * x0, + nmin.Z + sidelen / 2 + sidelen * z0 + ); + v2s16 p2d_min( // Minimum edge of part of division + nmin.X + sidelen * x0, + nmin.Z + sidelen * z0 + ); + v2s16 p2d_max( // Maximum edge of part of division + nmin.X + sidelen + sidelen * x0 - 1, + nmin.Z + sidelen + sidelen * z0 - 1 + ); + + bool cover = false; + // Amount of decorations + float nval = (flags & DECO_USE_NOISE) ? + NoisePerlin2D(&np, p2d_center.X, p2d_center.Y, mapseed) : + fill_ratio; + u32 deco_count = 0; + + if (nval >= 10.0f) { + // Complete coverage. Disable random placement to avoid + // redundant multiple placements at one position. + cover = true; + deco_count = area; + } else { + float deco_count_f = (float)area * nval; + if (deco_count_f >= 1.0f) { + deco_count = deco_count_f; + } else if (deco_count_f > 0.0f) { + // For very low density calculate a chance for 1 decoration + if (ps.range(1000) <= deco_count_f * 1000.0f) + deco_count = 1; + } + } + + s16 x = p2d_min.X - 1; + s16 z = p2d_min.Y; + + for (u32 i = 0; i < deco_count; i++) { + if (!cover) { + x = ps.range(p2d_min.X, p2d_max.X); + z = ps.range(p2d_min.Y, p2d_max.Y); } else { - float deco_count_f = (float)area * nval; - if (deco_count_f >= 1.0f) { - deco_count = deco_count_f; - } else if (deco_count_f > 0.0f) { - // For very low density calculate a chance for 1 - // decoration - if (ps.range(1000) <= deco_count_f * 1000.0f) - deco_count = 1; + x++; + if (x == p2d_max.X + 1) { + z++; + x = p2d_min.X; } } - - s16 x = p2d_min.X - 1; - s16 z = p2d_min.Y; - - for (u32 i = 0; i < deco_count; i++) { - if (!cover) { - x = ps.range(p2d_min.X, p2d_max.X); - z = ps.range(p2d_min.Y, p2d_max.Y); - } else { - x++; - if (x == p2d_max.X + 1) { - z++; - x = p2d_min.X; - } + int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X); + + if ((flags & DECO_ALL_FLOORS) || + (flags & DECO_ALL_CEILINGS)) { + // All-surfaces decorations + // Check biome of column + if (mg->biomemap && !biomes.empty()) { + auto iter = biomes.find(mg->biomemap[mapindex]); + if (iter == biomes.end()) + continue; } - int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X); - - if ((flags & DECO_ALL_FLOORS) || - (flags & DECO_ALL_CEILINGS)) { - // All-surfaces decorations - // Check biome of column - if (mg->biomemap && !biomes.empty()) { - auto iter = biomes.find( - mg->biomemap[mapindex]); - if (iter == biomes.end()) - continue; - } - // Get all floors and ceilings in node column - u16 size = (nmax.Y - nmin.Y + 1) / 2; - std::vector floors; - std::vector ceilings; - floors.reserve(size); - ceilings.reserve(size); - - mg->getSurfaces(v2s16(x, z), nmin.Y, nmax.Y, - floors, ceilings); - - if (flags & DECO_ALL_FLOORS) { - // Floor decorations - for (const s16 y : floors) { - if (y < y_min || y > y_max) - continue; - - v3s16 pos(x, y, z); - if (generate(mg->vm, &ps, pos, - false)) - mg->gennotify.addEvent( - GENNOTIFY_DECORATION, - pos, - index); - } - } + // Get all floors and ceilings in node column + u16 size = (nmax.Y - nmin.Y + 1) / 2; + std::vector floors; + std::vector ceilings; + floors.reserve(size); + ceilings.reserve(size); - if (flags & DECO_ALL_CEILINGS) { - // Ceiling decorations - for (const s16 y : ceilings) { - if (y < y_min || y > y_max) - continue; - - v3s16 pos(x, y, z); - if (generate(mg->vm, &ps, pos, - true)) - mg->gennotify.addEvent( - GENNOTIFY_DECORATION, - pos, - index); - } - } - } else { // Heightmap decorations - s16 y = -MAX_MAP_GENERATION_LIMIT; - if (flags & DECO_LIQUID_SURFACE) - y = mg->findLiquidSurface(v2s16(x, z), - nmin.Y, nmax.Y); - else if (mg->heightmap) - y = mg->heightmap[mapindex]; - else - y = mg->findGroundLevel(v2s16(x, z), - nmin.Y, nmax.Y); - - if (y < y_min || y > y_max || y < nmin.Y || - y > nmax.Y) - continue; + mg->getSurfaces(v2s16(x, z), nmin.Y, nmax.Y, floors, ceilings); - if (mg->biomemap && !biomes.empty()) { - auto iter = biomes.find( - mg->biomemap[mapindex]); - if (iter == biomes.end()) + if (flags & DECO_ALL_FLOORS) { + // Floor decorations + for (const s16 y : floors) { + if (y < y_min || y > y_max) continue; + + v3s16 pos(x, y, z); + if (generate(mg->vm, &ps, pos, false)) + mg->gennotify.addEvent( + GENNOTIFY_DECORATION, pos, index); } + } + + if (flags & DECO_ALL_CEILINGS) { + // Ceiling decorations + for (const s16 y : ceilings) { + if (y < y_min || y > y_max) + continue; - v3s16 pos(x, y, z); - if (generate(mg->vm, &ps, pos, false)) - mg->gennotify.addEvent( - GENNOTIFY_DECORATION, pos, - index); + v3s16 pos(x, y, z); + if (generate(mg->vm, &ps, pos, true)) + mg->gennotify.addEvent( + GENNOTIFY_DECORATION, pos, index); + } + } + } else { // Heightmap decorations + s16 y = -MAX_MAP_GENERATION_LIMIT; + if (flags & DECO_LIQUID_SURFACE) + y = mg->findLiquidSurface(v2s16(x, z), nmin.Y, nmax.Y); + else if (mg->heightmap) + y = mg->heightmap[mapindex]; + else + y = mg->findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y); + + if (y < y_min || y > y_max || y < nmin.Y || y > nmax.Y) + continue; + + if (mg->biomemap && !biomes.empty()) { + auto iter = biomes.find(mg->biomemap[mapindex]); + if (iter == biomes.end()) + continue; } + + v3s16 pos(x, y, z); + if (generate(mg->vm, &ps, pos, false)) + mg->gennotify.addEvent(GENNOTIFY_DECORATION, pos, index); } } + } return 0; } + void Decoration::cloneTo(Decoration *def) const { ObjDef::cloneTo(def); @@ -278,8 +291,10 @@ void Decoration::cloneTo(Decoration *def) const def->biomes = biomes; } + /////////////////////////////////////////////////////////////////////////////// + ObjDef *DecoSimple::clone() const { auto def = new DecoSimple(); @@ -294,12 +309,14 @@ ObjDef *DecoSimple::clone() const return def; } + void DecoSimple::resolveNodeNames() { Decoration::resolveNodeNames(); getIdsFromNrBacklog(&c_decos); } + size_t DecoSimple::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) { // Don't bother if there aren't any decorations to place @@ -330,10 +347,10 @@ size_t DecoSimple::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) } content_t c_place = c_decos[pr->range(0, c_decos.size() - 1)]; - s16 height = (deco_height_max > 0) ? pr->range(deco_height, deco_height_max) - : deco_height; - u8 param2 = (deco_param2_max > 0) ? pr->range(deco_param2, deco_param2_max) - : deco_param2; + s16 height = (deco_height_max > 0) ? + pr->range(deco_height, deco_height_max) : deco_height; + u8 param2 = (deco_param2_max > 0) ? + pr->range(deco_param2, deco_param2_max) : deco_param2; bool force_placement = (flags & DECO_FORCE_PLACEMENT); const v3s16 &em = vm->m_area.getExtent(); @@ -368,14 +385,17 @@ size_t DecoSimple::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) return 1; } + /////////////////////////////////////////////////////////////////////////////// + DecoSchematic::~DecoSchematic() { if (was_cloned) delete schematic; } + ObjDef *DecoSchematic::clone() const { auto def = new DecoSchematic(); @@ -387,12 +407,13 @@ ObjDef *DecoSchematic::clone() const * and not a handle. We are left with no option but to clone it ourselves. * This is a waste of memory and should be replaced with an alternative * approach sometime. */ - def->schematic = dynamic_cast(schematic->clone()); + def->schematic = dynamic_cast(schematic->clone()); def->was_cloned = true; return def; } + size_t DecoSchematic::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceiling) { // Schematic could have been unloaded but not the decoration @@ -422,9 +443,8 @@ size_t DecoSchematic::generate(MMVManip *vm, PcgRandom *pr, v3s16 p, bool ceilin if (p.Y < vm->m_area.MinEdge.Y) return 0; - Rotation rot = (rotation == ROTATE_RAND) - ? (Rotation)pr->range(ROTATE_0, ROTATE_270) - : rotation; + Rotation rot = (rotation == ROTATE_RAND) ? + (Rotation)pr->range(ROTATE_0, ROTATE_270) : rotation; if (flags & DECO_PLACE_CENTER_X) { if (rot == ROTATE_0 || rot == ROTATE_180) diff --git a/src/mapgen/mg_decoration.h b/src/mapgen/mg_decoration.h index c0cd4af9f..1ea02a527 100644 --- a/src/mapgen/mg_decoration.h +++ b/src/mapgen/mg_decoration.h @@ -25,33 +25,32 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "noise.h" #include "nodedef.h" -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class Mapgen; class MMVManip; class PcgRandom; class Schematic; -enum DecorationType -{ +enum DecorationType { DECO_SIMPLE, DECO_SCHEMATIC, DECO_LSYSTEM }; -#define DECO_PLACE_CENTER_X 0x01 -#define DECO_PLACE_CENTER_Y 0x02 -#define DECO_PLACE_CENTER_Z 0x04 -#define DECO_USE_NOISE 0x08 +#define DECO_PLACE_CENTER_X 0x01 +#define DECO_PLACE_CENTER_Y 0x02 +#define DECO_PLACE_CENTER_Z 0x04 +#define DECO_USE_NOISE 0x08 #define DECO_FORCE_PLACEMENT 0x10 -#define DECO_LIQUID_SURFACE 0x20 -#define DECO_ALL_FLOORS 0x40 -#define DECO_ALL_CEILINGS 0x80 +#define DECO_LIQUID_SURFACE 0x20 +#define DECO_ALL_FLOORS 0x40 +#define DECO_ALL_CEILINGS 0x80 extern FlagDesc flagdesc_deco[]; -class Decoration : public ObjDef, public NodeResolver -{ + +class Decoration : public ObjDef, public NodeResolver { public: Decoration() = default; virtual ~Decoration() = default; @@ -81,8 +80,8 @@ class Decoration : public ObjDef, public NodeResolver void cloneTo(Decoration *def) const; }; -class DecoSimple : public Decoration -{ + +class DecoSimple : public Decoration { public: ObjDef *clone() const; @@ -96,8 +95,8 @@ class DecoSimple : public Decoration u8 deco_param2_max; }; -class DecoSchematic : public Decoration -{ + +class DecoSchematic : public Decoration { public: ObjDef *clone() const; @@ -111,6 +110,7 @@ class DecoSchematic : public Decoration bool was_cloned = false; // see FIXME inside DecoSchemtic::clone() }; + /* class DecoLSystem : public Decoration { public: @@ -118,15 +118,18 @@ class DecoLSystem : public Decoration { }; */ -class DecorationManager : public ObjDefManager -{ + +class DecorationManager : public ObjDefManager { public: DecorationManager(IGameDef *gamedef); virtual ~DecorationManager() = default; DecorationManager *clone() const; - const char *getObjectTitle() const { return "decoration"; } + const char *getObjectTitle() const + { + return "decoration"; + } static Decoration *create(DecorationType type) { @@ -135,7 +138,7 @@ class DecorationManager : public ObjDefManager return new DecoSimple; case DECO_SCHEMATIC: return new DecoSchematic; - // case DECO_LSYSTEM: + //case DECO_LSYSTEM: // return new DecoLSystem; default: return NULL; @@ -145,5 +148,5 @@ class DecorationManager : public ObjDefManager size_t placeAllDecos(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); private: - DecorationManager(){}; + DecorationManager() {}; }; diff --git a/src/mapgen/mg_ore.cpp b/src/mapgen/mg_ore.cpp index 5af8e31e4..b50ed6a32 100644 --- a/src/mapgen/mg_ore.cpp +++ b/src/mapgen/mg_ore.cpp @@ -27,16 +27,24 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -FlagDesc flagdesc_ore[] = {{"absheight", OREFLAG_ABSHEIGHT}, // Non-functional - {"puff_cliffs", OREFLAG_PUFF_CLIFFS}, - {"puff_additive_composition", OREFLAG_PUFF_ADDITIVE}, {NULL, 0}}; + +FlagDesc flagdesc_ore[] = { + {"absheight", OREFLAG_ABSHEIGHT}, // Non-functional + {"puff_cliffs", OREFLAG_PUFF_CLIFFS}, + {"puff_additive_composition", OREFLAG_PUFF_ADDITIVE}, + {NULL, 0} +}; + /////////////////////////////////////////////////////////////////////////////// -OreManager::OreManager(IGameDef *gamedef) : ObjDefManager(gamedef, OBJDEF_ORE) + +OreManager::OreManager(IGameDef *gamedef) : + ObjDefManager(gamedef, OBJDEF_ORE) { } + size_t OreManager::placeAllOres(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { size_t nplaced = 0; @@ -53,15 +61,17 @@ size_t OreManager::placeAllOres(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nma return nplaced; } + void OreManager::clear() { for (ObjDef *object : m_objects) { - Ore *ore = (Ore *)object; + Ore *ore = (Ore *) object; delete ore; } m_objects.clear(); } + OreManager *OreManager::clone() const { auto mgr = new OreManager(); @@ -69,19 +79,23 @@ OreManager *OreManager::clone() const return mgr; } + /////////////////////////////////////////////////////////////////////////////// + Ore::~Ore() { delete noise; } + void Ore::resolveNodeNames() { getIdFromNrBacklog(&c_ore, "", CONTENT_AIR); getIdsFromNrBacklog(&c_wherein); } + size_t Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { if (nmin.Y > y_max || nmax.Y < y_min) @@ -99,6 +113,7 @@ size_t Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) return 1; } + void Ore::cloneTo(Ore *def) const { ObjDef::cloneTo(def); @@ -118,8 +133,10 @@ void Ore::cloneTo(Ore *def) const def->biomes = biomes; } + /////////////////////////////////////////////////////////////////////////////// + ObjDef *OreScatter::clone() const { auto def = new OreScatter(); @@ -127,17 +144,19 @@ ObjDef *OreScatter::clone() const return def; } -void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap) + +void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed); MapNode n_ore(c_ore, 0, ore_param2); - u32 sizex = (nmax.X - nmin.X + 1); - u32 volume = (nmax.X - nmin.X + 1) * (nmax.Y - nmin.Y + 1) * - (nmax.Z - nmin.Z + 1); - u32 csize = clust_size; - u32 cvolume = csize * csize * csize; + u32 sizex = (nmax.X - nmin.X + 1); + u32 volume = (nmax.X - nmin.X + 1) * + (nmax.Y - nmin.Y + 1) * + (nmax.Z - nmin.Z + 1); + u32 csize = clust_size; + u32 cvolume = csize * csize * csize; u32 nclusters = volume / clust_scarcity; for (u32 i = 0; i != nclusters; i++) { @@ -146,7 +165,7 @@ void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, int z0 = pr.range(nmin.Z, nmax.Z - csize + 1); if ((flags & OREFLAG_USE_NOISE) && - (NoisePerlin3D(&np, x0, y0, z0, mapseed) < nthresh)) + (NoisePerlin3D(&np, x0, y0, z0, mapseed) < nthresh)) continue; if (biomemap && !biomes.empty()) { @@ -157,24 +176,24 @@ void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, } for (u32 z1 = 0; z1 != csize; z1++) - for (u32 y1 = 0; y1 != csize; y1++) - for (u32 x1 = 0; x1 != csize; x1++) { - if (pr.range(1, cvolume) > clust_num_ores) - continue; - - u32 i = vm->m_area.index( - x0 + x1, y0 + y1, z0 + z1); - if (!CONTAINS(c_wherein, - vm->m_data[i].getContent())) - continue; - - vm->m_data[i] = n_ore; - } + for (u32 y1 = 0; y1 != csize; y1++) + for (u32 x1 = 0; x1 != csize; x1++) { + if (pr.range(1, cvolume) > clust_num_ores) + continue; + + u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1); + if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) + continue; + + vm->m_data[i] = n_ore; + } } } + /////////////////////////////////////////////////////////////////////////////// + ObjDef *OreSheet::clone() const { auto def = new OreSheet(); @@ -187,8 +206,9 @@ ObjDef *OreSheet::clone() const return def; } -void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, - biome_t *biomemap) + +void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); @@ -197,8 +217,9 @@ void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3 int y_start_min = nmin.Y + max_height; int y_start_max = nmax.Y - max_height; - int y_start = y_start_min < y_start_max ? pr.range(y_start_min, y_start_max) - : (y_start_min + y_start_max) / 2; + int y_start = y_start_min < y_start_max ? + pr.range(y_start_min, y_start_max) : + (y_start_min + y_start_max) / 2; if (!noise) { int sx = nmax.X - nmin.X + 1; @@ -210,43 +231,45 @@ void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3 size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) - for (int x = nmin.X; x <= nmax.X; x++, index++) { - float noiseval = noise->result[index]; - if (noiseval < nthresh) - continue; + for (int x = nmin.X; x <= nmax.X; x++, index++) { + float noiseval = noise->result[index]; + if (noiseval < nthresh) + continue; - if (biomemap && !biomes.empty()) { - auto it = biomes.find(biomemap[index]); - if (it == biomes.end()) - continue; - } + if (biomemap && !biomes.empty()) { + auto it = biomes.find(biomemap[index]); + if (it == biomes.end()) + continue; + } - u16 height = pr.range(column_height_min, column_height_max); - int ymidpoint = y_start + noiseval; - int y0 = MYMAX(nmin.Y, - ymidpoint - height * (1 - column_midpoint_factor)); - int y1 = MYMIN(nmax.Y, y0 + height - 1); + u16 height = pr.range(column_height_min, column_height_max); + int ymidpoint = y_start + noiseval; + int y0 = MYMAX(nmin.Y, ymidpoint - height * (1 - column_midpoint_factor)); + int y1 = MYMIN(nmax.Y, y0 + height - 1); - for (int y = y0; y <= y1; y++) { - u32 i = vm->m_area.index(x, y, z); - if (!vm->m_area.contains(i)) - continue; - if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) - continue; + for (int y = y0; y <= y1; y++) { + u32 i = vm->m_area.index(x, y, z); + if (!vm->m_area.contains(i)) + continue; + if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) + continue; - vm->m_data[i] = n_ore; - } + vm->m_data[i] = n_ore; } + } } + /////////////////////////////////////////////////////////////////////////////// + OrePuff::~OrePuff() { delete noise_puff_top; delete noise_puff_bottom; } + ObjDef *OrePuff::clone() const { auto def = new OrePuff(); @@ -260,8 +283,9 @@ ObjDef *OrePuff::clone() const return def; } -void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, - biome_t *biomemap) + +void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); @@ -282,55 +306,57 @@ void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) - for (int x = nmin.X; x <= nmax.X; x++, index++) { - float noiseval = noise->result[index]; - if (noiseval < nthresh) - continue; + for (int x = nmin.X; x <= nmax.X; x++, index++) { + float noiseval = noise->result[index]; + if (noiseval < nthresh) + continue; - if (biomemap && !biomes.empty()) { - auto it = biomes.find(biomemap[index]); - if (it == biomes.end()) - continue; - } + if (biomemap && !biomes.empty()) { + auto it = biomes.find(biomemap[index]); + if (it == biomes.end()) + continue; + } - if (!noise_generated) { - noise_generated = true; - noise_puff_top->perlinMap2D(nmin.X, nmin.Z); - noise_puff_bottom->perlinMap2D(nmin.X, nmin.Z); - } + if (!noise_generated) { + noise_generated = true; + noise_puff_top->perlinMap2D(nmin.X, nmin.Z); + noise_puff_bottom->perlinMap2D(nmin.X, nmin.Z); + } - float ntop = noise_puff_top->result[index]; - float nbottom = noise_puff_bottom->result[index]; + float ntop = noise_puff_top->result[index]; + float nbottom = noise_puff_bottom->result[index]; - if (!(flags & OREFLAG_PUFF_CLIFFS)) { - float ndiff = noiseval - nthresh; - if (ndiff < 1.0f) { - ntop *= ndiff; - nbottom *= ndiff; - } + if (!(flags & OREFLAG_PUFF_CLIFFS)) { + float ndiff = noiseval - nthresh; + if (ndiff < 1.0f) { + ntop *= ndiff; + nbottom *= ndiff; } + } - int ymid = y_start; - int y0 = ymid - nbottom; - int y1 = ymid + ntop; + int ymid = y_start; + int y0 = ymid - nbottom; + int y1 = ymid + ntop; - if ((flags & OREFLAG_PUFF_ADDITIVE) && (y0 > y1)) - SWAP(int, y0, y1); + if ((flags & OREFLAG_PUFF_ADDITIVE) && (y0 > y1)) + SWAP(int, y0, y1); - for (int y = y0; y <= y1; y++) { - u32 i = vm->m_area.index(x, y, z); - if (!vm->m_area.contains(i)) - continue; - if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) - continue; + for (int y = y0; y <= y1; y++) { + u32 i = vm->m_area.index(x, y, z); + if (!vm->m_area.contains(i)) + continue; + if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) + continue; - vm->m_data[i] = n_ore; - } + vm->m_data[i] = n_ore; } + } } + /////////////////////////////////////////////////////////////////////////////// + ObjDef *OreBlob::clone() const { auto def = new OreBlob(); @@ -338,16 +364,18 @@ ObjDef *OreBlob::clone() const return def; } -void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, - biome_t *biomemap) + +void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 2404); MapNode n_ore(c_ore, 0, ore_param2); - u32 sizex = (nmax.X - nmin.X + 1); - u32 volume = (nmax.X - nmin.X + 1) * (nmax.Y - nmin.Y + 1) * - (nmax.Z - nmin.Z + 1); - u32 csize = clust_size; + u32 sizex = (nmax.X - nmin.X + 1); + u32 volume = (nmax.X - nmin.X + 1) * + (nmax.Y - nmin.Y + 1) * + (nmax.Z - nmin.Z + 1); + u32 csize = clust_size; u32 nblobs = volume / clust_scarcity; if (!noise) @@ -370,48 +398,45 @@ void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s size_t index = 0; for (u32 z1 = 0; z1 != csize; z1++) - for (u32 y1 = 0; y1 != csize; y1++) - for (u32 x1 = 0; x1 != csize; x1++, index++) { - u32 i = vm->m_area.index( - x0 + x1, y0 + y1, z0 + z1); - if (!CONTAINS(c_wherein, - vm->m_data[i].getContent())) - continue; - - // Lazily generate noise only if there's a chance - // of ore being placed This simple optimization - // makes calls 6x faster on average - if (!noise_generated) { - noise_generated = true; - noise->perlinMap3D(x0, y0, z0); - } - - float noiseval = noise->result[index]; - - float xdist = (s32)x1 - (s32)csize / 2; - float ydist = (s32)y1 - (s32)csize / 2; - float zdist = (s32)z1 - (s32)csize / 2; - - noiseval -= std::sqrt(xdist * xdist + - ydist * ydist + - zdist * zdist) / - csize; - - if (noiseval < nthresh) - continue; - - vm->m_data[i] = n_ore; - } + for (u32 y1 = 0; y1 != csize; y1++) + for (u32 x1 = 0; x1 != csize; x1++, index++) { + u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1); + if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) + continue; + + // Lazily generate noise only if there's a chance of ore being placed + // This simple optimization makes calls 6x faster on average + if (!noise_generated) { + noise_generated = true; + noise->perlinMap3D(x0, y0, z0); + } + + float noiseval = noise->result[index]; + + float xdist = (s32)x1 - (s32)csize / 2; + float ydist = (s32)y1 - (s32)csize / 2; + float zdist = (s32)z1 - (s32)csize / 2; + + noiseval -= std::sqrt(xdist * xdist + ydist * ydist + zdist * zdist) / csize; + + if (noiseval < nthresh) + continue; + + vm->m_data[i] = n_ore; + } } } + /////////////////////////////////////////////////////////////////////////////// + OreVein::~OreVein() { delete noise2; } + ObjDef *OreVein::clone() const { auto def = new OreVein(); @@ -424,8 +449,9 @@ ObjDef *OreVein::clone() const return def; } -void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, - biome_t *biomemap) + +void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 520); MapNode n_ore(c_ore, 0, ore_param2); @@ -441,7 +467,7 @@ void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s delete noise; delete noise2; int sizez = nmax.Z - nmin.Z + 1; - noise = new Noise(&np, mapseed, sizex, sizey, sizez); + noise = new Noise(&np, mapseed, sizex, sizey, sizez); noise2 = new Noise(&np, mapseed + 436, sizex, sizey, sizez); sizey_prev = sizey; } @@ -449,48 +475,49 @@ void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s bool noise_generated = false; size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) - for (int y = nmin.Y; y <= nmax.Y; y++) - for (int x = nmin.X; x <= nmax.X; x++, index++) { - u32 i = vm->m_area.index(x, y, z); - if (!vm->m_area.contains(i)) - continue; - if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) - continue; - - if (biomemap && !biomes.empty()) { - u32 bmapidx = sizex * (z - nmin.Z) + (x - nmin.X); - auto it = biomes.find(biomemap[bmapidx]); - if (it == biomes.end()) - continue; - } - - // Same lazy generation optimization as in OreBlob - if (!noise_generated) { - noise_generated = true; - noise->perlinMap3D(nmin.X, nmin.Y, nmin.Z); - noise2->perlinMap3D(nmin.X, nmin.Y, nmin.Z); - } - - // randval ranges from -1..1 - float randval = (float)pr.next() / (pr.RANDOM_RANGE / 2) - - 1.f; - float noiseval = contour(noise->result[index]); - float noiseval2 = contour(noise2->result[index]); - if (noiseval * noiseval2 + randval * random_factor < - nthresh) - continue; - - vm->m_data[i] = n_ore; - } + for (int y = nmin.Y; y <= nmax.Y; y++) + for (int x = nmin.X; x <= nmax.X; x++, index++) { + u32 i = vm->m_area.index(x, y, z); + if (!vm->m_area.contains(i)) + continue; + if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) + continue; + + if (biomemap && !biomes.empty()) { + u32 bmapidx = sizex * (z - nmin.Z) + (x - nmin.X); + auto it = biomes.find(biomemap[bmapidx]); + if (it == biomes.end()) + continue; + } + + // Same lazy generation optimization as in OreBlob + if (!noise_generated) { + noise_generated = true; + noise->perlinMap3D(nmin.X, nmin.Y, nmin.Z); + noise2->perlinMap3D(nmin.X, nmin.Y, nmin.Z); + } + + // randval ranges from -1..1 + float randval = (float)pr.next() / (pr.RANDOM_RANGE / 2) - 1.f; + float noiseval = contour(noise->result[index]); + float noiseval2 = contour(noise2->result[index]); + if (noiseval * noiseval2 + randval * random_factor < nthresh) + continue; + + vm->m_data[i] = n_ore; + } } + /////////////////////////////////////////////////////////////////////////////// + OreStratum::~OreStratum() { delete noise_stratum_thickness; } + ObjDef *OreStratum::clone() const { auto def = new OreStratum(); @@ -503,8 +530,9 @@ ObjDef *OreStratum::clone() const return def; } -void OreStratum::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap) + +void OreStratum::generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); @@ -522,8 +550,7 @@ void OreStratum::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, if (!noise_stratum_thickness) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; - noise_stratum_thickness = - new Noise(&np_stratum_thickness, 0, sx, sz); + noise_stratum_thickness = new Noise(&np_stratum_thickness, 0, sx, sz); } noise_stratum_thickness->perlinMap2D(nmin.X, nmin.Z); } @@ -531,41 +558,39 @@ void OreStratum::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) - for (int x = nmin.X; x <= nmax.X; x++, index++) { - if (biomemap && !biomes.empty()) { - auto it = biomes.find(biomemap[index]); - if (it == biomes.end()) - continue; - } + for (int x = nmin.X; x <= nmax.X; x++, index++) { + if (biomemap && !biomes.empty()) { + auto it = biomes.find(biomemap[index]); + if (it == biomes.end()) + continue; + } - int y0; - int y1; - - if (flags & OREFLAG_USE_NOISE) { - float nhalfthick = - ((flags & OREFLAG_USE_NOISE2) ? noise_stratum_thickness - ->result[index] - : (float)stratum_thickness) / - 2.0f; - float nmid = noise->result[index]; - y0 = MYMAX(nmin.Y, std::ceil(nmid - nhalfthick)); - y1 = MYMIN(nmax.Y, nmid + nhalfthick); - } else { // Simple horizontal stratum - y0 = nmin.Y; - y1 = nmax.Y; - } + int y0; + int y1; + + if (flags & OREFLAG_USE_NOISE) { + float nhalfthick = ((flags & OREFLAG_USE_NOISE2) ? + noise_stratum_thickness->result[index] : (float)stratum_thickness) / + 2.0f; + float nmid = noise->result[index]; + y0 = MYMAX(nmin.Y, std::ceil(nmid - nhalfthick)); + y1 = MYMIN(nmax.Y, nmid + nhalfthick); + } else { // Simple horizontal stratum + y0 = nmin.Y; + y1 = nmax.Y; + } - for (int y = y0; y <= y1; y++) { - if (pr.range(1, clust_scarcity) != 1) - continue; + for (int y = y0; y <= y1; y++) { + if (pr.range(1, clust_scarcity) != 1) + continue; - u32 i = vm->m_area.index(x, y, z); - if (!vm->m_area.contains(i)) - continue; - if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) - continue; + u32 i = vm->m_area.index(x, y, z); + if (!vm->m_area.contains(i)) + continue; + if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) + continue; - vm->m_data[i] = n_ore; - } + vm->m_data[i] = n_ore; } + } } diff --git a/src/mapgen/mg_ore.h b/src/mapgen/mg_ore.h index e2053a274..76420fab4 100644 --- a/src/mapgen/mg_ore.h +++ b/src/mapgen/mg_ore.h @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "noise.h" #include "nodedef.h" -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class Noise; class Mapgen; @@ -33,14 +33,13 @@ class MMVManip; /////////////////// Ore generation flags -#define OREFLAG_ABSHEIGHT 0x01 // Non-functional but kept to not break flags -#define OREFLAG_PUFF_CLIFFS 0x02 +#define OREFLAG_ABSHEIGHT 0x01 // Non-functional but kept to not break flags +#define OREFLAG_PUFF_CLIFFS 0x02 #define OREFLAG_PUFF_ADDITIVE 0x04 -#define OREFLAG_USE_NOISE 0x08 -#define OREFLAG_USE_NOISE2 0x10 +#define OREFLAG_USE_NOISE 0x08 +#define OREFLAG_USE_NOISE2 0x10 -enum OreType -{ +enum OreType { ORE_SCATTER, ORE_SHEET, ORE_PUFF, @@ -51,54 +50,48 @@ enum OreType extern FlagDesc flagdesc_ore[]; -class Ore : public ObjDef, public NodeResolver -{ +class Ore : public ObjDef, public NodeResolver { public: static const bool NEEDS_NOISE = false; - content_t c_ore; // the node to place + content_t c_ore; // the node to place std::vector c_wherein; // the nodes to be placed in - u32 clust_scarcity; // ore cluster has a 1-in-clust_scarcity chance of appearing - // at a node + u32 clust_scarcity; // ore cluster has a 1-in-clust_scarcity chance of appearing at a node s16 clust_num_ores; // how many ore nodes are in a chunk - s16 clust_size; // how large (in nodes) a chunk of ore is + s16 clust_size; // how large (in nodes) a chunk of ore is s16 y_min; s16 y_max; - u8 ore_param2; // to set node-specific attributes - u32 flags = 0; // attributes for this ore - float nthresh; // threshold for noise at which an ore is placed - NoiseParams np; // noise for distribution of clusters (NULL for uniform - // scattering) + u8 ore_param2; // to set node-specific attributes + u32 flags = 0; // attributes for this ore + float nthresh; // threshold for noise at which an ore is placed + NoiseParams np; // noise for distribution of clusters (NULL for uniform scattering) Noise *noise = nullptr; std::unordered_set biomes; - Ore() = default; - ; + Ore() = default;; virtual ~Ore(); virtual void resolveNodeNames(); size_t placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap) = 0; + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) = 0; protected: void cloneTo(Ore *def) const; }; -class OreScatter : public Ore -{ +class OreScatter : public Ore { public: static const bool NEEDS_NOISE = false; ObjDef *clone() const; - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap); + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap); }; -class OreSheet : public Ore -{ +class OreSheet : public Ore { public: static const bool NEEDS_NOISE = true; @@ -108,12 +101,11 @@ class OreSheet : public Ore u16 column_height_max; float column_midpoint_factor; - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap); + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap); }; -class OrePuff : public Ore -{ +class OrePuff : public Ore { public: static const bool NEEDS_NOISE = true; @@ -127,23 +119,21 @@ class OrePuff : public Ore OrePuff() = default; virtual ~OrePuff(); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap); + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap); }; -class OreBlob : public Ore -{ +class OreBlob : public Ore { public: static const bool NEEDS_NOISE = true; ObjDef *clone() const; - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap); + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap); }; -class OreVein : public Ore -{ +class OreVein : public Ore { public: static const bool NEEDS_NOISE = true; @@ -156,12 +146,11 @@ class OreVein : public Ore OreVein() = default; virtual ~OreVein(); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap); + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap); }; -class OreStratum : public Ore -{ +class OreStratum : public Ore { public: static const bool NEEDS_NOISE = false; @@ -174,19 +163,21 @@ class OreStratum : public Ore OreStratum() = default; virtual ~OreStratum(); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, - v3s16 nmax, biome_t *biomemap); + virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap); }; -class OreManager : public ObjDefManager -{ +class OreManager : public ObjDefManager { public: OreManager(IGameDef *gamedef); virtual ~OreManager() = default; OreManager *clone() const; - const char *getObjectTitle() const { return "ore"; } + const char *getObjectTitle() const + { + return "ore"; + } static Ore *create(OreType type) { @@ -213,5 +204,5 @@ class OreManager : public ObjDefManager size_t placeAllOres(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax); private: - OreManager(){}; + OreManager() {}; }; diff --git a/src/mapgen/mg_schematic.cpp b/src/mapgen/mg_schematic.cpp index 598c044d6..ba102d997 100644 --- a/src/mapgen/mg_schematic.cpp +++ b/src/mapgen/mg_schematic.cpp @@ -35,11 +35,14 @@ with this program; if not, write to the Free Software Foundation, Inc., /////////////////////////////////////////////////////////////////////////////// + SchematicManager::SchematicManager(Server *server) : - ObjDefManager(server, OBJDEF_SCHEMATIC), m_server(server) + ObjDefManager(server, OBJDEF_SCHEMATIC), + m_server(server) { } + SchematicManager *SchematicManager::clone() const { auto mgr = new SchematicManager(); @@ -48,6 +51,7 @@ SchematicManager *SchematicManager::clone() const return mgr; } + void SchematicManager::clear() { EmergeManager *emerge = m_server->getEmergeManager(); @@ -68,14 +72,18 @@ void SchematicManager::clear() ObjDefManager::clear(); } + /////////////////////////////////////////////////////////////////////////////// -Schematic::Schematic() = default; + +Schematic::Schematic() += default; + Schematic::~Schematic() { - delete[] schemdata; - delete[] slice_probs; + delete []schemdata; + delete []slice_probs; } ObjDef *Schematic::clone() const @@ -97,6 +105,7 @@ ObjDef *Schematic::clone() const return def; } + void Schematic::resolveNodeNames() { getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR); @@ -109,6 +118,7 @@ void Schematic::resolveNodeNames() } } + void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place) { assert(schemdata && slice_probs); @@ -124,33 +134,33 @@ void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_pla int i_start, i_step_x, i_step_z; switch (rot) { - case ROTATE_90: - i_start = sx - 1; - i_step_x = zstride; - i_step_z = -xstride; - SWAP(s16, sx, sz); - break; - case ROTATE_180: - i_start = zstride * (sz - 1) + sx - 1; - i_step_x = -xstride; - i_step_z = -zstride; - break; - case ROTATE_270: - i_start = zstride * (sz - 1); - i_step_x = -zstride; - i_step_z = xstride; - SWAP(s16, sx, sz); - break; - default: - i_start = 0; - i_step_x = xstride; - i_step_z = zstride; + case ROTATE_90: + i_start = sx - 1; + i_step_x = zstride; + i_step_z = -xstride; + SWAP(s16, sx, sz); + break; + case ROTATE_180: + i_start = zstride * (sz - 1) + sx - 1; + i_step_x = -xstride; + i_step_z = -zstride; + break; + case ROTATE_270: + i_start = zstride * (sz - 1); + i_step_x = -zstride; + i_step_z = xstride; + SWAP(s16, sx, sz); + break; + default: + i_start = 0; + i_step_x = xstride; + i_step_z = zstride; } s16 y_map = p.Y; for (s16 y = 0; y != sy; y++) { if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) && - (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS))) + (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS))) continue; for (s16 z = 0; z != sz; z++) { @@ -163,10 +173,8 @@ void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_pla if (schemdata[i].getContent() == CONTENT_IGNORE) continue; - u8 placement_prob = - schemdata[i].param1 & MTSCHEM_PROB_MASK; - bool force_place_node = - schemdata[i].param1 & MTSCHEM_FORCE_PLACE; + u8 placement_prob = schemdata[i].param1 & MTSCHEM_PROB_MASK; + bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE; if (placement_prob == MTSCHEM_PROB_NEVER) continue; @@ -179,8 +187,7 @@ void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_pla } if ((placement_prob != MTSCHEM_PROB_ALWAYS) && - (placement_prob <= - myrand_range(1, MTSCHEM_PROB_ALWAYS))) + (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS))) continue; vm->m_data[vi] = schemdata[i]; @@ -194,8 +201,9 @@ void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_pla } } -bool Schematic::placeOnVManip( - MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place) + +bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags, + Rotation rot, bool force_place) { assert(vm != NULL); assert(schemdata && slice_probs); @@ -205,8 +213,8 @@ bool Schematic::placeOnVManip( if (rot == ROTATE_RAND) rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270); - v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X) - : size; + v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? + v3s16(size.Z, size.Y, size.X) : size; //// Adjust placement position if necessary if (flags & DECO_PLACE_CENTER_X) @@ -221,8 +229,8 @@ bool Schematic::placeOnVManip( return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1))); } -void Schematic::placeOnMap( - ServerMap *map, v3s16 p, u32 flags, Rotation rot, bool force_place) +void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags, + Rotation rot, bool force_place) { std::map lighting_modified_blocks; std::map modified_blocks; @@ -236,8 +244,8 @@ void Schematic::placeOnMap( if (rot == ROTATE_RAND) rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270); - v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X) - : size; + v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? + v3s16(size.Z, size.Y, size.X) : size; //// Adjust placement position if necessary if (flags & DECO_PLACE_CENTER_X) @@ -270,7 +278,9 @@ void Schematic::placeOnMap( map->dispatchEvent(event); } -bool Schematic::deserializeFromMts(std::istream *is, std::vector *names) + +bool Schematic::deserializeFromMts(std::istream *is, + std::vector *names) { std::istream &ss = *is; content_t cignore = CONTENT_IGNORE; @@ -279,20 +289,16 @@ bool Schematic::deserializeFromMts(std::istream *is, std::vector *n //// Read signature u32 signature = readU32(ss); if (signature != MTSCHEM_FILE_SIGNATURE) { - errorstream << __FUNCTION__ - << ": invalid schematic " - "file" - << std::endl; + errorstream << __FUNCTION__ << ": invalid schematic " + "file" << std::endl; return false; } //// Read version u16 version = readU16(ss); if (version > MTSCHEM_FILE_VER_HIGHEST_READ) { - errorstream << __FUNCTION__ - << ": unsupported schematic " - "file version" - << std::endl; + errorstream << __FUNCTION__ << ": unsupported schematic " + "file version" << std::endl; return false; } @@ -300,7 +306,7 @@ bool Schematic::deserializeFromMts(std::istream *is, std::vector *n size = readV3S16(ss); //// Read Y-slice probability values - delete[] slice_probs; + delete []slice_probs; slice_probs = new u8[size.Y]; for (int y = 0; y != size.Y; y++) slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD; @@ -324,11 +330,11 @@ bool Schematic::deserializeFromMts(std::istream *is, std::vector *n //// Read node data size_t nodecount = size.X * size.Y * size.Z; - delete[] schemdata; + delete []schemdata; schemdata = new MapNode[nodecount]; - MapNode::deSerializeBulk( - ss, SER_FMT_VER_HIGHEST_READ, schemdata, nodecount, 2, 2, true); + MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata, + nodecount, 2, 2, true); // Fix probability values for nodes that were ignore; removed in v2 if (version < 2) { @@ -351,16 +357,17 @@ bool Schematic::deserializeFromMts(std::istream *is, std::vector *n return true; } -bool Schematic::serializeToMts( - std::ostream *os, const std::vector &names) const + +bool Schematic::serializeToMts(std::ostream *os, + const std::vector &names) const { std::ostream &ss = *os; - writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature + writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version - writeV3S16(ss, size); // schematic size + writeV3S16(ss, size); // schematic size - for (int y = 0; y != size.Y; y++) // Y slice probabilities + for (int y = 0; y != size.Y; y++) // Y slice probabilities writeU8(ss, slice_probs[y]); writeU16(ss, names.size()); // name count @@ -368,14 +375,16 @@ bool Schematic::serializeToMts( ss << serializeString(names[i]); // node names // compressed bulk node data - MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, schemdata, - size.X * size.Y * size.Z, 2, 2, true); + MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, + schemdata, size.X * size.Y * size.Z, 2, 2, true); return true; } -bool Schematic::serializeToLua(std::ostream *os, const std::vector &names, - bool use_comments, u32 indent_spaces) const + +bool Schematic::serializeToLua(std::ostream *os, + const std::vector &names, bool use_comments, + u32 indent_spaces) const { std::ostream &ss = *os; @@ -387,8 +396,10 @@ bool Schematic::serializeToLua(std::ostream *os, const std::vector { ss << "schematic = {" << std::endl; ss << indent << "size = " - << "{x=" << size.X << ", y=" << size.Y << ", z=" << size.Z << "}," - << std::endl; + << "{x=" << size.X + << ", y=" << size.Y + << ", z=" << size.Z + << "}," << std::endl; } //// Write y-slice probabilities @@ -399,8 +410,9 @@ bool Schematic::serializeToLua(std::ostream *os, const std::vector u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK; ss << indent << indent << "{" - << "ypos=" << y << ", prob=" << (u16)probability * 2 << "}," - << std::endl; + << "ypos=" << y + << ", prob=" << (u16)probability * 2 + << "}," << std::endl; } ss << indent << "}," << std::endl; @@ -412,31 +424,29 @@ bool Schematic::serializeToLua(std::ostream *os, const std::vector u32 i = 0; for (u16 z = 0; z != size.Z; z++) - for (u16 y = 0; y != size.Y; y++) { - if (use_comments) { - ss << std::endl - << indent << indent << "-- z=" << z - << ", y=" << y << std::endl; - } + for (u16 y = 0; y != size.Y; y++) { + if (use_comments) { + ss << std::endl + << indent << indent + << "-- z=" << z + << ", y=" << y << std::endl; + } - for (u16 x = 0; x != size.X; x++, i++) { - u8 probability = schemdata[i].param1 & - MTSCHEM_PROB_MASK; - bool force_place = schemdata[i].param1 & - MTSCHEM_FORCE_PLACE; + for (u16 x = 0; x != size.X; x++, i++) { + u8 probability = schemdata[i].param1 & MTSCHEM_PROB_MASK; + bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE; - ss << indent << indent << "{" - << "name=\"" - << names[schemdata[i].getContent()] - << "\", prob=" << (u16)probability * 2 - << ", param2=" << (u16)schemdata[i].param2; + ss << indent << indent << "{" + << "name=\"" << names[schemdata[i].getContent()] + << "\", prob=" << (u16)probability * 2 + << ", param2=" << (u16)schemdata[i].param2; - if (force_place) - ss << ", force_place=true"; + if (force_place) + ss << ", force_place=true"; - ss << "}," << std::endl; - } + ss << "}," << std::endl; } + } ss << indent << "}," << std::endl; } @@ -446,13 +456,14 @@ bool Schematic::serializeToLua(std::ostream *os, const std::vector return true; } + bool Schematic::loadSchematicFromFile(const std::string &filename, - const NodeDefManager *ndef, StringMap *replace_names) + const NodeDefManager *ndef, StringMap *replace_names) { std::ifstream is(filename.c_str(), std::ios_base::binary); if (!is.good()) { - errorstream << __FUNCTION__ << ": unable to open file '" << filename - << "'" << std::endl; + errorstream << __FUNCTION__ << ": unable to open file '" + << filename << "'" << std::endl; return false; } @@ -479,8 +490,9 @@ bool Schematic::loadSchematicFromFile(const std::string &filename, return true; } -bool Schematic::saveSchematicToFile( - const std::string &filename, const NodeDefManager *ndef) + +bool Schematic::saveSchematicToFile(const std::string &filename, + const NodeDefManager *ndef) { MapNode *orig_schemdata = schemdata; std::vector ndef_nodenames; @@ -506,7 +518,7 @@ bool Schematic::saveSchematicToFile( bool status = serializeToMts(&os, *names); if (ndef) { - delete[] schemdata; + delete []schemdata; schemdata = orig_schemdata; } @@ -516,6 +528,7 @@ bool Schematic::saveSchematicToFile( return fs::safeWriteToFile(filename, os.str()); } + bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) { MMVManip *vm = new MMVManip(map); @@ -534,20 +547,22 @@ bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) u32 i = 0; for (s16 z = p1.Z; z <= p2.Z; z++) - for (s16 y = p1.Y; y <= p2.Y; y++) { - u32 vi = vm->m_area.index(p1.X, y, z); - for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) { - schemdata[i] = vm->m_data[vi]; - schemdata[i].param1 = MTSCHEM_PROB_ALWAYS; - } + for (s16 y = p1.Y; y <= p2.Y; y++) { + u32 vi = vm->m_area.index(p1.X, y, z); + for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) { + schemdata[i] = vm->m_data[vi]; + schemdata[i].param1 = MTSCHEM_PROB_ALWAYS; } + } delete vm; return true; } -void Schematic::applyProbabilities(v3s16 p0, std::vector> *plist, - std::vector> *splist) + +void Schematic::applyProbabilities(v3s16 p0, + std::vector > *plist, + std::vector > *splist) { for (size_t i = 0; i != plist->size(); i++) { v3s16 p = (*plist)[i].first - p0; @@ -568,8 +583,9 @@ void Schematic::applyProbabilities(v3s16 p0, std::vector> * } } + void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, - std::vector *usednodes, const NodeDefManager *ndef) + std::vector *usednodes, const NodeDefManager *ndef) { std::unordered_map nodeidmap; content_t numids = 0; @@ -578,8 +594,7 @@ void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, content_t id; content_t c = nodes[i].getContent(); - std::unordered_map::const_iterator it = - nodeidmap.find(c); + std::unordered_map::const_iterator it = nodeidmap.find(c); if (it == nodeidmap.end()) { id = numids; numids++; diff --git a/src/mapgen/mg_schematic.h b/src/mapgen/mg_schematic.h index 9ba96b4a1..6b31251b6 100644 --- a/src/mapgen/mg_schematic.h +++ b/src/mapgen/mg_schematic.h @@ -68,31 +68,29 @@ class Server; //// Schematic constants #define MTSCHEM_FILE_SIGNATURE 0x4d54534d // 'MTSM' -#define MTSCHEM_FILE_VER_HIGHEST_READ 4 +#define MTSCHEM_FILE_VER_HIGHEST_READ 4 #define MTSCHEM_FILE_VER_HIGHEST_WRITE 4 -#define MTSCHEM_PROB_MASK 0x7F +#define MTSCHEM_PROB_MASK 0x7F -#define MTSCHEM_PROB_NEVER 0x00 -#define MTSCHEM_PROB_ALWAYS 0x7F +#define MTSCHEM_PROB_NEVER 0x00 +#define MTSCHEM_PROB_ALWAYS 0x7F #define MTSCHEM_PROB_ALWAYS_OLD 0xFF -#define MTSCHEM_FORCE_PLACE 0x80 +#define MTSCHEM_FORCE_PLACE 0x80 enum SchematicType { SCHEMATIC_NORMAL, }; -enum SchematicFormatType -{ +enum SchematicFormatType { SCHEM_FMT_HANDLE, SCHEM_FMT_MTS, SCHEM_FMT_LUA, }; -class Schematic : public ObjDef, public NodeResolver -{ +class Schematic : public ObjDef, public NodeResolver { public: Schematic(); virtual ~Schematic(); @@ -102,24 +100,24 @@ class Schematic : public ObjDef, public NodeResolver virtual void resolveNodeNames(); bool loadSchematicFromFile(const std::string &filename, - const NodeDefManager *ndef, StringMap *replace_names = NULL); - bool saveSchematicToFile(const std::string &filename, const NodeDefManager *ndef); + const NodeDefManager *ndef, StringMap *replace_names = NULL); + bool saveSchematicToFile(const std::string &filename, + const NodeDefManager *ndef); bool getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2); bool deserializeFromMts(std::istream *is, std::vector *names); - bool serializeToMts( - std::ostream *os, const std::vector &names) const; + bool serializeToMts(std::ostream *os, + const std::vector &names) const; bool serializeToLua(std::ostream *os, const std::vector &names, - bool use_comments, u32 indent_spaces) const; + bool use_comments, u32 indent_spaces) const; void blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place); - bool placeOnVManip( - MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place); - void placeOnMap(ServerMap *map, v3s16 p, u32 flags, Rotation rot, - bool force_place); + bool placeOnVManip(MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place); + void placeOnMap(ServerMap *map, v3s16 p, u32 flags, Rotation rot, bool force_place); - void applyProbabilities(v3s16 p0, std::vector> *plist, - std::vector> *splist); + void applyProbabilities(v3s16 p0, + std::vector > *plist, + std::vector > *splist); std::vector c_nodes; u32 flags = 0; @@ -128,8 +126,7 @@ class Schematic : public ObjDef, public NodeResolver u8 *slice_probs = nullptr; }; -class SchematicManager : public ObjDefManager -{ +class SchematicManager : public ObjDefManager { public: SchematicManager(Server *server); virtual ~SchematicManager() = default; @@ -138,15 +135,21 @@ class SchematicManager : public ObjDefManager virtual void clear(); - const char *getObjectTitle() const { return "schematic"; } + const char *getObjectTitle() const + { + return "schematic"; + } - static Schematic *create(SchematicType type) { return new Schematic; } + static Schematic *create(SchematicType type) + { + return new Schematic; + } private: - SchematicManager(){}; + SchematicManager() {}; Server *m_server; }; void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, - std::vector *usednodes, const NodeDefManager *ndef); + std::vector *usednodes, const NodeDefManager *ndef); diff --git a/src/mapgen/treegen.cpp b/src/mapgen/treegen.cpp index ddf518290..e7e30c880 100644 --- a/src/mapgen/treegen.cpp +++ b/src/mapgen/treegen.cpp @@ -32,8 +32,8 @@ with this program; if not, write to the Free Software Foundation, Inc., namespace treegen { -void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, const NodeDefManager *ndef, - s32 seed) +void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, + const NodeDefManager *ndef, s32 seed) { /* NOTE: Tree-placing code is currently duplicated in the engine @@ -44,14 +44,11 @@ void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, const NodeDefMana MapNode leavesnode(ndef->getId("mapgen_leaves")); MapNode applenode(ndef->getId("mapgen_apple")); if (treenode == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_tree' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_tree' is invalid!" << std::endl; if (leavesnode == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_leaves' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_leaves' is invalid!" << std::endl; if (applenode == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_apple' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_apple' is invalid!" << std::endl; PseudoRandom pr(seed); s16 trunk_h = pr.range(4, 5); @@ -75,56 +72,57 @@ void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, const NodeDefMana // Force leaves at near the end of the trunk s16 d = 1; for (s16 z = -d; z <= d; z++) - for (s16 y = -d; y <= d; y++) - for (s16 x = -d; x <= d; x++) { - leaves_d[leaves_a.index(v3s16(x, y, z))] = 1; - } + for (s16 y = -d; y <= d; y++) + for (s16 x = -d; x <= d; x++) { + leaves_d[leaves_a.index(v3s16(x, y, z))] = 1; + } // Add leaves randomly for (u32 iii = 0; iii < 7; iii++) { - v3s16 p(pr.range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X - d), - pr.range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y - d), - pr.range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z - d)); + v3s16 p( + pr.range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X - d), + pr.range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y - d), + pr.range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z - d) + ); for (s16 z = 0; z <= d; z++) - for (s16 y = 0; y <= d; y++) - for (s16 x = 0; x <= d; x++) { - leaves_d[leaves_a.index(p + v3s16(x, y, z))] = 1; - } + for (s16 y = 0; y <= d; y++) + for (s16 x = 0; x <= d; x++) { + leaves_d[leaves_a.index(p + v3s16(x, y, z))] = 1; + } } // Blit leaves to vmanip for (s16 z = leaves_a.MinEdge.Z; z <= leaves_a.MaxEdge.Z; z++) - for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { - v3s16 pmin(leaves_a.MinEdge.X, y, z); - u32 i = leaves_a.index(pmin); - u32 vi = vmanip.m_area.index(pmin + p1); - for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { - v3s16 p(x, y, z); - if (vmanip.m_area.contains(p + p1) && - (vmanip.m_data[vi].getContent() == - CONTENT_AIR || - vmanip.m_data[vi].getContent() == - CONTENT_IGNORE)) { - if (leaves_d[i] == 1) { - bool is_apple = pr.range(0, 99) < 10; - if (is_apple_tree && is_apple) - vmanip.m_data[vi] = applenode; - else - vmanip.m_data[vi] = leavesnode; - } + for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { + v3s16 pmin(leaves_a.MinEdge.X, y, z); + u32 i = leaves_a.index(pmin); + u32 vi = vmanip.m_area.index(pmin + p1); + for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { + v3s16 p(x, y, z); + if (vmanip.m_area.contains(p + p1) && + (vmanip.m_data[vi].getContent() == CONTENT_AIR || + vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) { + if (leaves_d[i] == 1) { + bool is_apple = pr.range(0, 99) < 10; + if (is_apple_tree && is_apple) + vmanip.m_data[vi] = applenode; + else + vmanip.m_data[vi] = leavesnode; } - vi++; - i++; } + vi++; + i++; } + } } + // L-System tree LUA spawner -treegen::error spawn_ltree(ServerMap *map, v3s16 p0, const NodeDefManager *ndef, - const TreeDef &tree_definition) +treegen::error spawn_ltree(ServerMap *map, v3s16 p0, + const NodeDefManager *ndef, const TreeDef &tree_definition) { - std::map modified_blocks; + std::map modified_blocks; MMVManip vmanip(map); v3s16 tree_blockp = getNodeBlockPos(p0); treegen::error e; @@ -145,15 +143,16 @@ treegen::error spawn_ltree(ServerMap *map, v3s16 p0, const NodeDefManager *ndef, return SUCCESS; } -// L-System tree generator -treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, - TreeDef tree_definition) + +//L-System tree generator +treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, + const NodeDefManager *ndef, TreeDef tree_definition) { s32 seed; if (tree_definition.explicit_seed) seed = tree_definition.seed + 14002; else - seed = p0.X * 2 + p0.Y * 4 + p0.Z; // use the tree position to seed PRNG + seed = p0.X * 2 + p0.Y * 4 + p0.Z; // use the tree position to seed PRNG PseudoRandom ps(seed); // chance of inserting abcd rules @@ -162,7 +161,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef double prop_c = 7; double prop_d = 6; - // randomize tree growth level, minimum=2 + //randomize tree growth level, minimum=2 s16 iterations = tree_definition.iterations; if (tree_definition.iterations_random_level > 0) iterations -= ps.range(0, tree_definition.iterations_random_level); @@ -171,20 +170,19 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef s16 MAX_ANGLE_OFFSET = 5; double angle_in_radians = (double)tree_definition.angle * M_PI / 180; - double angleOffset_in_radians = - (s16)(ps.range(0, 1) % MAX_ANGLE_OFFSET) * M_PI / 180; + double angleOffset_in_radians = (s16)(ps.range(0, 1) % MAX_ANGLE_OFFSET) * M_PI / 180; - // initialize rotation matrix, position and stacks for branches + //initialize rotation matrix, position and stacks for branches core::matrix4 rotation; rotation = setRotationAxisRadians(rotation, M_PI / 2, v3f(0, 0, 1)); v3f position; position.X = p0.X; position.Y = p0.Y; position.Z = p0.Z; - std::stack stack_orientation; - std::stack stack_position; + std::stack stack_orientation; + std::stack stack_position; - // generate axiom + //generate axiom std::string axiom = tree_definition.initial_axiom; for (s16 i = 0; i < iterations; i++) { std::string temp; @@ -229,28 +227,42 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef // Add trunk nodes below a wide trunk to avoid gaps when tree is on sloping ground if (tree_definition.trunk_type == "double") { - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y - 1, position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y - 1, position.Z + 1), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y - 1, position.Z + 1), - tree_definition); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y - 1, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y - 1, position.Z + 1), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y - 1, position.Z + 1), + tree_definition + ); } else if (tree_definition.trunk_type == "crossed") { - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y - 1, position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X - 1, position.Y - 1, position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y - 1, position.Z + 1), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y - 1, position.Z - 1), - tree_definition); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y - 1, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X - 1, position.Y - 1, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y - 1, position.Z + 1), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y - 1, position.Z - 1), + tree_definition + ); } /* build tree out of generated axiom @@ -281,7 +293,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef */ - s16 x, y, z; + s16 x,y,z; for (s16 i = 0; i < (s16)axiom.size(); i++) { char axiom_char = axiom.at(i); core::matrix4 temp_rotation; @@ -294,149 +306,164 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef position += dir; break; case 'T': - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, position.Z), - tree_definition); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z), + tree_definition + ); if (tree_definition.trunk_type == "double" && !tree_definition.thin_branches) { - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y, - position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, - position.Z + 1), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y, - position.Z + 1), - tree_definition); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z + 1), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y, position.Z + 1), + tree_definition + ); } else if (tree_definition.trunk_type == "crossed" && !tree_definition.thin_branches) { - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y, - position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X - 1, position.Y, - position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, - position.Z + 1), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, - position.Z - 1), - tree_definition); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X - 1, position.Y, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z + 1), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z - 1), + tree_definition + ); } dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'F': - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, position.Z), - tree_definition); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z), + tree_definition + ); if ((stack_orientation.empty() && - tree_definition.trunk_type == "double") || + tree_definition.trunk_type == "double") || (!stack_orientation.empty() && - tree_definition.trunk_type == - "double" && - !tree_definition.thin_branches)) { - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y, - position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, - position.Z + 1), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y, - position.Z + 1), - tree_definition); + tree_definition.trunk_type == "double" && + !tree_definition.thin_branches)) { + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z + 1), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y, position.Z + 1), + tree_definition + ); } else if ((stack_orientation.empty() && - tree_definition.trunk_type == - "crossed") || + tree_definition.trunk_type == "crossed") || (!stack_orientation.empty() && - tree_definition.trunk_type == - "crossed" && - !tree_definition.thin_branches)) { - tree_trunk_placement(vmanip, - v3f(position.X + 1, position.Y, - position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X - 1, position.Y, - position.Z), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, - position.Z + 1), - tree_definition); - tree_trunk_placement(vmanip, - v3f(position.X, position.Y, - position.Z - 1), - tree_definition); - } - if (!stack_orientation.empty()) { + tree_definition.trunk_type == "crossed" && + !tree_definition.thin_branches)) { + tree_trunk_placement( + vmanip, + v3f(position.X + 1, position.Y, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X - 1, position.Y, position.Z), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z + 1), + tree_definition + ); + tree_trunk_placement( + vmanip, + v3f(position.X, position.Y, position.Z - 1), + tree_definition + ); + } if (!stack_orientation.empty()) { s16 size = 1; for (x = -size; x <= size; x++) - for (y = -size; y <= size; y++) - for (z = -size; z <= size; z++) { - if (abs(x) == size && - abs(y) == size && - abs(z) == size) { - tree_leaves_placement( - vmanip, - v3f(position.X + x + 1, - position.Y + y, - position.Z + z), - ps.next(), - tree_definition); - tree_leaves_placement( - vmanip, - v3f(position.X + x - 1, - position.Y + y, - position.Z + z), - ps.next(), - tree_definition); - tree_leaves_placement( - vmanip, - v3f(position.X + x, - position.Y + y, - position.Z + z + - 1), - ps.next(), - tree_definition); - tree_leaves_placement( - vmanip, - v3f(position.X + x, - position.Y + y, - position.Z + z - - 1), - ps.next(), - tree_definition); - } - } + for (y = -size; y <= size; y++) + for (z = -size; z <= size; z++) { + if (abs(x) == size && + abs(y) == size && + abs(z) == size) { + tree_leaves_placement( + vmanip, + v3f(position.X + x + 1, position.Y + y, + position.Z + z), + ps.next(), + tree_definition + ); + tree_leaves_placement( + vmanip, + v3f(position.X + x - 1, position.Y + y, + position.Z + z), + ps.next(), + tree_definition + ); + tree_leaves_placement( + vmanip,v3f(position.X + x, position.Y + y, + position.Z + z + 1), + ps.next(), + tree_definition + ); + tree_leaves_placement( + vmanip,v3f(position.X + x, position.Y + y, + position.Z + z - 1), + ps.next(), + tree_definition + ); + } + } } dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'f': - tree_single_leaves_placement(vmanip, - v3f(position.X, position.Y, position.Z), - ps.next(), tree_definition); + tree_single_leaves_placement( + vmanip, + v3f(position.X, position.Y, position.Z), + ps.next(), + tree_definition + ); dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; break; case 'R': - tree_fruit_placement(vmanip, - v3f(position.X, position.Y, position.Z), - tree_definition); + tree_fruit_placement( + vmanip, + v3f(position.X, position.Y, position.Z), + tree_definition + ); dir = v3f(1, 0, 0); dir = transposeMatrix(rotation, dir); position += dir; @@ -458,41 +485,37 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef case '+': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, - angle_in_radians + angleOffset_in_radians, - v3f(0, 0, 1)); + angle_in_radians + angleOffset_in_radians, v3f(0, 0, 1)); rotation *= temp_rotation; break; case '-': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, - angle_in_radians + angleOffset_in_radians, - v3f(0, 0, -1)); + angle_in_radians + angleOffset_in_radians, v3f(0, 0, -1)); rotation *= temp_rotation; break; case '&': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, - angle_in_radians + angleOffset_in_radians, - v3f(0, 1, 0)); + angle_in_radians + angleOffset_in_radians, v3f(0, 1, 0)); rotation *= temp_rotation; break; case '^': temp_rotation.makeIdentity(); temp_rotation = setRotationAxisRadians(temp_rotation, - angle_in_radians + angleOffset_in_radians, - v3f(0, -1, 0)); + angle_in_radians + angleOffset_in_radians, v3f(0, -1, 0)); rotation *= temp_rotation; break; case '*': temp_rotation.makeIdentity(); - temp_rotation = setRotationAxisRadians( - temp_rotation, angle_in_radians, v3f(1, 0, 0)); + temp_rotation = setRotationAxisRadians(temp_rotation, + angle_in_radians, v3f(1, 0, 0)); rotation *= temp_rotation; break; case '/': temp_rotation.makeIdentity(); - temp_rotation = setRotationAxisRadians( - temp_rotation, angle_in_radians, v3f(-1, 0, 0)); + temp_rotation = setRotationAxisRadians(temp_rotation, + angle_in_radians, v3f(-1, 0, 0)); rotation *= temp_rotation; break; default: @@ -503,18 +526,20 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef return SUCCESS; } + void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node) { v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); - if (vmanip.m_data[vi].getContent() != CONTENT_AIR && - vmanip.m_data[vi].getContent() != CONTENT_IGNORE) + if (vmanip.m_data[vi].getContent() != CONTENT_AIR + && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; vmanip.m_data[vmanip.m_area.index(p1)] = node; } + void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) { v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); @@ -522,16 +547,17 @@ void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) return; u32 vi = vmanip.m_area.index(p1); content_t current_node = vmanip.m_data[vi].getContent(); - if (current_node != CONTENT_AIR && current_node != CONTENT_IGNORE && - current_node != tree_definition.leavesnode.getContent() && - current_node != tree_definition.leaves2node.getContent() && - current_node != tree_definition.fruitnode.getContent()) + if (current_node != CONTENT_AIR && current_node != CONTENT_IGNORE + && current_node != tree_definition.leavesnode.getContent() + && current_node != tree_definition.leaves2node.getContent() + && current_node != tree_definition.fruitnode.getContent()) return; vmanip.m_data[vi] = tree_definition.trunknode; } -void tree_leaves_placement( - MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition) + +void tree_leaves_placement(MMVManip &vmanip, v3f p0, + PseudoRandom ps, TreeDef &tree_definition) { MapNode leavesnode = tree_definition.leavesnode; if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance) @@ -540,13 +566,12 @@ void tree_leaves_placement( if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); - if (vmanip.m_data[vi].getContent() != CONTENT_AIR && - vmanip.m_data[vi].getContent() != CONTENT_IGNORE) + if (vmanip.m_data[vi].getContent() != CONTENT_AIR + && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; if (tree_definition.fruit_chance > 0) { if (ps.range(1, 100) > 100 - tree_definition.fruit_chance) - vmanip.m_data[vmanip.m_area.index(p1)] = - tree_definition.fruitnode; + vmanip.m_data[vmanip.m_area.index(p1)] = tree_definition.fruitnode; else vmanip.m_data[vmanip.m_area.index(p1)] = leavesnode; } else if (ps.range(1, 100) > 20) { @@ -554,8 +579,9 @@ void tree_leaves_placement( } } -void tree_single_leaves_placement( - MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition) + +void tree_single_leaves_placement(MMVManip &vmanip, v3f p0, + PseudoRandom ps, TreeDef &tree_definition) { MapNode leavesnode = tree_definition.leavesnode; if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance) @@ -564,36 +590,38 @@ void tree_single_leaves_placement( if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); - if (vmanip.m_data[vi].getContent() != CONTENT_AIR && - vmanip.m_data[vi].getContent() != CONTENT_IGNORE) + if (vmanip.m_data[vi].getContent() != CONTENT_AIR + && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; vmanip.m_data[vmanip.m_area.index(p1)] = leavesnode; } + void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) { v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); if (!vmanip.m_area.contains(p1)) return; u32 vi = vmanip.m_area.index(p1); - if (vmanip.m_data[vi].getContent() != CONTENT_AIR && - vmanip.m_data[vi].getContent() != CONTENT_IGNORE) + if (vmanip.m_data[vi].getContent() != CONTENT_AIR + && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) return; vmanip.m_data[vmanip.m_area.index(p1)] = tree_definition.fruitnode; } + irr::core::matrix4 setRotationAxisRadians(irr::core::matrix4 M, double angle, v3f axis) { double c = cos(angle); double s = sin(angle); double t = 1.0 - c; - double tx = t * axis.X; - double ty = t * axis.Y; - double tz = t * axis.Z; - double sx = s * axis.X; - double sy = s * axis.Y; - double sz = s * axis.Z; + double tx = t * axis.X; + double ty = t * axis.Y; + double tz = t * axis.Z; + double sx = s * axis.X; + double sy = s * axis.Y; + double sz = s * axis.Z; M[0] = tx * axis.X + c; M[1] = tx * axis.Y + sz; @@ -603,64 +631,65 @@ irr::core::matrix4 setRotationAxisRadians(irr::core::matrix4 M, double angle, v3 M[5] = ty * axis.Y + c; M[6] = ty * axis.Z + sx; - M[8] = tz * axis.X + sy; - M[9] = tz * axis.Y - sx; + M[8] = tz * axis.X + sy; + M[9] = tz * axis.Y - sx; M[10] = tz * axis.Z + c; return M; } + v3f transposeMatrix(irr::core::matrix4 M, v3f v) { v3f translated; - double x = M[0] * v.X + M[4] * v.Y + M[8] * v.Z + M[12]; - double y = M[1] * v.X + M[5] * v.Y + M[9] * v.Z + M[13]; - double z = M[2] * v.X + M[6] * v.Y + M[10] * v.Z + M[14]; + double x = M[0] * v.X + M[4] * v.Y + M[8] * v.Z +M[12]; + double y = M[1] * v.X + M[5] * v.Y + M[9] * v.Z +M[13]; + double z = M[2] * v.X + M[6] * v.Y + M[10] * v.Z +M[14]; translated.X = x; translated.Y = y; translated.Z = z; return translated; } -void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed) + +void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, + s32 seed) { /* NOTE: Tree-placing code is currently duplicated in the engine and in games that have saplings; both are deprecated but not replaced yet */ - content_t c_tree = ndef->getId("mapgen_jungletree"); + content_t c_tree = ndef->getId("mapgen_jungletree"); content_t c_leaves = ndef->getId("mapgen_jungleleaves"); if (c_tree == CONTENT_IGNORE) c_tree = ndef->getId("mapgen_tree"); if (c_leaves == CONTENT_IGNORE) c_leaves = ndef->getId("mapgen_leaves"); if (c_tree == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_jungletree' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_jungletree' is invalid!" << std::endl; if (c_leaves == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_jungleleaves' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_jungleleaves' is invalid!" << std::endl; MapNode treenode(c_tree); MapNode leavesnode(c_leaves); PseudoRandom pr(seed); - for (s16 x = -1; x <= 1; x++) - for (s16 z = -1; z <= 1; z++) { - if (pr.range(0, 2) == 0) - continue; - v3s16 p1 = p0 + v3s16(x, 0, z); - v3s16 p2 = p0 + v3s16(x, -1, z); - u32 vi1 = vmanip.m_area.index(p1); - u32 vi2 = vmanip.m_area.index(p2); - - if (vmanip.m_area.contains(p2) && - vmanip.m_data[vi2].getContent() == CONTENT_AIR) - vmanip.m_data[vi2] = treenode; - else if (vmanip.m_area.contains(p1) && - vmanip.m_data[vi1].getContent() == CONTENT_AIR) - vmanip.m_data[vi1] = treenode; - } + for (s16 x= -1; x <= 1; x++) + for (s16 z= -1; z <= 1; z++) { + if (pr.range(0, 2) == 0) + continue; + v3s16 p1 = p0 + v3s16(x, 0, z); + v3s16 p2 = p0 + v3s16(x, -1, z); + u32 vi1 = vmanip.m_area.index(p1); + u32 vi2 = vmanip.m_area.index(p2); + + if (vmanip.m_area.contains(p2) && + vmanip.m_data[vi2].getContent() == CONTENT_AIR) + vmanip.m_data[vi2] = treenode; + else if (vmanip.m_area.contains(p1) && + vmanip.m_data[vi1].getContent() == CONTENT_AIR) + vmanip.m_data[vi1] = treenode; + } vmanip.m_data[vmanip.m_area.index(p0)] = treenode; s16 trunk_h = pr.range(8, 12); @@ -677,7 +706,7 @@ void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 p1.Y -= 1; VoxelArea leaves_a(v3s16(-3, -2, -3), v3s16(3, 2, 3)); - // SharedPtr leaves_d(new u8[leaves_a.getVolume()]); + //SharedPtr leaves_d(new u8[leaves_a.getVolume()]); Buffer leaves_d(leaves_a.getVolume()); for (s32 i = 0; i < leaves_a.getVolume(); i++) leaves_d[i] = 0; @@ -685,54 +714,56 @@ void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 // Force leaves at near the end of the trunk s16 d = 1; for (s16 z = -d; z <= d; z++) - for (s16 y = -d; y <= d; y++) - for (s16 x = -d; x <= d; x++) { - leaves_d[leaves_a.index(v3s16(x, y, z))] = 1; - } + for (s16 y = -d; y <= d; y++) + for (s16 x = -d; x <= d; x++) { + leaves_d[leaves_a.index(v3s16(x,y,z))] = 1; + } // Add leaves randomly for (u32 iii = 0; iii < 30; iii++) { - v3s16 p(pr.range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X - d), - pr.range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y - d), - pr.range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z - d)); + v3s16 p( + pr.range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X - d), + pr.range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y - d), + pr.range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z - d) + ); for (s16 z = 0; z <= d; z++) - for (s16 y = 0; y <= d; y++) - for (s16 x = 0; x <= d; x++) { - leaves_d[leaves_a.index(p + v3s16(x, y, z))] = 1; - } + for (s16 y = 0; y <= d; y++) + for (s16 x = 0; x <= d; x++) { + leaves_d[leaves_a.index(p + v3s16(x, y, z))] = 1; + } } // Blit leaves to vmanip for (s16 z = leaves_a.MinEdge.Z; z <= leaves_a.MaxEdge.Z; z++) - for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { - v3s16 pmin(leaves_a.MinEdge.X, y, z); - u32 i = leaves_a.index(pmin); - u32 vi = vmanip.m_area.index(pmin + p1); - for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { - v3s16 p(x, y, z); - if (vmanip.m_area.contains(p + p1) && - (vmanip.m_data[vi].getContent() == - CONTENT_AIR || - vmanip.m_data[vi].getContent() == - CONTENT_IGNORE)) { - if (leaves_d[i] == 1) - vmanip.m_data[vi] = leavesnode; - } - vi++; - i++; + for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { + v3s16 pmin(leaves_a.MinEdge.X, y, z); + u32 i = leaves_a.index(pmin); + u32 vi = vmanip.m_area.index(pmin + p1); + for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { + v3s16 p(x, y, z); + if (vmanip.m_area.contains(p + p1) && + (vmanip.m_data[vi].getContent() == CONTENT_AIR || + vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) { + if (leaves_d[i] == 1) + vmanip.m_data[vi] = leavesnode; } + vi++; + i++; } + } } -void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed) + +void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, + s32 seed) { /* NOTE: Tree-placing code is currently duplicated in the engine and in games that have saplings; both are deprecated but not replaced yet */ - content_t c_tree = ndef->getId("mapgen_pine_tree"); + content_t c_tree = ndef->getId("mapgen_pine_tree"); content_t c_leaves = ndef->getId("mapgen_pine_needles"); content_t c_snow = ndef->getId("mapgen_snow"); if (c_tree == CONTENT_IGNORE) @@ -742,11 +773,9 @@ void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 if (c_snow == CONTENT_IGNORE) c_snow = CONTENT_AIR; if (c_tree == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_pine_tree' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_pine_tree' is invalid!" << std::endl; if (c_leaves == CONTENT_IGNORE) - errorstream << "Treegen: Mapgen alias 'mapgen_pine_needles' is invalid!" - << std::endl; + errorstream << "Treegen: Mapgen alias 'mapgen_pine_needles' is invalid!" << std::endl; MapNode treenode(c_tree); MapNode leavesnode(c_leaves); @@ -776,7 +805,7 @@ void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 for (s16 yy = -1; yy <= 1; yy++) { for (s16 zz = -dev; zz <= dev; zz++) { u32 i = leaves_a.index(v3s16(-dev, yy, zz)); - u32 ia = leaves_a.index(v3s16(-dev, yy + 1, zz)); + u32 ia = leaves_a.index(v3s16(-dev, yy+1, zz)); for (s16 xx = -dev; xx <= dev; xx++) { if (pr.range(0, 20) <= 19 - dev) { leaves_d[i] = 1; @@ -834,28 +863,25 @@ void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 // Blit leaves to vmanip for (s16 z = leaves_a.MinEdge.Z; z <= leaves_a.MaxEdge.Z; z++) - for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { - v3s16 pmin(leaves_a.MinEdge.X, y, z); - u32 i = leaves_a.index(pmin); - u32 vi = vmanip.m_area.index(pmin + p1); - for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { - v3s16 p(x, y, z); - if (vmanip.m_area.contains(p + p1) && - (vmanip.m_data[vi].getContent() == - CONTENT_AIR || - vmanip.m_data[vi].getContent() == - CONTENT_IGNORE || - vmanip.m_data[vi] == - snownode)) { - if (leaves_d[i] == 1) - vmanip.m_data[vi] = leavesnode; - else if (leaves_d[i] == 2) - vmanip.m_data[vi] = snownode; - } - vi++; - i++; + for (s16 y = leaves_a.MinEdge.Y; y <= leaves_a.MaxEdge.Y; y++) { + v3s16 pmin(leaves_a.MinEdge.X, y, z); + u32 i = leaves_a.index(pmin); + u32 vi = vmanip.m_area.index(pmin + p1); + for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { + v3s16 p(x, y, z); + if (vmanip.m_area.contains(p + p1) && + (vmanip.m_data[vi].getContent() == CONTENT_AIR || + vmanip.m_data[vi].getContent() == CONTENT_IGNORE || + vmanip.m_data[vi] == snownode)) { + if (leaves_d[i] == 1) + vmanip.m_data[vi] = leavesnode; + else if (leaves_d[i] == 2) + vmanip.m_data[vi] = snownode; } + vi++; + i++; } + } } }; // namespace treegen diff --git a/src/mapgen/treegen.h b/src/mapgen/treegen.h index f2ee36a4e..447baabb3 100644 --- a/src/mapgen/treegen.h +++ b/src/mapgen/treegen.h @@ -28,64 +28,66 @@ class MMVManip; class NodeDefManager; class ServerMap; -namespace treegen -{ - -enum error -{ - SUCCESS, - UNBALANCED_BRACKETS -}; - -struct TreeDef -{ - std::string initial_axiom; - std::string rules_a; - std::string rules_b; - std::string rules_c; - std::string rules_d; - - MapNode trunknode; - MapNode leavesnode; - MapNode leaves2node; - - int leaves2_chance; - int angle; - int iterations; - int iterations_random_level; - std::string trunk_type; - bool thin_branches; - MapNode fruitnode; - int fruit_chance; - s32 seed; - bool explicit_seed; -}; - -// Add default tree -void make_tree(MMVManip &vmanip, v3s16 p0, bool is_apple_tree, const NodeDefManager *ndef, - s32 seed); -// Add jungle tree -void make_jungletree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed); -// Add pine tree -void make_pine_tree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, s32 seed); - -// Add L-Systems tree (used by engine) -treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, const NodeDefManager *ndef, - TreeDef tree_definition); -// Spawn L-systems tree from LUA -treegen::error spawn_ltree(ServerMap *map, v3s16 p0, const NodeDefManager *ndef, - const TreeDef &tree_definition); - -// L-System tree gen helper functions -void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node); -void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition); -void tree_leaves_placement( - MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition); -void tree_single_leaves_placement( - MMVManip &vmanip, v3f p0, PseudoRandom ps, TreeDef &tree_definition); -void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition); -irr::core::matrix4 setRotationAxisRadians(irr::core::matrix4 M, double angle, v3f axis); - -v3f transposeMatrix(irr::core::matrix4 M, v3f v); +namespace treegen { + + enum error { + SUCCESS, + UNBALANCED_BRACKETS + }; + + struct TreeDef { + std::string initial_axiom; + std::string rules_a; + std::string rules_b; + std::string rules_c; + std::string rules_d; + + MapNode trunknode; + MapNode leavesnode; + MapNode leaves2node; + + int leaves2_chance; + int angle; + int iterations; + int iterations_random_level; + std::string trunk_type; + bool thin_branches; + MapNode fruitnode; + int fruit_chance; + s32 seed; + bool explicit_seed; + }; + + // Add default tree + void make_tree(MMVManip &vmanip, v3s16 p0, + bool is_apple_tree, const NodeDefManager *ndef, s32 seed); + // Add jungle tree + void make_jungletree(MMVManip &vmanip, v3s16 p0, + const NodeDefManager *ndef, s32 seed); + // Add pine tree + void make_pine_tree(MMVManip &vmanip, v3s16 p0, + const NodeDefManager *ndef, s32 seed); + + // Add L-Systems tree (used by engine) + treegen::error make_ltree(MMVManip &vmanip, v3s16 p0, + const NodeDefManager *ndef, TreeDef tree_definition); + // Spawn L-systems tree from LUA + treegen::error spawn_ltree (ServerMap *map, v3s16 p0, + const NodeDefManager *ndef, const TreeDef &tree_definition); + + // L-System tree gen helper functions + void tree_node_placement(MMVManip &vmanip, v3f p0, + MapNode node); + void tree_trunk_placement(MMVManip &vmanip, v3f p0, + TreeDef &tree_definition); + void tree_leaves_placement(MMVManip &vmanip, v3f p0, + PseudoRandom ps, TreeDef &tree_definition); + void tree_single_leaves_placement(MMVManip &vmanip, v3f p0, + PseudoRandom ps, TreeDef &tree_definition); + void tree_fruit_placement(MMVManip &vmanip, v3f p0, + TreeDef &tree_definition); + irr::core::matrix4 setRotationAxisRadians(irr::core::matrix4 M, double angle, v3f axis); + + v3f transposeMatrix(irr::core::matrix4 M ,v3f v); }; // namespace treegen diff --git a/src/mapnode.cpp b/src/mapnode.cpp index fb56f3ef4..dcf1f6d6e 100644 --- a/src/mapnode.cpp +++ b/src/mapnode.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "map.h" #include "content_mapnode.h" // For mapnode_translate_*_internal -#include "serialization.h" // For ser_ver_supported +#include "serialization.h" // For ser_ver_supported #include "util/serialize.h" #include "log.h" #include "util/directiontables.h" @@ -32,9 +32,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include static const Rotation wallmounted_to_rot[] = { - ROTATE_0, ROTATE_180, ROTATE_90, ROTATE_270}; + ROTATE_0, ROTATE_180, ROTATE_90, ROTATE_270 +}; + +static const u8 rot_to_wallmounted[] = { + 2, 4, 3, 5 +}; -static const u8 rot_to_wallmounted[] = {2, 4, 3, 5}; /* MapNode @@ -52,15 +56,19 @@ void MapNode::getColor(const ContentFeatures &f, video::SColor *color) const void MapNode::setLight(LightBank bank, u8 a_light, const ContentFeatures &f) noexcept { // If node doesn't contain light data, ignore this - if (f.param_type != CPT_LIGHT) + if(f.param_type != CPT_LIGHT) return; - if (bank == LIGHTBANK_DAY) { + if(bank == LIGHTBANK_DAY) + { param1 &= 0xf0; param1 |= a_light & 0x0f; - } else if (bank == LIGHTBANK_NIGHT) { + } + else if(bank == LIGHTBANK_NIGHT) + { param1 &= 0x0f; - param1 |= (a_light & 0x0f) << 4; - } else + param1 |= (a_light & 0x0f)<<4; + } + else assert("Invalid light bank" == NULL); } @@ -75,7 +83,7 @@ bool MapNode::isLightDayNightEq(const NodeDefManager *nodemgr) const bool isEqual; if (f.param_type == CPT_LIGHT) { - u8 day = MYMAX(f.light_source, param1 & 0x0f); + u8 day = MYMAX(f.light_source, param1 & 0x0f); u8 night = MYMAX(f.light_source, (param1 >> 4) & 0x0f); isEqual = day == night; } else { @@ -91,7 +99,7 @@ u8 MapNode::getLight(LightBank bank, const NodeDefManager *nodemgr) const const ContentFeatures &f = nodemgr->get(*this); u8 light; - if (f.param_type == CPT_LIGHT) + if(f.param_type == CPT_LIGHT) light = bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f; else light = 0; @@ -101,7 +109,7 @@ u8 MapNode::getLight(LightBank bank, const NodeDefManager *nodemgr) const u8 MapNode::getLightRaw(LightBank bank, const ContentFeatures &f) const noexcept { - if (f.param_type == CPT_LIGHT) + if(f.param_type == CPT_LIGHT) return bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f; return 0; } @@ -109,36 +117,40 @@ u8 MapNode::getLightRaw(LightBank bank, const ContentFeatures &f) const noexcept u8 MapNode::getLightNoChecks(LightBank bank, const ContentFeatures *f) const noexcept { return MYMAX(f->light_source, - bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f); + bank == LIGHTBANK_DAY ? param1 & 0x0f : (param1 >> 4) & 0x0f); } -bool MapNode::getLightBanks( - u8 &lightday, u8 &lightnight, const NodeDefManager *nodemgr) const +bool MapNode::getLightBanks(u8 &lightday, u8 &lightnight, + const NodeDefManager *nodemgr) const { // Select the brightest of [light source, propagated light] const ContentFeatures &f = nodemgr->get(*this); - if (f.param_type == CPT_LIGHT) { + if(f.param_type == CPT_LIGHT) + { lightday = param1 & 0x0f; - lightnight = (param1 >> 4) & 0x0f; - } else { + lightnight = (param1>>4)&0x0f; + } + else + { lightday = 0; lightnight = 0; } - if (f.light_source > lightday) + if(f.light_source > lightday) lightday = f.light_source; - if (f.light_source > lightnight) + if(f.light_source > lightnight) lightnight = f.light_source; return f.param_type == CPT_LIGHT || f.light_source != 0; } -u8 MapNode::getFaceDir(const NodeDefManager *nodemgr, bool allow_wallmounted) const +u8 MapNode::getFaceDir(const NodeDefManager *nodemgr, + bool allow_wallmounted) const { const ContentFeatures &f = nodemgr->get(*this); - if (f.param_type_2 == CPT2_FACEDIR || f.param_type_2 == CPT2_COLORED_FACEDIR) + if (f.param_type_2 == CPT2_FACEDIR || + f.param_type_2 == CPT2_COLORED_FACEDIR) return (getParam2() & 0x1F) % 24; - if (allow_wallmounted && - (f.param_type_2 == CPT2_WALLMOUNTED || - f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) + if (allow_wallmounted && (f.param_type_2 == CPT2_WALLMOUNTED || + f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) return wallmounted_to_facedir[getParam2() & 0x07]; return 0; } @@ -154,20 +166,14 @@ u8 MapNode::getWallMounted(const NodeDefManager *nodemgr) const v3s16 MapNode::getWallMountedDir(const NodeDefManager *nodemgr) const { - switch (getWallMounted(nodemgr)) { - case 0: - default: - return v3s16(0, 1, 0); - case 1: - return v3s16(0, -1, 0); - case 2: - return v3s16(1, 0, 0); - case 3: - return v3s16(-1, 0, 0); - case 4: - return v3s16(0, 0, 1); - case 5: - return v3s16(0, 0, -1); + switch(getWallMounted(nodemgr)) + { + case 0: default: return v3s16(0,1,0); + case 1: return v3s16(0,-1,0); + case 2: return v3s16(1,0,0); + case 3: return v3s16(-1,0,0); + case 4: return v3s16(0,0,1); + case 5: return v3s16(0,0,-1); } } @@ -176,33 +182,47 @@ void MapNode::rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot) ContentParamType2 cpt2 = nodemgr->get(*this).param_type_2; if (cpt2 == CPT2_FACEDIR || cpt2 == CPT2_COLORED_FACEDIR) { - static const u8 rotate_facedir[24 * 4] = {// Table value = rotated facedir - // Columns: 0, 90, 180, 270 degrees rotation around - // vertical axis - // Rotation is anticlockwise as seen from above (+Y) - - 0, 1, 2, 3, // Initial facedir 0 to 3 - 1, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 2, - - 4, 13, 10, 19, // 4 to 7 - 5, 14, 11, 16, 6, 15, 8, 17, 7, 12, 9, 18, - - 8, 17, 6, 15, // 8 to 11 - 9, 18, 7, 12, 10, 19, 4, 13, 11, 16, 5, 14, - - 12, 9, 18, 7, // 12 to 15 - 13, 10, 19, 4, 14, 11, 16, 5, 15, 8, 17, 6, - - 16, 5, 14, 11, // 16 to 19 - 17, 6, 15, 8, 18, 7, 12, 9, 19, 4, 13, 10, - - 20, 23, 22, 21, // 20 to 23 - 21, 20, 23, 22, 22, 21, 20, 23, 23, 22, 21, 20}; + static const u8 rotate_facedir[24 * 4] = { + // Table value = rotated facedir + // Columns: 0, 90, 180, 270 degrees rotation around vertical axis + // Rotation is anticlockwise as seen from above (+Y) + + 0, 1, 2, 3, // Initial facedir 0 to 3 + 1, 2, 3, 0, + 2, 3, 0, 1, + 3, 0, 1, 2, + + 4, 13, 10, 19, // 4 to 7 + 5, 14, 11, 16, + 6, 15, 8, 17, + 7, 12, 9, 18, + + 8, 17, 6, 15, // 8 to 11 + 9, 18, 7, 12, + 10, 19, 4, 13, + 11, 16, 5, 14, + + 12, 9, 18, 7, // 12 to 15 + 13, 10, 19, 4, + 14, 11, 16, 5, + 15, 8, 17, 6, + + 16, 5, 14, 11, // 16 to 19 + 17, 6, 15, 8, + 18, 7, 12, 9, + 19, 4, 13, 10, + + 20, 23, 22, 21, // 20 to 23 + 21, 20, 23, 22, + 22, 21, 20, 23, + 23, 22, 21, 20 + }; u8 facedir = (param2 & 31) % 24; u8 index = facedir * 4 + rot; param2 &= ~31; param2 |= rotate_facedir[index]; - } else if (cpt2 == CPT2_WALLMOUNTED || cpt2 == CPT2_COLORED_WALLMOUNTED) { + } else if (cpt2 == CPT2_WALLMOUNTED || + cpt2 == CPT2_COLORED_WALLMOUNTED) { u8 wmountface = (param2 & 7); if (wmountface <= 1) return; @@ -214,30 +234,34 @@ void MapNode::rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot) } void transformNodeBox(const MapNode &n, const NodeBox &nodebox, - const NodeDefManager *nodemgr, std::vector *p_boxes, - u8 neighbors = 0) + const NodeDefManager *nodemgr, std::vector *p_boxes, + u8 neighbors = 0) { std::vector &boxes = *p_boxes; if (nodebox.type == NODEBOX_FIXED || nodebox.type == NODEBOX_LEVELED) { const std::vector &fixed = nodebox.fixed; int facedir = n.getFaceDir(nodemgr, true); - u8 axisdir = facedir >> 2; - facedir &= 0x03; + u8 axisdir = facedir>>2; + facedir&=0x03; for (aabb3f box : fixed) { if (nodebox.type == NODEBOX_LEVELED) - box.MaxEdge.Y = (-0.5f + n.getLevel(nodemgr) / 64.0f) * - BS; + box.MaxEdge.Y = (-0.5f + n.getLevel(nodemgr) / 64.0f) * BS; switch (axisdir) { case 0: - if (facedir == 1) { + if(facedir == 1) + { box.MinEdge.rotateXZBy(-90); box.MaxEdge.rotateXZBy(-90); - } else if (facedir == 2) { + } + else if(facedir == 2) + { box.MinEdge.rotateXZBy(180); box.MaxEdge.rotateXZBy(180); - } else if (facedir == 3) { + } + else if(facedir == 3) + { box.MinEdge.rotateXZBy(90); box.MaxEdge.rotateXZBy(90); } @@ -245,55 +269,75 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, case 1: // z+ box.MinEdge.rotateYZBy(90); box.MaxEdge.rotateYZBy(90); - if (facedir == 1) { + if(facedir == 1) + { box.MinEdge.rotateXYBy(90); box.MaxEdge.rotateXYBy(90); - } else if (facedir == 2) { + } + else if(facedir == 2) + { box.MinEdge.rotateXYBy(180); box.MaxEdge.rotateXYBy(180); - } else if (facedir == 3) { + } + else if(facedir == 3) + { box.MinEdge.rotateXYBy(-90); box.MaxEdge.rotateXYBy(-90); } break; - case 2: // z- + case 2: //z- box.MinEdge.rotateYZBy(-90); box.MaxEdge.rotateYZBy(-90); - if (facedir == 1) { + if(facedir == 1) + { box.MinEdge.rotateXYBy(-90); box.MaxEdge.rotateXYBy(-90); - } else if (facedir == 2) { + } + else if(facedir == 2) + { box.MinEdge.rotateXYBy(180); box.MaxEdge.rotateXYBy(180); - } else if (facedir == 3) { + } + else if(facedir == 3) + { box.MinEdge.rotateXYBy(90); box.MaxEdge.rotateXYBy(90); } break; - case 3: // x+ + case 3: //x+ box.MinEdge.rotateXYBy(-90); box.MaxEdge.rotateXYBy(-90); - if (facedir == 1) { + if(facedir == 1) + { box.MinEdge.rotateYZBy(90); box.MaxEdge.rotateYZBy(90); - } else if (facedir == 2) { + } + else if(facedir == 2) + { box.MinEdge.rotateYZBy(180); box.MaxEdge.rotateYZBy(180); - } else if (facedir == 3) { + } + else if(facedir == 3) + { box.MinEdge.rotateYZBy(-90); box.MaxEdge.rotateYZBy(-90); } break; - case 4: // x- + case 4: //x- box.MinEdge.rotateXYBy(90); box.MaxEdge.rotateXYBy(90); - if (facedir == 1) { + if(facedir == 1) + { box.MinEdge.rotateYZBy(-90); box.MaxEdge.rotateYZBy(-90); - } else if (facedir == 2) { + } + else if(facedir == 2) + { box.MinEdge.rotateYZBy(180); box.MaxEdge.rotateYZBy(180); - } else if (facedir == 3) { + } + else if(facedir == 3) + { box.MinEdge.rotateYZBy(90); box.MaxEdge.rotateYZBy(90); } @@ -301,13 +345,18 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, case 5: box.MinEdge.rotateXYBy(-180); box.MaxEdge.rotateXYBy(-180); - if (facedir == 1) { + if(facedir == 1) + { box.MinEdge.rotateXZBy(90); box.MaxEdge.rotateXZBy(90); - } else if (facedir == 2) { + } + else if(facedir == 2) + { box.MinEdge.rotateXZBy(180); box.MaxEdge.rotateXZBy(180); - } else if (facedir == 3) { + } + else if(facedir == 3) + { box.MinEdge.rotateXZBy(-90); box.MaxEdge.rotateXZBy(-90); } @@ -318,30 +367,38 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, box.repair(); boxes.push_back(box); } - } else if (nodebox.type == NODEBOX_WALLMOUNTED) { + } + else if(nodebox.type == NODEBOX_WALLMOUNTED) + { v3s16 dir = n.getWallMountedDir(nodemgr); // top - if (dir == v3s16(0, 1, 0)) { + if(dir == v3s16(0,1,0)) + { boxes.push_back(nodebox.wall_top); } // bottom - else if (dir == v3s16(0, -1, 0)) { + else if(dir == v3s16(0,-1,0)) + { boxes.push_back(nodebox.wall_bottom); } // side - else { - v3f vertices[2] = {nodebox.wall_side.MinEdge, - nodebox.wall_side.MaxEdge}; + else + { + v3f vertices[2] = + { + nodebox.wall_side.MinEdge, + nodebox.wall_side.MaxEdge + }; for (v3f &vertex : vertices) { - if (dir == v3s16(-1, 0, 0)) + if(dir == v3s16(-1,0,0)) vertex.rotateXZBy(0); - if (dir == v3s16(1, 0, 0)) + if(dir == v3s16(1,0,0)) vertex.rotateXZBy(180); - if (dir == v3s16(0, 0, -1)) + if(dir == v3s16(0,0,-1)) vertex.rotateXZBy(90); - if (dir == v3s16(0, 0, 1)) + if(dir == v3s16(0,0,1)) vertex.rotateXZBy(-90); } @@ -349,7 +406,9 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, box.addInternalPoint(vertices[1]); boxes.push_back(box); } - } else if (nodebox.type == NODEBOX_CONNECTED) { + } + else if (nodebox.type == NODEBOX_CONNECTED) + { size_t boxes_size = boxes.size(); boxes_size += nodebox.fixed.size(); if (neighbors & 1) @@ -390,10 +449,11 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, boxes.reserve(boxes_size); -#define BOXESPUSHBACK(c) \ - for (std::vector::const_iterator it = (c).begin(); it != (c).end(); \ - ++it) \ - (boxes).push_back(*it); +#define BOXESPUSHBACK(c) \ + for (std::vector::const_iterator \ + it = (c).begin(); \ + it != (c).end(); ++it) \ + (boxes).push_back(*it); BOXESPUSHBACK(nodebox.fixed); @@ -441,15 +501,16 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, BOXESPUSHBACK(nodebox.disconnected_sides); } - } else // NODEBOX_REGULAR + } + else // NODEBOX_REGULAR { - boxes.emplace_back(-BS / 2, -BS / 2, -BS / 2, BS / 2, BS / 2, BS / 2); + boxes.emplace_back(-BS/2,-BS/2,-BS/2,BS/2,BS/2,BS/2); } } -static inline void getNeighborConnectingFace(const v3s16 &p, - const NodeDefManager *nodedef, Map *map, MapNode n, u8 bitmask, - u8 *neighbors) +static inline void getNeighborConnectingFace( + const v3s16 &p, const NodeDefManager *nodedef, + Map *map, MapNode n, u8 bitmask, u8 *neighbors) { MapNode n2 = map->getNode(p); if (nodedef->nodeboxConnects(n, n2, bitmask)) @@ -492,15 +553,15 @@ u8 MapNode::getNeighbors(v3s16 p, Map *map) const return neighbors; } -void MapNode::getNodeBoxes(const NodeDefManager *nodemgr, std::vector *boxes, - u8 neighbors) const +void MapNode::getNodeBoxes(const NodeDefManager *nodemgr, + std::vector *boxes, u8 neighbors) const { const ContentFeatures &f = nodemgr->get(*this); transformNodeBox(*this, f.node_box, nodemgr, boxes, neighbors); } -void MapNode::getCollisionBoxes(const NodeDefManager *nodemgr, std::vector *boxes, - u8 neighbors) const +void MapNode::getCollisionBoxes(const NodeDefManager *nodemgr, + std::vector *boxes, u8 neighbors) const { const ContentFeatures &f = nodemgr->get(*this); if (f.collision_box.fixed.empty()) @@ -509,8 +570,8 @@ void MapNode::getCollisionBoxes(const NodeDefManager *nodemgr, std::vector *boxes, - u8 neighbors) const +void MapNode::getSelectionBoxes(const NodeDefManager *nodemgr, + std::vector *boxes, u8 neighbors) const { const ContentFeatures &f = nodemgr->get(*this); transformNodeBox(*this, f.selection_box, nodemgr, boxes, neighbors); @@ -520,9 +581,9 @@ u8 MapNode::getMaxLevel(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); // todo: after update in all games leave only if (f.param_type_2 == - if (f.liquid_type == LIQUID_FLOWING || f.param_type_2 == CPT2_FLOWINGLIQUID) + if( f.liquid_type == LIQUID_FLOWING || f.param_type_2 == CPT2_FLOWINGLIQUID) return LIQUID_LEVEL_MAX; - if (f.leveled || f.param_type_2 == CPT2_LEVELED) + if(f.leveled || f.param_type_2 == CPT2_LEVELED) return f.leveled_max; return 0; } @@ -531,11 +592,11 @@ u8 MapNode::getLevel(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); // todo: after update in all games leave only if (f.param_type_2 == - if (f.liquid_type == LIQUID_SOURCE) + if(f.liquid_type == LIQUID_SOURCE) return LIQUID_LEVEL_SOURCE; if (f.param_type_2 == CPT2_FLOWINGLIQUID) return getParam2() & LIQUID_LEVEL_MASK; - if (f.liquid_type == LIQUID_FLOWING) // can remove if all param_type_2 setted + if(f.liquid_type == LIQUID_FLOWING) // can remove if all param_type_2 setted return getParam2() & LIQUID_LEVEL_MASK; if (f.param_type_2 == CPT2_LEVELED) { u8 level = getParam2() & LEVELED_MASK; @@ -552,8 +613,9 @@ s8 MapNode::setLevel(const NodeDefManager *nodemgr, s16 level) { s8 rest = 0; const ContentFeatures &f = nodemgr->get(*this); - if (f.param_type_2 == CPT2_FLOWINGLIQUID || f.liquid_type == LIQUID_FLOWING || - f.liquid_type == LIQUID_SOURCE) { + if (f.param_type_2 == CPT2_FLOWINGLIQUID + || f.liquid_type == LIQUID_FLOWING + || f.liquid_type == LIQUID_SOURCE) { if (level <= 0) { // liquid can’t exist with zero level setContent(CONTENT_AIR); return 0; @@ -564,8 +626,7 @@ s8 MapNode::setLevel(const NodeDefManager *nodemgr, s16 level) setParam2(0); } else { setContent(f.liquid_alternative_flowing_id); - setParam2((level & LIQUID_LEVEL_MASK) | - (getParam2() & ~LIQUID_LEVEL_MASK)); + setParam2((level & LIQUID_LEVEL_MASK) | (getParam2() & ~LIQUID_LEVEL_MASK)); } } else if (f.param_type_2 == CPT2_LEVELED) { if (level < 0) { // zero means default for a leveled nodebox @@ -589,7 +650,7 @@ s8 MapNode::addLevel(const NodeDefManager *nodemgr, s16 add) u32 MapNode::serializedLength(u8 version) { - if (!ser_ver_supported(version)) + if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); if (version == 0) @@ -605,45 +666,47 @@ u32 MapNode::serializedLength(u8 version) } void MapNode::serialize(u8 *dest, u8 version) const { - if (!ser_ver_supported(version)) + if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); // Can't do this anymore; we have 16-bit dynamically allocated node IDs // in memory; conversion just won't work in this direction. - if (version < 24) + if(version < 24) throw SerializationError("MapNode::serialize: serialization to " - "version < 24 not possible"); + "version < 24 not possible"); - writeU16(dest + 0, param0); - writeU8(dest + 2, param1); - writeU8(dest + 3, param2); + writeU16(dest+0, param0); + writeU8(dest+2, param1); + writeU8(dest+3, param2); } void MapNode::deSerialize(u8 *source, u8 version) { - if (!ser_ver_supported(version)) + if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); - if (version <= 21) { + if(version <= 21) + { deSerialize_pre22(source, version); return; } - if (version >= 24) { - param0 = readU16(source + 0); - param1 = readU8(source + 2); - param2 = readU8(source + 3); - } else { - param0 = readU8(source + 0); - param1 = readU8(source + 1); - param2 = readU8(source + 2); - if (param0 > 0x7F) { - param0 |= ((param2 & 0xF0) << 4); + if(version >= 24){ + param0 = readU16(source+0); + param1 = readU8(source+2); + param2 = readU8(source+3); + }else{ + param0 = readU8(source+0); + param1 = readU8(source+1); + param2 = readU8(source+2); + if(param0 > 0x7F){ + param0 |= ((param2&0xF0)<<4); param2 &= 0x0F; } } } -void MapNode::serializeBulk(std::ostream &os, int version, const MapNode *nodes, - u32 nodecount, u8 content_width, u8 params_width, bool compressed) +void MapNode::serializeBulk(std::ostream &os, int version, + const MapNode *nodes, u32 nodecount, + u8 content_width, u8 params_width, bool compressed) { if (!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); @@ -655,7 +718,7 @@ void MapNode::serializeBulk(std::ostream &os, int version, const MapNode *nodes, // in memory; conversion just won't work in this direction. if (version < 24) throw SerializationError("MapNode::serializeBulk: serialization to " - "version < 24 not possible"); + "version < 24 not possible"); size_t databuf_size = nodecount * (content_width + params_width); u8 *databuf = new u8[databuf_size]; @@ -677,67 +740,78 @@ void MapNode::serializeBulk(std::ostream &os, int version, const MapNode *nodes, if (compressed) compressZlib(databuf, databuf_size, os); else - os.write((const char *)&databuf[0], databuf_size); + os.write((const char*) &databuf[0], databuf_size); - delete[] databuf; + delete [] databuf; } // Deserialize bulk node data -void MapNode::deSerializeBulk(std::istream &is, int version, MapNode *nodes, - u32 nodecount, u8 content_width, u8 params_width, bool compressed) +void MapNode::deSerializeBulk(std::istream &is, int version, + MapNode *nodes, u32 nodecount, + u8 content_width, u8 params_width, bool compressed) { - if (!ser_ver_supported(version)) + if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapNode format not supported"); - if (version < 22 || (content_width != 1 && content_width != 2) || - params_width != 2) + if (version < 22 + || (content_width != 1 && content_width != 2) + || params_width != 2) FATAL_ERROR("Deserialize bulk node data error"); // Uncompress or read data u32 len = nodecount * (content_width + params_width); SharedBuffer databuf(len); - if (compressed) { + if(compressed) + { std::ostringstream os(std::ios_base::binary); decompressZlib(is, os); std::string s = os.str(); - if (s.size() != len) + if(s.size() != len) throw SerializationError("deSerializeBulkNodes: " - "decompress resulted in invalid size"); + "decompress resulted in invalid size"); memcpy(&databuf[0], s.c_str(), len); - } else { - is.read((char *)&databuf[0], len); - if (is.eof() || is.fail()) + } + else + { + is.read((char*) &databuf[0], len); + if(is.eof() || is.fail()) throw SerializationError("deSerializeBulkNodes: " - "failed to read bulk node data"); + "failed to read bulk node data"); } // Deserialize content - if (content_width == 1) { - for (u32 i = 0; i < nodecount; i++) + if(content_width == 1) + { + for(u32 i=0; i 0x7F) { + if(nodes[i].param0 > 0x7F){ nodes[i].param0 <<= 4; - nodes[i].param0 |= (nodes[i].param2 & 0xF0) >> 4; + nodes[i].param0 |= (nodes[i].param2&0xF0)>>4; nodes[i].param2 &= 0x0F; } } - } else if (content_width == 2) { - for (u32 i = 0; i < nodecount; i++) + } + else if(content_width == 2) + { + for(u32 i=0; i 0x7f) { + if(param0 > 0x7f){ param0 <<= 4; - param0 |= (param2 & 0xf0) >> 4; + param0 |= (param2&0xf0)>>4; param2 &= 0x0f; } } // Convert special values from old version to new - if (version <= 19) { + if(version <= 19) + { // In these versions, CONTENT_IGNORE and CONTENT_AIR // are 255 and 254 // Version 19 is messed up with sometimes the old values and sometimes not - if (param0 == 255) + if(param0 == 255) param0 = CONTENT_IGNORE; - else if (param0 == 254) + else if(param0 == 254) param0 = CONTENT_AIR; } diff --git a/src/mapnode.h b/src/mapnode.h index eaf37b01f..32ac1b4f6 100644 --- a/src/mapnode.h +++ b/src/mapnode.h @@ -79,8 +79,7 @@ enum LightBank /* Simple rotation enum. */ -enum Rotation -{ +enum Rotation { ROTATE_0, ROTATE_90, ROTATE_180, @@ -99,20 +98,22 @@ enum Rotation /* maximum amount of liquid in a block */ #define LIQUID_LEVEL_MAX LIQUID_LEVEL_MASK -#define LIQUID_LEVEL_SOURCE (LIQUID_LEVEL_MAX + 1) +#define LIQUID_LEVEL_SOURCE (LIQUID_LEVEL_MAX+1) -#define LIQUID_INFINITY_MASK 0x80 // 0b10000000 +#define LIQUID_INFINITY_MASK 0x80 //0b10000000 // mask for leveled nodebox param2 #define LEVELED_MASK 0x7F #define LEVELED_MAX LEVELED_MASK + struct ContentFeatures; /* This is the stuff what the whole world consists of. */ + struct MapNode { /* @@ -138,24 +139,44 @@ struct MapNode MapNode() = default; - MapNode(content_t content, u8 a_param1 = 0, u8 a_param2 = 0) noexcept : - param0(content), param1(a_param1), param2(a_param2) - { - } + MapNode(content_t content, u8 a_param1=0, u8 a_param2=0) noexcept + : param0(content), + param1(a_param1), + param2(a_param2) + { } bool operator==(const MapNode &other) const noexcept { - return (param0 == other.param0 && param1 == other.param1 && - param2 == other.param2); + return (param0 == other.param0 + && param1 == other.param1 + && param2 == other.param2); } // To be used everywhere - content_t getContent() const noexcept { return param0; } - void setContent(content_t c) noexcept { param0 = c; } - u8 getParam1() const noexcept { return param1; } - void setParam1(u8 p) noexcept { param1 = p; } - u8 getParam2() const noexcept { return param2; } - void setParam2(u8 p) noexcept { param2 = p; } + content_t getContent() const noexcept + { + return param0; + } + void setContent(content_t c) noexcept + { + param0 = c; + } + u8 getParam1() const noexcept + { + return param1; + } + void setParam1(u8 p) noexcept + { + param1 = p; + } + u8 getParam2() const noexcept + { + return param2; + } + void setParam2(u8 p) noexcept + { + param2 = p; + } /*! * Returns the color of the node. @@ -203,7 +224,7 @@ struct MapNode u8 getLightNoChecks(LightBank bank, const ContentFeatures *f) const noexcept; bool getLightBanks(u8 &lightday, u8 &lightnight, - const NodeDefManager *nodemgr) const; + const NodeDefManager *nodemgr) const; // 0 <= daylight_factor <= 1000 // 0 <= return value <= LIGHT_SUN @@ -215,8 +236,7 @@ struct MapNode return blend_light(daylight_factor, lightday, lightnight); } - u8 getFaceDir(const NodeDefManager *nodemgr, - bool allow_wallmounted = false) const; + u8 getFaceDir(const NodeDefManager *nodemgr, bool allow_wallmounted = false) const; u8 getWallMounted(const NodeDefManager *nodemgr) const; v3s16 getWallMountedDir(const NodeDefManager *nodemgr) const; @@ -233,19 +253,19 @@ struct MapNode Gets list of node boxes (used for rendering (NDT_NODEBOX)) */ void getNodeBoxes(const NodeDefManager *nodemgr, std::vector *boxes, - u8 neighbors = 0) const; + u8 neighbors = 0) const; /* Gets list of selection boxes */ - void getSelectionBoxes(const NodeDefManager *nodemg, std::vector *boxes, - u8 neighbors = 0) const; + void getSelectionBoxes(const NodeDefManager *nodemg, + std::vector *boxes, u8 neighbors = 0) const; /* Gets list of collision boxes */ - void getCollisionBoxes(const NodeDefManager *nodemgr, std::vector *boxes, - u8 neighbors = 0) const; + void getCollisionBoxes(const NodeDefManager *nodemgr, + std::vector *boxes, u8 neighbors = 0) const; /* Liquid/leveled helpers @@ -270,12 +290,12 @@ struct MapNode // content_width = the number of bytes of content per node // params_width = the number of bytes of params per node // compressed = true to zlib-compress output - static void serializeBulk(std::ostream &os, int version, const MapNode *nodes, - u32 nodecount, u8 content_width, u8 params_width, - bool compressed); - static void deSerializeBulk(std::istream &is, int version, MapNode *nodes, - u32 nodecount, u8 content_width, u8 params_width, - bool compressed); + static void serializeBulk(std::ostream &os, int version, + const MapNode *nodes, u32 nodecount, + u8 content_width, u8 params_width, bool compressed); + static void deSerializeBulk(std::istream &is, int version, + MapNode *nodes, u32 nodecount, + u8 content_width, u8 params_width, bool compressed); private: // Deprecated serialization methods diff --git a/src/mapsector.cpp b/src/mapsector.cpp index b004b9013..3eefa5410 100644 --- a/src/mapsector.cpp +++ b/src/mapsector.cpp @@ -22,8 +22,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapblock.h" #include "serialization.h" -MapSector::MapSector(Map *parent, v2s16 pos, IGameDef *gamedef) : - m_parent(parent), m_pos(pos), m_gamedef(gamedef) +MapSector::MapSector(Map *parent, v2s16 pos, IGameDef *gamedef): + m_parent(parent), + m_pos(pos), + m_gamedef(gamedef) { } @@ -46,7 +48,7 @@ void MapSector::deleteBlocks() m_blocks.clear(); } -MapBlock *MapSector::getBlockBuffered(s16 y) +MapBlock * MapSector::getBlockBuffered(s16 y) { MapBlock *block; @@ -55,7 +57,7 @@ MapBlock *MapSector::getBlockBuffered(s16 y) } // If block doesn't exist, return NULL - std::unordered_map::const_iterator n = m_blocks.find(y); + std::unordered_map::const_iterator n = m_blocks.find(y); block = (n != m_blocks.end() ? n->second : nullptr); // Cache the last result @@ -65,14 +67,14 @@ MapBlock *MapSector::getBlockBuffered(s16 y) return block; } -MapBlock *MapSector::getBlockNoCreateNoEx(s16 y) +MapBlock * MapSector::getBlockNoCreateNoEx(s16 y) { return getBlockBuffered(y); } -MapBlock *MapSector::createBlankBlockNoInsert(s16 y) +MapBlock * MapSector::createBlankBlockNoInsert(s16 y) { - assert(getBlockBuffered(y) == NULL); // Pre-condition + assert(getBlockBuffered(y) == NULL); // Pre-condition v3s16 blockpos_map(m_pos.X, y, m_pos.Y); @@ -81,7 +83,7 @@ MapBlock *MapSector::createBlankBlockNoInsert(s16 y) return block; } -MapBlock *MapSector::createBlankBlock(s16 y) +MapBlock * MapSector::createBlankBlock(s16 y) { MapBlock *block = createBlankBlockNoInsert(y); diff --git a/src/mapsector.h b/src/mapsector.h index ff96be498..dede364f6 100644 --- a/src/mapsector.h +++ b/src/mapsector.h @@ -39,16 +39,20 @@ class IGameDef; class MapSector { public: + MapSector(Map *parent, v2s16 pos, IGameDef *gamedef); virtual ~MapSector(); void deleteBlocks(); - v2s16 getPos() { return m_pos; } + v2s16 getPos() + { + return m_pos; + } - MapBlock *getBlockNoCreateNoEx(s16 y); - MapBlock *createBlankBlockNoInsert(s16 y); - MapBlock *createBlankBlock(s16 y); + MapBlock * getBlockNoCreateNoEx(s16 y); + MapBlock * createBlankBlockNoInsert(s16 y); + MapBlock * createBlankBlock(s16 y); void insertBlock(MapBlock *block); @@ -59,8 +63,9 @@ class MapSector bool empty() const { return m_blocks.empty(); } protected: + // The pile of MapBlocks - std::unordered_map m_blocks; + std::unordered_map m_blocks; Map *m_parent; // Position on parent (in MapBlock widths) @@ -77,4 +82,5 @@ class MapSector Private methods */ MapBlock *getBlockBuffered(s16 y); + }; diff --git a/src/metadata.h b/src/metadata.h index 68b5c8f3c..5333f8a9d 100644 --- a/src/metadata.h +++ b/src/metadata.h @@ -27,7 +27,6 @@ with this program; if not, write to the Free Software Foundation, Inc., class Metadata { bool m_modified = false; - public: virtual ~Metadata() = default; @@ -35,7 +34,10 @@ class Metadata virtual bool empty() const; bool operator==(const Metadata &other) const; - inline bool operator!=(const Metadata &other) const { return !(*this == other); } + inline bool operator!=(const Metadata &other) const + { + return !(*this == other); + } // // Key-value related @@ -44,17 +46,18 @@ class Metadata size_t size() const; bool contains(const std::string &name) const; const std::string &getString(const std::string &name, u16 recursion = 0) const; - bool getStringToRef(const std::string &name, std::string &str, - u16 recursion = 0) const; + bool getStringToRef(const std::string &name, std::string &str, u16 recursion = 0) const; virtual bool setString(const std::string &name, const std::string &var); inline bool removeString(const std::string &name) { return setString(name, ""); } - const StringMap &getStrings() const { return m_stringvars; } + const StringMap &getStrings() const + { + return m_stringvars; + } // Add support for variable names in values const std::string &resolveString(const std::string &str, u16 recursion = 0) const; - inline bool isModified() const { return m_modified; } + inline bool isModified() const { return m_modified; } inline void setModified(bool v) { m_modified = v; } - protected: StringMap m_stringvars; }; diff --git a/src/network/address.cpp b/src/network/address.cpp index d24a56027..05678aa62 100644 --- a/src/network/address.cpp +++ b/src/network/address.cpp @@ -283,7 +283,7 @@ bool Address::isLocalhost() const auto addr = m_address.ipv6.sin6_addr.s6_addr; return memcmp(addr, localhost_bytes, 16) == 0 || - memcmp(addr, mapped_ipv4_localhost, 13) == 0; + memcmp(addr, mapped_ipv4_localhost, 13) == 0; } return (m_address.ipv4.sin_addr.s_addr & 0xFF) == 0x7f; diff --git a/src/network/clientopcodes.cpp b/src/network/clientopcodes.cpp index b7dd78f65..f812a08a1 100644 --- a/src/network/clientopcodes.cpp +++ b/src/network/clientopcodes.cpp @@ -20,152 +20,111 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "clientopcodes.h" -const static ToClientCommandHandler null_command_handler = { - "TOCLIENT_NULL", TOCLIENT_STATE_ALL, &Client::handleCommand_Null}; +const static ToClientCommandHandler null_command_handler = {"TOCLIENT_NULL", TOCLIENT_STATE_ALL, &Client::handleCommand_Null}; -const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] = { - null_command_handler, // 0x00 (never use this) - null_command_handler, // 0x01 - {"TOCLIENT_HELLO", TOCLIENT_STATE_NOT_CONNECTED, - &Client::handleCommand_Hello}, // 0x02 - {"TOCLIENT_AUTH_ACCEPT", TOCLIENT_STATE_NOT_CONNECTED, - &Client::handleCommand_AuthAccept}, // 0x03 - {"TOCLIENT_ACCEPT_SUDO_MODE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_AcceptSudoMode}, // 0x04 - {"TOCLIENT_DENY_SUDO_MODE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_DenySudoMode}, // 0x05 - null_command_handler, // 0x06 - null_command_handler, // 0x07 - null_command_handler, // 0x08 - null_command_handler, // 0x09 - {"TOCLIENT_ACCESS_DENIED", TOCLIENT_STATE_NOT_CONNECTED, - &Client::handleCommand_AccessDenied}, // 0x0A - null_command_handler, // 0x0B - null_command_handler, // 0x0C - null_command_handler, // 0x0D - null_command_handler, // 0x0E - null_command_handler, // 0x0F - null_command_handler, // 0x10 - null_command_handler, null_command_handler, null_command_handler, - null_command_handler, null_command_handler, null_command_handler, - null_command_handler, null_command_handler, null_command_handler, - null_command_handler, null_command_handler, null_command_handler, - null_command_handler, null_command_handler, null_command_handler, - {"TOCLIENT_BLOCKDATA", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_BlockData}, // 0x20 - {"TOCLIENT_ADDNODE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_AddNode}, // 0x21 - {"TOCLIENT_REMOVENODE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_RemoveNode}, // 0x22 - null_command_handler, null_command_handler, null_command_handler, - null_command_handler, - {"TOCLIENT_INVENTORY", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_Inventory}, // 0x27 - null_command_handler, - {"TOCLIENT_TIME_OF_DAY", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_TimeOfDay}, // 0x29 - {"TOCLIENT_CSM_RESTRICTION_FLAGS", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_CSMRestrictionFlags}, // 0x2A - {"TOCLIENT_PLAYER_SPEED", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_PlayerSpeed}, // 0x2B - {"TOCLIENT_MEDIA_PUSH", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_MediaPush}, // 0x2C - null_command_handler, null_command_handler, - {"TOCLIENT_CHAT_MESSAGE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ChatMessage}, // 0x2F - null_command_handler, // 0x30 - {"TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ActiveObjectRemoveAdd}, // 0x31 - {"TOCLIENT_ACTIVE_OBJECT_MESSAGES", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ActiveObjectMessages}, // 0x32 - {"TOCLIENT_HP", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HP}, // 0x33 - {"TOCLIENT_MOVE_PLAYER", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_MovePlayer}, // 0x34 - {"TOCLIENT_ACCESS_DENIED_LEGACY", TOCLIENT_STATE_NOT_CONNECTED, - &Client::handleCommand_AccessDenied}, // 0x35 - {"TOCLIENT_FOV", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_Fov}, // 0x36 - {"TOCLIENT_DEATHSCREEN", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_DeathScreen}, // 0x37 - {"TOCLIENT_MEDIA", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_Media}, // 0x38 - null_command_handler, - {"TOCLIENT_NODEDEF", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_NodeDef}, // 0x3a - null_command_handler, - {"TOCLIENT_ANNOUNCE_MEDIA", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_AnnounceMedia}, // 0x3c - {"TOCLIENT_ITEMDEF", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ItemDef}, // 0x3d - null_command_handler, - {"TOCLIENT_PLAY_SOUND", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_PlaySound}, // 0x3f - {"TOCLIENT_STOP_SOUND", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_StopSound}, // 0x40 - {"TOCLIENT_PRIVILEGES", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_Privileges}, // 0x41 - {"TOCLIENT_INVENTORY_FORMSPEC", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_InventoryFormSpec}, // 0x42 - {"TOCLIENT_DETACHED_INVENTORY", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_DetachedInventory}, // 0x43 - {"TOCLIENT_SHOW_FORMSPEC", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ShowFormSpec}, // 0x44 - {"TOCLIENT_MOVEMENT", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_Movement}, // 0x45 - {"TOCLIENT_SPAWN_PARTICLE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_SpawnParticle}, // 0x46 - {"TOCLIENT_ADD_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_AddParticleSpawner}, // 0x47 - null_command_handler, - {"TOCLIENT_HUDADD", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudAdd}, // 0x49 - {"TOCLIENT_HUDRM", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudRemove}, // 0x4a - {"TOCLIENT_HUDCHANGE", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudChange}, // 0x4b - {"TOCLIENT_HUD_SET_FLAGS", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudSetFlags}, // 0x4c - {"TOCLIENT_HUD_SET_PARAM", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudSetParam}, // 0x4d - {"TOCLIENT_BREATH", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_Breath}, // 0x4e - {"TOCLIENT_SET_SKY", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudSetSky}, // 0x4f - {"TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_OverrideDayNightRatio}, // 0x50 - {"TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_LocalPlayerAnimations}, // 0x51 - {"TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_EyeOffset}, // 0x52 - {"TOCLIENT_DELETE_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_DeleteParticleSpawner}, // 0x53 - {"TOCLIENT_CLOUD_PARAMS", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_CloudParams}, // 0x54 - {"TOCLIENT_FADE_SOUND", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_FadeSound}, // 0x55 - {"TOCLIENT_UPDATE_PLAYER_LIST", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_UpdatePlayerList}, // 0x56 - {"TOCLIENT_MODCHANNEL_MSG", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ModChannelMsg}, // 0x57 - {"TOCLIENT_MODCHANNEL_SIGNAL", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_ModChannelSignal}, // 0x58 - {"TOCLIENT_NODEMETA_CHANGED", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_NodemetaChanged}, // 0x59 - {"TOCLIENT_SET_SUN", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudSetSun}, // 0x5a - {"TOCLIENT_SET_MOON", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudSetMoon}, // 0x5b - {"TOCLIENT_SET_STARS", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_HudSetStars}, // 0x5c - null_command_handler, null_command_handler, null_command_handler, - {"TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED, - &Client::handleCommand_SrpBytesSandB}, // 0x60 - {"TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED, - &Client::handleCommand_FormspecPrepend}, // 0x61, +const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] = +{ + null_command_handler, // 0x00 (never use this) + null_command_handler, // 0x01 + { "TOCLIENT_HELLO", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_Hello }, // 0x02 + { "TOCLIENT_AUTH_ACCEPT", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AuthAccept }, // 0x03 + { "TOCLIENT_ACCEPT_SUDO_MODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AcceptSudoMode}, // 0x04 + { "TOCLIENT_DENY_SUDO_MODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DenySudoMode}, // 0x05 + null_command_handler, // 0x06 + null_command_handler, // 0x07 + null_command_handler, // 0x08 + null_command_handler, // 0x09 + { "TOCLIENT_ACCESS_DENIED", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AccessDenied }, // 0x0A + null_command_handler, // 0x0B + null_command_handler, // 0x0C + null_command_handler, // 0x0D + null_command_handler, // 0x0E + null_command_handler, // 0x0F + null_command_handler, // 0x10 + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + { "TOCLIENT_BLOCKDATA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_BlockData }, // 0x20 + { "TOCLIENT_ADDNODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AddNode }, // 0x21 + { "TOCLIENT_REMOVENODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_RemoveNode }, // 0x22 + null_command_handler, + null_command_handler, + null_command_handler, + null_command_handler, + { "TOCLIENT_INVENTORY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Inventory }, // 0x27 + null_command_handler, + { "TOCLIENT_TIME_OF_DAY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_TimeOfDay }, // 0x29 + { "TOCLIENT_CSM_RESTRICTION_FLAGS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_CSMRestrictionFlags }, // 0x2A + { "TOCLIENT_PLAYER_SPEED", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_PlayerSpeed }, // 0x2B + { "TOCLIENT_MEDIA_PUSH", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MediaPush }, // 0x2C + null_command_handler, + null_command_handler, + { "TOCLIENT_CHAT_MESSAGE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ChatMessage }, // 0x2F + null_command_handler, // 0x30 + { "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ActiveObjectRemoveAdd }, // 0x31 + { "TOCLIENT_ACTIVE_OBJECT_MESSAGES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ActiveObjectMessages }, // 0x32 + { "TOCLIENT_HP", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HP }, // 0x33 + { "TOCLIENT_MOVE_PLAYER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MovePlayer }, // 0x34 + { "TOCLIENT_ACCESS_DENIED_LEGACY", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AccessDenied }, // 0x35 + { "TOCLIENT_FOV", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Fov }, // 0x36 + { "TOCLIENT_DEATHSCREEN", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DeathScreen }, // 0x37 + { "TOCLIENT_MEDIA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Media }, // 0x38 + null_command_handler, + { "TOCLIENT_NODEDEF", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_NodeDef }, // 0x3a + null_command_handler, + { "TOCLIENT_ANNOUNCE_MEDIA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AnnounceMedia }, // 0x3c + { "TOCLIENT_ITEMDEF", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ItemDef }, // 0x3d + null_command_handler, + { "TOCLIENT_PLAY_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_PlaySound }, // 0x3f + { "TOCLIENT_STOP_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_StopSound }, // 0x40 + { "TOCLIENT_PRIVILEGES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Privileges }, // 0x41 + { "TOCLIENT_INVENTORY_FORMSPEC", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_InventoryFormSpec }, // 0x42 + { "TOCLIENT_DETACHED_INVENTORY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DetachedInventory }, // 0x43 + { "TOCLIENT_SHOW_FORMSPEC", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ShowFormSpec }, // 0x44 + { "TOCLIENT_MOVEMENT", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Movement }, // 0x45 + { "TOCLIENT_SPAWN_PARTICLE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_SpawnParticle }, // 0x46 + { "TOCLIENT_ADD_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AddParticleSpawner }, // 0x47 + null_command_handler, + { "TOCLIENT_HUDADD", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudAdd }, // 0x49 + { "TOCLIENT_HUDRM", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudRemove }, // 0x4a + { "TOCLIENT_HUDCHANGE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudChange }, // 0x4b + { "TOCLIENT_HUD_SET_FLAGS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetFlags }, // 0x4c + { "TOCLIENT_HUD_SET_PARAM", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetParam }, // 0x4d + { "TOCLIENT_BREATH", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Breath }, // 0x4e + { "TOCLIENT_SET_SKY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetSky }, // 0x4f + { "TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_OverrideDayNightRatio }, // 0x50 + { "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_LocalPlayerAnimations }, // 0x51 + { "TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_EyeOffset }, // 0x52 + { "TOCLIENT_DELETE_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DeleteParticleSpawner }, // 0x53 + { "TOCLIENT_CLOUD_PARAMS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_CloudParams }, // 0x54 + { "TOCLIENT_FADE_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FadeSound }, // 0x55 + { "TOCLIENT_UPDATE_PLAYER_LIST", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_UpdatePlayerList }, // 0x56 + { "TOCLIENT_MODCHANNEL_MSG", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ModChannelMsg }, // 0x57 + { "TOCLIENT_MODCHANNEL_SIGNAL", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ModChannelSignal }, // 0x58 + { "TOCLIENT_NODEMETA_CHANGED", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_NodemetaChanged }, // 0x59 + { "TOCLIENT_SET_SUN", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetSun }, // 0x5a + { "TOCLIENT_SET_MOON", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetMoon }, // 0x5b + { "TOCLIENT_SET_STARS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetStars }, // 0x5c + null_command_handler, + null_command_handler, + null_command_handler, + { "TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_SrpBytesSandB }, // 0x60 + { "TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FormspecPrepend }, // 0x61, }; -const static ServerCommandFactory null_command_factory = {"TOSERVER_NULL", 0, false}; +const static ServerCommandFactory null_command_factory = { "TOSERVER_NULL", 0, false }; /* Channels used for Client -> Server communication @@ -177,88 +136,89 @@ const static ServerCommandFactory null_command_factory = {"TOSERVER_NULL", 0, fa the same objects are *required* to be in the same channel. */ -const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES] = { - null_command_factory, // 0x00 - null_command_factory, // 0x01 - {"TOSERVER_INIT", 1, false}, // 0x02 - null_command_factory, // 0x03 - null_command_factory, // 0x04 - null_command_factory, // 0x05 - null_command_factory, // 0x06 - null_command_factory, // 0x07 - null_command_factory, // 0x08 - null_command_factory, // 0x09 - null_command_factory, // 0x0a - null_command_factory, // 0x0b - null_command_factory, // 0x0c - null_command_factory, // 0x0d - null_command_factory, // 0x0e - null_command_factory, // 0x0f - null_command_factory, // 0x10 - {"TOSERVER_INIT2", 1, true}, // 0x11 - null_command_factory, // 0x12 - null_command_factory, // 0x13 - null_command_factory, // 0x14 - null_command_factory, // 0x15 - null_command_factory, // 0x16 - {"TOSERVER_MODCHANNEL_JOIN", 0, true}, // 0x17 - {"TOSERVER_MODCHANNEL_LEAVE", 0, true}, // 0x18 - {"TOSERVER_MODCHANNEL_MSG", 0, true}, // 0x19 - null_command_factory, // 0x1a - null_command_factory, // 0x1b - null_command_factory, // 0x1c - null_command_factory, // 0x1d - null_command_factory, // 0x1e - null_command_factory, // 0x1f - null_command_factory, // 0x20 - null_command_factory, // 0x21 - null_command_factory, // 0x22 - {"TOSERVER_PLAYERPOS", 0, false}, // 0x23 - {"TOSERVER_GOTBLOCKS", 2, true}, // 0x24 - {"TOSERVER_DELETEDBLOCKS", 2, true}, // 0x25 - null_command_factory, // 0x26 - null_command_factory, // 0x27 - null_command_factory, // 0x28 - null_command_factory, // 0x29 - null_command_factory, // 0x2a - null_command_factory, // 0x2b - null_command_factory, // 0x2c - null_command_factory, // 0x2d - null_command_factory, // 0x2e - null_command_factory, // 0x2f - null_command_factory, // 0x30 - {"TOSERVER_INVENTORY_ACTION", 0, true}, // 0x31 - {"TOSERVER_CHAT_MESSAGE", 0, true}, // 0x32 - null_command_factory, // 0x33 - null_command_factory, // 0x34 - {"TOSERVER_DAMAGE", 0, true}, // 0x35 - null_command_factory, // 0x36 - {"TOSERVER_PLAYERITEM", 0, true}, // 0x37 - {"TOSERVER_RESPAWN", 0, true}, // 0x38 - {"TOSERVER_INTERACT", 0, true}, // 0x39 - {"TOSERVER_REMOVED_SOUNDS", 2, true}, // 0x3a - {"TOSERVER_NODEMETA_FIELDS", 0, true}, // 0x3b - {"TOSERVER_INVENTORY_FIELDS", 0, true}, // 0x3c - null_command_factory, // 0x3d - null_command_factory, // 0x3e - null_command_factory, // 0x3f - {"TOSERVER_REQUEST_MEDIA", 1, true}, // 0x40 - null_command_factory, // 0x41 - null_command_factory, // 0x42 - {"TOSERVER_CLIENT_READY", 1, true}, // 0x43 - null_command_factory, // 0x44 - null_command_factory, // 0x45 - null_command_factory, // 0x46 - null_command_factory, // 0x47 - null_command_factory, // 0x48 - null_command_factory, // 0x49 - null_command_factory, // 0x4a - null_command_factory, // 0x4b - null_command_factory, // 0x4c - null_command_factory, // 0x4d - null_command_factory, // 0x4e - null_command_factory, // 0x4f - {"TOSERVER_FIRST_SRP", 1, true}, // 0x50 - {"TOSERVER_SRP_BYTES_A", 1, true}, // 0x51 - {"TOSERVER_SRP_BYTES_M", 1, true}, // 0x52 +const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES] = +{ + null_command_factory, // 0x00 + null_command_factory, // 0x01 + { "TOSERVER_INIT", 1, false }, // 0x02 + null_command_factory, // 0x03 + null_command_factory, // 0x04 + null_command_factory, // 0x05 + null_command_factory, // 0x06 + null_command_factory, // 0x07 + null_command_factory, // 0x08 + null_command_factory, // 0x09 + null_command_factory, // 0x0a + null_command_factory, // 0x0b + null_command_factory, // 0x0c + null_command_factory, // 0x0d + null_command_factory, // 0x0e + null_command_factory, // 0x0f + null_command_factory, // 0x10 + { "TOSERVER_INIT2", 1, true }, // 0x11 + null_command_factory, // 0x12 + null_command_factory, // 0x13 + null_command_factory, // 0x14 + null_command_factory, // 0x15 + null_command_factory, // 0x16 + { "TOSERVER_MODCHANNEL_JOIN", 0, true }, // 0x17 + { "TOSERVER_MODCHANNEL_LEAVE", 0, true }, // 0x18 + { "TOSERVER_MODCHANNEL_MSG", 0, true }, // 0x19 + null_command_factory, // 0x1a + null_command_factory, // 0x1b + null_command_factory, // 0x1c + null_command_factory, // 0x1d + null_command_factory, // 0x1e + null_command_factory, // 0x1f + null_command_factory, // 0x20 + null_command_factory, // 0x21 + null_command_factory, // 0x22 + { "TOSERVER_PLAYERPOS", 0, false }, // 0x23 + { "TOSERVER_GOTBLOCKS", 2, true }, // 0x24 + { "TOSERVER_DELETEDBLOCKS", 2, true }, // 0x25 + null_command_factory, // 0x26 + null_command_factory, // 0x27 + null_command_factory, // 0x28 + null_command_factory, // 0x29 + null_command_factory, // 0x2a + null_command_factory, // 0x2b + null_command_factory, // 0x2c + null_command_factory, // 0x2d + null_command_factory, // 0x2e + null_command_factory, // 0x2f + null_command_factory, // 0x30 + { "TOSERVER_INVENTORY_ACTION", 0, true }, // 0x31 + { "TOSERVER_CHAT_MESSAGE", 0, true }, // 0x32 + null_command_factory, // 0x33 + null_command_factory, // 0x34 + { "TOSERVER_DAMAGE", 0, true }, // 0x35 + null_command_factory, // 0x36 + { "TOSERVER_PLAYERITEM", 0, true }, // 0x37 + { "TOSERVER_RESPAWN", 0, true }, // 0x38 + { "TOSERVER_INTERACT", 0, true }, // 0x39 + { "TOSERVER_REMOVED_SOUNDS", 2, true }, // 0x3a + { "TOSERVER_NODEMETA_FIELDS", 0, true }, // 0x3b + { "TOSERVER_INVENTORY_FIELDS", 0, true }, // 0x3c + null_command_factory, // 0x3d + null_command_factory, // 0x3e + null_command_factory, // 0x3f + { "TOSERVER_REQUEST_MEDIA", 1, true }, // 0x40 + null_command_factory, // 0x41 + null_command_factory, // 0x42 + { "TOSERVER_CLIENT_READY", 1, true }, // 0x43 + null_command_factory, // 0x44 + null_command_factory, // 0x45 + null_command_factory, // 0x46 + null_command_factory, // 0x47 + null_command_factory, // 0x48 + null_command_factory, // 0x49 + null_command_factory, // 0x4a + null_command_factory, // 0x4b + null_command_factory, // 0x4c + null_command_factory, // 0x4d + null_command_factory, // 0x4e + null_command_factory, // 0x4f + { "TOSERVER_FIRST_SRP", 1, true }, // 0x50 + { "TOSERVER_SRP_BYTES_A", 1, true }, // 0x51 + { "TOSERVER_SRP_BYTES_M", 1, true }, // 0x52 }; diff --git a/src/network/clientopcodes.h b/src/network/clientopcodes.h index d984d0cb7..d03dc457d 100644 --- a/src/network/clientopcodes.h +++ b/src/network/clientopcodes.h @@ -25,8 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class NetworkPacket; -enum ToClientConnectionState -{ +enum ToClientConnectionState { TOCLIENT_STATE_NOT_CONNECTED, TOCLIENT_STATE_CONNECTED, TOCLIENT_STATE_ALL, @@ -34,14 +33,14 @@ enum ToClientConnectionState struct ToClientCommandHandler { - const char *name; - ToClientConnectionState state; - void (Client::*handler)(NetworkPacket *pkt); + const char* name; + ToClientConnectionState state; + void (Client::*handler)(NetworkPacket* pkt); }; struct ServerCommandFactory { - const char *name; + const char* name; u8 channel; bool reliable; }; diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 7e72bc549..f0fb09fad 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -46,14 +46,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gettext.h" #include "skyparams.h" -void Client::handleCommand_Deprecated(NetworkPacket *pkt) +void Client::handleCommand_Deprecated(NetworkPacket* pkt) { infostream << "Got deprecated command " - << toClientCommandTable[pkt->getCommand()].name << " from peer " - << pkt->getPeerId() << "!" << std::endl; + << toClientCommandTable[pkt->getCommand()].name << " from peer " + << pkt->getPeerId() << "!" << std::endl; } -void Client::handleCommand_Hello(NetworkPacket *pkt) +void Client::handleCommand_Hello(NetworkPacket* pkt) { if (pkt->getSize() < 1) return; @@ -63,38 +63,39 @@ void Client::handleCommand_Hello(NetworkPacket *pkt) u16 compression_mode; u32 auth_mechs; std::string username_legacy; // for case insensitivity - *pkt >> serialization_ver >> compression_mode >> proto_ver >> auth_mechs >> - username_legacy; + *pkt >> serialization_ver >> compression_mode >> proto_ver + >> auth_mechs >> username_legacy; // Chose an auth method we support AuthMechanism chosen_auth_mechanism = choseAuthMech(auth_mechs); infostream << "Client: TOCLIENT_HELLO received with " - << "serialization_ver=" << (u32)serialization_ver - << ", auth_mechs=" << auth_mechs << ", proto_ver=" << proto_ver - << ", compression_mode=" << compression_mode - << ". Doing auth with mech " << chosen_auth_mechanism << std::endl; + << "serialization_ver=" << (u32)serialization_ver + << ", auth_mechs=" << auth_mechs + << ", proto_ver=" << proto_ver + << ", compression_mode=" << compression_mode + << ". Doing auth with mech " << chosen_auth_mechanism << std::endl; if (!ser_ver_supported(serialization_ver)) { infostream << "Client: TOCLIENT_HELLO: Server sent " - << "unsupported ser_fmt_ver" << std::endl; + << "unsupported ser_fmt_ver"<< std::endl; return; } m_server_ser_ver = serialization_ver; m_proto_ver = proto_ver; - // TODO verify that username_legacy matches sent username, only + //TODO verify that username_legacy matches sent username, only // differs in casing (make both uppercase and compare) // This is only neccessary though when we actually want to add casing support if (m_chosen_auth_mech != AUTH_MECHANISM_NONE) { // we recieved a TOCLIENT_HELLO while auth was already going on errorstream << "Client: TOCLIENT_HELLO while auth was already going on" - << "(chosen_mech=" << m_chosen_auth_mech << ")." << std::endl; + << "(chosen_mech=" << m_chosen_auth_mech << ")." << std::endl; if (m_chosen_auth_mech == AUTH_MECHANISM_SRP || m_chosen_auth_mech == AUTH_MECHANISM_LEGACY_PASSWORD) { - srp_user_delete((SRPUser *)m_auth_data); + srp_user_delete((SRPUser *) m_auth_data); m_auth_data = 0; } } @@ -115,15 +116,16 @@ void Client::handleCommand_Hello(NetworkPacket *pkt) m_access_denied_reason = "Unknown"; m_con->Disconnect(); } + } -void Client::handleCommand_AuthAccept(NetworkPacket *pkt) +void Client::handleCommand_AuthAccept(NetworkPacket* pkt) { deleteAuthData(); v3f playerpos; - *pkt >> playerpos >> m_map_seed >> m_recommended_send_interval >> - m_sudo_auth_methods; + *pkt >> playerpos >> m_map_seed >> m_recommended_send_interval + >> m_sudo_auth_methods; playerpos -= v3f(0, BS / 2, 0); @@ -134,7 +136,7 @@ void Client::handleCommand_AuthAccept(NetworkPacket *pkt) infostream << "Client: received map seed: " << m_map_seed << std::endl; infostream << "Client: received recommended send interval " - << m_recommended_send_interval << std::endl; + << m_recommended_send_interval<getSize() < 6) return; @@ -235,7 +237,7 @@ void Client::handleCommand_RemoveNode(NetworkPacket *pkt) removeNode(p); } -void Client::handleCommand_AddNode(NetworkPacket *pkt) +void Client::handleCommand_AddNode(NetworkPacket* pkt) { if (pkt->getSize() < 6 + MapNode::serializedLength(m_server_ser_ver)) return; @@ -272,7 +274,8 @@ void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt) i != meta_updates_list.end(); ++i) { v3s16 pos = i->first; - if (map.isValidPosition(pos) && map.setNodeMetadata(pos, i->second)) + if (map.isValidPosition(pos) && + map.setNodeMetadata(pos, i->second)) continue; // Prevent from deleting metadata // Meta couldn't be set, unused metadata @@ -280,7 +283,7 @@ void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt) } } -void Client::handleCommand_BlockData(NetworkPacket *pkt) +void Client::handleCommand_BlockData(NetworkPacket* pkt) { // Ignore too small packet if (pkt->getSize() < 6) @@ -307,7 +310,8 @@ void Client::handleCommand_BlockData(NetworkPacket *pkt) */ block->deSerialize(istr, m_server_ser_ver, false); block->deSerializeNetworkSpecific(istr); - } else { + } + else { /* Create a new block */ @@ -327,7 +331,7 @@ void Client::handleCommand_BlockData(NetworkPacket *pkt) addUpdateMeshTaskWithEdge(p, true); } -void Client::handleCommand_Inventory(NetworkPacket *pkt) +void Client::handleCommand_Inventory(NetworkPacket* pkt) { if (pkt->getSize() < 1) return; @@ -347,7 +351,7 @@ void Client::handleCommand_Inventory(NetworkPacket *pkt) m_inventory_from_server_age = 0.0; } -void Client::handleCommand_TimeOfDay(NetworkPacket *pkt) +void Client::handleCommand_TimeOfDay(NetworkPacket* pkt) { if (pkt->getSize() < 2) return; @@ -356,12 +360,13 @@ void Client::handleCommand_TimeOfDay(NetworkPacket *pkt) *pkt >> time_of_day; - time_of_day = time_of_day % 24000; + time_of_day = time_of_day % 24000; float time_speed = 0; if (pkt->getSize() >= 2 + 4) { *pkt >> time_speed; - } else { + } + else { // Old message; try to approximate speed of time by ourselves float time_of_day_f = (float)time_of_day / 24000.0f; float tod_diff_f = 0; @@ -371,15 +376,15 @@ void Client::handleCommand_TimeOfDay(NetworkPacket *pkt) else tod_diff_f = time_of_day_f - m_last_time_of_day_f; - m_last_time_of_day_f = time_of_day_f; - float time_diff = m_time_of_day_update_timer; + m_last_time_of_day_f = time_of_day_f; + float time_diff = m_time_of_day_update_timer; m_time_of_day_update_timer = 0; if (m_time_of_day_set) { time_speed = (3600.0f * 24.0f) * tod_diff_f / time_diff; infostream << "Client: Measured time_of_day speed (old format): " - << time_speed << " tod_diff_f=" << tod_diff_f - << " time_diff=" << time_diff << std::endl; + << time_speed << " tod_diff_f=" << tod_diff_f + << " time_diff=" << time_diff << std::endl; } } @@ -388,8 +393,8 @@ void Client::handleCommand_TimeOfDay(NetworkPacket *pkt) m_env.setTimeOfDaySpeed(time_speed); m_time_of_day_set = true; - // u32 dr = m_env.getDayNightRatio(); - // infostream << "Client: time_of_day=" << time_of_day + //u32 dr = m_env.getDayNightRatio(); + //infostream << "Client: time_of_day=" << time_of_day // << " time_speed=" << time_speed // << " dr=" << dr << std::endl; } @@ -418,11 +423,11 @@ void Client::handleCommand_ChatMessage(NetworkPacket *pkt) *pkt >> chatMessage->sender >> chatMessage->message >> timestamp; chatMessage->timestamp = static_cast(timestamp); - chatMessage->type = (ChatMessageType)message_type; + chatMessage->type = (ChatMessageType) message_type; // @TODO send this to CSM using ChatMessage object if (modsLoaded() && m_script->on_receiving_message( - wide_to_utf8(chatMessage->message))) { + wide_to_utf8(chatMessage->message))) { // Message was consumed by CSM and should not be handled by client delete chatMessage; } else { @@ -430,7 +435,7 @@ void Client::handleCommand_ChatMessage(NetworkPacket *pkt) } } -void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt) +void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt) { /* u16 count of removed objects @@ -445,10 +450,10 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt) string initialization data } */ - + LocalPlayer *player = m_env.getLocalPlayer(); - bool try_reattach = player && player->isWaitingForReattach(); - + bool try_reattach = player && player->isWaitingForReattach(); + try { u8 type; u16 removed_count, added_count, id; @@ -472,7 +477,7 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt) } } catch (PacketError &e) { infostream << "handleCommand_ActiveObjectRemoveAdd: " << e.what() - << ". The packet is unreliable, ignoring" << std::endl; + << ". The packet is unreliable, ignoring" << std::endl; } // m_activeobjects_received is false before the first @@ -480,7 +485,7 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt) m_activeobjects_received = true; } -void Client::handleCommand_ActiveObjectMessages(NetworkPacket *pkt) +void Client::handleCommand_ActiveObjectMessages(NetworkPacket* pkt) { /* for all objects @@ -506,32 +511,32 @@ void Client::handleCommand_ActiveObjectMessages(NetworkPacket *pkt) } } catch (SerializationError &e) { errorstream << "Client::handleCommand_ActiveObjectMessages: " - << "caught SerializationError: " << e.what() << std::endl; + << "caught SerializationError: " << e.what() << std::endl; } } -void Client::handleCommand_Movement(NetworkPacket *pkt) +void Client::handleCommand_Movement(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); float mad, maa, maf, msw, mscr, msf, mscl, msj, lf, lfs, ls, g; - *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj >> lf >> lfs >> - ls >> g; - - player->movement_acceleration_default = mad * BS; - player->movement_acceleration_air = maa * BS; - player->movement_acceleration_fast = maf * BS; - player->movement_speed_walk = msw * BS; - player->movement_speed_crouch = mscr * BS; - player->movement_speed_fast = msf * BS; - player->movement_speed_climb = mscl * BS; - player->movement_speed_jump = msj * BS; - player->movement_liquid_fluidity = lf * BS; + *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj + >> lf >> lfs >> ls >> g; + + player->movement_acceleration_default = mad * BS; + player->movement_acceleration_air = maa * BS; + player->movement_acceleration_fast = maf * BS; + player->movement_speed_walk = msw * BS; + player->movement_speed_crouch = mscr * BS; + player->movement_speed_fast = msf * BS; + player->movement_speed_climb = mscl * BS; + player->movement_speed_jump = msj * BS; + player->movement_liquid_fluidity = lf * BS; player->movement_liquid_fluidity_smooth = lfs * BS; - player->movement_liquid_sink = ls * BS; - player->movement_gravity = g * BS; + player->movement_liquid_sink = ls * BS; + player->movement_gravity = g * BS; } void Client::handleCommand_Fov(NetworkPacket *pkt) @@ -546,12 +551,11 @@ void Client::handleCommand_Fov(NetworkPacket *pkt) // try-catch to preserve backwards compat try { *pkt >> transition_time; - } catch (PacketError &e) { - }; + } catch (PacketError &e) {}; LocalPlayer *player = m_env.getLocalPlayer(); assert(player); - player->setFov({fov, is_multiplier, transition_time}); + player->setFov({ fov, is_multiplier, transition_time }); m_camera->notifyFovChange(); } @@ -579,7 +583,7 @@ void Client::handleCommand_HP(NetworkPacket *pkt) } } -void Client::handleCommand_Breath(NetworkPacket *pkt) +void Client::handleCommand_Breath(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); @@ -591,15 +595,14 @@ void Client::handleCommand_Breath(NetworkPacket *pkt) player->setBreath(breath); } -void Client::handleCommand_MovePlayer(NetworkPacket *pkt) -{ +void Client::handleCommand_MovePlayer(NetworkPacket* pkt) +{ LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); - if ((player->getCAO() && player->getCAO()->getParentId()) || - player->isWaitingForReattach()) + if ((player->getCAO() && player->getCAO()->getParentId()) || player->isWaitingForReattach()) return; - + v3f pos; f32 pitch, yaw; @@ -608,8 +611,10 @@ void Client::handleCommand_MovePlayer(NetworkPacket *pkt) player->setLegitPosition(pos); infostream << "Client got TOCLIENT_MOVE_PLAYER" - << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" - << " pitch=" << pitch << " yaw=" << yaw << std::endl; + << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" + << " pitch=" << pitch + << " yaw=" << yaw + << std::endl; /* Add to ClientEvent queue. @@ -617,10 +622,10 @@ void Client::handleCommand_MovePlayer(NetworkPacket *pkt) it would just force the pitch and yaw values to whatever the camera points to. */ - + if (g_settings->getBool("no_force_rotate")) return; - + ClientEvent *event = new ClientEvent(); event->type = CE_PLAYER_FORCE_MOVE; event->player_force_move.pitch = pitch; @@ -628,7 +633,7 @@ void Client::handleCommand_MovePlayer(NetworkPacket *pkt) m_client_event_queue.push(event); } -void Client::handleCommand_DeathScreen(NetworkPacket *pkt) +void Client::handleCommand_DeathScreen(NetworkPacket* pkt) { bool set_camera_point_target; v3f camera_point_target; @@ -637,32 +642,32 @@ void Client::handleCommand_DeathScreen(NetworkPacket *pkt) *pkt >> camera_point_target; ClientEvent *event = new ClientEvent(); - event->type = CE_DEATHSCREEN; + event->type = CE_DEATHSCREEN; event->deathscreen.set_camera_point_target = set_camera_point_target; - event->deathscreen.camera_point_target_x = camera_point_target.X; - event->deathscreen.camera_point_target_y = camera_point_target.Y; - event->deathscreen.camera_point_target_z = camera_point_target.Z; + event->deathscreen.camera_point_target_x = camera_point_target.X; + event->deathscreen.camera_point_target_y = camera_point_target.Y; + event->deathscreen.camera_point_target_z = camera_point_target.Z; m_client_event_queue.push(event); } -void Client::handleCommand_AnnounceMedia(NetworkPacket *pkt) +void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt) { u16 num_files; *pkt >> num_files; infostream << "Client: Received media announcement: packet size: " - << pkt->getSize() << std::endl; - - if (m_media_downloader == NULL || m_media_downloader->isStarted()) { - const char *problem = - m_media_downloader - ? "we already saw another announcement" - : "all media has been received already"; - errorstream << "Client: Received media announcement but " << problem - << "! " - << " files=" << num_files << " size=" << pkt->getSize() - << std::endl; + << pkt->getSize() << std::endl; + + if (m_media_downloader == NULL || + m_media_downloader->isStarted()) { + const char *problem = m_media_downloader ? + "we already saw another announcement" : + "all media has been received already"; + errorstream << "Client: Received media announcement but " + << problem << "! " + << " files=" << num_files + << " size=" << pkt->getSize() << std::endl; return; } @@ -685,19 +690,20 @@ void Client::handleCommand_AnnounceMedia(NetworkPacket *pkt) *pkt >> str; Strfnd sf(str); - while (!sf.at_end()) { + while(!sf.at_end()) { std::string baseurl = trim(sf.next(",")); if (!baseurl.empty()) m_media_downloader->addRemoteServer(baseurl); } - } catch (SerializationError &e) { + } + catch(SerializationError& e) { // not supported by server or turned off } m_media_downloader->step(this); } -void Client::handleCommand_Media(NetworkPacket *pkt) +void Client::handleCommand_Media(NetworkPacket* pkt) { /* u16 command @@ -717,21 +723,22 @@ void Client::handleCommand_Media(NetworkPacket *pkt) *pkt >> num_bunches >> bunch_i >> num_files; - infostream << "Client: Received files: bunch " << bunch_i << "/" << num_bunches - << " files=" << num_files << " size=" << pkt->getSize() << std::endl; + infostream << "Client: Received files: bunch " << bunch_i << "/" + << num_bunches << " files=" << num_files + << " size=" << pkt->getSize() << std::endl; if (num_files == 0) return; if (!m_media_downloader || !m_media_downloader->isStarted()) { - const char *problem = - m_media_downloader - ? "media has not been requested" - : "all media has been received already"; - errorstream << "Client: Received media but " << problem << "! " - << " bunch " << bunch_i << "/" << num_bunches - << " files=" << num_files << " size=" << pkt->getSize() - << std::endl; + const char *problem = m_media_downloader ? + "media has not been requested" : + "all media has been received already"; + errorstream << "Client: Received media but " + << problem << "! " + << " bunch " << bunch_i << "/" << num_bunches + << " files=" << num_files + << " size=" << pkt->getSize() << std::endl; return; } @@ -739,21 +746,22 @@ void Client::handleCommand_Media(NetworkPacket *pkt) // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); - for (u32 i = 0; i < num_files; i++) { + for (u32 i=0; i < num_files; i++) { std::string name; *pkt >> name; std::string data = pkt->readLongString(); - m_media_downloader->conventionalTransferDone(name, data, this); + m_media_downloader->conventionalTransferDone( + name, data, this); } } -void Client::handleCommand_NodeDef(NetworkPacket *pkt) +void Client::handleCommand_NodeDef(NetworkPacket* pkt) { - infostream << "Client: Received node definitions: packet size: " << pkt->getSize() - << std::endl; + infostream << "Client: Received node definitions: packet size: " + << pkt->getSize() << std::endl; // Mesh update thread must be stopped while // updating content definitions @@ -770,10 +778,10 @@ void Client::handleCommand_NodeDef(NetworkPacket *pkt) m_nodedef_received = true; } -void Client::handleCommand_ItemDef(NetworkPacket *pkt) +void Client::handleCommand_ItemDef(NetworkPacket* pkt) { - infostream << "Client: Received item definitions: packet size: " << pkt->getSize() - << std::endl; + infostream << "Client: Received item definitions: packet size: " + << pkt->getSize() << std::endl; // Mesh update thread must be stopped while // updating content definitions @@ -790,7 +798,7 @@ void Client::handleCommand_ItemDef(NetworkPacket *pkt) m_itemdef_received = true; } -void Client::handleCommand_PlaySound(NetworkPacket *pkt) +void Client::handleCommand_PlaySound(NetworkPacket* pkt) { /* [0] u32 server_id @@ -824,27 +832,27 @@ void Client::handleCommand_PlaySound(NetworkPacket *pkt) *pkt >> fade; *pkt >> pitch; *pkt >> ephemeral; - } catch (PacketError &e) { - }; + } catch (PacketError &e) {}; // Start playing int client_id = -1; - switch (type) { - case 0: // local - client_id = m_sound->playSound(name, loop, gain, fade, pitch); - break; - case 1: // positional - client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); - break; - case 2: { // object - ClientActiveObject *cao = m_env.getActiveObject(object_id); - if (cao) - pos = cao->getPosition(); - client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); - break; - } - default: - break; + switch(type) { + case 0: // local + client_id = m_sound->playSound(name, loop, gain, fade, pitch); + break; + case 1: // positional + client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); + break; + case 2: + { // object + ClientActiveObject *cao = m_env.getActiveObject(object_id); + if (cao) + pos = cao->getPosition(); + client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); + break; + } + default: + break; } if (client_id != -1) { @@ -858,14 +866,13 @@ void Client::handleCommand_PlaySound(NetworkPacket *pkt) } } -void Client::handleCommand_StopSound(NetworkPacket *pkt) +void Client::handleCommand_StopSound(NetworkPacket* pkt) { s32 server_id; *pkt >> server_id; - std::unordered_map::iterator i = - m_sounds_server_to_client.find(server_id); + std::unordered_map::iterator i = m_sounds_server_to_client.find(server_id); if (i != m_sounds_server_to_client.end()) { int client_id = i->second; m_sound->stopSound(client_id); @@ -887,7 +894,7 @@ void Client::handleCommand_FadeSound(NetworkPacket *pkt) m_sound->fadeSound(i->second, step, gain); } -void Client::handleCommand_Privileges(NetworkPacket *pkt) +void Client::handleCommand_Privileges(NetworkPacket* pkt) { m_privileges.clear(); infostream << "Client: Privileges updated: "; @@ -906,7 +913,7 @@ void Client::handleCommand_Privileges(NetworkPacket *pkt) infostream << std::endl; } -void Client::handleCommand_InventoryFormSpec(NetworkPacket *pkt) +void Client::handleCommand_InventoryFormSpec(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); @@ -915,14 +922,14 @@ void Client::handleCommand_InventoryFormSpec(NetworkPacket *pkt) player->inventory_formspec = pkt->readLongString(); } -void Client::handleCommand_DetachedInventory(NetworkPacket *pkt) +void Client::handleCommand_DetachedInventory(NetworkPacket* pkt) { std::string name; bool keep_inv = true; *pkt >> name >> keep_inv; infostream << "Client: Detached inventory update: \"" << name - << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl; + << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl; const auto &inv_it = m_detached_inventories.find(name); if (!keep_inv) { @@ -948,7 +955,7 @@ void Client::handleCommand_DetachedInventory(NetworkPacket *pkt) inv->deSerialize(is); } -void Client::handleCommand_ShowFormSpec(NetworkPacket *pkt) +void Client::handleCommand_ShowFormSpec(NetworkPacket* pkt) { std::string formspec = pkt->readLongString(); std::string formname; @@ -964,7 +971,7 @@ void Client::handleCommand_ShowFormSpec(NetworkPacket *pkt) m_client_event_queue.push(event); } -void Client::handleCommand_SpawnParticle(NetworkPacket *pkt) +void Client::handleCommand_SpawnParticle(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); @@ -973,17 +980,17 @@ void Client::handleCommand_SpawnParticle(NetworkPacket *pkt) p.deSerialize(is, m_proto_ver); ClientEvent *event = new ClientEvent(); - event->type = CE_SPAWN_PARTICLE; + event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); - + if (g_settings->getBool("log_particles")) { std::cout << p.pos.X << " " << p.pos.Y << " " << p.pos.Z << std::endl; } - + m_client_event_queue.push(event); } -void Client::handleCommand_AddParticleSpawner(NetworkPacket *pkt) +void Client::handleCommand_AddParticleSpawner(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); @@ -992,20 +999,20 @@ void Client::handleCommand_AddParticleSpawner(NetworkPacket *pkt) u32 server_id; u16 attached_id = 0; - p.amount = readU16(is); - p.time = readF32(is); - p.minpos = readV3F32(is); - p.maxpos = readV3F32(is); - p.minvel = readV3F32(is); - p.maxvel = readV3F32(is); - p.minacc = readV3F32(is); - p.maxacc = readV3F32(is); - p.minexptime = readF32(is); - p.maxexptime = readF32(is); - p.minsize = readF32(is); - p.maxsize = readF32(is); + p.amount = readU16(is); + p.time = readF32(is); + p.minpos = readV3F32(is); + p.maxpos = readV3F32(is); + p.minvel = readV3F32(is); + p.maxvel = readV3F32(is); + p.minacc = readV3F32(is); + p.maxacc = readV3F32(is); + p.minexptime = readF32(is); + p.maxexptime = readF32(is); + p.minsize = readF32(is); + p.maxsize = readF32(is); p.collisiondetection = readU8(is); - p.texture = deSerializeLongString(is); + p.texture = deSerializeLongString(is); server_id = readU32(is); @@ -1025,19 +1032,20 @@ void Client::handleCommand_AddParticleSpawner(NetworkPacket *pkt) break; p.node.param0 = tmp_param0; p.node.param2 = readU8(is); - p.node_tile = readU8(is); + p.node_tile = readU8(is); } while (0); auto event = new ClientEvent(); - event->type = CE_ADD_PARTICLESPAWNER; - event->add_particlespawner.p = new ParticleSpawnerParameters(p); + event->type = CE_ADD_PARTICLESPAWNER; + event->add_particlespawner.p = new ParticleSpawnerParameters(p); event->add_particlespawner.attached_id = attached_id; - event->add_particlespawner.id = server_id; + event->add_particlespawner.id = server_id; m_client_event_queue.push(event); } -void Client::handleCommand_DeleteParticleSpawner(NetworkPacket *pkt) + +void Client::handleCommand_DeleteParticleSpawner(NetworkPacket* pkt) { u32 server_id; *pkt >> server_id; @@ -1049,7 +1057,7 @@ void Client::handleCommand_DeleteParticleSpawner(NetworkPacket *pkt) m_client_event_queue.push(event); } -void Client::handleCommand_HudAdd(NetworkPacket *pkt) +void Client::handleCommand_HudAdd(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); @@ -1070,37 +1078,36 @@ void Client::handleCommand_HudAdd(NetworkPacket *pkt) s16 z_index = 0; std::string text2; - *pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item >> - dir >> align >> offset; + *pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item + >> dir >> align >> offset; try { *pkt >> world_pos; *pkt >> size; *pkt >> z_index; *pkt >> text2; - } catch (PacketError &e) { - }; + } catch(PacketError &e) {}; ClientEvent *event = new ClientEvent(); - event->type = CE_HUDADD; + event->type = CE_HUDADD; event->hudadd.server_id = server_id; - event->hudadd.type = type; - event->hudadd.pos = new v2f(pos); - event->hudadd.name = new std::string(name); - event->hudadd.scale = new v2f(scale); - event->hudadd.text = new std::string(text); - event->hudadd.number = number; - event->hudadd.item = item; - event->hudadd.dir = dir; - event->hudadd.align = new v2f(align); - event->hudadd.offset = new v2f(offset); + event->hudadd.type = type; + event->hudadd.pos = new v2f(pos); + event->hudadd.name = new std::string(name); + event->hudadd.scale = new v2f(scale); + event->hudadd.text = new std::string(text); + event->hudadd.number = number; + event->hudadd.item = item; + event->hudadd.dir = dir; + event->hudadd.align = new v2f(align); + event->hudadd.offset = new v2f(offset); event->hudadd.world_pos = new v3f(world_pos); - event->hudadd.size = new v2s32(size); - event->hudadd.z_index = z_index; - event->hudadd.text2 = new std::string(text2); + event->hudadd.size = new v2s32(size); + event->hudadd.z_index = z_index; + event->hudadd.text2 = new std::string(text2); m_client_event_queue.push(event); } -void Client::handleCommand_HudRemove(NetworkPacket *pkt) +void Client::handleCommand_HudRemove(NetworkPacket* pkt) { u32 server_id; @@ -1112,13 +1119,13 @@ void Client::handleCommand_HudRemove(NetworkPacket *pkt) m_hud_server_to_client.erase(i); ClientEvent *event = new ClientEvent(); - event->type = CE_HUDRM; + event->type = CE_HUDRM; event->hudrm.id = client_id; m_client_event_queue.push(event); } } -void Client::handleCommand_HudChange(NetworkPacket *pkt) +void Client::handleCommand_HudChange(NetworkPacket* pkt) { std::string sdata; v2f v2fdata; @@ -1130,35 +1137,34 @@ void Client::handleCommand_HudChange(NetworkPacket *pkt) *pkt >> server_id >> stat; - if (stat == HUD_STAT_POS || stat == HUD_STAT_SCALE || stat == HUD_STAT_ALIGN || - stat == HUD_STAT_OFFSET) + if (stat == HUD_STAT_POS || stat == HUD_STAT_SCALE || + stat == HUD_STAT_ALIGN || stat == HUD_STAT_OFFSET) *pkt >> v2fdata; else if (stat == HUD_STAT_NAME || stat == HUD_STAT_TEXT || stat == HUD_STAT_TEXT2) *pkt >> sdata; else if (stat == HUD_STAT_WORLD_POS) *pkt >> v3fdata; - else if (stat == HUD_STAT_SIZE) + else if (stat == HUD_STAT_SIZE ) *pkt >> v2s32data; else *pkt >> intdata; - std::unordered_map::const_iterator i = - m_hud_server_to_client.find(server_id); + std::unordered_map::const_iterator i = m_hud_server_to_client.find(server_id); if (i != m_hud_server_to_client.end()) { ClientEvent *event = new ClientEvent(); - event->type = CE_HUDCHANGE; - event->hudchange.id = i->second; - event->hudchange.stat = (HudElementStat)stat; + event->type = CE_HUDCHANGE; + event->hudchange.id = i->second; + event->hudchange.stat = (HudElementStat)stat; event->hudchange.v2fdata = new v2f(v2fdata); event->hudchange.v3fdata = new v3f(v3fdata); - event->hudchange.sdata = new std::string(sdata); - event->hudchange.data = intdata; + event->hudchange.sdata = new std::string(sdata); + event->hudchange.data = intdata; event->hudchange.v2s32data = new v2s32(v2s32data); m_client_event_queue.push(event); } } -void Client::handleCommand_HudSetFlags(NetworkPacket *pkt) +void Client::handleCommand_HudSetFlags(NetworkPacket* pkt) { u32 flags, mask; @@ -1168,22 +1174,20 @@ void Client::handleCommand_HudSetFlags(NetworkPacket *pkt) assert(player != NULL); bool was_minimap_visible = player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE; - bool was_minimap_radar_visible = - player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE; + bool was_minimap_radar_visible = player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE; player->hud_flags &= ~mask; player->hud_flags |= flags; if (g_settings->getBool("hud_flags_bypass")) - player->hud_flags = - HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE | - HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE | - HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE | - HUD_FLAG_MINIMAP_RADAR_VISIBLE; + player->hud_flags = HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE | + HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE | + HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE | + HUD_FLAG_MINIMAP_RADAR_VISIBLE; + m_minimap_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE); - bool m_minimap_radar_disabled_by_server = - !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE); + bool m_minimap_radar_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE); // Hide minimap if it has been disabled by the server if (m_minimap && m_minimap_disabled_by_server && was_minimap_visible) @@ -1194,12 +1198,13 @@ void Client::handleCommand_HudSetFlags(NetworkPacket *pkt) // Switch to surface mode if radar disabled by server if (m_minimap && m_minimap_radar_disabled_by_server && was_minimap_radar_visible) m_minimap->setMinimapMode(MINIMAP_MODE_SURFACEx1); + + } -void Client::handleCommand_HudSetParam(NetworkPacket *pkt) +void Client::handleCommand_HudSetParam(NetworkPacket* pkt) { - u16 param; - std::string value; + u16 param; std::string value; *pkt >> param >> value; @@ -1207,17 +1212,19 @@ void Client::handleCommand_HudSetParam(NetworkPacket *pkt) assert(player != NULL); if (param == HUD_PARAM_HOTBAR_ITEMCOUNT && value.size() == 4) { - s32 hotbar_itemcount = readS32((u8 *)value.c_str()); + s32 hotbar_itemcount = readS32((u8*) value.c_str()); if (hotbar_itemcount > 0 && hotbar_itemcount <= HUD_HOTBAR_ITEMCOUNT_MAX) player->hud_hotbar_itemcount = hotbar_itemcount; - } else if (param == HUD_PARAM_HOTBAR_IMAGE) { + } + else if (param == HUD_PARAM_HOTBAR_IMAGE) { player->hotbar_image = value; - } else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) { + } + else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) { player->hotbar_selected_image = value; } } -void Client::handleCommand_HudSetSky(NetworkPacket *pkt) +void Client::handleCommand_HudSetSky(NetworkPacket* pkt) { if (m_proto_ver < 39) { // Handle Protocol 38 and below servers with old set_sky, @@ -1236,8 +1243,7 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt) skybox.clouds = true; try { skybox.clouds = readU8(is); - } catch (...) { - } + } catch (...) {} // Use default skybox settings: SkyboxDefaults sky_defaults; @@ -1251,7 +1257,8 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt) skybox.fog_tint_type = "default"; skybox.fog_moon_tint = video::SColor(255, 255, 255, 255); skybox.fog_sun_tint = video::SColor(255, 255, 255, 255); - } else { + } + else { sun.visible = false; sun.sunrise_visible = false; moon.visible = false; @@ -1284,8 +1291,7 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt) std::string texture; *pkt >> skybox.bgcolor >> skybox.type >> skybox.clouds >> - skybox.fog_sun_tint >> skybox.fog_moon_tint >> - skybox.fog_tint_type; + skybox.fog_sun_tint >> skybox.fog_moon_tint >> skybox.fog_tint_type; if (skybox.type == "skybox") { *pkt >> texture_count; @@ -1293,14 +1299,12 @@ void Client::handleCommand_HudSetSky(NetworkPacket *pkt) *pkt >> texture; skybox.textures.emplace_back(texture); } - } else if (skybox.type == "regular") { - *pkt >> skybox.sky_color.day_sky >> - skybox.sky_color.day_horizon >> - skybox.sky_color.dawn_sky >> - skybox.sky_color.dawn_horizon >> - skybox.sky_color.night_sky >> - skybox.sky_color.night_horizon >> - skybox.sky_color.indoors; + } + else if (skybox.type == "regular") { + *pkt >> skybox.sky_color.day_sky >> skybox.sky_color.day_horizon + >> skybox.sky_color.dawn_sky >> skybox.sky_color.dawn_horizon + >> skybox.sky_color.night_sky >> skybox.sky_color.night_horizon + >> skybox.sky_color.indoors; } ClientEvent *event = new ClientEvent(); @@ -1314,12 +1318,12 @@ void Client::handleCommand_HudSetSun(NetworkPacket *pkt) { SunParams sun; - *pkt >> sun.visible >> sun.texture >> sun.tonemap >> sun.sunrise >> - sun.sunrise_visible >> sun.scale; + *pkt >> sun.visible >> sun.texture>> sun.tonemap + >> sun.sunrise >> sun.sunrise_visible >> sun.scale; ClientEvent *event = new ClientEvent(); - event->type = CE_SET_SUN; - event->sun_params = new SunParams(sun); + event->type = CE_SET_SUN; + event->sun_params = new SunParams(sun); m_client_event_queue.push(event); } @@ -1327,10 +1331,11 @@ void Client::handleCommand_HudSetMoon(NetworkPacket *pkt) { MoonParams moon; - *pkt >> moon.visible >> moon.texture >> moon.tonemap >> moon.scale; + *pkt >> moon.visible >> moon.texture + >> moon.tonemap >> moon.scale; ClientEvent *event = new ClientEvent(); - event->type = CE_SET_MOON; + event->type = CE_SET_MOON; event->moon_params = new MoonParams(moon); m_client_event_queue.push(event); } @@ -1339,16 +1344,17 @@ void Client::handleCommand_HudSetStars(NetworkPacket *pkt) { StarParams stars; - *pkt >> stars.visible >> stars.count >> stars.starcolor >> stars.scale; + *pkt >> stars.visible >> stars.count + >> stars.starcolor >> stars.scale; ClientEvent *event = new ClientEvent(); - event->type = CE_SET_STARS; + event->type = CE_SET_STARS; event->star_params = new StarParams(stars); m_client_event_queue.push(event); } -void Client::handleCommand_CloudParams(NetworkPacket *pkt) +void Client::handleCommand_CloudParams(NetworkPacket* pkt) { f32 density; video::SColor color_bright; @@ -1357,25 +1363,26 @@ void Client::handleCommand_CloudParams(NetworkPacket *pkt) f32 thickness; v2f speed; - *pkt >> density >> color_bright >> color_ambient >> height >> thickness >> speed; + *pkt >> density >> color_bright >> color_ambient + >> height >> thickness >> speed; ClientEvent *event = new ClientEvent(); - event->type = CE_CLOUD_PARAMS; - event->cloud_params.density = density; + event->type = CE_CLOUD_PARAMS; + event->cloud_params.density = density; // use the underlying u32 representation, because we can't // use struct members with constructors here, and this way // we avoid using new() and delete() for no good reason - event->cloud_params.color_bright = color_bright.color; + event->cloud_params.color_bright = color_bright.color; event->cloud_params.color_ambient = color_ambient.color; - event->cloud_params.height = height; - event->cloud_params.thickness = thickness; + event->cloud_params.height = height; + event->cloud_params.thickness = thickness; // same here: deconstruct to skip constructor - event->cloud_params.speed_x = speed.X; - event->cloud_params.speed_y = speed.Y; + event->cloud_params.speed_x = speed.X; + event->cloud_params.speed_y = speed.Y; m_client_event_queue.push(event); } -void Client::handleCommand_OverrideDayNightRatio(NetworkPacket *pkt) +void Client::handleCommand_OverrideDayNightRatio(NetworkPacket* pkt) { bool do_override; u16 day_night_ratio_u; @@ -1385,13 +1392,13 @@ void Client::handleCommand_OverrideDayNightRatio(NetworkPacket *pkt) float day_night_ratio_f = (float)day_night_ratio_u / 65536; ClientEvent *event = new ClientEvent(); - event->type = CE_OVERRIDE_DAY_NIGHT_RATIO; + event->type = CE_OVERRIDE_DAY_NIGHT_RATIO; event->override_day_night_ratio.do_override = do_override; - event->override_day_night_ratio.ratio_f = day_night_ratio_f; + event->override_day_night_ratio.ratio_f = day_night_ratio_f; m_client_event_queue.push(event); } -void Client::handleCommand_LocalPlayerAnimations(NetworkPacket *pkt) +void Client::handleCommand_LocalPlayerAnimations(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); @@ -1403,7 +1410,7 @@ void Client::handleCommand_LocalPlayerAnimations(NetworkPacket *pkt) *pkt >> player->local_animation_speed; } -void Client::handleCommand_EyeOffset(NetworkPacket *pkt) +void Client::handleCommand_EyeOffset(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); @@ -1411,12 +1418,12 @@ void Client::handleCommand_EyeOffset(NetworkPacket *pkt) *pkt >> player->eye_offset_first >> player->eye_offset_third; } -void Client::handleCommand_UpdatePlayerList(NetworkPacket *pkt) +void Client::handleCommand_UpdatePlayerList(NetworkPacket* pkt) { u8 type; u16 num_players; *pkt >> type >> num_players; - PlayerListModifer notice_type = (PlayerListModifer)type; + PlayerListModifer notice_type = (PlayerListModifer) type; for (u16 i = 0; i < num_players; i++) { std::string name; @@ -1433,30 +1440,30 @@ void Client::handleCommand_UpdatePlayerList(NetworkPacket *pkt) } } -void Client::handleCommand_SrpBytesSandB(NetworkPacket *pkt) +void Client::handleCommand_SrpBytesSandB(NetworkPacket* pkt) { if (m_chosen_auth_mech != AUTH_MECHANISM_SRP && m_chosen_auth_mech != AUTH_MECHANISM_LEGACY_PASSWORD) { errorstream << "Client: Received SRP S_B login message," - << " but wasn't supposed to (chosen_mech=" - << m_chosen_auth_mech << ")." << std::endl; + << " but wasn't supposed to (chosen_mech=" + << m_chosen_auth_mech << ")." << std::endl; return; } char *bytes_M = 0; size_t len_M = 0; - SRPUser *usr = (SRPUser *)m_auth_data; + SRPUser *usr = (SRPUser *) m_auth_data; std::string s; std::string B; *pkt >> s >> B; infostream << "Client: Received TOCLIENT_SRP_BYTES_S_B." << std::endl; - srp_user_process_challenge(usr, (const unsigned char *)s.c_str(), s.size(), - (const unsigned char *)B.c_str(), B.size(), - (unsigned char **)&bytes_M, &len_M); + srp_user_process_challenge(usr, (const unsigned char *) s.c_str(), s.size(), + (const unsigned char *) B.c_str(), B.size(), + (unsigned char **) &bytes_M, &len_M); - if (!bytes_M) { + if ( !bytes_M ) { errorstream << "Client: SRP-6a S_B safety check violation!" << std::endl; return; } @@ -1511,8 +1518,8 @@ void Client::handleCommand_MediaPush(NetworkPacket *pkt) } verbosestream << "Server pushes media file \"" << filename << "\" with " - << filedata.size() << " bytes of data (cached=" << cached << ")" - << std::endl; + << filedata.size() << " bytes of data (cached=" << cached + << ")" << std::endl; if (m_media_pushed_files.count(filename) != 0) { // Silently ignore for synchronization purposes @@ -1525,7 +1532,7 @@ void Client::handleCommand_MediaPush(NetworkPacket *pkt) SHA1 ctx; ctx.addBytes(filedata.c_str(), filedata.size()); unsigned char *buf = ctx.getDigest(); - computed_hash.assign((char *)buf, 20); + computed_hash.assign((char*) buf, 20); free(buf); } if (raw_hash != computed_hash) { @@ -1552,12 +1559,12 @@ void Client::handleCommand_ModChannelMsg(NetworkPacket *pkt) *pkt >> channel_name >> sender >> channel_msg; verbosestream << "Mod channel message received from server " << pkt->getPeerId() - << " on channel " << channel_name << ". sender: `" << sender - << "`, message: " << channel_msg << std::endl; + << " on channel " << channel_name << ". sender: `" << sender << "`, message: " + << channel_msg << std::endl; if (!m_modchannel_mgr->channelRegistered(channel_name)) { verbosestream << "Server sent us messages on unregistered channel " - << channel_name << ", ignoring." << std::endl; + << channel_name << ", ignoring." << std::endl; return; } @@ -1577,57 +1584,56 @@ void Client::handleCommand_ModChannelSignal(NetworkPacket *pkt) bool valid_signal = true; // @TODO: send Signal to Lua API switch (signal) { - case MODCHANNEL_SIGNAL_JOIN_OK: - m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE); - infostream << "Server ack our mod channel join on channel `" << channel - << "`, joining." << std::endl; - break; - case MODCHANNEL_SIGNAL_JOIN_FAILURE: - // Unable to join, remove channel - m_modchannel_mgr->leaveChannel(channel, 0); - infostream << "Server refused our mod channel join on channel `" - << channel << "`" << std::endl; - break; - case MODCHANNEL_SIGNAL_LEAVE_OK: + case MODCHANNEL_SIGNAL_JOIN_OK: + m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE); + infostream << "Server ack our mod channel join on channel `" << channel + << "`, joining." << std::endl; + break; + case MODCHANNEL_SIGNAL_JOIN_FAILURE: + // Unable to join, remove channel + m_modchannel_mgr->leaveChannel(channel, 0); + infostream << "Server refused our mod channel join on channel `" << channel + << "`" << std::endl; + break; + case MODCHANNEL_SIGNAL_LEAVE_OK: #ifndef NDEBUG - infostream << "Server ack our mod channel leave on channel " << channel - << "`, leaving." << std::endl; + infostream << "Server ack our mod channel leave on channel " << channel + << "`, leaving." << std::endl; #endif - break; - case MODCHANNEL_SIGNAL_LEAVE_FAILURE: - infostream << "Server refused our mod channel leave on channel `" - << channel << "`" << std::endl; - break; - case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED: + break; + case MODCHANNEL_SIGNAL_LEAVE_FAILURE: + infostream << "Server refused our mod channel leave on channel `" << channel + << "`" << std::endl; + break; + case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED: #ifndef NDEBUG - // Generally unused, but ensure we don't do an implementation error - infostream << "Server tells us we sent a message on channel `" << channel - << "` but we are not registered. Message was dropped." - << std::endl; + // Generally unused, but ensure we don't do an implementation error + infostream << "Server tells us we sent a message on channel `" << channel + << "` but we are not registered. Message was dropped." << std::endl; #endif - break; - case MODCHANNEL_SIGNAL_SET_STATE: { - u8 state; - *pkt >> state; - - if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) { - infostream << "Received wrong channel state " << state - << ", ignoring." << std::endl; - return; - } + break; + case MODCHANNEL_SIGNAL_SET_STATE: { + u8 state; + *pkt >> state; + + if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) { + infostream << "Received wrong channel state " << state + << ", ignoring." << std::endl; + return; + } - m_modchannel_mgr->setChannelState(channel, (ModChannelState)state); - infostream << "Server sets mod channel `" << channel - << "` in read-only mode." << std::endl; - break; - } - default: + m_modchannel_mgr->setChannelState(channel, (ModChannelState) state); + infostream << "Server sets mod channel `" << channel + << "` in read-only mode." << std::endl; + break; + } + default: #ifndef NDEBUG - warningstream << "Received unhandled mod channel signal ID " << signal - << ", ignoring." << std::endl; + warningstream << "Received unhandled mod channel signal ID " + << signal << ", ignoring." << std::endl; #endif - valid_signal = false; - break; + valid_signal = false; + break; } // If signal is valid, forward it to client side mods diff --git a/src/network/connection.cpp b/src/network/connection.cpp index dbcece99d..3692e45a9 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -41,29 +41,29 @@ namespace con /* defines used for debugging and profiling */ /******************************************************************************/ #ifdef NDEBUG -#define LOG(a) a -#define PROFILE(a) + #define LOG(a) a + #define PROFILE(a) #else -#if 0 + #if 0 /* this mutex is used to achieve log message consistency */ std::mutex log_message_mutex; -#define LOG(a) \ - { \ - MutexAutoLock loglock(log_message_mutex); \ - a; \ - } -#else -// Prevent deadlocks until a solution is found after 5.2.0 (TODO) -#define LOG(a) a -#endif + #define LOG(a) \ + { \ + MutexAutoLock loglock(log_message_mutex); \ + a; \ + } + #else + // Prevent deadlocks until a solution is found after 5.2.0 (TODO) + #define LOG(a) a + #endif -#define PROFILE(a) a + #define PROFILE(a) a #endif #define PING_TIMEOUT 5.0 -BufferedPacket makePacket(Address &address, const SharedBuffer &data, u32 protocol_id, - session_t sender_peer_id, u8 channel) +BufferedPacket makePacket(Address &address, const SharedBuffer &data, + u32 protocol_id, session_t sender_peer_id, u8 channel) { u32 packet_size = data.getSize() + BASE_HEADER_SIZE; BufferedPacket p(packet_size); @@ -123,7 +123,8 @@ void makeSplitPacket(const SharedBuffer &data, u32 chunksize_max, u16 seqnum start = end + 1; chunk_num++; - } while (end != data.getSize() - 1); + } + while (end != data.getSize() - 1); for (SharedBuffer &chunk : *chunks) { // Write chunk_count @@ -166,11 +167,11 @@ SharedBuffer makeReliablePacket(const SharedBuffer &data, u16 seqnum) void ReliablePacketBuffer::print() { MutexAutoLock listlock(m_list_mutex); - LOG(dout_con << "Dump of ReliablePacketBuffer:" << std::endl); + LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl); unsigned int index = 0; for (BufferedPacket &bufferedPacket : m_list) { - u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE + 1])); - LOG(dout_con << index << ":" << s << std::endl); + u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1])); + LOG(dout_con<::iterator i = m_list.begin(); - for (; i != m_list.end(); ++i) { - u16 s = readU16(&(i->data[BASE_HEADER_SIZE + 1])); + for(; i != m_list.end(); ++i) + { + u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); if (s == seqnum) break; } @@ -203,7 +205,7 @@ RPBSearchResult ReliablePacketBuffer::notFound() return m_list.end(); } -bool ReliablePacketBuffer::getFirstSeqnum(u16 &result) +bool ReliablePacketBuffer::getFirstSeqnum(u16& result) { MutexAutoLock listlock(m_list_mutex); if (m_list.empty()) @@ -235,16 +237,17 @@ BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum) MutexAutoLock listlock(m_list_mutex); RPBSearchResult r = findPacket(seqnum); if (r == notFound()) { - LOG(dout_con << "Sequence number: " << seqnum - << " not found in reliable buffer" << std::endl); + LOG(dout_con<<"Sequence number: " << seqnum + << " not found in reliable buffer"<data[BASE_HEADER_SIZE + 1])); + u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1])); m_oldest_non_answered_ack = s; } @@ -264,27 +267,25 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected) MutexAutoLock listlock(m_list_mutex); if (p.data.getSize() < BASE_HEADER_SIZE + 3) { errorstream << "ReliablePacketBuffer::insert(): Invalid data size for " - "reliable packet" - << std::endl; + "reliable packet" << std::endl; return; } u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]); if (type != PACKET_TYPE_RELIABLE) { errorstream << "ReliablePacketBuffer::insert(): type is not reliable" - << std::endl; + << std::endl; return; } u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]); if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) { errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of " - "expected window " - << std::endl; + "expected window " << std::endl; return; } if (seqnum == next_expected) { errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected" - << std::endl; + << std::endl; return; } @@ -292,7 +293,8 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected) // Find the right place for the packet and insert it there // If list is empty, just add it - if (m_list.empty()) { + if (m_list.empty()) + { m_list.push_back(p); m_oldest_non_answered_ack = seqnum; // Done. @@ -302,47 +304,47 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected) // Otherwise find the right place std::list::iterator i = m_list.begin(); // Find the first packet in the list which has a higher seqnum - u16 s = readU16(&(i->data[BASE_HEADER_SIZE + 1])); + u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); /* case seqnum is smaller then next_expected seqnum */ /* this is true e.g. on wrap around */ if (seqnum < next_expected) { - while (((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) { + while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) { ++i; if (i != m_list.end()) - s = readU16(&(i->data[BASE_HEADER_SIZE + 1])); + s = readU16(&(i->data[BASE_HEADER_SIZE+1])); } } /* non wrap around case (at least for incoming and next_expected */ - else { - while (((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) { + else + { + while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) { ++i; if (i != m_list.end()) - s = readU16(&(i->data[BASE_HEADER_SIZE + 1])); + s = readU16(&(i->data[BASE_HEADER_SIZE+1])); } } if (s == seqnum) { /* nothing to do this seems to be a resent packet */ /* for paranoia reason data should be compared */ - if ((readU16(&(i->data[BASE_HEADER_SIZE + 1])) != seqnum) || - (i->data.getSize() != p.data.getSize()) || - (i->address != p.address)) { + if ( + (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) || + (i->data.getSize() != p.data.getSize()) || + (i->address != p.address) + ) + { /* if this happens your maximum transfer window may be to big */ fprintf(stderr, - "Duplicated seqnum %d non matching packet " - "detected:\n", + "Duplicated seqnum %d non matching packet detected:\n", seqnum); fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n", - readU16(&(i->data[BASE_HEADER_SIZE + 1])), - i->data.getSize(), + readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(), i->address.serializeString().c_str()); fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n", - readU16(&(p.data[BASE_HEADER_SIZE + 1])), - p.data.getSize(), + readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(), p.address.serializeString().c_str()); - throw IncomingDataCorruption( - "duplicated packet isn't same as original one"); + throw IncomingDataCorruption("duplicated packet isn't same as original one"); } } /* insert or push back */ @@ -353,8 +355,7 @@ void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected) } /* update last packet number */ - m_oldest_non_answered_ack = - readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE + 1]); + m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); } void ReliablePacketBuffer::incrementTimeouts(float dtime) @@ -366,8 +367,8 @@ void ReliablePacketBuffer::incrementTimeouts(float dtime) } } -std::list ReliablePacketBuffer::getTimedOuts( - float timeout, unsigned int max_packets) +std::list ReliablePacketBuffer::getTimedOuts(float timeout, + unsigned int max_packets) { MutexAutoLock listlock(m_list_mutex); std::list timed_outs; @@ -375,7 +376,7 @@ std::list ReliablePacketBuffer::getTimedOuts( if (bufferedPacket.time >= timeout) { timed_outs.push_back(bufferedPacket); - // this packet will be sent right afterwards reset timeout here + //this packet will be sent right afterwards reset timeout here bufferedPacket.time = 0.0f; if (timed_outs.size() >= max_packets) break; @@ -446,19 +447,19 @@ SharedBuffer IncomingSplitBuffer::insert(const BufferedPacket &p, bool relia errorstream << "Invalid data size for split packet" << std::endl; return SharedBuffer(); } - u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]); - u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]); - u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE + 3]); - u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE + 5]); + u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]); + u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]); + u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]); + u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]); if (type != PACKET_TYPE_SPLIT) { errorstream << "IncomingSplitBuffer::insert(): type is not split" - << std::endl; + << std::endl; return SharedBuffer(); } if (chunk_num >= chunk_count) { errorstream << "IncomingSplitBuffer::insert(): chunk_num=" << chunk_num - << " >= chunk_count=" << chunk_count << std::endl; + << " >= chunk_count=" << chunk_count << std::endl; return SharedBuffer(); } @@ -473,13 +474,14 @@ SharedBuffer IncomingSplitBuffer::insert(const BufferedPacket &p, bool relia if (chunk_count != sp->chunk_count) { errorstream << "IncomingSplitBuffer::insert(): chunk_count=" - << chunk_count << " != sp->chunk_count=" << sp->chunk_count - << std::endl; + << chunk_count << " != sp->chunk_count=" << sp->chunk_count + << std::endl; return SharedBuffer(); } if (reliable != sp->reliable) - LOG(derr_con << "Connection: WARNING: reliable=" << reliable - << " != sp->reliable=" << sp->reliable << std::endl); + LOG(derr_con<<"Connection: WARNING: reliable="<reliable="<reliable + < - window_size) { + // know about difference of two unsigned may be negative in general + // but we already made sure it won't happen in this case + if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) { successful = false; return 0; } - } else { + } + else { // ugly cast but this one is required in order to tell compiler we - // know about difference of two unsigned may be negative in - // general but we already made sure it won't happen in this case - if ((next_outgoing_seqnum + - (u16)(SEQNUM_MAX - - lowest_unacked_seqnumber)) > - window_size) { + // know about difference of two unsigned may be negative in general + // but we already made sure it won't happen in this case + if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) > + window_size) { successful = false; return 0; } @@ -617,7 +618,7 @@ u16 Channel::readOutgoingSequenceNumber() bool Channel::putBackSequenceNumber(u16 seqnum) { - if (((seqnum + 1) % (SEQNUM_MAX + 1)) == next_outgoing_seqnum) { + if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) { next_outgoing_seqnum = seqnum; return true; @@ -632,8 +633,7 @@ void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets) current_packet_successful += packets; } -void Channel::UpdateBytesReceived(unsigned int bytes) -{ +void Channel::UpdateBytesReceived(unsigned int bytes) { MutexAutoLock internal(m_internal_mutex); current_bytes_received += bytes; } @@ -644,6 +644,7 @@ void Channel::UpdateBytesLost(unsigned int bytes) current_bytes_lost += bytes; } + void Channel::UpdatePacketLossCounter(unsigned int count) { MutexAutoLock internal(m_internal_mutex); @@ -664,21 +665,19 @@ void Channel::UpdateTimers(float dtime) if (packet_loss_counter > 1.0f) { packet_loss_counter -= 1.0f; - unsigned int packet_loss = - 11; /* use a neutral value for initialization */ + unsigned int packet_loss = 11; /* use a neutral value for initialization */ unsigned int packets_successful = 0; - // unsigned int packet_too_late = 0; + //unsigned int packet_too_late = 0; bool reasonable_amount_of_data_transmitted = false; { MutexAutoLock internal(m_internal_mutex); packet_loss = current_packet_loss; - // packet_too_late = current_packet_too_late; + //packet_too_late = current_packet_too_late; packets_successful = current_packet_successful; - if (current_bytes_transfered > - (unsigned int)(window_size * 512 / 2)) { + if (current_bytes_transfered > (unsigned int) (window_size*512/2)) { reasonable_amount_of_data_transmitted = true; } current_packet_loss = 0; @@ -691,33 +690,38 @@ void Channel::UpdateTimers(float dtime) bool done = false; if (packets_successful > 0) { - successful_to_lost_ratio = packet_loss / packets_successful; + successful_to_lost_ratio = packet_loss/packets_successful; } else if (packet_loss > 0) { window_size = std::max( - (window_size - 10), MIN_RELIABLE_WINDOW_SIZE); + (window_size - 10), + MIN_RELIABLE_WINDOW_SIZE); done = true; } if (!done) { if ((successful_to_lost_ratio < 0.01f) && - (window_size < MAX_RELIABLE_WINDOW_SIZE)) { + (window_size < MAX_RELIABLE_WINDOW_SIZE)) { /* don't even think about increasing if we didn't even * use major parts of our window */ if (reasonable_amount_of_data_transmitted) - window_size = std::min((window_size + 100), + window_size = std::min( + (window_size + 100), MAX_RELIABLE_WINDOW_SIZE); } else if ((successful_to_lost_ratio < 0.05f) && (window_size < MAX_RELIABLE_WINDOW_SIZE)) { /* don't even think about increasing if we didn't even * use major parts of our window */ if (reasonable_amount_of_data_transmitted) - window_size = std::min((window_size + 50), + window_size = std::min( + (window_size + 50), MAX_RELIABLE_WINDOW_SIZE); } else if (successful_to_lost_ratio > 0.15f) { - window_size = std::max((window_size - 100), + window_size = std::max( + (window_size - 100), MIN_RELIABLE_WINDOW_SIZE); } else if (successful_to_lost_ratio > 0.1f) { - window_size = std::max((window_size - 50), + window_size = std::max( + (window_size - 50), MIN_RELIABLE_WINDOW_SIZE); } } @@ -726,17 +730,16 @@ void Channel::UpdateTimers(float dtime) if (bpm_counter > 10.0f) { { MutexAutoLock internal(m_internal_mutex); - cur_kbps = (((float)current_bytes_transfered) / bpm_counter) / - 1024.0f; + cur_kbps = + (((float) current_bytes_transfered)/bpm_counter)/1024.0f; current_bytes_transfered = 0; - cur_kbps_lost = (((float)current_bytes_lost) / bpm_counter) / - 1024.0f; - current_bytes_lost = 0; - cur_incoming_kbps = - (((float)current_bytes_received) / bpm_counter) / - 1024.0f; - current_bytes_received = 0; - bpm_counter = 0.0f; + cur_kbps_lost = + (((float) current_bytes_lost)/bpm_counter)/1024.0f; + current_bytes_lost = 0; + cur_incoming_kbps = + (((float) current_bytes_received)/bpm_counter)/1024.0f; + current_bytes_received = 0; + bpm_counter = 0.0f; } if (cur_kbps > max_kbps) { @@ -751,21 +754,24 @@ void Channel::UpdateTimers(float dtime) max_incoming_kbps = cur_incoming_kbps; } - rate_samples = MYMIN(rate_samples + 1, 10); - float old_fraction = ((float)(rate_samples - 1)) / ((float)rate_samples); - avg_kbps = avg_kbps * old_fraction + cur_kbps * (1.0 - old_fraction); - avg_kbps_lost = avg_kbps_lost * old_fraction + + rate_samples = MYMIN(rate_samples+1,10); + float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples); + avg_kbps = avg_kbps * old_fraction + + cur_kbps * (1.0 - old_fraction); + avg_kbps_lost = avg_kbps_lost * old_fraction + cur_kbps_lost * (1.0 - old_fraction); - avg_incoming_kbps = avg_incoming_kbps * old_fraction + - cur_incoming_kbps * (1.0 - old_fraction); + avg_incoming_kbps = avg_incoming_kbps * old_fraction + + cur_incoming_kbps * (1.0 - old_fraction); } } + /* Peer */ -PeerHelper::PeerHelper(Peer *peer) : m_peer(peer) +PeerHelper::PeerHelper(Peer* peer) : + m_peer(peer) { if (peer && !peer->IncUseCount()) m_peer = nullptr; @@ -779,7 +785,7 @@ PeerHelper::~PeerHelper() m_peer = nullptr; } -PeerHelper &PeerHelper::operator=(Peer *peer) +PeerHelper& PeerHelper::operator=(Peer* peer) { m_peer = peer; if (peer && !peer->IncUseCount()) @@ -787,24 +793,24 @@ PeerHelper &PeerHelper::operator=(Peer *peer) return *this; } -Peer *PeerHelper::operator->() const +Peer* PeerHelper::operator->() const { return m_peer; } -Peer *PeerHelper::operator&() const +Peer* PeerHelper::operator&() const { return m_peer; } bool PeerHelper::operator!() { - return !m_peer; + return ! m_peer; } -bool PeerHelper::operator!=(void *ptr) +bool PeerHelper::operator!=(void* ptr) { - return ((void *)m_peer != ptr); + return ((void*) m_peer != ptr); } bool Peer::IncUseCount() @@ -832,9 +838,8 @@ void Peer::DecUseCount() delete this; } -void Peer::RTTStatistics( - float rtt, const std::string &profiler_id, unsigned int num_samples) -{ +void Peer::RTTStatistics(float rtt, const std::string &profiler_id, + unsigned int num_samples) { if (m_last_rtt > 0) { /* set min max values */ @@ -845,18 +850,18 @@ void Peer::RTTStatistics( /* do average calculation */ if (m_rtt.avg_rtt < 0.0) - m_rtt.avg_rtt = rtt; + m_rtt.avg_rtt = rtt; else - m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples / (num_samples - 1)) + - rtt * (1 / num_samples); + m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) + + rtt * (1/num_samples); /* do jitter calculation */ - // just use some neutral value at beginning + //just use some neutral value at beginning float jitter = m_rtt.jitter_min; if (rtt > m_last_rtt) - jitter = rtt - m_last_rtt; + jitter = rtt-m_last_rtt; if (rtt <= m_last_rtt) jitter = m_last_rtt - rtt; @@ -867,17 +872,14 @@ void Peer::RTTStatistics( m_rtt.jitter_max = jitter; if (m_rtt.jitter_avg < 0.0) - m_rtt.jitter_avg = jitter; + m_rtt.jitter_avg = jitter; else - m_rtt.jitter_avg = - m_rtt.jitter_avg * - (num_samples / (num_samples - 1)) + - jitter * (1 / num_samples); + m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) + + jitter * (1/num_samples); if (!profiler_id.empty()) { g_profiler->graphAdd(profiler_id + " RTT [ms]", rtt * 1000.f); - g_profiler->graphAdd( - profiler_id + " jitter [ms]", jitter * 1000.f); + g_profiler->graphAdd(profiler_id + " jitter [ms]", jitter * 1000.f); } } /* save values required for next loop */ @@ -889,7 +891,7 @@ bool Peer::isTimedOut(float timeout) MutexAutoLock lock(m_exclusive_access_mutex); u64 current_time = porting::getTimeMs(); - float dtime = CALC_DTIME(m_last_timeout_check, current_time); + float dtime = CALC_DTIME(m_last_timeout_check,current_time); m_last_timeout_check = current_time; m_timeout_counter += dtime; @@ -907,28 +909,28 @@ void Peer::Drop() } PROFILE(std::stringstream peerIdentifier1); - PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc() << ";" << id - << ";RELIABLE]"); + PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc() + << ";" << id << ";RELIABLE]"); PROFILE(g_profiler->remove(peerIdentifier1.str())); PROFILE(std::stringstream peerIdentifier2); - PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc() << ";" << id - << ";RELIABLE]"); + PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc() + << ";" << id << ";RELIABLE]"); PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG)); delete this; } -UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection *connection) : - Peer(a_address, a_id, connection) +UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) : + Peer(a_address,a_id,connection) { for (Channel &channel : channels) channel.setWindowSize(START_RELIABLE_WINDOW_SIZE); } -bool UDPPeer::getAddress(MTProtocols type, Address &toset) +bool UDPPeer::getAddress(MTProtocols type,Address& toset) { - if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || - (type == MTP_PRIMARY)) { + if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY)) + { toset = address; return true; } @@ -941,7 +943,7 @@ void UDPPeer::reportRTT(float rtt) if (rtt < 0.0) { return; } - RTTStatistics(rtt, "rudp", MAX_RELIABLE_WINDOW_SIZE * 10); + RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10); float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR; if (timeout < RESEND_TIMEOUT_MIN) @@ -953,10 +955,11 @@ void UDPPeer::reportRTT(float rtt) resend_timeout = timeout; } -bool UDPPeer::Ping(float dtime, SharedBuffer &data) +bool UDPPeer::Ping(float dtime,SharedBuffer& data) { m_ping_timer += dtime; - if (m_ping_timer >= PING_TIMEOUT) { + if (m_ping_timer >= PING_TIMEOUT) + { // Create and send PING packet writeU8(&data[0], PACKET_TYPE_CONTROL); writeU8(&data[1], CONTROLTYPE_PING); @@ -966,7 +969,8 @@ bool UDPPeer::Ping(float dtime, SharedBuffer &data) return false; } -void UDPPeer::PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size) +void UDPPeer::PutReliableSendCommand(ConnectionCommand &c, + unsigned int max_packet_size) { if (m_pending_disconnect) return; @@ -976,37 +980,41 @@ void UDPPeer::PutReliableSendCommand(ConnectionCommand &c, unsigned int max_pack if (chan.queued_commands.empty() && /* don't queue more packets then window size */ (chan.queued_reliables.size() < chan.getWindowSize() / 2)) { - LOG(dout_con << m_connection->getDesc() - << " processing reliable command for peer id: " << c.peer_id - << " data size: " << c.data.getSize() << std::endl); - if (!processReliableSendCommand(c, max_packet_size)) { + LOG(dout_con<getDesc() + <<" processing reliable command for peer id: " << c.peer_id + <<" data size: " << c.data.getSize() << std::endl); + if (!processReliableSendCommand(c,max_packet_size)) { chan.queued_commands.push_back(c); } - } else { - LOG(dout_con << m_connection->getDesc() - << " Queueing reliable command for peer id: " << c.peer_id - << " data size: " << c.data.getSize() << std::endl); + } + else { + LOG(dout_con<getDesc() + <<" Queueing reliable command for peer id: " << c.peer_id + <<" data size: " << c.data.getSize() <= chan.getWindowSize() / 2) { LOG(derr_con << m_connection->getDesc() - << "Possible packet stall to peer id: " << c.peer_id - << " queued_commands=" << chan.queued_commands.size() - << std::endl); + << "Possible packet stall to peer id: " << c.peer_id + << " queued_commands=" << chan.queued_commands.size() + << std::endl); } } } bool UDPPeer::processReliableSendCommand( - ConnectionCommand &c, unsigned int max_packet_size) + ConnectionCommand &c, + unsigned int max_packet_size) { if (m_pending_disconnect) return true; Channel &chan = channels[c.channelnum]; - u32 chunksize_max = max_packet_size - BASE_HEADER_SIZE - RELIABLE_HEADER_SIZE; + u32 chunksize_max = max_packet_size + - BASE_HEADER_SIZE + - RELIABLE_HEADER_SIZE; - sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE * 512); + sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512); std::list> originals; u16 split_sequence_number = chan.readNextSplitSeqNum(); @@ -1014,8 +1022,7 @@ bool UDPPeer::processReliableSendCommand( if (c.raw) { originals.emplace_back(c.data); } else { - makeAutoSplitPacket( - c.data, chunksize_max, split_sequence_number, &originals); + makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals); chan.setNextSplitSeqNum(split_sequence_number); } @@ -1031,7 +1038,8 @@ bool UDPPeer::processReliableSendCommand( if (!have_sequence_number) break; - if (!have_initial_sequence_number) { + if (!have_initial_sequence_number) + { initial_sequence_number = seqnum; have_initial_sequence_number = true; } @@ -1051,14 +1059,11 @@ bool UDPPeer::processReliableSendCommand( while (!toadd.empty()) { BufferedPacket p = toadd.front(); toadd.pop(); - // LOG(dout_con<getDesc() - // << " queuing reliable packet for - //peer_id: " << c.peer_id - // << " channel: " << - //(c.channelnum&0xFF) - // << " seqnum: " << - //readU16(&p.data[BASE_HEADER_SIZE+1]) - // << std::endl) +// LOG(dout_con<getDesc() +// << " queuing reliable packet for peer_id: " << c.peer_id +// << " channel: " << (c.channelnum&0xFF) +// << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1]) +// << std::endl) chan.queued_reliables.push(p); pcount++; } @@ -1076,9 +1081,9 @@ bool UDPPeer::processReliableSendCommand( /* remove packet */ toadd.pop(); - bool successfully_put_back_sequence_number = chan.putBackSequenceNumber( - (initial_sequence_number + - toadd.size() % (SEQNUM_MAX + 1))); + bool successfully_put_back_sequence_number + = chan.putBackSequenceNumber( + (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1))); FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error"); } @@ -1087,20 +1092,24 @@ bool UDPPeer::processReliableSendCommand( // 'log_message_mutex' and 'm_list_mutex'. u32 n_queued = chan.outgoing_reliables_sent.size(); - LOG(dout_con << m_connection->getDesc() - << " Windowsize exceeded on reliable sending " << c.data.getSize() - << " bytes" << std::endl - << "\t\tinitial_sequence_number: " << initial_sequence_number - << std::endl - << "\t\tgot at most : " << packets_available << " packets" - << std::endl - << "\t\tpackets queued : " << n_queued << std::endl); + LOG(dout_con<getDesc() + << " Windowsize exceeded on reliable sending " + << c.data.getSize() << " bytes" + << std::endl << "\t\tinitial_sequence_number: " + << initial_sequence_number + << std::endl << "\t\tgot at most : " + << packets_available << " packets" + << std::endl << "\t\tpackets queued : " + << n_queued + << std::endl); return false; } -void UDPPeer::RunCommandQueues(unsigned int max_packet_size, unsigned int maxcommands, - unsigned int maxtransfer) +void UDPPeer::RunCommandQueues( + unsigned int max_packet_size, + unsigned int maxcommands, + unsigned int maxtransfer) { for (Channel &channel : channels) { @@ -1113,22 +1122,19 @@ void UDPPeer::RunCommandQueues(unsigned int max_packet_size, unsigned int maxcom ConnectionCommand c = channel.queued_commands.front(); LOG(dout_con << m_connection->getDesc() - << " processing queued reliable command " - << std::endl); + << " processing queued reliable command " << std::endl); // Packet is processed, remove it from queue - if (processReliableSendCommand(c, max_packet_size)) { + if (processReliableSendCommand(c,max_packet_size)) { channel.queued_commands.pop_front(); } else { LOG(dout_con << m_connection->getDesc() - << " Failed to queue packets for " - "peer_id: " - << c.peer_id - << ", delaying sending of " - << c.data.getSize() << " bytes" - << std::endl); + << " Failed to queue packets for peer_id: " << c.peer_id + << ", delaying sending of " << c.data.getSize() + << " bytes" << std::endl); } - } catch (ItemNotFoundException &e) { + } + catch (ItemNotFoundException &e) { // intentionally empty } } @@ -1147,8 +1153,8 @@ void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum) channels[channel].setNextSplitSeqNum(seqnum); } -SharedBuffer UDPPeer::addSplitPacket( - u8 channel, const BufferedPacket &toadd, bool reliable) +SharedBuffer UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd, + bool reliable) { assert(channel < CHANNEL_COUNT); // Pre-condition return channels[channel].incoming_splits.insert(toadd, reliable); @@ -1158,13 +1164,13 @@ SharedBuffer UDPPeer::addSplitPacket( Connection */ -Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6, - PeerHandler *peerhandler) : - m_udpSocket(ipv6), - m_protocol_id(protocol_id), - m_sendThread(new ConnectionSendThread(max_packet_size, timeout)), - m_receiveThread(new ConnectionReceiveThread(max_packet_size)), - m_bc_peerhandler(peerhandler) +Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout, + bool ipv6, PeerHandler *peerhandler) : + m_udpSocket(ipv6), + m_protocol_id(protocol_id), + m_sendThread(new ConnectionSendThread(max_packet_size, timeout)), + m_receiveThread(new ConnectionReceiveThread(max_packet_size)), + m_bc_peerhandler(peerhandler) { /* Amount of time Receive() will wait for data, this is entirely different @@ -1178,6 +1184,7 @@ Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool m_receiveThread->start(); } + Connection::~Connection() { m_shutting_down = true; @@ -1185,7 +1192,7 @@ Connection::~Connection() m_sendThread->stop(); m_receiveThread->stop(); - // TODO for some unkonwn reason send/receive threads do not exit as they're + //TODO for some unkonwn reason send/receive threads do not exit as they're // supposed to be but wait on peer timeout. To speed up shutdown we reduce // timeout to half a second. m_sendThread->setPeerTimeout(0.5); @@ -1228,20 +1235,20 @@ PeerHelper Connection::getPeerNoEx(session_t peer_id) } /* find peer_id for address */ -u16 Connection::lookupPeer(Address &sender) +u16 Connection::lookupPeer(Address& sender) { MutexAutoLock peerlock(m_peers_mutex); - std::map::iterator j; + std::map::iterator j; j = m_peers.begin(); - for (; j != m_peers.end(); ++j) { + for(; j != m_peers.end(); ++j) + { Peer *peer = j->second; if (peer->isPendingDeletion()) continue; Address tocheck; - if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && - (tocheck == sender)) + if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender)) return peer->id; if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender)) @@ -1266,13 +1273,14 @@ bool Connection::deletePeer(session_t peer_id, bool timeout) } Address peer_address; - // any peer has a primary address this never fails! + //any peer has a primary address this never fails! peer->getAddress(MTP_PRIMARY, peer_address); // Create event ConnectionEvent e; e.peerRemoved(peer_id, timeout, peer_address); putEvent(e); + peer->Drop(); return true; } @@ -1283,7 +1291,7 @@ ConnectionEvent Connection::waitEvent(u32 timeout_ms) { try { return m_event_queue.pop_front(timeout_ms); - } catch (ItemNotFoundException &ex) { + } catch(ItemNotFoundException &ex) { ConnectionEvent e; e.type = CONNEVENT_NONE; return e; @@ -1343,12 +1351,12 @@ bool Connection::Receive(NetworkPacket *pkt, u32 timeout) events keep happening before the timeout expires. This is not considered to be a problem (is it?) */ - for (;;) { + for(;;) { ConnectionEvent e = waitEvent(timeout); if (e.type != CONNEVENT_NONE) LOG(dout_con << getDesc() << ": Receive: got event: " - << e.describe() << std::endl); - switch (e.type) { + << e.describe() << std::endl); + switch(e.type) { case CONNEVENT_NONE: return false; case CONNEVENT_DATA_RECEIVED: @@ -1373,7 +1381,7 @@ bool Connection::Receive(NetworkPacket *pkt, u32 timeout) } case CONNEVENT_BIND_FAILED: throw ConnectionBindFailed("Failed to bind socket " - "(port already in use?)"); + "(port already in use?)"); } } return false; @@ -1391,7 +1399,8 @@ bool Connection::TryReceive(NetworkPacket *pkt) return Receive(pkt, 0); } -void Connection::Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable) +void Connection::Send(session_t peer_id, u8 channelnum, + NetworkPacket *pkt, bool reliable) { assert(channelnum < CHANNEL_COUNT); // Pre-condition @@ -1415,8 +1424,7 @@ Address Connection::GetPeerAddress(session_t peer_id) float Connection::getPeerStat(session_t peer_id, rtt_stat_type type) { PeerHelper peer = getPeerNoEx(peer_id); - if (!peer) - return -1; + if (!peer) return -1; return peer->getStat(type); } @@ -1424,31 +1432,30 @@ float Connection::getLocalStat(rate_stat_type type) { PeerHelper peer = getPeerNoEx(PEER_ID_SERVER); - FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? " - "are you serious???"); + FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???"); float retval = 0.0; for (Channel &channel : dynamic_cast(&peer)->channels) { - switch (type) { - case CUR_DL_RATE: - retval += channel.getCurrentDownloadRateKB(); - break; - case AVG_DL_RATE: - retval += channel.getAvgDownloadRateKB(); - break; - case CUR_INC_RATE: - retval += channel.getCurrentIncomingRateKB(); - break; - case AVG_INC_RATE: - retval += channel.getAvgIncomingRateKB(); - break; - case AVG_LOSS_RATE: - retval += channel.getAvgLossRateKB(); - break; - case CUR_LOSS_RATE: - retval += channel.getCurrentLossRateKB(); - break; + switch(type) { + case CUR_DL_RATE: + retval += channel.getCurrentDownloadRateKB(); + break; + case AVG_DL_RATE: + retval += channel.getAvgDownloadRateKB(); + break; + case CUR_INC_RATE: + retval += channel.getCurrentIncomingRateKB(); + break; + case AVG_INC_RATE: + retval += channel.getAvgIncomingRateKB(); + break; + case AVG_LOSS_RATE: + retval += channel.getAvgLossRateKB(); + break; + case CUR_LOSS_RATE: + retval += channel.getCurrentLossRateKB(); + break; default: FATAL_ERROR("Connection::getLocalStat Invalid stat type"); } @@ -1456,20 +1463,20 @@ float Connection::getLocalStat(rate_stat_type type) return retval; } -u16 Connection::createPeer(Address &sender, MTProtocols protocol, int fd) +u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd) { // Somebody wants to make a new connection // Get a unique peer id (2 or higher) session_t peer_id_new = m_next_remote_peer_id; - u16 overflow = MAX_UDP_PEERS; + u16 overflow = MAX_UDP_PEERS; /* Find an unused peer id */ MutexAutoLock lock(m_peers_mutex); bool out_of_ids = false; - for (;;) { + for(;;) { // Check if exists if (m_peers.find(peer_id_new) == m_peers.end()) @@ -1494,17 +1501,17 @@ u16 Connection::createPeer(Address &sender, MTProtocols protocol, int fd) m_peers[peer->id] = peer; m_peer_ids.push_back(peer->id); - m_next_remote_peer_id = (peer_id_new + 1) % MAX_UDP_PEERS; + m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS; - LOG(dout_con << getDesc() << "createPeer(): giving peer_id=" << peer_id_new - << std::endl); + LOG(dout_con << getDesc() + << "createPeer(): giving peer_id=" << peer_id_new << std::endl); ConnectionCommand cmd; SharedBuffer reply(4); writeU8(&reply[0], PACKET_TYPE_CONTROL); writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID); writeU16(&reply[2], peer_id_new); - cmd.createPeer(peer_id_new, reply); + cmd.createPeer(peer_id_new,reply); putCommand(cmd); // Create peer addition event @@ -1519,14 +1526,14 @@ u16 Connection::createPeer(Address &sender, MTProtocols protocol, int fd) void Connection::PrintInfo(std::ostream &out) { m_info_mutex.lock(); - out << getDesc() << ": "; + out< ack(4); @@ -1555,9 +1563,10 @@ void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum) m_sendThread->Trigger(); } -UDPPeer *Connection::createServerPeer(Address &address) +UDPPeer* Connection::createServerPeer(Address& address) { - if (getPeerNoEx(PEER_ID_SERVER) != 0) { + if (getPeerNoEx(PEER_ID_SERVER) != 0) + { throw ConnectionException("Already connected to a server"); } diff --git a/src/network/connection.h b/src/network/connection.h index 9febfb2b7..47b0805ce 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -41,8 +41,7 @@ namespace con class ConnectionReceiveThread; class ConnectionSendThread; -typedef enum MTProtocols -{ +typedef enum MTProtocols { MTP_PRIMARY, MTP_UDP, MTP_MINETEST_RELIABLE_UDP @@ -54,43 +53,49 @@ typedef enum MTProtocols inline bool seqnum_higher(u16 totest, u16 base) { - if (totest > base) { - if ((totest - base) > (SEQNUM_MAX / 2)) + if (totest > base) + { + if ((totest - base) > (SEQNUM_MAX/2)) return false; return true; } - if ((base - totest) > (SEQNUM_MAX / 2)) + if ((base - totest) > (SEQNUM_MAX/2)) return true; return false; } -inline bool seqnum_in_window(u16 seqnum, u16 next, u16 window_size) +inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size) { u16 window_start = next; - u16 window_end = (next + window_size) % (SEQNUM_MAX + 1); + u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1); if (window_start < window_end) { return ((seqnum >= window_start) && (seqnum < window_end)); } + return ((seqnum < window_end) || (seqnum >= window_start)); } static inline float CALC_DTIME(u64 lasttime, u64 curtime) { - float value = (curtime - lasttime) / 1000.0; - return MYMAX(MYMIN(value, 0.1), 0.0); + float value = ( curtime - lasttime) / 1000.0; + return MYMAX(MYMIN(value,0.1),0.0); } struct BufferedPacket { - BufferedPacket(u8 *a_data, u32 a_size) : data(a_data, a_size) {} - BufferedPacket(u32 a_size) : data(a_size) {} - Buffer data; // Data of the packet, including headers - float time = 0.0f; // Seconds from buffering the packet or re-sending + BufferedPacket(u8 *a_data, u32 a_size): + data(a_data, a_size) + {} + BufferedPacket(u32 a_size): + data(a_size) + {} + Buffer data; // Data of the packet, including headers + float time = 0.0f; // Seconds from buffering the packet or re-sending float totaltime = 0.0f; // Seconds from buffering the packet u64 absolute_send_time = -1; Address address; // Sender or destination @@ -98,8 +103,8 @@ struct BufferedPacket }; // This adds the base headers to the data and makes a packet out of it -BufferedPacket makePacket(Address &address, const SharedBuffer &data, u32 protocol_id, - session_t sender_peer_id, u8 channel); +BufferedPacket makePacket(Address &address, const SharedBuffer &data, + u32 protocol_id, session_t sender_peer_id, u8 channel); // Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet // Increments split_seqnum if a split packet is made @@ -111,7 +116,8 @@ SharedBuffer makeReliablePacket(const SharedBuffer &data, u16 seqnum); struct IncomingSplitPacket { - IncomingSplitPacket(u32 cc, bool r) : chunk_count(cc), reliable(r) {} + IncomingSplitPacket(u32 cc, bool r): + chunk_count(cc), reliable(r) {} IncomingSplitPacket() = delete; @@ -119,7 +125,10 @@ struct IncomingSplitPacket u32 chunk_count; bool reliable; // If true, isn't deleted on timeout - bool allReceived() const { return (chunks.size() == chunk_count); } + bool allReceived() const + { + return (chunks.size() == chunk_count); + } bool insert(u32 chunk_num, SharedBuffer &chunkdata); SharedBuffer reassemble(); @@ -210,8 +219,7 @@ with a buffer in the receiving and transmitting end. #define RELIABLE_HEADER_SIZE 3 #define SEQNUM_INITIAL 65500 -enum PacketType : u8 -{ +enum PacketType: u8 { PACKET_TYPE_CONTROL = 0, PACKET_TYPE_ORIGINAL = 1, PACKET_TYPE_SPLIT = 2, @@ -230,20 +238,22 @@ class ReliablePacketBuffer public: ReliablePacketBuffer() = default; - bool getFirstSeqnum(u16 &result); + bool getFirstSeqnum(u16& result); BufferedPacket popFirst(); BufferedPacket popSeqnum(u16 seqnum); void insert(BufferedPacket &p, u16 next_expected); void incrementTimeouts(float dtime); - std::list getTimedOuts(float timeout, unsigned int max_packets); + std::list getTimedOuts(float timeout, + unsigned int max_packets); void print(); bool empty(); RPBSearchResult notFound(); u32 size(); + private: RPBSearchResult findPacket(u16 seqnum); // does not perform locking @@ -272,7 +282,7 @@ class IncomingSplitBuffer private: // Key is seqnum - std::map m_buf; + std::map m_buf; std::mutex m_map_mutex; }; @@ -286,16 +296,17 @@ struct OutgoingPacket bool ack; OutgoingPacket(session_t peer_id_, u8 channelnum_, const SharedBuffer &data_, - bool reliable_, bool ack_ = false) : - peer_id(peer_id_), - channelnum(channelnum_), data(data_), reliable(reliable_), - ack(ack_) + bool reliable_,bool ack_=false): + peer_id(peer_id_), + channelnum(channelnum_), + data(data_), + reliable(reliable_), + ack(ack_) { } }; -enum ConnectionCommandType -{ +enum ConnectionCommandType{ CONNCMD_NONE, CONNCMD_SERVE, CONNCMD_CONNECT, @@ -341,7 +352,10 @@ struct ConnectionCommand type = CONNCMD_CONNECT; address = address_; } - void disconnect() { type = CONNCMD_DISCONNECT; } + void disconnect() + { + type = CONNCMD_DISCONNECT; + } void disconnect_peer(session_t peer_id_) { type = CONNCMD_DISCONNECT_PEER; @@ -387,7 +401,7 @@ class Channel u16 readNextIncomingSeqNum(); u16 incNextIncomingSeqNum(); - u16 getOutgoingSequenceNumber(bool &successfull); + u16 getOutgoingSequenceNumber(bool& successfull); u16 readOutgoingSequenceNumber(); bool putBackSequenceNumber(u16); @@ -401,10 +415,10 @@ class Channel // re-send them if no ACK is received ReliablePacketBuffer outgoing_reliables_sent; - // queued reliable packets + //queued reliable packets std::queue queued_reliables; - // queue commands prior splitting to packets + //queue commands prior splitting to packets std::deque queued_commands; IncomingSplitBuffer incoming_splits; @@ -414,65 +428,37 @@ class Channel void UpdatePacketLossCounter(unsigned int count); void UpdatePacketTooLateCounter(); - void UpdateBytesSent(unsigned int bytes, unsigned int packages = 1); + void UpdateBytesSent(unsigned int bytes,unsigned int packages=1); void UpdateBytesLost(unsigned int bytes); void UpdateBytesReceived(unsigned int bytes); void UpdateTimers(float dtime); const float getCurrentDownloadRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return cur_kbps; - }; + { MutexAutoLock lock(m_internal_mutex); return cur_kbps; }; const float getMaxDownloadRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return max_kbps; - }; + { MutexAutoLock lock(m_internal_mutex); return max_kbps; }; const float getCurrentLossRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return cur_kbps_lost; - }; + { MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; }; const float getMaxLossRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return max_kbps_lost; - }; + { MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; }; const float getCurrentIncomingRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return cur_incoming_kbps; - }; + { MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; }; const float getMaxIncomingRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return max_incoming_kbps; - }; + { MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; }; const float getAvgDownloadRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return avg_kbps; - }; + { MutexAutoLock lock(m_internal_mutex); return avg_kbps; }; const float getAvgLossRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return avg_kbps_lost; - }; + { MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; }; const float getAvgIncomingRateKB() - { - MutexAutoLock lock(m_internal_mutex); - return avg_incoming_kbps; - }; + { MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; }; const unsigned int getWindowSize() const { return window_size; }; void setWindowSize(unsigned int size) { window_size = size; }; - private: std::mutex m_internal_mutex; int window_size = MIN_RELIABLE_WINDOW_SIZE; @@ -510,14 +496,14 @@ class PeerHelper { public: PeerHelper() = default; - PeerHelper(Peer *peer); + PeerHelper(Peer* peer); ~PeerHelper(); - PeerHelper &operator=(Peer *peer); - Peer *operator->() const; - bool operator!(); - Peer *operator&() const; - bool operator!=(void *ptr); + PeerHelper& operator=(Peer* peer); + Peer* operator->() const; + bool operator!(); + Peer* operator&() const; + bool operator!=(void* ptr); private: Peer *m_peer = nullptr; @@ -525,8 +511,7 @@ class PeerHelper class Connection; -typedef enum -{ +typedef enum { CUR_DL_RATE, AVG_DL_RATE, CUR_INC_RATE, @@ -535,144 +520,140 @@ typedef enum AVG_LOSS_RATE, } rate_stat_type; -class Peer -{ -public: - friend class PeerHelper; - - Peer(Address address_, u16 id_, Connection *connection) : - id(id_), m_connection(connection), address(address_), - m_last_timeout_check(porting::getTimeMs()){}; - - virtual ~Peer() - { - MutexAutoLock usage_lock(m_exclusive_access_mutex); - FATAL_ERROR_IF(m_usage != 0, "Reference counting failure"); - }; - - // Unique id of the peer - u16 id; - - void Drop(); - - virtual void PutReliableSendCommand( - ConnectionCommand &c, unsigned int max_packet_size){}; - - virtual bool getAddress(MTProtocols type, Address &toset) = 0; - - bool isPendingDeletion() - { - MutexAutoLock lock(m_exclusive_access_mutex); - return m_pending_deletion; - }; - - void ResetTimeout() - { - MutexAutoLock lock(m_exclusive_access_mutex); - m_timeout_counter = 0.0; - }; - - bool isTimedOut(float timeout); - - unsigned int m_increment_packets_remaining = 0; - - virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; }; - virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum){}; - virtual SharedBuffer addSplitPacket( - u8 channel, const BufferedPacket &toadd, bool reliable) - { - errorstream << "Peer::addSplitPacket called," - << " this is supposed to be never called!" << std::endl; - return SharedBuffer(0); - }; - - virtual bool Ping(float dtime, SharedBuffer &data) { return false; }; - - virtual float getStat(rtt_stat_type type) const - { - switch (type) { - case MIN_RTT: - return m_rtt.min_rtt; - case MAX_RTT: - return m_rtt.max_rtt; - case AVG_RTT: - return m_rtt.avg_rtt; - case MIN_JITTER: - return m_rtt.jitter_min; - case MAX_JITTER: - return m_rtt.jitter_max; - case AVG_JITTER: - return m_rtt.jitter_avg; +class Peer { + public: + friend class PeerHelper; + + Peer(Address address_,u16 id_,Connection* connection) : + id(id_), + m_connection(connection), + address(address_), + m_last_timeout_check(porting::getTimeMs()) + { + }; + + virtual ~Peer() { + MutexAutoLock usage_lock(m_exclusive_access_mutex); + FATAL_ERROR_IF(m_usage != 0, "Reference counting failure"); + }; + + // Unique id of the peer + u16 id; + + void Drop(); + + virtual void PutReliableSendCommand(ConnectionCommand &c, + unsigned int max_packet_size) {}; + + virtual bool getAddress(MTProtocols type, Address& toset) = 0; + + bool isPendingDeletion() + { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; }; + + void ResetTimeout() + {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; }; + + bool isTimedOut(float timeout); + + unsigned int m_increment_packets_remaining = 0; + + virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; }; + virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {}; + virtual SharedBuffer addSplitPacket(u8 channel, const BufferedPacket &toadd, + bool reliable) + { + errorstream << "Peer::addSplitPacket called," + << " this is supposed to be never called!" << std::endl; + return SharedBuffer(0); + }; + + virtual bool Ping(float dtime, SharedBuffer& data) { return false; }; + + virtual float getStat(rtt_stat_type type) const { + switch (type) { + case MIN_RTT: + return m_rtt.min_rtt; + case MAX_RTT: + return m_rtt.max_rtt; + case AVG_RTT: + return m_rtt.avg_rtt; + case MIN_JITTER: + return m_rtt.jitter_min; + case MAX_JITTER: + return m_rtt.jitter_max; + case AVG_JITTER: + return m_rtt.jitter_avg; + } + return -1; } - return -1; - } + protected: + virtual void reportRTT(float rtt) {}; -protected: - virtual void reportRTT(float rtt){}; + void RTTStatistics(float rtt, + const std::string &profiler_id = "", + unsigned int num_samples = 1000); - void RTTStatistics(float rtt, const std::string &profiler_id = "", - unsigned int num_samples = 1000); + bool IncUseCount(); + void DecUseCount(); - bool IncUseCount(); - void DecUseCount(); + std::mutex m_exclusive_access_mutex; - std::mutex m_exclusive_access_mutex; + bool m_pending_deletion = false; - bool m_pending_deletion = false; + Connection* m_connection; - Connection *m_connection; + // Address of the peer + Address address; - // Address of the peer - Address address; - - // Ping timer - float m_ping_timer = 0.0f; + // Ping timer + float m_ping_timer = 0.0f; + private: -private: - struct rttstats - { - float jitter_min = FLT_MAX; - float jitter_max = 0.0f; - float jitter_avg = -1.0f; - float min_rtt = FLT_MAX; - float max_rtt = 0.0f; - float avg_rtt = -1.0f; + struct rttstats { + float jitter_min = FLT_MAX; + float jitter_max = 0.0f; + float jitter_avg = -1.0f; + float min_rtt = FLT_MAX; + float max_rtt = 0.0f; + float avg_rtt = -1.0f; - rttstats() = default; - }; + rttstats() = default; + }; - rttstats m_rtt; - float m_last_rtt = -1.0f; + rttstats m_rtt; + float m_last_rtt = -1.0f; - // current usage count - unsigned int m_usage = 0; + // current usage count + unsigned int m_usage = 0; - // Seconds from last receive - float m_timeout_counter = 0.0f; + // Seconds from last receive + float m_timeout_counter = 0.0f; - u64 m_last_timeout_check; + u64 m_last_timeout_check; }; class UDPPeer : public Peer { public: + friend class PeerHelper; friend class ConnectionReceiveThread; friend class ConnectionSendThread; friend class Connection; - UDPPeer(u16 a_id, Address a_address, Connection *connection); + UDPPeer(u16 a_id, Address a_address, Connection* connection); virtual ~UDPPeer() = default; - void PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size); + void PutReliableSendCommand(ConnectionCommand &c, + unsigned int max_packet_size); - bool getAddress(MTProtocols type, Address &toset); + bool getAddress(MTProtocols type, Address& toset); u16 getNextSplitSequenceNumber(u8 channel); void setNextSplitSequenceNumber(u8 channel, u16 seqnum); - SharedBuffer addSplitPacket( - u8 channel, const BufferedPacket &toadd, bool reliable); + SharedBuffer addSplitPacket(u8 channel, const BufferedPacket &toadd, + bool reliable); protected: /* @@ -681,39 +662,34 @@ class UDPPeer : public Peer */ void reportRTT(float rtt); - void RunCommandQueues(unsigned int max_packet_size, unsigned int maxcommands, - unsigned int maxtransfer); + void RunCommandQueues( + unsigned int max_packet_size, + unsigned int maxcommands, + unsigned int maxtransfer); float getResendTimeout() - { - MutexAutoLock lock(m_exclusive_access_mutex); - return resend_timeout; - } + { MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; } void setResendTimeout(float timeout) - { - MutexAutoLock lock(m_exclusive_access_mutex); - resend_timeout = timeout; - } - bool Ping(float dtime, SharedBuffer &data); + { MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; } + bool Ping(float dtime,SharedBuffer& data); Channel channels[CHANNEL_COUNT]; bool m_pending_disconnect = false; - private: // This is changed dynamically float resend_timeout = 0.5; bool processReliableSendCommand( - ConnectionCommand &c, unsigned int max_packet_size); + ConnectionCommand &c, + unsigned int max_packet_size); }; /* Connection */ -enum ConnectionEventType -{ +enum ConnectionEventType{ CONNEVENT_NONE, CONNEVENT_DATA_RECEIVED, CONNEVENT_PEER_ADDED, @@ -733,7 +709,7 @@ struct ConnectionEvent std::string describe() { - switch (type) { + switch(type) { case CONNEVENT_NONE: return "CONNEVENT_NONE"; case CONNEVENT_DATA_RECEIVED: @@ -767,7 +743,10 @@ struct ConnectionEvent timeout = timeout_; address = address_; } - void bindFailed() { type = CONNEVENT_BIND_FAILED; } + void bindFailed() + { + type = CONNEVENT_BIND_FAILED; + } }; class PeerHandler; @@ -791,7 +770,7 @@ class Connection void Connect(Address address); bool Connected(); void Disconnect(); - void Receive(NetworkPacket *pkt); + void Receive(NetworkPacket* pkt); bool TryReceive(NetworkPacket *pkt); void Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable); session_t GetPeerID() const { return m_peer_id; } @@ -804,10 +783,10 @@ class Connection protected: PeerHelper getPeerNoEx(session_t peer_id); - u16 lookupPeer(Address &sender); + u16 lookupPeer(Address& sender); - u16 createPeer(Address &sender, MTProtocols protocol, int fd); - UDPPeer *createServerPeer(Address &sender); + u16 createPeer(Address& sender, MTProtocols protocol, int fd); + UDPPeer* createServerPeer(Address& sender); bool deletePeer(session_t peer_id, bool timeout); void SetPeerID(session_t id) { m_peer_id = id; } @@ -830,7 +809,6 @@ class Connection void putEvent(ConnectionEvent &e); void TriggerSend(); - private: MutexedQueue m_event_queue; diff --git a/src/network/connectionthreads.cpp b/src/network/connectionthreads.cpp index 4d47b776c..9a6617a1c 100644 --- a/src/network/connectionthreads.cpp +++ b/src/network/connectionthreads.cpp @@ -38,10 +38,10 @@ namespace con #else /* this mutex is used to achieve log message consistency */ std::mutex log_conthread_mutex; -#define LOG(a) \ - { \ - MutexAutoLock loglock(log_conthread_mutex); \ - a; \ +#define LOG(a) \ + { \ + MutexAutoLock loglock(log_conthread_mutex); \ + a; \ } #define PROFILE(a) a //#define DEBUG_CONNECTION_KBPS @@ -66,10 +66,12 @@ static u8 readChannel(u8 *packetdata) /* Connection Threads */ /******************************************************************************/ -ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size, float timeout) : - Thread("ConnectionSend"), m_max_packet_size(max_packet_size), - m_timeout(timeout), m_max_data_packets_per_iteration(g_settings->getU16( - "max_packets_per_iteration")) +ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size, + float timeout) : + Thread("ConnectionSend"), + m_max_packet_size(max_packet_size), + m_timeout(timeout), + m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")) { SANITY_CHECK(m_max_data_packets_per_iteration > 1); } @@ -78,15 +80,14 @@ void *ConnectionSendThread::run() { assert(m_connection); - LOG(dout_con << m_connection->getDesc() << "ConnectionSend thread started" - << std::endl); + LOG(dout_con << m_connection->getDesc() + << "ConnectionSend thread started" << std::endl); u64 curtime = porting::getTimeMs(); u64 lasttime = curtime; PROFILE(std::stringstream ThreadIdentifier); - PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() - << "]"); + PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]"); /* if stop is requested don't stop immediately but try to send all */ /* packets first */ @@ -111,10 +112,8 @@ void *ConnectionSendThread::run() runTimeouts(dtime); if (m_iteration_packets_avaialble == 0) { LOG(warningstream << m_connection->getDesc() - << " Packet quota used up after re-sending " - "packets, " - << "max=" << m_max_data_packets_per_iteration - << std::endl); + << " Packet quota used up after re-sending packets, " + << "max=" << m_max_data_packets_per_iteration << std::endl); } /* translate commands to packets */ @@ -166,6 +165,7 @@ bool ConnectionSendThread::packetsQueued() } } + return false; } @@ -185,20 +185,21 @@ void ConnectionSendThread::runTimeouts(float dtime) continue; PROFILE(std::stringstream peerIdentifier); - PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() << ";" - << peerId << ";RELIABLE]"); - PROFILE(ScopeProfiler peerprofiler( - g_profiler, peerIdentifier.str(), SPT_AVG)); + PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() + << ";" << peerId << ";RELIABLE]"); + PROFILE(ScopeProfiler + peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG)); - SharedBuffer data(2); // data for sending ping, required here because - // of goto + SharedBuffer data(2); // data for sending ping, required here because of goto /* Check peer timeout */ if (peer->isTimedOut(m_timeout)) { - infostream << m_connection->getDesc() << "RunTimeouts(): Peer " - << peer->id << " has timed out." << std::endl; + infostream << m_connection->getDesc() + << "RunTimeouts(): Peer " << peer->id + << " has timed out." + << std::endl; // Add peer to the list timeouted_peers.push_back(peer->id); // Don't bother going through the buffers of this one @@ -211,8 +212,7 @@ void ConnectionSendThread::runTimeouts(float dtime) std::list timed_outs; // Remove timed out incomplete unreliable split packets - channel.incoming_splits.removeUnreliableTimedOuts( - dtime, m_timeout); + channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout); // Increment reliable packet times channel.outgoing_reliables_sent.incrementTimeouts(dtime); @@ -223,9 +223,8 @@ void ConnectionSendThread::runTimeouts(float dtime) return; // Re-send timed out outgoing reliables - timed_outs = channel.outgoing_reliables_sent.getTimedOuts( - resend_timeout, - (m_max_data_packets_per_iteration / numpeers)); + timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout, + (m_max_data_packets_per_iteration / numpeers)); channel.UpdatePacketLossCounter(timed_outs.size()); g_profiler->graphAdd("packets_lost", timed_outs.size()); @@ -233,7 +232,7 @@ void ConnectionSendThread::runTimeouts(float dtime) m_iteration_packets_avaialble -= timed_outs.size(); for (std::list::iterator k = timed_outs.begin(); - k != timed_outs.end(); ++k) { + k != timed_outs.end(); ++k) { session_t peer_id = readPeerId(*(k->data)); u8 channelnum = readChannel(*(k->data)); u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE + 1])); @@ -244,28 +243,27 @@ void ConnectionSendThread::runTimeouts(float dtime) if (k->resend_count > MAX_RELIABLE_RETRY) { retry_count_exceeded = true; timeouted_peers.push_back(peer->id); - /* no need to check additional packets if a single - * one did timeout*/ + /* no need to check additional packets if a single one did timeout*/ break; } LOG(derr_con << m_connection->getDesc() - << "RE-SENDING timed-out RELIABLE to " - << k->address.serializeString() - << "(t/o=" << resend_timeout << "): " - << "from_peer_id=" << peer_id - << ", channel=" << ((int)channelnum & 0xff) - << ", seqnum=" << seqnum << std::endl); + << "RE-SENDING timed-out RELIABLE to " + << k->address.serializeString() + << "(t/o=" << resend_timeout << "): " + << "from_peer_id=" << peer_id + << ", channel=" << ((int) channelnum & 0xff) + << ", seqnum=" << seqnum + << std::endl); rawSend(*k); - // do not handle rtt here as we can't decide if this - // packet was lost or really takes more time to transmit + // do not handle rtt here as we can't decide if this packet was + // lost or really takes more time to transmit } if (retry_count_exceeded) { - break; /* no need to check other channels if we already - did timeout */ + break; /* no need to check other channels if we already did timeout */ } channel.UpdateTimers(dtime); @@ -278,23 +276,23 @@ void ConnectionSendThread::runTimeouts(float dtime) /* send ping if necessary */ if (udpPeer->Ping(dtime, data)) { LOG(dout_con << m_connection->getDesc() - << "Sending ping for peer_id: " << udpPeer->id - << std::endl); + << "Sending ping for peer_id: " << udpPeer->id << std::endl); /* this may fail if there ain't a sequence number left */ if (!rawSendAsPacket(udpPeer->id, 0, data, true)) { - // retrigger with reduced ping interval + //retrigger with reduced ping interval udpPeer->Ping(4.0, data); } } - udpPeer->RunCommandQueues(m_max_packet_size, m_max_commands_per_iteration, - m_max_packets_requeued); + udpPeer->RunCommandQueues(m_max_packet_size, + m_max_commands_per_iteration, + m_max_packets_requeued); } // Remove timed out peers for (u16 timeouted_peer : timeouted_peers) { - LOG(dout_con << m_connection->getDesc() << "RunTimeouts(): Removing peer " - << timeouted_peer << std::endl); + LOG(dout_con << m_connection->getDesc() + << "RunTimeouts(): Removing peer " << timeouted_peer << std::endl); m_connection->deletePeer(timeouted_peer, true); } } @@ -302,14 +300,15 @@ void ConnectionSendThread::runTimeouts(float dtime) void ConnectionSendThread::rawSend(const BufferedPacket &packet) { try { - m_connection->m_udpSocket.Send( - packet.address, *packet.data, packet.data.getSize()); - LOG(dout_con << m_connection->getDesc() << " rawSend: " - << packet.data.getSize() << " bytes sent" << std::endl); + m_connection->m_udpSocket.Send(packet.address, *packet.data, + packet.data.getSize()); + LOG(dout_con << m_connection->getDesc() + << " rawSend: " << packet.data.getSize() + << " bytes sent" << std::endl); } catch (SendFailedException &e) { LOG(derr_con << m_connection->getDesc() - << "Connection::rawSend(): SendFailedException: " - << packet.address.serializeString() << std::endl); + << "Connection::rawSend(): SendFailedException: " + << packet.address.serializeString() << std::endl); } } @@ -318,14 +317,14 @@ void ConnectionSendThread::sendAsPacketReliable(BufferedPacket &p, Channel *chan try { p.absolute_send_time = porting::getTimeMs(); // Buffer the packet - channel->outgoing_reliables_sent.insert( - p, (channel->readOutgoingSequenceNumber() - - MAX_RELIABLE_WINDOW_SIZE) % - (MAX_RELIABLE_WINDOW_SIZE + 1)); - } catch (AlreadyExistsException &e) { + channel->outgoing_reliables_sent.insert(p, + (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE) + % (MAX_RELIABLE_WINDOW_SIZE + 1)); + } + catch (AlreadyExistsException &e) { LOG(derr_con << m_connection->getDesc() - << "WARNING: Going to send a reliable packet" - << " in outgoing buffer" << std::endl); + << "WARNING: Going to send a reliable packet" + << " in outgoing buffer" << std::endl); } // Send the packet @@ -333,22 +332,21 @@ void ConnectionSendThread::sendAsPacketReliable(BufferedPacket &p, Channel *chan } bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum, - const SharedBuffer &data, bool reliable) + const SharedBuffer &data, bool reliable) { PeerHelper peer = m_connection->getPeerNoEx(peer_id); if (!peer) { - LOG(errorstream << m_connection->getDesc() << " dropped " - << (reliable ? "reliable " : "") - << "packet for non existent peer_id: " << peer_id - << std::endl); + LOG(errorstream << m_connection->getDesc() + << " dropped " << (reliable ? "reliable " : "") + << "packet for non existent peer_id: " << peer_id << std::endl); return false; } Channel *channel = &(dynamic_cast(&peer)->channels[channelnum]); if (reliable) { bool have_sequence_number_for_raw_packet = true; - u16 seqnum = channel->getOutgoingSequenceNumber( - have_sequence_number_for_raw_packet); + u16 seqnum = + channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet); if (!have_sequence_number_for_raw_packet) return false; @@ -359,23 +357,24 @@ bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum, // Add base headers and make a packet BufferedPacket p = con::makePacket(peer_address, reliable, - m_connection->GetProtocolID(), m_connection->GetPeerID(), - channelnum); + m_connection->GetProtocolID(), m_connection->GetPeerID(), + channelnum); // first check if our send window is already maxed out - if (channel->outgoing_reliables_sent.size() < channel->getWindowSize()) { + if (channel->outgoing_reliables_sent.size() + < channel->getWindowSize()) { LOG(dout_con << m_connection->getDesc() - << " INFO: sending a reliable packet to peer_id " - << peer_id << " channel: " << (u32)channelnum - << " seqnum: " << seqnum << std::endl); + << " INFO: sending a reliable packet to peer_id " << peer_id + << " channel: " << (u32)channelnum + << " seqnum: " << seqnum << std::endl); sendAsPacketReliable(p, channel); return true; } LOG(dout_con << m_connection->getDesc() - << " INFO: queueing reliable packet for peer_id: " << peer_id - << " channel: " << (u32)channelnum << " seqnum: " << seqnum - << std::endl); + << " INFO: queueing reliable packet for peer_id: " << peer_id + << " channel: " << (u32)channelnum + << " seqnum: " << seqnum << std::endl); channel->queued_reliables.push(p); return false; } @@ -384,8 +383,8 @@ bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum, if (peer->getAddress(MTP_UDP, peer_address)) { // Add base headers and make a packet BufferedPacket p = con::makePacket(peer_address, data, - m_connection->GetProtocolID(), m_connection->GetPeerID(), - channelnum); + m_connection->GetProtocolID(), m_connection->GetPeerID(), + channelnum); // Send the packet rawSend(p); @@ -393,116 +392,116 @@ bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum, } LOG(dout_con << m_connection->getDesc() - << " INFO: dropped unreliable packet for peer_id: " << peer_id - << " because of (yet) missing udp address" << std::endl); + << " INFO: dropped unreliable packet for peer_id: " << peer_id + << " because of (yet) missing udp address" << std::endl); return false; } void ConnectionSendThread::processReliableCommand(ConnectionCommand &c) { - assert(c.reliable); // Pre-condition + assert(c.reliable); // Pre-condition switch (c.type) { - case CONNCMD_NONE: - LOG(dout_con << m_connection->getDesc() - << "UDP processing reliable CONNCMD_NONE" << std::endl); - return; + case CONNCMD_NONE: + LOG(dout_con << m_connection->getDesc() + << "UDP processing reliable CONNCMD_NONE" << std::endl); + return; - case CONNCMD_SEND: - LOG(dout_con << m_connection->getDesc() - << "UDP processing reliable CONNCMD_SEND" << std::endl); - sendReliable(c); - return; + case CONNCMD_SEND: + LOG(dout_con << m_connection->getDesc() + << "UDP processing reliable CONNCMD_SEND" << std::endl); + sendReliable(c); + return; - case CONNCMD_SEND_TO_ALL: - LOG(dout_con << m_connection->getDesc() - << "UDP processing CONNCMD_SEND_TO_ALL" << std::endl); - sendToAllReliable(c); - return; + case CONNCMD_SEND_TO_ALL: + LOG(dout_con << m_connection->getDesc() + << "UDP processing CONNCMD_SEND_TO_ALL" << std::endl); + sendToAllReliable(c); + return; - case CONCMD_CREATE_PEER: - LOG(dout_con << m_connection->getDesc() - << "UDP processing reliable CONCMD_CREATE_PEER" - << std::endl); - if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) { - /* put to queue if we couldn't send it immediately */ - sendReliable(c); - } - return; + case CONCMD_CREATE_PEER: + LOG(dout_con << m_connection->getDesc() + << "UDP processing reliable CONCMD_CREATE_PEER" << std::endl); + if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) { + /* put to queue if we couldn't send it immediately */ + sendReliable(c); + } + return; - case CONNCMD_SERVE: - case CONNCMD_CONNECT: - case CONNCMD_DISCONNECT: - case CONCMD_ACK: - FATAL_ERROR("Got command that shouldn't be reliable as reliable command"); - default: - LOG(dout_con << m_connection->getDesc() - << " Invalid reliable command type: " << c.type - << std::endl); + case CONNCMD_SERVE: + case CONNCMD_CONNECT: + case CONNCMD_DISCONNECT: + case CONCMD_ACK: + FATAL_ERROR("Got command that shouldn't be reliable as reliable command"); + default: + LOG(dout_con << m_connection->getDesc() + << " Invalid reliable command type: " << c.type << std::endl); } } + void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c) { assert(!c.reliable); // Pre-condition switch (c.type) { - case CONNCMD_NONE: - LOG(dout_con << m_connection->getDesc() << " UDP processing CONNCMD_NONE" - << std::endl); - return; - case CONNCMD_SERVE: - LOG(dout_con << m_connection->getDesc() - << " UDP processing CONNCMD_SERVE port=" - << c.address.serializeString() << std::endl); - serve(c.address); - return; - case CONNCMD_CONNECT: - LOG(dout_con << m_connection->getDesc() - << " UDP processing CONNCMD_CONNECT" << std::endl); - connect(c.address); - return; - case CONNCMD_DISCONNECT: - LOG(dout_con << m_connection->getDesc() - << " UDP processing CONNCMD_DISCONNECT" << std::endl); - disconnect(); - return; - case CONNCMD_DISCONNECT_PEER: - LOG(dout_con << m_connection->getDesc() - << " UDP processing CONNCMD_DISCONNECT_PEER" << std::endl); - disconnect_peer(c.peer_id); - return; - case CONNCMD_SEND: - LOG(dout_con << m_connection->getDesc() << " UDP processing CONNCMD_SEND" - << std::endl); - send(c.peer_id, c.channelnum, c.data); - return; - case CONNCMD_SEND_TO_ALL: - LOG(dout_con << m_connection->getDesc() - << " UDP processing CONNCMD_SEND_TO_ALL" << std::endl); - sendToAll(c.channelnum, c.data); - return; - case CONCMD_ACK: - LOG(dout_con << m_connection->getDesc() << " UDP processing CONCMD_ACK" - << std::endl); - sendAsPacket(c.peer_id, c.channelnum, c.data, true); - return; - case CONCMD_CREATE_PEER: - FATAL_ERROR("Got command that should be reliable as unreliable command"); - default: - LOG(dout_con << m_connection->getDesc() - << " Invalid command type: " << c.type << std::endl); + case CONNCMD_NONE: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_NONE" << std::endl); + return; + case CONNCMD_SERVE: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_SERVE port=" + << c.address.serializeString() << std::endl); + serve(c.address); + return; + case CONNCMD_CONNECT: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_CONNECT" << std::endl); + connect(c.address); + return; + case CONNCMD_DISCONNECT: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_DISCONNECT" << std::endl); + disconnect(); + return; + case CONNCMD_DISCONNECT_PEER: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_DISCONNECT_PEER" << std::endl); + disconnect_peer(c.peer_id); + return; + case CONNCMD_SEND: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_SEND" << std::endl); + send(c.peer_id, c.channelnum, c.data); + return; + case CONNCMD_SEND_TO_ALL: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONNCMD_SEND_TO_ALL" << std::endl); + sendToAll(c.channelnum, c.data); + return; + case CONCMD_ACK: + LOG(dout_con << m_connection->getDesc() + << " UDP processing CONCMD_ACK" << std::endl); + sendAsPacket(c.peer_id, c.channelnum, c.data, true); + return; + case CONCMD_CREATE_PEER: + FATAL_ERROR("Got command that should be reliable as unreliable command"); + default: + LOG(dout_con << m_connection->getDesc() + << " Invalid command type: " << c.type << std::endl); } } void ConnectionSendThread::serve(Address bind_address) { - LOG(dout_con << m_connection->getDesc() << "UDP serving at port " - << bind_address.serializeString() << std::endl); + LOG(dout_con << m_connection->getDesc() + << "UDP serving at port " << bind_address.serializeString() << std::endl); try { m_connection->m_udpSocket.Bind(bind_address); m_connection->SetPeerID(PEER_ID_SERVER); - } catch (SocketException &e) { + } + catch (SocketException &e) { // Create event ConnectionEvent ce; ce.bindFailed(); @@ -513,8 +512,8 @@ void ConnectionSendThread::serve(Address bind_address) void ConnectionSendThread::connect(Address address) { LOG(dout_con << m_connection->getDesc() << " connecting to " - << address.serializeString() << ":" << address.getPort() - << std::endl); + << address.serializeString() + << ":" << address.getPort() << std::endl); UDPPeer *peer = m_connection->createServerPeer(address); @@ -526,7 +525,7 @@ void ConnectionSendThread::connect(Address address) Address bind_addr; if (address.isIPv6()) - bind_addr.setAddress((IPv6AddressBytes *)NULL); + bind_addr.setAddress((IPv6AddressBytes *) NULL); else bind_addr.setAddress(0, 0, 0, 0); @@ -547,6 +546,7 @@ void ConnectionSendThread::disconnect() writeU8(&data[0], PACKET_TYPE_CONTROL); writeU8(&data[1], CONTROLTYPE_DISCO); + // Send to all std::list peerids = m_connection->getPeerIDs(); @@ -577,23 +577,23 @@ void ConnectionSendThread::disconnect_peer(session_t peer_id) dynamic_cast(&peer)->m_pending_disconnect = true; } -void ConnectionSendThread::send( - session_t peer_id, u8 channelnum, const SharedBuffer &data) +void ConnectionSendThread::send(session_t peer_id, u8 channelnum, + const SharedBuffer &data) { assert(channelnum < CHANNEL_COUNT); // Pre-condition PeerHelper peer = m_connection->getPeerNoEx(peer_id); if (!peer) { LOG(dout_con << m_connection->getDesc() << " peer: peer_id=" << peer_id - << ">>>NOT<<< found on sending packet" - << ", channel " << (channelnum % 0xFF) - << ", size: " << data.getSize() << std::endl); + << ">>>NOT<<< found on sending packet" + << ", channel " << (channelnum % 0xFF) + << ", size: " << data.getSize() << std::endl); return; } LOG(dout_con << m_connection->getDesc() << " sending to peer_id=" << peer_id - << ", channel " << (channelnum % 0xFF) - << ", size: " << data.getSize() << std::endl); + << ", channel " << (channelnum % 0xFF) + << ", size: " << data.getSize() << std::endl); u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum); @@ -647,16 +647,16 @@ void ConnectionSendThread::sendPackets(float dtime) std::list pendingDisconnect; std::map pending_unreliable; - const unsigned int peer_packet_quota = - m_iteration_packets_avaialble / MYMAX(peerIds.size(), 1); + const unsigned int peer_packet_quota = m_iteration_packets_avaialble + / MYMAX(peerIds.size(), 1); for (session_t peerId : peerIds) { PeerHelper peer = m_connection->getPeerNoEx(peerId); - // peer may have been removed + //peer may have been removed if (!peer) { - LOG(dout_con << m_connection->getDesc() - << " Peer not found: peer_id=" << peerId - << std::endl); + LOG(dout_con << m_connection->getDesc() << " Peer not found: peer_id=" + << peerId + << std::endl); continue; } peer->m_increment_packets_remaining = peer_packet_quota; @@ -671,16 +671,17 @@ void ConnectionSendThread::sendPackets(float dtime) pendingDisconnect.push_back(peerId); } - PROFILE(std::stringstream peerIdentifier); - PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" - << peerId << ";RELIABLE]"); - PROFILE(ScopeProfiler peerprofiler( - g_profiler, peerIdentifier.str(), SPT_AVG)); + PROFILE(std::stringstream + peerIdentifier); + PROFILE( + peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId + << ";RELIABLE]"); + PROFILE(ScopeProfiler + peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG)); LOG(dout_con << m_connection->getDesc() - << " Handle per peer queues: peer_id=" << peerId - << " packet quota: " << peer->m_increment_packets_remaining - << std::endl); + << " Handle per peer queues: peer_id=" << peerId + << " packet quota: " << peer->m_increment_packets_remaining << std::endl); // first send queued reliable packets for all peers (if possible) for (unsigned int i = 0; i < CHANNEL_COUNT; i++) { @@ -691,34 +692,38 @@ void ConnectionSendThread::sendPackets(float dtime) u16 next_to_receive = 0; channel.incoming_reliables.getFirstSeqnum(next_to_receive); - LOG(dout_con << m_connection->getDesc() << "\t channel: " << i - << ", peer quota:" - << peer->m_increment_packets_remaining << std::endl - << "\t\t\treliables on wire: " - << channel.outgoing_reliables_sent.size() - << ", waiting for ack for " << next_to_ack - << std::endl - << "\t\t\tincoming_reliables: " - << channel.incoming_reliables.size() - << ", next reliable packet: " - << channel.readNextIncomingSeqNum() - << ", next queued: " << next_to_receive << std::endl - << "\t\t\treliables queued : " - << channel.queued_reliables.size() << std::endl - << "\t\t\tqueued commands : " - << channel.queued_commands.size() << std::endl); + LOG(dout_con << m_connection->getDesc() << "\t channel: " + << i << ", peer quota:" + << peer->m_increment_packets_remaining + << std::endl + << "\t\t\treliables on wire: " + << channel.outgoing_reliables_sent.size() + << ", waiting for ack for " << next_to_ack + << std::endl + << "\t\t\tincoming_reliables: " + << channel.incoming_reliables.size() + << ", next reliable packet: " + << channel.readNextIncomingSeqNum() + << ", next queued: " << next_to_receive + << std::endl + << "\t\t\treliables queued : " + << channel.queued_reliables.size() + << std::endl + << "\t\t\tqueued commands : " + << channel.queued_commands.size() + << std::endl); while (!channel.queued_reliables.empty() && - channel.outgoing_reliables_sent.size() < - channel.getWindowSize() && + channel.outgoing_reliables_sent.size() + < channel.getWindowSize() && peer->m_increment_packets_remaining > 0) { BufferedPacket p = channel.queued_reliables.front(); channel.queued_reliables.pop(); LOG(dout_con << m_connection->getDesc() - << " INFO: sending a queued reliable packet " - << " channel: " << i << ", seqnum: " - << readU16(&p.data[BASE_HEADER_SIZE + 1]) - << std::endl); + << " INFO: sending a queued reliable packet " + << " channel: " << i + << ", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE + 1]) + << std::endl); sendAsPacketReliable(p, &channel); peer->m_increment_packets_remaining--; } @@ -726,8 +731,9 @@ void ConnectionSendThread::sendPackets(float dtime) } if (!m_outgoing_queue.empty()) { - LOG(dout_con << m_connection->getDesc() << " Handle non reliable queue (" - << m_outgoing_queue.size() << " pkts)" << std::endl); + LOG(dout_con << m_connection->getDesc() + << " Handle non reliable queue (" + << m_outgoing_queue.size() << " pkts)" << std::endl); } unsigned int initial_queuesize = m_outgoing_queue.size(); @@ -742,18 +748,17 @@ void ConnectionSendThread::sendPackets(float dtime) PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id); if (!peer) { LOG(dout_con << m_connection->getDesc() - << " Outgoing queue: peer_id=" << packet.peer_id - << ">>>NOT<<< found on sending packet" - << ", channel " << (packet.channelnum % 0xFF) - << ", size: " << packet.data.getSize() << std::endl); + << " Outgoing queue: peer_id=" << packet.peer_id + << ">>>NOT<<< found on sending packet" + << ", channel " << (packet.channelnum % 0xFF) + << ", size: " << packet.data.getSize() << std::endl); continue; } /* send acks immediately */ - if (packet.ack || peer->m_increment_packets_remaining > 0 || - stopRequested()) { - rawSendAsPacket(packet.peer_id, packet.channelnum, packet.data, - packet.reliable); + if (packet.ack || peer->m_increment_packets_remaining > 0 || stopRequested()) { + rawSendAsPacket(packet.peer_id, packet.channelnum, + packet.data, packet.reliable); if (peer->m_increment_packets_remaining > 0) peer->m_increment_packets_remaining--; } else { @@ -769,10 +774,8 @@ void ConnectionSendThread::sendPackets(float dtime) continue; if (peer->m_increment_packets_remaining == 0) { LOG(warningstream << m_connection->getDesc() - << " Packet quota used up for peer_id=" - << peerId << ", was " - << peer_packet_quota << " pkts" - << std::endl); + << " Packet quota used up for peer_id=" << peerId + << ", was " << peer_packet_quota << " pkts" << std::endl); } } } @@ -784,15 +787,15 @@ void ConnectionSendThread::sendPackets(float dtime) } } -void ConnectionSendThread::sendAsPacket( - session_t peer_id, u8 channelnum, const SharedBuffer &data, bool ack) +void ConnectionSendThread::sendAsPacket(session_t peer_id, u8 channelnum, + const SharedBuffer &data, bool ack) { OutgoingPacket packet(peer_id, channelnum, data, false, ack); m_outgoing_queue.push(packet); } ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) : - Thread("ConnectionReceive") + Thread("ConnectionReceive") { } @@ -800,12 +803,12 @@ void *ConnectionReceiveThread::run() { assert(m_connection); - LOG(dout_con << m_connection->getDesc() << "ConnectionReceive thread started" - << std::endl); + LOG(dout_con << m_connection->getDesc() + << "ConnectionReceive thread started" << std::endl); - PROFILE(std::stringstream ThreadIdentifier); - PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() - << "]"); + PROFILE(std::stringstream + ThreadIdentifier); + PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]"); // use IPv6 minimum allowed MTU as receive buffer size as this is // theoretical reliable upper boundary of a udp packet for all IPv6 enabled @@ -823,12 +826,13 @@ void *ConnectionReceiveThread::run() while (!stopRequested()) { BEGIN_DEBUG_EXCEPTION_HANDLER - PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG)); + PROFILE(ScopeProfiler + sp(g_profiler, ThreadIdentifier.str(), SPT_AVG)); #ifdef DEBUG_CONNECTION_KBPS lasttime = curtime; curtime = porting::getTimeMs(); - float dtime = CALC_DTIME(lasttime, curtime); + float dtime = CALC_DTIME(lasttime,curtime); #endif /* receive packets */ @@ -842,7 +846,9 @@ void *ConnectionReceiveThread::run() std::list peerids = m_connection->getPeerIDs(); for (std::list::iterator i = peerids.begin(); - i != peerids.end(); i++) { + i != peerids.end(); + i++) + { PeerHelper peer = m_connection->getPeerNoEx(*i); if (!peer) continue; @@ -852,52 +858,35 @@ void *ConnectionReceiveThread::run() float avg_rate = 0.0; float avg_loss = 0.0; - for (u16 j = 0; j < CHANNEL_COUNT; j++) { - peer_current += peer->channels[j] - .getCurrentDownloadRateKB(); - peer_loss += peer->channels[j] - .getCurrentLossRateKB(); - avg_rate += peer->channels[j] - .getAvgDownloadRateKB(); + for(u16 j=0; jchannels[j].getCurrentDownloadRateKB(); + peer_loss += peer->channels[j].getCurrentLossRateKB(); + avg_rate += peer->channels[j].getAvgDownloadRateKB(); avg_loss += peer->channels[j].getAvgLossRateKB(); } std::stringstream output; output << std::fixed << std::setprecision(1); - output << "OUT to Peer " << *i << " RATES (good / loss) " - << std::endl; - output << "\tcurrent (sum): " << peer_current << "kb/s " - << peer_loss << "kb/s" << std::endl; - output << "\taverage (sum): " << avg_rate << "kb/s " - << avg_loss << "kb/s" << std::endl; + output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl; + output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl; + output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl; output << std::setfill(' '); - for (u16 j = 0; j < CHANNEL_COUNT; j++) { + for(u16 j=0; jchannels[j].getCurrentDownloadRateKB() - << "kb/s" - << " AVG: " << std::setw(6) - << peer->channels[j].getAvgDownloadRateKB() - << "kb/s" - << " MAX: " << std::setw(6) - << peer->channels[j].getMaxDownloadRateKB() - << "kb/s" - << " /" - << " CUR: " << std::setw(6) - << peer->channels[j].getCurrentLossRateKB() - << "kb/s" - << " AVG: " << std::setw(6) - << peer->channels[j].getAvgLossRateKB() - << "kb/s" - << " MAX: " << std::setw(6) - << peer->channels[j].getMaxLossRateKB() - << "kb/s" - << " / WS: " - << peer->channels[j].getWindowSize() - << std::endl; + << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s" + << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s" + << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s" + << " /" + << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s" + << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s" + << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s" + << " / WS: " << peer->channels[j].getWindowSize() + << std::endl; } - fprintf(stderr, "%s\n", output.str().c_str()); + fprintf(stderr,"%s\n",output.str().c_str()); } } #endif @@ -909,7 +898,8 @@ void *ConnectionReceiveThread::run() } // Receive packets from the network and buffers and create ConnectionEvents -void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet_queued) +void ConnectionReceiveThread::receive(SharedBuffer &packetdata, + bool &packet_queued) { try { // First, see if there any buffered packets we can process now @@ -925,7 +915,8 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet e.dataReceived(peer_id, resultdata); m_connection->putEvent(e); } - } catch (ProcessedSilentlyException &e) { + } + catch (ProcessedSilentlyException &e) { /* try reading again */ } } @@ -934,20 +925,19 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet // Call Receive() to wait for incoming data Address sender; - s32 received_size = m_connection->m_udpSocket.Receive( - sender, *packetdata, packetdata.getSize()); + s32 received_size = m_connection->m_udpSocket.Receive(sender, + *packetdata, packetdata.getSize()); if (received_size < 0) return; if ((received_size < BASE_HEADER_SIZE) || - (readU32(&packetdata[0]) != - m_connection->GetProtocolID())) { + (readU32(&packetdata[0]) != m_connection->GetProtocolID())) { LOG(derr_con << m_connection->getDesc() - << "Receive(): Invalid incoming packet, " - << "size: " << received_size << ", protocol: " - << ((received_size >= 4) ? readU32(&packetdata[0]) - : -1) - << std::endl); + << "Receive(): Invalid incoming packet, " + << "size: " << received_size + << ", protocol: " + << ((received_size >= 4) ? readU32(&packetdata[0]) : -1) + << std::endl); return; } @@ -956,8 +946,7 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet if (channelnum > CHANNEL_COUNT - 1) { LOG(derr_con << m_connection->getDesc() - << "Receive(): Invalid channel " << (u32)channelnum - << std::endl); + << "Receive(): Invalid channel " << (u32)channelnum << std::endl); return; } @@ -971,15 +960,14 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet /* The peer was not found in our lists. Add it. */ if (peer_id == PEER_ID_INEXISTENT) { - peer_id = m_connection->createPeer( - sender, MTP_MINETEST_RELIABLE_UDP, 0); + peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0); } PeerHelper peer = m_connection->getPeerNoEx(peer_id); if (!peer) { LOG(dout_con << m_connection->getDesc() - << " got packet from unknown peer_id: " << peer_id - << " Ignoring." << std::endl); + << " got packet from unknown peer_id: " + << peer_id << " Ignoring." << std::endl); return; } @@ -988,18 +976,15 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet Address peer_address; if (peer->getAddress(MTP_UDP, peer_address)) { if (peer_address != sender) { - LOG(derr_con << m_connection->getDesc() << " Peer " - << peer_id - << " sending from different address." - " Ignoring." - << std::endl); + LOG(derr_con << m_connection->getDesc() + << " Peer " << peer_id << " sending from different address." + " Ignoring." << std::endl); return; } } else { - LOG(derr_con << m_connection->getDesc() << " Peer " << peer_id - << " doesn't have an address?!" - " Ignoring." - << std::endl); + LOG(derr_con << m_connection->getDesc() + << " Peer " << peer_id << " doesn't have an address?!" + " Ignoring." << std::endl); return; } @@ -1010,10 +995,8 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet channel = &dynamic_cast(&peer)->channels[channelnum]; } else { LOG(derr_con << m_connection->getDesc() - << "Receive(): peer_id=" << peer_id - << " isn't an UDPPeer?!" - " Ignoring." - << std::endl); + << "Receive(): peer_id=" << peer_id << " isn't an UDPPeer?!" + " Ignoring." << std::endl); return; } @@ -1024,30 +1007,33 @@ void ConnectionReceiveThread::receive(SharedBuffer &packetdata, bool &packet // Make a new SharedBuffer from the data without the base headers SharedBuffer strippeddata(received_size - BASE_HEADER_SIZE); memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE], - strippeddata.getSize()); + strippeddata.getSize()); try { // Process it (the result is some data with no headers made by us) - SharedBuffer resultdata = processPacket(channel, strippeddata, - peer_id, channelnum, false); + SharedBuffer resultdata = processPacket + (channel, strippeddata, peer_id, channelnum, false); LOG(dout_con << m_connection->getDesc() - << " ProcessPacket from peer_id: " << peer_id - << ", channel: " << (u32)channelnum << ", returned " - << resultdata.getSize() << " bytes" << std::endl); + << " ProcessPacket from peer_id: " << peer_id + << ", channel: " << (u32)channelnum << ", returned " + << resultdata.getSize() << " bytes" << std::endl); ConnectionEvent e; e.dataReceived(peer_id, resultdata); m_connection->putEvent(e); - } catch (ProcessedSilentlyException &e) { - } catch (ProcessedQueued &e) { + } + catch (ProcessedSilentlyException &e) { + } + catch (ProcessedQueued &e) { // we set it to true anyway (see below) } /* Every time we receive a packet it can happen that a previously * buffered packet is now ready to process. */ packet_queued = true; - } catch (InvalidIncomingDataException &e) { + } + catch (InvalidIncomingDataException &e) { } } @@ -1072,8 +1058,8 @@ bool ConnectionReceiveThread::getFromBuffers(session_t &peer_id, SharedBuffer &dst) +bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel, + session_t &peer_id, SharedBuffer &dst) { u16 firstseqnum = 0; if (channel->incoming_reliables.getFirstSeqnum(firstseqnum)) { @@ -1084,10 +1070,11 @@ bool ConnectionReceiveThread::checkIncomingBuffers( u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]); LOG(dout_con << m_connection->getDesc() - << "UNBUFFERING TYPE_RELIABLE" - << " seqnum=" << seqnum << " peer_id=" << peer_id - << " channel=" << ((int)channelnum & 0xff) - << std::endl); + << "UNBUFFERING TYPE_RELIABLE" + << " seqnum=" << seqnum + << " peer_id=" << peer_id + << " channel=" << ((int) channelnum & 0xff) + << std::endl); channel->incNextIncomingSeqNum(); @@ -1104,8 +1091,7 @@ bool ConnectionReceiveThread::checkIncomingBuffers( } SharedBuffer ConnectionReceiveThread::processPacket(Channel *channel, - const SharedBuffer &packetdata, session_t peer_id, u8 channelnum, - bool reliable) + const SharedBuffer &packetdata, session_t peer_id, u8 channelnum, bool reliable) { PeerHelper peer = m_connection->getPeerNoEx(peer_id); @@ -1126,8 +1112,8 @@ SharedBuffer ConnectionReceiveThread::processPacket(Channel *channel, } if (type >= PACKET_TYPE_MAX) { - derr_con << m_connection->getDesc() - << "Got invalid type=" << ((int)type & 0xff) << std::endl; + derr_con << m_connection->getDesc() << "Got invalid type=" << ((int) type & 0xff) + << std::endl; throw InvalidIncomingDataException("Invalid packet type"); } @@ -1136,16 +1122,15 @@ SharedBuffer ConnectionReceiveThread::processPacket(Channel *channel, } const ConnectionReceiveThread::PacketTypeHandler - ConnectionReceiveThread::packetTypeRouter[PACKET_TYPE_MAX] = { - {&ConnectionReceiveThread::handlePacketType_Control}, - {&ConnectionReceiveThread::handlePacketType_Original}, - {&ConnectionReceiveThread::handlePacketType_Split}, - {&ConnectionReceiveThread::handlePacketType_Reliable}, + ConnectionReceiveThread::packetTypeRouter[PACKET_TYPE_MAX] = { + {&ConnectionReceiveThread::handlePacketType_Control}, + {&ConnectionReceiveThread::handlePacketType_Original}, + {&ConnectionReceiveThread::handlePacketType_Split}, + {&ConnectionReceiveThread::handlePacketType_Reliable}, }; SharedBuffer ConnectionReceiveThread::handlePacketType_Control(Channel *channel, - const SharedBuffer &packetdata, Peer *peer, u8 channelnum, - bool reliable) + const SharedBuffer &packetdata, Peer *peer, u8 channelnum, bool reliable) { if (packetdata.getSize() < 2) throw InvalidIncomingDataException("packetdata.getSize() < 2"); @@ -1157,29 +1142,26 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Control(Channel *chan if (packetdata.getSize() < 4) { throw InvalidIncomingDataException( - "packetdata.getSize() < 4 (ACK header size)"); + "packetdata.getSize() < 4 (ACK header size)"); } u16 seqnum = readU16(&packetdata[2]); - LOG(dout_con << m_connection->getDesc() - << " [ CONTROLTYPE_ACK: channelnum=" - << ((int)channelnum & 0xff) << ", peer_id=" << peer->id - << ", seqnum=" << seqnum << " ]" << std::endl); + LOG(dout_con << m_connection->getDesc() << " [ CONTROLTYPE_ACK: channelnum=" + << ((int) channelnum & 0xff) << ", peer_id=" << peer->id << ", seqnum=" + << seqnum << " ]" << std::endl); try { - BufferedPacket p = channel->outgoing_reliables_sent.popSeqnum( - seqnum); + BufferedPacket p = channel->outgoing_reliables_sent.popSeqnum(seqnum); // only calculate rtt from straight sent packets if (p.resend_count == 0) { // Get round trip time u64 current_time = porting::getTimeMs(); - // a overflow is quite unlikely but as it'd result in - // major rtt miscalculation we handle it here + // a overflow is quite unlikely but as it'd result in major + // rtt miscalculation we handle it here if (current_time > p.absolute_send_time) { - float rtt = (current_time - p.absolute_send_time) / - 1000.0; + float rtt = (current_time - p.absolute_send_time) / 1000.0; // Let peer calculate stuff according to it // (avg_rtt and resend_timeout) @@ -1198,8 +1180,8 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Control(Channel *chan m_connection->TriggerSend(); } catch (NotFoundException &e) { LOG(derr_con << m_connection->getDesc() - << "WARNING: ACKed packet not in outgoing queue" - << " seqnum=" << seqnum << std::endl); + << "WARNING: ACKed packet not in outgoing queue" + << " seqnum=" << seqnum << std::endl); channel->UpdatePacketTooLateCounter(); } @@ -1207,19 +1189,18 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Control(Channel *chan } else if (controltype == CONTROLTYPE_SET_PEER_ID) { // Got a packet to set our peer id if (packetdata.getSize() < 4) - throw InvalidIncomingDataException("packetdata.getSize() < 4 " - "(SET_PEER_ID header size)"); + throw InvalidIncomingDataException + ("packetdata.getSize() < 4 (SET_PEER_ID header size)"); session_t peer_id_new = readU16(&packetdata[2]); - LOG(dout_con << m_connection->getDesc() << "Got new peer id: " - << peer_id_new << "... " << std::endl); + LOG(dout_con << m_connection->getDesc() << "Got new peer id: " << peer_id_new + << "... " << std::endl); if (m_connection->GetPeerID() != PEER_ID_INEXISTENT) { LOG(derr_con << m_connection->getDesc() - << "WARNING: Not changing existing peer id." - << std::endl); + << "WARNING: Not changing existing peer id." << std::endl); } else { LOG(dout_con << m_connection->getDesc() << "changing own peer id" - << std::endl); + << std::endl); m_connection->SetPeerID(peer_id_new); } @@ -1233,31 +1214,29 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Control(Channel *chan // Just ignore it, the incoming data already reset // the timeout counter LOG(dout_con << m_connection->getDesc() << "DISCO: Removing peer " - << peer->id << std::endl); + << peer->id << std::endl); if (!m_connection->deletePeer(peer->id, false)) { - derr_con << m_connection->getDesc() << "DISCO: Peer not found" - << std::endl; + derr_con << m_connection->getDesc() << "DISCO: Peer not found" << std::endl; } throw ProcessedSilentlyException("Got a DISCO"); } else { LOG(derr_con << m_connection->getDesc() - << "INVALID TYPE_CONTROL: invalid controltype=" - << ((int)controltype & 0xff) << std::endl); + << "INVALID TYPE_CONTROL: invalid controltype=" + << ((int) controltype & 0xff) << std::endl); throw InvalidIncomingDataException("Invalid control type"); } } SharedBuffer ConnectionReceiveThread::handlePacketType_Original(Channel *channel, - const SharedBuffer &packetdata, Peer *peer, u8 channelnum, - bool reliable) + const SharedBuffer &packetdata, Peer *peer, u8 channelnum, bool reliable) { if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE) - throw InvalidIncomingDataException( - "packetdata.getSize() <= ORIGINAL_HEADER_SIZE"); + throw InvalidIncomingDataException + ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE"); LOG(dout_con << m_connection->getDesc() << "RETURNING TYPE_ORIGINAL to user" - << std::endl); + << std::endl); // Get the inside packet out and return it SharedBuffer payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE); memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize()); @@ -1265,29 +1244,29 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Original(Channel *cha } SharedBuffer ConnectionReceiveThread::handlePacketType_Split(Channel *channel, - const SharedBuffer &packetdata, Peer *peer, u8 channelnum, - bool reliable) + const SharedBuffer &packetdata, Peer *peer, u8 channelnum, bool reliable) { Address peer_address; if (peer->getAddress(MTP_UDP, peer_address)) { // We have to create a packet again for buffering // This isn't actually too bad an idea. - BufferedPacket packet = makePacket(peer_address, packetdata, - m_connection->GetProtocolID(), peer->id, channelnum); + BufferedPacket packet = makePacket(peer_address, + packetdata, + m_connection->GetProtocolID(), + peer->id, + channelnum); // Buffer the packet - SharedBuffer data = - peer->addSplitPacket(channelnum, packet, reliable); + SharedBuffer data = peer->addSplitPacket(channelnum, packet, reliable); if (data.getSize() != 0) { LOG(dout_con << m_connection->getDesc() - << "RETURNING TYPE_SPLIT: Constructed full data, " - << "size=" << data.getSize() << std::endl); + << "RETURNING TYPE_SPLIT: Constructed full data, " + << "size=" << data.getSize() << std::endl); return data; } - LOG(dout_con << m_connection->getDesc() << "BUFFERED TYPE_SPLIT" - << std::endl); + LOG(dout_con << m_connection->getDesc() << "BUFFERED TYPE_SPLIT" << std::endl); throw ProcessedSilentlyException("Buffered a split packet chunk"); } @@ -1296,8 +1275,7 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Split(Channel *channe } SharedBuffer ConnectionReceiveThread::handlePacketType_Reliable(Channel *channel, - const SharedBuffer &packetdata, Peer *peer, u8 channelnum, - bool reliable) + const SharedBuffer &packetdata, Peer *peer, u8 channelnum, bool reliable) { assert(channel != NULL); @@ -1306,44 +1284,41 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Reliable(Channel *cha throw InvalidIncomingDataException("Found nested reliable packets"); if (packetdata.getSize() < RELIABLE_HEADER_SIZE) - throw InvalidIncomingDataException( - "packetdata.getSize() < RELIABLE_HEADER_SIZE"); + throw InvalidIncomingDataException("packetdata.getSize() < RELIABLE_HEADER_SIZE"); u16 seqnum = readU16(&packetdata[1]); bool is_future_packet = false; bool is_old_packet = false; /* packet is within our receive window send ack */ - if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(), - MAX_RELIABLE_WINDOW_SIZE)) { + if (seqnum_in_window(seqnum, + channel->readNextIncomingSeqNum(), MAX_RELIABLE_WINDOW_SIZE)) { m_connection->sendAck(peer->id, channelnum, seqnum); } else { - is_future_packet = - seqnum_higher(seqnum, channel->readNextIncomingSeqNum()); + is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum()); is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum); /* packet is not within receive window, don't send ack. * * if this was a valid packet it's gonna be retransmitted */ if (is_future_packet) - throw ProcessedSilentlyException("Received packet newer then " - "expected, not sending ack"); + throw ProcessedSilentlyException( + "Received packet newer then expected, not sending ack"); /* seems like our ack was lost, send another one for a old packet */ if (is_old_packet) { LOG(dout_con << m_connection->getDesc() - << "RE-SENDING ACK: peer_id: " << peer->id - << ", channel: " << (channelnum & 0xFF) - << ", seqnum: " << seqnum << std::endl;) + << "RE-SENDING ACK: peer_id: " << peer->id + << ", channel: " << (channelnum & 0xFF) + << ", seqnum: " << seqnum << std::endl;) m_connection->sendAck(peer->id, channelnum, seqnum); // we already have this packet so this one was on wire at least // the current timeout - // we don't know how long this packet was on wire don't do silly - // guessing dynamic_cast(&peer)-> + // we don't know how long this packet was on wire don't do silly guessing + // dynamic_cast(&peer)-> // reportRTT(dynamic_cast(&peer)->getResendTimeout()); - throw ProcessedSilentlyException( - "Retransmitting ack for old packet"); + throw ProcessedSilentlyException("Retransmitting ack for old packet"); } } @@ -1355,16 +1330,19 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Reliable(Channel *cha // This one comes later, buffer it. // Actually we have to make a packet to buffer one. // Well, we have all the ingredients, so just do it. - BufferedPacket packet = con::makePacket(peer_address, packetdata, - m_connection->GetProtocolID(), peer->id, channelnum); + BufferedPacket packet = con::makePacket( + peer_address, + packetdata, + m_connection->GetProtocolID(), + peer->id, + channelnum); try { - channel->incoming_reliables.insert( - packet, channel->readNextIncomingSeqNum()); + channel->incoming_reliables.insert(packet, channel->readNextIncomingSeqNum()); LOG(dout_con << m_connection->getDesc() - << "BUFFERING, TYPE_RELIABLE peer_id: " << peer->id - << ", channel: " << (channelnum & 0xFF) - << ", seqnum: " << seqnum << std::endl;) + << "BUFFERING, TYPE_RELIABLE peer_id: " << peer->id + << ", channel: " << (channelnum & 0xFF) + << ", seqnum: " << seqnum << std::endl;) throw ProcessedQueued("Buffered future reliable packet"); } catch (AlreadyExistsException &e) { @@ -1374,24 +1352,25 @@ SharedBuffer ConnectionReceiveThread::handlePacketType_Reliable(Channel *cha m_connection->putCommand(discon); LOG(derr_con << m_connection->getDesc() - << "INVALID, TYPE_RELIABLE peer_id: " << peer->id - << ", channel: " << (channelnum & 0xFF) - << ", seqnum: " << seqnum << "DROPPING CLIENT!" - << std::endl;) + << "INVALID, TYPE_RELIABLE peer_id: " << peer->id + << ", channel: " << (channelnum & 0xFF) + << ", seqnum: " << seqnum + << "DROPPING CLIENT!" << std::endl;) } } /* we got a packet to process right now */ - LOG(dout_con << m_connection->getDesc() << "RECURSIVE, TYPE_RELIABLE peer_id: " - << peer->id << ", channel: " << (channelnum & 0xFF) - << ", seqnum: " << seqnum << std::endl;) + LOG(dout_con << m_connection->getDesc() + << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer->id + << ", channel: " << (channelnum & 0xFF) + << ", seqnum: " << seqnum << std::endl;) + /* check for resend case */ u16 queued_seqnum = 0; if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum)) { if (queued_seqnum == seqnum) { - BufferedPacket queued_packet = - channel->incoming_reliables.popFirst(); + BufferedPacket queued_packet = channel->incoming_reliables.popFirst(); /** TODO find a way to verify the new against the old packet */ } } diff --git a/src/network/networkpacket.cpp b/src/network/networkpacket.cpp index e82dd583e..4d531b611 100644 --- a/src/network/networkpacket.cpp +++ b/src/network/networkpacket.cpp @@ -23,14 +23,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/serialize.h" #include "networkprotocol.h" -NetworkPacket::NetworkPacket(u16 command, u32 datasize, session_t peer_id) : - m_datasize(datasize), m_command(command), m_peer_id(peer_id) +NetworkPacket::NetworkPacket(u16 command, u32 datasize, session_t peer_id): +m_datasize(datasize), m_command(command), m_peer_id(peer_id) { m_data.resize(m_datasize); } -NetworkPacket::NetworkPacket(u16 command, u32 datasize) : - m_datasize(datasize), m_command(command) +NetworkPacket::NetworkPacket(u16 command, u32 datasize): +m_datasize(datasize), m_command(command) { m_data.resize(m_datasize); } @@ -44,8 +44,8 @@ void NetworkPacket::checkReadOffset(u32 from_offset, u32 field_size) { if (from_offset + field_size > m_datasize) { std::stringstream ss; - ss << "Reading outside packet (offset: " << from_offset - << ", packet size: " << getSize() << ")"; + ss << "Reading outside packet (offset: " << + from_offset << ", packet size: " << getSize() << ")"; throw PacketError(ss.str()); } } @@ -75,14 +75,14 @@ void NetworkPacket::clear() m_peer_id = 0; } -const char *NetworkPacket::getString(u32 from_offset) +const char* NetworkPacket::getString(u32 from_offset) { checkReadOffset(from_offset, 0); - return (char *)&m_data[from_offset]; + return (char*)&m_data[from_offset]; } -void NetworkPacket::putRawString(const char *src, u32 len) +void NetworkPacket::putRawString(const char* src, u32 len) { if (m_read_offset + len > m_datasize) { m_datasize = m_read_offset + len; @@ -96,7 +96,7 @@ void NetworkPacket::putRawString(const char *src, u32 len) m_read_offset += len; } -NetworkPacket &NetworkPacket::operator>>(std::string &dst) +NetworkPacket& NetworkPacket::operator>>(std::string& dst) { checkReadOffset(m_read_offset, 2); u16 strLen = readU16(&m_data[m_read_offset]); @@ -111,13 +111,13 @@ NetworkPacket &NetworkPacket::operator>>(std::string &dst) checkReadOffset(m_read_offset, strLen); dst.reserve(strLen); - dst.append((char *)&m_data[m_read_offset], strLen); + dst.append((char*)&m_data[m_read_offset], strLen); m_read_offset += strLen; return *this; } -NetworkPacket &NetworkPacket::operator<<(const std::string &src) +NetworkPacket& NetworkPacket::operator<<(const std::string &src) { if (src.size() > STRING_MAX_LEN) { throw PacketError("String too long"); @@ -145,7 +145,7 @@ void NetworkPacket::putLongString(const std::string &src) putRawString(src.c_str(), msgsize); } -NetworkPacket &NetworkPacket::operator>>(std::wstring &dst) +NetworkPacket& NetworkPacket::operator>>(std::wstring& dst) { checkReadOffset(m_read_offset, 2); u16 strLen = readU16(&m_data[m_read_offset]); @@ -160,7 +160,7 @@ NetworkPacket &NetworkPacket::operator>>(std::wstring &dst) checkReadOffset(m_read_offset, strLen * 2); dst.reserve(strLen); - for (u16 i = 0; i < strLen; i++) { + for(u16 i=0; i>(std::wstring &dst) return *this; } -NetworkPacket &NetworkPacket::operator<<(const std::wstring &src) +NetworkPacket& NetworkPacket::operator<<(const std::wstring &src) { if (src.size() > WIDE_STRING_MAX_LEN) { throw PacketError("String too long"); @@ -180,8 +180,8 @@ NetworkPacket &NetworkPacket::operator<<(const std::wstring &src) *this << msgsize; // Write string - for (u16 i = 0; i < msgsize; i++) { - *this << (u16)src[i]; + for (u16 i=0; i>(char &dst) +NetworkPacket& NetworkPacket::operator>>(char& dst) { checkReadOffset(m_read_offset, 1); @@ -230,7 +230,7 @@ char NetworkPacket::getChar(u32 offset) return readU8(&m_data[offset]); } -NetworkPacket &NetworkPacket::operator<<(char src) +NetworkPacket& NetworkPacket::operator<<(char src) { checkDataSize(1); @@ -240,7 +240,7 @@ NetworkPacket &NetworkPacket::operator<<(char src) return *this; } -NetworkPacket &NetworkPacket::operator<<(u8 src) +NetworkPacket& NetworkPacket::operator<<(u8 src) { checkDataSize(1); @@ -250,7 +250,7 @@ NetworkPacket &NetworkPacket::operator<<(u8 src) return *this; } -NetworkPacket &NetworkPacket::operator<<(bool src) +NetworkPacket& NetworkPacket::operator<<(bool src) { checkDataSize(1); @@ -260,7 +260,7 @@ NetworkPacket &NetworkPacket::operator<<(bool src) return *this; } -NetworkPacket &NetworkPacket::operator<<(u16 src) +NetworkPacket& NetworkPacket::operator<<(u16 src) { checkDataSize(2); @@ -270,7 +270,7 @@ NetworkPacket &NetworkPacket::operator<<(u16 src) return *this; } -NetworkPacket &NetworkPacket::operator<<(u32 src) +NetworkPacket& NetworkPacket::operator<<(u32 src) { checkDataSize(4); @@ -280,7 +280,7 @@ NetworkPacket &NetworkPacket::operator<<(u32 src) return *this; } -NetworkPacket &NetworkPacket::operator<<(u64 src) +NetworkPacket& NetworkPacket::operator<<(u64 src) { checkDataSize(8); @@ -290,7 +290,7 @@ NetworkPacket &NetworkPacket::operator<<(u64 src) return *this; } -NetworkPacket &NetworkPacket::operator<<(float src) +NetworkPacket& NetworkPacket::operator<<(float src) { checkDataSize(4); @@ -300,7 +300,7 @@ NetworkPacket &NetworkPacket::operator<<(float src) return *this; } -NetworkPacket &NetworkPacket::operator>>(bool &dst) +NetworkPacket& NetworkPacket::operator>>(bool& dst) { checkReadOffset(m_read_offset, 1); @@ -310,7 +310,7 @@ NetworkPacket &NetworkPacket::operator>>(bool &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(u8 &dst) +NetworkPacket& NetworkPacket::operator>>(u8& dst) { checkReadOffset(m_read_offset, 1); @@ -327,7 +327,7 @@ u8 NetworkPacket::getU8(u32 offset) return readU8(&m_data[offset]); } -u8 *NetworkPacket::getU8Ptr(u32 from_offset) +u8* NetworkPacket::getU8Ptr(u32 from_offset) { if (m_datasize == 0) { return NULL; @@ -335,10 +335,10 @@ u8 *NetworkPacket::getU8Ptr(u32 from_offset) checkReadOffset(from_offset, 1); - return (u8 *)&m_data[from_offset]; + return (u8*)&m_data[from_offset]; } -NetworkPacket &NetworkPacket::operator>>(u16 &dst) +NetworkPacket& NetworkPacket::operator>>(u16& dst) { checkReadOffset(m_read_offset, 2); @@ -355,7 +355,7 @@ u16 NetworkPacket::getU16(u32 from_offset) return readU16(&m_data[from_offset]); } -NetworkPacket &NetworkPacket::operator>>(u32 &dst) +NetworkPacket& NetworkPacket::operator>>(u32& dst) { checkReadOffset(m_read_offset, 4); @@ -365,7 +365,7 @@ NetworkPacket &NetworkPacket::operator>>(u32 &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(u64 &dst) +NetworkPacket& NetworkPacket::operator>>(u64& dst) { checkReadOffset(m_read_offset, 8); @@ -375,7 +375,7 @@ NetworkPacket &NetworkPacket::operator>>(u64 &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(float &dst) +NetworkPacket& NetworkPacket::operator>>(float& dst) { checkReadOffset(m_read_offset, 4); @@ -385,7 +385,7 @@ NetworkPacket &NetworkPacket::operator>>(float &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(v2f &dst) +NetworkPacket& NetworkPacket::operator>>(v2f& dst) { checkReadOffset(m_read_offset, 8); @@ -395,7 +395,7 @@ NetworkPacket &NetworkPacket::operator>>(v2f &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(v3f &dst) +NetworkPacket& NetworkPacket::operator>>(v3f& dst) { checkReadOffset(m_read_offset, 12); @@ -405,7 +405,7 @@ NetworkPacket &NetworkPacket::operator>>(v3f &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(s16 &dst) +NetworkPacket& NetworkPacket::operator>>(s16& dst) { checkReadOffset(m_read_offset, 2); @@ -415,13 +415,13 @@ NetworkPacket &NetworkPacket::operator>>(s16 &dst) return *this; } -NetworkPacket &NetworkPacket::operator<<(s16 src) +NetworkPacket& NetworkPacket::operator<<(s16 src) { - *this << (u16)src; + *this << (u16) src; return *this; } -NetworkPacket &NetworkPacket::operator>>(s32 &dst) +NetworkPacket& NetworkPacket::operator>>(s32& dst) { checkReadOffset(m_read_offset, 4); @@ -431,13 +431,13 @@ NetworkPacket &NetworkPacket::operator>>(s32 &dst) return *this; } -NetworkPacket &NetworkPacket::operator<<(s32 src) +NetworkPacket& NetworkPacket::operator<<(s32 src) { - *this << (u32)src; + *this << (u32) src; return *this; } -NetworkPacket &NetworkPacket::operator>>(v3s16 &dst) +NetworkPacket& NetworkPacket::operator>>(v3s16& dst) { checkReadOffset(m_read_offset, 6); @@ -447,7 +447,7 @@ NetworkPacket &NetworkPacket::operator>>(v3s16 &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(v2s32 &dst) +NetworkPacket& NetworkPacket::operator>>(v2s32& dst) { checkReadOffset(m_read_offset, 8); @@ -457,7 +457,7 @@ NetworkPacket &NetworkPacket::operator>>(v2s32 &dst) return *this; } -NetworkPacket &NetworkPacket::operator>>(v3s32 &dst) +NetworkPacket& NetworkPacket::operator>>(v3s32& dst) { checkReadOffset(m_read_offset, 12); @@ -467,45 +467,45 @@ NetworkPacket &NetworkPacket::operator>>(v3s32 &dst) return *this; } -NetworkPacket &NetworkPacket::operator<<(v2f src) +NetworkPacket& NetworkPacket::operator<<(v2f src) { - *this << (float)src.X; - *this << (float)src.Y; + *this << (float) src.X; + *this << (float) src.Y; return *this; } -NetworkPacket &NetworkPacket::operator<<(v3f src) +NetworkPacket& NetworkPacket::operator<<(v3f src) { - *this << (float)src.X; - *this << (float)src.Y; - *this << (float)src.Z; + *this << (float) src.X; + *this << (float) src.Y; + *this << (float) src.Z; return *this; } -NetworkPacket &NetworkPacket::operator<<(v3s16 src) +NetworkPacket& NetworkPacket::operator<<(v3s16 src) { - *this << (s16)src.X; - *this << (s16)src.Y; - *this << (s16)src.Z; + *this << (s16) src.X; + *this << (s16) src.Y; + *this << (s16) src.Z; return *this; } -NetworkPacket &NetworkPacket::operator<<(v2s32 src) +NetworkPacket& NetworkPacket::operator<<(v2s32 src) { - *this << (s32)src.X; - *this << (s32)src.Y; + *this << (s32) src.X; + *this << (s32) src.Y; return *this; } -NetworkPacket &NetworkPacket::operator<<(v3s32 src) +NetworkPacket& NetworkPacket::operator<<(v3s32 src) { - *this << (s32)src.X; - *this << (s32)src.Y; - *this << (s32)src.Z; + *this << (s32) src.X; + *this << (s32) src.Y; + *this << (s32) src.Z; return *this; } -NetworkPacket &NetworkPacket::operator>>(video::SColor &dst) +NetworkPacket& NetworkPacket::operator>>(video::SColor& dst) { checkReadOffset(m_read_offset, 4); @@ -515,7 +515,7 @@ NetworkPacket &NetworkPacket::operator>>(video::SColor &dst) return *this; } -NetworkPacket &NetworkPacket::operator<<(video::SColor src) +NetworkPacket& NetworkPacket::operator<<(video::SColor src) { checkDataSize(4); @@ -530,7 +530,7 @@ SharedBuffer NetworkPacket::oldForgePacket() SharedBuffer sb(m_datasize + 2); writeU16(&sb[0], m_command); - u8 *datas = getU8Ptr(0); + u8* datas = getU8Ptr(0); if (datas != NULL) memcpy(&sb[2], datas, m_datasize); diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h index c6b3d43d0..e57a7a794 100644 --- a/src/network/networkprotocol.h +++ b/src/network/networkprotocol.h @@ -127,8 +127,9 @@ with this program; if not, write to the Free Software Foundation, Inc., TOSERVER_SRP_BYTES_M, TOCLIENT_SRP_BYTES_S_B for the three supported auth mechanisms around srp Add new opcodes TOCLIENT_ACCEPT_SUDO_MODE and TOCLIENT_DENY_SUDO_MODE - for sudo mode handling (auth mech generic way of changing - password). Add TOCLIENT_HELLO for presenting server to client after client presentation + for sudo mode handling (auth mech generic way of changing password). + Add TOCLIENT_HELLO for presenting server to client after client + presentation Add TOCLIENT_AUTH_ACCEPT to accept connection from client Rename GENERIC_CMD_SET_ATTACHMENT to AO_CMD_ATTACH_TO PROTOCOL_VERSION 26: @@ -160,14 +161,14 @@ with this program; if not, write to the Free Software Foundation, Inc., PROTOCOL VERSION 34: Add sound pitch PROTOCOL VERSION 35: - Rename TOCLIENT_CHAT_MESSAGE to TOCLIENT_CHAT_MESSAGE_OLD (0x30) - Add TOCLIENT_CHAT_MESSAGE (0x2F) - This chat message is a signalisation message containing various + Rename TOCLIENT_CHAT_MESSAGE to TOCLIENT_CHAT_MESSAGE_OLD (0x30) + Add TOCLIENT_CHAT_MESSAGE (0x2F) + This chat message is a signalisation message containing various informations: - * timestamp - * sender - * type (RAW, NORMAL, ANNOUNCE, SYSTEM) - * content + * timestamp + * sender + * type (RAW, NORMAL, ANNOUNCE, SYSTEM) + * content Add TOCLIENT_CSM_RESTRICTION_FLAGS to define which CSM features should be limited Add settable player collisionbox. Breaks compatibility with older @@ -221,9 +222,8 @@ with this program; if not, write to the Free Software Foundation, Inc., // Constant that differentiates the protocol from random data and other protocols #define PROTOCOL_ID 0x4f457403 -#define PASSWORD_SIZE \ - 28 // Maximum password length. Allows for - // base64-encoded SHA-1 (27+\0). +#define PASSWORD_SIZE 28 // Maximum password length. Allows for + // base64-encoded SHA-1 (27+\0). /* Changes by FORMSPEC_API_VERSION: @@ -243,8 +243,7 @@ with this program; if not, write to the Free Software Foundation, Inc., */ #define FORMSPEC_API_VERSION 4 -#define TEXTURENAME_ALLOWED_CHARS \ - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-" +#define TEXTURENAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-" typedef u16 session_t; @@ -258,8 +257,7 @@ enum ToClientCommand u16 deployed network compression mode u16 deployed protocol version u32 supported auth methods - std::string username that should be used for legacy hash (for proper - casing) + std::string username that should be used for legacy hash (for proper casing) */ TOCLIENT_AUTH_ACCEPT = 0x03, /* @@ -288,7 +286,7 @@ enum ToClientCommand TOCLIENT_INIT_LEGACY = 0x10, // Obsolete - TOCLIENT_BLOCKDATA = 0x20, // TODO: Multiple blocks + TOCLIENT_BLOCKDATA = 0x20, //TODO: Multiple blocks TOCLIENT_ADDNODE = 0x21, /* v3s16 position @@ -297,10 +295,10 @@ enum ToClientCommand */ TOCLIENT_REMOVENODE = 0x22, - TOCLIENT_PLAYERPOS = 0x23, // Obsolete - TOCLIENT_PLAYERINFO = 0x24, // Obsolete + TOCLIENT_PLAYERPOS = 0x23, // Obsolete + TOCLIENT_PLAYERINFO = 0x24, // Obsolete TOCLIENT_OPT_BLOCK_NOT_FOUND = 0x25, // Obsolete - TOCLIENT_SECTORMETA = 0x26, // Obsolete + TOCLIENT_SECTORMETA = 0x26, // Obsolete TOCLIENT_INVENTORY = 0x27, /* @@ -698,8 +696,8 @@ enum ToClientCommand */ TOCLIENT_UPDATE_PLAYER_LIST = 0x56, /* - u8 type - u16 number of players + u8 type + u16 number of players for each player u16 len u8[len] player name @@ -708,18 +706,18 @@ enum ToClientCommand TOCLIENT_MODCHANNEL_MSG = 0x57, /* u16 channel name length - std::string channel name - u16 channel name sender - std::string channel name - u16 message length - std::string message + std::string channel name + u16 channel name sender + std::string channel name + u16 message length + std::string message */ TOCLIENT_MODCHANNEL_SIGNAL = 0x58, /* u8 signal id - u16 channel name length - std::string channel name + u16 channel name length + std::string channel name */ TOCLIENT_NODEMETA_CHANGED = 0x59, @@ -795,25 +793,25 @@ enum ToServerCommand TOSERVER_MODCHANNEL_JOIN = 0x17, /* u16 channel name length - std::string channel name + std::string channel name */ TOSERVER_MODCHANNEL_LEAVE = 0x18, /* u16 channel name length - std::string channel name + std::string channel name */ TOSERVER_MODCHANNEL_MSG = 0x19, /* u16 channel name length - std::string channel name - u16 message length - std::string message + std::string channel name + u16 message length + std::string message */ - TOSERVER_GETBLOCK = 0x20, // Obsolete - TOSERVER_ADDNODE = 0x21, // Obsolete + TOSERVER_GETBLOCK = 0x20, // Obsolete + TOSERVER_ADDNODE = 0x21, // Obsolete TOSERVER_REMOVENODE = 0x22, // Obsolete TOSERVER_PLAYERPOS = 0x23, @@ -847,10 +845,10 @@ enum ToServerCommand */ TOSERVER_ADDNODE_FROM_INVENTORY = 0x26, // Obsolete - TOSERVER_CLICK_OBJECT = 0x27, // Obsolete - TOSERVER_GROUND_ACTION = 0x28, // Obsolete - TOSERVER_RELEASE = 0x29, // Obsolete - TOSERVER_SIGNTEXT = 0x30, // Obsolete + TOSERVER_CLICK_OBJECT = 0x27, // Obsolete + TOSERVER_GROUND_ACTION = 0x28, // Obsolete + TOSERVER_RELEASE = 0x29, // Obsolete + TOSERVER_SIGNTEXT = 0x30, // Obsolete TOSERVER_INVENTORY_ACTION = 0x31, /* @@ -863,7 +861,7 @@ enum ToServerCommand wstring message */ - TOSERVER_SIGNNODETEXT = 0x33, // Obsolete + TOSERVER_SIGNNODETEXT = 0x33, // Obsolete TOSERVER_CLICK_ACTIVEOBJECT = 0x34, // Obsolete TOSERVER_DAMAGE = 0x35, @@ -942,7 +940,7 @@ enum ToServerCommand */ TOSERVER_RECEIVED_MEDIA = 0x41, // Obsolete - TOSERVER_BREATH = 0x42, // Obsolete + TOSERVER_BREATH = 0x42, // Obsolete TOSERVER_CLIENT_READY = 0x43, /* @@ -970,8 +968,8 @@ enum ToServerCommand std::string bytes_A u8 current_login_based_on : on which version of the password's - hash this login is based on (0 legacy hash, - or 1 directly the password) + hash this login is based on (0 legacy hash, + or 1 directly the password) */ TOSERVER_SRP_BYTES_M = 0x52, @@ -999,8 +997,7 @@ enum AuthMechanism AUTH_MECHANISM_FIRST_SRP = 1 << 2, }; -enum AccessDeniedCode -{ +enum AccessDeniedCode { SERVER_ACCESSDENIED_WRONG_PASSWORD, SERVER_ACCESSDENIED_UNEXPECTED_DATA, SERVER_ACCESSDENIED_SINGLEPLAYER, @@ -1017,58 +1014,54 @@ enum AccessDeniedCode SERVER_ACCESSDENIED_MAX, }; -enum NetProtoCompressionMode -{ +enum NetProtoCompressionMode { NETPROTO_COMPRESSION_NONE = 0, }; const static std::string accessDeniedStrings[SERVER_ACCESSDENIED_MAX] = { - "Invalid password", - "Your client sent something the server didn't expect. Try reconnecting " - "or updating your client", - "The server is running in simple singleplayer mode. You cannot connect.", - "Your client's version is not supported.\nPlease contact server " - "administrator.", - "Player name contains disallowed characters.", "Player name not allowed.", - "Too many users.", - "Empty passwords are disallowed. Set a password and try again.", - "Another client is connected with this name. If your client closed " - "unexpectedly, try again in a minute.", - "Server authentication failed. This is likely a server error.", "", - "Server shutting down.", - "This server has experienced an internal error. You will now be " - "disconnected."}; - -enum PlayerListModifer : u8 + "Invalid password", + "Your client sent something the server didn't expect. Try reconnecting or updating your client", + "The server is running in simple singleplayer mode. You cannot connect.", + "Your client's version is not supported.\nPlease contact server administrator.", + "Player name contains disallowed characters.", + "Player name not allowed.", + "Too many users.", + "Empty passwords are disallowed. Set a password and try again.", + "Another client is connected with this name. If your client closed unexpectedly, try again in a minute.", + "Server authentication failed. This is likely a server error.", + "", + "Server shutting down.", + "This server has experienced an internal error. You will now be disconnected." +}; + +enum PlayerListModifer: u8 { PLAYER_LIST_INIT, PLAYER_LIST_ADD, PLAYER_LIST_REMOVE, }; -enum CSMRestrictionFlags : u64 -{ +enum CSMRestrictionFlags : u64 { CSM_RF_NONE = 0x00000000, // Until server-sent CSM and verifying of builtin are complete, // 'CSM_RF_LOAD_CLIENT_MODS' also disables loading 'builtin'. // When those are complete, this should return to only being a restriction on the // loading of client mods. - CSM_RF_LOAD_CLIENT_MODS = - 0x00000001, // Don't load client-provided mods or 'builtin' - CSM_RF_CHAT_MESSAGES = 0x00000002, // Disable chat message sending from CSM - CSM_RF_READ_ITEMDEFS = 0x00000004, // Disable itemdef lookups - CSM_RF_READ_NODEDEFS = 0x00000008, // Disable nodedef lookups - CSM_RF_LOOKUP_NODES = 0x00000010, // Limit node lookups - CSM_RF_READ_PLAYERINFO = 0x00000020, // Disable player info lookups + CSM_RF_LOAD_CLIENT_MODS = 0x00000001, // Don't load client-provided mods or 'builtin' + CSM_RF_CHAT_MESSAGES = 0x00000002, // Disable chat message sending from CSM + CSM_RF_READ_ITEMDEFS = 0x00000004, // Disable itemdef lookups + CSM_RF_READ_NODEDEFS = 0x00000008, // Disable nodedef lookups + CSM_RF_LOOKUP_NODES = 0x00000010, // Limit node lookups + CSM_RF_READ_PLAYERINFO = 0x00000020, // Disable player info lookups CSM_RF_ALL = 0xFFFFFFFF, }; enum InteractAction : u8 { - INTERACT_START_DIGGING, // 0: start digging (from undersurface) or use - INTERACT_STOP_DIGGING, // 1: stop digging (all parameters ignored) + INTERACT_START_DIGGING, // 0: start digging (from undersurface) or use + INTERACT_STOP_DIGGING, // 1: stop digging (all parameters ignored) INTERACT_DIGGING_COMPLETED, // 2: digging completed - INTERACT_PLACE, // 3: place block or item (to abovesurface) - INTERACT_USE, // 4: use item - INTERACT_ACTIVATE // 5: rightclick air ("activate") + INTERACT_PLACE, // 3: place block or item (to abovesurface) + INTERACT_USE, // 4: use item + INTERACT_ACTIVATE // 5: rightclick air ("activate") }; diff --git a/src/network/serveropcodes.cpp b/src/network/serveropcodes.cpp index ecfac0fcd..2fc3197c2 100644 --- a/src/network/serveropcodes.cpp +++ b/src/network/serveropcodes.cpp @@ -20,118 +20,96 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serveropcodes.h" -const static ToServerCommandHandler null_command_handler = { - "TOSERVER_NULL", TOSERVER_STATE_ALL, &Server::handleCommand_Null}; +const static ToServerCommandHandler null_command_handler = { "TOSERVER_NULL", TOSERVER_STATE_ALL, &Server::handleCommand_Null }; -const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES] = { - null_command_handler, // 0x00 (never use this) - null_command_handler, // 0x01 - {"TOSERVER_INIT", TOSERVER_STATE_NOT_CONNECTED, - &Server::handleCommand_Init}, // 0x02 - null_command_handler, // 0x03 - null_command_handler, // 0x04 - null_command_handler, // 0x05 - null_command_handler, // 0x06 - null_command_handler, // 0x07 - null_command_handler, // 0x08 - null_command_handler, // 0x09 - null_command_handler, // 0x0a - null_command_handler, // 0x0b - null_command_handler, // 0x0c - null_command_handler, // 0x0d - null_command_handler, // 0x0e - null_command_handler, // 0x0f - null_command_handler, // 0x10 - {"TOSERVER_INIT2", TOSERVER_STATE_NOT_CONNECTED, - &Server::handleCommand_Init2}, // 0x11 - null_command_handler, // 0x12 - null_command_handler, // 0x13 - null_command_handler, // 0x14 - null_command_handler, // 0x15 - null_command_handler, // 0x16 - {"TOSERVER_MODCHANNEL_JOIN", TOSERVER_STATE_INGAME, - &Server::handleCommand_ModChannelJoin}, // 0x17 - {"TOSERVER_MODCHANNEL_LEAVE", TOSERVER_STATE_INGAME, - &Server::handleCommand_ModChannelLeave}, // 0x18 - {"TOSERVER_MODCHANNEL_MSG", TOSERVER_STATE_INGAME, - &Server::handleCommand_ModChannelMsg}, // 0x19 - null_command_handler, // 0x1a - null_command_handler, // 0x1b - null_command_handler, // 0x1c - null_command_handler, // 0x1d - null_command_handler, // 0x1e - null_command_handler, // 0x1f - null_command_handler, // 0x20 - null_command_handler, // 0x21 - null_command_handler, // 0x22 - {"TOSERVER_PLAYERPOS", TOSERVER_STATE_INGAME, - &Server::handleCommand_PlayerPos}, // 0x23 - {"TOSERVER_GOTBLOCKS", TOSERVER_STATE_STARTUP, - &Server::handleCommand_GotBlocks}, // 0x24 - {"TOSERVER_DELETEDBLOCKS", TOSERVER_STATE_INGAME, - &Server::handleCommand_DeletedBlocks}, // 0x25 - null_command_handler, // 0x26 - null_command_handler, // 0x27 - null_command_handler, // 0x28 - null_command_handler, // 0x29 - null_command_handler, // 0x2a - null_command_handler, // 0x2b - null_command_handler, // 0x2c - null_command_handler, // 0x2d - null_command_handler, // 0x2e - null_command_handler, // 0x2f - null_command_handler, // 0x30 - {"TOSERVER_INVENTORY_ACTION", TOSERVER_STATE_INGAME, - &Server::handleCommand_InventoryAction}, // 0x31 - {"TOSERVER_CHAT_MESSAGE", TOSERVER_STATE_INGAME, - &Server::handleCommand_ChatMessage}, // 0x32 - null_command_handler, // 0x33 - null_command_handler, // 0x34 - {"TOSERVER_DAMAGE", TOSERVER_STATE_INGAME, - &Server::handleCommand_Damage}, // 0x35 - null_command_handler, // 0x36 - {"TOSERVER_PLAYERITEM", TOSERVER_STATE_INGAME, - &Server::handleCommand_PlayerItem}, // 0x37 - {"TOSERVER_RESPAWN", TOSERVER_STATE_INGAME, - &Server::handleCommand_Respawn}, // 0x38 - {"TOSERVER_INTERACT", TOSERVER_STATE_INGAME, - &Server::handleCommand_Interact}, // 0x39 - {"TOSERVER_REMOVED_SOUNDS", TOSERVER_STATE_INGAME, - &Server::handleCommand_RemovedSounds}, // 0x3a - {"TOSERVER_NODEMETA_FIELDS", TOSERVER_STATE_INGAME, - &Server::handleCommand_NodeMetaFields}, // 0x3b - {"TOSERVER_INVENTORY_FIELDS", TOSERVER_STATE_INGAME, - &Server::handleCommand_InventoryFields}, // 0x3c - null_command_handler, // 0x3d - null_command_handler, // 0x3e - null_command_handler, // 0x3f - {"TOSERVER_REQUEST_MEDIA", TOSERVER_STATE_STARTUP, - &Server::handleCommand_RequestMedia}, // 0x40 - null_command_handler, // 0x41 - null_command_handler, // 0x42 - {"TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP, - &Server::handleCommand_ClientReady}, // 0x43 - null_command_handler, // 0x44 - null_command_handler, // 0x45 - null_command_handler, // 0x46 - null_command_handler, // 0x47 - null_command_handler, // 0x48 - null_command_handler, // 0x49 - null_command_handler, // 0x4a - null_command_handler, // 0x4b - null_command_handler, // 0x4c - null_command_handler, // 0x4d - null_command_handler, // 0x4e - null_command_handler, // 0x4f - {"TOSERVER_FIRST_SRP", TOSERVER_STATE_NOT_CONNECTED, - &Server::handleCommand_FirstSrp}, // 0x50 - {"TOSERVER_SRP_BYTES_A", TOSERVER_STATE_NOT_CONNECTED, - &Server::handleCommand_SrpBytesA}, // 0x51 - {"TOSERVER_SRP_BYTES_M", TOSERVER_STATE_NOT_CONNECTED, - &Server::handleCommand_SrpBytesM}, // 0x52 +const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES] = +{ + null_command_handler, // 0x00 (never use this) + null_command_handler, // 0x01 + { "TOSERVER_INIT", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_Init }, // 0x02 + null_command_handler, // 0x03 + null_command_handler, // 0x04 + null_command_handler, // 0x05 + null_command_handler, // 0x06 + null_command_handler, // 0x07 + null_command_handler, // 0x08 + null_command_handler, // 0x09 + null_command_handler, // 0x0a + null_command_handler, // 0x0b + null_command_handler, // 0x0c + null_command_handler, // 0x0d + null_command_handler, // 0x0e + null_command_handler, // 0x0f + null_command_handler, // 0x10 + { "TOSERVER_INIT2", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_Init2 }, // 0x11 + null_command_handler, // 0x12 + null_command_handler, // 0x13 + null_command_handler, // 0x14 + null_command_handler, // 0x15 + null_command_handler, // 0x16 + { "TOSERVER_MODCHANNEL_JOIN", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelJoin }, // 0x17 + { "TOSERVER_MODCHANNEL_LEAVE", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelLeave }, // 0x18 + { "TOSERVER_MODCHANNEL_MSG", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelMsg }, // 0x19 + null_command_handler, // 0x1a + null_command_handler, // 0x1b + null_command_handler, // 0x1c + null_command_handler, // 0x1d + null_command_handler, // 0x1e + null_command_handler, // 0x1f + null_command_handler, // 0x20 + null_command_handler, // 0x21 + null_command_handler, // 0x22 + { "TOSERVER_PLAYERPOS", TOSERVER_STATE_INGAME, &Server::handleCommand_PlayerPos }, // 0x23 + { "TOSERVER_GOTBLOCKS", TOSERVER_STATE_STARTUP, &Server::handleCommand_GotBlocks }, // 0x24 + { "TOSERVER_DELETEDBLOCKS", TOSERVER_STATE_INGAME, &Server::handleCommand_DeletedBlocks }, // 0x25 + null_command_handler, // 0x26 + null_command_handler, // 0x27 + null_command_handler, // 0x28 + null_command_handler, // 0x29 + null_command_handler, // 0x2a + null_command_handler, // 0x2b + null_command_handler, // 0x2c + null_command_handler, // 0x2d + null_command_handler, // 0x2e + null_command_handler, // 0x2f + null_command_handler, // 0x30 + { "TOSERVER_INVENTORY_ACTION", TOSERVER_STATE_INGAME, &Server::handleCommand_InventoryAction }, // 0x31 + { "TOSERVER_CHAT_MESSAGE", TOSERVER_STATE_INGAME, &Server::handleCommand_ChatMessage }, // 0x32 + null_command_handler, // 0x33 + null_command_handler, // 0x34 + { "TOSERVER_DAMAGE", TOSERVER_STATE_INGAME, &Server::handleCommand_Damage }, // 0x35 + null_command_handler, // 0x36 + { "TOSERVER_PLAYERITEM", TOSERVER_STATE_INGAME, &Server::handleCommand_PlayerItem }, // 0x37 + { "TOSERVER_RESPAWN", TOSERVER_STATE_INGAME, &Server::handleCommand_Respawn }, // 0x38 + { "TOSERVER_INTERACT", TOSERVER_STATE_INGAME, &Server::handleCommand_Interact }, // 0x39 + { "TOSERVER_REMOVED_SOUNDS", TOSERVER_STATE_INGAME, &Server::handleCommand_RemovedSounds }, // 0x3a + { "TOSERVER_NODEMETA_FIELDS", TOSERVER_STATE_INGAME, &Server::handleCommand_NodeMetaFields }, // 0x3b + { "TOSERVER_INVENTORY_FIELDS", TOSERVER_STATE_INGAME, &Server::handleCommand_InventoryFields }, // 0x3c + null_command_handler, // 0x3d + null_command_handler, // 0x3e + null_command_handler, // 0x3f + { "TOSERVER_REQUEST_MEDIA", TOSERVER_STATE_STARTUP, &Server::handleCommand_RequestMedia }, // 0x40 + null_command_handler, // 0x41 + null_command_handler, // 0x42 + { "TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP, &Server::handleCommand_ClientReady }, // 0x43 + null_command_handler, // 0x44 + null_command_handler, // 0x45 + null_command_handler, // 0x46 + null_command_handler, // 0x47 + null_command_handler, // 0x48 + null_command_handler, // 0x49 + null_command_handler, // 0x4a + null_command_handler, // 0x4b + null_command_handler, // 0x4c + null_command_handler, // 0x4d + null_command_handler, // 0x4e + null_command_handler, // 0x4f + { "TOSERVER_FIRST_SRP", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_FirstSrp }, // 0x50 + { "TOSERVER_SRP_BYTES_A", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_SrpBytesA }, // 0x51 + { "TOSERVER_SRP_BYTES_M", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_SrpBytesM }, // 0x52 }; -const static ClientCommandFactory null_command_factory = {"TOCLIENT_NULL", 0, false}; +const static ClientCommandFactory null_command_factory = { "TOCLIENT_NULL", 0, false }; /* Channels used for Server -> Client communication @@ -143,104 +121,104 @@ const static ClientCommandFactory null_command_factory = {"TOCLIENT_NULL", 0, fa the same objects are *required* to be in the same channel. */ -const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] = { - null_command_factory, // 0x00 - null_command_factory, // 0x01 - {"TOCLIENT_HELLO", 0, true}, // 0x02 - {"TOCLIENT_AUTH_ACCEPT", 0, true}, // 0x03 - {"TOCLIENT_ACCEPT_SUDO_MODE", 0, true}, // 0x04 - {"TOCLIENT_DENY_SUDO_MODE", 0, true}, // 0x05 - null_command_factory, // 0x06 - null_command_factory, // 0x07 - null_command_factory, // 0x08 - null_command_factory, // 0x09 - {"TOCLIENT_ACCESS_DENIED", 0, true}, // 0x0A - null_command_factory, // 0x0B - null_command_factory, // 0x0C - null_command_factory, // 0x0D - null_command_factory, // 0x0E - null_command_factory, // 0x0F - {"TOCLIENT_INIT", 0, true}, // 0x10 - null_command_factory, // 0x11 - null_command_factory, // 0x12 - null_command_factory, // 0x13 - null_command_factory, // 0x14 - null_command_factory, // 0x15 - null_command_factory, // 0x16 - null_command_factory, // 0x17 - null_command_factory, // 0x18 - null_command_factory, // 0x19 - null_command_factory, // 0x1A - null_command_factory, // 0x1B - null_command_factory, // 0x1C - null_command_factory, // 0x1D - null_command_factory, // 0x1E - null_command_factory, // 0x1F - {"TOCLIENT_BLOCKDATA", 2, true}, // 0x20 - {"TOCLIENT_ADDNODE", 0, true}, // 0x21 - {"TOCLIENT_REMOVENODE", 0, true}, // 0x22 - null_command_factory, // 0x23 - null_command_factory, // 0x24 - null_command_factory, // 0x25 - null_command_factory, // 0x26 - {"TOCLIENT_INVENTORY", 0, true}, // 0x27 - null_command_factory, // 0x28 - {"TOCLIENT_TIME_OF_DAY", 0, true}, // 0x29 - {"TOCLIENT_CSM_RESTRICTION_FLAGS", 0, true}, // 0x2A - {"TOCLIENT_PLAYER_SPEED", 0, true}, // 0x2B - {"TOCLIENT_MEDIA_PUSH", 0, true}, // 0x2C (sent over channel 1 too) - null_command_factory, // 0x2D - null_command_factory, // 0x2E - {"TOCLIENT_CHAT_MESSAGE", 0, true}, // 0x2F - null_command_factory, // 0x30 - {"TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", 0, true}, // 0x31 - {"TOCLIENT_ACTIVE_OBJECT_MESSAGES", 0, - true}, // 0x32 (may be sent as unrel over channel 1 too) - {"TOCLIENT_HP", 0, true}, // 0x33 - {"TOCLIENT_MOVE_PLAYER", 0, true}, // 0x34 - {"TOCLIENT_ACCESS_DENIED_LEGACY", 0, true}, // 0x35 - {"TOCLIENT_FOV", 0, true}, // 0x36 - {"TOCLIENT_DEATHSCREEN", 0, true}, // 0x37 - {"TOCLIENT_MEDIA", 2, true}, // 0x38 - null_command_factory, // 0x39 - {"TOCLIENT_NODEDEF", 0, true}, // 0x3A - null_command_factory, // 0x3B - {"TOCLIENT_ANNOUNCE_MEDIA", 0, true}, // 0x3C - {"TOCLIENT_ITEMDEF", 0, true}, // 0x3D - null_command_factory, // 0x3E - {"TOCLIENT_PLAY_SOUND", 0, true}, // 0x3f (may be sent as unrel too) - {"TOCLIENT_STOP_SOUND", 0, true}, // 0x40 - {"TOCLIENT_PRIVILEGES", 0, true}, // 0x41 - {"TOCLIENT_INVENTORY_FORMSPEC", 0, true}, // 0x42 - {"TOCLIENT_DETACHED_INVENTORY", 0, true}, // 0x43 - {"TOCLIENT_SHOW_FORMSPEC", 0, true}, // 0x44 - {"TOCLIENT_MOVEMENT", 0, true}, // 0x45 - {"TOCLIENT_SPAWN_PARTICLE", 0, true}, // 0x46 - {"TOCLIENT_ADD_PARTICLESPAWNER", 0, true}, // 0x47 - null_command_factory, // 0x48 - {"TOCLIENT_HUDADD", 1, true}, // 0x49 - {"TOCLIENT_HUDRM", 1, true}, // 0x4a - {"TOCLIENT_HUDCHANGE", 1, true}, // 0x4b - {"TOCLIENT_HUD_SET_FLAGS", 1, true}, // 0x4c - {"TOCLIENT_HUD_SET_PARAM", 1, true}, // 0x4d - {"TOCLIENT_BREATH", 0, true}, // 0x4e - {"TOCLIENT_SET_SKY", 0, true}, // 0x4f - {"TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", 0, true}, // 0x50 - {"TOCLIENT_LOCAL_PLAYER_ANIMATIONS", 0, true}, // 0x51 - {"TOCLIENT_EYE_OFFSET", 0, true}, // 0x52 - {"TOCLIENT_DELETE_PARTICLESPAWNER", 0, true}, // 0x53 - {"TOCLIENT_CLOUD_PARAMS", 0, true}, // 0x54 - {"TOCLIENT_FADE_SOUND", 0, true}, // 0x55 - {"TOCLIENT_UPDATE_PLAYER_LIST", 0, true}, // 0x56 - {"TOCLIENT_MODCHANNEL_MSG", 0, true}, // 0x57 - {"TOCLIENT_MODCHANNEL_SIGNAL", 0, true}, // 0x58 - {"TOCLIENT_NODEMETA_CHANGED", 0, true}, // 0x59 - {"TOCLIENT_SET_SUN", 0, true}, // 0x5a - {"TOCLIENT_SET_MOON", 0, true}, // 0x5b - {"TOCLIENT_SET_STARS", 0, true}, // 0x5c - null_command_factory, // 0x5d - null_command_factory, // 0x5e - null_command_factory, // 0x5f - {"TOSERVER_SRP_BYTES_S_B", 0, true}, // 0x60 - {"TOCLIENT_FORMSPEC_PREPEND", 0, true}, // 0x61 +const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] = +{ + null_command_factory, // 0x00 + null_command_factory, // 0x01 + { "TOCLIENT_HELLO", 0, true }, // 0x02 + { "TOCLIENT_AUTH_ACCEPT", 0, true }, // 0x03 + { "TOCLIENT_ACCEPT_SUDO_MODE", 0, true }, // 0x04 + { "TOCLIENT_DENY_SUDO_MODE", 0, true }, // 0x05 + null_command_factory, // 0x06 + null_command_factory, // 0x07 + null_command_factory, // 0x08 + null_command_factory, // 0x09 + { "TOCLIENT_ACCESS_DENIED", 0, true }, // 0x0A + null_command_factory, // 0x0B + null_command_factory, // 0x0C + null_command_factory, // 0x0D + null_command_factory, // 0x0E + null_command_factory, // 0x0F + { "TOCLIENT_INIT", 0, true }, // 0x10 + null_command_factory, // 0x11 + null_command_factory, // 0x12 + null_command_factory, // 0x13 + null_command_factory, // 0x14 + null_command_factory, // 0x15 + null_command_factory, // 0x16 + null_command_factory, // 0x17 + null_command_factory, // 0x18 + null_command_factory, // 0x19 + null_command_factory, // 0x1A + null_command_factory, // 0x1B + null_command_factory, // 0x1C + null_command_factory, // 0x1D + null_command_factory, // 0x1E + null_command_factory, // 0x1F + { "TOCLIENT_BLOCKDATA", 2, true }, // 0x20 + { "TOCLIENT_ADDNODE", 0, true }, // 0x21 + { "TOCLIENT_REMOVENODE", 0, true }, // 0x22 + null_command_factory, // 0x23 + null_command_factory, // 0x24 + null_command_factory, // 0x25 + null_command_factory, // 0x26 + { "TOCLIENT_INVENTORY", 0, true }, // 0x27 + null_command_factory, // 0x28 + { "TOCLIENT_TIME_OF_DAY", 0, true }, // 0x29 + { "TOCLIENT_CSM_RESTRICTION_FLAGS", 0, true }, // 0x2A + { "TOCLIENT_PLAYER_SPEED", 0, true }, // 0x2B + { "TOCLIENT_MEDIA_PUSH", 0, true }, // 0x2C (sent over channel 1 too) + null_command_factory, // 0x2D + null_command_factory, // 0x2E + { "TOCLIENT_CHAT_MESSAGE", 0, true }, // 0x2F + null_command_factory, // 0x30 + { "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", 0, true }, // 0x31 + { "TOCLIENT_ACTIVE_OBJECT_MESSAGES", 0, true }, // 0x32 (may be sent as unrel over channel 1 too) + { "TOCLIENT_HP", 0, true }, // 0x33 + { "TOCLIENT_MOVE_PLAYER", 0, true }, // 0x34 + { "TOCLIENT_ACCESS_DENIED_LEGACY", 0, true }, // 0x35 + { "TOCLIENT_FOV", 0, true }, // 0x36 + { "TOCLIENT_DEATHSCREEN", 0, true }, // 0x37 + { "TOCLIENT_MEDIA", 2, true }, // 0x38 + null_command_factory, // 0x39 + { "TOCLIENT_NODEDEF", 0, true }, // 0x3A + null_command_factory, // 0x3B + { "TOCLIENT_ANNOUNCE_MEDIA", 0, true }, // 0x3C + { "TOCLIENT_ITEMDEF", 0, true }, // 0x3D + null_command_factory, // 0x3E + { "TOCLIENT_PLAY_SOUND", 0, true }, // 0x3f (may be sent as unrel too) + { "TOCLIENT_STOP_SOUND", 0, true }, // 0x40 + { "TOCLIENT_PRIVILEGES", 0, true }, // 0x41 + { "TOCLIENT_INVENTORY_FORMSPEC", 0, true }, // 0x42 + { "TOCLIENT_DETACHED_INVENTORY", 0, true }, // 0x43 + { "TOCLIENT_SHOW_FORMSPEC", 0, true }, // 0x44 + { "TOCLIENT_MOVEMENT", 0, true }, // 0x45 + { "TOCLIENT_SPAWN_PARTICLE", 0, true }, // 0x46 + { "TOCLIENT_ADD_PARTICLESPAWNER", 0, true }, // 0x47 + null_command_factory, // 0x48 + { "TOCLIENT_HUDADD", 1, true }, // 0x49 + { "TOCLIENT_HUDRM", 1, true }, // 0x4a + { "TOCLIENT_HUDCHANGE", 1, true }, // 0x4b + { "TOCLIENT_HUD_SET_FLAGS", 1, true }, // 0x4c + { "TOCLIENT_HUD_SET_PARAM", 1, true }, // 0x4d + { "TOCLIENT_BREATH", 0, true }, // 0x4e + { "TOCLIENT_SET_SKY", 0, true }, // 0x4f + { "TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", 0, true }, // 0x50 + { "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", 0, true }, // 0x51 + { "TOCLIENT_EYE_OFFSET", 0, true }, // 0x52 + { "TOCLIENT_DELETE_PARTICLESPAWNER", 0, true }, // 0x53 + { "TOCLIENT_CLOUD_PARAMS", 0, true }, // 0x54 + { "TOCLIENT_FADE_SOUND", 0, true }, // 0x55 + { "TOCLIENT_UPDATE_PLAYER_LIST", 0, true }, // 0x56 + { "TOCLIENT_MODCHANNEL_MSG", 0, true }, // 0x57 + { "TOCLIENT_MODCHANNEL_SIGNAL", 0, true }, // 0x58 + { "TOCLIENT_NODEMETA_CHANGED", 0, true }, // 0x59 + { "TOCLIENT_SET_SUN", 0, true }, // 0x5a + { "TOCLIENT_SET_MOON", 0, true }, // 0x5b + { "TOCLIENT_SET_STARS", 0, true }, // 0x5c + null_command_factory, // 0x5d + null_command_factory, // 0x5e + null_command_factory, // 0x5f + { "TOSERVER_SRP_BYTES_S_B", 0, true }, // 0x60 + { "TOCLIENT_FORMSPEC_PREPEND", 0, true }, // 0x61 }; diff --git a/src/network/serveropcodes.h b/src/network/serveropcodes.h index 9d3c1ab9e..6df09d5ef 100644 --- a/src/network/serveropcodes.h +++ b/src/network/serveropcodes.h @@ -25,8 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class NetworkPacket; -enum ToServerConnectionState -{ +enum ToServerConnectionState { TOSERVER_STATE_NOT_CONNECTED, TOSERVER_STATE_STARTUP, TOSERVER_STATE_INGAME, @@ -34,14 +33,14 @@ enum ToServerConnectionState }; struct ToServerCommandHandler { - const std::string name; - ToServerConnectionState state; - void (Server::*handler)(NetworkPacket *pkt); + const std::string name; + ToServerConnectionState state; + void (Server::*handler)(NetworkPacket* pkt); }; struct ClientCommandFactory { - const char *name; + const char* name; u8 channel; bool reliable; }; diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index 2b4c5c718..b3008bb50 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -41,16 +41,16 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/serialize.h" #include "util/srp.h" -void Server::handleCommand_Deprecated(NetworkPacket *pkt) +void Server::handleCommand_Deprecated(NetworkPacket* pkt) { infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name - << " not supported anymore" << std::endl; + << " not supported anymore" << std::endl; } -void Server::handleCommand_Init(NetworkPacket *pkt) +void Server::handleCommand_Init(NetworkPacket* pkt) { - if (pkt->getSize() < 1) + if(pkt->getSize() < 1) return; session_t peer_id = pkt->getPeerId(); @@ -60,33 +60,34 @@ void Server::handleCommand_Init(NetworkPacket *pkt) try { Address address = getPeerAddress(peer_id); addr_s = address.serializeString(); - } catch (con::PeerNotFoundException &e) { + } + catch (con::PeerNotFoundException &e) { /* * no peer for this packet found * most common reason is peer timeout, e.g. peer didn't * respond for some time, your server was overloaded or * things like that. */ - infostream << "Server::ProcessData(): Canceling: peer " << peer_id - << " not found" << std::endl; + infostream << "Server::ProcessData(): Canceling: peer " << peer_id << + " not found" << std::endl; return; } // If net_proto_version is set, this client has already been handled if (client->getState() > CS_Created) { - verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " - << addr_s << " (peer_id=" << peer_id << ")" << std::endl; + verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " << + addr_s << " (peer_id=" << peer_id << ")" << std::endl; return; } - verbosestream << "Server: Got TOSERVER_INIT from " << addr_s - << " (peer_id=" << peer_id << ")" << std::endl; + verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << + " (peer_id=" << peer_id << ")" << std::endl; // Do not allow multiple players in simple singleplayer mode. // This isn't a perfect way to do it, but will suffice for now if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) { - infostream << "Server: Not allowing another client (" << addr_s - << ") to connect in simple singleplayer mode" << std::endl; + infostream << "Server: Not allowing another client (" << addr_s << + ") to connect in simple singleplayer mode" << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER); return; } @@ -99,8 +100,8 @@ void Server::handleCommand_Init(NetworkPacket *pkt) u16 max_net_proto_version; std::string playerName; - *pkt >> client_max >> supp_compr_modes >> min_net_proto_version >> - max_net_proto_version >> playerName; + *pkt >> client_max >> supp_compr_modes >> min_net_proto_version + >> max_net_proto_version >> playerName; u8 our_max = SER_FMT_VER_HIGHEST_READ; // Use the highest version supported by both @@ -110,8 +111,8 @@ void Server::handleCommand_Init(NetworkPacket *pkt) depl_serial_v = SER_FMT_VER_INVALID; if (depl_serial_v == SER_FMT_VER_INVALID) { - actionstream << "Server: A mismatched client tried to connect from " - << addr_s << " ser_fmt_max=" << (int)client_max << std::endl; + actionstream << "Server: A mismatched client tried to connect from " << + addr_s << " ser_fmt_max=" << (int)client_max << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION); return; } @@ -135,20 +136,18 @@ void Server::handleCommand_Init(NetworkPacket *pkt) net_proto_version = max_net_proto_version; } - verbosestream << "Server: " << addr_s - << ": Protocol version: min: " << min_net_proto_version - << ", max: " << max_net_proto_version - << ", chosen: " << net_proto_version << std::endl; + verbosestream << "Server: " << addr_s << ": Protocol version: min: " + << min_net_proto_version << ", max: " << max_net_proto_version + << ", chosen: " << net_proto_version << std::endl; client->net_proto_version = net_proto_version; if ((g_settings->getBool("strict_protocol_version_checking") && - net_proto_version != LATEST_PROTOCOL_VERSION) || + net_proto_version != LATEST_PROTOCOL_VERSION) || net_proto_version < SERVER_PROTOCOL_VERSION_MIN || net_proto_version > SERVER_PROTOCOL_VERSION_MAX) { - actionstream << "Server: A mismatched client tried to connect from " - << addr_s << " proto_max=" << (int)max_net_proto_version - << std::endl; + actionstream << "Server: A mismatched client tried to connect from " << + addr_s << " proto_max=" << (int)max_net_proto_version << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION); return; } @@ -156,34 +155,32 @@ void Server::handleCommand_Init(NetworkPacket *pkt) /* Validate player name */ - const char *playername = playerName.c_str(); + const char* playername = playerName.c_str(); size_t pns = playerName.size(); if (pns == 0 || pns > PLAYERNAME_SIZE) { - actionstream << "Server: Player with " - << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") - << " name tried to connect from " << addr_s << std::endl; + actionstream << "Server: Player with " << + ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") << + " name tried to connect from " << addr_s << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME); return; } if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) { actionstream << "Server: Player with an invalid name tried to connect " - "from " - << addr_s << std::endl; + "from " << addr_s << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME); return; } m_clients.setPlayerName(peer_id, playername); - // TODO (later) case insensitivity + //TODO (later) case insensitivity std::string legacyPlayerNameCasing = playerName; if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) { actionstream << "Server: Player with the name \"singleplayer\" tried " - "to connect from " - << addr_s << std::endl; + "to connect from " << addr_s << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME); return; } @@ -191,27 +188,26 @@ void Server::handleCommand_Init(NetworkPacket *pkt) { std::string reason; if (m_script->on_prejoinplayer(playername, addr_s, &reason)) { - actionstream << "Server: Player with the name \"" << playerName - << "\" tried to connect from " << addr_s - << " but it was disallowed for the following " - "reason: " - << reason << std::endl; + actionstream << "Server: Player with the name \"" << playerName << + "\" tried to connect from " << addr_s << + " but it was disallowed for the following reason: " << reason << + std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason); return; } } - infostream << "Server: New connection: \"" << playerName << "\" from " << addr_s - << " (peer_id=" << peer_id << ")" << std::endl; + infostream << "Server: New connection: \"" << playerName << "\" from " << + addr_s << " (peer_id=" << peer_id << ")" << std::endl; // Enforce user limit. // Don't enforce for users that have some admin right or mod permits it. - if (m_clients.isUserLimitReached() && playername != g_settings->get("name") && + if (m_clients.isUserLimitReached() && + playername != g_settings->get("name") && !m_script->can_bypass_userlimit(playername, addr_s)) { - actionstream << "Server: " << playername << " tried to join from " - << addr_s << ", but there are already max_users=" - << g_settings->getU16("max_users") << " players." - << std::endl; + actionstream << "Server: " << playername << " tried to join from " << + addr_s << ", but there are already max_users=" << + g_settings->getU16("max_users") << " players." << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS); return; } @@ -232,11 +228,9 @@ void Server::handleCommand_Init(NetworkPacket *pkt) auth_mechs |= AUTH_MECHANISM_SRP; client->enc_pwd = encpwd; } else { - actionstream << "User " << playername - << " tried to log in, " - "but password field was invalid (unknown " - "mechcode)." - << std::endl; + actionstream << "User " << playername << " tried to log in, " + "but password field was invalid (unknown mechcode)." << + std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL); return; } @@ -244,10 +238,8 @@ void Server::handleCommand_Init(NetworkPacket *pkt) auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD; client->enc_pwd = encpwd; } else { - actionstream << "User " << playername - << " tried to log in, but " - "password field was invalid (invalid base64)." - << std::endl; + actionstream << "User " << playername << " tried to log in, but " + "password field was invalid (invalid base64)." << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL); return; } @@ -257,8 +249,7 @@ void Server::handleCommand_Init(NetworkPacket *pkt) auth_mechs |= AUTH_MECHANISM_FIRST_SRP; } else { // Take care of default passwords. - client->enc_pwd = get_encoded_srp_verifier( - playerName, default_password); + client->enc_pwd = get_encoded_srp_verifier(playerName, default_password); auth_mechs |= AUTH_MECHANISM_SRP; // Allocate player in db, but only on successful login. client->create_player_on_auth_success = true; @@ -269,15 +260,15 @@ void Server::handleCommand_Init(NetworkPacket *pkt) Answer with a TOCLIENT_HELLO */ - verbosestream << "Sending TOCLIENT_HELLO with auth method field: " << auth_mechs - << std::endl; + verbosestream << "Sending TOCLIENT_HELLO with auth method field: " + << auth_mechs << std::endl; - NetworkPacket resp_pkt( - TOCLIENT_HELLO, 1 + 4 + legacyPlayerNameCasing.size(), peer_id); + NetworkPacket resp_pkt(TOCLIENT_HELLO, + 1 + 4 + legacyPlayerNameCasing.size(), peer_id); u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE; - resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version << auth_mechs - << legacyPlayerNameCasing; + resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version + << auth_mechs << legacyPlayerNameCasing; Send(&resp_pkt); @@ -287,7 +278,7 @@ void Server::handleCommand_Init(NetworkPacket *pkt) m_clients.event(peer_id, CSE_Hello); } -void Server::handleCommand_Init2(NetworkPacket *pkt) +void Server::handleCommand_Init2(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl; @@ -303,8 +294,8 @@ void Server::handleCommand_Init2(NetworkPacket *pkt) Send some initialization data */ - infostream << "Server: Sending content to " << getPlayerName(peer_id) - << std::endl; + infostream << "Server: Sending content to " << getPlayerName(peer_id) << + std::endl; // Send item definitions SendItemDef(peer_id, m_itemdef, protocol_version); @@ -344,15 +335,13 @@ void Server::handleCommand_Init2(NetworkPacket *pkt) // Warnings about protocol version can be issued here if (client->net_proto_version < LATEST_PROTOCOL_VERSION) { - SendChatMessage(peer_id, - ChatMessage(CHATMESSAGE_TYPE_SYSTEM, - L"# Server: WARNING: YOUR CLIENT'S " - L"VERSION MAY NOT BE FULLY COMPATIBLE " - L"WITH THIS SERVER!")); + SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM, + L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE " + L"WITH THIS SERVER!")); } } -void Server::handleCommand_RequestMedia(NetworkPacket *pkt) +void Server::handleCommand_RequestMedia(NetworkPacket* pkt) { std::vector tosend; u16 numfiles; @@ -360,8 +349,8 @@ void Server::handleCommand_RequestMedia(NetworkPacket *pkt) *pkt >> numfiles; session_t peer_id = pkt->getPeerId(); - infostream << "Sending " << numfiles << " files to " << getPlayerName(peer_id) - << std::endl; + infostream << "Sending " << numfiles << " files to " << + getPlayerName(peer_id) << std::endl; verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl; for (u16 i = 0; i < numfiles; i++) { @@ -370,31 +359,30 @@ void Server::handleCommand_RequestMedia(NetworkPacket *pkt) *pkt >> name; tosend.push_back(name); - verbosestream << "TOSERVER_REQUEST_MEDIA: requested file " << name - << std::endl; + verbosestream << "TOSERVER_REQUEST_MEDIA: requested file " + << name << std::endl; } sendRequestedMedia(peer_id, tosend); } -void Server::handleCommand_ClientReady(NetworkPacket *pkt) +void Server::handleCommand_ClientReady(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); - PlayerSAO *playersao = StageTwoClientInit(peer_id); + PlayerSAO* playersao = StageTwoClientInit(peer_id); if (playersao == NULL) { errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed " - "peer_id=" - << peer_id << std::endl; + "peer_id=" << peer_id << std::endl; DisconnectPeer(peer_id); return; } + if (pkt->getSize() < 8) { errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, " - "disconnecting peer_id: " - << peer_id << std::endl; + "disconnecting peer_id: " << peer_id << std::endl; DisconnectPeer(peer_id); return; } @@ -403,29 +391,28 @@ void Server::handleCommand_ClientReady(NetworkPacket *pkt) std::string full_ver; *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver; - m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver, full_ver); + m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver, + full_ver); if (pkt->getRemainingBytes() >= 2) *pkt >> playersao->getPlayer()->formspec_version; const std::vector &players = m_clients.getPlayerNames(); NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id); - list_pkt << (u8)PLAYER_LIST_INIT << (u16)players.size(); - for (const std::string &player : players) { - list_pkt << player; + list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size(); + for (const std::string &player: players) { + list_pkt << player; } m_clients.send(peer_id, 0, &list_pkt, true); NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT); // (u16) 1 + std::string represents a pseudo vector serialization representation - notice_pkt << (u8)PLAYER_LIST_ADD << (u16)1 - << std::string(playersao->getPlayer()->getName()); + notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName()); m_clients.sendToAll(¬ice_pkt); m_clients.event(peer_id, CSE_SetClientReady); s64 last_login; - m_script->getAuth( - playersao->getPlayer()->getName(), nullptr, nullptr, &last_login); + m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login); m_script->on_joinplayer(playersao, last_login); // Send shutdown timer if shutdown has been scheduled @@ -434,7 +421,7 @@ void Server::handleCommand_ClientReady(NetworkPacket *pkt) } } -void Server::handleCommand_GotBlocks(NetworkPacket *pkt) +void Server::handleCommand_GotBlocks(NetworkPacket* pkt) { if (pkt->getSize() < 1) return; @@ -453,7 +440,8 @@ void Server::handleCommand_GotBlocks(NetworkPacket *pkt) RemoteClient *client = getClient(pkt->getPeerId()); if ((s16)pkt->getSize() < 1 + (int)count * 6) { - throw con::InvalidIncomingDataException("GOTBLOCKS length is too short"); + throw con::InvalidIncomingDataException + ("GOTBLOCKS length is too short"); } for (u16 i = 0; i < count; i++) { @@ -463,8 +451,8 @@ void Server::handleCommand_GotBlocks(NetworkPacket *pkt) } } -void Server::process_PlayerPos( - RemotePlayer *player, PlayerSAO *playersao, NetworkPacket *pkt) +void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao, + NetworkPacket *pkt) { if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1) return; @@ -522,22 +510,23 @@ void Server::process_PlayerPos( } } -void Server::handleCommand_PlayerPos(NetworkPacket *pkt) +void Server::handleCommand_PlayerPos(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } @@ -545,14 +534,14 @@ void Server::handleCommand_PlayerPos(NetworkPacket *pkt) // If player is dead we don't care of this packet if (playersao->isDead()) { verbosestream << "TOSERVER_PLAYERPOS: " << player->getName() - << " is dead. Ignoring packet"; + << " is dead. Ignoring packet"; return; } process_PlayerPos(player, playersao, pkt); } -void Server::handleCommand_DeletedBlocks(NetworkPacket *pkt) +void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt) { if (pkt->getSize() < 1) return; @@ -571,8 +560,8 @@ void Server::handleCommand_DeletedBlocks(NetworkPacket *pkt) RemoteClient *client = getClient(pkt->getPeerId()); if ((s16)pkt->getSize() < 1 + (int)count * 6) { - throw con::InvalidIncomingDataException( - "DELETEDBLOCKS length is too short"); + throw con::InvalidIncomingDataException + ("DELETEDBLOCKS length is too short"); } for (u16 i = 0; i < count; i++) { @@ -582,42 +571,45 @@ void Server::handleCommand_DeletedBlocks(NetworkPacket *pkt) } } -void Server::handleCommand_InventoryAction(NetworkPacket *pkt) +void Server::handleCommand_InventoryAction(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } // Strip command and create a stream std::string datastring(pkt->getString(0), pkt->getSize()); - verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring << std::endl; + verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring + << std::endl; std::istringstream is(datastring, std::ios_base::binary); // Create an action InventoryAction *a = InventoryAction::deSerialize(is); if (!a) { infostream << "TOSERVER_INVENTORY_ACTION: " - << "InventoryAction::deSerialize() returned NULL" << std::endl; + << "InventoryAction::deSerialize() returned NULL" + << std::endl; return; } // If something goes wrong, this player is to blame - RollbackScopeActor rollback_scope( - m_rollback, std::string("player:") + player->getName()); + RollbackScopeActor rollback_scope(m_rollback, + std::string("player:")+player->getName()); /* Note: Always set inventory not sent, to repair cases @@ -628,7 +620,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) Handle restrictions and special cases of the move action */ if (a->getType() == IAction::Move) { - IMoveAction *ma = (IMoveAction *)a; + IMoveAction *ma = (IMoveAction*)a; ma->from_inv.applyCurrentPlayer(player->getName()); ma->to_inv.applyCurrentPlayer(player->getName()); @@ -638,19 +630,19 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) m_inventory_mgr->setInventoryModified(ma->to_inv); bool from_inv_is_current_player = - (ma->from_inv.type == InventoryLocation::PLAYER) && - (ma->from_inv.name == player->getName()); + (ma->from_inv.type == InventoryLocation::PLAYER) && + (ma->from_inv.name == player->getName()); bool to_inv_is_current_player = - (ma->to_inv.type == InventoryLocation::PLAYER) && - (ma->to_inv.name == player->getName()); + (ma->to_inv.type == InventoryLocation::PLAYER) && + (ma->to_inv.name == player->getName()); - InventoryLocation *remote = - from_inv_is_current_player ? &ma->to_inv : &ma->from_inv; + InventoryLocation *remote = from_inv_is_current_player ? + &ma->to_inv : &ma->from_inv; // Check for out-of-range interaction if (remote->type == InventoryLocation::NODEMETA) { - v3f node_pos = intToFloat(remote->p, BS); + v3f node_pos = intToFloat(remote->p, BS); v3f player_pos = player->getPlayerSAO()->getEyePosition(); f32 d = player_pos.getDistanceFrom(node_pos); if (!checkInteractDistance(player, d, "inventory")) @@ -662,9 +654,9 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) */ if (ma->from_list == "craftpreview") { infostream << "Ignoring IMoveAction from " - << (ma->from_inv.dump()) << ":" << ma->from_list - << " to " << (ma->to_inv.dump()) << ":" << ma->to_list - << " because src is " << ma->from_list << std::endl; + << (ma->from_inv.dump()) << ":" << ma->from_list + << " to " << (ma->to_inv.dump()) << ":" << ma->to_list + << " because src is " << ma->from_list << std::endl; delete a; return; } @@ -674,9 +666,9 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) */ if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") { infostream << "Ignoring IMoveAction from " - << (ma->from_inv.dump()) << ":" << ma->from_list - << " to " << (ma->to_inv.dump()) << ":" << ma->to_list - << " because dst is " << ma->to_list << std::endl; + << (ma->from_inv.dump()) << ":" << ma->from_list + << " to " << (ma->to_inv.dump()) << ":" << ma->to_list + << " because dst is " << ma->to_list << std::endl; delete a; return; } @@ -685,9 +677,9 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) // if not allowed to interact if (!checkPriv(player->getName(), "interact") && (!from_inv_is_current_player || - !to_inv_is_current_player)) { + !to_inv_is_current_player)) { infostream << "Cannot move outside of player's inventory: " - << "No interact privilege" << std::endl; + << "No interact privilege" << std::endl; delete a; return; } @@ -696,7 +688,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) Handle restrictions and special cases of the drop action */ else if (a->getType() == IAction::Drop) { - IDropAction *da = (IDropAction *)a; + IDropAction *da = (IDropAction*)a; da->from_inv.applyCurrentPlayer(player->getName()); @@ -707,8 +699,8 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) */ if (da->from_list == "craftpreview") { infostream << "Ignoring IDropAction from " - << (da->from_inv.dump()) << ":" << da->from_list - << " because src is " << da->from_list << std::endl; + << (da->from_inv.dump()) << ":" << da->from_list + << " because src is " << da->from_list << std::endl; delete a; return; } @@ -722,8 +714,8 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) // Disallow dropping items if dead if (playersao->isDead()) { infostream << "Ignoring IDropAction from " - << (da->from_inv.dump()) << ":" << da->from_list - << " because player is dead." << std::endl; + << (da->from_inv.dump()) << ":" << da->from_list + << " because player is dead." << std::endl; delete a; return; } @@ -732,20 +724,20 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) Handle restrictions and special cases of the craft action */ else if (a->getType() == IAction::Craft) { - ICraftAction *ca = (ICraftAction *)a; + ICraftAction *ca = (ICraftAction*)a; ca->craft_inv.applyCurrentPlayer(player->getName()); m_inventory_mgr->setInventoryModified(ca->craft_inv); - // bool craft_inv_is_current_player = + //bool craft_inv_is_current_player = // (ca->craft_inv.type == InventoryLocation::PLAYER) && // (ca->craft_inv.name == player->getName()); // Disallow crafting if not allowed to interact if (!checkPriv(player->getName(), "interact")) { infostream << "Cannot craft: " - << "No interact privilege" << std::endl; + << "No interact privilege" << std::endl; delete a; return; } @@ -757,7 +749,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket *pkt) delete a; } -void Server::handleCommand_ChatMessage(NetworkPacket *pkt) +void Server::handleCommand_ChatMessage(NetworkPacket* pkt) { /* u16 command @@ -778,8 +770,9 @@ void Server::handleCommand_ChatMessage(NetworkPacket *pkt) session_t peer_id = pkt->getPeerId(); RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } @@ -792,11 +785,11 @@ void Server::handleCommand_ChatMessage(NetworkPacket *pkt) if (!answer_to_sender.empty()) { // Send the answer to sender SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_NORMAL, - answer_to_sender, wname)); + answer_to_sender, wname)); } } -void Server::handleCommand_Damage(NetworkPacket *pkt) +void Server::handleCommand_Damage(NetworkPacket* pkt) { u16 damage; @@ -806,17 +799,18 @@ void Server::handleCommand_Damage(NetworkPacket *pkt) RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } @@ -824,15 +818,14 @@ void Server::handleCommand_Damage(NetworkPacket *pkt) if (!playersao->isImmortal()) { if (playersao->isDead()) { verbosestream << "Server::ProcessData(): Info: " - "Ignoring damage as player " - << player->getName() << " is already dead." - << std::endl; + "Ignoring damage as player " << player->getName() + << " is already dead." << std::endl; return; } - actionstream << player->getName() << " damaged by " << (int)damage - << " hp at " << PP(playersao->getBasePosition() / BS) - << std::endl; + actionstream << player->getName() << " damaged by " + << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS) + << std::endl; PlayerHPChangeReason reason(PlayerHPChangeReason::FALL); playersao->setHP((s32)playersao->getHP() - (s32)damage, reason); @@ -840,7 +833,7 @@ void Server::handleCommand_Damage(NetworkPacket *pkt) } } -void Server::handleCommand_PlayerItem(NetworkPacket *pkt) +void Server::handleCommand_PlayerItem(NetworkPacket* pkt) { if (pkt->getSize() < 2) return; @@ -849,17 +842,18 @@ void Server::handleCommand_PlayerItem(NetworkPacket *pkt) RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } @@ -871,13 +865,14 @@ void Server::handleCommand_PlayerItem(NetworkPacket *pkt) playersao->getPlayer()->setWieldIndex(item); } -void Server::handleCommand_Respawn(NetworkPacket *pkt) +void Server::handleCommand_Respawn(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } @@ -891,27 +886,27 @@ void Server::handleCommand_Respawn(NetworkPacket *pkt) RespawnPlayer(peer_id); actionstream << player->getName() << " respawns at " - << PP(playersao->getBasePosition() / BS) << std::endl; + << PP(playersao->getBasePosition() / BS) << std::endl; // ActiveObject is added to environment in AsyncRunStep after // the previous addition has been successfully removed } -bool Server::checkInteractDistance( - RemotePlayer *player, const f32 d, const std::string &what) +bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what) { ItemStack selected_item, hand_item; player->getWieldedItem(&selected_item, &hand_item); f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef), - hand_item.getDefinition(m_itemdef)); + hand_item.getDefinition(m_itemdef)); // Cube diagonal * 1.5 for maximal supported node extents: // sqrt(3) * 1.5 ≅ 2.6 if (d > max_d + 2.6f * BS) { - actionstream << "Player " << player->getName() << " tried to access " - << what << " from too far: " - << "d=" << d << ", max_d=" << max_d << "; ignoring." - << std::endl; + actionstream << "Player " << player->getName() + << " tried to access " << what + << " from too far: " + << "d=" << d << ", max_d=" << max_d + << "; ignoring." << std::endl; // Call callbacks m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far"); return false; @@ -940,32 +935,32 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) PointedThing pointed; pointed.deSerialize(tmp_is); - verbosestream << "TOSERVER_INTERACT: action=" << (int)action - << ", item=" << item_i << ", pointed=" << pointed.dump() - << std::endl; + verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item=" + << item_i << ", pointed=" << pointed.dump() << std::endl; session_t peer_id = pkt->getPeerId(); RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } if (playersao->isDead()) { actionstream << "Server: " << player->getName() - << " tried to interact while dead; ignoring." << std::endl; + << " tried to interact while dead; ignoring." << std::endl; if (pointed.type == POINTEDTHING_NODE) { // Re-send block to revert change on client-side RemoteClient *client = getClient(peer_id); @@ -994,10 +989,10 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) pointed_object = m_env->getActiveObject(pointed.object_id); if (pointed_object == NULL) { verbosestream << "TOSERVER_INTERACT: " - "pointed object is NULL" - << std::endl; + "pointed object is NULL" << std::endl; return; } + } v3f pointed_pos_under = player_pos; @@ -1005,7 +1000,8 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) if (pointed.type == POINTEDTHING_NODE) { pointed_pos_under = intToFloat(p_under, BS); pointed_pos_above = intToFloat(p_above, BS); - } else if (pointed.type == POINTEDTHING_OBJECT) { + } + else if (pointed.type == POINTEDTHING_OBJECT) { pointed_pos_under = pointed_object->getBasePosition(); pointed_pos_above = pointed_pos_under; } @@ -1014,22 +1010,19 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) Make sure the player is allowed to do it */ if (!checkPriv(player->getName(), "interact")) { - actionstream << player->getName() << " attempted to interact with " - << pointed.dump() << " without 'interact' privilege" - << std::endl; + actionstream << player->getName() << " attempted to interact with " << + pointed.dump() << " without 'interact' privilege" << std::endl; // Re-send block to revert change on client-side RemoteClient *client = getClient(peer_id); // Digging completed -> under if (action == INTERACT_DIGGING_COMPLETED) { - v3s16 blockpos = getNodeBlockPos( - floatToInt(pointed_pos_under, BS)); + v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS)); client->SetBlockNotSent(blockpos); } // Placement -> above else if (action == INTERACT_PLACE) { - v3s16 blockpos = getNodeBlockPos( - floatToInt(pointed_pos_above, BS)); + v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS)); client->SetBlockNotSent(blockpos); } return; @@ -1043,15 +1036,14 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) !g_settings->getBool("disable_anticheat"); if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED || - action == INTERACT_PLACE || action == INTERACT_USE) && + action == INTERACT_PLACE || action == INTERACT_USE) && enable_anticheat && !isSingleplayer()) { float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under); if (!checkInteractDistance(player, d, pointed.dump())) { // Re-send block to revert change on client-side RemoteClient *client = getClient(peer_id); - v3s16 blockpos = getNodeBlockPos( - floatToInt(pointed_pos_under, BS)); + v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS)); client->SetBlockNotSent(blockpos); return; } @@ -1060,8 +1052,8 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) /* If something goes wrong, this player is to blame */ - RollbackScopeActor rollback_scope( - m_rollback, std::string("player:") + player->getName()); + RollbackScopeActor rollback_scope(m_rollback, + std::string("player:")+player->getName()); /* 0: start digging or punch object @@ -1074,10 +1066,9 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) n = m_env->getMap().getNode(p_under, &pos_ok); if (!pos_ok) { infostream << "Server: Not punching: Node not found. " - "Adding block to emerge queue." - << std::endl; - m_emerge->enqueueBlockEmerge( - peer_id, getNodeBlockPos(p_above), false); + "Adding block to emerge queue." << std::endl; + m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above), + false); } if (n.getContent() != CONTENT_IGNORE) @@ -1085,27 +1076,27 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) // Cheat prevention playersao->noCheatDigStart(p_under); - } else if (pointed.type == POINTEDTHING_OBJECT) { + } + else if (pointed.type == POINTEDTHING_OBJECT) { // Skip if object can't be interacted with anymore if (pointed_object->isGone()) return; ItemStack selected_item, hand_item; - ItemStack tool_item = playersao->getWieldedItem( - &selected_item, &hand_item); + ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item); ToolCapabilities toolcap = tool_item.getToolCapabilities(m_itemdef); v3f dir = (pointed_object->getBasePosition() - - (playersao->getBasePosition() + - playersao->getEyeOffset())) - .normalize(); - float time_from_last_punch = playersao->resetTimeFromLastPunch(); + (playersao->getBasePosition() + playersao->getEyeOffset()) + ).normalize(); + float time_from_last_punch = + playersao->resetTimeFromLastPunch(); u16 src_original_hp = pointed_object->getHP(); u16 dst_origin_hp = playersao->getHP(); - u16 wear = pointed_object->punch( - dir, &toolcap, playersao, time_from_last_punch); + u16 wear = pointed_object->punch(dir, &toolcap, playersao, + time_from_last_punch); // Callback may have changed item, so get it again playersao->getWieldedItem(&selected_item); @@ -1115,22 +1106,15 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) // If the object is a player and its HP changed if (src_original_hp != pointed_object->getHP() && - pointed_object->getType() == - ACTIVEOBJECT_TYPE_PLAYER) { + pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) { SendPlayerHPOrDie((PlayerSAO *)pointed_object, - PlayerHPChangeReason( - PlayerHPChangeReason:: - PLAYER_PUNCH, - playersao)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao)); } // If the puncher is a player and its HP changed if (dst_origin_hp != playersao->getHP()) SendPlayerHPOrDie(playersao, - PlayerHPChangeReason( - PlayerHPChangeReason:: - PLAYER_PUNCH, - pointed_object)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object)); } } // action == INTERACT_START_DIGGING @@ -1150,12 +1134,10 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) bool pos_ok; MapNode n = m_env->getMap().getNode(p_under, &pos_ok); if (!pos_ok) { - infostream << "Server: Not finishing digging: Node not " - "found. " - "Adding block to emerge queue." - << std::endl; - m_emerge->enqueueBlockEmerge( - peer_id, getNodeBlockPos(p_above), false); + infostream << "Server: Not finishing digging: Node not found. " + "Adding block to emerge queue." << std::endl; + m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above), + false); } /* Cheat prevention */ @@ -1167,39 +1149,33 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) // If player didn't start digging this, ignore dig if (nocheat_p != p_under) { infostream << "Server: " << player->getName() - << " started digging " << PP(nocheat_p) - << " and completed digging " - << PP(p_under) << "; not digging." - << std::endl; + << " started digging " + << PP(nocheat_p) << " and completed digging " + << PP(p_under) << "; not digging." << std::endl; is_valid_dig = false; // Call callbacks - m_script->on_cheat(playersao, - "finished_unknown_dig"); + m_script->on_cheat(playersao, "finished_unknown_dig"); } // Get player's wielded item // See also: Game::handleDigging ItemStack selected_item, hand_item; - playersao->getPlayer()->getWieldedItem( - &selected_item, &hand_item); + playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item); // Get diggability and expected digging time DigParams params = getDigParams(m_nodedef->get(n).groups, - &selected_item.getToolCapabilities( - m_itemdef)); + &selected_item.getToolCapabilities(m_itemdef)); // If can't dig, try hand if (!params.diggable) { params = getDigParams(m_nodedef->get(n).groups, - &hand_item.getToolCapabilities( - m_itemdef)); + &hand_item.getToolCapabilities(m_itemdef)); } // If can't dig, ignore dig if (!params.diggable) { infostream << "Server: " << player->getName() - << " completed digging " << PP(p_under) - << ", which is not diggable with " - "tool; not digging." - << std::endl; + << " completed digging " << PP(p_under) + << ", which is not diggable with tool; not digging." + << std::endl; is_valid_dig = false; // Call callbacks m_script->on_cheat(playersao, "dug_unbreakable"); @@ -1210,10 +1186,9 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) // Well not our problem then } // Clean and long dig - else if (params.time > 2.0 && - nocheat_t * 1.2 > params.time) { - // All is good, but grab time from pool; don't - // care if it's actually available + else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) { + // All is good, but grab time from pool; don't care if + // it's actually available playersao->getDigPool().grab(params.time); } // Short or laggy dig @@ -1224,9 +1199,8 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) // Dig not possible else { infostream << "Server: " << player->getName() - << " completed digging " << PP(p_under) - << "too fast; not digging." - << std::endl; + << " completed digging " << PP(p_under) + << "too fast; not digging." << std::endl; is_valid_dig = false; // Call callbacks m_script->on_cheat(playersao, "dug_too_fast"); @@ -1238,15 +1212,14 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) if (is_valid_dig && n.getContent() != CONTENT_IGNORE) m_script->node_on_dig(p_under, n, playersao); - v3s16 blockpos = getNodeBlockPos( - floatToInt(pointed_pos_under, BS)); + v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS)); RemoteClient *client = getClient(peer_id); // Send unusual result (that is, node not being removed) - if (m_env->getMap().getNode(p_under).getContent() != - CONTENT_AIR) { + if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) { // Re-send block to revert change on client-side client->SetBlockNotSent(blockpos); - } else { + } + else { client->ResendBlockIfOnWire(blockpos); } } @@ -1272,19 +1245,20 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) return; actionstream << player->getName() << " right-clicks object " - << pointed.object_id << ": " - << pointed_object->getDescription() << std::endl; + << pointed.object_id << ": " + << pointed_object->getDescription() << std::endl; // Do stuff if (m_script->item_OnSecondaryUse( - selected_item, playersao, pointed)) { + selected_item, playersao, pointed)) { if (playersao->setWieldedItem(selected_item)) { SendInventory(playersao, true); } } pointed_object->rightClick(playersao); - } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) { + } else if (m_script->item_OnPlace( + selected_item, playersao, pointed)) { // Placement was handled in lua // Apply returned ItemStack @@ -1298,13 +1272,13 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) RemoteClient *client = getClient(peer_id); v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS)); v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS)); - if (!selected_item.getDefinition(m_itemdef) - .node_placement_prediction.empty()) { + if (!selected_item.getDefinition(m_itemdef).node_placement_prediction.empty()) { client->SetBlockNotSent(blockpos); if (blockpos2 != blockpos) { client->SetBlockNotSent(blockpos2); } - } else { + } + else { client->ResendBlockIfOnWire(blockpos); if (blockpos2 != blockpos) { client->ResendBlockIfOnWire(blockpos2); @@ -1320,9 +1294,10 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) playersao->getWieldedItem(&selected_item, nullptr); actionstream << player->getName() << " uses " << selected_item.name - << ", pointing at " << pointed.dump() << std::endl; + << ", pointing at " << pointed.dump() << std::endl; - if (m_script->item_OnUse(selected_item, playersao, pointed)) { + if (m_script->item_OnUse( + selected_item, playersao, pointed)) { // Apply returned ItemStack if (playersao->setWieldedItem(selected_item)) { SendInventory(playersao, true); @@ -1338,27 +1313,30 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) ItemStack selected_item; playersao->getWieldedItem(&selected_item, nullptr); - actionstream << player->getName() << " activates " << selected_item.name - << std::endl; + actionstream << player->getName() << " activates " + << selected_item.name << std::endl; pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING - if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) { + if (m_script->item_OnSecondaryUse( + selected_item, playersao, pointed)) { if (playersao->setWieldedItem(selected_item)) { SendInventory(playersao, true); } } } // action == INTERACT_ACTIVATE + /* Catch invalid actions */ else { - warningstream << "Server: Invalid action " << action << std::endl; + warningstream << "Server: Invalid action " + << action << std::endl; } } -void Server::handleCommand_RemovedSounds(NetworkPacket *pkt) +void Server::handleCommand_RemovedSounds(NetworkPacket* pkt) { u16 num; *pkt >> num; @@ -1368,7 +1346,7 @@ void Server::handleCommand_RemovedSounds(NetworkPacket *pkt) *pkt >> id; std::unordered_map::iterator i = - m_playing_sounds.find(id); + m_playing_sounds.find(id); if (i == m_playing_sounds.end()) continue; @@ -1379,7 +1357,7 @@ void Server::handleCommand_RemovedSounds(NetworkPacket *pkt) } } -void Server::handleCommand_NodeMetaFields(NetworkPacket *pkt) +void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt) { v3s16 p; std::string formname; @@ -1398,24 +1376,25 @@ void Server::handleCommand_NodeMetaFields(NetworkPacket *pkt) RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } // If something goes wrong, this player is to blame - RollbackScopeActor rollback_scope( - m_rollback, std::string("player:") + player->getName()); + RollbackScopeActor rollback_scope(m_rollback, + std::string("player:")+player->getName()); // Check the target node for rollback data; leave others unnoticed RollbackNode rn_old(&m_env->getMap(), p, this); @@ -1431,7 +1410,7 @@ void Server::handleCommand_NodeMetaFields(NetworkPacket *pkt) } } -void Server::handleCommand_InventoryFields(NetworkPacket *pkt) +void Server::handleCommand_InventoryFields(NetworkPacket* pkt) { std::string client_formspec_name; u16 num; @@ -1449,17 +1428,18 @@ void Server::handleCommand_InventoryFields(NetworkPacket *pkt) RemotePlayer *player = m_env->getPlayer(peer_id); if (player == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player for peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } PlayerSAO *playersao = player->getPlayerSAO(); if (playersao == NULL) { - errorstream << "Server::ProcessData(): Canceling: No player object for " - "peer_id=" - << peer_id << " disconnecting peer!" << std::endl; + errorstream << + "Server::ProcessData(): Canceling: No player object for peer_id=" << + peer_id << " disconnecting peer!" << std::endl; DisconnectPeer(peer_id); return; } @@ -1478,25 +1458,23 @@ void Server::handleCommand_InventoryFields(NetworkPacket *pkt) if (it != fields.end() && it->second == "true") m_formspec_state_data.erase(peer_state_iterator); - m_script->on_playerReceiveFields( - playersao, client_formspec_name, fields); + m_script->on_playerReceiveFields(playersao, client_formspec_name, fields); return; } - actionstream << "'" << player->getName() << "' submitted formspec ('" - << client_formspec_name - << "') but the name of the formspec doesn't match the" - " expected name ('" - << server_formspec_name << "')"; + actionstream << "'" << player->getName() + << "' submitted formspec ('" << client_formspec_name + << "') but the name of the formspec doesn't match the" + " expected name ('" << server_formspec_name << "')"; } else { - actionstream << "'" << player->getName() << "' submitted formspec ('" - << client_formspec_name - << "') but server hasn't sent formspec to client"; + actionstream << "'" << player->getName() + << "' submitted formspec ('" << client_formspec_name + << "') but server hasn't sent formspec to client"; } actionstream << ", possible exploitation attempt" << std::endl; } -void Server::handleCommand_FirstSrp(NetworkPacket *pkt) +void Server::handleCommand_FirstSrp(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); RemoteClient *client = getClient(peer_id, CS_Invalid); @@ -1513,24 +1491,23 @@ void Server::handleCommand_FirstSrp(NetworkPacket *pkt) *pkt >> salt >> verification_key >> is_empty; verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s - << ", with is_empty=" << (is_empty == 1) << std::endl; + << ", with is_empty=" << (is_empty == 1) << std::endl; // Either this packet is sent because the user is new or to change the password if (cstate == CS_HelloSent) { if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) { actionstream << "Server: Client from " << addr_s - << " tried to set password without being " - << "authenticated, or the username being new." - << std::endl; + << " tried to set password without being " + << "authenticated, or the username being new." << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA); return; } - if (!isSingleplayer() && g_settings->getBool("disallow_empty_password") && + if (!isSingleplayer() && + g_settings->getBool("disallow_empty_password") && is_empty == 1) { actionstream << "Server: " << playername - << " supplied empty password from " << addr_s - << std::endl; + << " supplied empty password from " << addr_s << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD); return; } @@ -1544,11 +1521,9 @@ void Server::handleCommand_FirstSrp(NetworkPacket *pkt) acceptAuth(peer_id, false); } else { if (cstate < CS_SudoMode) { - infostream << "Server::ProcessData(): Ignoring " - "TOSERVER_FIRST_SRP from " - << addr_s << ": " - << "Client has wrong state " << cstate << "." - << std::endl; + infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from " + << addr_s << ": " << "Client has wrong state " << cstate << "." + << std::endl; return; } m_clients.event(peer_id, CSE_SudoLeave); @@ -1556,22 +1531,18 @@ void Server::handleCommand_FirstSrp(NetworkPacket *pkt) bool success = m_script->setPassword(playername, pw_db_field); if (success) { actionstream << playername << " changes password" << std::endl; - SendChatMessage(peer_id, - ChatMessage(CHATMESSAGE_TYPE_SYSTEM, - L"Password change successful.")); + SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM, + L"Password change successful.")); } else { - actionstream << playername - << " tries to change password but it fails" - << std::endl; - SendChatMessage(peer_id, - ChatMessage(CHATMESSAGE_TYPE_SYSTEM, - L"Password change failed or " - L"unavailable.")); + actionstream << playername << + " tries to change password but it fails" << std::endl; + SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM, + L"Password change failed or unavailable.")); } } } -void Server::handleCommand_SrpBytesA(NetworkPacket *pkt) +void Server::handleCommand_SrpBytesA(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); RemoteClient *client = getClient(peer_id, CS_Invalid); @@ -1580,18 +1551,17 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt) bool wantSudo = (cstate == CS_Active); if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) { - actionstream << "Server: got SRP _A packet in wrong state " << cstate - << " from " << getPeerAddress(peer_id).serializeString() - << ". Ignoring." << std::endl; + actionstream << "Server: got SRP _A packet in wrong state " << cstate << + " from " << getPeerAddress(peer_id).serializeString() << + ". Ignoring." << std::endl; return; } if (client->chosen_mech != AUTH_MECHANISM_NONE) { actionstream << "Server: got SRP _A packet, while auth is already " - "going on with mech " - << client->chosen_mech << " from " - << getPeerAddress(peer_id).serializeString() - << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl; + "going on with mech " << client->chosen_mech << " from " << + getPeerAddress(peer_id).serializeString() << + " (wantSudo=" << wantSudo << "). Ignoring." << std::endl; if (wantSudo) { DenySudoAccess(peer_id); return; @@ -1606,28 +1576,26 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt) *pkt >> bytes_A >> based_on; infostream << "Server: TOSERVER_SRP_BYTES_A received with " - << "based_on=" << int(based_on) << " and len_A=" << bytes_A.length() - << "." << std::endl; + << "based_on=" << int(based_on) << " and len_A=" + << bytes_A.length() << "." << std::endl; - AuthMechanism chosen = (based_on == 0) ? AUTH_MECHANISM_LEGACY_PASSWORD - : AUTH_MECHANISM_SRP; + AuthMechanism chosen = (based_on == 0) ? + AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP; if (wantSudo) { if (!client->isSudoMechAllowed(chosen)) { - actionstream << "Server: Player \"" << client->getName() - << "\" at " - << getPeerAddress(peer_id).serializeString() - << " tried to change password using unallowed mech " - << chosen << "." << std::endl; + actionstream << "Server: Player \"" << client->getName() << + "\" at " << getPeerAddress(peer_id).serializeString() << + " tried to change password using unallowed mech " << chosen << + "." << std::endl; DenySudoAccess(peer_id); return; } } else { if (!client->isMechAllowed(chosen)) { - actionstream << "Server: Client tried to authenticate from " - << getPeerAddress(peer_id).serializeString() - << " using unallowed mech " << chosen << "." - << std::endl; + actionstream << "Server: Client tried to authenticate from " << + getPeerAddress(peer_id).serializeString() << + " using unallowed mech " << chosen << "." << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA); return; } @@ -1640,15 +1608,13 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt) if (based_on == 0) { - generate_srp_verifier_and_salt( - client->getName(), client->enc_pwd, &verifier, &salt); + generate_srp_verifier_and_salt(client->getName(), client->enc_pwd, + &verifier, &salt); } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) { // Non-base64 errors should have been catched in the init handler - actionstream << "Server: User " << client->getName() - << " tried to log in, but srp verifier field was invalid " - "(most likely " - "invalid base64)." - << std::endl; + actionstream << "Server: User " << client->getName() << + " tried to log in, but srp verifier field was invalid (most likely " + "invalid base64)." << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL); return; } @@ -1657,17 +1623,17 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt) size_t len_B = 0; client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048, - client->getName().c_str(), (const unsigned char *)salt.c_str(), - salt.size(), (const unsigned char *)verifier.c_str(), - verifier.size(), (const unsigned char *)bytes_A.c_str(), - bytes_A.size(), NULL, 0, (unsigned char **)&bytes_B, &len_B, NULL, - NULL); + client->getName().c_str(), + (const unsigned char *) salt.c_str(), salt.size(), + (const unsigned char *) verifier.c_str(), verifier.size(), + (const unsigned char *) bytes_A.c_str(), bytes_A.size(), + NULL, 0, + (unsigned char **) &bytes_B, &len_B, NULL, NULL); if (!bytes_B) { actionstream << "Server: User " << client->getName() - << " tried to log in, SRP-6a safety check violated in _A " - "handler." - << std::endl; + << " tried to log in, SRP-6a safety check violated in _A handler." + << std::endl; if (wantSudo) { DenySudoAccess(peer_id); return; @@ -1682,7 +1648,7 @@ void Server::handleCommand_SrpBytesA(NetworkPacket *pkt) Send(&resp_pkt); } -void Server::handleCommand_SrpBytesM(NetworkPacket *pkt) +void Server::handleCommand_SrpBytesM(NetworkPacket* pkt) { session_t peer_id = pkt->getPeerId(); RemoteClient *client = getClient(peer_id, CS_Invalid); @@ -1695,17 +1661,17 @@ void Server::handleCommand_SrpBytesM(NetworkPacket *pkt) verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl; if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) { - actionstream << "Server: got SRP _M packet in wrong state " << cstate - << " from " << addr_s << ". Ignoring." << std::endl; + actionstream << "Server: got SRP _M packet in wrong state " + << cstate << " from " << addr_s + << ". Ignoring." << std::endl; return; } if (client->chosen_mech != AUTH_MECHANISM_SRP && client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) { actionstream << "Server: got SRP _M packet, while auth" - << "is going on with mech " << client->chosen_mech - << " from " << addr_s << " (wantSudo=" << wantSudo - << "). Denying." << std::endl; + << "is going on with mech " << client->chosen_mech << " from " + << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl; if (wantSudo) { DenySudoAccess(peer_id); return; @@ -1718,34 +1684,30 @@ void Server::handleCommand_SrpBytesM(NetworkPacket *pkt) std::string bytes_M; *pkt >> bytes_M; - if (srp_verifier_get_session_key_length((SRPVerifier *)client->auth_data) != - bytes_M.size()) { + if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data) + != bytes_M.size()) { actionstream << "Server: User " << playername << " at " << addr_s - << " sent bytes_M with invalid length " << bytes_M.size() - << std::endl; + << " sent bytes_M with invalid length " << bytes_M.size() << std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA); return; } unsigned char *bytes_HAMK = 0; - srp_verifier_verify_session((SRPVerifier *)client->auth_data, - (unsigned char *)bytes_M.c_str(), &bytes_HAMK); + srp_verifier_verify_session((SRPVerifier *) client->auth_data, + (unsigned char *)bytes_M.c_str(), &bytes_HAMK); if (!bytes_HAMK) { if (wantSudo) { actionstream << "Server: User " << playername << " at " << addr_s - << " tried to change their password, but supplied " - "wrong" - << " (SRP) password for authentication." - << std::endl; + << " tried to change their password, but supplied wrong" + << " (SRP) password for authentication." << std::endl; DenySudoAccess(peer_id); return; } actionstream << "Server: User " << playername << " at " << addr_s - << " supplied wrong password (auth mechanism: SRP)." - << std::endl; + << " supplied wrong password (auth mechanism: SRP)." << std::endl; m_script->on_authplayer(playername, addr_s, false); DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD); return; @@ -1756,10 +1718,9 @@ void Server::handleCommand_SrpBytesM(NetworkPacket *pkt) std::string checkpwd; // not used, but needed for passing something if (!m_script->getAuth(playername, &checkpwd, NULL)) { - actionstream << "Server: " << playername - << " cannot be authenticated (auth handler does not " - "work?)" - << std::endl; + actionstream << "Server: " << playername << + " cannot be authenticated (auth handler does not work?)" << + std::endl; DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL); return; } @@ -1780,20 +1741,20 @@ void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt) *pkt >> channel_name; session_t peer_id = pkt->getPeerId(); - NetworkPacket resp_pkt( - TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(), peer_id); + NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, + 1 + 2 + channel_name.size(), peer_id); // Send signal to client to notify join succeed or not if (g_settings->getBool("enable_mod_channels") && m_modchannel_mgr->joinChannel(channel_name, peer_id)) { - resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_OK; - infostream << "Peer " << peer_id << " joined channel " << channel_name - << std::endl; - } else { + resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK; + infostream << "Peer " << peer_id << " joined channel " << + channel_name << std::endl; + } + else { resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE; - infostream << "Peer " << peer_id << " tried to join channel " - << channel_name << ", but was already registered." - << std::endl; + infostream << "Peer " << peer_id << " tried to join channel " << + channel_name << ", but was already registered." << std::endl; } resp_pkt << channel_name; Send(&resp_pkt); @@ -1805,19 +1766,19 @@ void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt) *pkt >> channel_name; session_t peer_id = pkt->getPeerId(); - NetworkPacket resp_pkt( - TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(), peer_id); + NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, + 1 + 2 + channel_name.size(), peer_id); // Send signal to client to notify join succeed or not if (g_settings->getBool("enable_mod_channels") && m_modchannel_mgr->leaveChannel(channel_name, peer_id)) { resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK; - infostream << "Peer " << peer_id << " left channel " << channel_name - << std::endl; + infostream << "Peer " << peer_id << " left channel " << channel_name << + std::endl; } else { - resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_FAILURE; - infostream << "Peer " << peer_id << " left channel " << channel_name - << ", but was not registered." << std::endl; + resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE; + infostream << "Peer " << peer_id << " left channel " << channel_name << + ", but was not registered." << std::endl; } resp_pkt << channel_name; Send(&resp_pkt); @@ -1829,9 +1790,9 @@ void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt) *pkt >> channel_name >> channel_msg; session_t peer_id = pkt->getPeerId(); - verbosestream << "Mod channel message received from peer " << peer_id - << " on channel " << channel_name << " message: " << channel_msg - << std::endl; + verbosestream << "Mod channel message received from peer " << peer_id << + " on channel " << channel_name << " message: " << channel_msg << + std::endl; // If mod channels are not enabled, discard message if (!g_settings->getBool("enable_mod_channels")) { @@ -1841,7 +1802,7 @@ void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt) // If channel not registered, signal it and ignore message if (!m_modchannel_mgr->channelRegistered(channel_name)) { NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, - 1 + 2 + channel_name.size(), peer_id); + 1 + 2 + channel_name.size(), peer_id); resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name; Send(&resp_pkt); return; diff --git a/src/nodedef.cpp b/src/nodedef.cpp index f528a5a50..540ed6086 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -51,10 +51,9 @@ void NodeBox::reset() // default is empty fixed.clear(); // default is sign/ladder-like - wall_top = aabb3f(-BS / 2, BS / 2 - BS / 16., -BS / 2, BS / 2, BS / 2, BS / 2); - wall_bottom = aabb3f( - -BS / 2, -BS / 2, -BS / 2, BS / 2, -BS / 2 + BS / 16., BS / 2); - wall_side = aabb3f(-BS / 2, -BS / 2, -BS / 2, -BS / 2 + BS / 16., BS / 2, BS / 2); + wall_top = aabb3f(-BS/2, BS/2-BS/16., -BS/2, BS/2, BS/2, BS/2); + wall_bottom = aabb3f(-BS/2, -BS/2, -BS/2, BS/2, -BS/2+BS/16., BS/2); + wall_side = aabb3f(-BS/2, -BS/2, -BS/2, -BS/2+BS/16., BS/2, BS/2); // no default for other parts connect_top.clear(); connect_bottom.clear(); @@ -102,12 +101,12 @@ void NodeBox::serialize(std::ostream &os, u16 protocol_version) const case NODEBOX_CONNECTED: writeU8(os, type); -#define WRITEBOX(box) \ - writeU16(os, (box).size()); \ - for (const aabb3f &i : (box)) { \ - writeV3F32(os, i.MinEdge); \ - writeV3F32(os, i.MaxEdge); \ - }; +#define WRITEBOX(box) \ + writeU16(os, (box).size()); \ + for (const aabb3f &i: (box)) { \ + writeV3F32(os, i.MinEdge); \ + writeV3F32(os, i.MaxEdge); \ + }; WRITEBOX(fixed); WRITEBOX(connect_top); @@ -141,32 +140,35 @@ void NodeBox::deSerialize(std::istream &is) type = (enum NodeBoxType)readU8(is); - if (type == NODEBOX_FIXED || type == NODEBOX_LEVELED) { + if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED) + { u16 fixed_count = readU16(is); - while (fixed_count--) { + while(fixed_count--) + { aabb3f box; box.MinEdge = readV3F32(is); box.MaxEdge = readV3F32(is); fixed.push_back(box); } - } else if (type == NODEBOX_WALLMOUNTED) { + } + else if(type == NODEBOX_WALLMOUNTED) + { wall_top.MinEdge = readV3F32(is); wall_top.MaxEdge = readV3F32(is); wall_bottom.MinEdge = readV3F32(is); wall_bottom.MaxEdge = readV3F32(is); wall_side.MinEdge = readV3F32(is); wall_side.MaxEdge = readV3F32(is); - } else if (type == NODEBOX_CONNECTED) { -#define READBOXES(box) \ - { \ - count = readU16(is); \ - (box).reserve(count); \ - while (count--) { \ - v3f min = readV3F32(is); \ - v3f max = readV3F32(is); \ - (box).emplace_back(min, max); \ - }; \ } + else if (type == NODEBOX_CONNECTED) + { +#define READBOXES(box) { \ + count = readU16(is); \ + (box).reserve(count); \ + while (count--) { \ + v3f min = readV3F32(is); \ + v3f max = readV3F32(is); \ + (box).emplace_back(min, max); }; } u16 count; @@ -192,12 +194,12 @@ void NodeBox::deSerialize(std::istream &is) TileDef */ -#define TILE_FLAG_BACKFACE_CULLING (1 << 0) -#define TILE_FLAG_TILEABLE_HORIZONTAL (1 << 1) -#define TILE_FLAG_TILEABLE_VERTICAL (1 << 2) -#define TILE_FLAG_HAS_COLOR (1 << 3) -#define TILE_FLAG_HAS_SCALE (1 << 4) -#define TILE_FLAG_HAS_ALIGN_STYLE (1 << 5) +#define TILE_FLAG_BACKFACE_CULLING (1 << 0) +#define TILE_FLAG_TILEABLE_HORIZONTAL (1 << 1) +#define TILE_FLAG_TILEABLE_VERTICAL (1 << 2) +#define TILE_FLAG_HAS_COLOR (1 << 3) +#define TILE_FLAG_HAS_SCALE (1 << 4) +#define TILE_FLAG_HAS_ALIGN_STYLE (1 << 5) void TileDef::serialize(std::ostream &os, u16 protocol_version) const { @@ -233,8 +235,8 @@ void TileDef::serialize(std::ostream &os, u16 protocol_version) const writeU8(os, align_style); } -void TileDef::deSerialize( - std::istream &is, u8 contentfeatures_version, NodeDrawType drawtype) +void TileDef::deSerialize(std::istream &is, u8 contentfeatures_version, + NodeDrawType drawtype) { int version = readU8(is); if (version < 6) @@ -262,16 +264,16 @@ void TileDef::deSerialize( void TextureSettings::readSettings() { - connected_glass = g_settings->getBool("connected_glass"); - opaque_water = g_settings->getBool("opaque_water"); - bool enable_shaders = g_settings->getBool("enable_shaders"); - bool enable_bumpmapping = g_settings->getBool("enable_bumpmapping"); + connected_glass = g_settings->getBool("connected_glass"); + opaque_water = g_settings->getBool("opaque_water"); + bool enable_shaders = g_settings->getBool("enable_shaders"); + bool enable_bumpmapping = g_settings->getBool("enable_bumpmapping"); bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion"); - bool smooth_lighting = g_settings->getBool("smooth_lighting"); - enable_mesh_cache = g_settings->getBool("enable_mesh_cache"); - enable_minimap = g_settings->getBool("enable_minimap"); - node_texture_size = g_settings->getU16("texture_min_size"); - std::string leaves_style_str = g_settings->get("leaves_style"); + bool smooth_lighting = g_settings->getBool("smooth_lighting"); + enable_mesh_cache = g_settings->getBool("enable_mesh_cache"); + enable_minimap = g_settings->getBool("enable_minimap"); + node_texture_size = g_settings->getU16("texture_min_size"); + std::string leaves_style_str = g_settings->get("leaves_style"); std::string world_aligned_mode_str = g_settings->get("world_aligned_mode"); std::string autoscale_mode_str = g_settings->get("autoscale_mode"); @@ -280,7 +282,7 @@ void TextureSettings::readSettings() enable_mesh_cache = false; use_normal_texture = enable_shaders && - (enable_bumpmapping || enable_parallax_occlusion); + (enable_bumpmapping || enable_parallax_occlusion); if (leaves_style_str == "fancy") { leaves_style = LEAVES_FANCY; } else if (leaves_style_str == "simple") { @@ -386,7 +388,7 @@ void ContentFeatures::reset() liquid_alternative_source_id = CONTENT_IGNORE; liquid_viscosity = 0; liquid_renewable = true; - liquid_range = LIQUID_LEVEL_MAX + 1; + liquid_range = LIQUID_LEVEL_MAX+1; drowning = 0; light_source = 0; damage_per_second = 0; @@ -525,11 +527,11 @@ void ContentFeatures::deSerialize(std::istream &is) int value = readS16(is); groups[name] = value; } - param_type = (enum ContentParamType)readU8(is); - param_type_2 = (enum ContentParamType2)readU8(is); + param_type = (enum ContentParamType) readU8(is); + param_type_2 = (enum ContentParamType2) readU8(is); // visual - drawtype = (enum NodeDrawType)readU8(is); + drawtype = (enum NodeDrawType) readU8(is); mesh = deSerializeString(is); visual_scale = readF32(is); if (readU8(is) != 6) @@ -575,7 +577,7 @@ void ContentFeatures::deSerialize(std::istream &is) damage_per_second = readU32(is); // liquid - liquid_type = (enum LiquidType)readU8(is); + liquid_type = (enum LiquidType) readU8(is); liquid_alternative_flowing = deSerializeString(is); liquid_alternative_source = deSerializeString(is); liquid_viscosity = readU8(is); @@ -604,22 +606,22 @@ void ContentFeatures::deSerialize(std::istream &is) if (is.eof()) /* readU8 doesn't throw exceptions so we have to do this */ throw SerializationError(""); leveled_max = tmp_leveled_max; - } catch (SerializationError &e) { - }; + } catch(SerializationError &e) {}; } #ifndef SERVER -static void fillTileAttribs(ITextureSource *tsrc, TileLayer *layer, const TileSpec &tile, - const TileDef &tiledef, video::SColor color, u8 material_type, - u32 shader_id, bool backface_culling, const TextureSettings &tsettings) +static void fillTileAttribs(ITextureSource *tsrc, TileLayer *layer, + const TileSpec &tile, const TileDef &tiledef, video::SColor color, + u8 material_type, u32 shader_id, bool backface_culling, + const TextureSettings &tsettings) { - layer->shader_id = shader_id; - layer->texture = tsrc->getTextureForMesh(tiledef.name, &layer->texture_id); + layer->shader_id = shader_id; + layer->texture = tsrc->getTextureForMesh(tiledef.name, &layer->texture_id); layer->material_type = material_type; bool has_scale = tiledef.scale > 0; bool use_autoscale = tsettings.autoscale_mode == AUTOSCALE_FORCE || - (tsettings.autoscale_mode == AUTOSCALE_ENABLE && !has_scale); + (tsettings.autoscale_mode == AUTOSCALE_ENABLE && !has_scale); if (use_autoscale && layer->texture) { auto texture_size = layer->texture->getOriginalSize(); float base_size = tsettings.node_texture_size; @@ -637,8 +639,7 @@ static void fillTileAttribs(ITextureSource *tsrc, TileLayer *layer, const TileSp if (tsettings.use_normal_texture) { layer->normal_texture = tsrc->getNormalTexture(tiledef.name); } - layer->flags_texture = - tsrc->getShaderFlagsTexture(layer->normal_texture ? true : false); + layer->flags_texture = tsrc->getShaderFlagsTexture(layer->normal_texture ? true : false); // Material flags layer->material_flags = 0; @@ -683,11 +684,10 @@ static void fillTileAttribs(ITextureSource *tsrc, TileLayer *layer, const TileSp os.str(""); os << tiledef.name; - tiledef.animation.getTextureModifer( - os, layer->texture->getOriginalSize(), i); + tiledef.animation.getTextureModifer(os, + layer->texture->getOriginalSize(), i); - frame.texture = tsrc->getTextureForMesh( - os.str(), &frame.texture_id); + frame.texture = tsrc->getTextureForMesh(os.str(), &frame.texture_id); if (layer->normal_texture) frame.normal_texture = tsrc->getNormalTexture(os.str()); frame.flags_texture = layer->flags_texture; @@ -714,8 +714,7 @@ bool isWorldAligned(AlignStyle style, WorldAlignMode mode, NodeDrawType drawtype } void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc, - scene::IMeshManipulator *meshmanip, Client *client, - const TextureSettings &tsettings) + scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings) { // minimap pixel color - the average color of a texture if (tsettings.enable_minimap && !tiledef[0].name.empty()) @@ -739,13 +738,14 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc bool is_liquid = false; - u8 material_type = (alpha == 255) ? TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA; + u8 material_type = (alpha == 255) ? + TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA; switch (drawtype) { default: case NDT_NORMAL: - material_type = (alpha == 255) ? TILE_MATERIAL_OPAQUE - : TILE_MATERIAL_ALPHA; + material_type = (alpha == 255) ? + TILE_MATERIAL_OPAQUE : TILE_MATERIAL_ALPHA; solidness = 2; break; case NDT_AIRLIKE: @@ -776,8 +776,7 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc case NDT_GLASSLIKE_FRAMED_OPTIONAL: solidness = 0; visual_solidness = 1; - drawtype = tsettings.connected_glass ? NDT_GLASSLIKE_FRAMED - : NDT_GLASSLIKE; + drawtype = tsettings.connected_glass ? NDT_GLASSLIKE_FRAMED : NDT_GLASSLIKE; break; case NDT_ALLFACES: solidness = 0; @@ -841,11 +840,11 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc correctAlpha(tdef_spec, CF_SPECIAL_COUNT); if (waving == 3) { - material_type = (alpha == 255) ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE - : TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT; + material_type = (alpha == 255) ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE : + TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT; } else { - material_type = (alpha == 255) ? TILE_MATERIAL_LIQUID_OPAQUE - : TILE_MATERIAL_LIQUID_TRANSPARENT; + material_type = (alpha == 255) ? TILE_MATERIAL_LIQUID_OPAQUE : + TILE_MATERIAL_LIQUID_TRANSPARENT; } } @@ -857,21 +856,19 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc else if (overlay_material == TILE_MATERIAL_LIQUID_OPAQUE) overlay_material = TILE_MATERIAL_LIQUID_TRANSPARENT; - u32 overlay_shader = - shdsrc->getShader("nodes_shader", overlay_material, drawtype); + u32 overlay_shader = shdsrc->getShader("nodes_shader", overlay_material, drawtype); // Tiles (fill in f->tiles[]) for (u16 j = 0; j < 6; j++) { tiles[j].world_aligned = isWorldAligned(tdef[j].align_style, tsettings.world_aligned_mode, drawtype); - fillTileAttribs(tsrc, &tiles[j].layers[0], tiles[j], tdef[j], color, - material_type, tile_shader, tdef[j].backface_culling, - tsettings); + fillTileAttribs(tsrc, &tiles[j].layers[0], tiles[j], tdef[j], + color, material_type, tile_shader, + tdef[j].backface_culling, tsettings); if (!tdef_overlay[j].name.empty()) - fillTileAttribs(tsrc, &tiles[j].layers[1], tiles[j], - tdef_overlay[j], color, overlay_material, - overlay_shader, tdef[j].backface_culling, - tsettings); + fillTileAttribs(tsrc, &tiles[j].layers[1], tiles[j], tdef_overlay[j], + color, overlay_material, overlay_shader, + tdef[j].backface_culling, tsettings); } u8 special_material = material_type; @@ -881,16 +878,16 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc else if (waving == 2) special_material = TILE_MATERIAL_WAVING_LEAVES; } - u32 special_shader = - shdsrc->getShader("nodes_shader", special_material, drawtype); + u32 special_shader = shdsrc->getShader("nodes_shader", special_material, drawtype); // Special tiles (fill in f->special_tiles[]) for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) - fillTileAttribs(tsrc, &special_tiles[j].layers[0], special_tiles[j], - tdef_spec[j], color, special_material, special_shader, + fillTileAttribs(tsrc, &special_tiles[j].layers[0], special_tiles[j], tdef_spec[j], + color, special_material, special_shader, tdef_spec[j].backface_culling, tsettings); - if (param_type_2 == CPT2_COLOR || param_type_2 == CPT2_COLORED_FACEDIR || + if (param_type_2 == CPT2_COLOR || + param_type_2 == CPT2_COLORED_FACEDIR || param_type_2 == CPT2_COLORED_WALLMOUNTED) palette = tsrc->getPalette(palette_name); @@ -898,7 +895,7 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc // Meshnode drawtype // Read the mesh and apply scale mesh_ptr[0] = client->getMesh(mesh); - if (mesh_ptr[0]) { + if (mesh_ptr[0]){ v3f scale = v3f(1.0, 1.0, 1.0) * BS * visual_scale; scaleMesh(mesh_ptr[0], scale); recalculateBoundingBox(mesh_ptr[0]); @@ -906,20 +903,20 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc } } - // Cache 6dfacedir and wallmounted rotated clones of meshes + //Cache 6dfacedir and wallmounted rotated clones of meshes if (tsettings.enable_mesh_cache && mesh_ptr[0] && - (param_type_2 == CPT2_FACEDIR || - param_type_2 == CPT2_COLORED_FACEDIR)) { + (param_type_2 == CPT2_FACEDIR + || param_type_2 == CPT2_COLORED_FACEDIR)) { for (u16 j = 1; j < 24; j++) { mesh_ptr[j] = cloneMesh(mesh_ptr[0]); rotateMeshBy6dFacedir(mesh_ptr[j], j); recalculateBoundingBox(mesh_ptr[j]); meshmanip->recalculateNormals(mesh_ptr[j], true, false); } - } else if (tsettings.enable_mesh_cache && mesh_ptr[0] && - (param_type_2 == CPT2_WALLMOUNTED || - param_type_2 == CPT2_COLORED_WALLMOUNTED)) { - static const u8 wm_to_6d[6] = {20, 0, 16 + 1, 12 + 3, 8, 4 + 2}; + } else if (tsettings.enable_mesh_cache && mesh_ptr[0] + && (param_type_2 == CPT2_WALLMOUNTED || + param_type_2 == CPT2_COLORED_WALLMOUNTED)) { + static const u8 wm_to_6d[6] = { 20, 0, 16 + 1, 12 + 3, 8, 4 + 2 }; for (u16 j = 1; j < 6; j++) { mesh_ptr[j] = cloneMesh(mesh_ptr[0]); rotateMeshBy6dFacedir(mesh_ptr[j], wm_to_6d[j]); @@ -937,11 +934,15 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc NodeDefManager */ + + + NodeDefManager::NodeDefManager() { clear(); } + NodeDefManager::~NodeDefManager() { #ifndef SERVER @@ -954,6 +955,7 @@ NodeDefManager::~NodeDefManager() #endif } + void NodeDefManager::clear() { m_content_features.clear(); @@ -961,8 +963,8 @@ void NodeDefManager::clear() m_name_id_mapping_with_aliases.clear(); m_group_to_items.clear(); m_next_id = 0; - m_selection_box_union.reset(0, 0, 0); - m_selection_box_int_union.reset(0, 0, 0); + m_selection_box_union.reset(0,0,0); + m_selection_box_int_union.reset(0,0,0); resetNodeResolveState(); @@ -985,17 +987,17 @@ void NodeDefManager::clear() // Set CONTENT_AIR { ContentFeatures f; - f.name = "air"; - f.drawtype = NDT_AIRLIKE; - f.param_type = CPT_LIGHT; - f.light_propagates = true; + f.name = "air"; + f.drawtype = NDT_AIRLIKE; + f.param_type = CPT_LIGHT; + f.light_propagates = true; f.sunlight_propagates = true; - f.walkable = false; - f.pointable = false; - f.diggable = false; - f.buildable_to = true; - f.floodable = true; - f.is_ground_content = true; + f.walkable = false; + f.pointable = false; + f.diggable = false; + f.buildable_to = true; + f.floodable = true; + f.is_ground_content = true; // Insert directly into containers content_t c = CONTENT_AIR; m_content_features[c] = f; @@ -1005,16 +1007,16 @@ void NodeDefManager::clear() // Set CONTENT_IGNORE { ContentFeatures f; - f.name = "ignore"; - f.drawtype = NDT_AIRLIKE; - f.param_type = CPT_NONE; - f.light_propagates = false; + f.name = "ignore"; + f.drawtype = NDT_AIRLIKE; + f.param_type = CPT_NONE; + f.light_propagates = false; f.sunlight_propagates = false; - f.walkable = false; - f.pointable = false; - f.diggable = false; - f.buildable_to = true; // A way to remove accidental CONTENT_IGNOREs - f.is_ground_content = true; + f.walkable = false; + f.pointable = false; + f.diggable = false; + f.buildable_to = true; // A way to remove accidental CONTENT_IGNOREs + f.is_ground_content = true; // Insert directly into containers content_t c = CONTENT_IGNORE; m_content_features[c] = f; @@ -1022,16 +1024,18 @@ void NodeDefManager::clear() } } + bool NodeDefManager::getId(const std::string &name, content_t &result) const { - std::unordered_map::const_iterator i = - m_name_id_mapping_with_aliases.find(name); - if (i == m_name_id_mapping_with_aliases.end()) + std::unordered_map::const_iterator + i = m_name_id_mapping_with_aliases.find(name); + if(i == m_name_id_mapping_with_aliases.end()) return false; result = i->second; return true; } + content_t NodeDefManager::getId(const std::string &name) const { content_t id = CONTENT_IGNORE; @@ -1039,10 +1043,12 @@ content_t NodeDefManager::getId(const std::string &name) const return id; } -bool NodeDefManager::getIds(const std::string &name, std::vector &result) const + +bool NodeDefManager::getIds(const std::string &name, + std::vector &result) const { - // TimeTaker t("getIds", NULL, PRECISION_MICRO); - if (name.substr(0, 6) != "group:") { + //TimeTaker t("getIds", NULL, PRECISION_MICRO); + if (name.substr(0,6) != "group:") { content_t id = CONTENT_IGNORE; bool exists = getId(name, id); if (exists) @@ -1051,28 +1057,31 @@ bool NodeDefManager::getIds(const std::string &name, std::vector &res } std::string group = name.substr(6); - std::unordered_map>::const_iterator i = - m_group_to_items.find(group); + std::unordered_map>::const_iterator + i = m_group_to_items.find(group); if (i == m_group_to_items.end()) return true; const std::vector &items = i->second; result.insert(result.end(), items.begin(), items.end()); - // printf("getIds: %dus\n", t.stop()); + //printf("getIds: %dus\n", t.stop()); return true; } -const ContentFeatures &NodeDefManager::get(const std::string &name) const + +const ContentFeatures& NodeDefManager::get(const std::string &name) const { content_t id = CONTENT_UNKNOWN; getId(name, id); return get(id); } + // returns CONTENT_IGNORE if no free ID found content_t NodeDefManager::allocateId() { - for (content_t id = m_next_id; id >= m_next_id; // overflow? + for (content_t id = m_next_id; + id >= m_next_id; // overflow? ++id) { while (id >= m_content_features.size()) { m_content_features.emplace_back(); @@ -1088,6 +1097,7 @@ content_t NodeDefManager::allocateId() return CONTENT_IGNORE; } + /*! * Returns the smallest box that contains all boxes * in the vector. Box_union is expanded. @@ -1101,6 +1111,7 @@ void boxVectorUnion(const std::vector &boxes, aabb3f *box_union) } } + /*! * Returns a box that contains the nodebox in every case. * The argument node_union is expanded. @@ -1110,27 +1121,52 @@ void boxVectorUnion(const std::vector &boxes, aabb3f *box_union) * @param[in, out] box_union the union of the arguments */ void getNodeBoxUnion(const NodeBox &nodebox, const ContentFeatures &features, - aabb3f *box_union) + aabb3f *box_union) { - switch (nodebox.type) { - case NODEBOX_FIXED: - case NODEBOX_LEVELED: { - // Raw union - aabb3f half_processed(0, 0, 0, 0, 0, 0); - boxVectorUnion(nodebox.fixed, &half_processed); - // Set leveled boxes to maximal - if (nodebox.type == NODEBOX_LEVELED) { - half_processed.MaxEdge.Y = +BS / 2; - } - if (features.param_type_2 == CPT2_FACEDIR || - features.param_type_2 == CPT2_COLORED_FACEDIR) { - // Get maximal coordinate - f32 coords[] = {fabsf(half_processed.MinEdge.X), + switch(nodebox.type) { + case NODEBOX_FIXED: + case NODEBOX_LEVELED: { + // Raw union + aabb3f half_processed(0, 0, 0, 0, 0, 0); + boxVectorUnion(nodebox.fixed, &half_processed); + // Set leveled boxes to maximal + if (nodebox.type == NODEBOX_LEVELED) { + half_processed.MaxEdge.Y = +BS / 2; + } + if (features.param_type_2 == CPT2_FACEDIR || + features.param_type_2 == CPT2_COLORED_FACEDIR) { + // Get maximal coordinate + f32 coords[] = { + fabsf(half_processed.MinEdge.X), fabsf(half_processed.MinEdge.Y), fabsf(half_processed.MinEdge.Z), fabsf(half_processed.MaxEdge.X), fabsf(half_processed.MaxEdge.Y), - fabsf(half_processed.MaxEdge.Z)}; + fabsf(half_processed.MaxEdge.Z) }; + f32 max = 0; + for (float coord : coords) { + if (max < coord) { + max = coord; + } + } + // Add the union of all possible rotated boxes + box_union->addInternalPoint(-max, -max, -max); + box_union->addInternalPoint(+max, +max, +max); + } else { + box_union->addInternalBox(half_processed); + } + break; + } + case NODEBOX_WALLMOUNTED: { + // Add fix boxes + box_union->addInternalBox(nodebox.wall_top); + box_union->addInternalBox(nodebox.wall_bottom); + // Find maximal coordinate in the X-Z plane + f32 coords[] = { + fabsf(nodebox.wall_side.MinEdge.X), + fabsf(nodebox.wall_side.MinEdge.Z), + fabsf(nodebox.wall_side.MaxEdge.X), + fabsf(nodebox.wall_side.MaxEdge.Z) }; f32 max = 0; for (float coord : coords) { if (max < coord) { @@ -1138,76 +1174,55 @@ void getNodeBoxUnion(const NodeBox &nodebox, const ContentFeatures &features, } } // Add the union of all possible rotated boxes - box_union->addInternalPoint(-max, -max, -max); - box_union->addInternalPoint(+max, +max, +max); - } else { - box_union->addInternalBox(half_processed); + box_union->addInternalPoint(-max, nodebox.wall_side.MinEdge.Y, -max); + box_union->addInternalPoint(max, nodebox.wall_side.MaxEdge.Y, max); + break; } - break; - } - case NODEBOX_WALLMOUNTED: { - // Add fix boxes - box_union->addInternalBox(nodebox.wall_top); - box_union->addInternalBox(nodebox.wall_bottom); - // Find maximal coordinate in the X-Z plane - f32 coords[] = {fabsf(nodebox.wall_side.MinEdge.X), - fabsf(nodebox.wall_side.MinEdge.Z), - fabsf(nodebox.wall_side.MaxEdge.X), - fabsf(nodebox.wall_side.MaxEdge.Z)}; - f32 max = 0; - for (float coord : coords) { - if (max < coord) { - max = coord; - } + case NODEBOX_CONNECTED: { + // Add all possible connected boxes + boxVectorUnion(nodebox.fixed, box_union); + boxVectorUnion(nodebox.connect_top, box_union); + boxVectorUnion(nodebox.connect_bottom, box_union); + boxVectorUnion(nodebox.connect_front, box_union); + boxVectorUnion(nodebox.connect_left, box_union); + boxVectorUnion(nodebox.connect_back, box_union); + boxVectorUnion(nodebox.connect_right, box_union); + boxVectorUnion(nodebox.disconnected_top, box_union); + boxVectorUnion(nodebox.disconnected_bottom, box_union); + boxVectorUnion(nodebox.disconnected_front, box_union); + boxVectorUnion(nodebox.disconnected_left, box_union); + boxVectorUnion(nodebox.disconnected_back, box_union); + boxVectorUnion(nodebox.disconnected_right, box_union); + boxVectorUnion(nodebox.disconnected, box_union); + boxVectorUnion(nodebox.disconnected_sides, box_union); + break; + } + default: { + // NODEBOX_REGULAR + box_union->addInternalPoint(-BS / 2, -BS / 2, -BS / 2); + box_union->addInternalPoint(+BS / 2, +BS / 2, +BS / 2); } - // Add the union of all possible rotated boxes - box_union->addInternalPoint(-max, nodebox.wall_side.MinEdge.Y, -max); - box_union->addInternalPoint(max, nodebox.wall_side.MaxEdge.Y, max); - break; - } - case NODEBOX_CONNECTED: { - // Add all possible connected boxes - boxVectorUnion(nodebox.fixed, box_union); - boxVectorUnion(nodebox.connect_top, box_union); - boxVectorUnion(nodebox.connect_bottom, box_union); - boxVectorUnion(nodebox.connect_front, box_union); - boxVectorUnion(nodebox.connect_left, box_union); - boxVectorUnion(nodebox.connect_back, box_union); - boxVectorUnion(nodebox.connect_right, box_union); - boxVectorUnion(nodebox.disconnected_top, box_union); - boxVectorUnion(nodebox.disconnected_bottom, box_union); - boxVectorUnion(nodebox.disconnected_front, box_union); - boxVectorUnion(nodebox.disconnected_left, box_union); - boxVectorUnion(nodebox.disconnected_back, box_union); - boxVectorUnion(nodebox.disconnected_right, box_union); - boxVectorUnion(nodebox.disconnected, box_union); - boxVectorUnion(nodebox.disconnected_sides, box_union); - break; - } - default: { - // NODEBOX_REGULAR - box_union->addInternalPoint(-BS / 2, -BS / 2, -BS / 2); - box_union->addInternalPoint(+BS / 2, +BS / 2, +BS / 2); - } } } + inline void NodeDefManager::fixSelectionBoxIntUnion() { - m_selection_box_int_union.MinEdge.X = - floorf(m_selection_box_union.MinEdge.X / BS + 0.5f); - m_selection_box_int_union.MinEdge.Y = - floorf(m_selection_box_union.MinEdge.Y / BS + 0.5f); - m_selection_box_int_union.MinEdge.Z = - floorf(m_selection_box_union.MinEdge.Z / BS + 0.5f); - m_selection_box_int_union.MaxEdge.X = - ceilf(m_selection_box_union.MaxEdge.X / BS - 0.5f); - m_selection_box_int_union.MaxEdge.Y = - ceilf(m_selection_box_union.MaxEdge.Y / BS - 0.5f); - m_selection_box_int_union.MaxEdge.Z = - ceilf(m_selection_box_union.MaxEdge.Z / BS - 0.5f); + m_selection_box_int_union.MinEdge.X = floorf( + m_selection_box_union.MinEdge.X / BS + 0.5f); + m_selection_box_int_union.MinEdge.Y = floorf( + m_selection_box_union.MinEdge.Y / BS + 0.5f); + m_selection_box_int_union.MinEdge.Z = floorf( + m_selection_box_union.MinEdge.Z / BS + 0.5f); + m_selection_box_int_union.MaxEdge.X = ceilf( + m_selection_box_union.MaxEdge.X / BS - 0.5f); + m_selection_box_int_union.MaxEdge.Y = ceilf( + m_selection_box_union.MaxEdge.Y / BS - 0.5f); + m_selection_box_int_union.MaxEdge.Z = ceilf( + m_selection_box_union.MaxEdge.Z / BS - 0.5f); } + void NodeDefManager::eraseIdFromGroups(content_t id) { // For all groups in m_group_to_items... @@ -1227,20 +1242,21 @@ void NodeDefManager::eraseIdFromGroups(content_t id) } } + // IWritableNodeDefManager content_t NodeDefManager::set(const std::string &name, const ContentFeatures &d) { ContentFeatures def = d; - + // Pre-conditions assert(name != ""); assert(name != "ignore"); assert(name == def.name); content_t id = CONTENT_IGNORE; - + if (m_name_id_mapping.getId(name, id)) { -#ifndef SERVER +#ifndef SERVER ContentFeatures old_def = get(name); for (u32 j = 0; j < 6; j++) if (def.tiledef[j].name.empty()) @@ -1257,8 +1273,7 @@ content_t NodeDefManager::set(const std::string &name, const ContentFeatures &d) id = allocateId(); if (id == CONTENT_IGNORE) { warningstream << "NodeDefManager: Absolute " - "limit reached" - << std::endl; + "limit reached" << std::endl; return CONTENT_IGNORE; } assert(id != CONTENT_IGNORE); @@ -1271,7 +1286,7 @@ content_t NodeDefManager::set(const std::string &name, const ContentFeatures &d) m_content_features[id] = def; verbosestream << "NodeDefManager: registering content id \"" << id - << "\": name=\"" << def.name << "\"" << std::endl; + << "\": name=\"" << def.name << "\""< all; @@ -1317,7 +1335,8 @@ void NodeDefManager::updateAliases(IItemDefManager *idef) const std::string &convert_to = idef->getAlias(name); content_t id; if (m_name_id_mapping.getId(convert_to, id)) { - m_name_id_mapping_with_aliases.insert(std::make_pair(name, id)); + m_name_id_mapping_with_aliases.insert( + std::make_pair(name, id)); } } } @@ -1325,10 +1344,9 @@ void NodeDefManager::updateAliases(IItemDefManager *idef) void NodeDefManager::applyTextureOverrides(const std::vector &overrides) { infostream << "NodeDefManager::applyTextureOverrides(): Applying " - "overrides to textures" - << std::endl; + "overrides to textures" << std::endl; - for (const TextureOverride &texture_override : overrides) { + for (const TextureOverride& texture_override : overrides) { content_t id; if (!getId(texture_override.id, id)) continue; // Ignore unknown node @@ -1356,20 +1374,18 @@ void NodeDefManager::applyTextureOverrides(const std::vector &o } void NodeDefManager::updateTextures(IGameDef *gamedef, - void (*progress_callback)( - void *progress_args, u32 progress, u32 max_progress), - void *progress_callback_args) + void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress), + void *progress_callback_args) { #ifndef SERVER infostream << "NodeDefManager::updateTextures(): Updating " - "textures in node definitions" - << std::endl; + "textures in node definitions" << std::endl; Client *client = (Client *)gamedef; ITextureSource *tsrc = client->tsrc(); IShaderSource *shdsrc = client->getShaderSource(); scene::IMeshManipulator *meshmanip = - RenderingEngine::get_scene_manager()->getMeshManipulator(); + RenderingEngine::get_scene_manager()->getMeshManipulator(); TextureSettings tsettings; tsettings.readSettings(); @@ -1389,7 +1405,8 @@ void NodeDefManager::serialize(std::ostream &os, u16 protocol_version) const u16 count = 0; std::ostringstream os2(std::ios::binary); for (u32 i = 0; i < m_content_features.size(); i++) { - if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) + if (i == CONTENT_IGNORE || i == CONTENT_AIR + || i == CONTENT_UNKNOWN) continue; const ContentFeatures *f = &m_content_features[i]; if (f->name.empty()) @@ -1399,7 +1416,7 @@ void NodeDefManager::serialize(std::ostream &os, u16 protocol_version) const // strict version incompatibilities std::ostringstream wrapper_os(std::ios::binary); f->serialize(wrapper_os, protocol_version); - os2 << serializeString(wrapper_os.str()); + os2<m_ndef = this; @@ -1486,6 +1504,7 @@ void NodeDefManager::pendNodeResolve(NodeResolver *nr) const m_pending_resolve_callbacks.push_back(nr); } + bool NodeDefManager::cancelNodeResolveCallback(NodeResolver *nr) const { size_t len = m_pending_resolve_callbacks.size(); @@ -1502,6 +1521,7 @@ bool NodeDefManager::cancelNodeResolveCallback(NodeResolver *nr) const return false; } + void NodeDefManager::runNodeResolveCallbacks() { for (size_t i = 0; i != m_pending_resolve_callbacks.size(); i++) { @@ -1512,6 +1532,7 @@ void NodeDefManager::runNodeResolveCallbacks() m_pending_resolve_callbacks.clear(); } + void NodeDefManager::resetNodeResolveState() { m_node_registration_complete = false; @@ -1529,10 +1550,8 @@ void NodeDefManager::resolveCrossrefs() { for (ContentFeatures &f : m_content_features) { if (f.liquid_type != LIQUID_NONE) { - f.liquid_alternative_flowing_id = - getId(f.liquid_alternative_flowing); - f.liquid_alternative_source_id = - getId(f.liquid_alternative_source); + f.liquid_alternative_flowing_id = getId(f.liquid_alternative_flowing); + f.liquid_alternative_source_id = getId(f.liquid_alternative_source); continue; } if (f.drawtype != NDT_NODEBOX || f.node_box.type != NODEBOX_CONNECTED) @@ -1545,7 +1564,8 @@ void NodeDefManager::resolveCrossrefs() } } -bool NodeDefManager::nodeboxConnects(MapNode from, MapNode to, u8 connect_face) const +bool NodeDefManager::nodeboxConnects(MapNode from, MapNode to, + u8 connect_face) const { const ContentFeatures &f1 = get(from); @@ -1565,24 +1585,22 @@ bool NodeDefManager::nodeboxConnects(MapNode from, MapNode to, u8 connect_face) // does to node declare usable faces? if (f2.connect_sides > 0) { if ((f2.param_type_2 == CPT2_FACEDIR || - f2.param_type_2 == CPT2_COLORED_FACEDIR) && - (connect_face >= 4)) { - static const u8 rot[33 * 4] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, - 32, 16, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, // 4 - back - 8, 4, 32, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, // 8 - right - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 8, 4, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, // 16 - front - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 16, - 8, 4 // 32 - left - }; - return (f2.connect_sides & - rot[(connect_face * 4) + (to.param2 & 0x1F)]); + f2.param_type_2 == CPT2_COLORED_FACEDIR) + && (connect_face >= 4)) { + static const u8 rot[33 * 4] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 4, 32, 16, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 4 - back + 8, 4, 32, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 8 - right + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 8, 4, 32, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 16 - front + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 32, 16, 8, 4 // 32 - left + }; + return (f2.connect_sides + & rot[(connect_face * 4) + (to.param2 & 0x1F)]); } return (f2.connect_sides & connect_face); } @@ -1600,16 +1618,18 @@ NodeResolver::NodeResolver() m_nnlistsizes.reserve(4); } + NodeResolver::~NodeResolver() { if (!m_resolve_done && m_ndef) m_ndef->cancelNodeResolveCallback(this); } + void NodeResolver::cloneTo(NodeResolver *res) const { FATAL_ERROR_IF(!m_resolve_done, "NodeResolver can only be cloned" - " after resolving has completed"); + " after resolving has completed"); /* We don't actually do anything significant. Since the node resolving has * already completed, the class that called us will already have the * resolved IDs in its data structures (which it copies on its own) */ @@ -1617,9 +1637,10 @@ void NodeResolver::cloneTo(NodeResolver *res) const res->m_resolve_done = true; } + void NodeResolver::nodeResolveInternal() { - m_nodenames_idx = 0; + m_nodenames_idx = 0; m_nnlistsizes_idx = 0; resolveNodeNames(); @@ -1629,8 +1650,9 @@ void NodeResolver::nodeResolveInternal() m_nnlistsizes.clear(); } -bool NodeResolver::getIdFromNrBacklog(content_t *result_out, const std::string &node_alt, - content_t c_fallback, bool error_on_fallback) + +bool NodeResolver::getIdFromNrBacklog(content_t *result_out, + const std::string &node_alt, content_t c_fallback, bool error_on_fallback) { if (m_nodenames_idx == m_nodenames.size()) { *result_out = c_fallback; @@ -1649,8 +1671,8 @@ bool NodeResolver::getIdFromNrBacklog(content_t *result_out, const std::string & if (!success) { if (error_on_fallback) - errorstream << "NodeResolver: failed to resolve node name '" - << name << "'." << std::endl; + errorstream << "NodeResolver: failed to resolve node name '" << name + << "'." << std::endl; c = c_fallback; } @@ -1658,8 +1680,9 @@ bool NodeResolver::getIdFromNrBacklog(content_t *result_out, const std::string & return success; } + bool NodeResolver::getIdsFromNrBacklog(std::vector *result_out, - bool all_required, content_t c_fallback) + bool all_required, content_t c_fallback) { bool success = true; @@ -1679,13 +1702,12 @@ bool NodeResolver::getIdsFromNrBacklog(std::vector *result_out, content_t c; std::string &name = m_nodenames[m_nodenames_idx++]; - if (name.substr(0, 6) != "group:") { + if (name.substr(0,6) != "group:") { if (m_ndef->getId(name, c)) { result_out->push_back(c); } else if (all_required) { - errorstream << "NodeResolver: failed to resolve node " - "name '" - << name << "'." << std::endl; + errorstream << "NodeResolver: failed to resolve node name '" + << name << "'." << std::endl; result_out->push_back(c_fallback); success = false; } diff --git a/src/nodedef.h b/src/nodedef.h index b1492588a..cf03abaae 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -31,8 +31,8 @@ with this program; if not, write to the Free Software Foundation, Inc., class Client; #endif #include "itemgroup.h" -#include "sound.h" // SimpleSoundSpec -#include "constants.h" // BS +#include "sound.h" // SimpleSoundSpec +#include "constants.h" // BS #include "texture_override.h" // TextureOverride #include "tileanimation.h" @@ -87,11 +87,10 @@ enum LiquidType enum NodeBoxType { - NODEBOX_REGULAR, // Regular block; allows buildable_to - NODEBOX_FIXED, // Static separately defined box(es) + NODEBOX_REGULAR, // Regular block; allows buildable_to + NODEBOX_FIXED, // Static separately defined box(es) NODEBOX_WALLMOUNTED, // Box for wall mounted nodes; (top, bottom, side) - NODEBOX_LEVELED, // Same as fixed, but with dynamic height from param2. for snow, - // ... + NODEBOX_LEVELED, // Same as fixed, but with dynamic height from param2. for snow, ... NODEBOX_CONNECTED, // optionally draws nodeboxes if a neighbor node attaches }; @@ -121,7 +120,8 @@ struct NodeBox std::vector disconnected; std::vector disconnected_sides; - NodeBox() { reset(); } + NodeBox() + { reset(); } void reset(); void serialize(std::ostream &os, u16 protocol_version) const; @@ -131,30 +131,26 @@ struct NodeBox struct MapNode; class NodeMetadata; -enum LeavesStyle -{ +enum LeavesStyle { LEAVES_FANCY, LEAVES_SIMPLE, LEAVES_OPAQUE, }; -enum AutoScale : u8 -{ +enum AutoScale : u8 { AUTOSCALE_DISABLE, AUTOSCALE_ENABLE, AUTOSCALE_FORCE, }; -enum WorldAlignMode : u8 -{ +enum WorldAlignMode : u8 { WORLDALIGN_DISABLE, WORLDALIGN_ENABLE, WORLDALIGN_FORCE, WORLDALIGN_FORCE_NODEBOX, }; -class TextureSettings -{ +class TextureSettings { public: LeavesStyle leaves_style; WorldAlignMode world_aligned_mode; @@ -218,12 +214,11 @@ enum NodeDrawType }; // Mesh options for NDT_PLANTLIKE with CPT2_MESHOPTIONS -static const u8 MO_MASK_STYLE = 0x07; -static const u8 MO_BIT_RANDOM_OFFSET = 0x08; -static const u8 MO_BIT_SCALE_SQRT2 = 0x10; +static const u8 MO_MASK_STYLE = 0x07; +static const u8 MO_BIT_RANDOM_OFFSET = 0x08; +static const u8 MO_BIT_SCALE_SQRT2 = 0x10; static const u8 MO_BIT_RANDOM_OFFSET_Y = 0x20; -enum PlantlikeStyle -{ +enum PlantlikeStyle { PLANT_STYLE_CROSS, PLANT_STYLE_CROSS2, PLANT_STYLE_STAR, @@ -231,8 +226,7 @@ enum PlantlikeStyle PLANT_STYLE_HASH2, }; -enum AlignStyle : u8 -{ +enum AlignStyle : u8 { ALIGN_STYLE_NODE, ALIGN_STYLE_WORLD, ALIGN_STYLE_USER_DEFINED, @@ -257,11 +251,14 @@ struct TileDef struct TileAnimationParams animation; - TileDef() { animation.type = TAT_NONE; } + TileDef() + { + animation.type = TAT_NONE; + } void serialize(std::ostream &os, u16 protocol_version) const; void deSerialize(std::istream &is, u8 contentfeatures_version, - NodeDrawType drawtype); + NodeDrawType drawtype); }; #define CF_SPECIAL_COUNT 6 @@ -278,7 +275,7 @@ struct ContentFeatures // Special tiles // - Currently used for flowing liquids TileSpec special_tiles[CF_SPECIAL_COUNT]; - u8 solidness; // Used when choosing which face is drawn + u8 solidness; // Used when choosing which face is drawn u8 visual_solidness; // When solidness=0, this tells how it looks like bool backface_culling; #endif @@ -294,7 +291,7 @@ struct ContentFeatures // --- GENERAL PROPERTIES --- - std::string name; // "" = undefined node + std::string name; // "" = undefined node ItemGroupList groups; // Same as in itemdef // Type of MapNode::param1 ContentParamType param_type; @@ -428,11 +425,11 @@ struct ContentFeatures /* Some handy methods */ - bool isLiquid() const { return (liquid_type != LIQUID_NONE); } - bool sameLiquid(const ContentFeatures &f) const - { - if (!isLiquid() || !f.isLiquid()) - return false; + bool isLiquid() const{ + return (liquid_type != LIQUID_NONE); + } + bool sameLiquid(const ContentFeatures &f) const{ + if(!isLiquid() || !f.isLiquid()) return false; return (liquid_alternative_flowing_id == f.liquid_alternative_flowing_id); } @@ -443,8 +440,7 @@ struct ContentFeatures #ifndef SERVER void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc, - scene::IMeshManipulator *meshmanip, Client *client, - const TextureSettings &tsettings); + scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings); #endif }; @@ -460,8 +456,7 @@ struct ContentFeatures * functions only get `const` pointers to it, to prevent modification of * registered nodes. */ -class NodeDefManager -{ +class NodeDefManager { public: /*! * Creates a NodeDefManager, and registers three ContentFeatures: @@ -476,11 +471,10 @@ class NodeDefManager * @return properties of the given content type, or \ref CONTENT_UNKNOWN * if the given content type is not registered. */ - inline const ContentFeatures &get(content_t c) const - { - return c < m_content_features.size() - ? m_content_features[c] - : m_content_features[CONTENT_UNKNOWN]; + inline const ContentFeatures& get(content_t c) const { + return + c < m_content_features.size() ? + m_content_features[c] : m_content_features[CONTENT_UNKNOWN]; } /*! @@ -489,8 +483,7 @@ class NodeDefManager * @return properties of the given node or @ref CONTENT_UNKNOWN if the * given content type is not registered. */ - inline const ContentFeatures &get(const MapNode &n) const - { + inline const ContentFeatures& get(const MapNode &n) const { return get(n.getContent()); } @@ -500,7 +493,7 @@ class NodeDefManager * @return properties of the given node or @ref CONTENT_UNKNOWN if * not found */ - const ContentFeatures &get(const std::string &name) const; + const ContentFeatures& get(const std::string &name) const; /*! * Returns the content ID for the given name. @@ -533,8 +526,7 @@ class NodeDefManager * contains all nodes' selection boxes. The returned box might be larger * than the minimal size if the largest node is removed from the manager. */ - inline core::aabbox3d getSelectionBoxIntUnion() const - { + inline core::aabbox3d getSelectionBoxIntUnion() const { return m_selection_box_int_union; } @@ -547,7 +539,8 @@ class NodeDefManager * Bits: +y (least significant), -y, -z, -x, +z, +x (most significant). * @return true if the node connects, false otherwise */ - bool nodeboxConnects(MapNode from, MapNode to, u8 connect_face) const; + bool nodeboxConnects(MapNode from, MapNode to, + u8 connect_face) const; /*! * Registers a NodeResolver to wait for the registration of @@ -612,9 +605,8 @@ class NodeDefManager * @param progress_cbk_args passed to the callback function */ void updateTextures(IGameDef *gamedef, - void (*progress_cbk)(void *progress_args, u32 progress, - u32 max_progress), - void *progress_cbk_args); + void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress), + void *progress_cbk_args); /*! * Writes the content of this manager to the given output stream. @@ -633,8 +625,7 @@ class NodeDefManager * Used to indicate that node registration has finished. * @param completed tells whether registration is complete */ - inline void setNodeRegistrationStatus(bool completed) - { + inline void setNodeRegistrationStatus(bool completed) { m_node_registration_complete = completed; } @@ -747,8 +738,7 @@ class NodeDefManager NodeDefManager *createNodeDefManager(); -class NodeResolver -{ +class NodeResolver { public: NodeResolver(); virtual ~NodeResolver(); @@ -757,10 +747,11 @@ class NodeResolver // required because this class is used as mixin for ObjDef void cloneTo(NodeResolver *res) const; - bool getIdFromNrBacklog(content_t *result_out, const std::string &node_alt, - content_t c_fallback, bool error_on_fallback = true); + bool getIdFromNrBacklog(content_t *result_out, + const std::string &node_alt, content_t c_fallback, + bool error_on_fallback = true); bool getIdsFromNrBacklog(std::vector *result_out, - bool all_required = false, content_t c_fallback = CONTENT_IGNORE); + bool all_required = false, content_t c_fallback = CONTENT_IGNORE); void nodeResolveInternal(); diff --git a/src/nodemetadata.cpp b/src/nodemetadata.cpp index bab7a96af..b84ffc8cb 100644 --- a/src/nodemetadata.cpp +++ b/src/nodemetadata.cpp @@ -31,10 +31,9 @@ with this program; if not, write to the Free Software Foundation, Inc., NodeMetadata */ -NodeMetadata::NodeMetadata(IItemDefManager *item_def_mgr) : - m_inventory(new Inventory(item_def_mgr)) -{ -} +NodeMetadata::NodeMetadata(IItemDefManager *item_def_mgr): + m_inventory(new Inventory(item_def_mgr)) +{} NodeMetadata::~NodeMetadata() { @@ -63,7 +62,7 @@ void NodeMetadata::deSerialize(std::istream &is, u8 version) { clear(); int num_vars = readU32(is); - for (int i = 0; i < num_vars; i++) { + for(int i=0; igetLists().empty(); } + void NodeMetadata::markPrivate(const std::string &name, bool set) { if (set) @@ -112,8 +112,8 @@ int NodeMetadata::countNonPrivate() const NodeMetadataList */ -void NodeMetadataList::serialize( - std::ostream &os, u8 blockver, bool disk, bool absolute_pos) const +void NodeMetadataList::serialize(std::ostream &os, u8 blockver, bool disk, + bool absolute_pos) const { /* Version 0 is a placeholder for "nothing to see here; go away." @@ -129,7 +129,9 @@ void NodeMetadataList::serialize( writeU8(os, version); writeU16(os, count); - for (NodeMetadataMap::const_iterator i = m_data.begin(); i != m_data.end(); ++i) { + for (NodeMetadataMap::const_iterator + i = m_data.begin(); + i != m_data.end(); ++i) { v3s16 p = i->first; NodeMetadata *data = i->second; if (data->empty()) @@ -148,8 +150,8 @@ void NodeMetadataList::serialize( } } -void NodeMetadataList::deSerialize( - std::istream &is, IItemDefManager *item_def_mgr, bool absolute_pos) +void NodeMetadataList::deSerialize(std::istream &is, + IItemDefManager *item_def_mgr, bool absolute_pos) { clear(); @@ -161,8 +163,8 @@ void NodeMetadataList::deSerialize( } if (version > 2) { - std::string err_str = std::string(FUNCTION_NAME) + ": version " + - itos(version) + " not supported"; + std::string err_str = std::string(FUNCTION_NAME) + + ": version " + itos(version) + " not supported"; infostream << err_str << std::endl; throw SerializationError(err_str); } @@ -185,8 +187,8 @@ void NodeMetadataList::deSerialize( } if (m_data.find(p) != m_data.end()) { warningstream << "NodeMetadataList::deSerialize(): " - << "already set data at position " << PP(p) - << ": Ignoring." << std::endl; + << "already set data at position " << PP(p) + << ": Ignoring." << std::endl; continue; } diff --git a/src/nodemetadata.h b/src/nodemetadata.h index 9002151cc..c028caf88 100644 --- a/src/nodemetadata.h +++ b/src/nodemetadata.h @@ -40,14 +40,17 @@ class NodeMetadata : public Metadata NodeMetadata(IItemDefManager *item_def_mgr); ~NodeMetadata(); - void serialize(std::ostream &os, u8 version, bool disk = true) const; + void serialize(std::ostream &os, u8 version, bool disk=true) const; void deSerialize(std::istream &is, u8 version); void clear(); bool empty() const; // The inventory - Inventory *getInventory() { return m_inventory; } + Inventory *getInventory() + { + return m_inventory; + } inline bool isPrivate(const std::string &name) const { @@ -62,6 +65,7 @@ class NodeMetadata : public Metadata std::unordered_set m_privatevars; }; + /* List of metadata of all the nodes of a block */ @@ -72,16 +76,15 @@ class NodeMetadataList { public: NodeMetadataList(bool is_metadata_owner = true) : - m_is_metadata_owner(is_metadata_owner) - { - } + m_is_metadata_owner(is_metadata_owner) + {} ~NodeMetadataList(); void serialize(std::ostream &os, u8 blockver, bool disk = true, - bool absolute_pos = false) const; + bool absolute_pos = false) const; void deSerialize(std::istream &is, IItemDefManager *item_def_mgr, - bool absolute_pos = false); + bool absolute_pos = false); // Add all keys in this list to the vector keys std::vector getAllKeys(); @@ -96,9 +99,15 @@ class NodeMetadataList size_t size() const { return m_data.size(); } - NodeMetadataMap::const_iterator begin() { return m_data.begin(); } + NodeMetadataMap::const_iterator begin() + { + return m_data.begin(); + } - NodeMetadataMap::const_iterator end() { return m_data.end(); } + NodeMetadataMap::const_iterator end() + { + return m_data.end(); + } private: int countNonEmpty() const; diff --git a/src/nodetimer.cpp b/src/nodetimer.cpp index e0c5194fe..ec8611a01 100644 --- a/src/nodetimer.cpp +++ b/src/nodetimer.cpp @@ -63,7 +63,7 @@ void NodeTimerList::serialize(std::ostream &os, u8 map_format_version) const for (const auto &timer : m_timers) { NodeTimer t = timer.second; NodeTimer nt = NodeTimer(t.timeout, - t.timeout - (f32)(timer.first - m_time), t.position); + t.timeout - (f32)(timer.first - m_time), t.position); v3s16 p = t.position; u16 p16 = p.Z * MAP_BLOCKSIZE * MAP_BLOCKSIZE + p.Y * MAP_BLOCKSIZE + p.X; @@ -78,15 +78,15 @@ void NodeTimerList::deSerialize(std::istream &is, u8 map_format_version) if (map_format_version == 24) { u8 timer_version = readU8(is); - if (timer_version == 0) + if(timer_version == 0) return; - if (timer_version != 1) + if(timer_version != 1) throw SerializationError("unsupported NodeTimerList version"); } if (map_format_version >= 25) { u8 timer_data_len = readU8(is); - if (timer_data_len != 2 + 4 + 4) + if(timer_data_len != 2+4+4) throw SerializationError("unsupported NodeTimer data length"); } @@ -106,18 +106,18 @@ void NodeTimerList::deSerialize(std::istream &is, u8 map_format_version) t.deSerialize(is); if (t.timeout <= 0) { - warningstream << "NodeTimerList::deSerialize(): " - << "invalid data at position" - << "(" << p.X << "," << p.Y << "," << p.Z - << "): Ignoring." << std::endl; + warningstream<<"NodeTimerList::deSerialize(): " + <<"invalid data at position" + <<"("<::iterator>::iterator n = - m_iterators.find(p); + m_iterators.find(p); if (n == m_iterators.end()) return NodeTimer(); NodeTimer t = n->second->second; @@ -76,11 +74,10 @@ class NodeTimerList return t; } // Deletes timer - void remove(v3s16 p) - { + void remove(v3s16 p) { std::map::iterator>::iterator n = - m_iterators.find(p); - if (n != m_iterators.end()) { + m_iterators.find(p); + if(n != m_iterators.end()) { double removed_time = n->second->first; m_timers.erase(n->second); m_iterators.erase(n); @@ -96,26 +93,25 @@ class NodeTimerList } } // Undefined behaviour if there already is a timer - void insert(NodeTimer timer) - { + void insert(NodeTimer timer) { v3s16 p = timer.position; double trigger_time = m_time + (double)(timer.timeout - timer.elapsed); - std::multimap::iterator it = m_timers.insert( - std::pair(trigger_time, timer)); - m_iterators.insert(std::pair::iterator>(p, it)); + std::multimap::iterator it = + m_timers.insert(std::pair( + trigger_time, timer + )); + m_iterators.insert( + std::pair::iterator>(p, it)); if (m_next_trigger_time == -1. || trigger_time < m_next_trigger_time) m_next_trigger_time = trigger_time; } // Deletes old timer and sets a new one - inline void set(const NodeTimer &timer) - { + inline void set(const NodeTimer &timer) { remove(timer.position); insert(timer); } // Deletes all timers - void clear() - { + void clear() { m_timers.clear(); m_iterators.clear(); m_next_trigger_time = -1.; diff --git a/src/noise.cpp b/src/noise.cpp index 04739423b..5a1d989cb 100644 --- a/src/noise.cpp +++ b/src/noise.cpp @@ -9,18 +9,18 @@ * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other - * materials provided with the distribution. + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include @@ -32,21 +32,28 @@ #include "util/string.h" #include "exceptions.h" -#define NOISE_MAGIC_X 1619 -#define NOISE_MAGIC_Y 31337 -#define NOISE_MAGIC_Z 52591 +#define NOISE_MAGIC_X 1619 +#define NOISE_MAGIC_Y 31337 +#define NOISE_MAGIC_Z 52591 #define NOISE_MAGIC_SEED 1013 typedef float (*Interp2dFxn)( - float v00, float v10, float v01, float v11, float x, float y); - -typedef float (*Interp3dFxn)(float v000, float v100, float v010, float v110, float v001, - float v101, float v011, float v111, float x, float y, float z); - -FlagDesc flagdesc_noiseparams[] = {{"defaults", NOISE_FLAG_DEFAULTS}, - {"eased", NOISE_FLAG_EASED}, {"absvalue", NOISE_FLAG_ABSVALUE}, - {"pointbuffer", NOISE_FLAG_POINTBUFFER}, {"simplex", NOISE_FLAG_SIMPLEX}, - {NULL, 0}}; + float v00, float v10, float v01, float v11, + float x, float y); + +typedef float (*Interp3dFxn)( + float v000, float v100, float v010, float v110, + float v001, float v101, float v011, float v111, + float x, float y, float z); + +FlagDesc flagdesc_noiseparams[] = { + {"defaults", NOISE_FLAG_DEFAULTS}, + {"eased", NOISE_FLAG_EASED}, + {"absvalue", NOISE_FLAG_ABSVALUE}, + {"pointbuffer", NOISE_FLAG_POINTBUFFER}, + {"simplex", NOISE_FLAG_SIMPLEX}, + {NULL, 0} +}; /////////////////////////////////////////////////////////////////////////////// @@ -64,6 +71,7 @@ void PcgRandom::seed(u64 state, u64 seq) next(); } + u32 PcgRandom::next() { u64 oldstate = m_state; @@ -74,6 +82,7 @@ u32 PcgRandom::next() return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); } + u32 PcgRandom::range(u32 bound) { // If the bound is 0, we cover the whole RNG's range @@ -110,6 +119,7 @@ u32 PcgRandom::range(u32 bound) return r % bound; } + s32 PcgRandom::range(s32 min, s32 max) { if (max < min) @@ -121,6 +131,7 @@ s32 PcgRandom::range(s32 min, s32 max) return range(bound) + min; } + void PcgRandom::bytes(void *out, size_t len) { u8 *outb = (u8 *)out; @@ -140,6 +151,7 @@ void PcgRandom::bytes(void *out, size_t len) } } + s32 PcgRandom::randNormalDist(s32 min, s32 max, int num_trials) { s32 accum = 0; @@ -152,36 +164,40 @@ s32 PcgRandom::randNormalDist(s32 min, s32 max, int num_trials) float noise2d(int x, int y, s32 seed) { - unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + - NOISE_MAGIC_SEED * seed) & - 0x7fffffff; + unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + + NOISE_MAGIC_SEED * seed) & 0x7fffffff; n = (n >> 13) ^ n; n = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; return 1.f - (float)(int)n / 0x40000000; } + float noise3d(int x, int y, int z, s32 seed) { - unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z + - NOISE_MAGIC_SEED * seed) & - 0x7fffffff; + unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z + + NOISE_MAGIC_SEED * seed) & 0x7fffffff; n = (n >> 13) ^ n; n = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; return 1.f - (float)(int)n / 0x40000000; } + inline float dotProduct(float vx, float vy, float wx, float wy) { return vx * wx + vy * wy; } + inline float linearInterpolation(float v0, float v1, float t) { return v0 + (v1 - v0) * t; } + inline float biLinearInterpolation( - float v00, float v10, float v01, float v11, float x, float y) + float v00, float v10, + float v01, float v11, + float x, float y) { float tx = easeCurve(x); float ty = easeCurve(y); @@ -190,16 +206,22 @@ inline float biLinearInterpolation( return linearInterpolation(u, v, ty); } + inline float biLinearInterpolationNoEase( - float v00, float v10, float v01, float v11, float x, float y) + float v00, float v10, + float v01, float v11, + float x, float y) { float u = linearInterpolation(v00, v10, x); float v = linearInterpolation(v01, v11, x); return linearInterpolation(u, v, y); } -float triLinearInterpolation(float v000, float v100, float v010, float v110, float v001, - float v101, float v011, float v111, float x, float y, float z) + +float triLinearInterpolation( + float v000, float v100, float v010, float v110, + float v001, float v101, float v011, float v111, + float x, float y, float z) { float tx = easeCurve(x); float ty = easeCurve(y); @@ -209,8 +231,10 @@ float triLinearInterpolation(float v000, float v100, float v010, float v110, flo return linearInterpolation(u, v, tz); } -float triLinearInterpolationNoEase(float v000, float v100, float v010, float v110, - float v001, float v101, float v011, float v111, float x, float y, float z) +float triLinearInterpolationNoEase( + float v000, float v100, float v010, float v110, + float v001, float v101, float v011, float v111, + float x, float y, float z) { float u = biLinearInterpolationNoEase(v000, v100, v010, v110, x, y); float v = biLinearInterpolationNoEase(v001, v101, v011, v111, x, y); @@ -227,9 +251,9 @@ float noise2d_gradient(float x, float y, s32 seed, bool eased) float yl = y - (float)y0; // Get values for corners of square float v00 = noise2d(x0, y0, seed); - float v10 = noise2d(x0 + 1, y0, seed); - float v01 = noise2d(x0, y0 + 1, seed); - float v11 = noise2d(x0 + 1, y0 + 1, seed); + float v10 = noise2d(x0+1, y0, seed); + float v01 = noise2d(x0, y0+1, seed); + float v11 = noise2d(x0+1, y0+1, seed); // Interpolate if (eased) return biLinearInterpolation(v00, v10, v01, v11, xl, yl); @@ -237,6 +261,7 @@ float noise2d_gradient(float x, float y, s32 seed, bool eased) return biLinearInterpolationNoEase(v00, v10, v01, v11, xl, yl); } + float noise3d_gradient(float x, float y, float z, s32 seed, bool eased) { // Calculate the integer coordinates @@ -248,31 +273,37 @@ float noise3d_gradient(float x, float y, float z, s32 seed, bool eased) float yl = y - (float)y0; float zl = z - (float)z0; // Get values for corners of cube - float v000 = noise3d(x0, y0, z0, seed); - float v100 = noise3d(x0 + 1, y0, z0, seed); - float v010 = noise3d(x0, y0 + 1, z0, seed); - float v110 = noise3d(x0 + 1, y0 + 1, z0, seed); - float v001 = noise3d(x0, y0, z0 + 1, seed); - float v101 = noise3d(x0 + 1, y0, z0 + 1, seed); - float v011 = noise3d(x0, y0 + 1, z0 + 1, seed); + float v000 = noise3d(x0, y0, z0, seed); + float v100 = noise3d(x0 + 1, y0, z0, seed); + float v010 = noise3d(x0, y0 + 1, z0, seed); + float v110 = noise3d(x0 + 1, y0 + 1, z0, seed); + float v001 = noise3d(x0, y0, z0 + 1, seed); + float v101 = noise3d(x0 + 1, y0, z0 + 1, seed); + float v011 = noise3d(x0, y0 + 1, z0 + 1, seed); float v111 = noise3d(x0 + 1, y0 + 1, z0 + 1, seed); // Interpolate if (eased) { - return triLinearInterpolation(v000, v100, v010, v110, v001, v101, v011, - v111, xl, yl, zl); + return triLinearInterpolation( + v000, v100, v010, v110, + v001, v101, v011, v111, + xl, yl, zl); } return triLinearInterpolationNoEase( - v000, v100, v010, v110, v001, v101, v011, v111, xl, yl, zl); + v000, v100, v010, v110, + v001, v101, v011, v111, + xl, yl, zl); } -float noise2d_perlin( - float x, float y, s32 seed, int octaves, float persistence, bool eased) + +float noise2d_perlin(float x, float y, s32 seed, + int octaves, float persistence, bool eased) { float a = 0; float f = 1.0; float g = 1.0; - for (int i = 0; i < octaves; i++) { + for (int i = 0; i < octaves; i++) + { a += g * noise2d_gradient(x * f, y * f, seed + i, eased); f *= 2.0; g *= persistence; @@ -280,8 +311,9 @@ float noise2d_perlin( return a; } -float noise2d_perlin_abs( - float x, float y, s32 seed, int octaves, float persistence, bool eased) + +float noise2d_perlin_abs(float x, float y, s32 seed, + int octaves, float persistence, bool eased) { float a = 0; float f = 1.0; @@ -294,8 +326,9 @@ float noise2d_perlin_abs( return a; } -float noise3d_perlin(float x, float y, float z, s32 seed, int octaves, float persistence, - bool eased) + +float noise3d_perlin(float x, float y, float z, s32 seed, + int octaves, float persistence, bool eased) { float a = 0; float f = 1.0; @@ -308,21 +341,22 @@ float noise3d_perlin(float x, float y, float z, s32 seed, int octaves, float per return a; } -float noise3d_perlin_abs(float x, float y, float z, s32 seed, int octaves, - float persistence, bool eased) + +float noise3d_perlin_abs(float x, float y, float z, s32 seed, + int octaves, float persistence, bool eased) { float a = 0; float f = 1.0; float g = 1.0; for (int i = 0; i < octaves; i++) { - a += g * - std::fabs(noise3d_gradient(x * f, y * f, z * f, seed + i, eased)); + a += g * std::fabs(noise3d_gradient(x * f, y * f, z * f, seed + i, eased)); f *= 2.0; g *= persistence; } return a; } + float contour(float v) { v = std::fabs(v); @@ -331,8 +365,10 @@ float contour(float v) return (1.0 - v); } + ///////////////////////// [ New noise ] //////////////////////////// + float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed) { float a = 0; @@ -345,7 +381,7 @@ float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed) for (size_t i = 0; i < np->octaves; i++) { float noiseval = noise2d_gradient(x * f, y * f, seed + i, - np->flags & (NOISE_FLAG_DEFAULTS | NOISE_FLAG_EASED)); + np->flags & (NOISE_FLAG_DEFAULTS | NOISE_FLAG_EASED)); if (np->flags & NOISE_FLAG_ABSVALUE) noiseval = std::fabs(noiseval); @@ -358,6 +394,7 @@ float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed) return np->offset + a * np->scale; } + float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed) { float a = 0; @@ -371,7 +408,7 @@ float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed) for (size_t i = 0; i < np->octaves; i++) { float noiseval = noise3d_gradient(x * f, y * f, z * f, seed + i, - np->flags & NOISE_FLAG_EASED); + np->flags & NOISE_FLAG_EASED); if (np->flags & NOISE_FLAG_ABSVALUE) noiseval = std::fabs(noiseval); @@ -384,17 +421,19 @@ float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed) return np->offset + a * np->scale; } + Noise::Noise(NoiseParams *np_, s32 seed, u32 sx, u32 sy, u32 sz) { memcpy(&np, np_, sizeof(np)); this->seed = seed; - this->sx = sx; - this->sy = sy; - this->sz = sz; + this->sx = sx; + this->sy = sy; + this->sz = sz; allocBuffers(); } + Noise::~Noise() { delete[] gradient_buf; @@ -403,6 +442,7 @@ Noise::~Noise() delete[] result; } + void Noise::allocBuffers() { if (sx < 1) @@ -421,14 +461,15 @@ void Noise::allocBuffers() try { size_t bufsize = sx * sy * sz; - this->persist_buf = NULL; + this->persist_buf = NULL; this->gradient_buf = new float[bufsize]; - this->result = new float[bufsize]; + this->result = new float[bufsize]; } catch (std::bad_alloc &e) { throw InvalidNoiseParamsException(); } } + void Noise::setSize(u32 sx, u32 sy, u32 sz) { this->sx = sx; @@ -438,6 +479,7 @@ void Noise::setSize(u32 sx, u32 sy, u32 sz) allocBuffers(); } + void Noise::setSpreadFactor(v3f spread) { this->np.spread = spread; @@ -445,6 +487,7 @@ void Noise::setSpreadFactor(v3f spread) resizeNoiseBuf(sz > 1); } + void Noise::setOctaves(int octaves) { this->np.octaves = octaves; @@ -452,11 +495,13 @@ void Noise::setOctaves(int octaves) resizeNoiseBuf(sz > 1); } + void Noise::resizeNoiseBuf(bool is3d) { // Maximum possible spread value factor - float ofactor = (np.lacunarity > 1.0) ? pow(np.lacunarity, np.octaves - 1) - : np.lacunarity; + float ofactor = (np.lacunarity > 1.0) ? + pow(np.lacunarity, np.octaves - 1) : + np.lacunarity; // Noise lattice point count // (int)(sz * spread * ofactor) is # of lattice points crossed due to length @@ -465,17 +510,18 @@ void Noise::resizeNoiseBuf(bool is3d) float num_noise_points_z = sz * ofactor / np.spread.Z; // Protect against obviously invalid parameters - if (num_noise_points_x > 1000000000.f || num_noise_points_y > 1000000000.f || + if (num_noise_points_x > 1000000000.f || + num_noise_points_y > 1000000000.f || num_noise_points_z > 1000000000.f) throw InvalidNoiseParamsException(); // Protect against an octave having a spread < 1, causing broken noise values - if (np.spread.X / ofactor < 1.0f || np.spread.Y / ofactor < 1.0f || + if (np.spread.X / ofactor < 1.0f || + np.spread.Y / ofactor < 1.0f || np.spread.Z / ofactor < 1.0f) { - errorstream << "A noise parameter has too many octaves: " << np.octaves - << " octaves" << std::endl; - throw InvalidNoiseParamsException( - "A noise parameter has too many octaves"); + errorstream << "A noise parameter has too many octaves: " + << np.octaves << " octaves" << std::endl; + throw InvalidNoiseParamsException("A noise parameter has too many octaves"); } // + 2 for the two initial endpoints @@ -492,6 +538,7 @@ void Noise::resizeNoiseBuf(bool is3d) } } + /* * NB: This algorithm is not optimal in terms of space complexity. The entire * integer lattice of noise points could be done as 2 lines instead, and for 3D, @@ -503,8 +550,11 @@ void Noise::resizeNoiseBuf(bool is3d) * values from the previous noise lattice as midpoints in the new lattice for the * next octave. */ -#define idx(x, y) ((y)*nlx + (x)) -void Noise::gradientMap2D(float x, float y, float step_x, float step_y, s32 seed) +#define idx(x, y) ((y) * nlx + (x)) +void Noise::gradientMap2D( + float x, float y, + float step_x, float step_y, + s32 seed) { float v00, v01, v10, v11, u, v, orig_u; u32 index, i, j, noisex, noisey; @@ -512,8 +562,8 @@ void Noise::gradientMap2D(float x, float y, float step_x, float step_y, s32 seed s32 x0, y0; bool eased = np.flags & (NOISE_FLAG_DEFAULTS | NOISE_FLAG_EASED); - Interp2dFxn interpolate = - eased ? biLinearInterpolation : biLinearInterpolationNoEase; + Interp2dFxn interpolate = eased ? + biLinearInterpolation : biLinearInterpolationNoEase; x0 = std::floor(x); y0 = std::floor(y); @@ -521,7 +571,7 @@ void Noise::gradientMap2D(float x, float y, float step_x, float step_y, s32 seed v = y - (float)y0; orig_u = u; - // calculate noise point lattice + //calculate noise point lattice nlx = (u32)(u + sx * step_x) + 2; nly = (u32)(v + sy * step_y) + 2; index = 0; @@ -529,8 +579,8 @@ void Noise::gradientMap2D(float x, float y, float step_x, float step_y, s32 seed for (i = 0; i != nlx; i++) noise_buf[index++] = noise2d(x0 + i, y0 + j, seed); - // calculate interpolations - index = 0; + //calculate interpolations + index = 0; noisey = 0; for (j = 0; j != sy; j++) { v00 = noise_buf[idx(0, noisey)]; @@ -563,9 +613,12 @@ void Noise::gradientMap2D(float x, float y, float step_x, float step_y, s32 seed } #undef idx -#define idx(x, y, z) ((z)*nly * nlx + (y)*nlx + (x)) -void Noise::gradientMap3D(float x, float y, float z, float step_x, float step_y, - float step_z, s32 seed) + +#define idx(x, y, z) ((z) * nly * nlx + (y) * nlx + (x)) +void Noise::gradientMap3D( + float x, float y, float z, + float step_x, float step_y, float step_z, + s32 seed) { float v000, v010, v100, v110; float v001, v011, v101, v111; @@ -574,9 +627,8 @@ void Noise::gradientMap3D(float x, float y, float z, float step_x, float step_y, u32 nlx, nly, nlz; s32 x0, y0, z0; - Interp3dFxn interpolate = (np.flags & NOISE_FLAG_EASED) - ? triLinearInterpolation - : triLinearInterpolationNoEase; + Interp3dFxn interpolate = (np.flags & NOISE_FLAG_EASED) ? + triLinearInterpolation : triLinearInterpolationNoEase; x0 = std::floor(x); y0 = std::floor(y); @@ -587,7 +639,7 @@ void Noise::gradientMap3D(float x, float y, float z, float step_x, float step_y, orig_u = u; orig_v = v; - // calculate noise point lattice + //calculate noise point lattice nlx = (u32)(u + sx * step_x) + 2; nly = (u32)(v + sy * step_y) + 2; nlz = (u32)(w + sz * step_z) + 2; @@ -595,31 +647,32 @@ void Noise::gradientMap3D(float x, float y, float z, float step_x, float step_y, for (k = 0; k != nlz; k++) for (j = 0; j != nly; j++) for (i = 0; i != nlx; i++) - noise_buf[index++] = - noise3d(x0 + i, y0 + j, z0 + k, seed); + noise_buf[index++] = noise3d(x0 + i, y0 + j, z0 + k, seed); - // calculate interpolations - index = 0; + //calculate interpolations + index = 0; noisey = 0; noisez = 0; for (k = 0; k != sz; k++) { v = orig_v; noisey = 0; for (j = 0; j != sy; j++) { - v000 = noise_buf[idx(0, noisey, noisez)]; - v100 = noise_buf[idx(1, noisey, noisez)]; + v000 = noise_buf[idx(0, noisey, noisez)]; + v100 = noise_buf[idx(1, noisey, noisez)]; v010 = noise_buf[idx(0, noisey + 1, noisez)]; v110 = noise_buf[idx(1, noisey + 1, noisez)]; - v001 = noise_buf[idx(0, noisey, noisez + 1)]; - v101 = noise_buf[idx(1, noisey, noisez + 1)]; + v001 = noise_buf[idx(0, noisey, noisez + 1)]; + v101 = noise_buf[idx(1, noisey, noisez + 1)]; v011 = noise_buf[idx(0, noisey + 1, noisez + 1)]; v111 = noise_buf[idx(1, noisey + 1, noisez + 1)]; u = orig_u; noisex = 0; for (i = 0; i != sx; i++) { - gradient_buf[index++] = interpolate(v000, v100, v010, - v110, v001, v101, v011, v111, u, v, w); + gradient_buf[index++] = interpolate( + v000, v100, v010, v110, + v001, v101, v011, v111, + u, v, w); u += step_x; if (u >= 1.0) { @@ -627,15 +680,12 @@ void Noise::gradientMap3D(float x, float y, float z, float step_x, float step_y, noisex++; v000 = v100; v010 = v110; - v100 = noise_buf[idx(noisex + 1, noisey, noisez)]; - v110 = noise_buf[idx( - noisex + 1, noisey + 1, noisez)]; + v100 = noise_buf[idx(noisex + 1, noisey, noisez)]; + v110 = noise_buf[idx(noisex + 1, noisey + 1, noisez)]; v001 = v101; v011 = v111; - v101 = noise_buf[idx( - noisex + 1, noisey, noisez + 1)]; - v111 = noise_buf[idx(noisex + 1, noisey + 1, - noisez + 1)]; + v101 = noise_buf[idx(noisex + 1, noisey, noisez + 1)]; + v111 = noise_buf[idx(noisex + 1, noisey + 1, noisez + 1)]; } } @@ -655,6 +705,7 @@ void Noise::gradientMap3D(float x, float y, float z, float step_x, float step_y, } #undef idx + float *Noise::perlinMap2D(float x, float y, float *persistence_map) { float f = 1.0, g = 1.0; @@ -673,8 +724,9 @@ float *Noise::perlinMap2D(float x, float y, float *persistence_map) } for (size_t oct = 0; oct < np.octaves; oct++) { - gradientMap2D(x * f, y * f, f / np.spread.X, f / np.spread.Y, - seed + np.seed + oct); + gradientMap2D(x * f, y * f, + f / np.spread.X, f / np.spread.Y, + seed + np.seed + oct); updateResults(g, persist_buf, persistence_map, bufsize); @@ -690,6 +742,7 @@ float *Noise::perlinMap2D(float x, float y, float *persistence_map) return result; } + float *Noise::perlinMap3D(float x, float y, float z, float *persistence_map) { float f = 1.0, g = 1.0; @@ -709,8 +762,9 @@ float *Noise::perlinMap3D(float x, float y, float z, float *persistence_map) } for (size_t oct = 0; oct < np.octaves; oct++) { - gradientMap3D(x * f, y * f, z * f, f / np.spread.X, f / np.spread.Y, - f / np.spread.Z, seed + np.seed + oct); + gradientMap3D(x * f, y * f, z * f, + f / np.spread.X, f / np.spread.Y, f / np.spread.Z, + seed + np.seed + oct); updateResults(g, persist_buf, persistence_map, bufsize); @@ -726,8 +780,9 @@ float *Noise::perlinMap3D(float x, float y, float z, float *persistence_map) return result; } -void Noise::updateResults( - float g, float *gmap, const float *persistence_map, size_t bufsize) + +void Noise::updateResults(float g, float *gmap, + const float *persistence_map, size_t bufsize) { // This looks very ugly, but it is 50-70% faster than having // conditional statements inside the loop diff --git a/src/noise.h b/src/noise.h index cb1c31904..7b5e83251 100644 --- a/src/noise.h +++ b/src/noise.h @@ -9,18 +9,18 @@ * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other - * materials provided with the distribution. + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once @@ -33,14 +33,19 @@ extern FlagDesc flagdesc_noiseparams[]; // Note: this class is not polymorphic so that its high level of // optimizability may be preserved in the common use case -class PseudoRandom -{ +class PseudoRandom { public: const static u32 RANDOM_RANGE = 32767; - inline PseudoRandom(int seed = 0) : m_next(seed) {} + inline PseudoRandom(int seed=0): + m_next(seed) + { + } - inline void seed(int seed) { m_next = seed; } + inline void seed(int seed) + { + m_next = seed; + } inline int next() { @@ -68,36 +73,34 @@ class PseudoRandom int m_next; }; -class PcgRandom -{ +class PcgRandom { public: - const static s32 RANDOM_MIN = -0x7fffffff - 1; - const static s32 RANDOM_MAX = 0x7fffffff; + const static s32 RANDOM_MIN = -0x7fffffff - 1; + const static s32 RANDOM_MAX = 0x7fffffff; const static u32 RANDOM_RANGE = 0xffffffff; - PcgRandom(u64 state = 0x853c49e6748fea9bULL, u64 seq = 0xda3e39cb94b95bdbULL); - void seed(u64 state, u64 seq = 0xda3e39cb94b95bdbULL); + PcgRandom(u64 state=0x853c49e6748fea9bULL, u64 seq=0xda3e39cb94b95bdbULL); + void seed(u64 state, u64 seq=0xda3e39cb94b95bdbULL); u32 next(); u32 range(u32 bound); s32 range(s32 min, s32 max); void bytes(void *out, size_t len); - s32 randNormalDist(s32 min, s32 max, int num_trials = 6); + s32 randNormalDist(s32 min, s32 max, int num_trials=6); private: u64 m_state; u64 m_inc; }; -#define NOISE_FLAG_DEFAULTS 0x01 -#define NOISE_FLAG_EASED 0x02 -#define NOISE_FLAG_ABSVALUE 0x04 +#define NOISE_FLAG_DEFAULTS 0x01 +#define NOISE_FLAG_EASED 0x02 +#define NOISE_FLAG_ABSVALUE 0x04 //// TODO(hmmmm): implement these! #define NOISE_FLAG_POINTBUFFER 0x08 -#define NOISE_FLAG_SIMPLEX 0x10 +#define NOISE_FLAG_SIMPLEX 0x10 -struct NoiseParams -{ +struct NoiseParams { float offset = 0.0f; float scale = 1.0f; v3f spread = v3f(250, 250, 250); @@ -110,22 +113,21 @@ struct NoiseParams NoiseParams() = default; NoiseParams(float offset_, float scale_, const v3f &spread_, s32 seed_, - u16 octaves_, float persist_, float lacunarity_, - u32 flags_ = NOISE_FLAG_DEFAULTS) + u16 octaves_, float persist_, float lacunarity_, + u32 flags_=NOISE_FLAG_DEFAULTS) { - offset = offset_; - scale = scale_; - spread = spread_; - seed = seed_; - octaves = octaves_; - persist = persist_; + offset = offset_; + scale = scale_; + spread = spread_; + seed = seed_; + octaves = octaves_; + persist = persist_; lacunarity = lacunarity_; - flags = flags_; + flags = flags_; } }; -class Noise -{ +class Noise { public: NoiseParams np; s32 seed; @@ -137,32 +139,42 @@ class Noise float *persist_buf = nullptr; float *result = nullptr; - Noise(NoiseParams *np, s32 seed, u32 sx, u32 sy, u32 sz = 1); + Noise(NoiseParams *np, s32 seed, u32 sx, u32 sy, u32 sz=1); ~Noise(); - void setSize(u32 sx, u32 sy, u32 sz = 1); + void setSize(u32 sx, u32 sy, u32 sz=1); void setSpreadFactor(v3f spread); void setOctaves(int octaves); - void gradientMap2D(float x, float y, float step_x, float step_y, s32 seed); - void gradientMap3D(float x, float y, float z, float step_x, float step_y, - float step_z, s32 seed); + void gradientMap2D( + float x, float y, + float step_x, float step_y, + s32 seed); + void gradientMap3D( + float x, float y, float z, + float step_x, float step_y, float step_z, + s32 seed); - float *perlinMap2D(float x, float y, float *persistence_map = NULL); - float *perlinMap3D(float x, float y, float z, float *persistence_map = NULL); + float *perlinMap2D(float x, float y, float *persistence_map=NULL); + float *perlinMap3D(float x, float y, float z, float *persistence_map=NULL); inline float *perlinMap2D_PO(float x, float xoff, float y, float yoff, - float *persistence_map = NULL) + float *persistence_map=NULL) { - return perlinMap2D(x + xoff * np.spread.X, y + yoff * np.spread.Y, - persistence_map); + return perlinMap2D( + x + xoff * np.spread.X, + y + yoff * np.spread.Y, + persistence_map); } - inline float *perlinMap3D_PO(float x, float xoff, float y, float yoff, float z, - float zoff, float *persistence_map = NULL) + inline float *perlinMap3D_PO(float x, float xoff, float y, float yoff, + float z, float zoff, float *persistence_map=NULL) { - return perlinMap3D(x + xoff * np.spread.X, y + yoff * np.spread.Y, - z + zoff * np.spread.Z, persistence_map); + return perlinMap3D( + x + xoff * np.spread.X, + y + yoff * np.spread.Y, + z + zoff * np.spread.Z, + persistence_map); } private: @@ -170,42 +182,49 @@ class Noise void resizeNoiseBuf(bool is3d); void updateResults(float g, float *gmap, const float *persistence_map, size_t bufsize); + }; float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed); float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed); -inline float NoisePerlin2D_PO( - NoiseParams *np, float x, float xoff, float y, float yoff, s32 seed) +inline float NoisePerlin2D_PO(NoiseParams *np, float x, float xoff, + float y, float yoff, s32 seed) { - return NoisePerlin2D(np, x + xoff * np->spread.X, y + yoff * np->spread.Y, seed); + return NoisePerlin2D(np, + x + xoff * np->spread.X, + y + yoff * np->spread.Y, + seed); } -inline float NoisePerlin3D_PO(NoiseParams *np, float x, float xoff, float y, float yoff, - float z, float zoff, s32 seed) +inline float NoisePerlin3D_PO(NoiseParams *np, float x, float xoff, + float y, float yoff, float z, float zoff, s32 seed) { - return NoisePerlin3D(np, x + xoff * np->spread.X, y + yoff * np->spread.Y, - z + zoff * np->spread.Z, seed); + return NoisePerlin3D(np, + x + xoff * np->spread.X, + y + yoff * np->spread.Y, + z + zoff * np->spread.Z, + seed); } // Return value: -1 ... 1 float noise2d(int x, int y, s32 seed); float noise3d(int x, int y, int z, s32 seed); -float noise2d_gradient(float x, float y, s32 seed, bool eased = true); -float noise3d_gradient(float x, float y, float z, s32 seed, bool eased = false); +float noise2d_gradient(float x, float y, s32 seed, bool eased=true); +float noise3d_gradient(float x, float y, float z, s32 seed, bool eased=false); -float noise2d_perlin(float x, float y, s32 seed, int octaves, float persistence, - bool eased = true); +float noise2d_perlin(float x, float y, s32 seed, + int octaves, float persistence, bool eased=true); -float noise2d_perlin_abs(float x, float y, s32 seed, int octaves, float persistence, - bool eased = true); +float noise2d_perlin_abs(float x, float y, s32 seed, + int octaves, float persistence, bool eased=true); -float noise3d_perlin(float x, float y, float z, s32 seed, int octaves, float persistence, - bool eased = false); +float noise3d_perlin(float x, float y, float z, s32 seed, + int octaves, float persistence, bool eased=false); -float noise3d_perlin_abs(float x, float y, float z, s32 seed, int octaves, - float persistence, bool eased = false); +float noise3d_perlin_abs(float x, float y, float z, s32 seed, + int octaves, float persistence, bool eased=false); inline float easeCurve(float t) { diff --git a/src/objdef.cpp b/src/objdef.cpp index 6a5294271..482544d37 100644 --- a/src/objdef.cpp +++ b/src/objdef.cpp @@ -28,12 +28,14 @@ ObjDefManager::ObjDefManager(IGameDef *gamedef, ObjDefType type) m_ndef = gamedef ? gamedef->getNodeDefManager() : NULL; } + ObjDefManager::~ObjDefManager() { for (size_t i = 0; i != m_objects.size(); i++) delete m_objects[i]; } + ObjDefHandle ObjDefManager::add(ObjDef *obj) { assert(obj); @@ -49,12 +51,14 @@ ObjDefHandle ObjDefManager::add(ObjDef *obj) return obj->handle; } + ObjDef *ObjDefManager::get(ObjDefHandle handle) const { u32 index = validateHandle(handle); return (index != OBJDEF_INVALID_INDEX) ? getRaw(index) : NULL; } + ObjDef *ObjDefManager::set(ObjDefHandle handle, ObjDef *obj) { u32 index = validateHandle(handle); @@ -63,13 +67,14 @@ ObjDef *ObjDefManager::set(ObjDefHandle handle, ObjDef *obj) ObjDef *oldobj = setRaw(index, obj); - obj->uid = oldobj->uid; - obj->index = oldobj->index; + obj->uid = oldobj->uid; + obj->index = oldobj->index; obj->handle = oldobj->handle; return oldobj; } + u32 ObjDefManager::addRaw(ObjDef *obj) { size_t nobjects = m_objects.size(); @@ -86,18 +91,22 @@ u32 ObjDefManager::addRaw(ObjDef *obj) m_objects.push_back(obj); - infostream << "ObjDefManager: added " << getObjectTitle() << ": name=\"" - << obj->name << "\" index=" << obj->index << " uid=" << obj->uid - << std::endl; + infostream << "ObjDefManager: added " << getObjectTitle() + << ": name=\"" << obj->name + << "\" index=" << obj->index + << " uid=" << obj->uid + << std::endl; return nobjects; } + ObjDef *ObjDefManager::getRaw(u32 index) const { return m_objects[index]; } + ObjDef *ObjDefManager::setRaw(u32 index, ObjDef *obj) { ObjDef *old_obj = m_objects[index]; @@ -105,6 +114,7 @@ ObjDef *ObjDefManager::setRaw(u32 index, ObjDef *obj) return old_obj; } + ObjDef *ObjDefManager::getByName(const std::string &name) const { for (size_t i = 0; i != m_objects.size(); i++) { @@ -116,6 +126,7 @@ ObjDef *ObjDefManager::getByName(const std::string &name) const return NULL; } + void ObjDefManager::clear() { for (size_t i = 0; i != m_objects.size(); i++) @@ -124,20 +135,24 @@ void ObjDefManager::clear() m_objects.clear(); } + u32 ObjDefManager::validateHandle(ObjDefHandle handle) const { ObjDefType type; u32 index; u32 uid; - bool is_valid = (handle != OBJDEF_INVALID_HANDLE) && - decodeHandle(handle, &index, &type, &uid) && - (type == m_objtype) && (index < m_objects.size()) && - (m_objects[index]->uid == uid); + bool is_valid = + (handle != OBJDEF_INVALID_HANDLE) && + decodeHandle(handle, &index, &type, &uid) && + (type == m_objtype) && + (index < m_objects.size()) && + (m_objects[index]->uid == uid); return is_valid ? index : -1; } + ObjDefHandle ObjDefManager::createHandle(u32 index, ObjDefType type, u32 uid) { ObjDefHandle handle = 0; @@ -151,8 +166,9 @@ ObjDefHandle ObjDefManager::createHandle(u32 index, ObjDefType type, u32 uid) return handle ^ OBJDEF_HANDLE_SALT; } -bool ObjDefManager::decodeHandle( - ObjDefHandle handle, u32 *index, ObjDefType *type, u32 *uid) + +bool ObjDefManager::decodeHandle(ObjDefHandle handle, u32 *index, + ObjDefType *type, u32 *uid) { handle ^= OBJDEF_HANDLE_SALT; @@ -162,8 +178,8 @@ bool ObjDefManager::decodeHandle( return false; *index = get_bits(handle, 0, 18); - *type = (ObjDefType)get_bits(handle, 18, 6); - *uid = get_bits(handle, 24, 7); + *type = (ObjDefType)get_bits(handle, 18, 6); + *uid = get_bits(handle, 24, 7); return true; } diff --git a/src/objdef.h b/src/objdef.h index 7b3ae186f..e40324a88 100644 --- a/src/objdef.h +++ b/src/objdef.h @@ -33,8 +33,7 @@ class NodeDefManager; typedef u32 ObjDefHandle; -enum ObjDefType -{ +enum ObjDefType { OBJDEF_GENERIC, OBJDEF_BIOME, OBJDEF_ORE, @@ -42,8 +41,7 @@ enum ObjDefType OBJDEF_SCHEMATIC, }; -class ObjDef -{ +class ObjDef { public: virtual ~ObjDef() = default; @@ -69,8 +67,7 @@ class ObjDef // added/set to. Note that ObjDefs managed by ObjDefManager are NOT refcounted, // so the same ObjDef instance must not be referenced multiple // TODO: const correctness for getter methods -class ObjDefManager -{ +class ObjDefManager { public: ObjDefManager(IGameDef *gamedef, ObjDefType type); virtual ~ObjDefManager(); @@ -102,11 +99,11 @@ class ObjDefManager u32 validateHandle(ObjDefHandle handle) const; static ObjDefHandle createHandle(u32 index, ObjDefType type, u32 uid); - static bool decodeHandle( - ObjDefHandle handle, u32 *index, ObjDefType *type, u32 *uid); + static bool decodeHandle(ObjDefHandle handle, u32 *index, + ObjDefType *type, u32 *uid); protected: - ObjDefManager(){}; + ObjDefManager() {}; // Helper for child classes to implement clone() void cloneTo(ObjDefManager *mgr) const; diff --git a/src/object_properties.cpp b/src/object_properties.cpp index 97914f53e..8d51bcbfa 100644 --- a/src/object_properties.cpp +++ b/src/object_properties.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., ObjectProperties::ObjectProperties() { textures.emplace_back("unknown_object.png"); - colors.emplace_back(255, 255, 255, 255); + colors.emplace_back(255,255,255,255); } std::string ObjectProperties::dump() @@ -37,8 +37,7 @@ std::string ObjectProperties::dump() os << ", breath_max=" << breath_max; os << ", physical=" << physical; os << ", collideWithObjects=" << collideWithObjects; - os << ", collisionbox=" << PP(collisionbox.MinEdge) << "," - << PP(collisionbox.MaxEdge); + os << ", collisionbox=" << PP(collisionbox.MinEdge) << "," << PP(collisionbox.MaxEdge); os << ", visual=" << visual; os << ", mesh=" << mesh; os << ", visual_size=" << PP(visual_size); @@ -50,22 +49,20 @@ std::string ObjectProperties::dump() os << ", colors=["; for (const video::SColor &color : colors) { os << "\"" << color.getAlpha() << "," << color.getRed() << "," - << color.getGreen() << "," << color.getBlue() << "\" "; + << color.getGreen() << "," << color.getBlue() << "\" "; } os << "]"; os << ", spritediv=" << PP2(spritediv); os << ", initial_sprite_basepos=" << PP2(initial_sprite_basepos); os << ", is_visible=" << is_visible; os << ", makes_footstep_sound=" << makes_footstep_sound; - os << ", automatic_rotate=" << automatic_rotate; - os << ", backface_culling=" << backface_culling; + os << ", automatic_rotate="<< automatic_rotate; + os << ", backface_culling="<< backface_culling; os << ", glow=" << glow; os << ", nametag=" << nametag; - os << ", nametag_color=" - << "\"" << nametag_color.getAlpha() << "," << nametag_color.getRed() << "," - << nametag_color.getGreen() << "," << nametag_color.getBlue() << "\" "; - os << ", selectionbox=" << PP(selectionbox.MinEdge) << "," - << PP(selectionbox.MaxEdge); + os << ", nametag_color=" << "\"" << nametag_color.getAlpha() << "," << nametag_color.getRed() + << "," << nametag_color.getGreen() << "," << nametag_color.getBlue() << "\" "; + os << ", selectionbox=" << PP(selectionbox.MinEdge) << "," << PP(selectionbox.MaxEdge); os << ", pointable=" << pointable; os << ", static_save=" << static_save; os << ", eye_height=" << eye_height; @@ -144,7 +141,7 @@ void ObjectProperties::deSerialize(std::istream &is) visual_size = readV3F32(is); textures.clear(); u32 texture_count = readU16(is); - for (u32 i = 0; i < texture_count; i++) { + for (u32 i = 0; i < texture_count; i++){ textures.push_back(deSerializeString(is)); } spritediv = readV2S16(is); @@ -155,7 +152,7 @@ void ObjectProperties::deSerialize(std::istream &is) mesh = deSerializeString(is); colors.clear(); u32 color_count = readU16(is); - for (u32 i = 0; i < color_count; i++) { + for (u32 i = 0; i < color_count; i++){ colors.push_back(readARGB8(is)); } collideWithObjects = readU8(is); @@ -179,6 +176,5 @@ void ObjectProperties::deSerialize(std::istream &is) if (is.eof()) throw SerializationError(""); shaded = tmp; - } catch (SerializationError &e) { - } + } catch (SerializationError &e) {} } diff --git a/src/particles.cpp b/src/particles.cpp index 03373590e..fd81238dc 100644 --- a/src/particles.cpp +++ b/src/particles.cpp @@ -41,23 +41,23 @@ void ParticleParameters::serialize(std::ostream &os, u16 protocol_ver) const void ParticleParameters::deSerialize(std::istream &is, u16 protocol_ver) { - pos = readV3F32(is); - vel = readV3F32(is); - acc = readV3F32(is); - expirationtime = readF32(is); - size = readF32(is); + pos = readV3F32(is); + vel = readV3F32(is); + acc = readV3F32(is); + expirationtime = readF32(is); + size = readF32(is); collisiondetection = readU8(is); - texture = deSerializeLongString(is); - vertical = readU8(is); - collision_removal = readU8(is); + texture = deSerializeLongString(is); + vertical = readU8(is); + collision_removal = readU8(is); animation.deSerialize(is, 6); /* NOT the protocol ver */ - glow = readU8(is); - object_collision = readU8(is); + glow = readU8(is); + object_collision = readU8(is); // This is kinda awful u16 tmp_param0 = readU16(is); if (is.eof()) return; node.param0 = tmp_param0; node.param2 = readU8(is); - node_tile = readU8(is); + node_tile = readU8(is); } diff --git a/src/particles.h b/src/particles.h index aae460060..6f518b771 100644 --- a/src/particles.h +++ b/src/particles.h @@ -27,8 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // This file defines the particle-related structures that both the server and // client need. The ParticleManager and rendering is in client/particles.h -struct CommonParticleParams -{ +struct CommonParticleParams { bool collisiondetection = false; bool collision_removal = false; bool object_collision = false; @@ -39,16 +38,14 @@ struct CommonParticleParams MapNode node; u8 node_tile = 0; - CommonParticleParams() - { + CommonParticleParams() { animation.type = TAT_NONE; node.setContent(CONTENT_IGNORE); } /* This helper is useful for copying params from * ParticleSpawnerParameters to ParticleParameters */ - inline void copyCommon(CommonParticleParams &to) const - { + inline void copyCommon(CommonParticleParams &to) const { to.collisiondetection = collisiondetection; to.collision_removal = collision_removal; to.object_collision = object_collision; @@ -61,8 +58,7 @@ struct CommonParticleParams } }; -struct ParticleParameters : CommonParticleParams -{ +struct ParticleParameters : CommonParticleParams { v3f pos; v3f vel; v3f acc; @@ -73,8 +69,7 @@ struct ParticleParameters : CommonParticleParams void deSerialize(std::istream &is, u16 protocol_ver); }; -struct ParticleSpawnerParameters : CommonParticleParams -{ +struct ParticleSpawnerParameters : CommonParticleParams { u16 amount = 1; v3f minpos, maxpos, minvel, maxvel, minacc, maxacc; f32 time = 1; diff --git a/src/pathfinder.cpp b/src/pathfinder.cpp index ec418c45d..3f0b98c10 100644 --- a/src/pathfinder.cpp +++ b/src/pathfinder.cpp @@ -30,13 +30,13 @@ with this program; if not, write to the Free Software Foundation, Inc., //#define PATHFINDER_CALC_TIME #ifdef PATHFINDER_DEBUG -#include + #include #endif #ifdef PATHFINDER_DEBUG -#include + #include #endif #ifdef PATHFINDER_CALC_TIME -#include + #include #endif /******************************************************************************/ @@ -46,15 +46,15 @@ with this program; if not, write to the Free Software Foundation, Inc., #define LVL "(" << level << ")" << #ifdef PATHFINDER_DEBUG -#define DEBUG_OUT(a) std::cout << a -#define INFO_TARGET std::cout -#define VERBOSE_TARGET std::cout -#define ERROR_TARGET std::cout +#define DEBUG_OUT(a) std::cout << a +#define INFO_TARGET std::cout +#define VERBOSE_TARGET std::cout +#define ERROR_TARGET std::cout #else -#define DEBUG_OUT(a) while (0) -#define INFO_TARGET infostream << "Pathfinder: " -#define VERBOSE_TARGET verbosestream << "Pathfinder: " -#define ERROR_TARGET warningstream << "Pathfinder: " +#define DEBUG_OUT(a) while(0) +#define INFO_TARGET infostream << "Pathfinder: " +#define VERBOSE_TARGET verbosestream << "Pathfinder: " +#define ERROR_TARGET warningstream << "Pathfinder: " #endif #define PATHFINDER_MAX_WAYPOINTS 700 @@ -63,10 +63,11 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Class definitions */ /******************************************************************************/ + /** representation of cost in specific direction */ -class PathCost -{ +class PathCost { public: + /** default constructor */ PathCost() = default; @@ -74,17 +75,18 @@ class PathCost PathCost(const PathCost &b); /** assignment operator */ - PathCost &operator=(const PathCost &b); + PathCost &operator= (const PathCost &b); + + bool valid = false; /**< movement is possible */ + int value = 0; /**< cost of movement */ + int y_change = 0; /**< change of y position of movement */ + bool updated = false; /**< this cost has ben calculated */ - bool valid = false; /**< movement is possible */ - int value = 0; /**< cost of movement */ - int y_change = 0; /**< change of y position of movement */ - bool updated = false; /**< this cost has ben calculated */ }; + /** representation of a mapnode to be used for pathfinding */ -class PathGridnode -{ +class PathGridnode { public: /** default constructor */ @@ -97,7 +99,7 @@ class PathGridnode * assignment operator * @param b node to copy */ - PathGridnode &operator=(const PathGridnode &b); + PathGridnode &operator= (const PathGridnode &b); /** * read cost in a specific direction @@ -110,38 +112,37 @@ class PathGridnode * @param dir direction to set cost for * @cost cost to set */ - void setCost(v3s16 dir, const PathCost &cost); - - bool valid = false; /**< node is on surface */ - bool target = false; /**< node is target position */ - bool source = false; /**< node is stating position */ - int totalcost = -1; /**< cost to move here from starting point */ - int estimated_cost = -1; /**< totalcost + heuristic cost to end */ - v3s16 sourcedir; /**< origin of movement for current cost */ - v3s16 pos; /**< real position of node */ - PathCost directions[4]; /**< cost in different directions */ - bool is_closed = false; /**< for A* search: if true, is in closed list */ - bool is_open = false; /**< for A* search: if true, is in open list */ + void setCost(v3s16 dir, const PathCost &cost); + + bool valid = false; /**< node is on surface */ + bool target = false; /**< node is target position */ + bool source = false; /**< node is stating position */ + int totalcost = -1; /**< cost to move here from starting point */ + int estimated_cost = -1; /**< totalcost + heuristic cost to end */ + v3s16 sourcedir; /**< origin of movement for current cost */ + v3s16 pos; /**< real position of node */ + PathCost directions[4]; /**< cost in different directions */ + bool is_closed = false; /**< for A* search: if true, is in closed list */ + bool is_open = false; /**< for A* search: if true, is in open list */ /* debug values */ - bool is_element = false; /**< node is element of path detected */ - char type = 'u'; /**< Type of pathfinding node. - * u = unknown - * i = invalid - * s = surface (walkable node) - * - = non-walkable node (e.g. air) above surface - * g = other non-walkable node - */ + bool is_element = false; /**< node is element of path detected */ + char type = 'u'; /**< Type of pathfinding node. + * u = unknown + * i = invalid + * s = surface (walkable node) + * - = non-walkable node (e.g. air) above surface + * g = other non-walkable node + */ }; class Pathfinder; class PathfinderCompareHeuristic; /** Abstract class to manage the map data */ -class GridNodeContainer -{ +class GridNodeContainer { public: - virtual PathGridnode &access(v3s16 p) = 0; + virtual PathGridnode &access(v3s16 p)=0; virtual ~GridNodeContainer() = default; protected: @@ -150,14 +151,12 @@ class GridNodeContainer void initNode(v3s16 ipos, PathGridnode *p_node); }; -class ArrayGridNodeContainer : public GridNodeContainer -{ +class ArrayGridNodeContainer : public GridNodeContainer { public: virtual ~ArrayGridNodeContainer() = default; ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions); virtual PathGridnode &access(v3s16 p); - private: v3s16 m_dimensions; @@ -166,21 +165,18 @@ class ArrayGridNodeContainer : public GridNodeContainer std::vector m_nodes_array; }; -class MapGridNodeContainer : public GridNodeContainer -{ +class MapGridNodeContainer : public GridNodeContainer { public: virtual ~MapGridNodeContainer() = default; MapGridNodeContainer(Pathfinder *pathf); virtual PathGridnode &access(v3s16 p); - private: std::map m_nodes; }; /** class doing pathfinding */ -class Pathfinder -{ +class Pathfinder { public: Pathfinder() = delete; @@ -198,9 +194,12 @@ class Pathfinder * @param max_drop maximum number of blocks a path may drop * @param algo Algorithm to use for finding a path */ - std::vector getPath(v3s16 source, v3s16 destination, - unsigned int searchdistance, unsigned int max_jump, - unsigned int max_drop, PathAlgorithm algo); + std::vector getPath(v3s16 source, + v3s16 destination, + unsigned int searchdistance, + unsigned int max_jump, + unsigned int max_drop, + PathAlgorithm algo); private: /* helper functions */ @@ -210,14 +209,14 @@ class Pathfinder * @param ipos a index position * @return map position */ - v3s16 getRealPos(v3s16 ipos); + v3s16 getRealPos(v3s16 ipos); /** * transform mappos to index pos * @param pos a real pos * @return index position */ - v3s16 getIndexPos(v3s16 pos); + v3s16 getIndexPos(v3s16 pos); /** * get gridnode at a specific index position @@ -237,14 +236,15 @@ class Pathfinder * @param pos 3D position * @return pos *-1 */ - v3s16 invert(v3s16 pos); + v3s16 invert(v3s16 pos); /** * check if a index is within current search area * @param index position to validate * @return true/false */ - bool isValidIndex(v3s16 index); + bool isValidIndex(v3s16 index); + /* algorithm functions */ @@ -253,7 +253,7 @@ class Pathfinder * @param pos position to calc distance * @return integer distance */ - int getXZManhattanDist(v3s16 pos); + int getXZManhattanDist(v3s16 pos); /** * calculate cost of movement @@ -261,7 +261,7 @@ class Pathfinder * @param dir direction to move to * @return cost information */ - PathCost calcCost(v3s16 pos, v3s16 dir); + PathCost calcCost(v3s16 pos, v3s16 dir); /** * recursive update whole search areas total cost information @@ -271,7 +271,7 @@ class Pathfinder * @param level current recursion depth * @return true/false path to destination has been found */ - bool updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int level); + bool updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int level); /** * try to find a path to destination using a heuristic function @@ -280,7 +280,7 @@ class Pathfinder * @param idestination end position (index pos) * @return true/false path to destination has been found */ - bool updateCostHeuristic(v3s16 isource, v3s16 idestination); + bool updateCostHeuristic(v3s16 isource, v3s16 idestination); /** * build a vector containing all nodes from destination to source; @@ -289,7 +289,7 @@ class Pathfinder * @param ipos initial pos to check (index pos) * @return true/false path has been fully built */ - bool buildPath(std::vector &path, v3s16 ipos); + bool buildPath(std::vector &path, v3s16 ipos); /** * go downwards from a position until some barrier @@ -299,22 +299,23 @@ class Pathfinder * @return new position after movement; if too far down, * pos is returned */ - v3s16 walkDownwards(v3s16 pos, unsigned int max_down); + v3s16 walkDownwards(v3s16 pos, unsigned int max_down); /* variables */ - int m_max_index_x = 0; /**< max index of search area in x direction */ - int m_max_index_y = 0; /**< max index of search area in y direction */ - int m_max_index_z = 0; /**< max index of search area in z direction */ + int m_max_index_x = 0; /**< max index of search area in x direction */ + int m_max_index_y = 0; /**< max index of search area in y direction */ + int m_max_index_z = 0; /**< max index of search area in z direction */ + - int m_searchdistance = 0; /**< max distance to search in each direction */ - int m_maxdrop = 0; /**< maximum number of blocks a path may drop */ - int m_maxjump = 0; /**< maximum number of blocks a path may jump */ - int m_min_target_distance = 0; /**< current smalest path to target */ + int m_searchdistance = 0; /**< max distance to search in each direction */ + int m_maxdrop = 0; /**< maximum number of blocks a path may drop */ + int m_maxjump = 0; /**< maximum number of blocks a path may jump */ + int m_min_target_distance = 0; /**< current smalest path to target */ - bool m_prefetch = true; /**< prefetch cost data */ + bool m_prefetch = true; /**< prefetch cost data */ - v3s16 m_start; /**< source position */ - v3s16 m_destination; /**< destination position */ + v3s16 m_start; /**< source position */ + v3s16 m_destination; /**< destination position */ core::aabbox3d m_limits; /**< position limits in real map coordinates */ @@ -383,62 +384,72 @@ class Pathfinder */ class PathfinderCompareHeuristic { -private: - Pathfinder *myPathfinder; - -public: - PathfinderCompareHeuristic(Pathfinder *pf) { myPathfinder = pf; } - bool operator()(v3s16 pos1, v3s16 pos2) - { - v3s16 ipos1 = myPathfinder->getIndexPos(pos1); - v3s16 ipos2 = myPathfinder->getIndexPos(pos2); - PathGridnode &g_pos1 = myPathfinder->getIndexElement(ipos1); - PathGridnode &g_pos2 = myPathfinder->getIndexElement(ipos2); - if (!g_pos1.valid) - return false; - if (!g_pos2.valid) - return false; - return g_pos1.estimated_cost > g_pos2.estimated_cost; - } + private: + Pathfinder *myPathfinder; + public: + PathfinderCompareHeuristic(Pathfinder *pf) + { + myPathfinder = pf; + } + bool operator() (v3s16 pos1, v3s16 pos2) { + v3s16 ipos1 = myPathfinder->getIndexPos(pos1); + v3s16 ipos2 = myPathfinder->getIndexPos(pos2); + PathGridnode &g_pos1 = myPathfinder->getIndexElement(ipos1); + PathGridnode &g_pos2 = myPathfinder->getIndexElement(ipos2); + if (!g_pos1.valid) + return false; + if (!g_pos2.valid) + return false; + return g_pos1.estimated_cost > g_pos2.estimated_cost; + } }; /******************************************************************************/ /* implementation */ /******************************************************************************/ -std::vector get_path(Map *map, const NodeDefManager *ndef, v3s16 source, - v3s16 destination, unsigned int searchdistance, unsigned int max_jump, - unsigned int max_drop, PathAlgorithm algo) +std::vector get_path(Map* map, const NodeDefManager *ndef, + v3s16 source, + v3s16 destination, + unsigned int searchdistance, + unsigned int max_jump, + unsigned int max_drop, + PathAlgorithm algo) { - return Pathfinder(map, ndef).getPath( - source, destination, searchdistance, max_jump, max_drop, algo); + return Pathfinder(map, ndef).getPath(source, destination, + searchdistance, max_jump, max_drop, algo); } /******************************************************************************/ PathCost::PathCost(const PathCost &b) { - valid = b.valid; - y_change = b.y_change; - value = b.value; - updated = b.updated; + valid = b.valid; + y_change = b.y_change; + value = b.value; + updated = b.updated; } /******************************************************************************/ -PathCost &PathCost::operator=(const PathCost &b) +PathCost &PathCost::operator= (const PathCost &b) { - valid = b.valid; - y_change = b.y_change; - value = b.value; - updated = b.updated; + valid = b.valid; + y_change = b.y_change; + value = b.value; + updated = b.updated; return *this; } /******************************************************************************/ -PathGridnode::PathGridnode(const PathGridnode &b) : - valid(b.valid), target(b.target), source(b.source), - totalcost(b.totalcost), sourcedir(b.sourcedir), pos(b.pos), - is_element(b.is_element), type(b.type) +PathGridnode::PathGridnode(const PathGridnode &b) +: valid(b.valid), + target(b.target), + source(b.source), + totalcost(b.totalcost), + sourcedir(b.sourcedir), + pos(b.pos), + is_element(b.is_element), + type(b.type) { directions[DIR_XP] = b.directions[DIR_XP]; @@ -448,16 +459,16 @@ PathGridnode::PathGridnode(const PathGridnode &b) : } /******************************************************************************/ -PathGridnode &PathGridnode::operator=(const PathGridnode &b) +PathGridnode &PathGridnode::operator= (const PathGridnode &b) { - valid = b.valid; - target = b.target; - source = b.source; + valid = b.valid; + target = b.target; + source = b.source; is_element = b.is_element; - totalcost = b.totalcost; - sourcedir = b.sourcedir; - pos = b.pos; - type = b.type; + totalcost = b.totalcost; + sourcedir = b.sourcedir; + pos = b.pos; + type = b.type; directions[DIR_XP] = b.directions[DIR_XP]; directions[DIR_XM] = b.directions[DIR_XM]; @@ -511,12 +522,13 @@ void GridNodeContainer::initNode(v3s16 ipos, PathGridnode *p_node) v3s16 realpos = m_pathf->getRealPos(ipos); MapNode current = m_pathf->m_map->getNode(realpos); - MapNode below = m_pathf->m_map->getNode(realpos + v3s16(0, -1, 0)); + MapNode below = m_pathf->m_map->getNode(realpos + v3s16(0, -1, 0)); + - if ((current.param0 == CONTENT_IGNORE) || (below.param0 == CONTENT_IGNORE)) { - DEBUG_OUT("Pathfinder: " << PP(realpos) - << " current or below is invalid element" - << std::endl); + if ((current.param0 == CONTENT_IGNORE) || + (below.param0 == CONTENT_IGNORE)) { + DEBUG_OUT("Pathfinder: " << PP(realpos) << + " current or below is invalid element" << std::endl); if (current.param0 == CONTENT_IGNORE) { elem.type = 'i'; DEBUG_OUT(PP(ipos) << ": " << 'i' << std::endl); @@ -524,35 +536,36 @@ void GridNodeContainer::initNode(v3s16 ipos, PathGridnode *p_node) return; } - // don't add anything if it isn't an air node + //don't add anything if it isn't an air node if (ndef->get(current).walkable || !ndef->get(below).walkable) { - DEBUG_OUT("Pathfinder: " << PP(realpos) << " not on surface" - << std::endl); - if (ndef->get(current).walkable) { - elem.type = 's'; - DEBUG_OUT(PP(ipos) << ": " << 's' << std::endl); - } else { - elem.type = '-'; - DEBUG_OUT(PP(ipos) << ": " << '-' << std::endl); - } - return; + DEBUG_OUT("Pathfinder: " << PP(realpos) + << " not on surface" << std::endl); + if (ndef->get(current).walkable) { + elem.type = 's'; + DEBUG_OUT(PP(ipos) << ": " << 's' << std::endl); + } else { + elem.type = '-'; + DEBUG_OUT(PP(ipos) << ": " << '-' << std::endl); + } + return; } elem.valid = true; - elem.pos = realpos; - elem.type = 'g'; + elem.pos = realpos; + elem.type = 'g'; DEBUG_OUT(PP(ipos) << ": " << 'a' << std::endl); if (m_pathf->m_prefetch) { - elem.directions[DIR_XP] = m_pathf->calcCost(realpos, v3s16(1, 0, 0)); + elem.directions[DIR_XP] = m_pathf->calcCost(realpos, v3s16( 1, 0, 0)); elem.directions[DIR_XM] = m_pathf->calcCost(realpos, v3s16(-1, 0, 0)); - elem.directions[DIR_ZP] = m_pathf->calcCost(realpos, v3s16(0, 0, 1)); - elem.directions[DIR_ZM] = m_pathf->calcCost(realpos, v3s16(0, 0, -1)); + elem.directions[DIR_ZP] = m_pathf->calcCost(realpos, v3s16( 0, 0, 1)); + elem.directions[DIR_ZM] = m_pathf->calcCost(realpos, v3s16( 0, 0,-1)); } } ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions) : - m_x_stride(dimensions.Y * dimensions.Z), m_y_stride(dimensions.Z) + m_x_stride(dimensions.Y * dimensions.Z), + m_y_stride(dimensions.Z) { m_pathf = pathf; @@ -560,7 +573,7 @@ ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensio INFO_TARGET << "Pathfinder ArrayGridNodeContainer constructor." << std::endl; for (int x = 0; x < dimensions.X; x++) { for (int y = 0; y < dimensions.Y; y++) { - for (int z = 0; z < dimensions.Z; z++) { + for (int z= 0; z < dimensions.Z; z++) { v3s16 ipos(x, y, z); initNode(ipos, &access(ipos)); } @@ -589,10 +602,15 @@ PathGridnode &MapGridNodeContainer::access(v3s16 p) return n; } + + /******************************************************************************/ -std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, - unsigned int searchdistance, unsigned int max_jump, unsigned int max_drop, - PathAlgorithm algo) +std::vector Pathfinder::getPath(v3s16 source, + v3s16 destination, + unsigned int searchdistance, + unsigned int max_jump, + unsigned int max_drop, + PathAlgorithm algo) { #ifdef PATHFINDER_CALC_TIME timespec ts; @@ -600,11 +618,11 @@ std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, #endif std::vector retval; - // initialization + //initialization m_searchdistance = searchdistance; m_maxjump = max_jump; m_maxdrop = max_drop; - m_start = source; + m_start = source; m_destination = destination; m_min_target_distance = -1; m_prefetch = true; @@ -613,7 +631,7 @@ std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, m_prefetch = false; } - // calculate boundaries within we're allowed to search + //calculate boundaries within we're allowed to search int min_x = MYMIN(source.X, destination.X); int max_x = MYMAX(source.X, destination.X); @@ -649,73 +667,73 @@ std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, printYdir(); #endif - // fail if source or destination is walkable + //fail if source or destination is walkable MapNode node_at_pos = m_map->getNode(destination); if (m_ndef->get(node_at_pos).walkable) { - VERBOSE_TARGET << "Destination is walkable. " - << "Pos: " << PP(destination) << std::endl; + VERBOSE_TARGET << "Destination is walkable. " << + "Pos: " << PP(destination) << std::endl; return retval; } node_at_pos = m_map->getNode(source); if (m_ndef->get(node_at_pos).walkable) { - VERBOSE_TARGET << "Source is walkable. " - << "Pos: " << PP(source) << std::endl; + VERBOSE_TARGET << "Source is walkable. " << + "Pos: " << PP(source) << std::endl; return retval; } - // If source pos is hovering above air, drop - // to the first walkable node (up to m_maxdrop). - // All algorithms expect the source pos to be *directly* above - // a walkable node. + //If source pos is hovering above air, drop + //to the first walkable node (up to m_maxdrop). + //All algorithms expect the source pos to be *directly* above + //a walkable node. v3s16 true_source = v3s16(source); source = walkDownwards(source, m_maxdrop); - // If destination pos is hovering above air, go downwards - // to the first walkable node (up to m_maxjump). - // This means a hovering destination pos could be reached - // by a final upwards jump. + //If destination pos is hovering above air, go downwards + //to the first walkable node (up to m_maxjump). + //This means a hovering destination pos could be reached + //by a final upwards jump. v3s16 true_destination = v3s16(destination); destination = walkDownwards(destination, m_maxjump); - // validate and mark start and end pos + //validate and mark start and end pos - v3s16 StartIndex = getIndexPos(source); - v3s16 EndIndex = getIndexPos(destination); + v3s16 StartIndex = getIndexPos(source); + v3s16 EndIndex = getIndexPos(destination); PathGridnode &startpos = getIndexElement(StartIndex); - PathGridnode &endpos = getIndexElement(EndIndex); + PathGridnode &endpos = getIndexElement(EndIndex); if (!startpos.valid) { - VERBOSE_TARGET << "Invalid startpos " - << "Index: " << PP(StartIndex) - << "Realpos: " << PP(getRealPos(StartIndex)) << std::endl; + VERBOSE_TARGET << "Invalid startpos " << + "Index: " << PP(StartIndex) << + "Realpos: " << PP(getRealPos(StartIndex)) << std::endl; return retval; } if (!endpos.valid) { - VERBOSE_TARGET << "Invalid stoppos " - << "Index: " << PP(EndIndex) - << "Realpos: " << PP(getRealPos(EndIndex)) << std::endl; + VERBOSE_TARGET << "Invalid stoppos " << + "Index: " << PP(EndIndex) << + "Realpos: " << PP(getRealPos(EndIndex)) << std::endl; return retval; } - endpos.target = true; - startpos.source = true; + endpos.target = true; + startpos.source = true; startpos.totalcost = 0; bool update_cost_retval = false; - // calculate node costs + //calculate node costs switch (algo) { - case PA_DIJKSTRA: - update_cost_retval = updateAllCosts(StartIndex, v3s16(0, 0, 0), 0, 0); - break; - case PA_PLAIN_NP: - case PA_PLAIN: - update_cost_retval = updateCostHeuristic(StartIndex, EndIndex); - break; - default: - ERROR_TARGET << "Missing PathAlgorithm" << std::endl; - break; + case PA_DIJKSTRA: + update_cost_retval = updateAllCosts(StartIndex, v3s16(0, 0, 0), 0, 0); + break; + case PA_PLAIN_NP: + case PA_PLAIN: + update_cost_retval = updateCostHeuristic(StartIndex, EndIndex); + break; + default: + ERROR_TARGET << "Missing PathAlgorithm" << std::endl; + break; } if (update_cost_retval) { @@ -725,22 +743,22 @@ std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, printPathLen(); #endif - // find path + //find path std::vector index_path; buildPath(index_path, EndIndex); - // Now we have a path of index positions, - // and it's in reverse. - // The "true" start or end position might be missing - // since those have been given special treatment. + //Now we have a path of index positions, + //and it's in reverse. + //The "true" start or end position might be missing + //since those have been given special treatment. #ifdef PATHFINDER_DEBUG std::cout << "Index path:" << std::endl; printPath(index_path); #endif - // from here we'll make the final changes to the path + //from here we'll make the final changes to the path std::vector full_path; - // calculate required size + //calculate required size int full_path_size = index_path.size(); if (source != true_source) { full_path_size++; @@ -750,22 +768,23 @@ std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, } full_path.reserve(full_path_size); - // manually add true_source to start of path, if needed + //manually add true_source to start of path, if needed if (source != true_source) { full_path.push_back(true_source); } - // convert all index positions to "normal" positions and insert - // them into full_path in reverse + //convert all index positions to "normal" positions and insert + //them into full_path in reverse std::vector::reverse_iterator rit = index_path.rbegin(); for (; rit != index_path.rend(); ++rit) { full_path.push_back(getIndexElement(*rit).pos); } - // manually add true_destination to end of path, if needed + //manually add true_destination to end of path, if needed if (destination != true_destination) { full_path.push_back(true_destination); } - // Done! We now have a complete path of normal positions. + //Done! We now have a complete path of normal positions. + #ifdef PATHFINDER_DEBUG std::cout << "Full path:" << std::endl; @@ -775,23 +794,25 @@ std::vector Pathfinder::getPath(v3s16 source, v3s16 destination, timespec ts2; clock_gettime(CLOCK_REALTIME, &ts2); - int ms = (ts2.tv_nsec - ts.tv_nsec) / (1000 * 1000); - int us = ((ts2.tv_nsec - ts.tv_nsec) - (ms * 1000 * 1000)) / 1000; - int ns = ((ts2.tv_nsec - ts.tv_nsec) - - ((ms * 1000 * 1000) + (us * 1000))); + int ms = (ts2.tv_nsec - ts.tv_nsec)/(1000*1000); + int us = ((ts2.tv_nsec - ts.tv_nsec) - (ms*1000*1000))/1000; + int ns = ((ts2.tv_nsec - ts.tv_nsec) - ( (ms*1000*1000) + (us*1000))); + - std::cout << "Calculating path took: " << (ts2.tv_sec - ts.tv_sec) << "s " - << ms << "ms " << us << "us " << ns << "ns " << std::endl; + std::cout << "Calculating path took: " << (ts2.tv_sec - ts.tv_sec) << + "s " << ms << "ms " << us << "us " << ns << "ns " << std::endl; #endif return full_path; - } else { + } + else { #ifdef PATHFINDER_DEBUG printPathLen(); #endif INFO_TARGET << "No path found" << std::endl; } - // return + + //return return retval; } @@ -814,42 +835,44 @@ PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir) v3s16 pos2 = pos + dir; - // check limits + //check limits if (!m_limits.isPointInside(pos2)) { - DEBUG_OUT("Pathfinder: " << PP(pos2) << " no cost -> out of limits" - << std::endl); + DEBUG_OUT("Pathfinder: " << PP(pos2) << + " no cost -> out of limits" << std::endl); return retval; } MapNode node_at_pos2 = m_map->getNode(pos2); - // did we get information about node? - if (node_at_pos2.param0 == CONTENT_IGNORE) { - VERBOSE_TARGET << "Pathfinder: (1) area at pos: " << PP(pos2) - << " not loaded"; - return retval; + //did we get information about node? + if (node_at_pos2.param0 == CONTENT_IGNORE ) { + VERBOSE_TARGET << "Pathfinder: (1) area at pos: " + << PP(pos2) << " not loaded"; + return retval; } if (!m_ndef->get(node_at_pos2).walkable) { - MapNode node_below_pos2 = m_map->getNode(pos2 + v3s16(0, -1, 0)); - - // did we get information about node? - if (node_below_pos2.param0 == CONTENT_IGNORE) { - VERBOSE_TARGET << "Pathfinder: (2) area at pos: " - << PP((pos2 + v3s16(0, -1, 0))) << " not loaded"; - return retval; + MapNode node_below_pos2 = + m_map->getNode(pos2 + v3s16(0, -1, 0)); + + //did we get information about node? + if (node_below_pos2.param0 == CONTENT_IGNORE ) { + VERBOSE_TARGET << "Pathfinder: (2) area at pos: " + << PP((pos2 + v3s16(0, -1, 0))) << " not loaded"; + return retval; } - // test if the same-height neighbor is suitable + //test if the same-height neighbor is suitable if (m_ndef->get(node_below_pos2).walkable) { - // SUCCESS! + //SUCCESS! retval.valid = true; retval.value = 1; retval.y_change = 0; - DEBUG_OUT("Pathfinder: " << PP(pos) << " cost same height found" - << std::endl); - } else { - // test if we can fall a couple of nodes (m_maxdrop) + DEBUG_OUT("Pathfinder: "<< PP(pos) + << " cost same height found" << std::endl); + } + else { + //test if we can fall a couple of nodes (m_maxdrop) v3s16 testpos = pos2 + v3s16(0, -1, 0); MapNode node_at_pos = m_map->getNode(testpos); @@ -860,36 +883,35 @@ PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir) node_at_pos = m_map->getNode(testpos); } - // did we find surface? + //did we find surface? if ((testpos.Y >= m_limits.MinEdge.Y) && (node_at_pos.param0 != CONTENT_IGNORE) && (m_ndef->get(node_at_pos).walkable)) { if ((pos2.Y - testpos.Y - 1) <= m_maxdrop) { - // SUCCESS! + //SUCCESS! retval.valid = true; retval.value = 2; - // difference of y-pos +1 (target node is ABOVE - // solid node) - retval.y_change = ((testpos.Y - pos2.Y) + 1); - DEBUG_OUT("Pathfinder cost below height found" - << std::endl); - } else { + //difference of y-pos +1 (target node is ABOVE solid node) + retval.y_change = ((testpos.Y - pos2.Y) +1); + DEBUG_OUT("Pathfinder cost below height found" << std::endl); + } + else { INFO_TARGET << "Pathfinder:" - " distance to surface below too " - "big: " - << (testpos.Y - pos2.Y) - << " max: " << m_maxdrop << std::endl; + " distance to surface below too big: " + << (testpos.Y - pos2.Y) << " max: " << m_maxdrop + << std::endl; } - } else { - DEBUG_OUT("Pathfinder: no surface below found" - << std::endl); + } + else { + DEBUG_OUT("Pathfinder: no surface below found" << std::endl); } } - } else { - // test if we can jump upwards (m_maxjump) + } + else { + //test if we can jump upwards (m_maxjump) v3s16 targetpos = pos2; // position for jump target - v3s16 jumppos = pos; // position for checking if jumping space is free + v3s16 jumppos = pos; // position for checking if jumping space is free MapNode node_target = m_map->getNode(targetpos); MapNode node_jump = m_map->getNode(jumppos); bool headbanger = false; // true if anything blocks jumppath @@ -897,40 +919,42 @@ PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir) while ((node_target.param0 != CONTENT_IGNORE) && (m_ndef->get(node_target).walkable) && (targetpos.Y < m_limits.MaxEdge.Y)) { - // if the jump would hit any solid node, discard + //if the jump would hit any solid node, discard if ((node_jump.param0 == CONTENT_IGNORE) || (m_ndef->get(node_jump).walkable)) { - headbanger = true; + headbanger = true; break; } targetpos += v3s16(0, 1, 0); - jumppos += v3s16(0, 1, 0); + jumppos += v3s16(0, 1, 0); node_target = m_map->getNode(targetpos); - node_jump = m_map->getNode(jumppos); + node_jump = m_map->getNode(jumppos); + } - // check headbanger one last time + //check headbanger one last time if ((node_jump.param0 == CONTENT_IGNORE) || - (m_ndef->get(node_jump).walkable)) { + (m_ndef->get(node_jump).walkable)) { headbanger = true; } - // did we find surface without banging our head? + //did we find surface without banging our head? if ((!headbanger) && (targetpos.Y <= m_limits.MaxEdge.Y) && (!m_ndef->get(node_target).walkable)) { if (targetpos.Y - pos2.Y <= m_maxjump) { - // SUCCESS! + //SUCCESS! retval.valid = true; retval.value = 2; retval.y_change = (targetpos.Y - pos2.Y); DEBUG_OUT("Pathfinder cost above found" << std::endl); - } else { - DEBUG_OUT("Pathfinder: distance to surface above too " - "big: " - << (targetpos.Y - pos2.Y) - << " max: " << m_maxjump << std::endl); } - } else { + else { + DEBUG_OUT("Pathfinder: distance to surface above too big: " + << (targetpos.Y - pos2.Y) << " max: " << m_maxjump + << std::endl); + } + } + else { DEBUG_OUT("Pathfinder: no surface above found" << std::endl); } } @@ -952,14 +976,17 @@ PathGridnode &Pathfinder::getIndexElement(v3s16 ipos) /******************************************************************************/ inline PathGridnode &Pathfinder::getIdxElem(s16 x, s16 y, s16 z) { - return m_nodes_container->access(v3s16(x, y, z)); + return m_nodes_container->access(v3s16(x,y,z)); } /******************************************************************************/ bool Pathfinder::isValidIndex(v3s16 index) { - if ((index.X < m_max_index_x) && (index.Y < m_max_index_y) && - (index.Z < m_max_index_z) && (index.X >= 0) && (index.Y >= 0) && + if ( (index.X < m_max_index_x) && + (index.Y < m_max_index_y) && + (index.Z < m_max_index_z) && + (index.X >= 0) && + (index.Y >= 0) && (index.Z >= 0)) return true; @@ -971,23 +998,26 @@ v3s16 Pathfinder::invert(v3s16 pos) { v3s16 retval = pos; - retval.X *= -1; - retval.Y *= -1; - retval.Z *= -1; + retval.X *=-1; + retval.Y *=-1; + retval.Z *=-1; return retval; } /******************************************************************************/ -bool Pathfinder::updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int level) +bool Pathfinder::updateAllCosts(v3s16 ipos, + v3s16 srcdir, + int current_cost, + int level) { PathGridnode &g_pos = getIndexElement(ipos); g_pos.totalcost = current_cost; g_pos.sourcedir = srcdir; - level++; + level ++; - // check if target has been found + //check if target has been found if (g_pos.target) { m_min_target_distance = current_cost; DEBUG_OUT(LVL " Pathfinder: target found!" << std::endl); @@ -998,7 +1028,11 @@ bool Pathfinder::updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int // the 4 cardinal directions const static v3s16 directions[4] = { - v3s16(1, 0, 0), v3s16(-1, 0, 0), v3s16(0, 0, 1), v3s16(0, 0, -1)}; + v3s16(1,0, 0), + v3s16(-1,0, 0), + v3s16(0,0, 1), + v3s16(0,0,-1) + }; for (v3s16 direction : directions) { if (direction != srcdir) { @@ -1010,20 +1044,16 @@ bool Pathfinder::updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int v3s16 ipos2 = ipos + direction; if (!isValidIndex(ipos2)) { - DEBUG_OUT(LVL " Pathfinder: " - << PP(ipos2) - << " out of range, max=" - << PP(m_limits.MaxEdge) - << std::endl); + DEBUG_OUT(LVL " Pathfinder: " << PP(ipos2) << + " out of range, max=" << PP(m_limits.MaxEdge) << std::endl); continue; } PathGridnode &g_pos2 = getIndexElement(ipos2); if (!g_pos2.valid) { - VERBOSE_TARGET << LVL "Pathfinder: no data for " - "new position: " - << PP(ipos2) << std::endl; + VERBOSE_TARGET << LVL "Pathfinder: no data for new position: " + << PP(ipos2) << std::endl; continue; } @@ -1039,22 +1069,23 @@ bool Pathfinder::updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int if ((g_pos2.totalcost < 0) || (g_pos2.totalcost > new_cost)) { - DEBUG_OUT(LVL "Pathfinder: updating path at: " - << PP(ipos2) << " from: " - << g_pos2.totalcost << " to " - << new_cost << std::endl); + DEBUG_OUT(LVL "Pathfinder: updating path at: "<< + PP(ipos2) << " from: " << g_pos2.totalcost << " to "<< + new_cost << std::endl); if (updateAllCosts(ipos2, invert(direction), - new_cost, level)) { + new_cost, level)) { retval = true; + } } - } else { + else { DEBUG_OUT(LVL "Pathfinder:" - " already found shorter path to: " + " already found shorter path to: " << PP(ipos2) << std::endl); } - } else { + } + else { DEBUG_OUT(LVL "Pathfinder:" - " not moving to invalid direction: " + " not moving to invalid direction: " << PP(directions[i]) << std::endl); } } @@ -1073,6 +1104,8 @@ int Pathfinder::getXZManhattanDist(v3s16 pos) return (max_x - min_x) + (max_z - min_z); } + + /******************************************************************************/ bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination) { @@ -1092,10 +1125,14 @@ bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination) // the 4 cardinal directions const static v3s16 directions[4] = { - v3s16(1, 0, 0), v3s16(-1, 0, 0), v3s16(0, 0, 1), v3s16(0, 0, -1)}; + v3s16(1,0, 0), + v3s16(-1,0, 0), + v3s16(0,0, 1), + v3s16(0,0,-1) + }; v3s16 current_pos; - PathGridnode &s_pos = getIndexElement(isource); + PathGridnode& s_pos = getIndexElement(isource); s_pos.source = true; s_pos.totalcost = 0; @@ -1112,14 +1149,12 @@ bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination) // check if node is inside searchdistance and valid if (!isValidIndex(ipos)) { - DEBUG_OUT(LVL " Pathfinder: " << PP(current_pos) - << " out of search distance, max=" - << PP(m_limits.MaxEdge) - << std::endl); + DEBUG_OUT(LVL " Pathfinder: " << PP(current_pos) << + " out of search distance, max=" << PP(m_limits.MaxEdge) << std::endl); continue; } - PathGridnode &g_pos = getIndexElement(ipos); + PathGridnode& g_pos = getIndexElement(ipos); g_pos.is_closed = true; g_pos.is_open = false; if (!g_pos.valid) { @@ -1142,8 +1177,7 @@ bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination) cost = calcCost(current_pos, direction_flat); g_pos.setCost(direction_flat, cost); } - // update Y component of direction if neighbor requires jump or - // fall + // update Y component of direction if neighbor requires jump or fall v3s16 direction_3d = v3s16(direction_flat); direction_3d.Y = cost.y_change; @@ -1153,15 +1187,13 @@ bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination) PathGridnode &n_pos = getIndexElement(ineighbor); if (cost.valid && !n_pos.is_closed && !n_pos.is_open) { - // heuristic function; estimate cost from neighbor to - // destination + // heuristic function; estimate cost from neighbor to destination cur_manhattan = getXZManhattanDist(neighbor); // add neighbor to open list n_pos.sourcedir = invert(direction_3d); n_pos.totalcost = current_totalcost + cost.value; - n_pos.estimated_cost = current_totalcost + cost.value + - cur_manhattan; + n_pos.estimated_cost = current_totalcost + cost.value + cur_manhattan; n_pos.is_open = true; openList.push(neighbor); } @@ -1175,21 +1207,16 @@ bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination) bool Pathfinder::buildPath(std::vector &path, v3s16 ipos) { // The cost calculation should have set a source direction for all relevant nodes. - // To build the path, we go backwards from the destination until we reach the - // start. - for (u32 waypoints = 1; waypoints++;) { + // To build the path, we go backwards from the destination until we reach the start. + for(u32 waypoints = 1; waypoints++; ) { if (waypoints > PATHFINDER_MAX_WAYPOINTS) { - ERROR_TARGET << "Pathfinder: buildPath: path is too long (too " - "many waypoints), aborting" - << std::endl; + ERROR_TARGET << "Pathfinder: buildPath: path is too long (too many waypoints), aborting" << std::endl; return false; } // Insert node into path PathGridnode &g_pos = getIndexElement(ipos); if (!g_pos.valid) { - ERROR_TARGET << "Pathfinder: buildPath: invalid next pos " - "detected, aborting" - << std::endl; + ERROR_TARGET << "Pathfinder: buildPath: invalid next pos detected, aborting" << std::endl; return false; } @@ -1208,8 +1235,7 @@ bool Pathfinder::buildPath(std::vector &path, v3s16 ipos) } /******************************************************************************/ -v3s16 Pathfinder::walkDownwards(v3s16 pos, unsigned int max_down) -{ +v3s16 Pathfinder::walkDownwards(v3s16 pos, unsigned int max_down) { if (max_down == 0) return pos; v3s16 testpos = v3s16(pos); @@ -1217,25 +1243,27 @@ v3s16 Pathfinder::walkDownwards(v3s16 pos, unsigned int max_down) unsigned int down = 0; while ((node_at_pos.param0 != CONTENT_IGNORE) && (!m_ndef->get(node_at_pos).walkable) && - (testpos.Y > m_limits.MinEdge.Y) && (down <= max_down)) { + (testpos.Y > m_limits.MinEdge.Y) && + (down <= max_down)) { testpos += v3s16(0, -1, 0); down++; node_at_pos = m_map->getNode(testpos); } - // did we find surface? - if ((testpos.Y >= m_limits.MinEdge.Y) && (node_at_pos.param0 != CONTENT_IGNORE) && + //did we find surface? + if ((testpos.Y >= m_limits.MinEdge.Y) && + (node_at_pos.param0 != CONTENT_IGNORE) && (m_ndef->get(node_at_pos).walkable)) { if (down == 0) { pos = testpos; } else if ((down - 1) <= max_down) { - // difference of y-pos +1 (target node is ABOVE solid node) + //difference of y-pos +1 (target node is ABOVE solid node) testpos += v3s16(0, 1, 0); pos = testpos; - } else { - VERBOSE_TARGET << "Pos too far above ground: " - << "Index: " << PP(getIndexPos(pos)) - << "Realpos: " << PP(getRealPos(getIndexPos(pos))) - << std::endl; + } + else { + VERBOSE_TARGET << "Pos too far above ground: " << + "Index: " << PP(getIndexPos(pos)) << + "Realpos: " << PP(getRealPos(getIndexPos(pos))) << std::endl; } } else { DEBUG_OUT("Pathfinder: no surface found below pos" << std::endl); @@ -1273,23 +1301,21 @@ void Pathfinder::printCost(PathDirections dir) std::cout << "Level: " << y << std::endl; - std::cout << std::setw(4) << " " - << " "; + std::cout << std::setw(4) << " " << " "; for (int x = 0; x < m_max_index_x; x++) { std::cout << std::setw(4) << x; } std::cout << std::endl; for (int z = 0; z < m_max_index_z; z++) { - std::cout << std::setw(4) << z << ": "; + std::cout << std::setw(4) << z <<": "; for (int x = 0; x < m_max_index_x; x++) { if (getIdxElem(x, y, z).directions[dir].valid) std::cout << std::setw(4) - << getIdxElem(x, y, z).directions[dir] - .value; + << getIdxElem(x, y, z).directions[dir].value; else std::cout << std::setw(4) << "-"; - } + } std::cout << std::endl; } std::cout << std::endl; @@ -1306,23 +1332,21 @@ void Pathfinder::printYdir(PathDirections dir) std::cout << "Level: " << y << std::endl; - std::cout << std::setw(4) << " " - << " "; + std::cout << std::setw(4) << " " << " "; for (int x = 0; x < m_max_index_x; x++) { std::cout << std::setw(4) << x; } std::cout << std::endl; for (int z = 0; z < m_max_index_z; z++) { - std::cout << std::setw(4) << z << ": "; + std::cout << std::setw(4) << z <<": "; for (int x = 0; x < m_max_index_x; x++) { if (getIdxElem(x, y, z).directions[dir].valid) std::cout << std::setw(4) - << getIdxElem(x, y, z).directions[dir] - .y_change; + << getIdxElem(x, y, z).directions[dir].y_change; else std::cout << std::setw(4) << "-"; - } + } std::cout << std::endl; } std::cout << std::endl; @@ -1339,15 +1363,14 @@ void Pathfinder::printType() std::cout << "Level: " << y << std::endl; - std::cout << std::setw(3) << " " - << " "; + std::cout << std::setw(3) << " " << " "; for (int x = 0; x < m_max_index_x; x++) { std::cout << std::setw(3) << x; } std::cout << std::endl; for (int z = 0; z < m_max_index_z; z++) { - std::cout << std::setw(3) << z << ": "; + std::cout << std::setw(3) << z <<": "; for (int x = 0; x < m_max_index_x; x++) { char toshow = getIdxElem(x, y, z).type; std::cout << std::setw(3) << toshow; @@ -1363,30 +1386,28 @@ void Pathfinder::printType() void Pathfinder::printPathLen() { std::cout << "Pathlen:" << std::endl; - std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl; - std::cout << std::setfill(' '); - for (int y = 0; y < m_max_index_y; y++) { + std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl; + std::cout << std::setfill(' '); + for (int y = 0; y < m_max_index_y; y++) { - std::cout << "Level: " << y << std::endl; - - std::cout << std::setw(3) << " " - << " "; - for (int x = 0; x < m_max_index_x; x++) { - std::cout << std::setw(3) << x; - } - std::cout << std::endl; + std::cout << "Level: " << y << std::endl; - for (int z = 0; z < m_max_index_z; z++) { - std::cout << std::setw(3) << z << ": "; + std::cout << std::setw(3) << " " << " "; for (int x = 0; x < m_max_index_x; x++) { - std::cout << std::setw(3) - << getIdxElem(x, y, z).totalcost; + std::cout << std::setw(3) << x; + } + std::cout << std::endl; + + for (int z = 0; z < m_max_index_z; z++) { + std::cout << std::setw(3) << z <<": "; + for (int x = 0; x < m_max_index_x; x++) { + std::cout << std::setw(3) << getIdxElem(x, y, z).totalcost; + } + std::cout << std::endl; } std::cout << std::endl; } std::cout << std::endl; - } - std::cout << std::endl; } /******************************************************************************/ @@ -1414,7 +1435,8 @@ std::string Pathfinder::dirToName(PathDirections dir) void Pathfinder::printPath(std::vector path) { unsigned int current = 0; - for (std::vector::iterator i = path.begin(); i != path.end(); ++i) { + for (std::vector::iterator i = path.begin(); + i != path.end(); ++i) { std::cout << std::setw(3) << current << ":" << PP((*i)) << std::endl; current++; } diff --git a/src/pathfinder.h b/src/pathfinder.h index f8a463361..526aa0ee8 100644 --- a/src/pathfinder.h +++ b/src/pathfinder.h @@ -36,8 +36,7 @@ class Map; /* Typedefs and macros */ /******************************************************************************/ -typedef enum -{ +typedef enum { DIR_XP, DIR_XM, DIR_ZP, @@ -45,11 +44,10 @@ typedef enum } PathDirections; /** List of supported algorithms */ -typedef enum -{ - PA_DIJKSTRA, /**< Dijkstra shortest path algorithm */ - PA_PLAIN, /**< A* algorithm using heuristics to find a path */ - PA_PLAIN_NP /**< A* algorithm without prefetching of map data */ +typedef enum { + PA_DIJKSTRA, /**< Dijkstra shortest path algorithm */ + PA_PLAIN, /**< A* algorithm using heuristics to find a path */ + PA_PLAIN_NP /**< A* algorithm without prefetching of map data */ } PathAlgorithm; /******************************************************************************/ @@ -57,6 +55,10 @@ typedef enum /******************************************************************************/ /** c wrapper function to use from scriptapi */ -std::vector get_path(Map *map, const NodeDefManager *ndef, v3s16 source, - v3s16 destination, unsigned int searchdistance, unsigned int max_jump, - unsigned int max_drop, PathAlgorithm algo); +std::vector get_path(Map *map, const NodeDefManager *ndef, + v3s16 source, + v3s16 destination, + unsigned int searchdistance, + unsigned int max_jump, + unsigned int max_drop, + PathAlgorithm algo); diff --git a/src/player.cpp b/src/player.cpp index ac6dc18b9..13b79da04 100644 --- a/src/player.cpp +++ b/src/player.cpp @@ -26,9 +26,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gamedef.h" #include "settings.h" #include "log.h" -#include "porting.h" // strlcpy +#include "porting.h" // strlcpy -Player::Player(const char *name, IItemDefManager *idef) : inventory(idef) + +Player::Player(const char *name, IItemDefManager *idef): + inventory(idef) { strlcpy(m_name, name, PLAYERNAME_SIZE); @@ -42,32 +44,33 @@ Player::Player(const char *name, IItemDefManager *idef) : inventory(idef) // Can be redefined via Lua inventory_formspec = "size[8,7.5]" - //"image[1,0.6;1,2;player.png]" - "list[current_player;main;0,3.5;8,4;]" - "list[current_player;craft;3,0;3,3;]" - "listring[]" - "list[current_player;craftpreview;7,1;1,1;]"; + //"image[1,0.6;1,2;player.png]" + "list[current_player;main;0,3.5;8,4;]" + "list[current_player;craft;3,0;3,3;]" + "listring[]" + "list[current_player;craftpreview;7,1;1,1;]"; // Initialize movement settings at default values, so movement can work // if the server fails to send them - movement_acceleration_default = 3 * BS; - movement_acceleration_air = 2 * BS; - movement_acceleration_fast = 10 * BS; - movement_speed_walk = 4 * BS; - movement_speed_crouch = 1.35 * BS; - movement_speed_fast = 20 * BS; - movement_speed_climb = 2 * BS; - movement_speed_jump = 6.5 * BS; - movement_liquid_fluidity = 1 * BS; - movement_liquid_fluidity_smooth = 0.5 * BS; - movement_liquid_sink = 10 * BS; - movement_gravity = 9.81 * BS; - local_animation_speed = 0.0; - - hud_flags = HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE | - HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE | - HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE | - HUD_FLAG_MINIMAP_RADAR_VISIBLE; + movement_acceleration_default = 3 * BS; + movement_acceleration_air = 2 * BS; + movement_acceleration_fast = 10 * BS; + movement_speed_walk = 4 * BS; + movement_speed_crouch = 1.35 * BS; + movement_speed_fast = 20 * BS; + movement_speed_climb = 2 * BS; + movement_speed_jump = 6.5 * BS; + movement_liquid_fluidity = 1 * BS; + movement_liquid_fluidity_smooth = 0.5 * BS; + movement_liquid_sink = 10 * BS; + movement_gravity = 9.81 * BS; + local_animation_speed = 0.0; + + hud_flags = + HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE | + HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE | + HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE | + HUD_FLAG_MINIMAP_RADAR_VISIBLE; hud_hotbar_itemcount = HUD_HOTBAR_ITEMCOUNT_DEFAULT; @@ -75,7 +78,7 @@ Player::Player(const char *name, IItemDefManager *idef) : inventory(idef) // Register player setting callbacks for (const std::string &name : m_player_settings.setting_names) g_settings->registerChangedCallback(name, - &Player::settingsChangedCallback, &m_player_settings); + &Player::settingsChangedCallback, &m_player_settings); } Player::~Player() @@ -83,7 +86,7 @@ Player::~Player() // m_player_settings becomes invalid, remove callbacks for (const std::string &name : m_player_settings.setting_names) g_settings->deregisterChangedCallback(name, - &Player::settingsChangedCallback, &m_player_settings); + &Player::settingsChangedCallback, &m_player_settings); clearHud(); } @@ -124,7 +127,7 @@ u32 Player::addHud(HudElement *toadd) return id; } -HudElement *Player::getHud(u32 id) +HudElement* Player::getHud(u32 id) { MutexAutoLock lock(m_mutex); @@ -134,11 +137,11 @@ HudElement *Player::getHud(u32 id) return NULL; } -HudElement *Player::removeHud(u32 id) +HudElement* Player::removeHud(u32 id) { MutexAutoLock lock(m_mutex); - HudElement *retval = NULL; + HudElement* retval = NULL; if (id < hud.size()) { retval = hud[id]; hud[id] = NULL; @@ -150,7 +153,7 @@ void Player::clearHud() { MutexAutoLock lock(m_mutex); - while (!hud.empty()) { + while(!hud.empty()) { delete hud.back(); hud.pop_back(); } diff --git a/src/player.h b/src/player.h index 9a7e1d5b6..f1b848a2a 100644 --- a/src/player.h +++ b/src/player.h @@ -29,8 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #define PLAYERNAME_SIZE 20 -#define PLAYERNAME_ALLOWED_CHARS \ - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" +#define PLAYERNAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" #define PLAYERNAME_ALLOWED_CHARS_USER_EXPL "'a' to 'z', 'A' to 'Z', '0' to '9', '-', '_'" struct PlayerFovSpec @@ -49,10 +48,22 @@ struct PlayerControl { PlayerControl() = default; - PlayerControl(bool a_up, bool a_down, bool a_left, bool a_right, bool a_jump, - bool a_aux1, bool a_sneak, bool a_zoom, bool a_LMB, bool a_RMB, - float a_pitch, float a_yaw, float a_sidew_move_joystick_axis, - float a_forw_move_joystick_axis) + PlayerControl( + bool a_up, + bool a_down, + bool a_left, + bool a_right, + bool a_jump, + bool a_aux1, + bool a_sneak, + bool a_zoom, + bool a_LMB, + bool a_RMB, + float a_pitch, + float a_yaw, + float a_sidew_move_joystick_axis, + float a_forw_move_joystick_axis + ) { up = a_up; down = a_down; @@ -97,9 +108,10 @@ struct PlayerSettings bool noclip = false; bool autojump = false; - const std::string setting_names[9] = {"free_move", "pitch_move", "fast_move", - "freecam", "continuous_forward", "always_fly_fast", - "aux1_descends", "noclip", "autojump"}; + const std::string setting_names[9] = { + "free_move", "pitch_move", "fast_move", "freecam", "continuous_forward", "always_fly_fast", + "aux1_descends", "noclip", "autojump" + }; void readGlobalSettings(); }; @@ -111,20 +123,27 @@ class Environment; class Player { public: + Player(const char *name, IItemDefManager *idef); virtual ~Player() = 0; DISABLE_CLASS_COPY(Player); - virtual void move(f32 dtime, Environment *env, f32 pos_max_d) {} + virtual void move(f32 dtime, Environment *env, f32 pos_max_d) + {} virtual void move(f32 dtime, Environment *env, f32 pos_max_d, std::vector *collision_info) + {} + + const v3f &getSpeed() const { + return m_speed; } - const v3f &getSpeed() const { return m_speed; } - - void setSpeed(const v3f &speed) { m_speed = speed; } + void setSpeed(const v3f &speed) + { + m_speed = speed; + } const char *getName() const { return m_name; } @@ -163,7 +182,7 @@ class Player std::string formspec_prepend; PlayerControl control; - const PlayerControl &getPlayerControl() { return control; } + const PlayerControl& getPlayerControl() { return control; } PlayerSettings &getPlayerSettings() { return m_player_settings; } static void settingsChangedCallback(const std::string &name, void *data); @@ -172,16 +191,22 @@ class Player void setWieldIndex(u16 index); u16 getWieldIndex() const { return m_wield_index; } - void setFov(const PlayerFovSpec &spec) { m_fov_override_spec = spec; } + void setFov(const PlayerFovSpec &spec) + { + m_fov_override_spec = spec; + } - const PlayerFovSpec &getFov() const { return m_fov_override_spec; } + const PlayerFovSpec &getFov() const + { + return m_fov_override_spec; + } u32 keyPressed = 0; - HudElement *getHud(u32 id); - u32 addHud(HudElement *hud); - HudElement *removeHud(u32 id); - void clearHud(); + HudElement* getHud(u32 id); + u32 addHud(HudElement* hud); + HudElement* removeHud(u32 id); + void clearHud(); u32 hud_flags; s32 hud_hotbar_itemcount; @@ -190,10 +215,9 @@ class Player char m_name[PLAYERNAME_SIZE]; v3f m_speed; u16 m_wield_index = 0; - PlayerFovSpec m_fov_override_spec = {0.0f, false, 0.0f}; + PlayerFovSpec m_fov_override_spec = { 0.0f, false, 0.0f }; std::vector hud; - private: // Protect some critical areas // hud for example can be modified by EmergeThread diff --git a/src/porting.cpp b/src/porting.cpp index dc247acbf..d902d3737 100644 --- a/src/porting.cpp +++ b/src/porting.cpp @@ -25,35 +25,35 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "porting.h" -#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) -#include -#include -extern char **environ; +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) + #include + #include + extern char **environ; #elif defined(_WIN32) -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include #endif #if !defined(_WIN32) -#include -#include -#if !defined(__ANDROID__) -#include -#endif + #include + #include + #if !defined(__ANDROID__) + #include + #endif #endif #if defined(__hpux) -#define _PSTAT64 -#include + #define _PSTAT64 + #include #endif #if defined(__ANDROID__) -#include "porting_android.h" + #include "porting_android.h" #endif #if defined(__APPLE__) -// For _NSGetEnviron() -// Related: https://gitlab.haskell.org/ghc/ghc/issues/2458 -#include + // For _NSGetEnviron() + // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458 + #include #endif #include "config.h" @@ -80,7 +80,7 @@ bool *signal_handler_killstatus() } #if !defined(_WIN32) // POSIX -#include + #include void signal_handler(int sig) { @@ -111,7 +111,7 @@ void signal_handler_init(void) } #else // _WIN32 -#include + #include BOOL WINAPI event_handler(DWORD sig) { @@ -123,8 +123,7 @@ BOOL WINAPI event_handler(DWORD sig) if (!g_killed) { dstream << "INFO: event_handler(): " << "Ctrl+C, Close Event, Logoff Event or Shutdown Event," - " shutting down." - << std::endl; + " shutting down." << std::endl; g_killed = true; } else { (void)signal(SIGINT, SIG_DFL); @@ -144,6 +143,7 @@ void signal_handler_init(void) #endif + /* Path mangler */ @@ -154,6 +154,7 @@ std::string path_user = ".."; std::string path_locale = path_share + DIR_DELIM + "locale"; std::string path_cache = path_user + DIR_DELIM + "cache"; + std::string getDataPath(const char *subpath) { return path_share + DIR_DELIM + subpath; @@ -163,8 +164,9 @@ void pathRemoveFile(char *path, char delim) { // Remove filename and path delimiter int i; - for (i = strlen(path) - 1; i >= 0; i--) { - if (path[i] == delim) + for(i = strlen(path)-1; i>=0; i--) + { + if(path[i] == delim) break; } path[i] = 0; @@ -172,8 +174,14 @@ void pathRemoveFile(char *path, char delim) bool detectMSVCBuildDir(const std::string &path) { - const char *ends[] = {"bin\\Release", "bin\\MinSizeRel", "bin\\RelWithDebInfo", - "bin\\Debug", "bin\\Build", NULL}; + const char *ends[] = { + "bin\\Release", + "bin\\MinSizeRel", + "bin\\RelWithDebInfo", + "bin\\Debug", + "bin\\Build", + NULL + }; return (!removeStringEnd(path, ends).empty()); } @@ -195,19 +203,20 @@ std::string get_sysinfo() GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo); VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize); - oss << "Windows/" << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major - << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor - << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build + oss << "Windows/" + << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major + << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor + << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build -#ifdef _WIN64 + #ifdef _WIN64 oss << "x86_64"; -#else + #else BOOL is64 = FALSE; if (IsWow64Process(GetCurrentProcess(), &is64) && is64) oss << "x86_64"; // 32-bit app on 64-bit OS else oss << "x86"; -#endif + #endif delete[] lpVersionInfo; delete[] filePath; @@ -216,10 +225,12 @@ std::string get_sysinfo() #else struct utsname osinfo; uname(&osinfo); - return std::string(osinfo.sysname) + "/" + osinfo.release + " " + osinfo.machine; + return std::string(osinfo.sysname) + "/" + + osinfo.release + " " + osinfo.machine; #endif } + bool getCurrentWorkingDir(char *buf, size_t len) { #ifdef _WIN32 @@ -230,15 +241,16 @@ bool getCurrentWorkingDir(char *buf, size_t len) #endif } + bool getExecPathFromProcfs(char *buf, size_t buflen) { #ifndef _WIN32 buflen--; ssize_t len; - if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 && - (len = readlink("/proc/curproc/file", buf, buflen)) == -1 && - (len = readlink("/proc/curproc/exe", buf, buflen)) == -1) + if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 && + (len = readlink("/proc/curproc/file", buf, buflen)) == -1 && + (len = readlink("/proc/curproc/exe", buf, buflen)) == -1) return false; buf[len] = '\0'; @@ -260,6 +272,7 @@ bool getCurrentExecPath(char *buf, size_t len) return true; } + //// Linux #elif defined(__linux__) @@ -271,6 +284,7 @@ bool getCurrentExecPath(char *buf, size_t len) return true; } + //// Mac OS X, Darwin #elif defined(__APPLE__) @@ -283,6 +297,7 @@ bool getCurrentExecPath(char *buf, size_t len) return true; } + //// FreeBSD, NetBSD, DragonFlyBSD #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) @@ -306,6 +321,7 @@ bool getCurrentExecPath(char *buf, size_t len) return true; } + //// Solaris #elif defined(__sun) || defined(sun) @@ -321,6 +337,7 @@ bool getCurrentExecPath(char *buf, size_t len) return true; } + // HP-UX #elif defined(__hpux) @@ -337,6 +354,7 @@ bool getCurrentExecPath(char *buf, size_t len) return true; } + #else bool getCurrentExecPath(char *buf, size_t len) @@ -346,6 +364,7 @@ bool getCurrentExecPath(char *buf, size_t len) #endif + //// Non-Windows #if !defined(_WIN32) @@ -353,12 +372,14 @@ const char *getHomeOrFail() { const char *home = getenv("HOME"); // In rare cases the HOME environment variable may be unset - FATAL_ERROR_IF(!home, "Required environment variable HOME is not set"); + FATAL_ERROR_IF(!home, + "Required environment variable HOME is not set"); return home; } #endif + //// Windows #if defined(_WIN32) @@ -368,7 +389,7 @@ bool setSystemPaths() // Find path of executable and set path_share relative to it FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)), - "Failed to get current executable path"); + "Failed to get current executable path"); pathRemoveFile(buf, '\\'); std::string exepath(buf); @@ -376,8 +397,8 @@ bool setSystemPaths() // Use ".\bin\.." path_share = exepath + "\\.."; if (detectMSVCBuildDir(exepath)) { - // The msvc build dir schould normaly not be present if properly - // installed, but its usefull for debugging. + // The msvc build dir schould normaly not be present if properly installed, + // but its usefull for debugging. path_share += DIR_DELIM ".."; } @@ -389,9 +410,9 @@ bool setSystemPaths() return true; } + //// Linux -#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ - defined(__DragonFly__) +#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) bool setSystemPaths() { @@ -399,7 +420,7 @@ bool setSystemPaths() if (!getCurrentExecPath(buf, sizeof(buf))) { #ifdef __ANDROID__ - errorstream << "Unable to read bindir " << std::endl; + errorstream << "Unable to read bindir "<< std::endl; #else FATAL_ERROR("Unable to read bindir"); #endif @@ -416,28 +437,28 @@ bool setSystemPaths() if (!static_sharedir.empty() && static_sharedir != ".") trylist.push_back(static_sharedir); - trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share" DIR_DELIM + - PROJECT_NAME); + trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share" + DIR_DELIM + PROJECT_NAME); trylist.push_back(bindir + DIR_DELIM ".."); #ifdef __ANDROID__ trylist.push_back(path_user); #endif - for (std::list::const_iterator i = trylist.begin(); - i != trylist.end(); ++i) { + for (std::list::const_iterator + i = trylist.begin(); i != trylist.end(); ++i) { const std::string &trypath = *i; if (!fs::PathExists(trypath) || - !fs::PathExists(trypath + DIR_DELIM + "builtin")) { - warningstream << "system-wide share not found at \"" << trypath - << "\"" << std::endl; + !fs::PathExists(trypath + DIR_DELIM + "builtin")) { + warningstream << "system-wide share not found at \"" + << trypath << "\""<< std::endl; continue; } // Warn if was not the first alternative if (i != trylist.begin()) { - warningstream << "system-wide share found at \"" << trypath - << "\"" << std::endl; + warningstream << "system-wide share found at \"" + << trypath << "\"" << std::endl; } path_share = trypath; @@ -445,12 +466,14 @@ bool setSystemPaths() } #ifndef __ANDROID__ - path_user = std::string(getHomeOrFail()) + DIR_DELIM "." + PROJECT_NAME; + path_user = std::string(getHomeOrFail()) + DIR_DELIM "." + + PROJECT_NAME; #endif return true; } + //// Mac OS X #elif defined(__APPLE__) @@ -459,29 +482,32 @@ bool setSystemPaths() CFBundleRef main_bundle = CFBundleGetMainBundle(); CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); char path[PATH_MAX]; - if (CFURLGetFileSystemRepresentation( - resources_url, TRUE, (UInt8 *)path, PATH_MAX)) { + if (CFURLGetFileSystemRepresentation(resources_url, + TRUE, (UInt8 *)path, PATH_MAX)) { path_share = std::string(path); } else { warningstream << "Could not determine bundle resource path" << std::endl; } CFRelease(resources_url); - path_user = std::string(getHomeOrFail()) + "/Library/Application Support/" + - PROJECT_NAME; + path_user = std::string(getHomeOrFail()) + + "/Library/Application Support/" + + PROJECT_NAME; return true; } + #else bool setSystemPaths() { path_share = STATIC_SHAREDIR; - path_user = std::string(getHomeOrFail()) + DIR_DELIM "." + - lowercase(PROJECT_NAME); + path_user = std::string(getHomeOrFail()) + DIR_DELIM "." + + lowercase(PROJECT_NAME); return true; } + #endif void migrateCachePath() @@ -494,14 +520,13 @@ void migrateCachePath() fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp"); // Bail if migration impossible - if (path_cache == local_cache_path || !fs::PathExists(local_cache_path) || - fs::PathExists(path_cache)) { + if (path_cache == local_cache_path || !fs::PathExists(local_cache_path) + || fs::PathExists(path_cache)) { return; } if (!fs::Rename(local_cache_path, path_cache)) { errorstream << "Failed to migrate local cache path " - "to system path!" - << std::endl; + "to system path!" << std::endl; } } @@ -512,24 +537,24 @@ void initializePaths() infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl; - bool success = getCurrentExecPath(buf, sizeof(buf)) || - getExecPathFromProcfs(buf, sizeof(buf)); + bool success = + getCurrentExecPath(buf, sizeof(buf)) || + getExecPathFromProcfs(buf, sizeof(buf)); if (success) { pathRemoveFile(buf, DIR_DELIM_CHAR); std::string execpath(buf); path_share = execpath + DIR_DELIM ".."; - path_user = execpath + DIR_DELIM ".."; + path_user = execpath + DIR_DELIM ".."; if (detectMSVCBuildDir(execpath)) { path_share += DIR_DELIM ".."; - path_user += DIR_DELIM ".."; + path_user += DIR_DELIM ".."; } } else { errorstream << "Failed to get paths by executable location, " - "trying cwd" - << std::endl; + "trying cwd" << std::endl; if (!getCurrentWorkingDir(buf, sizeof(buf))) FATAL_ERROR("Ran out of methods to get paths"); @@ -546,7 +571,7 @@ void initializePaths() std::string execpath(buf); path_share = execpath; - path_user = execpath; + path_user = execpath; } path_cache = path_user + DIR_DELIM + "cache"; #else @@ -555,9 +580,10 @@ void initializePaths() if (!setSystemPaths()) errorstream << "Failed to get one or more system-wide path" << std::endl; -#ifdef _WIN32 + +# ifdef _WIN32 path_cache = path_user + DIR_DELIM + "cache"; -#else +# else // Initialize path_cache // First try $XDG_CACHE_HOME/PROJECT_NAME const char *cache_dir = getenv("XDG_CACHE_HOME"); @@ -566,15 +592,15 @@ void initializePaths() path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME; } else if (home_dir) { // Then try $HOME/.cache/PROJECT_NAME - path_cache = std::string(home_dir) + DIR_DELIM + ".cache" + DIR_DELIM + - PROJECT_NAME; + path_cache = std::string(home_dir) + DIR_DELIM + ".cache" + + DIR_DELIM + PROJECT_NAME; } else { // If neither works, use $PATH_USER/cache path_cache = path_user + DIR_DELIM + "cache"; } // Migrate cache folder to new location if possible migrateCachePath(); -#endif // _WIN32 +# endif // _WIN32 #endif // RUN_IN_PLACE infostream << "Detected share path: " << path_share << std::endl; @@ -583,30 +609,30 @@ void initializePaths() #if USE_GETTEXT bool found_localedir = false; -#ifdef STATIC_LOCALEDIR +# ifdef STATIC_LOCALEDIR /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that * doesn't necessarily contain our locale files, so check data path first. */ path_locale = getDataPath("locale"); if (fs::PathExists(path_locale)) { found_localedir = true; infostream << "Using in-place locale directory " << path_locale - << " even though a static one was provided." << std::endl; + << " even though a static one was provided." << std::endl; } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) { found_localedir = true; path_locale = STATIC_LOCALEDIR; infostream << "Using static locale directory " << STATIC_LOCALEDIR - << std::endl; + << std::endl; } -#else +# else path_locale = getDataPath("locale"); if (fs::PathExists(path_locale)) { found_localedir = true; } -#endif +# endif if (!found_localedir) { warningstream << "Couldn't find a locale directory!" << std::endl; } -#endif // USE_GETTEXT +#endif // USE_GETTEXT } //// @@ -652,11 +678,8 @@ void attachOrCreateConsole() { #ifdef _WIN32 static bool consoleAllocated = false; - const bool redirected = (_fileno(stdout) == -2 || - _fileno(stdout) == -1); // If output is redirected to e.g - // a file - if (!consoleAllocated && redirected && - (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) { + const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file + if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) { freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); consoleAllocated = true; @@ -695,18 +718,17 @@ bool openURL(const std::string &url) } #if defined(_WIN32) - return (intptr_t)ShellExecuteA( - NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32; + return (intptr_t)ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32; #elif defined(__ANDROID__) openURLAndroid(url); return true; #elif defined(__APPLE__) const char *argv[] = {"open", url.c_str(), NULL}; - return posix_spawnp(NULL, "open", NULL, NULL, (char **)argv, - (*_NSGetEnviron())) == 0; + return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv, + (*_NSGetEnviron())) == 0; #else const char *argv[] = {"xdg-open", url.c_str(), NULL}; - return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char **)argv, environ) == 0; + return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0; #endif } @@ -724,4 +746,4 @@ double perf_freq = get_perf_freq(); #endif -} // namespace porting +} //namespace porting diff --git a/src/porting.h b/src/porting.h index e187b6e4b..f50f0a950 100644 --- a/src/porting.h +++ b/src/porting.h @@ -24,11 +24,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #ifdef _WIN32 -#ifdef _WIN32_WINNT -#undef _WIN32_WINNT -#endif -#define _WIN32_WINNT 0x0501 // We need to do this before any other headers -// because those might include sdkddkver.h which defines _WIN32_WINNT if not already set + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT 0x0501 // We need to do this before any other headers + // because those might include sdkddkver.h which defines _WIN32_WINNT if not already set #endif #include @@ -41,48 +41,48 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gettime.h" #ifdef _MSC_VER -#define SWPRINTF_CHARSTRING L"%S" + #define SWPRINTF_CHARSTRING L"%S" #else -#define SWPRINTF_CHARSTRING L"%s" + #define SWPRINTF_CHARSTRING L"%s" #endif -// currently not needed -// template struct alignment_trick { char c; T member; }; +//currently not needed +//template struct alignment_trick { char c; T member; }; //#define ALIGNOF(type) offsetof (alignment_trick, member) #ifdef _WIN32 -#include + #include -#define sleep_ms(x) Sleep(x) + #define sleep_ms(x) Sleep(x) #else -#include -#include //for uintptr_t - -// Use standard Posix macro for Linux -#if (defined(linux) || defined(__linux)) && !defined(__linux__) -#define __linux__ -#endif -#if (defined(__linux__) || defined(__GNU__)) && !defined(_GNU_SOURCE) -#define _GNU_SOURCE -#endif - -#define sleep_ms(x) usleep(x * 1000) + #include + #include //for uintptr_t + + // Use standard Posix macro for Linux + #if (defined(linux) || defined(__linux)) && !defined(__linux__) + #define __linux__ + #endif + #if (defined(__linux__) || defined(__GNU__)) && !defined(_GNU_SOURCE) + #define _GNU_SOURCE + #endif + + #define sleep_ms(x) usleep(x*1000) #endif #ifdef _MSC_VER -#define ALIGNOF(x) __alignof(x) -#define strtok_r(x, y, z) strtok_s(x, y, z) -#define strtof(x, y) (float)strtod(x, y) -#define strtoll(x, y, z) _strtoi64(x, y, z) -#define strtoull(x, y, z) _strtoui64(x, y, z) -#define strcasecmp(x, y) stricmp(x, y) -#define strncasecmp(x, y, n) strnicmp(x, y, n) + #define ALIGNOF(x) __alignof(x) + #define strtok_r(x, y, z) strtok_s(x, y, z) + #define strtof(x, y) (float)strtod(x, y) + #define strtoll(x, y, z) _strtoi64(x, y, z) + #define strtoull(x, y, z) _strtoui64(x, y, z) + #define strcasecmp(x, y) stricmp(x, y) + #define strncasecmp(x, y, n) strnicmp(x, y, n) #else -#define ALIGNOF(x) __alignof__(x) + #define ALIGNOF(x) __alignof__(x) #endif #ifdef __MINGW32__ -#define strtok_r(x, y, z) mystrtok_r(x, y, z) + #define strtok_r(x, y, z) mystrtok_r(x, y, z) #endif // strlcpy is missing from glibc. thanks a lot, drepper. @@ -90,33 +90,34 @@ with this program; if not, write to the Free Software Foundation, Inc., // We can't simply alias strlcpy to MSVC's strcpy_s, since strcpy_s by // default raises an assertion error and aborts the program if the buffer is // too small. -#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ - defined(__DragonFly__) || defined(__APPLE__) || defined(__sun) || \ - defined(sun) || defined(__QNX__) || defined(__QNXNTO__) -#define HAVE_STRLCPY +#if defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__OpenBSD__) || defined(__DragonFly__) || \ + defined(__APPLE__) || \ + defined(__sun) || defined(sun) || \ + defined(__QNX__) || defined(__QNXNTO__) + #define HAVE_STRLCPY #endif // So we need to define our own. #ifndef HAVE_STRLCPY -#define strlcpy(d, s, n) mystrlcpy(d, s, n) + #define strlcpy(d, s, n) mystrlcpy(d, s, n) #endif -#define PADDING(x, y) \ - ((ALIGNOF(y) - ((uintptr_t)(x) & (ALIGNOF(y) - 1))) & (ALIGNOF(y) - 1)) +#define PADDING(x, y) ((ALIGNOF(y) - ((uintptr_t)(x) & (ALIGNOF(y) - 1))) & (ALIGNOF(y) - 1)) #if defined(__APPLE__) -#include -#include + #include + #include #endif #ifndef _WIN32 // Posix -#include -#include + #include + #include #if defined(__MACH__) && defined(__APPLE__) -#include -#include -#endif + #include + #include + #endif #endif namespace porting @@ -129,7 +130,7 @@ namespace porting void signal_handler_init(); // Returns a pointer to a bool. // When the bool is true, program should quit. -bool *signal_handler_killstatus(); +bool * signal_handler_killstatus(); /* Path of static data directory. @@ -177,6 +178,7 @@ void initializePaths(); */ std::string get_sysinfo(); + // Monotonic counter getters. #ifdef _WIN32 // Windows @@ -191,31 +193,18 @@ inline u64 os_get_time(double mult) } // Resolution is <1us. -inline u64 getTimeS() -{ - return os_get_time(1); -} -inline u64 getTimeMs() -{ - return os_get_time(1000); -} -inline u64 getTimeUs() -{ - return os_get_time(1000 * 1000); -} -inline u64 getTimeNs() -{ - return os_get_time(1000 * 1000 * 1000); -} +inline u64 getTimeS() { return os_get_time(1); } +inline u64 getTimeMs() { return os_get_time(1000); } +inline u64 getTimeUs() { return os_get_time(1000*1000); } +inline u64 getTimeNs() { return os_get_time(1000*1000*1000); } #else // Posix inline void os_get_clock(struct timespec *ts) { #if defined(__MACH__) && defined(__APPLE__) - // From - // http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x - // OS X does not have clock_gettime, use clock_get_time +// From http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x +// OS X does not have clock_gettime, use clock_get_time clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); @@ -267,14 +256,10 @@ inline u64 getTimeNs() inline u64 getTime(TimePrecision prec) { switch (prec) { - case PRECISION_SECONDS: - return getTimeS(); - case PRECISION_MILLI: - return getTimeMs(); - case PRECISION_MICRO: - return getTimeUs(); - case PRECISION_NANO: - return getTimeNs(); + case PRECISION_SECONDS: return getTimeS(); + case PRECISION_MILLI: return getTimeMs(); + case PRECISION_MICRO: return getTimeUs(); + case PRECISION_NANO: return getTimeNs(); } FATAL_ERROR("Called getTime with invalid time precision"); } @@ -298,44 +283,44 @@ inline const char *getPlatformName() { return #if defined(ANDROID) - "Android" + "Android" #elif defined(__linux__) - "Linux" + "Linux" #elif defined(_WIN32) || defined(_WIN64) - "Windows" -#elif defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ - defined(__OpenBSD__) - "BSD" + "Windows" +#elif defined(__DragonFly__) || defined(__FreeBSD__) || \ + defined(__NetBSD__) || defined(__OpenBSD__) + "BSD" #elif defined(__APPLE__) && defined(__MACH__) -#if TARGET_OS_MAC - "OSX" -#elif TARGET_OS_IPHONE - "iOS" -#else - "Apple" -#endif + #if TARGET_OS_MAC + "OSX" + #elif TARGET_OS_IPHONE + "iOS" + #else + "Apple" + #endif #elif defined(_AIX) - "AIX" + "AIX" #elif defined(__hpux) - "HP-UX" + "HP-UX" #elif defined(__sun) || defined(sun) -#if defined(__SVR4) - "Solaris" -#else - "SunOS" -#endif + #if defined(__SVR4) + "Solaris" + #else + "SunOS" + #endif #elif defined(__CYGWIN__) - "Cygwin" + "Cygwin" #elif defined(__unix__) || defined(__unix) -#if defined(_POSIX_VERSION) - "Posix" -#else - "Unix" -#endif + #if defined(_POSIX_VERSION) + "Posix" + #else + "Unix" + #endif #else - "?" + "?" #endif - ; + ; } bool secure_rand_fill_buf(void *buf, size_t len); diff --git a/src/porting_android.cpp b/src/porting_android.cpp index f3754d835..41b521ec2 100644 --- a/src/porting_android.cpp +++ b/src/porting_android.cpp @@ -51,8 +51,7 @@ void android_main(android_app *app) main(ARRLEN(argv) - 1, argv); free(argv[0]); } catch (std::exception &e) { - errorstream << "Uncaught exception in main thread: " << e.what() - << std::endl; + errorstream << "Uncaught exception in main thread: " << e.what() << std::endl; retval = -1; } catch (...) { errorstream << "Uncaught exception in main thread!" << std::endl; @@ -70,20 +69,19 @@ void android_main(android_app *app) * ToDo: this doesn't work as expected, there's a workaround for it right now */ extern "C" { -JNIEXPORT void JNICALL Java_net_minetest_minetest_GameActivity_putMessageBoxResult( - JNIEnv *env, jclass thiz, jstring text) -{ - errorstream << "Java_net_minetest_minetest_GameActivity_putMessageBoxResult got: " - << std::string((const char *)env->GetStringChars(text, nullptr)) - << std::endl; -} + JNIEXPORT void JNICALL Java_net_minetest_minetest_GameActivity_putMessageBoxResult( + JNIEnv *env, jclass thiz, jstring text) + { + errorstream << + "Java_net_minetest_minetest_GameActivity_putMessageBoxResult got: " << + std::string((const char*) env->GetStringChars(text, nullptr)) << std::endl; + } } -namespace porting -{ +namespace porting { android_app *app_global; -JNIEnv *jnienv; -jclass nativeActivity; +JNIEnv *jnienv; +jclass nativeActivity; jclass findClass(const std::string &classname) { @@ -94,12 +92,12 @@ jclass findClass(const std::string &classname) jmethodID getClassLoader = jnienv->GetMethodID( nativeactivity, "getClassLoader", "()Ljava/lang/ClassLoader;"); jobject cls = jnienv->CallObjectMethod( - app_global->activity->clazz, getClassLoader); + app_global->activity->clazz, getClassLoader); jclass classLoader = jnienv->FindClass("java/lang/ClassLoader"); jmethodID findClass = jnienv->GetMethodID(classLoader, "loadClass", - "(Ljava/lang/String;)Ljava/lang/Class;"); + "(Ljava/lang/String;)Ljava/lang/Class;"); jstring strClassName = jnienv->NewStringUTF(classname.c_str()); - return (jclass)jnienv->CallObjectMethod(cls, findClass, strClassName); + return (jclass) jnienv->CallObjectMethod(cls, findClass, strClassName); } void initAndroid() @@ -118,14 +116,14 @@ void initAndroid() nativeActivity = findClass("net/minetest/minetest/GameActivity"); if (nativeActivity == nullptr) - errorstream << "porting::initAndroid unable to find java native activity " - "class" - << std::endl; + errorstream << + "porting::initAndroid unable to find java native activity class" << + std::endl; #ifdef GPROF // in the start-up code - __android_log_print( - ANDROID_LOG_ERROR, PROJECT_NAME_C, "Initializing GPROF profiler"); + __android_log_print(ANDROID_LOG_ERROR, PROJECT_NAME_C, + "Initializing GPROF profiler"); monstartup("libMinetest.so"); #endif } @@ -173,7 +171,7 @@ static std::string getAndroidPath( ob_file = jnienv->CallStaticObjectMethod(cls, mt_getter); // Call getAbsolutePath - auto js_path = (jstring)jnienv->CallObjectMethod(ob_file, mt_getAbsPath); + auto js_path = (jstring) jnienv->CallObjectMethod(ob_file, mt_getAbsPath); return javaStringToUTF8(js_path); } @@ -185,15 +183,15 @@ void initializePathsAndroid() // Get File class jclass cls_File = jnienv->FindClass("java/io/File"); // Get getAbsolutePath method - jmethodID mt_getAbsPath = jnienv->GetMethodID( - cls_File, "getAbsolutePath", "()Ljava/lang/String;"); - std::string path_storage = getAndroidPath( - cls_Env, nullptr, mt_getAbsPath, "getExternalStorageDirectory"); - - path_user = path_storage + DIR_DELIM + PROJECT_NAME_C; - path_share = path_storage + DIR_DELIM + PROJECT_NAME_C; - path_cache = getAndroidPath(nativeActivity, app_global->activity->clazz, - mt_getAbsPath, "getCacheDir"); + jmethodID mt_getAbsPath = jnienv->GetMethodID(cls_File, + "getAbsolutePath", "()Ljava/lang/String;"); + std::string path_storage = getAndroidPath(cls_Env, nullptr, + mt_getAbsPath, "getExternalStorageDirectory"); + + path_user = path_storage + DIR_DELIM + PROJECT_NAME_C; + path_share = path_storage + DIR_DELIM + PROJECT_NAME_C; + path_cache = getAndroidPath(nativeActivity, + app_global->activity->clazz, mt_getAbsPath, "getCacheDir"); migrateCachePath(); } @@ -201,27 +199,27 @@ void showInputDialog(const std::string &acceptButton, const std::string &hint, const std::string ¤t, int editType) { jmethodID showdialog = jnienv->GetMethodID(nativeActivity, "showDialog", - "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V"); + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V"); - FATAL_ERROR_IF(showdialog == nullptr, "porting::showInputDialog unable to find " - "java show dialog method"); + FATAL_ERROR_IF(showdialog == nullptr, + "porting::showInputDialog unable to find java show dialog method"); jstring jacceptButton = jnienv->NewStringUTF(acceptButton.c_str()); - jstring jhint = jnienv->NewStringUTF(hint.c_str()); - jstring jcurrent = jnienv->NewStringUTF(current.c_str()); - jint jeditType = editType; + jstring jhint = jnienv->NewStringUTF(hint.c_str()); + jstring jcurrent = jnienv->NewStringUTF(current.c_str()); + jint jeditType = editType; - jnienv->CallVoidMethod(app_global->activity->clazz, showdialog, jacceptButton, - jhint, jcurrent, jeditType); + jnienv->CallVoidMethod(app_global->activity->clazz, showdialog, + jacceptButton, jhint, jcurrent, jeditType); } void openURLAndroid(const std::string &url) { - jmethodID url_open = jnienv->GetMethodID( - nativeActivity, "openURL", "(Ljava/lang/String;)V"); + jmethodID url_open = jnienv->GetMethodID(nativeActivity, "openURL", + "(Ljava/lang/String;)V"); FATAL_ERROR_IF(url_open == nullptr, - "porting::openURLAndroid unable to find java openURL method"); + "porting::openURLAndroid unable to find java openURL method"); jstring jurl = jnienv->NewStringUTF(url.c_str()); jnienv->CallVoidMethod(app_global->activity->clazz, url_open, jurl); @@ -229,29 +227,29 @@ void openURLAndroid(const std::string &url) int getInputDialogState() { - jmethodID dialogstate = - jnienv->GetMethodID(nativeActivity, "getDialogState", "()I"); + jmethodID dialogstate = jnienv->GetMethodID(nativeActivity, + "getDialogState", "()I"); - FATAL_ERROR_IF(dialogstate == nullptr, "porting::getInputDialogState unable to " - "find java dialog state method"); + FATAL_ERROR_IF(dialogstate == nullptr, + "porting::getInputDialogState unable to find java dialog state method"); return jnienv->CallIntMethod(app_global->activity->clazz, dialogstate); } std::string getInputDialogValue() { - jmethodID dialogvalue = jnienv->GetMethodID( - nativeActivity, "getDialogValue", "()Ljava/lang/String;"); + jmethodID dialogvalue = jnienv->GetMethodID(nativeActivity, + "getDialogValue", "()Ljava/lang/String;"); - FATAL_ERROR_IF(dialogvalue == nullptr, "porting::getInputDialogValue unable to " - "find java dialog value method"); + FATAL_ERROR_IF(dialogvalue == nullptr, + "porting::getInputDialogValue unable to find java dialog value method"); - jobject result = jnienv->CallObjectMethod( - app_global->activity->clazz, dialogvalue); + jobject result = jnienv->CallObjectMethod(app_global->activity->clazz, + dialogvalue); - const char *javachars = jnienv->GetStringUTFChars((jstring)result, nullptr); + const char *javachars = jnienv->GetStringUTFChars((jstring) result, nullptr); std::string text(javachars); - jnienv->ReleaseStringUTFChars((jstring)result, javachars); + jnienv->ReleaseStringUTFChars((jstring) result, javachars); return text; } @@ -263,11 +261,11 @@ float getDisplayDensity() static float value = 0; if (firstrun) { - jmethodID getDensity = - jnienv->GetMethodID(nativeActivity, "getDensity", "()F"); + jmethodID getDensity = jnienv->GetMethodID(nativeActivity, + "getDensity", "()F"); - FATAL_ERROR_IF(getDensity == nullptr, "porting::getDisplayDensity unable " - "to find java getDensity method"); + FATAL_ERROR_IF(getDensity == nullptr, + "porting::getDisplayDensity unable to find java getDensity method"); value = jnienv->CallFloatMethod(app_global->activity->clazz, getDensity); firstrun = false; @@ -281,25 +279,23 @@ v2u32 getDisplaySize() static v2u32 retval; if (firstrun) { - jmethodID getDisplayWidth = jnienv->GetMethodID( - nativeActivity, "getDisplayWidth", "()I"); + jmethodID getDisplayWidth = jnienv->GetMethodID(nativeActivity, + "getDisplayWidth", "()I"); FATAL_ERROR_IF(getDisplayWidth == nullptr, - "porting::getDisplayWidth unable to find java " - "getDisplayWidth method"); + "porting::getDisplayWidth unable to find java getDisplayWidth method"); - retval.X = jnienv->CallIntMethod( - app_global->activity->clazz, getDisplayWidth); + retval.X = jnienv->CallIntMethod(app_global->activity->clazz, + getDisplayWidth); - jmethodID getDisplayHeight = jnienv->GetMethodID( - nativeActivity, "getDisplayHeight", "()I"); + jmethodID getDisplayHeight = jnienv->GetMethodID(nativeActivity, + "getDisplayHeight", "()I"); FATAL_ERROR_IF(getDisplayHeight == nullptr, - "porting::getDisplayHeight unable to find java " - "getDisplayHeight method"); + "porting::getDisplayHeight unable to find java getDisplayHeight method"); - retval.Y = jnienv->CallIntMethod( - app_global->activity->clazz, getDisplayHeight); + retval.Y = jnienv->CallIntMethod(app_global->activity->clazz, + getDisplayHeight); firstrun = false; } diff --git a/src/porting_android.h b/src/porting_android.h index da78379b4..6eb054041 100644 --- a/src/porting_android.h +++ b/src/porting_android.h @@ -29,8 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include -namespace porting -{ +namespace porting { // java app extern android_app *app_global; @@ -56,8 +55,8 @@ void initializePathsAndroid(); * @param editType type of texfield * (1==multiline text input; 2==single line text input; 3=password field) */ -void showInputDialog(const std::string &acceptButton, const std::string &hint, - const std::string ¤t, int editType); +void showInputDialog(const std::string &acceptButton, + const std::string &hint, const std::string ¤t, int editType); void openURLAndroid(const std::string &url); diff --git a/src/profiler.h b/src/profiler.h index a68043d2a..b4a0657f9 100644 --- a/src/profiler.h +++ b/src/profiler.h @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "threading/mutex_auto_lock.h" #include "util/timetaker.h" -#include "util/numeric.h" // paging() +#include "util/numeric.h" // paging() // Global profiler class Profiler; @@ -56,11 +56,13 @@ class Profiler int print(std::ostream &o, u32 page = 1, u32 pagecount = 1); void getPage(GraphValues &o, u32 page, u32 pagecount); + void graphAdd(const std::string &id, float value) { MutexAutoLock lock(m_mutex); - std::map::iterator i = m_graphvalues.find(id); - if (i == m_graphvalues.end()) + std::map::iterator i = + m_graphvalues.find(id); + if(i == m_graphvalues.end()) m_graphvalues[id] = value; else i->second += value; @@ -72,7 +74,7 @@ class Profiler m_graphvalues.clear(); } - void remove(const std::string &name) + void remove(const std::string& name) { MutexAutoLock lock(m_mutex); m_avgcounts.erase(name); @@ -87,8 +89,7 @@ class Profiler u64 m_start_time; }; -enum ScopeProfilerType -{ +enum ScopeProfilerType{ SPT_ADD, SPT_AVG, SPT_GRAPH_ADD @@ -100,7 +101,6 @@ class ScopeProfiler ScopeProfiler(Profiler *profiler, const std::string &name, ScopeProfilerType type = SPT_ADD); ~ScopeProfiler(); - private: Profiler *m_profiler = nullptr; std::string m_name; diff --git a/src/raycast.cpp b/src/raycast.cpp index bb13e6108..a1993606f 100644 --- a/src/raycast.cpp +++ b/src/raycast.cpp @@ -22,7 +22,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irr_aabb3d.h" #include "constants.h" -bool RaycastSort::operator()(const PointedThing &pt1, const PointedThing &pt2) const +bool RaycastSort::operator() (const PointedThing &pt1, + const PointedThing &pt2) const { // "nothing" can not be sorted assert(pt1.type != POINTEDTHING_NOTHING); @@ -45,27 +46,30 @@ bool RaycastSort::operator()(const PointedThing &pt1, const PointedThing &pt2) c if (pt1_distSq == pt2.distanceSq) { // Sort them to allow only one order if (pt1.type == POINTEDTHING_OBJECT) - return (pt2.type == POINTEDTHING_OBJECT && - pt1.object_id < pt2.object_id); + return (pt2.type == POINTEDTHING_OBJECT + && pt1.object_id < pt2.object_id); - return (pt2.type == POINTEDTHING_OBJECT || - pt1.node_undersurface < pt2.node_undersurface); + return (pt2.type == POINTEDTHING_OBJECT + || pt1.node_undersurface < pt2.node_undersurface); } return true; } -RaycastState::RaycastState(const core::line3d &shootline, bool objects_pointable, - bool liquids_pointable, bool nodes_pointable) : - m_shootline(shootline), - m_iterator(shootline.start / BS, shootline.getVector() / BS), - m_previous_node(m_iterator.m_current_node_pos), - m_objects_pointable(objects_pointable), - m_liquids_pointable(liquids_pointable), m_nodes_pointable(nodes_pointable) + +RaycastState::RaycastState(const core::line3d &shootline, + bool objects_pointable, bool liquids_pointable, bool nodes_pointable) : + m_shootline(shootline), + m_iterator(shootline.start / BS, shootline.getVector() / BS), + m_previous_node(m_iterator.m_current_node_pos), + m_objects_pointable(objects_pointable), + m_liquids_pointable(liquids_pointable), + m_nodes_pointable(nodes_pointable) { } -bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir, - v3f *collision_point, v3s16 *collision_normal) + +bool boxLineCollision(const aabb3f &box, const v3f &start, + const v3f &dir, v3f *collision_point, v3s16 *collision_normal) { if (box.isPointInside(start)) { *collision_point = start; @@ -83,10 +87,10 @@ bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir, if (m >= 0 && m <= 1) { *collision_point = start + dir * m; - if ((collision_point->Y >= box.MinEdge.Y) && - (collision_point->Y <= box.MaxEdge.Y) && - (collision_point->Z >= box.MinEdge.Z) && - (collision_point->Z <= box.MaxEdge.Z)) { + if ((collision_point->Y >= box.MinEdge.Y) + && (collision_point->Y <= box.MaxEdge.Y) + && (collision_point->Z >= box.MinEdge.Z) + && (collision_point->Z <= box.MaxEdge.Z)) { collision_normal->set((dir.X > 0) ? -1 : 1, 0, 0); return true; } @@ -102,10 +106,10 @@ bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir, if (m >= 0 && m <= 1) { *collision_point = start + dir * m; - if ((collision_point->X >= box.MinEdge.X) && - (collision_point->X <= box.MaxEdge.X) && - (collision_point->Z >= box.MinEdge.Z) && - (collision_point->Z <= box.MaxEdge.Z)) { + if ((collision_point->X >= box.MinEdge.X) + && (collision_point->X <= box.MaxEdge.X) + && (collision_point->Z >= box.MinEdge.Z) + && (collision_point->Z <= box.MaxEdge.Z)) { collision_normal->set(0, (dir.Y > 0) ? -1 : 1, 0); return true; } @@ -121,10 +125,10 @@ bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir, if (m >= 0 && m <= 1) { *collision_point = start + dir * m; - if ((collision_point->X >= box.MinEdge.X) && - (collision_point->X <= box.MaxEdge.X) && - (collision_point->Y >= box.MinEdge.Y) && - (collision_point->Y <= box.MaxEdge.Y)) { + if ((collision_point->X >= box.MinEdge.X) + && (collision_point->X <= box.MaxEdge.X) + && (collision_point->Y >= box.MinEdge.Y) + && (collision_point->Y <= box.MaxEdge.Y)) { collision_normal->set(0, 0, (dir.Z > 0) ? -1 : 1); return true; } diff --git a/src/raycast.h b/src/raycast.h index 38190287f..4f5ca2a5b 100644 --- a/src/raycast.h +++ b/src/raycast.h @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., //! Sorts PointedThings based on their distance. struct RaycastSort { - bool operator()(const PointedThing &pt1, const PointedThing &pt2) const; + bool operator() (const PointedThing &pt1, const PointedThing &pt2) const; }; //! Describes the state of a raycast. @@ -38,7 +38,7 @@ class RaycastState * @param liquids pointable if false, liquid nodes won't be found */ RaycastState(const core::line3d &shootline, bool objects_pointable, - bool liquids_pointable, bool nodes_pointable = true); + bool liquids_pointable, bool nodes_pointable = true); //! Shootline of the raycast. core::line3d m_shootline; @@ -58,7 +58,7 @@ class RaycastState bool m_nodes_pointable; //! The code needs to search these nodes around the center node. - core::aabbox3d m_search_range{0, 0, 0, 0, 0, 0}; + core::aabbox3d m_search_range { 0, 0, 0, 0, 0, 0 }; //! If true, the Environment will initialize this state. bool m_initialization_needed = true; @@ -75,4 +75,4 @@ class RaycastState * @returns true if a collision point was found */ bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir, - v3f *collision_point, v3s16 *collision_normal); + v3f *collision_point, v3s16 *collision_normal); diff --git a/src/reflowscan.cpp b/src/reflowscan.cpp index 2b2581cfc..9d5c965d8 100644 --- a/src/reflowscan.cpp +++ b/src/reflowscan.cpp @@ -23,7 +23,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "util/timetaker.h" -ReflowScan::ReflowScan(Map *map, const NodeDefManager *ndef) : m_map(map), m_ndef(ndef) + +ReflowScan::ReflowScan(Map *map, const NodeDefManager *ndef) : + m_map(map), + m_ndef(ndef) { } @@ -45,9 +48,9 @@ void ReflowScan::scan(MapBlock *block, UniqueQueue *liquid_queue) // Scan the columns in the block for (s16 z = 0; z < MAP_BLOCKSIZE; z++) - for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { - scanColumn(x, z); - } + for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { + scanColumn(x, z); + } // Scan neighbouring columns from the nearby blocks as they might contain // liquid nodes that weren't allowed to flow to prevent gaps. @@ -91,9 +94,9 @@ inline bool ReflowScan::isLiquidFlowableTo(int x, int y, int z) MapNode node = block->getNodeNoCheck(dx, dy, dz, &valid_position); if (node.getContent() != CONTENT_IGNORE) { const ContentFeatures &f = m_ndef->get(node); - // NOTE: No need to check for flowing nodes with lower liquid - // level as they should only occur on top of other columns where - // they will be added to the queue themselves. + // NOTE: No need to check for flowing nodes with lower liquid level + // as they should only occur on top of other columns where they + // will be added to the queue themselves. return f.floodable; } } @@ -104,8 +107,10 @@ inline bool ReflowScan::isLiquidHorizontallyFlowable(int x, int y, int z) { // Check if the (x,y,z) might spread to one of the horizontally // neighbouring nodes - return isLiquidFlowableTo(x - 1, y, z) || isLiquidFlowableTo(x + 1, y, z) || - isLiquidFlowableTo(x, y, z - 1) || isLiquidFlowableTo(x, y, z + 1); + return isLiquidFlowableTo(x - 1, y, z) || + isLiquidFlowableTo(x + 1, y, z) || + isLiquidFlowableTo(x, y, z - 1) || + isLiquidFlowableTo(x, y, z + 1); } void ReflowScan::scanColumn(int x, int z) @@ -142,8 +147,7 @@ void ReflowScan::scanColumn(int x, int z) bool is_liquid = f.isLiquid(); if (is_ignore || was_ignore || is_liquid == was_liquid) { - // Neither topmost node of liquid column nor topmost node below - // column + // Neither topmost node of liquid column nor topmost node below column was_checked = false; was_pushed = false; } else if (is_liquid) { @@ -151,8 +155,7 @@ void ReflowScan::scanColumn(int x, int z) bool is_pushed = false; if (f.liquid_type == LIQUID_FLOWING || isLiquidHorizontallyFlowable(x, y, z)) { - m_liquid_queue->push_back( - m_rel_block_pos + v3s16(x, y, z)); + m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, y, z)); is_pushed = true; } // Remember waschecked and waspushed to avoid repeated @@ -161,16 +164,11 @@ void ReflowScan::scanColumn(int x, int z) was_pushed = is_pushed; } else { // This is the topmost node below a liquid column - if (!was_pushed && - (f.floodable || (!was_checked && - isLiquidHorizontallyFlowable( - x, - y + 1, - z)))) { + if (!was_pushed && (f.floodable || + (!was_checked && isLiquidHorizontallyFlowable(x, y + 1, z)))) { // Activate the lowest node in the column which is one // node above this one - m_liquid_queue->push_back( - m_rel_block_pos + v3s16(x, y + 1, z)); + m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, y + 1, z)); } } @@ -181,35 +179,26 @@ void ReflowScan::scanColumn(int x, int z) // Check the node below the current block MapBlock *below = lookupBlock(x, -1, z); if (below) { - MapNode node = below->getNodeNoCheck( - dx, MAP_BLOCKSIZE - 1, dz, &valid_position); + MapNode node = below->getNodeNoCheck(dx, MAP_BLOCKSIZE - 1, dz, &valid_position); const ContentFeatures &f = m_ndef->get(node); bool is_ignore = node.getContent() == CONTENT_IGNORE; bool is_liquid = f.isLiquid(); if (is_ignore || was_ignore || is_liquid == was_liquid) { - // Neither topmost node of liquid column nor topmost node below - // column + // Neither topmost node of liquid column nor topmost node below column } else if (is_liquid) { - // This is the topmost node in the column and might want to flow - // away + // This is the topmost node in the column and might want to flow away if (f.liquid_type == LIQUID_FLOWING || isLiquidHorizontallyFlowable(x, -1, z)) { - m_liquid_queue->push_back( - m_rel_block_pos + v3s16(x, -1, z)); + m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, -1, z)); } } else { // This is the topmost node below a liquid column - if (!was_pushed && - (f.floodable || (!was_checked && - isLiquidHorizontallyFlowable( - x, - 0, - z)))) { + if (!was_pushed && (f.floodable || + (!was_checked && isLiquidHorizontallyFlowable(x, 0, z)))) { // Activate the lowest node in the column which is one // node above this one - m_liquid_queue->push_back( - m_rel_block_pos + v3s16(x, 0, z)); + m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, 0, z)); } } } diff --git a/src/reflowscan.h b/src/reflowscan.h index 29f35d2d8..7961432bd 100644 --- a/src/reflowscan.h +++ b/src/reflowscan.h @@ -26,8 +26,7 @@ class NodeDefManager; class Map; class MapBlock; -class ReflowScan -{ +class ReflowScan { public: ReflowScan(Map *map, const NodeDefManager *ndef); void scan(MapBlock *block, UniqueQueue *liquid_queue); diff --git a/src/remoteplayer.cpp b/src/remoteplayer.cpp index 0fb337065..bef60c792 100644 --- a/src/remoteplayer.cpp +++ b/src/remoteplayer.cpp @@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "filesys.h" #include "gamedef.h" -#include "porting.h" // strlcpy +#include "porting.h" // strlcpy #include "server.h" #include "settings.h" #include "convert_json.h" @@ -36,31 +36,28 @@ bool RemotePlayer::m_setting_cache_loaded = false; float RemotePlayer::m_setting_chat_message_limit_per_10sec = 0.0f; u16 RemotePlayer::m_setting_chat_message_limit_trigger_kick = 0; -RemotePlayer::RemotePlayer(const char *name, IItemDefManager *idef) : Player(name, idef) +RemotePlayer::RemotePlayer(const char *name, IItemDefManager *idef): + Player(name, idef) { if (!RemotePlayer::m_setting_cache_loaded) { RemotePlayer::m_setting_chat_message_limit_per_10sec = - g_settings->getFloat("chat_message_limit_per_10sec"); + g_settings->getFloat("chat_message_limit_per_10sec"); RemotePlayer::m_setting_chat_message_limit_trigger_kick = - g_settings->getU16("chat_message_limit_trigger_kick"); + g_settings->getU16("chat_message_limit_trigger_kick"); RemotePlayer::m_setting_cache_loaded = true; } - movement_acceleration_default = - g_settings->getFloat("movement_acceleration_default") * BS; - movement_acceleration_air = - g_settings->getFloat("movement_acceleration_air") * BS; - movement_acceleration_fast = - g_settings->getFloat("movement_acceleration_fast") * BS; - movement_speed_walk = g_settings->getFloat("movement_speed_walk") * BS; - movement_speed_crouch = g_settings->getFloat("movement_speed_crouch") * BS; - movement_speed_fast = g_settings->getFloat("movement_speed_fast") * BS; - movement_speed_climb = g_settings->getFloat("movement_speed_climb") * BS; - movement_speed_jump = g_settings->getFloat("movement_speed_jump") * BS; - movement_liquid_fluidity = g_settings->getFloat("movement_liquid_fluidity") * BS; - movement_liquid_fluidity_smooth = - g_settings->getFloat("movement_liquid_fluidity_smooth") * BS; - movement_liquid_sink = g_settings->getFloat("movement_liquid_sink") * BS; - movement_gravity = g_settings->getFloat("movement_gravity") * BS; + movement_acceleration_default = g_settings->getFloat("movement_acceleration_default") * BS; + movement_acceleration_air = g_settings->getFloat("movement_acceleration_air") * BS; + movement_acceleration_fast = g_settings->getFloat("movement_acceleration_fast") * BS; + movement_speed_walk = g_settings->getFloat("movement_speed_walk") * BS; + movement_speed_crouch = g_settings->getFloat("movement_speed_crouch") * BS; + movement_speed_fast = g_settings->getFloat("movement_speed_fast") * BS; + movement_speed_climb = g_settings->getFloat("movement_speed_climb") * BS; + movement_speed_jump = g_settings->getFloat("movement_speed_jump") * BS; + movement_liquid_fluidity = g_settings->getFloat("movement_liquid_fluidity") * BS; + movement_liquid_fluidity_smooth = g_settings->getFloat("movement_liquid_fluidity_smooth") * BS; + movement_liquid_sink = g_settings->getFloat("movement_liquid_sink") * BS; + movement_gravity = g_settings->getFloat("movement_gravity") * BS; // copy defaults m_cloud_params.density = 0.4f; @@ -99,50 +96,45 @@ void RemotePlayer::serializeExtraAttributes(std::string &output) output = fastWriteJson(json_root); } -void RemotePlayer::deSerialize( - std::istream &is, const std::string &playername, PlayerSAO *sao) + +void RemotePlayer::deSerialize(std::istream &is, const std::string &playername, + PlayerSAO *sao) { Settings args; if (!args.parseConfigLines(is, "PlayerArgsEnd")) { - throw SerializationError( - "PlayerArgsEnd of player " + playername + " not found!"); + throw SerializationError("PlayerArgsEnd of player " + playername + " not found!"); } m_dirty = true; - // args.getS32("version"); // Version field value not used + //args.getS32("version"); // Version field value not used const std::string &name = args.get("name"); strlcpy(m_name, name.c_str(), PLAYERNAME_SIZE); if (sao) { try { sao->setHPRaw(args.getU16("hp")); - } catch (SettingNotFoundException &e) { + } catch(SettingNotFoundException &e) { sao->setHPRaw(PLAYER_MAX_HP_DEFAULT); } try { sao->setBasePosition(args.getV3F("position")); - } catch (SettingNotFoundException &e) { - } + } catch (SettingNotFoundException &e) {} try { sao->setLookPitch(args.getFloat("pitch")); - } catch (SettingNotFoundException &e) { - } + } catch (SettingNotFoundException &e) {} try { sao->setPlayerYaw(args.getFloat("yaw")); - } catch (SettingNotFoundException &e) { - } + } catch (SettingNotFoundException &e) {} try { sao->setBreath(args.getU16("breath"), false); - } catch (SettingNotFoundException &e) { - } + } catch (SettingNotFoundException &e) {} try { - const std::string &extended_attributes = - args.get("extended_attributes"); + const std::string &extended_attributes = args.get("extended_attributes"); std::istringstream iss(extended_attributes); Json::CharReaderBuilder builder; builder.settings_["collectComments"] = false; @@ -157,15 +149,14 @@ void RemotePlayer::deSerialize( sao->getMeta().setString(it, attr_value.asString()); } sao->getMeta().setModified(false); - } catch (SettingNotFoundException &e) { - } + } catch (SettingNotFoundException &e) {} } try { inventory.deSerialize(is); } catch (SerializationError &e) { errorstream << "Failed to deserialize player inventory. player_name=" - << name << " " << e.what() << std::endl; + << name << " " << e.what() << std::endl; } if (!inventory.getList("craftpreview") && inventory.getList("craftresult")) { @@ -173,9 +164,10 @@ void RemotePlayer::deSerialize( inventory.addList("craftpreview", 1); bool craftresult_is_preview = true; - if (args.exists("craftresult_is_preview")) + if(args.exists("craftresult_is_preview")) craftresult_is_preview = args.getBool("craftresult_is_preview"); - if (craftresult_is_preview) { + if(craftresult_is_preview) + { // Clear craftresult inventory.getList("craftresult")->changeItem(0, ItemStack()); } @@ -203,7 +195,7 @@ void RemotePlayer::serialize(std::ostream &os) args.writeLines(os); - os << "PlayerArgsEnd\n"; + os<<"PlayerArgsEnd\n"; inventory.serialize(os); } @@ -220,21 +212,18 @@ const RemotePlayerChatResult RemotePlayer::canSendChatMessage() return RPLAYER_CHATRESULT_OK; } - m_chat_message_allowance += - time_passed * (m_setting_chat_message_limit_per_10sec / 8.0f); + m_chat_message_allowance += time_passed * (m_setting_chat_message_limit_per_10sec / 8.0f); if (m_chat_message_allowance > m_setting_chat_message_limit_per_10sec) { m_chat_message_allowance = m_setting_chat_message_limit_per_10sec; } if (m_chat_message_allowance < 1.0f) { infostream << "Player " << m_name - << " chat limited due to excessive message amount." - << std::endl; + << " chat limited due to excessive message amount." << std::endl; // Kick player if flooding is too intensive m_message_rate_overhead++; - if (m_message_rate_overhead > - RemotePlayer::m_setting_chat_message_limit_trigger_kick) { + if (m_message_rate_overhead > RemotePlayer::m_setting_chat_message_limit_trigger_kick) { return RPLAYER_CHATRESULT_KICK; } diff --git a/src/rollback.cpp b/src/rollback.cpp index 487460dd0..3cd9c7ce7 100644 --- a/src/rollback.cpp +++ b/src/rollback.cpp @@ -34,28 +34,26 @@ with this program; if not, write to the Free Software Foundation, Inc., #define POINTS_PER_NODE (16.0) -#define SQLRES(f, good) \ - if ((f) != (good)) { \ - throw FileNotGoodException(std::string("RollbackManager: " \ - "SQLite3 error (" __FILE__ \ - ":" TOSTRING(__LINE__) "): ") + \ - sqlite3_errmsg(db)); \ +#define SQLRES(f, good) \ + if ((f) != (good)) {\ + throw FileNotGoodException(std::string("RollbackManager: " \ + "SQLite3 error (" __FILE__ ":" TOSTRING(__LINE__) \ + "): ") + sqlite3_errmsg(db)); \ } #define SQLOK(f) SQLRES(f, SQLITE_OK) -#define SQLOK_ERRSTREAM(s, m) \ - if ((s) != SQLITE_OK) { \ - errorstream << "RollbackManager: " << (m) << ": " << sqlite3_errmsg(db) \ - << std::endl; \ +#define SQLOK_ERRSTREAM(s, m) \ + if ((s) != SQLITE_OK) { \ + errorstream << "RollbackManager: " << (m) << ": " \ + << sqlite3_errmsg(db) << std::endl; \ } -#define FINALIZE_STATEMENT(statement) \ +#define FINALIZE_STATEMENT(statement) \ SQLOK_ERRSTREAM(sqlite3_finalize(statement), "Failed to finalize " #statement) -class ItemStackRow : public ItemStack -{ +class ItemStackRow : public ItemStack { public: - ItemStackRow &operator=(const ItemStack &other) + ItemStackRow & operator = (const ItemStack & other) { *static_cast(this) = other; return *this; @@ -64,37 +62,39 @@ class ItemStackRow : public ItemStack int id; }; -struct ActionRow -{ - int id; - int actor; - time_t timestamp; - int type; - std::string location, list; - int index, add; +struct ActionRow { + int id; + int actor; + time_t timestamp; + int type; + std::string location, list; + int index, add; ItemStackRow stack; - int nodeMeta; - int x, y, z; - int oldNode; - int oldParam1, oldParam2; - std::string oldMeta; - int newNode; - int newParam1, newParam2; - std::string newMeta; - int guessed; + int nodeMeta; + int x, y, z; + int oldNode; + int oldParam1, oldParam2; + std::string oldMeta; + int newNode; + int newParam1, newParam2; + std::string newMeta; + int guessed; }; -struct Entity -{ - int id; + +struct Entity { + int id; std::string name; }; -RollbackManager::RollbackManager(const std::string &world_path, IGameDef *gamedef_) : - gamedef(gamedef_) + + +RollbackManager::RollbackManager(const std::string & world_path, + IGameDef * gamedef_) : + gamedef(gamedef_) { - verbosestream << "RollbackManager::RollbackManager(" << world_path << ")" - << std::endl; + verbosestream << "RollbackManager::RollbackManager(" << world_path + << ")" << std::endl; std::string txt_filename = world_path + DIR_DELIM "rollback.txt"; std::string migrating_flag = txt_filename + ".migrating"; @@ -102,7 +102,8 @@ RollbackManager::RollbackManager(const std::string &world_path, IGameDef *gamede bool created = initDatabase(); - if (fs::PathExists(txt_filename) && (created || fs::PathExists(migrating_flag))) { + if (fs::PathExists(txt_filename) && (created || + fs::PathExists(migrating_flag))) { std::ofstream of(migrating_flag.c_str()); of.close(); migrate(txt_filename); @@ -110,6 +111,7 @@ RollbackManager::RollbackManager(const std::string &world_path, IGameDef *gamede } } + RollbackManager::~RollbackManager() { flush(); @@ -127,18 +129,21 @@ RollbackManager::~RollbackManager() SQLOK_ERRSTREAM(sqlite3_close(db), "Could not close db"); } + void RollbackManager::registerNewActor(const int id, const std::string &name) { Entity actor = {id, name}; knownActors.push_back(actor); } + void RollbackManager::registerNewNode(const int id, const std::string &name) { Entity node = {id, name}; knownNodes.push_back(node); } + int RollbackManager::getActorId(const std::string &name) { for (std::vector::const_iterator iter = knownActors.begin(); @@ -148,8 +153,7 @@ int RollbackManager::getActorId(const std::string &name) } } - SQLOK(sqlite3_bind_text( - stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL)); + SQLOK(sqlite3_bind_text(stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL)); SQLRES(sqlite3_step(stmt_knownActor_insert), SQLITE_DONE); SQLOK(sqlite3_reset(stmt_knownActor_insert)); @@ -159,6 +163,7 @@ int RollbackManager::getActorId(const std::string &name) return id; } + int RollbackManager::getNodeId(const std::string &name) { for (std::vector::const_iterator iter = knownNodes.begin(); @@ -168,8 +173,7 @@ int RollbackManager::getNodeId(const std::string &name) } } - SQLOK(sqlite3_bind_text( - stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL)); + SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL)); SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE); SQLOK(sqlite3_reset(stmt_knownNode_insert)); @@ -179,7 +183,8 @@ int RollbackManager::getNodeId(const std::string &name) return id; } -const char *RollbackManager::getActorName(const int id) + +const char * RollbackManager::getActorName(const int id) { for (std::vector::const_iterator iter = knownActors.begin(); iter != knownActors.end(); ++iter) { @@ -191,7 +196,8 @@ const char *RollbackManager::getActorName(const int id) return ""; } -const char *RollbackManager::getNodeName(const int id) + +const char * RollbackManager::getNodeName(const int id) { for (std::vector::const_iterator iter = knownNodes.begin(); iter != knownNodes.end(); ++iter) { @@ -203,54 +209,54 @@ const char *RollbackManager::getNodeName(const int id) return ""; } + bool RollbackManager::createTables() { SQLOK(sqlite3_exec(db, - "CREATE TABLE IF NOT EXISTS `actor` (\n" - " `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" - " `name` TEXT NOT NULL\n" - ");\n" - "CREATE TABLE IF NOT EXISTS `node` (\n" - " `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" - " `name` TEXT NOT NULL\n" - ");\n" - "CREATE TABLE IF NOT EXISTS `action` (\n" - " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" - " `actor` INTEGER NOT NULL,\n" - " `timestamp` TIMESTAMP NOT NULL,\n" - " `type` INTEGER NOT NULL,\n" - " `list` TEXT,\n" - " `index` INTEGER,\n" - " `add` INTEGER,\n" - " `stackNode` INTEGER,\n" - " `stackQuantity` INTEGER,\n" - " `nodeMeta` INTEGER,\n" - " `x` INT,\n" - " `y` INT,\n" - " `z` INT,\n" - " `oldNode` INTEGER,\n" - " `oldParam1` INTEGER,\n" - " `oldParam2` INTEGER,\n" - " `oldMeta` TEXT,\n" - " `newNode` INTEGER,\n" - " `newParam1` INTEGER,\n" - " `newParam2` INTEGER,\n" - " `newMeta` TEXT,\n" - " `guessedActor` INTEGER,\n" - " FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n" - " FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n" - " FOREIGN KEY (`oldNode`) REFERENCES `node`(`id`),\n" - " FOREIGN KEY (`newNode`) REFERENCES `node`(`id`)\n" - ");\n" - "CREATE INDEX IF NOT EXISTS `actionIndex` ON " - "`action`(`x`,`y`,`z`,`timestamp`,`actor`);\n", - NULL, NULL, NULL)); - verbosestream << "SQL Rollback: SQLite3 database structure was created" - << std::endl; + "CREATE TABLE IF NOT EXISTS `actor` (\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" + " `name` TEXT NOT NULL\n" + ");\n" + "CREATE TABLE IF NOT EXISTS `node` (\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" + " `name` TEXT NOT NULL\n" + ");\n" + "CREATE TABLE IF NOT EXISTS `action` (\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " `actor` INTEGER NOT NULL,\n" + " `timestamp` TIMESTAMP NOT NULL,\n" + " `type` INTEGER NOT NULL,\n" + " `list` TEXT,\n" + " `index` INTEGER,\n" + " `add` INTEGER,\n" + " `stackNode` INTEGER,\n" + " `stackQuantity` INTEGER,\n" + " `nodeMeta` INTEGER,\n" + " `x` INT,\n" + " `y` INT,\n" + " `z` INT,\n" + " `oldNode` INTEGER,\n" + " `oldParam1` INTEGER,\n" + " `oldParam2` INTEGER,\n" + " `oldMeta` TEXT,\n" + " `newNode` INTEGER,\n" + " `newParam1` INTEGER,\n" + " `newParam2` INTEGER,\n" + " `newMeta` TEXT,\n" + " `guessedActor` INTEGER,\n" + " FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n" + " FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n" + " FOREIGN KEY (`oldNode`) REFERENCES `node`(`id`),\n" + " FOREIGN KEY (`newNode`) REFERENCES `node`(`id`)\n" + ");\n" + "CREATE INDEX IF NOT EXISTS `actionIndex` ON `action`(`x`,`y`,`z`,`timestamp`,`actor`);\n", + NULL, NULL, NULL)); + verbosestream << "SQL Rollback: SQLite3 database structure was created" << std::endl; return true; } + bool RollbackManager::initDatabase() { verbosestream << "RollbackManager: Database connection setup" << std::endl; @@ -264,145 +270,142 @@ bool RollbackManager::initDatabase() } SQLOK(sqlite3_prepare_v2(db, - "INSERT INTO `action` (\n" - " `actor`, `timestamp`, `type`,\n" - " `list`, `index`, `add`, `stackNode`, `stackQuantity`, " - "`nodeMeta`,\n" - " `x`, `y`, `z`,\n" - " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" - " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" - " `guessedActor`\n" - ") VALUES (\n" - " ?, ?, ?,\n" - " ?, ?, ?, ?, ?, ?,\n" - " ?, ?, ?,\n" - " ?, ?, ?, ?,\n" - " ?, ?, ?, ?,\n" - " ?" - ");", - -1, &stmt_insert, NULL)); + "INSERT INTO `action` (\n" + " `actor`, `timestamp`, `type`,\n" + " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n" + " `x`, `y`, `z`,\n" + " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" + " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" + " `guessedActor`\n" + ") VALUES (\n" + " ?, ?, ?,\n" + " ?, ?, ?, ?, ?, ?,\n" + " ?, ?, ?,\n" + " ?, ?, ?, ?,\n" + " ?, ?, ?, ?,\n" + " ?" + ");", + -1, &stmt_insert, NULL)); SQLOK(sqlite3_prepare_v2(db, - "REPLACE INTO `action` (\n" - " `actor`, `timestamp`, `type`,\n" - " `list`, `index`, `add`, `stackNode`, `stackQuantity`, " - "`nodeMeta`,\n" - " `x`, `y`, `z`,\n" - " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" - " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" - " `guessedActor`, `id`\n" - ") VALUES (\n" - " ?, ?, ?,\n" - " ?, ?, ?, ?, ?, ?,\n" - " ?, ?, ?,\n" - " ?, ?, ?, ?,\n" - " ?, ?, ?, ?,\n" - " ?, ?\n" - ");", - -1, &stmt_replace, NULL)); + "REPLACE INTO `action` (\n" + " `actor`, `timestamp`, `type`,\n" + " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n" + " `x`, `y`, `z`,\n" + " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" + " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" + " `guessedActor`, `id`\n" + ") VALUES (\n" + " ?, ?, ?,\n" + " ?, ?, ?, ?, ?, ?,\n" + " ?, ?, ?,\n" + " ?, ?, ?, ?,\n" + " ?, ?, ?, ?,\n" + " ?, ?\n" + ");", + -1, &stmt_replace, NULL)); SQLOK(sqlite3_prepare_v2(db, - "SELECT\n" - " `actor`, `timestamp`, `type`,\n" - " `list`, `index`, `add`, `stackNode`, `stackQuantity`, " - "`nodemeta`,\n" - " `x`, `y`, `z`,\n" - " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" - " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" - " `guessedActor`\n" - " FROM `action`\n" - " WHERE `timestamp` >= ?\n" - " ORDER BY `timestamp` DESC, `id` DESC", - -1, &stmt_select, NULL)); + "SELECT\n" + " `actor`, `timestamp`, `type`,\n" + " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n" + " `x`, `y`, `z`,\n" + " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" + " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" + " `guessedActor`\n" + " FROM `action`\n" + " WHERE `timestamp` >= ?\n" + " ORDER BY `timestamp` DESC, `id` DESC", + -1, &stmt_select, NULL)); SQLOK(sqlite3_prepare_v2(db, - "SELECT\n" - " `actor`, `timestamp`, `type`,\n" - " `list`, `index`, `add`, `stackNode`, `stackQuantity`, " - "`nodemeta`,\n" - " `x`, `y`, `z`,\n" - " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" - " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" - " `guessedActor`\n" - "FROM `action`\n" - "WHERE `timestamp` >= ?\n" - " AND `x` IS NOT NULL\n" - " AND `y` IS NOT NULL\n" - " AND `z` IS NOT NULL\n" - " AND `x` BETWEEN ? AND ?\n" - " AND `y` BETWEEN ? AND ?\n" - " AND `z` BETWEEN ? AND ?\n" - "ORDER BY `timestamp` DESC, `id` DESC\n" - "LIMIT 0,?", - -1, &stmt_select_range, NULL)); + "SELECT\n" + " `actor`, `timestamp`, `type`,\n" + " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n" + " `x`, `y`, `z`,\n" + " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" + " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" + " `guessedActor`\n" + "FROM `action`\n" + "WHERE `timestamp` >= ?\n" + " AND `x` IS NOT NULL\n" + " AND `y` IS NOT NULL\n" + " AND `z` IS NOT NULL\n" + " AND `x` BETWEEN ? AND ?\n" + " AND `y` BETWEEN ? AND ?\n" + " AND `z` BETWEEN ? AND ?\n" + "ORDER BY `timestamp` DESC, `id` DESC\n" + "LIMIT 0,?", + -1, &stmt_select_range, NULL)); SQLOK(sqlite3_prepare_v2(db, - "SELECT\n" - " `actor`, `timestamp`, `type`,\n" - " `list`, `index`, `add`, `stackNode`, `stackQuantity`, " - "`nodemeta`,\n" - " `x`, `y`, `z`,\n" - " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" - " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" - " `guessedActor`\n" - "FROM `action`\n" - "WHERE `timestamp` >= ?\n" - " AND `actor` = ?\n" - "ORDER BY `timestamp` DESC, `id` DESC\n", - -1, &stmt_select_withActor, NULL)); - - SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`", -1, - &stmt_knownActor_select, NULL)); - - SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)", -1, - &stmt_knownActor_insert, NULL)); - - SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`", -1, - &stmt_knownNode_select, NULL)); - - SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)", -1, - &stmt_knownNode_insert, NULL)); + "SELECT\n" + " `actor`, `timestamp`, `type`,\n" + " `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n" + " `x`, `y`, `z`,\n" + " `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n" + " `newNode`, `newParam1`, `newParam2`, `newMeta`,\n" + " `guessedActor`\n" + "FROM `action`\n" + "WHERE `timestamp` >= ?\n" + " AND `actor` = ?\n" + "ORDER BY `timestamp` DESC, `id` DESC\n", + -1, &stmt_select_withActor, NULL)); + + SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`", + -1, &stmt_knownActor_select, NULL)); + + SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)", + -1, &stmt_knownActor_insert, NULL)); + + SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`", + -1, &stmt_knownNode_select, NULL)); + + SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)", + -1, &stmt_knownNode_insert, NULL)); verbosestream << "SQL prepared statements setup correctly" << std::endl; while (sqlite3_step(stmt_knownActor_select) == SQLITE_ROW) { - registerNewActor(sqlite3_column_int(stmt_knownActor_select, 0), - reinterpret_cast(sqlite3_column_text( - stmt_knownActor_select, 1))); + registerNewActor( + sqlite3_column_int(stmt_knownActor_select, 0), + reinterpret_cast(sqlite3_column_text(stmt_knownActor_select, 1)) + ); } SQLOK(sqlite3_reset(stmt_knownActor_select)); while (sqlite3_step(stmt_knownNode_select) == SQLITE_ROW) { - registerNewNode(sqlite3_column_int(stmt_knownNode_select, 0), - reinterpret_cast(sqlite3_column_text( - stmt_knownNode_select, 1))); + registerNewNode( + sqlite3_column_int(stmt_knownNode_select, 0), + reinterpret_cast(sqlite3_column_text(stmt_knownNode_select, 1)) + ); } SQLOK(sqlite3_reset(stmt_knownNode_select)); return needs_create; } -bool RollbackManager::registerRow(const ActionRow &row) + +bool RollbackManager::registerRow(const ActionRow & row) { - sqlite3_stmt *stmt_do = (row.id) ? stmt_replace : stmt_insert; + sqlite3_stmt * stmt_do = (row.id) ? stmt_replace : stmt_insert; bool nodeMeta = false; - SQLOK(sqlite3_bind_int(stmt_do, 1, row.actor)); + SQLOK(sqlite3_bind_int (stmt_do, 1, row.actor)); SQLOK(sqlite3_bind_int64(stmt_do, 2, row.timestamp)); - SQLOK(sqlite3_bind_int(stmt_do, 3, row.type)); + SQLOK(sqlite3_bind_int (stmt_do, 3, row.type)); if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) { - const std::string &loc = row.location; + const std::string & loc = row.location; nodeMeta = (loc.substr(0, 9) == "nodemeta:"); - SQLOK(sqlite3_bind_text( - stmt_do, 4, row.list.c_str(), row.list.size(), NULL)); - SQLOK(sqlite3_bind_int(stmt_do, 5, row.index)); - SQLOK(sqlite3_bind_int(stmt_do, 6, row.add)); - SQLOK(sqlite3_bind_int(stmt_do, 7, row.stack.id)); - SQLOK(sqlite3_bind_int(stmt_do, 8, row.stack.count)); - SQLOK(sqlite3_bind_int(stmt_do, 9, (int)nodeMeta)); + SQLOK(sqlite3_bind_text(stmt_do, 4, row.list.c_str(), row.list.size(), NULL)); + SQLOK(sqlite3_bind_int (stmt_do, 5, row.index)); + SQLOK(sqlite3_bind_int (stmt_do, 6, row.add)); + SQLOK(sqlite3_bind_int (stmt_do, 7, row.stack.id)); + SQLOK(sqlite3_bind_int (stmt_do, 8, row.stack.count)); + SQLOK(sqlite3_bind_int (stmt_do, 9, (int) nodeMeta)); if (nodeMeta) { std::string::size_type p1, p2; @@ -427,20 +430,18 @@ bool RollbackManager::registerRow(const ActionRow &row) } if (row.type == RollbackAction::TYPE_SET_NODE) { - SQLOK(sqlite3_bind_int(stmt_do, 10, row.x)); - SQLOK(sqlite3_bind_int(stmt_do, 11, row.y)); - SQLOK(sqlite3_bind_int(stmt_do, 12, row.z)); - SQLOK(sqlite3_bind_int(stmt_do, 13, row.oldNode)); - SQLOK(sqlite3_bind_int(stmt_do, 14, row.oldParam1)); - SQLOK(sqlite3_bind_int(stmt_do, 15, row.oldParam2)); - SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), - row.oldMeta.size(), NULL)); - SQLOK(sqlite3_bind_int(stmt_do, 17, row.newNode)); - SQLOK(sqlite3_bind_int(stmt_do, 18, row.newParam1)); - SQLOK(sqlite3_bind_int(stmt_do, 19, row.newParam2)); - SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), - row.newMeta.size(), NULL)); - SQLOK(sqlite3_bind_int(stmt_do, 21, row.guessed ? 1 : 0)); + SQLOK(sqlite3_bind_int (stmt_do, 10, row.x)); + SQLOK(sqlite3_bind_int (stmt_do, 11, row.y)); + SQLOK(sqlite3_bind_int (stmt_do, 12, row.z)); + SQLOK(sqlite3_bind_int (stmt_do, 13, row.oldNode)); + SQLOK(sqlite3_bind_int (stmt_do, 14, row.oldParam1)); + SQLOK(sqlite3_bind_int (stmt_do, 15, row.oldParam2)); + SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL)); + SQLOK(sqlite3_bind_int (stmt_do, 17, row.newNode)); + SQLOK(sqlite3_bind_int (stmt_do, 18, row.newParam1)); + SQLOK(sqlite3_bind_int (stmt_do, 19, row.newParam2)); + SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL)); + SQLOK(sqlite3_bind_int (stmt_do, 21, row.guessed ? 1 : 0)); } else { if (!nodeMeta) { SQLOK(sqlite3_bind_null(stmt_do, 10)); @@ -469,53 +470,51 @@ bool RollbackManager::registerRow(const ActionRow &row) return written == SQLITE_DONE; } -const std::list RollbackManager::actionRowsFromSelect(sqlite3_stmt *stmt) + +const std::list RollbackManager::actionRowsFromSelect(sqlite3_stmt* stmt) { std::list rows; - const unsigned char *text; + const unsigned char * text; size_t size; while (sqlite3_step(stmt) == SQLITE_ROW) { ActionRow row; - row.actor = sqlite3_column_int(stmt, 0); + row.actor = sqlite3_column_int (stmt, 0); row.timestamp = sqlite3_column_int64(stmt, 1); - row.type = sqlite3_column_int(stmt, 2); + row.type = sqlite3_column_int (stmt, 2); if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) { - text = sqlite3_column_text(stmt, 3); + text = sqlite3_column_text (stmt, 3); size = sqlite3_column_bytes(stmt, 3); - row.list = std::string( - reinterpret_cast(text), size); - row.index = sqlite3_column_int(stmt, 4); - row.add = sqlite3_column_int(stmt, 5); - row.stack.id = sqlite3_column_int(stmt, 6); + row.list = std::string(reinterpret_cast(text), size); + row.index = sqlite3_column_int(stmt, 4); + row.add = sqlite3_column_int(stmt, 5); + row.stack.id = sqlite3_column_int(stmt, 6); row.stack.count = sqlite3_column_int(stmt, 7); - row.nodeMeta = sqlite3_column_int(stmt, 8); + row.nodeMeta = sqlite3_column_int(stmt, 8); } if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta) { - row.x = sqlite3_column_int(stmt, 9); + row.x = sqlite3_column_int(stmt, 9); row.y = sqlite3_column_int(stmt, 10); row.z = sqlite3_column_int(stmt, 11); } if (row.type == RollbackAction::TYPE_SET_NODE) { - row.oldNode = sqlite3_column_int(stmt, 12); + row.oldNode = sqlite3_column_int(stmt, 12); row.oldParam1 = sqlite3_column_int(stmt, 13); row.oldParam2 = sqlite3_column_int(stmt, 14); - text = sqlite3_column_text(stmt, 15); + text = sqlite3_column_text (stmt, 15); size = sqlite3_column_bytes(stmt, 15); - row.oldMeta = std::string( - reinterpret_cast(text), size); - row.newNode = sqlite3_column_int(stmt, 16); + row.oldMeta = std::string(reinterpret_cast(text), size); + row.newNode = sqlite3_column_int(stmt, 16); row.newParam1 = sqlite3_column_int(stmt, 17); row.newParam2 = sqlite3_column_int(stmt, 18); text = sqlite3_column_text(stmt, 19); size = sqlite3_column_bytes(stmt, 19); - row.newMeta = std::string( - reinterpret_cast(text), size); - row.guessed = sqlite3_column_int(stmt, 20); + row.newMeta = std::string(reinterpret_cast(text), size); + row.guessed = sqlite3_column_int(stmt, 20); } if (row.nodeMeta) { @@ -537,77 +536,79 @@ const std::list RollbackManager::actionRowsFromSelect(sqlite3_stmt *s return rows; } -ActionRow RollbackManager::actionRowFromRollbackAction(const RollbackAction &action) + +ActionRow RollbackManager::actionRowFromRollbackAction(const RollbackAction & action) { ActionRow row; - row.id = 0; - row.actor = getActorId(action.actor); + row.id = 0; + row.actor = getActorId(action.actor); row.timestamp = action.unix_time; - row.type = action.type; + row.type = action.type; if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) { row.location = action.inventory_location; - row.list = action.inventory_list; - row.index = action.inventory_index; - row.add = action.inventory_add; - row.stack = action.inventory_stack; + row.list = action.inventory_list; + row.index = action.inventory_index; + row.add = action.inventory_add; + row.stack = action.inventory_stack; row.stack.id = getNodeId(row.stack.name); } else { - row.x = action.p.X; - row.y = action.p.Y; - row.z = action.p.Z; - row.oldNode = getNodeId(action.n_old.name); + row.x = action.p.X; + row.y = action.p.Y; + row.z = action.p.Z; + row.oldNode = getNodeId(action.n_old.name); row.oldParam1 = action.n_old.param1; row.oldParam2 = action.n_old.param2; - row.oldMeta = action.n_old.meta; - row.newNode = getNodeId(action.n_new.name); + row.oldMeta = action.n_old.meta; + row.newNode = getNodeId(action.n_new.name); row.newParam1 = action.n_new.param1; row.newParam2 = action.n_new.param2; - row.newMeta = action.n_new.meta; - row.guessed = action.actor_is_guess; + row.newMeta = action.n_new.meta; + row.guessed = action.actor_is_guess; } return row; } + const std::list RollbackManager::rollbackActionsFromActionRows( - const std::list &rows) + const std::list & rows) { std::list actions; for (const ActionRow &row : rows) { RollbackAction action; - action.actor = (row.actor) ? getActorName(row.actor) : ""; + action.actor = (row.actor) ? getActorName(row.actor) : ""; action.unix_time = row.timestamp; - action.type = static_cast(row.type); + action.type = static_cast(row.type); switch (action.type) { case RollbackAction::TYPE_MODIFY_INVENTORY_STACK: action.inventory_location = row.location; - action.inventory_list = row.list; - action.inventory_index = row.index; - action.inventory_add = row.add; - action.inventory_stack = row.stack; + action.inventory_list = row.list; + action.inventory_index = row.index; + action.inventory_add = row.add; + action.inventory_stack = row.stack; if (action.inventory_stack.name.empty()) { action.inventory_stack.name = getNodeName(row.stack.id); } break; case RollbackAction::TYPE_SET_NODE: - action.p = v3s16(row.x, row.y, row.z); - action.n_old.name = getNodeName(row.oldNode); + action.p = v3s16(row.x, row.y, row.z); + action.n_old.name = getNodeName(row.oldNode); action.n_old.param1 = row.oldParam1; action.n_old.param2 = row.oldParam2; - action.n_old.meta = row.oldMeta; - action.n_new.name = getNodeName(row.newNode); + action.n_old.meta = row.oldMeta; + action.n_new.name = getNodeName(row.newNode); action.n_new.param1 = row.newParam1; action.n_new.param2 = row.newParam2; - action.n_new.meta = row.newMeta; + action.n_new.meta = row.newMeta; break; default: - throw("W.T.F."); + throw ("W.T.F."); break; } @@ -617,8 +618,8 @@ const std::list RollbackManager::rollbackActionsFromActionRows( return actions; } -const std::list RollbackManager::getRowsSince( - time_t firstTime, const std::string &actor) + +const std::list RollbackManager::getRowsSince(time_t firstTime, const std::string & actor) { sqlite3_stmt *stmt_stmt = actor.empty() ? stmt_select : stmt_select_withActor; sqlite3_bind_int64(stmt_stmt, 1, firstTime); @@ -627,45 +628,48 @@ const std::list RollbackManager::getRowsSince( sqlite3_bind_int(stmt_stmt, 2, getActorId(actor)); } - const std::list &rows = actionRowsFromSelect(stmt_stmt); + const std::list & rows = actionRowsFromSelect(stmt_stmt); sqlite3_reset(stmt_stmt); return rows; } + const std::list RollbackManager::getRowsSince_range( time_t start_time, v3s16 p, int range, int limit) { sqlite3_bind_int64(stmt_select_range, 1, start_time); - sqlite3_bind_int(stmt_select_range, 2, static_cast(p.X - range)); - sqlite3_bind_int(stmt_select_range, 3, static_cast(p.X + range)); - sqlite3_bind_int(stmt_select_range, 4, static_cast(p.Y - range)); - sqlite3_bind_int(stmt_select_range, 5, static_cast(p.Y + range)); - sqlite3_bind_int(stmt_select_range, 6, static_cast(p.Z - range)); - sqlite3_bind_int(stmt_select_range, 7, static_cast(p.Z + range)); - sqlite3_bind_int(stmt_select_range, 8, limit); - - const std::list &rows = actionRowsFromSelect(stmt_select_range); + sqlite3_bind_int (stmt_select_range, 2, static_cast(p.X - range)); + sqlite3_bind_int (stmt_select_range, 3, static_cast(p.X + range)); + sqlite3_bind_int (stmt_select_range, 4, static_cast(p.Y - range)); + sqlite3_bind_int (stmt_select_range, 5, static_cast(p.Y + range)); + sqlite3_bind_int (stmt_select_range, 6, static_cast(p.Z - range)); + sqlite3_bind_int (stmt_select_range, 7, static_cast(p.Z + range)); + sqlite3_bind_int (stmt_select_range, 8, limit); + + const std::list & rows = actionRowsFromSelect(stmt_select_range); sqlite3_reset(stmt_select_range); return rows; } + const std::list RollbackManager::getActionsSince_range( time_t start_time, v3s16 p, int range, int limit) { - return rollbackActionsFromActionRows( - getRowsSince_range(start_time, p, range, limit)); + return rollbackActionsFromActionRows(getRowsSince_range(start_time, p, range, limit)); } + const std::list RollbackManager::getActionsSince( - time_t start_time, const std::string &actor) + time_t start_time, const std::string & actor) { return rollbackActionsFromActionRows(getRowsSince(start_time, actor)); } -void RollbackManager::migrate(const std::string &file_path) + +void RollbackManager::migrate(const std::string & file_path) { std::cout << "Migrating from rollback.txt to rollback.sqlite." << std::endl; @@ -718,12 +722,12 @@ void RollbackManager::migrate(const std::string &file_path) row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK; row.location = trim(deSerializeJsonString(fh)); std::getline(fh, bit, ' '); - row.list = trim(deSerializeJsonString(fh)); + row.list = trim(deSerializeJsonString(fh)); std::getline(fh, bit, ' '); std::getline(fh, bit, ' '); - row.index = atoi(trim(bit).c_str()); + row.index = atoi(trim(bit).c_str()); std::getline(fh, bit, ' '); - row.add = (int)(trim(bit) == "add"); + row.add = (int)(trim(bit) == "add"); row.stack.deSerialize(deSerializeJsonString(fh)); row.stack.id = getNodeId(row.stack.name); std::getline(fh, bit); @@ -731,11 +735,11 @@ void RollbackManager::migrate(const std::string &file_path) row.type = RollbackAction::TYPE_SET_NODE; std::getline(fh, bit, '('); std::getline(fh, bit, ','); - row.x = atoi(trim(bit).c_str()); + row.x = atoi(trim(bit).c_str()); std::getline(fh, bit, ','); - row.y = atoi(trim(bit).c_str()); + row.y = atoi(trim(bit).c_str()); std::getline(fh, bit, ')'); - row.z = atoi(trim(bit).c_str()); + row.z = atoi(trim(bit).c_str()); std::getline(fh, bit, ' '); row.oldNode = getNodeId(trim(deSerializeJsonString(fh))); std::getline(fh, bit, ' '); @@ -743,22 +747,22 @@ void RollbackManager::migrate(const std::string &file_path) row.oldParam1 = atoi(trim(bit).c_str()); std::getline(fh, bit, ' '); row.oldParam2 = atoi(trim(bit).c_str()); - row.oldMeta = trim(deSerializeJsonString(fh)); + row.oldMeta = trim(deSerializeJsonString(fh)); std::getline(fh, bit, ' '); - row.newNode = getNodeId(trim(deSerializeJsonString(fh))); + row.newNode = getNodeId(trim(deSerializeJsonString(fh))); std::getline(fh, bit, ' '); std::getline(fh, bit, ' '); row.newParam1 = atoi(trim(bit).c_str()); std::getline(fh, bit, ' '); row.newParam2 = atoi(trim(bit).c_str()); - row.newMeta = trim(deSerializeJsonString(fh)); + row.newMeta = trim(deSerializeJsonString(fh)); std::getline(fh, bit, ' '); std::getline(fh, bit, ' '); std::getline(fh, bit); row.guessed = (int)(trim(bit) == "actor_is_guess"); } else { - errorstream << "Unrecognized rollback action type \"" << bit - << "\"!" << std::endl; + errorstream << "Unrecognized rollback action type \"" + << bit << "\"!" << std::endl; continue; } @@ -769,15 +773,9 @@ void RollbackManager::migrate(const std::string &file_path) SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE); sqlite3_reset(stmt_commit); t = time(0); - std::cout << " Done: " - << static_cast( - (static_cast(fh.tellg()) / - static_cast( - file_size)) * - 100) - << "%" - << " Speed: " << i / (t - start) << "/second \r" - << std::flush; + std::cout + << " Done: " << static_cast((static_cast(fh.tellg()) / static_cast(file_size)) * 100) << "%" + << " Speed: " << i / (t - start) << "/second \r" << std::flush; SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE); sqlite3_reset(stmt_begin); } @@ -788,10 +786,12 @@ void RollbackManager::migrate(const std::string &file_path) SQLOK(sqlite3_finalize(stmt_begin)); SQLOK(sqlite3_finalize(stmt_commit)); - std::cout << " Done: 100% " << std::endl - << "Now you can delete the old rollback.txt file." << std::endl; + std::cout + << " Done: 100% " << std::endl + << "Now you can delete the old rollback.txt file." << std::endl; } + // Get nearness factor for subject's action for this action // Return value: 0 = impossible, >0 = factor float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p, @@ -799,13 +799,12 @@ float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p, { // Suspect cannot cause things in the past if (action_t < suspect_t) { - return 0; // 0 = cannot be + return 0; // 0 = cannot be } // Start from 100 int f = 100; // Distance (1 node = -x points) - f -= POINTS_PER_NODE * - intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1)); + f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1)); // Time (1 second = -x points) f -= 1 * (action_t - suspect_t); // If is a guess, halve the points @@ -819,6 +818,7 @@ float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p, return f; } + void RollbackManager::reportAction(const RollbackAction &action_) { // Ignore if not important @@ -860,14 +860,14 @@ bool RollbackManager::isActorGuess() return current_actor_is_guess; } -void RollbackManager::setActor(const std::string &actor, bool is_guess) +void RollbackManager::setActor(const std::string & actor, bool is_guess) { current_actor = actor; current_actor_is_guess = is_guess; } -std::string RollbackManager::getSuspect( - v3s16 p, float nearness_shortcut, float min_nearness) +std::string RollbackManager::getSuspect(v3s16 p, float nearness_shortcut, + float min_nearness) { if (!current_actor.empty()) { return current_actor; @@ -876,9 +876,9 @@ std::string RollbackManager::getSuspect( time_t first_time = cur_time - (100 - min_nearness); RollbackAction likely_suspect; float likely_suspect_nearness = 0; - for (std::list::const_reverse_iterator i = - action_latest_buffer.rbegin(); - i != action_latest_buffer.rend(); ++i) { + for (std::list::const_reverse_iterator + i = action_latest_buffer.rbegin(); + i != action_latest_buffer.rend(); ++i) { if (i->unix_time < first_time) { break; } @@ -890,8 +890,8 @@ std::string RollbackManager::getSuspect( if (!i->getPosition(&suspect_p)) { continue; } - float f = getSuspectNearness( - i->actor_is_guess, suspect_p, i->unix_time, p, cur_time); + float f = getSuspectNearness(i->actor_is_guess, suspect_p, + i->unix_time, p, cur_time); if (f >= min_nearness && f > likely_suspect_nearness) { likely_suspect_nearness = f; likely_suspect = *i; @@ -908,13 +908,15 @@ std::string RollbackManager::getSuspect( return likely_suspect.actor; } + void RollbackManager::flush() { sqlite3_exec(db, "BEGIN", NULL, NULL, NULL); std::list::const_iterator iter; - for (iter = action_todisk_buffer.begin(); iter != action_todisk_buffer.end(); + for (iter = action_todisk_buffer.begin(); + iter != action_todisk_buffer.end(); ++iter) { if (iter->actor.empty()) { continue; @@ -927,7 +929,8 @@ void RollbackManager::flush() action_todisk_buffer.clear(); } -void RollbackManager::addAction(const RollbackAction &action) + +void RollbackManager::addAction(const RollbackAction & action) { action_todisk_buffer.push_back(action); action_latest_buffer.push_back(action); @@ -944,8 +947,8 @@ std::list RollbackManager::getEntriesSince(time_t first_time) return getActionsSince(first_time); } -std::list RollbackManager::getNodeActors( - v3s16 pos, int range, time_t seconds, int limit) +std::list RollbackManager::getNodeActors(v3s16 pos, int range, + time_t seconds, int limit) { flush(); time_t cur_time = time(0); @@ -955,7 +958,8 @@ std::list RollbackManager::getNodeActors( } std::list RollbackManager::getRevertActions( - const std::string &actor_filter, time_t seconds) + const std::string &actor_filter, + time_t seconds) { time_t cur_time = time(0); time_t first_time = cur_time - seconds; @@ -964,3 +968,4 @@ std::list RollbackManager::getRevertActions( return getActionsSince(first_time, actor_filter); } + diff --git a/src/rollback.h b/src/rollback.h index b505750d2..1d9949d15 100644 --- a/src/rollback.h +++ b/src/rollback.h @@ -31,51 +31,53 @@ class IGameDef; struct ActionRow; struct Entity; -class RollbackManager : public IRollbackManager +class RollbackManager: public IRollbackManager { public: - RollbackManager(const std::string &world_path, IGameDef *gamedef); + RollbackManager(const std::string & world_path, IGameDef * gamedef); ~RollbackManager(); - void reportAction(const RollbackAction &action_); + void reportAction(const RollbackAction & action_); std::string getActor(); bool isActorGuess(); - void setActor(const std::string &actor, bool is_guess); - std::string getSuspect(v3s16 p, float nearness_shortcut, float min_nearness); + void setActor(const std::string & actor, bool is_guess); + std::string getSuspect(v3s16 p, float nearness_shortcut, + float min_nearness); void flush(); - void addAction(const RollbackAction &action); + void addAction(const RollbackAction & action); std::list getEntriesSince(time_t first_time); - std::list getNodeActors( - v3s16 pos, int range, time_t seconds, int limit); + std::list getNodeActors(v3s16 pos, int range, + time_t seconds, int limit); std::list getRevertActions( - const std::string &actor_filter, time_t seconds); + const std::string & actor_filter, time_t seconds); private: - void registerNewActor(const int id, const std::string &name); - void registerNewNode(const int id, const std::string &name); - int getActorId(const std::string &name); - int getNodeId(const std::string &name); - const char *getActorName(const int id); - const char *getNodeName(const int id); + void registerNewActor(const int id, const std::string & name); + void registerNewNode(const int id, const std::string & name); + int getActorId(const std::string & name); + int getNodeId(const std::string & name); + const char * getActorName(const int id); + const char * getNodeName(const int id); bool createTables(); bool initDatabase(); - bool registerRow(const ActionRow &row); - const std::list actionRowsFromSelect(sqlite3_stmt *stmt); - ActionRow actionRowFromRollbackAction(const RollbackAction &action); + bool registerRow(const ActionRow & row); + const std::list actionRowsFromSelect(sqlite3_stmt * stmt); + ActionRow actionRowFromRollbackAction(const RollbackAction & action); const std::list rollbackActionsFromActionRows( - const std::list &rows); - const std::list getRowsSince( - time_t firstTime, const std::string &actor); - const std::list getRowsSince_range( - time_t firstTime, v3s16 p, int range, int limit); - const std::list getActionsSince_range( - time_t firstTime, v3s16 p, int range, int limit); - const std::list getActionsSince( - time_t firstTime, const std::string &actor = ""); - void migrate(const std::string &filepath); - static float getSuspectNearness(bool is_guess, v3s16 suspect_p, time_t suspect_t, - v3s16 action_p, time_t action_t); + const std::list & rows); + const std::list getRowsSince(time_t firstTime, + const std::string & actor); + const std::list getRowsSince_range(time_t firstTime, v3s16 p, + int range, int limit); + const std::list getActionsSince_range(time_t firstTime, v3s16 p, + int range, int limit); + const std::list getActionsSince(time_t firstTime, + const std::string & actor = ""); + void migrate(const std::string & filepath); + static float getSuspectNearness(bool is_guess, v3s16 suspect_p, + time_t suspect_t, v3s16 action_p, time_t action_t); + IGameDef *gamedef = nullptr; @@ -86,16 +88,16 @@ class RollbackManager : public IRollbackManager std::list action_latest_buffer; std::string database_path; - sqlite3 *db; - sqlite3_stmt *stmt_insert; - sqlite3_stmt *stmt_replace; - sqlite3_stmt *stmt_select; - sqlite3_stmt *stmt_select_range; - sqlite3_stmt *stmt_select_withActor; - sqlite3_stmt *stmt_knownActor_select; - sqlite3_stmt *stmt_knownActor_insert; - sqlite3_stmt *stmt_knownNode_select; - sqlite3_stmt *stmt_knownNode_insert; + sqlite3 * db; + sqlite3_stmt * stmt_insert; + sqlite3_stmt * stmt_replace; + sqlite3_stmt * stmt_select; + sqlite3_stmt * stmt_select_range; + sqlite3_stmt * stmt_select_withActor; + sqlite3_stmt * stmt_knownActor_select; + sqlite3_stmt * stmt_knownActor_insert; + sqlite3_stmt * stmt_knownNode_select; + sqlite3_stmt * stmt_knownNode_insert; std::vector knownActors; std::vector knownNodes; diff --git a/src/rollback_interface.cpp b/src/rollback_interface.cpp index 2ab011192..c00206e98 100644 --- a/src/rollback_interface.cpp +++ b/src/rollback_interface.cpp @@ -33,6 +33,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventory.h" #include "mapblock.h" + RollbackNode::RollbackNode(Map *map, v3s16 p, IGameDef *gamedef) { const NodeDefManager *ndef = gamedef->ndef(); @@ -48,6 +49,7 @@ RollbackNode::RollbackNode(Map *map, v3s16 p, IGameDef *gamedef) } } + std::string RollbackAction::toString() const { std::ostringstream os(std::ios::binary); @@ -77,15 +79,16 @@ std::string RollbackAction::toString() const return os.str(); } + bool RollbackAction::isImportant(IGameDef *gamedef) const { if (type != TYPE_SET_NODE) return true; // If names differ, action is always important - if (n_old.name != n_new.name) + if(n_old.name != n_new.name) return true; // If metadata differs, action is always important - if (n_old.meta != n_new.meta) + if(n_old.meta != n_new.meta) return true; const NodeDefManager *ndef = gamedef->ndef(); // Both are of the same name, so a single definition is needed @@ -97,12 +100,12 @@ bool RollbackAction::isImportant(IGameDef *gamedef) const return true; } + bool RollbackAction::getPosition(v3s16 *dst) const { switch (type) { case TYPE_SET_NODE: - if (dst) - *dst = p; + if (dst) *dst = p; return true; case TYPE_MODIFY_INVENTORY_STACK: { InventoryLocation loc; @@ -110,17 +113,15 @@ bool RollbackAction::getPosition(v3s16 *dst) const if (loc.type != InventoryLocation::NODEMETA) { return false; } - if (dst) - *dst = loc.p; - return true; - } + if (dst) *dst = loc.p; + return true; } default: return false; } } -bool RollbackAction::applyRevert( - Map *map, InventoryManager *imgr, IGameDef *gamedef) const + +bool RollbackAction::applyRevert(Map *map, InventoryManager *imgr, IGameDef *gamedef) const { try { switch (type) { @@ -148,9 +149,9 @@ bool RollbackAction::applyRevert( try { if (!map->addNodeWithEvent(p, n)) { infostream << "RollbackAction::applyRevert(): " - << "AddNodeWithEvent failed at " - << PP(p) << " for " << n_old.name - << std::endl; + << "AddNodeWithEvent failed at " + << PP(p) << " for " << n_old.name + << std::endl; return false; } if (n_old.meta.empty()) { @@ -161,18 +162,14 @@ bool RollbackAction::applyRevert( meta = new NodeMetadata(gamedef->idef()); if (!map->setNodeMetadata(p, meta)) { delete meta; - infostream << "RollbackAction::" - "applyRevert(): " - << "setNodeMetadata " - "failed at " - << PP(p) << " for " - << n_old.name - << std::endl; + infostream << "RollbackAction::applyRevert(): " + << "setNodeMetadata failed at " + << PP(p) << " for " << n_old.name + << std::endl; return false; } } - std::istringstream is( - n_old.meta, std::ios::binary); + std::istringstream is(n_old.meta, std::ios::binary); meta->deSerialize(is, 1); // FIXME: version bump?? } // Inform other things that the meta data has changed @@ -182,38 +179,33 @@ bool RollbackAction::applyRevert( map->dispatchEvent(event); } catch (InvalidPositionException &e) { infostream << "RollbackAction::applyRevert(): " - << "InvalidPositionException: " << e.what() - << std::endl; + << "InvalidPositionException: " << e.what() + << std::endl; return false; } // Success - return true; - } + return true; } case TYPE_MODIFY_INVENTORY_STACK: { InventoryLocation loc; loc.deSerialize(inventory_location); Inventory *inv = imgr->getInventory(loc); if (!inv) { - infostream << "RollbackAction::applyRevert(): Could not " - "get " - "inventory at " - << inventory_location << std::endl; + infostream << "RollbackAction::applyRevert(): Could not get " + "inventory at " << inventory_location << std::endl; return false; } InventoryList *list = inv->getList(inventory_list); if (!list) { - infostream << "RollbackAction::applyRevert(): Could not " - "get " - "inventory list \"" - << inventory_list << "\" in " - << inventory_location << std::endl; + infostream << "RollbackAction::applyRevert(): Could not get " + "inventory list \"" << inventory_list << "\" in " + << inventory_location << std::endl; return false; } if (list->getSize() <= inventory_index) { infostream << "RollbackAction::applyRevert(): List index " - << inventory_index << " too large in " - << "inventory list \"" << inventory_list - << "\" in " << inventory_location << std::endl; + << inventory_index << " too large in " + << "inventory list \"" << inventory_list << "\" in " + << inventory_location << std::endl; return false; } @@ -221,8 +213,7 @@ bool RollbackAction::applyRevert( if (inventory_add) { // Silently ignore different current item if (list->getItem(inventory_index).name != - gamedef->idef()->getAlias( - inventory_stack.name)) + gamedef->idef()->getAlias(inventory_stack.name)) return false; list->takeItem(inventory_index, inventory_stack.count); } else { @@ -230,16 +221,16 @@ bool RollbackAction::applyRevert( } // Inventory was modified; send to clients imgr->setInventoryModified(loc); - return true; - } + return true; } default: errorstream << "RollbackAction::applyRevert(): type not handled" - << std::endl; + << std::endl; return false; } - } catch (SerializationError &e) { + } catch(SerializationError &e) { errorstream << "RollbackAction::applyRevert(): n_old.name=" << n_old.name - << ", SerializationError: " << e.what() << std::endl; + << ", SerializationError: " << e.what() << std::endl; } return false; } + diff --git a/src/rollback_interface.h b/src/rollback_interface.h index 827593782..94b800579 100644 --- a/src/rollback_interface.h +++ b/src/rollback_interface.h @@ -38,22 +38,22 @@ struct RollbackNode int param2 = 0; std::string meta; - bool operator==(const RollbackNode &other) + bool operator == (const RollbackNode &other) { return (name == other.name && param1 == other.param1 && param2 == other.param2 && meta == other.meta); } - bool operator!=(const RollbackNode &other) { return !(*this == other); } + bool operator != (const RollbackNode &other) { return !(*this == other); } RollbackNode() = default; RollbackNode(Map *map, v3s16 p, IGameDef *gamedef); }; + struct RollbackAction { - enum Type - { + enum Type{ TYPE_NOTHING, TYPE_SET_NODE, TYPE_MODIFY_INVENTORY_STACK, @@ -75,7 +75,8 @@ struct RollbackAction RollbackAction() = default; - void setSetNode(v3s16 p_, const RollbackNode &n_old_, const RollbackNode &n_new_) + void setSetNode(v3s16 p_, const RollbackNode &n_old_, + const RollbackNode &n_new_) { type = TYPE_SET_NODE; p = p_; @@ -84,8 +85,8 @@ struct RollbackAction } void setModifyInventoryStack(const std::string &inventory_location_, - const std::string &inventory_list_, u32 index_, bool add_, - const ItemStack &inventory_stack_) + const std::string &inventory_list_, u32 index_, + bool add_, const ItemStack &inventory_stack_) { type = TYPE_MODIFY_INVENTORY_STACK; inventory_location = inventory_location_; @@ -106,6 +107,7 @@ struct RollbackAction bool applyRevert(Map *map, InventoryManager *imgr, IGameDef *gamedef) const; }; + class IRollbackManager { public: @@ -113,27 +115,27 @@ class IRollbackManager virtual std::string getActor() = 0; virtual bool isActorGuess() = 0; virtual void setActor(const std::string &actor, bool is_guess) = 0; - virtual std::string getSuspect( - v3s16 p, float nearness_shortcut, float min_nearness) = 0; + virtual std::string getSuspect(v3s16 p, float nearness_shortcut, + float min_nearness) = 0; - virtual ~IRollbackManager() = default; - ; + virtual ~IRollbackManager() = default;; virtual void flush() = 0; // Get all actors that did something to position p, but not further than // in history - virtual std::list getNodeActors( - v3s16 pos, int range, time_t seconds, int limit) = 0; + virtual std::list getNodeActors(v3s16 pos, int range, + time_t seconds, int limit) = 0; // Get actions to revert of history made by - virtual std::list getRevertActions( - const std::string &actor, time_t seconds) = 0; + virtual std::list getRevertActions(const std::string &actor, + time_t seconds) = 0; }; + class RollbackScopeActor { public: - RollbackScopeActor(IRollbackManager *rollback_, const std::string &actor, - bool is_guess = false) : - rollback(rollback_) + RollbackScopeActor(IRollbackManager * rollback_, + const std::string & actor, bool is_guess = false) : + rollback(rollback_) { if (rollback) { old_actor = rollback->getActor(); @@ -149,7 +151,7 @@ class RollbackScopeActor } private: - IRollbackManager *rollback; + IRollbackManager * rollback; std::string old_actor; bool old_actor_guess; }; diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 9e99d5673..7d4c1e748 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -38,21 +38,23 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "debug.h" // For FATAL_ERROR #include -struct EnumString es_TileAnimationType[] = { - {TAT_NONE, "none"}, - {TAT_VERTICAL_FRAMES, "vertical_frames"}, - {TAT_SHEET_2D, "sheet_2d"}, - {0, NULL}, +struct EnumString es_TileAnimationType[] = +{ + {TAT_NONE, "none"}, + {TAT_VERTICAL_FRAMES, "vertical_frames"}, + {TAT_SHEET_2D, "sheet_2d"}, + {0, NULL}, }; /******************************************************************************/ -void read_item_definition(lua_State *L, int index, const ItemDefinition &default_def, - ItemDefinition &def) +void read_item_definition(lua_State* L, int index, + const ItemDefinition &default_def, ItemDefinition &def) { if (index < 0) index = lua_gettop(L) + 1 + index; - def.type = (ItemType)getenumfield(L, index, "type", es_ItemType, ITEM_NONE); + def.type = (ItemType)getenumfield(L, index, "type", + es_ItemType, ITEM_NONE); getstringfield(L, index, "name", def.name); getstringfield(L, index, "description", def.description); getstringfield(L, index, "inventory_image", def.inventory_image); @@ -67,7 +69,7 @@ void read_item_definition(lua_State *L, int index, const ItemDefinition &default lua_pop(L, 1); lua_getfield(L, index, "wield_scale"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ def.wield_scale = check_v3f(L, -1); } lua_pop(L, 1); @@ -85,15 +87,15 @@ void read_item_definition(lua_State *L, int index, const ItemDefinition &default "Obsolete; use tool_capabilities"); lua_getfield(L, index, "tool_capabilities"); - if (lua_istable(L, -1)) { - def.tool_capabilities = - new ToolCapabilities(read_tool_capabilities(L, -1)); + if(lua_istable(L, -1)){ + def.tool_capabilities = new ToolCapabilities( + read_tool_capabilities(L, -1)); } // If name is "" (hand), ensure there are ToolCapabilities // because it will be looked up there whenever any other item has // no ToolCapabilities - if (def.name.empty() && def.tool_capabilities == NULL) { + if (def.name.empty() && def.tool_capabilities == NULL){ def.tool_capabilities = new ToolCapabilities(); } @@ -180,10 +182,10 @@ void push_item_definition_full(lua_State *L, const ItemDefinition &i) } /******************************************************************************/ -void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, - ObjectProperties *prop, IItemDefManager *idef) +void read_object_properties(lua_State *L, int index, + ServerActiveObject *sao, ObjectProperties *prop, IItemDefManager *idef) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return; @@ -198,8 +200,7 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP); sao->setHP(prop->hp_max, reason); if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) - sao->getEnv()->getGameDef()->SendPlayerHPOrDie( - (PlayerSAO *)sao, reason); + sao->getEnv()->getGameDef()->SendPlayerHPOrDie((PlayerSAO *)sao, reason); } } @@ -247,13 +248,13 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, lua_pop(L, 1); lua_getfield(L, -1, "textures"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ prop->textures.clear(); int table = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table) != 0) { + while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 - if (lua_isstring(L, -1)) + if(lua_isstring(L, -1)) prop->textures.emplace_back(lua_tostring(L, -1)); else prop->textures.emplace_back(""); @@ -276,12 +277,12 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, lua_pop(L, 1); lua_getfield(L, -1, "spritediv"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) prop->spritediv = read_v2s16(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "initial_sprite_basepos"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) prop->initial_sprite_basepos = read_v2s16(L, -1); lua_pop(L, 1); @@ -315,8 +316,7 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec"); if (lua_isnumber(L, -1)) { - prop->automatic_face_movement_max_rotation_per_sec = - luaL_checknumber(L, -1); + prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1); } lua_pop(L, 1); @@ -417,15 +417,14 @@ void push_object_properties(lua_State *L, ObjectProperties *prop) lua_setfield(L, -2, "use_texture_alpha"); lua_pushboolean(L, prop->shaded); lua_setfield(L, -2, "shaded"); - lua_pushlstring(L, prop->damage_texture_modifier.c_str(), - prop->damage_texture_modifier.size()); + lua_pushlstring(L, prop->damage_texture_modifier.c_str(), prop->damage_texture_modifier.size()); lua_setfield(L, -2, "damage_texture_modifier"); } /******************************************************************************/ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; TileDef tiledef; @@ -433,39 +432,41 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) bool default_tiling = true; bool default_culling = true; switch (drawtype) { - case NDT_PLANTLIKE: - case NDT_PLANTLIKE_ROOTED: - case NDT_FIRELIKE: - default_tiling = false; - // "break" is omitted here intentionaly, as PLANTLIKE - // FIRELIKE drawtype both should default to having - // backface_culling to false. - case NDT_MESH: - case NDT_LIQUID: - default_culling = false; - break; - default: - break; + case NDT_PLANTLIKE: + case NDT_PLANTLIKE_ROOTED: + case NDT_FIRELIKE: + default_tiling = false; + // "break" is omitted here intentionaly, as PLANTLIKE + // FIRELIKE drawtype both should default to having + // backface_culling to false. + case NDT_MESH: + case NDT_LIQUID: + default_culling = false; + break; + default: + break; } // key at index -2 and value at index - if (lua_isstring(L, index)) { + if(lua_isstring(L, index)){ // "default_lava.png" tiledef.name = lua_tostring(L, index); tiledef.tileable_vertical = default_tiling; tiledef.tileable_horizontal = default_tiling; tiledef.backface_culling = default_culling; - } else if (lua_istable(L, index)) { + } + else if(lua_istable(L, index)) + { // name="default_lava.png" tiledef.name = ""; getstringfield(L, index, "name", tiledef.name); getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat. tiledef.backface_culling = getboolfield_default( - L, index, "backface_culling", default_culling); + L, index, "backface_culling", default_culling); tiledef.tileable_horizontal = getboolfield_default( - L, index, "tileable_horizontal", default_tiling); + L, index, "tileable_horizontal", default_tiling); tiledef.tileable_vertical = getboolfield_default( - L, index, "tileable_vertical", default_tiling); + L, index, "tileable_vertical", default_tiling); std::string align_style; if (getstringfield(L, index, "align_style", align_style)) { if (align_style == "user") @@ -492,23 +493,20 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) /******************************************************************************/ ContentFeatures read_content_features(lua_State *L, int index) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; ContentFeatures f; /* Cache existence of some callbacks */ lua_getfield(L, index, "on_construct"); - if (!lua_isnil(L, -1)) - f.has_on_construct = true; + if(!lua_isnil(L, -1)) f.has_on_construct = true; lua_pop(L, 1); lua_getfield(L, index, "on_destruct"); - if (!lua_isnil(L, -1)) - f.has_on_destruct = true; + if(!lua_isnil(L, -1)) f.has_on_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "after_destruct"); - if (!lua_isnil(L, -1)) - f.has_after_destruct = true; + if(!lua_isnil(L, -1)) f.has_after_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "on_rightclick"); @@ -525,8 +523,8 @@ ContentFeatures read_content_features(lua_State *L, int index) /* Visual definition */ - f.drawtype = (NodeDrawType)getenumfield( - L, index, "drawtype", ScriptApiNode::es_DrawType, NDT_NORMAL); + f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", + ScriptApiNode::es_DrawType,NDT_NORMAL); getfloatfield(L, index, "visual_scale", f.visual_scale); /* Meshnode model filename */ @@ -535,31 +533,31 @@ ContentFeatures read_content_features(lua_State *L, int index) // tiles = {} lua_getfield(L, index, "tiles"); // If nil, try the deprecated name "tile_images" instead - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "tile_images", "Deprecated; new name is \"tiles\"."); lua_getfield(L, index, "tile_images"); } - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; - while (lua_next(L, table) != 0) { + while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; - if (i == 6) { + if(i==6){ lua_pop(L, 1); break; } } // Copy last value to all remaining textures - if (i >= 1) { - TileDef lasttile = f.tiledef[i - 1]; - while (i < 6) { + if(i >= 1){ + TileDef lasttile = f.tiledef[i-1]; + while(i < 6){ f.tiledef[i] = lasttile; i++; } @@ -598,23 +596,23 @@ ContentFeatures read_content_features(lua_State *L, int index) // special_tiles = {} lua_getfield(L, index, "special_tiles"); // If nil, try the deprecated name "special_materials" instead - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "special_materials", "Deprecated; new name is \"special_tiles\"."); lua_getfield(L, index, "special_materials"); } - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; - while (lua_next(L, table) != 0) { + while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; - if (i == CF_SPECIAL_COUNT) { + if(i==CF_SPECIAL_COUNT){ lua_pop(L, 1); break; } @@ -624,7 +622,8 @@ ContentFeatures read_content_features(lua_State *L, int index) f.alpha = getintfield_default(L, index, "alpha", 255); - bool usealpha = getboolfield_default(L, index, "use_texture_alpha", false); + bool usealpha = getboolfield_default(L, index, + "use_texture_alpha", false); if (usealpha) f.alpha = 0; @@ -648,21 +647,22 @@ ContentFeatures read_content_features(lua_State *L, int index) if (!f.palette_name.empty() && !(f.param_type_2 == CPT2_COLOR || - f.param_type_2 == CPT2_COLORED_FACEDIR || - f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) + f.param_type_2 == CPT2_COLORED_FACEDIR || + f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) warningstream << "Node " << f.name.c_str() - << " has a palette, but not a suitable paramtype2." - << std::endl; + << " has a palette, but not a suitable paramtype2." << std::endl; // Warn about some obsolete fields warn_if_field_exists(L, index, "wall_mounted", "Obsolete; use paramtype2 = 'wallmounted'"); warn_if_field_exists(L, index, "light_propagates", "Obsolete; determined from paramtype"); - warn_if_field_exists(L, index, "dug_item", "Obsolete; use 'drop' field"); - warn_if_field_exists(L, index, "extra_dug_item", "Obsolete; use 'drop' field"); - warn_if_field_exists( - L, index, "extra_dug_item_rarity", "Obsolete; use 'drop' field"); + warn_if_field_exists(L, index, "dug_item", + "Obsolete; use 'drop' field"); + warn_if_field_exists(L, index, "extra_dug_item", + "Obsolete; use 'drop' field"); + warn_if_field_exists(L, index, "extra_dug_item_rarity", + "Obsolete; use 'drop' field"); warn_if_field_exists(L, index, "metadata_name", "Obsolete; use on_add and metadata callbacks"); @@ -695,27 +695,31 @@ ContentFeatures read_content_features(lua_State *L, int index) // Viscosity for fluid flow, ranging from 1 to 7, with // 1 giving almost instantaneous propagation and 7 being // the slowest possible - f.liquid_viscosity = getintfield_default( - L, index, "liquid_viscosity", f.liquid_viscosity); - f.liquid_range = getintfield_default(L, index, "liquid_range", f.liquid_range); + f.liquid_viscosity = getintfield_default(L, index, + "liquid_viscosity", f.liquid_viscosity); + f.liquid_range = getintfield_default(L, index, + "liquid_range", f.liquid_range); f.leveled = getintfield_default(L, index, "leveled", f.leveled); - f.leveled_max = getintfield_default(L, index, "leveled_max", f.leveled_max); + f.leveled_max = getintfield_default(L, index, + "leveled_max", f.leveled_max); getboolfield(L, index, "liquid_renewable", f.liquid_renewable); - f.drowning = getintfield_default(L, index, "drowning", f.drowning); + f.drowning = getintfield_default(L, index, + "drowning", f.drowning); // Amount of light the node emits - f.light_source = getintfield_default(L, index, "light_source", f.light_source); + f.light_source = getintfield_default(L, index, + "light_source", f.light_source); if (f.light_source > LIGHT_MAX) { warningstream << "Node " << f.name.c_str() - << " had greater light_source than " << LIGHT_MAX - << ", it was reduced." << std::endl; + << " had greater light_source than " << LIGHT_MAX + << ", it was reduced." << std::endl; f.light_source = LIGHT_MAX; } - f.damage_per_second = getintfield_default( - L, index, "damage_per_second", f.damage_per_second); + f.damage_per_second = getintfield_default(L, index, + "damage_per_second", f.damage_per_second); lua_getfield(L, index, "node_box"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) f.node_box = read_nodebox(L, -1); lua_pop(L, 1); @@ -753,23 +757,24 @@ ContentFeatures read_content_features(lua_State *L, int index) f.connect_sides |= 8; else warningstream << "Unknown value for \"connect_sides\": " - << side << std::endl; + << side << std::endl; lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, index, "selection_box"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) f.selection_box = read_nodebox(L, -1); - lua_pop(L, 1); + lua_pop(L, 1); lua_getfield(L, index, "collision_box"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) f.collision_box = read_nodebox(L, -1); lua_pop(L, 1); - f.waving = getintfield_default(L, index, "waving", f.waving); + f.waving = getintfield_default(L, index, + "waving", f.waving); // Set to true if paramtype used to be 'facedir_simple' getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple); @@ -778,7 +783,7 @@ ContentFeatures read_content_features(lua_State *L, int index) // Sound table lua_getfield(L, index, "sounds"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ lua_getfield(L, -1, "footstep"); read_soundspec(L, -1, f.sound_footstep); lua_pop(L, 1); @@ -792,7 +797,8 @@ ContentFeatures read_content_features(lua_State *L, int index) lua_pop(L, 1); // Node immediately placed by client when node is dug - getstringfield(L, index, "node_dig_prediction", f.node_dig_prediction); + getstringfield(L, index, "node_dig_prediction", + f.node_dig_prediction); return f; } @@ -800,8 +806,7 @@ ContentFeatures read_content_features(lua_State *L, int index) void push_content_features(lua_State *L, const ContentFeatures &c) { std::string paramtype(ScriptApiNode::es_ContentParamType[(int)c.param_type].str); - std::string paramtype2( - ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str); + std::string paramtype2(ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str); std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str); std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str); @@ -829,7 +834,7 @@ void push_content_features(lua_State *L, const ContentFeatures &c) lua_setfield(L, -2, "mesh"); } #ifndef SERVER - push_ARGB8(L, c.minimap_color); // I know this is not set-able w/ register_node, + push_ARGB8(L, c.minimap_color); // I know this is not set-able w/ register_node, lua_setfield(L, -2, "minimap_color"); // but the people need to know! #endif lua_pushnumber(L, c.visual_scale); @@ -929,47 +934,48 @@ void push_content_features(lua_State *L, const ContentFeatures &c) void push_nodebox(lua_State *L, const NodeBox &box) { lua_newtable(L); - switch (box.type) { - case NODEBOX_REGULAR: - lua_pushstring(L, "regular"); - lua_setfield(L, -2, "type"); - break; - case NODEBOX_LEVELED: - case NODEBOX_FIXED: - lua_pushstring(L, "fixed"); - lua_setfield(L, -2, "type"); - push_box(L, box.fixed); - lua_setfield(L, -2, "fixed"); - break; - case NODEBOX_WALLMOUNTED: - lua_pushstring(L, "wallmounted"); - lua_setfield(L, -2, "type"); - push_aabb3f(L, box.wall_top); - lua_setfield(L, -2, "wall_top"); - push_aabb3f(L, box.wall_bottom); - lua_setfield(L, -2, "wall_bottom"); - push_aabb3f(L, box.wall_side); - lua_setfield(L, -2, "wall_side"); - break; - case NODEBOX_CONNECTED: - lua_pushstring(L, "connected"); - lua_setfield(L, -2, "type"); - push_box(L, box.connect_top); - lua_setfield(L, -2, "connect_top"); - push_box(L, box.connect_bottom); - lua_setfield(L, -2, "connect_bottom"); - push_box(L, box.connect_front); - lua_setfield(L, -2, "connect_front"); - push_box(L, box.connect_back); - lua_setfield(L, -2, "connect_back"); - push_box(L, box.connect_left); - lua_setfield(L, -2, "connect_left"); - push_box(L, box.connect_right); - lua_setfield(L, -2, "connect_right"); - break; - default: - FATAL_ERROR("Invalid box.type"); - break; + switch (box.type) + { + case NODEBOX_REGULAR: + lua_pushstring(L, "regular"); + lua_setfield(L, -2, "type"); + break; + case NODEBOX_LEVELED: + case NODEBOX_FIXED: + lua_pushstring(L, "fixed"); + lua_setfield(L, -2, "type"); + push_box(L, box.fixed); + lua_setfield(L, -2, "fixed"); + break; + case NODEBOX_WALLMOUNTED: + lua_pushstring(L, "wallmounted"); + lua_setfield(L, -2, "type"); + push_aabb3f(L, box.wall_top); + lua_setfield(L, -2, "wall_top"); + push_aabb3f(L, box.wall_bottom); + lua_setfield(L, -2, "wall_bottom"); + push_aabb3f(L, box.wall_side); + lua_setfield(L, -2, "wall_side"); + break; + case NODEBOX_CONNECTED: + lua_pushstring(L, "connected"); + lua_setfield(L, -2, "type"); + push_box(L, box.connect_top); + lua_setfield(L, -2, "connect_top"); + push_box(L, box.connect_bottom); + lua_setfield(L, -2, "connect_bottom"); + push_box(L, box.connect_front); + lua_setfield(L, -2, "connect_front"); + push_box(L, box.connect_back); + lua_setfield(L, -2, "connect_back"); + push_box(L, box.connect_left); + lua_setfield(L, -2, "connect_left"); + push_box(L, box.connect_right); + lua_setfield(L, -2, "connect_right"); + break; + default: + FATAL_ERROR("Invalid box.type"); + break; } } @@ -998,37 +1004,37 @@ void push_palette(lua_State *L, const std::vector *palette) } /******************************************************************************/ -void read_server_sound_params(lua_State *L, int index, ServerSoundParams ¶ms) +void read_server_sound_params(lua_State *L, int index, + ServerSoundParams ¶ms) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; // Clear params = ServerSoundParams(); - if (lua_istable(L, index)) { + if(lua_istable(L, index)){ getfloatfield(L, index, "gain", params.gain); getstringfield(L, index, "to_player", params.to_player); getfloatfield(L, index, "fade", params.fade); getfloatfield(L, index, "pitch", params.pitch); lua_getfield(L, index, "pos"); - if (!lua_isnil(L, -1)) { - v3f p = read_v3f(L, -1) * BS; + if(!lua_isnil(L, -1)){ + v3f p = read_v3f(L, -1)*BS; params.pos = p; params.type = ServerSoundParams::SSP_POSITIONAL; } lua_pop(L, 1); lua_getfield(L, index, "object"); - if (!lua_isnil(L, -1)) { + if(!lua_isnil(L, -1)){ ObjectRef *ref = ObjectRef::checkobject(L, -1); ServerActiveObject *sao = ObjectRef::getobject(ref); - if (sao) { + if(sao){ params.object = sao->getId(); params.type = ServerSoundParams::SSP_OBJECT; } } lua_pop(L, 1); - params.max_hear_distance = - BS * getfloatfield_default(L, index, "max_hear_distance", - params.max_hear_distance / BS); + params.max_hear_distance = BS*getfloatfield_default(L, index, + "max_hear_distance", params.max_hear_distance/BS); getboolfield(L, index, "loop", params.loop); getstringfield(L, index, "exclude_player", params.exclude_player); } @@ -1037,7 +1043,7 @@ void read_server_sound_params(lua_State *L, int index, ServerSoundParams ¶ms /******************************************************************************/ void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return; @@ -1074,21 +1080,20 @@ NodeBox read_nodebox(lua_State *L, int index) luaL_checktype(L, -1, LUA_TTABLE); - nodebox.type = (NodeBoxType)getenumfield( - L, index, "type", ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); + nodebox.type = (NodeBoxType)getenumfield(L, index, "type", + ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); -#define NODEBOXREAD(n, s) \ - { \ - lua_getfield(L, index, (s)); \ - if (lua_istable(L, -1)) \ - (n) = read_aabb3f(L, -1, BS); \ - lua_pop(L, 1); \ +#define NODEBOXREAD(n, s){ \ + lua_getfield(L, index, (s)); \ + if (lua_istable(L, -1)) \ + (n) = read_aabb3f(L, -1, BS); \ + lua_pop(L, 1); \ } -#define NODEBOXREADVEC(n, s) \ - lua_getfield(L, index, (s)); \ - if (lua_istable(L, -1)) \ - (n) = read_aabb3f_vector(L, -1, BS); \ +#define NODEBOXREADVEC(n, s) \ + lua_getfield(L, index, (s)); \ + if (lua_istable(L, -1)) \ + (n) = read_aabb3f_vector(L, -1, BS); \ lua_pop(L, 1); NODEBOXREADVEC(nodebox.fixed, "fixed"); @@ -1154,31 +1159,34 @@ void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef) } /******************************************************************************/ -void warn_if_field_exists( - lua_State *L, int table, const char *name, const std::string &message) +void warn_if_field_exists(lua_State *L, int table, + const char *name, const std::string &message) { lua_getfield(L, table, name); if (!lua_isnil(L, -1)) { - warningstream << "Field \"" << name << "\": " << message << std::endl; + warningstream << "Field \"" << name << "\": " + << message << std::endl; infostream << script_get_backtrace(L) << std::endl; } lua_pop(L, 1); } /******************************************************************************/ -int getenumfield(lua_State *L, int table, const char *fieldname, const EnumString *spec, - int default_) +int getenumfield(lua_State *L, int table, + const char *fieldname, const EnumString *spec, int default_) { int result = default_; - string_to_enum(spec, result, getstringfield_default(L, table, fieldname, "")); + string_to_enum(spec, result, + getstringfield_default(L, table, fieldname, "")); return result; } /******************************************************************************/ -bool string_to_enum(const EnumString *spec, int &result, const std::string &str) +bool string_to_enum(const EnumString *spec, int &result, + const std::string &str) { const EnumString *esp = spec; - while (esp->str) { + while(esp->str){ if (!strcmp(str.c_str(), esp->str)) { result = esp->num; return true; @@ -1189,9 +1197,9 @@ bool string_to_enum(const EnumString *spec, int &result, const std::string &str) } /******************************************************************************/ -ItemStack read_item(lua_State *L, int index, IItemDefManager *idef) +ItemStack read_item(lua_State* L, int index, IItemDefManager *idef) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) { @@ -1207,16 +1215,21 @@ ItemStack read_item(lua_State *L, int index, IItemDefManager *idef) if (lua_isstring(L, index)) { // Convert from itemstring std::string itemstring = lua_tostring(L, index); - try { + try + { ItemStack item; item.deSerialize(itemstring, idef); return item; - } catch (SerializationError &e) { - warningstream << "unable to create item from itemstring" - << ": " << itemstring << std::endl; + } + catch(SerializationError &e) + { + warningstream<<"unable to create item from itemstring" + <<": "< lists = inventory->getLists(); - std::vector::iterator iter = lists.begin(); + std::vector lists = inventory->getLists(); + std::vector::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); for (; iter != lists.end(); iter++) { - const char *name = (*iter)->getName().c_str(); + const char* name = (*iter)->getName().c_str(); lua_pushstring(L, name); push_inventory_list(L, inventory, name); lua_rawset(L, -3); @@ -1312,40 +1325,40 @@ void push_inventory(lua_State *L, Inventory *inventory) void push_inventory_list(lua_State *L, Inventory *inv, const char *name) { InventoryList *invlist = inv->getList(name); - if (invlist == NULL) { + if(invlist == NULL){ lua_pushnil(L); return; } std::vector items; - for (u32 i = 0; i < invlist->getSize(); i++) + for(u32 i=0; igetSize(); i++) items.push_back(invlist->getItem(i)); push_items(L, items); } /******************************************************************************/ -void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const char *name, - Server *srv, int forcesize) +void read_inventory_list(lua_State *L, int tableindex, + Inventory *inv, const char *name, Server* srv, int forcesize) { - if (tableindex < 0) + if(tableindex < 0) tableindex = lua_gettop(L) + 1 + tableindex; // If nil, delete list - if (lua_isnil(L, tableindex)) { + if(lua_isnil(L, tableindex)){ inv->deleteList(name); return; } // Otherwise set list - std::vector items = read_items(L, tableindex, srv); + std::vector items = read_items(L, tableindex,srv); int listsize = (forcesize != -1) ? forcesize : items.size(); InventoryList *invlist = inv->addList(name, listsize); int index = 0; - for (std::vector::const_iterator i = items.begin(); i != items.end(); - ++i) { - if (forcesize != -1 && index == forcesize) + for(std::vector::const_iterator + i = items.begin(); i != items.end(); ++i){ + if(forcesize != -1 && index == forcesize) break; invlist->changeItem(index, *i); index++; } - while (forcesize != -1 && index < forcesize) { + while(forcesize != -1 && index < forcesize){ invlist->deleteItem(index); index++; } @@ -1354,7 +1367,7 @@ void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const cha /******************************************************************************/ struct TileAnimationParams read_animation_definition(lua_State *L, int index) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; struct TileAnimationParams anim; @@ -1362,75 +1375,74 @@ struct TileAnimationParams read_animation_definition(lua_State *L, int index) if (!lua_istable(L, index)) return anim; - anim.type = (TileAnimationType)getenumfield( - L, index, "type", es_TileAnimationType, TAT_NONE); + anim.type = (TileAnimationType) + getenumfield(L, index, "type", es_TileAnimationType, + TAT_NONE); if (anim.type == TAT_VERTICAL_FRAMES) { // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0} anim.vertical_frames.aspect_w = - getintfield_default(L, index, "aspect_w", 16); + getintfield_default(L, index, "aspect_w", 16); anim.vertical_frames.aspect_h = - getintfield_default(L, index, "aspect_h", 16); + getintfield_default(L, index, "aspect_h", 16); anim.vertical_frames.length = - getfloatfield_default(L, index, "length", 1.0); + getfloatfield_default(L, index, "length", 1.0); } else if (anim.type == TAT_SHEET_2D) { // {type="sheet_2d", frames_w=5, frames_h=3, frame_length=0.5} - getintfield(L, index, "frames_w", anim.sheet_2d.frames_w); - getintfield(L, index, "frames_h", anim.sheet_2d.frames_h); - getfloatfield(L, index, "frame_length", anim.sheet_2d.frame_length); + getintfield(L, index, "frames_w", + anim.sheet_2d.frames_w); + getintfield(L, index, "frames_h", + anim.sheet_2d.frames_h); + getfloatfield(L, index, "frame_length", + anim.sheet_2d.frame_length); } return anim; } /******************************************************************************/ -ToolCapabilities read_tool_capabilities(lua_State *L, int table) +ToolCapabilities read_tool_capabilities( + lua_State *L, int table) { ToolCapabilities toolcap; getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval); getintfield(L, table, "max_drop_level", toolcap.max_drop_level); getintfield(L, table, "punch_attack_uses", toolcap.punch_attack_uses); lua_getfield(L, table, "groupcaps"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_groupcaps = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table_groupcaps) != 0) { + while(lua_next(L, table_groupcaps) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_groupcap = lua_gettop(L); // This will be created ToolGroupCap groupcap; // Read simple parameters - getintfield(L, table_groupcap, "maxlevel", - groupcap.maxlevel); + getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel); getintfield(L, table_groupcap, "uses", groupcap.uses); // DEPRECATED: maxwear float maxwear = 0; - if (getfloatfield(L, table_groupcap, "maxwear", - maxwear)) { + if (getfloatfield(L, table_groupcap, "maxwear", maxwear)){ if (maxwear != 0) - groupcap.uses = 1.0 / maxwear; + groupcap.uses = 1.0/maxwear; else groupcap.uses = 0; - warningstream << "Field \"maxwear\" is " - "deprecated; " - << "replace with uses=1/maxwear" - << std::endl; - infostream << script_get_backtrace(L) - << std::endl; + warningstream << "Field \"maxwear\" is deprecated; " + << "replace with uses=1/maxwear" << std::endl; + infostream << script_get_backtrace(L) << std::endl; } // Read "times" table lua_getfield(L, table_groupcap, "times"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_times = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table_times) != 0) { + while(lua_next(L, table_times) != 0){ // key at index -2 and value at index -1 int rating = luaL_checkinteger(L, -2); float time = luaL_checknumber(L, -1); groupcap.times[rating] = time; - // removes value, keeps key for next - // iteration + // removes value, keeps key for next iteration lua_pop(L, 1); } } @@ -1445,10 +1457,10 @@ ToolCapabilities read_tool_capabilities(lua_State *L, int table) lua_pop(L, 1); lua_getfield(L, table, "damage_groups"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_damage_groups = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table_damage_groups) != 0) { + while(lua_next(L, table_damage_groups) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); u16 value = luaL_checkinteger(L, -1); @@ -1462,7 +1474,7 @@ ToolCapabilities read_tool_capabilities(lua_State *L, int table) } /******************************************************************************/ -void push_dig_params(lua_State *L, const DigParams ¶ms) +void push_dig_params(lua_State *L,const DigParams ¶ms) { lua_createtable(L, 0, 3); setboolfield(L, -1, "diggable", params.diggable); @@ -1471,7 +1483,7 @@ void push_dig_params(lua_State *L, const DigParams ¶ms) } /******************************************************************************/ -void push_hit_params(lua_State *L, const HitParams ¶ms) +void push_hit_params(lua_State *L,const HitParams ¶ms) { lua_createtable(L, 0, 3); setintfield(L, -1, "hp", params.hp); @@ -1480,8 +1492,8 @@ void push_hit_params(lua_State *L, const HitParams ¶ms) /******************************************************************************/ -bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *flagdesc, - u32 *flags, u32 *flagmask) +bool getflagsfield(lua_State *L, int table, const char *fieldname, + FlagDesc *flagdesc, u32 *flags, u32 *flagmask) { lua_getfield(L, table, fieldname); @@ -1492,7 +1504,8 @@ bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *fla return success; } -bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, u32 *flags, u32 *flagmask) +bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, + u32 *flags, u32 *flagmask) { if (lua_isstring(L, index)) { std::string flagstr = lua_tostring(L, index); @@ -1588,7 +1601,7 @@ void push_items(lua_State *L, const std::vector &items) /******************************************************************************/ std::vector read_items(lua_State *L, int index, Server *srv) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; std::vector items; @@ -1599,7 +1612,7 @@ std::vector read_items(lua_State *L, int index, Server *srv) if (key < 1) { throw LuaError("Invalid inventory list index"); } - if (items.size() < (u32)key) { + if (items.size() < (u32) key) { items.resize(key); } items[key - 1] = read_item(L, -1, srv->idef()); @@ -1630,23 +1643,21 @@ bool read_noiseparams(lua_State *L, int index, NoiseParams *np) if (!lua_istable(L, index)) return false; - getfloatfield(L, index, "offset", np->offset); - getfloatfield(L, index, "scale", np->scale); - getfloatfield(L, index, "persist", np->persist); + getfloatfield(L, index, "offset", np->offset); + getfloatfield(L, index, "scale", np->scale); + getfloatfield(L, index, "persist", np->persist); getfloatfield(L, index, "persistence", np->persist); - getfloatfield(L, index, "lacunarity", np->lacunarity); - getintfield(L, index, "seed", np->seed); - getintfield(L, index, "octaves", np->octaves); + getfloatfield(L, index, "lacunarity", np->lacunarity); + getintfield(L, index, "seed", np->seed); + getintfield(L, index, "octaves", np->octaves); - u32 flags = 0; + u32 flags = 0; u32 flagmask = 0; - np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams, &flags, - &flagmask) - ? flags - : NOISE_FLAG_DEFAULTS; + np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams, + &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS; lua_getfield(L, index, "spread"); - np->spread = read_v3f(L, -1); + np->spread = read_v3f(L, -1); lua_pop(L, 1); return true; @@ -1668,7 +1679,8 @@ void push_noiseparams(lua_State *L, NoiseParams *np) lua_pushnumber(L, np->octaves); lua_setfield(L, -2, "octaves"); - push_flags_string(L, flagdesc_noiseparams, np->flags, np->flags); + push_flags_string(L, flagdesc_noiseparams, np->flags, + np->flags); lua_setfield(L, -2, "flags"); push_v3_float_string(L, np->spread); @@ -1691,52 +1703,55 @@ static int push_json_value_getdepth(const Json::Value &value) return maxdepth + 1; } // Recursive function to convert JSON --> Lua table -static bool push_json_value_helper(lua_State *L, const Json::Value &value, int nullindex) +static bool push_json_value_helper(lua_State *L, const Json::Value &value, + int nullindex) { - switch (value.type()) { - case Json::nullValue: - default: - lua_pushvalue(L, nullindex); - break; - case Json::intValue: - lua_pushinteger(L, value.asLargestInt()); - break; - case Json::uintValue: - lua_pushinteger(L, value.asLargestUInt()); - break; - case Json::realValue: - lua_pushnumber(L, value.asDouble()); - break; - case Json::stringValue: { - const char *str = value.asCString(); - lua_pushstring(L, str ? str : ""); - } break; - case Json::booleanValue: - lua_pushboolean(L, value.asInt()); - break; - case Json::arrayValue: - lua_createtable(L, value.size(), 0); - for (Json::Value::const_iterator it = value.begin(); it != value.end(); - ++it) { - push_json_value_helper(L, *it, nullindex); - lua_rawseti(L, -2, it.index() + 1); - } - break; - case Json::objectValue: - lua_createtable(L, 0, value.size()); - for (Json::Value::const_iterator it = value.begin(); it != value.end(); - ++it) { + switch(value.type()) { + case Json::nullValue: + default: + lua_pushvalue(L, nullindex); + break; + case Json::intValue: + lua_pushinteger(L, value.asLargestInt()); + break; + case Json::uintValue: + lua_pushinteger(L, value.asLargestUInt()); + break; + case Json::realValue: + lua_pushnumber(L, value.asDouble()); + break; + case Json::stringValue: + { + const char *str = value.asCString(); + lua_pushstring(L, str ? str : ""); + } + break; + case Json::booleanValue: + lua_pushboolean(L, value.asInt()); + break; + case Json::arrayValue: + lua_createtable(L, value.size(), 0); + for (Json::Value::const_iterator it = value.begin(); + it != value.end(); ++it) { + push_json_value_helper(L, *it, nullindex); + lua_rawseti(L, -2, it.index() + 1); + } + break; + case Json::objectValue: + lua_createtable(L, 0, value.size()); + for (Json::Value::const_iterator it = value.begin(); + it != value.end(); ++it) { #if !defined(JSONCPP_STRING) && (JSONCPP_VERSION_MAJOR < 1 || JSONCPP_VERSION_MINOR < 9) - const char *str = it.memberName(); - lua_pushstring(L, str ? str : ""); + const char *str = it.memberName(); + lua_pushstring(L, str ? str : ""); #else - std::string str = it.name(); - lua_pushstring(L, str.c_str()); + std::string str = it.name(); + lua_pushstring(L, str.c_str()); #endif - push_json_value_helper(L, *it, nullindex); - lua_rawset(L, -3); - } - break; + push_json_value_helper(L, *it, nullindex); + lua_rawset(L, -3); + } + break; } return true; } @@ -1744,7 +1759,7 @@ static bool push_json_value_helper(lua_State *L, const Json::Value &value, int n // nullindex: Lua stack index of value to use in place of JSON null bool push_json_value(lua_State *L, const Json::Value &value, int nullindex) { - if (nullindex < 0) + if(nullindex < 0) nullindex = lua_gettop(L) + 1 + nullindex; int depth = push_json_value_getdepth(value); @@ -1765,7 +1780,7 @@ void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion) } int type = lua_type(L, index); if (type == LUA_TBOOLEAN) { - root = (bool)lua_toboolean(L, index); + root = (bool) lua_toboolean(L, index); } else if (type == LUA_TNUMBER) { root = lua_tonumber(L, index); } else if (type == LUA_TSTRING) { @@ -1783,43 +1798,33 @@ void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion) int keytype = lua_type(L, -1); if (keytype == LUA_TNUMBER) { lua_Number key = lua_tonumber(L, -1); - if (roottype != Json::nullValue && - roottype != Json::arrayValue) { - throw SerializationError("Can't mix array and " - "object values in JSON"); + if (roottype != Json::nullValue && roottype != Json::arrayValue) { + throw SerializationError("Can't mix array and object values in JSON"); } else if (key < 1) { - throw SerializationError( - "Can't use zero-based or " - "negative indexes in JSON"); + throw SerializationError("Can't use zero-based or negative indexes in JSON"); } else if (floor(key) != key) { - throw SerializationError( - "Can't use indexes with a " - "fractional part in JSON"); + throw SerializationError("Can't use indexes with a fractional part in JSON"); } - root[(Json::ArrayIndex)key - 1] = value; + root[(Json::ArrayIndex) key - 1] = value; } else if (keytype == LUA_TSTRING) { - if (roottype != Json::nullValue && - roottype != Json::objectValue) { - throw SerializationError("Can't mix array and " - "object values in JSON"); + if (roottype != Json::nullValue && roottype != Json::objectValue) { + throw SerializationError("Can't mix array and object values in JSON"); } root[lua_tostring(L, -1)] = value; } else { - throw SerializationError("Lua key to convert to JSON is " - "not a string or number"); + throw SerializationError("Lua key to convert to JSON is not a string or number"); } } } else if (type == LUA_TNIL) { root = Json::nullValue; } else { - throw SerializationError("Can only store booleans, numbers, strings, " - "objects, arrays, and null in JSON"); + throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON"); } lua_pop(L, 1); // Pop value } -void push_pointed_thing( - lua_State *L, const PointedThing &pointed, bool csm, bool hitpoint) +void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm, + bool hitpoint) { lua_newtable(L); if (pointed.type == POINTEDTHING_NODE) { @@ -1838,7 +1843,7 @@ void push_pointed_thing( } else { push_objectRef(L, pointed.object_id); } - + lua_setfield(L, -2, "ref"); } else { lua_pushstring(L, "nothing"); @@ -1868,8 +1873,8 @@ void push_objectRef(lua_State *L, const u16 id) void read_hud_element(lua_State *L, HudElement *elem) { - elem->type = (HudElementType)getenumfield( - L, 2, "hud_elem_type", es_HudElementType, HUD_ELEM_TEXT); + elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type", + es_HudElementType, HUD_ELEM_TEXT); lua_getfield(L, 2, "position"); elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f(); @@ -1883,18 +1888,18 @@ void read_hud_element(lua_State *L, HudElement *elem) elem->size = lua_istable(L, -1) ? read_v2s32(L, -1) : v2s32(); lua_pop(L, 1); - elem->name = getstringfield_default(L, 2, "name", ""); - elem->text = getstringfield_default(L, 2, "text", ""); - elem->number = getintfield_default(L, 2, "number", 0); + elem->name = getstringfield_default(L, 2, "name", ""); + elem->text = getstringfield_default(L, 2, "text", ""); + elem->number = getintfield_default(L, 2, "number", 0); if (elem->type == HUD_ELEM_WAYPOINT) // waypoints reuse the item field to store precision, item = precision + 1 elem->item = getintfield_default(L, 2, "precision", -1) + 1; else elem->item = getintfield_default(L, 2, "item", 0); - elem->dir = getintfield_default(L, 2, "direction", 0); - elem->z_index = MYMAX( - S16_MIN, MYMIN(S16_MAX, getintfield_default(L, 2, "z_index", 0))); - elem->text2 = getstringfield_default(L, 2, "text2", ""); + elem->dir = getintfield_default(L, 2, "direction", 0); + elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, + getintfield_default(L, 2, "z_index", 0))); + elem->text2 = getstringfield_default(L, 2, "text2", ""); // Deprecated, only for compatibility's sake if (elem->dir == 0) @@ -1913,8 +1918,8 @@ void read_hud_element(lua_State *L, HudElement *elem) lua_pop(L, 1); /* check for known deprecated element usage */ - if ((elem->type == HUD_ELEM_STATBAR) && (elem->size == v2s32())) - log_deprecated(L, "Deprecated usage of statbar without size!"); + if ((elem->type == HUD_ELEM_STATBAR) && (elem->size == v2s32())) + log_deprecated(L,"Deprecated usage of statbar without size!"); } void push_hud_element(lua_State *L, HudElement *elem) @@ -1974,64 +1979,63 @@ HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value) if (lua_isstring(L, 3)) { int statint; std::string statstr = lua_tostring(L, 3); - stat = string_to_enum(es_HudElementStat, statint, statstr) - ? (HudElementStat)statint - : stat; + stat = string_to_enum(es_HudElementStat, statint, statstr) ? + (HudElementStat)statint : stat; } switch (stat) { - case HUD_STAT_POS: - elem->pos = read_v2f(L, 4); - *value = &elem->pos; - break; - case HUD_STAT_NAME: - elem->name = luaL_checkstring(L, 4); - *value = &elem->name; - break; - case HUD_STAT_SCALE: - elem->scale = read_v2f(L, 4); - *value = &elem->scale; - break; - case HUD_STAT_TEXT: - elem->text = luaL_checkstring(L, 4); - *value = &elem->text; - break; - case HUD_STAT_NUMBER: - elem->number = luaL_checknumber(L, 4); - *value = &elem->number; - break; - case HUD_STAT_ITEM: - elem->item = luaL_checknumber(L, 4); - *value = &elem->item; - break; - case HUD_STAT_DIR: - elem->dir = luaL_checknumber(L, 4); - *value = &elem->dir; - break; - case HUD_STAT_ALIGN: - elem->align = read_v2f(L, 4); - *value = &elem->align; - break; - case HUD_STAT_OFFSET: - elem->offset = read_v2f(L, 4); - *value = &elem->offset; - break; - case HUD_STAT_WORLD_POS: - elem->world_pos = read_v3f(L, 4); - *value = &elem->world_pos; - break; - case HUD_STAT_SIZE: - elem->size = read_v2s32(L, 4); - *value = &elem->size; - break; - case HUD_STAT_Z_INDEX: - elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, luaL_checknumber(L, 4))); - *value = &elem->z_index; - break; - case HUD_STAT_TEXT2: - elem->text2 = luaL_checkstring(L, 4); - *value = &elem->text2; - break; + case HUD_STAT_POS: + elem->pos = read_v2f(L, 4); + *value = &elem->pos; + break; + case HUD_STAT_NAME: + elem->name = luaL_checkstring(L, 4); + *value = &elem->name; + break; + case HUD_STAT_SCALE: + elem->scale = read_v2f(L, 4); + *value = &elem->scale; + break; + case HUD_STAT_TEXT: + elem->text = luaL_checkstring(L, 4); + *value = &elem->text; + break; + case HUD_STAT_NUMBER: + elem->number = luaL_checknumber(L, 4); + *value = &elem->number; + break; + case HUD_STAT_ITEM: + elem->item = luaL_checknumber(L, 4); + *value = &elem->item; + break; + case HUD_STAT_DIR: + elem->dir = luaL_checknumber(L, 4); + *value = &elem->dir; + break; + case HUD_STAT_ALIGN: + elem->align = read_v2f(L, 4); + *value = &elem->align; + break; + case HUD_STAT_OFFSET: + elem->offset = read_v2f(L, 4); + *value = &elem->offset; + break; + case HUD_STAT_WORLD_POS: + elem->world_pos = read_v3f(L, 4); + *value = &elem->world_pos; + break; + case HUD_STAT_SIZE: + elem->size = read_v2s32(L, 4); + *value = &elem->size; + break; + case HUD_STAT_Z_INDEX: + elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, luaL_checknumber(L, 4))); + *value = &elem->z_index; + break; + case HUD_STAT_TEXT2: + elem->text2 = luaL_checkstring(L, 4); + *value = &elem->text2; + break; } return stat; } @@ -2040,15 +2044,15 @@ HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value) // Indices must match values in `enum CollisionType` exactly!! static const char *collision_type_str[] = { - "node", - "object", + "node", + "object", }; // Indices must match values in `enum CollisionAxis` exactly!! static const char *collision_axis_str[] = { - "x", - "y", - "z", + "x", + "y", + "z", }; void push_collision_move_result(lua_State *L, const collisionMoveResult &res) diff --git a/src/script/common/c_content.h b/src/script/common/c_content.h index 49ab96fd5..5a8bf6700 100644 --- a/src/script/common/c_content.h +++ b/src/script/common/c_content.h @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + /******************************************************************************/ /******************************************************************************/ /* WARNING!!!! do NOT add this header in any include file or any code file */ @@ -40,10 +41,7 @@ extern "C" { #include "c_types.h" #include "hud.h" -namespace Json -{ -class Value; -} +namespace Json { class Value; } struct MapNode; class NodeDefManager; @@ -69,96 +67,138 @@ struct collisionMoveResult; extern struct EnumString es_TileAnimationType[]; -ContentFeatures read_content_features(lua_State *L, int index); -void push_content_features(lua_State *L, const ContentFeatures &c); +ContentFeatures read_content_features (lua_State *L, int index); +void push_content_features (lua_State *L, + const ContentFeatures &c); -void push_nodebox(lua_State *L, const NodeBox &box); -void push_box(lua_State *L, const std::vector &box); +void push_nodebox (lua_State *L, + const NodeBox &box); +void push_box (lua_State *L, + const std::vector &box); -void push_palette(lua_State *L, const std::vector *palette); +void push_palette (lua_State *L, + const std::vector *palette); -TileDef read_tiledef(lua_State *L, int index, u8 drawtype); +TileDef read_tiledef (lua_State *L, int index, + u8 drawtype); -void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec); -NodeBox read_nodebox(lua_State *L, int index); +void read_soundspec (lua_State *L, int index, + SimpleSoundSpec &spec); +NodeBox read_nodebox (lua_State *L, int index); -void read_server_sound_params(lua_State *L, int index, ServerSoundParams ¶ms); +void read_server_sound_params (lua_State *L, int index, + ServerSoundParams ¶ms); -void push_dig_params(lua_State *L, const DigParams ¶ms); -void push_hit_params(lua_State *L, const HitParams ¶ms); +void push_dig_params (lua_State *L, + const DigParams ¶ms); +void push_hit_params (lua_State *L, + const HitParams ¶ms); -ItemStack read_item(lua_State *L, int index, IItemDefManager *idef); +ItemStack read_item (lua_State *L, int index, IItemDefManager *idef); struct TileAnimationParams read_animation_definition(lua_State *L, int index); -ToolCapabilities read_tool_capabilities(lua_State *L, int table); -void push_tool_capabilities(lua_State *L, const ToolCapabilities &prop); +ToolCapabilities read_tool_capabilities (lua_State *L, int table); +void push_tool_capabilities (lua_State *L, + const ToolCapabilities &prop); -void read_item_definition(lua_State *L, int index, const ItemDefinition &default_def, +void read_item_definition (lua_State *L, int index, const ItemDefinition &default_def, ItemDefinition &def); -void push_item_definition(lua_State *L, const ItemDefinition &i); -void push_item_definition_full(lua_State *L, const ItemDefinition &i); - -void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, - ObjectProperties *prop, IItemDefManager *idef); -void push_object_properties(lua_State *L, ObjectProperties *prop); - -void push_inventory(lua_State *L, Inventory *inventory); - -void push_inventory_list(lua_State *L, Inventory *inv, const char *name); -void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const char *name, - Server *srv, int forcesize = -1); - -MapNode readnode(lua_State *L, int index, const NodeDefManager *ndef); -void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef); - -void read_groups(lua_State *L, int index, ItemGroupList &result); - -void push_groups(lua_State *L, const ItemGroupList &groups); - -// TODO rename to "read_enum_field" -int getenumfield(lua_State *L, int table, const char *fieldname, const EnumString *spec, - int default_); - -bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *flagdesc, - u32 *flags, u32 *flagmask); - -bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, u32 *flags, u32 *flagmask); - -void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask); - -u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask); - -void push_items(lua_State *L, const std::vector &items); - -std::vector read_items(lua_State *L, int index, Server *srv); - -void push_soundspec(lua_State *L, const SimpleSoundSpec &spec); - -bool string_to_enum(const EnumString *spec, int &result, const std::string &str); - -bool read_noiseparams(lua_State *L, int index, NoiseParams *np); -void push_noiseparams(lua_State *L, NoiseParams *np); - -void luaentity_get(lua_State *L, u16 id); - -bool push_json_value(lua_State *L, const Json::Value &value, int nullindex); -void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion = 0); +void push_item_definition (lua_State *L, + const ItemDefinition &i); +void push_item_definition_full (lua_State *L, + const ItemDefinition &i); + +void read_object_properties (lua_State *L, int index, + ServerActiveObject *sao, + ObjectProperties *prop, + IItemDefManager *idef); +void push_object_properties (lua_State *L, + ObjectProperties *prop); + +void push_inventory (lua_State *L, + Inventory *inventory); + +void push_inventory_list (lua_State *L, + Inventory *inv, + const char *name); +void read_inventory_list (lua_State *L, int tableindex, + Inventory *inv, const char *name, + Server *srv, int forcesize=-1); + +MapNode readnode (lua_State *L, int index, + const NodeDefManager *ndef); +void pushnode (lua_State *L, const MapNode &n, + const NodeDefManager *ndef); + + +void read_groups (lua_State *L, int index, + ItemGroupList &result); + +void push_groups (lua_State *L, + const ItemGroupList &groups); + +//TODO rename to "read_enum_field" +int getenumfield (lua_State *L, int table, + const char *fieldname, + const EnumString *spec, + int default_); + +bool getflagsfield (lua_State *L, int table, + const char *fieldname, + FlagDesc *flagdesc, + u32 *flags, u32 *flagmask); + +bool read_flags (lua_State *L, int index, + FlagDesc *flagdesc, + u32 *flags, u32 *flagmask); + +void push_flags_string (lua_State *L, FlagDesc *flagdesc, + u32 flags, u32 flagmask); + +u32 read_flags_table (lua_State *L, int table, + FlagDesc *flagdesc, u32 *flagmask); + +void push_items (lua_State *L, + const std::vector &items); + +std::vector read_items (lua_State *L, + int index, + Server* srv); + +void push_soundspec (lua_State *L, + const SimpleSoundSpec &spec); + +bool string_to_enum (const EnumString *spec, + int &result, + const std::string &str); + +bool read_noiseparams (lua_State *L, int index, + NoiseParams *np); +void push_noiseparams (lua_State *L, NoiseParams *np); + +void luaentity_get (lua_State *L,u16 id); + +bool push_json_value (lua_State *L, + const Json::Value &value, + int nullindex); +void read_json_value (lua_State *L, Json::Value &root, + int index, u8 recursion = 0); /*! * Pushes a Lua `pointed_thing` to the given Lua stack. * \param csm If true, a client side pointed thing is pushed * \param hitpoint If true, the exact pointing location is also pushed */ -void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm = false, - bool hitpoint = false); +void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm = + false, bool hitpoint = false); -void push_objectRef(lua_State *L, const u16 id); +void push_objectRef (lua_State *L, const u16 id); -void read_hud_element(lua_State *L, HudElement *elem); +void read_hud_element (lua_State *L, HudElement *elem); -void push_hud_element(lua_State *L, HudElement *elem); +void push_hud_element (lua_State *L, HudElement *elem); -HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value); +HudElementStat read_hud_change (lua_State *L, HudElement *elem, void **value); -void push_collision_move_result(lua_State *L, const collisionMoveResult &res); +void push_collision_move_result(lua_State *L, const collisionMoveResult &res); diff --git a/src/script/common/c_converter.cpp b/src/script/common/c_converter.cpp index 349f148d3..eb6ab5331 100644 --- a/src/script/common/c_converter.cpp +++ b/src/script/common/c_converter.cpp @@ -30,27 +30,27 @@ extern "C" { #include "constants.h" #include -#define CHECK_TYPE(index, name, type) \ - { \ - int t = lua_type(L, (index)); \ - if (t != (type)) { \ - throw LuaError(std::string("Invalid ") + (name) + \ - " (expected " + lua_typename(L, (type)) + \ - " got " + lua_typename(L, t) + ")."); \ - } \ - } -#define CHECK_POS_COORD(name) \ - CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER) -#define CHECK_FLOAT_RANGE(value, name) \ - if (value < F1000_MIN || value > F1000_MAX) { \ - std::ostringstream error_text; \ - error_text << "Invalid float vector dimension range '" name "' " \ - << "(expected " << F1000_MIN << " < " name " < " << F1000_MAX \ - << " got " << value << ")." << std::endl; \ - throw LuaError(error_text.str()); \ + +#define CHECK_TYPE(index, name, type) { \ + int t = lua_type(L, (index)); \ + if (t != (type)) { \ + throw LuaError(std::string("Invalid ") + (name) + \ + " (expected " + lua_typename(L, (type)) + \ + " got " + lua_typename(L, t) + ")."); \ + } \ } +#define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER) +#define CHECK_FLOAT_RANGE(value, name) \ +if (value < F1000_MIN || value > F1000_MAX) { \ + std::ostringstream error_text; \ + error_text << "Invalid float vector dimension range '" name "' " << \ + "(expected " << F1000_MIN << " < " name " < " << F1000_MAX << \ + " got " << value << ")." << std::endl; \ + throw LuaError(error_text.str()); \ +} #define CHECK_POS_TAB(index) CHECK_TYPE(index, "position", LUA_TTABLE) + void push_float_string(lua_State *L, float value) { std::stringstream ss; @@ -360,7 +360,7 @@ bool is_color_table(lua_State *L, int index) aabb3f read_aabb3f(lua_State *L, int index, f32 scale) { aabb3f box; - if (lua_istable(L, index)) { + if(lua_istable(L, index)){ lua_rawgeti(L, index, 1); box.MinEdge.X = lua_tonumber(L, -1) * scale; lua_pop(L, 1); @@ -404,22 +404,22 @@ void push_aabb3f(lua_State *L, aabb3f box) std::vector read_aabb3f_vector(lua_State *L, int index, f32 scale) { std::vector boxes; - if (lua_istable(L, index)) { + if(lua_istable(L, index)){ int n = lua_objlen(L, index); // Check if it's a single box or a list of boxes bool possibly_single_box = (n == 6); - for (int i = 1; i <= n && possibly_single_box; i++) { + for(int i = 1; i <= n && possibly_single_box; i++){ lua_rawgeti(L, index, i); - if (!lua_isnumber(L, -1)) + if(!lua_isnumber(L, -1)) possibly_single_box = false; lua_pop(L, 1); } - if (possibly_single_box) { + if(possibly_single_box){ // Read a single box boxes.push_back(read_aabb3f(L, index, scale)); } else { // Read a list of boxes - for (int i = 1; i <= n; i++) { + for(int i = 1; i <= n; i++){ lua_rawgeti(L, index, i); boxes.push_back(read_aabb3f(L, -1, scale)); lua_pop(L, 1); @@ -487,8 +487,8 @@ bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname // Types mismatch. Log unique line. std::string backtrace = std::string("Invalid field ") + fieldname + - " (expected " + lua_typename(L, type) + " got " + - lua_typename(L, t) + ").\n" + script_get_backtrace(L); + " (expected " + lua_typename(L, type) + + " got " + lua_typename(L, t) + ").\n" + script_get_backtrace(L); u64 hash = murmur_hash_64_ua(backtrace.data(), backtrace.length(), 0xBADBABE); if (warned_msgs.find(hash) == warned_msgs.end()) { @@ -499,7 +499,8 @@ bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname return false; } -bool getstringfield(lua_State *L, int table, const char *fieldname, std::string &result) +bool getstringfield(lua_State *L, int table, + const char *fieldname, std::string &result) { lua_getfield(L, table, fieldname); bool got = false; @@ -516,7 +517,8 @@ bool getstringfield(lua_State *L, int table, const char *fieldname, std::string return got; } -bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result) +bool getfloatfield(lua_State *L, int table, + const char *fieldname, float &result) { lua_getfield(L, table, fieldname); bool got = false; @@ -529,12 +531,13 @@ bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result return got; } -bool getboolfield(lua_State *L, int table, const char *fieldname, bool &result) +bool getboolfield(lua_State *L, int table, + const char *fieldname, bool &result) { lua_getfield(L, table, fieldname); bool got = false; - if (check_field_or_nil(L, -1, LUA_TBOOLEAN, fieldname)) { + if (check_field_or_nil(L, -1, LUA_TBOOLEAN, fieldname)){ result = lua_toboolean(L, -1); got = true; } @@ -553,82 +556,93 @@ size_t getstringlistfield(lua_State *L, int table, const char *fieldname, return num_strings_read; } -std::string getstringfield_default(lua_State *L, int table, const char *fieldname, - const std::string &default_) +std::string getstringfield_default(lua_State *L, int table, + const char *fieldname, const std::string &default_) { std::string result = default_; getstringfield(L, table, fieldname, result); return result; } -int getintfield_default(lua_State *L, int table, const char *fieldname, int default_) +int getintfield_default(lua_State *L, int table, + const char *fieldname, int default_) { int result = default_; getintfield(L, table, fieldname, result); return result; } -float getfloatfield_default( - lua_State *L, int table, const char *fieldname, float default_) +float getfloatfield_default(lua_State *L, int table, + const char *fieldname, float default_) { float result = default_; getfloatfield(L, table, fieldname, result); return result; } -bool getboolfield_default(lua_State *L, int table, const char *fieldname, bool default_) +bool getboolfield_default(lua_State *L, int table, + const char *fieldname, bool default_) { bool result = default_; getboolfield(L, table, fieldname, result); return result; } -v3s16 getv3s16field_default( - lua_State *L, int table, const char *fieldname, v3s16 default_) +v3s16 getv3s16field_default(lua_State *L, int table, + const char *fieldname, v3s16 default_) { getv3intfield(L, table, fieldname, default_); return default_; } -void setstringfield( - lua_State *L, int table, const char *fieldname, const std::string &value) +void setstringfield(lua_State *L, int table, + const char *fieldname, const std::string &value) { lua_pushlstring(L, value.c_str(), value.length()); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } -void setintfield(lua_State *L, int table, const char *fieldname, int value) +void setintfield(lua_State *L, int table, + const char *fieldname, int value) { lua_pushinteger(L, value); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } -void setfloatfield(lua_State *L, int table, const char *fieldname, float value) +void setfloatfield(lua_State *L, int table, + const char *fieldname, float value) { lua_pushnumber(L, value); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } -void setboolfield(lua_State *L, int table, const char *fieldname, bool value) +void setboolfield(lua_State *L, int table, + const char *fieldname, bool value) { lua_pushboolean(L, value); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } + //// //// Array table slices //// -size_t write_array_slice_float(lua_State *L, int table_index, float *data, - v3u16 data_size, v3u16 slice_offset, v3u16 slice_size) +size_t write_array_slice_float( + lua_State *L, + int table_index, + float *data, + v3u16 data_size, + v3u16 slice_offset, + v3u16 slice_size) { v3u16 pmin, pmax(data_size); @@ -655,19 +669,25 @@ size_t write_array_slice_float(lua_State *L, int table_index, float *data, u32 elem_index = 1; for (u32 z = pmin.Z; z != pmax.Z; z++) - for (u32 y = pmin.Y; y != pmax.Y; y++) - for (u32 x = pmin.X; x != pmax.X; x++) { - u32 i = z * zstride + y * ystride + x; - lua_pushnumber(L, data[i]); - lua_rawseti(L, table_index, elem_index); - elem_index++; - } + for (u32 y = pmin.Y; y != pmax.Y; y++) + for (u32 x = pmin.X; x != pmax.X; x++) { + u32 i = z * zstride + y * ystride + x; + lua_pushnumber(L, data[i]); + lua_rawseti(L, table_index, elem_index); + elem_index++; + } return elem_index - 1; } -size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, v3u16 data_size, - v3u16 slice_offset, v3u16 slice_size) + +size_t write_array_slice_u16( + lua_State *L, + int table_index, + u16 *data, + v3u16 data_size, + v3u16 slice_offset, + v3u16 slice_size) { v3u16 pmin, pmax(data_size); @@ -694,13 +714,13 @@ size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, v3u16 dat u32 elem_index = 1; for (u32 z = pmin.Z; z != pmax.Z; z++) - for (u32 y = pmin.Y; y != pmax.Y; y++) - for (u32 x = pmin.X; x != pmax.X; x++) { - u32 i = z * zstride + y * ystride + x; - lua_pushinteger(L, data[i]); - lua_rawseti(L, table_index, elem_index); - elem_index++; - } + for (u32 y = pmin.Y; y != pmax.Y; y++) + for (u32 x = pmin.X; x != pmax.X; x++) { + u32 i = z * zstride + y * ystride + x; + lua_pushinteger(L, data[i]); + lua_rawseti(L, table_index, elem_index); + elem_index++; + } return elem_index - 1; } diff --git a/src/script/common/c_converter.h b/src/script/common/c_converter.h index 16d21db3b..a4a7079fd 100644 --- a/src/script/common/c_converter.h +++ b/src/script/common/c_converter.h @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + /******************************************************************************/ /******************************************************************************/ /* WARNING!!!! do NOT add this header in any include file or any code file */ @@ -35,21 +36,24 @@ extern "C" { #include } -std::string getstringfield_default(lua_State *L, int table, const char *fieldname, - const std::string &default_); -bool getboolfield_default(lua_State *L, int table, const char *fieldname, bool default_); -float getfloatfield_default( - lua_State *L, int table, const char *fieldname, float default_); -int getintfield_default(lua_State *L, int table, const char *fieldname, int default_); +std::string getstringfield_default(lua_State *L, int table, + const char *fieldname, const std::string &default_); +bool getboolfield_default(lua_State *L, int table, + const char *fieldname, bool default_); +float getfloatfield_default(lua_State *L, int table, + const char *fieldname, float default_); +int getintfield_default(lua_State *L, int table, + const char *fieldname, int default_); bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname); -template -bool getintfield(lua_State *L, int table, const char *fieldname, T &result) +template +bool getintfield(lua_State *L, int table, + const char *fieldname, T &result) { lua_getfield(L, table, fieldname); bool got = false; - if (check_field_or_nil(L, -1, LUA_TNUMBER, fieldname)) { + if (check_field_or_nil(L, -1, LUA_TNUMBER, fieldname)){ result = lua_tointeger(L, -1); got = true; } @@ -57,8 +61,9 @@ bool getintfield(lua_State *L, int table, const char *fieldname, T &result) return got; } -template -bool getv3intfield(lua_State *L, int index, const char *fieldname, T &result) +template +bool getv3intfield(lua_State *L, int index, + const char *fieldname, T &result) { lua_getfield(L, index, fieldname); bool got = false; @@ -71,54 +76,65 @@ bool getv3intfield(lua_State *L, int index, const char *fieldname, T &result) return got; } -v3s16 getv3s16field_default( - lua_State *L, int table, const char *fieldname, v3s16 default_); -bool getstringfield(lua_State *L, int table, const char *fieldname, std::string &result); -size_t getstringlistfield(lua_State *L, int table, const char *fieldname, - std::vector *result); -void read_groups(lua_State *L, int index, std::unordered_map &result); -bool getboolfield(lua_State *L, int table, const char *fieldname, bool &result); -bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result); - -void setstringfield( - lua_State *L, int table, const char *fieldname, const std::string &value); -void setintfield(lua_State *L, int table, const char *fieldname, int value); -void setfloatfield(lua_State *L, int table, const char *fieldname, float value); -void setboolfield(lua_State *L, int table, const char *fieldname, bool value); - -v3f checkFloatPos(lua_State *L, int index); -v3f check_v3f(lua_State *L, int index); -v3s16 check_v3s16(lua_State *L, int index); - -v3f read_v3f(lua_State *L, int index); -v2f read_v2f(lua_State *L, int index); -v2s16 read_v2s16(lua_State *L, int index); -v2s32 read_v2s32(lua_State *L, int index); -video::SColor read_ARGB8(lua_State *L, int index); -bool read_color(lua_State *L, int index, video::SColor *color); -bool is_color_table(lua_State *L, int index); - -aabb3f read_aabb3f(lua_State *L, int index, f32 scale); -v3s16 read_v3s16(lua_State *L, int index); -std::vector read_aabb3f_vector(lua_State *L, int index, f32 scale); -size_t read_stringlist(lua_State *L, int index, std::vector *result); - -void push_float_string(lua_State *L, float value); -void push_v3_float_string(lua_State *L, v3f p); -void push_v2_float_string(lua_State *L, v2f p); -void push_v2s16(lua_State *L, v2s16 p); -void push_v2s32(lua_State *L, v2s32 p); -void push_v3s16(lua_State *L, v3s16 p); -void push_aabb3f(lua_State *L, aabb3f box); -void push_ARGB8(lua_State *L, video::SColor color); -void pushFloatPos(lua_State *L, v3f p); -void push_v3f(lua_State *L, v3f p); -void push_v2f(lua_State *L, v2f p); - -void warn_if_field_exists(lua_State *L, int table, const char *fieldname, - const std::string &message); +v3s16 getv3s16field_default(lua_State *L, int table, + const char *fieldname, v3s16 default_); +bool getstringfield(lua_State *L, int table, + const char *fieldname, std::string &result); +size_t getstringlistfield(lua_State *L, int table, + const char *fieldname, + std::vector *result); +void read_groups(lua_State *L, int index, + std::unordered_map &result); +bool getboolfield(lua_State *L, int table, + const char *fieldname, bool &result); +bool getfloatfield(lua_State *L, int table, + const char *fieldname, float &result); + +void setstringfield(lua_State *L, int table, + const char *fieldname, const std::string &value); +void setintfield(lua_State *L, int table, + const char *fieldname, int value); +void setfloatfield(lua_State *L, int table, + const char *fieldname, float value); +void setboolfield(lua_State *L, int table, + const char *fieldname, bool value); + +v3f checkFloatPos (lua_State *L, int index); +v3f check_v3f (lua_State *L, int index); +v3s16 check_v3s16 (lua_State *L, int index); + +v3f read_v3f (lua_State *L, int index); +v2f read_v2f (lua_State *L, int index); +v2s16 read_v2s16 (lua_State *L, int index); +v2s32 read_v2s32 (lua_State *L, int index); +video::SColor read_ARGB8 (lua_State *L, int index); +bool read_color (lua_State *L, int index, + video::SColor *color); +bool is_color_table (lua_State *L, int index); + +aabb3f read_aabb3f (lua_State *L, int index, f32 scale); +v3s16 read_v3s16 (lua_State *L, int index); +std::vector read_aabb3f_vector (lua_State *L, int index, f32 scale); +size_t read_stringlist (lua_State *L, int index, + std::vector *result); + +void push_float_string (lua_State *L, float value); +void push_v3_float_string(lua_State *L, v3f p); +void push_v2_float_string(lua_State *L, v2f p); +void push_v2s16 (lua_State *L, v2s16 p); +void push_v2s32 (lua_State *L, v2s32 p); +void push_v3s16 (lua_State *L, v3s16 p); +void push_aabb3f (lua_State *L, aabb3f box); +void push_ARGB8 (lua_State *L, video::SColor color); +void pushFloatPos (lua_State *L, v3f p); +void push_v3f (lua_State *L, v3f p); +void push_v2f (lua_State *L, v2f p); + +void warn_if_field_exists(lua_State *L, int table, + const char *fieldname, + const std::string &message); size_t write_array_slice_float(lua_State *L, int table_index, float *data, - v3u16 data_size, v3u16 slice_offset, v3u16 slice_size); -size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, v3u16 data_size, - v3u16 slice_offset, v3u16 slice_size); + v3u16 data_size, v3u16 slice_offset, v3u16 slice_size); +size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, + v3u16 data_size, v3u16 slice_offset, v3u16 slice_size); diff --git a/src/script/common/c_internal.cpp b/src/script/common/c_internal.cpp index 19a874f63..6df1f8b7b 100644 --- a/src/script/common/c_internal.cpp +++ b/src/script/common/c_internal.cpp @@ -35,13 +35,13 @@ std::string script_get_backtrace(lua_State *L) int script_exception_wrapper(lua_State *L, lua_CFunction f) { try { - return f(L); // Call wrapped function and return result. - } catch (const char *s) { // Catch and convert exceptions. + return f(L); // Call wrapped function and return result. + } catch (const char *s) { // Catch and convert exceptions. lua_pushstring(L, s); } catch (std::exception &e) { lua_pushstring(L, e.what()); } - return lua_error(L); // Rethrow as a Lua error. + return lua_error(L); // Rethrow as a Lua error. } /* @@ -85,15 +85,15 @@ void script_error(lua_State *L, int pcall_result, const char *mod, const char *f err_descr = ""; char buf[256]; - porting::mt_snprintf(buf, sizeof(buf), - "%s error from mod '%s' in callback %s(): ", err_type, mod, fxn); + porting::mt_snprintf(buf, sizeof(buf), "%s error from mod '%s' in callback %s(): ", + err_type, mod, fxn); std::string err_msg(buf); err_msg += err_descr; if (pcall_result == LUA_ERRMEM) { - err_msg += "\nCurrent Lua memory usage: " + - itos(lua_gc(L, LUA_GCCOUNT, 0) >> 10) + " MB"; + err_msg += "\nCurrent Lua memory usage: " + + itos(lua_gc(L, LUA_GCCOUNT, 0) >> 10) + " MB"; } throw LuaError(err_msg); @@ -105,8 +105,8 @@ void script_error(lua_State *L, int pcall_result, const char *mod, const char *f // - runs the callbacks // - replaces the table and arguments with the return value, // computed depending on mode -void script_run_callbacks_f( - lua_State *L, int nargs, RunCallbacksMode mode, const char *fxn) +void script_run_callbacks_f(lua_State *L, int nargs, + RunCallbacksMode mode, const char *fxn) { FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments"); @@ -122,7 +122,7 @@ void script_run_callbacks_f( lua_insert(L, error_handler + 1); // Insert mode after table - lua_pushnumber(L, (int)mode); + lua_pushnumber(L, (int) mode); lua_insert(L, error_handler + 3); // Stack now looks like this: @@ -135,8 +135,8 @@ void script_run_callbacks_f( lua_remove(L, error_handler); } -static void script_log(lua_State *L, const std::string &message, std::ostream &log_to, - bool do_error, int stack_depth) +static void script_log(lua_State *L, const std::string &message, + std::ostream &log_to, bool do_error, int stack_depth) { lua_Debug ar; diff --git a/src/script/common/c_internal.h b/src/script/common/c_internal.h index 677194453..442546332 100644 --- a/src/script/common/c_internal.h +++ b/src/script/common/c_internal.h @@ -34,6 +34,7 @@ extern "C" { #include "config.h" #include "common/c_types.h" + /* Define our custom indices into the Lua registry table. @@ -44,15 +45,15 @@ extern "C" { so we can use numeric indices freely. */ #ifdef LUA_RIDX_LAST -#define CUSTOM_RIDX_BASE ((LUA_RIDX_LAST) + 1) +#define CUSTOM_RIDX_BASE ((LUA_RIDX_LAST)+1) #else #define CUSTOM_RIDX_BASE 1 #endif -#define CUSTOM_RIDX_SCRIPTAPI (CUSTOM_RIDX_BASE) -#define CUSTOM_RIDX_GLOBALS_BACKUP (CUSTOM_RIDX_BASE + 1) -#define CUSTOM_RIDX_CURRENT_MOD_NAME (CUSTOM_RIDX_BASE + 2) -#define CUSTOM_RIDX_BACKTRACE (CUSTOM_RIDX_BASE + 3) +#define CUSTOM_RIDX_SCRIPTAPI (CUSTOM_RIDX_BASE) +#define CUSTOM_RIDX_GLOBALS_BACKUP (CUSTOM_RIDX_BASE + 1) +#define CUSTOM_RIDX_CURRENT_MOD_NAME (CUSTOM_RIDX_BASE + 2) +#define CUSTOM_RIDX_BACKTRACE (CUSTOM_RIDX_BASE + 3) // Determine if CUSTOM_RIDX_SCRIPTAPI will hold a light or full userdata #if defined(__aarch64__) && USE_LUAJIT @@ -64,18 +65,17 @@ extern "C" { #endif // Pushes the error handler onto the stack and returns its index -#define PUSH_ERROR_HANDLER(L) \ +#define PUSH_ERROR_HANDLER(L) \ (lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L))) -#define PCALL_RESL(L, RES) \ - { \ - int result_ = (RES); \ - if (result_ != 0) { \ - script_error((L), result_, NULL, __FUNCTION__); \ - } \ - } +#define PCALL_RESL(L, RES) { \ + int result_ = (RES); \ + if (result_ != 0) { \ + script_error((L), result_, NULL, __FUNCTION__); \ + } \ +} -#define script_run_callbacks(L, nargs, mode) \ +#define script_run_callbacks(L, nargs, mode) \ script_run_callbacks_f((L), (nargs), (mode), __FUNCTION__) // What script_run_callbacks does with the return values of callbacks. @@ -111,7 +111,8 @@ enum RunCallbacksMode std::string script_get_backtrace(lua_State *L); int script_exception_wrapper(lua_State *L, lua_CFunction f); void script_error(lua_State *L, int pcall_result, const char *mod, const char *fxn); -void script_run_callbacks_f( - lua_State *L, int nargs, RunCallbacksMode mode, const char *fxn); +void script_run_callbacks_f(lua_State *L, int nargs, + RunCallbacksMode mode, const char *fxn); -void log_deprecated(lua_State *L, const std::string &message, int stack_depth = 1); +void log_deprecated(lua_State *L, const std::string &message, + int stack_depth=1); diff --git a/src/script/common/c_types.cpp b/src/script/common/c_types.cpp index 93bb5bd70..e832ff2ab 100644 --- a/src/script/common/c_types.cpp +++ b/src/script/common/c_types.cpp @@ -23,10 +23,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_internal.h" #include "itemdef.h" -struct EnumString es_ItemType[] = { + +struct EnumString es_ItemType[] = + { {ITEM_NONE, "none"}, {ITEM_NODE, "node"}, {ITEM_CRAFT, "craft"}, {ITEM_TOOL, "tool"}, {0, NULL}, -}; + }; diff --git a/src/script/common/c_types.h b/src/script/common/c_types.h index 860bfaaa8..86bfb0b6b 100644 --- a/src/script/common/c_types.h +++ b/src/script/common/c_types.h @@ -38,9 +38,10 @@ class StackUnroller private: lua_State *m_lua; int m_original_top; - public: - StackUnroller(lua_State *L) : m_lua(L), m_original_top(-1) + StackUnroller(lua_State *L): + m_lua(L), + m_original_top(-1) { m_original_top = lua_gettop(m_lua); // store stack height } @@ -56,4 +57,5 @@ class LuaError : public ModError LuaError(const std::string &s) : ModError(s) {} }; + extern EnumString es_ItemType[]; diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index d0e520ae9..5f1f9297e 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -42,6 +42,7 @@ AsyncEngine::~AsyncEngine() workerThread->stop(); } + // Wake up all threads for (std::vector::iterator it = workerThreads.begin(); it != workerThreads.end(); ++it) { @@ -76,16 +77,16 @@ void AsyncEngine::initialize(unsigned int numEngines) initDone = true; for (unsigned int i = 0; i < numEngines; i++) { - AsyncWorkerThread *toAdd = new AsyncWorkerThread( - this, std::string("AsyncWorker-") + itos(i)); + AsyncWorkerThread *toAdd = new AsyncWorkerThread(this, + std::string("AsyncWorker-") + itos(i)); workerThreads.push_back(toAdd); toAdd->start(); } } /******************************************************************************/ -unsigned int AsyncEngine::queueAsyncJob( - const std::string &func, const std::string ¶ms) +unsigned int AsyncEngine::queueAsyncJob(const std::string &func, + const std::string ¶ms) { jobQueueMutex.lock(); LuaJobInfo toAdd; @@ -157,8 +158,7 @@ void AsyncEngine::step(lua_State *L) } /******************************************************************************/ -void AsyncEngine::pushFinishedJobs(lua_State *L) -{ +void AsyncEngine::pushFinishedJobs(lua_State* L) { // Result Table MutexAutoLock l(resultQueueMutex); @@ -170,7 +170,7 @@ void AsyncEngine::pushFinishedJobs(lua_State *L) LuaJobInfo jobDone = resultQueue.front(); resultQueue.pop_front(); - lua_createtable(L, 0, 2); // Pre-allocate space for two map fields + lua_createtable(L, 0, 2); // Pre-allocate space for two map fields int top_lvl2 = lua_gettop(L); lua_pushstring(L, "jobid"); @@ -179,7 +179,7 @@ void AsyncEngine::pushFinishedJobs(lua_State *L) lua_pushstring(L, "retval"); lua_pushlstring(L, jobDone.serializedResult.data(), - jobDone.serializedResult.size()); + jobDone.serializedResult.size()); lua_settable(L, top_lvl2); lua_rawseti(L, top, index++); @@ -187,7 +187,7 @@ void AsyncEngine::pushFinishedJobs(lua_State *L) } /******************************************************************************/ -void AsyncEngine::prepareEnvironment(lua_State *L, int top) +void AsyncEngine::prepareEnvironment(lua_State* L, int top) { for (StateInitializer &stateInitializer : stateInitializers) { stateInitializer(L, top); @@ -195,10 +195,11 @@ void AsyncEngine::prepareEnvironment(lua_State *L, int top) } /******************************************************************************/ -AsyncWorkerThread::AsyncWorkerThread( - AsyncEngine *jobDispatcher, const std::string &name) : - Thread(name), - ScriptApiBase(ScriptingType::Async), jobDispatcher(jobDispatcher) +AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher, + const std::string &name) : + Thread(name), + ScriptApiBase(ScriptingType::Async), + jobDispatcher(jobDispatcher) { lua_State *L = getStack(); @@ -220,7 +221,7 @@ AsyncWorkerThread::~AsyncWorkerThread() } /******************************************************************************/ -void *AsyncWorkerThread::run() +void* AsyncWorkerThread::run() { lua_State *L = getStack(); @@ -228,8 +229,8 @@ void *AsyncWorkerThread::run() try { loadScript(script); } catch (const ModError &e) { - errorstream << "Execution of async base environment failed: " << e.what() - << std::endl; + errorstream << "Execution of async base environment failed: " + << e.what() << std::endl; FATAL_ERROR("Execution of async base environment failed"); } @@ -257,9 +258,11 @@ void *AsyncWorkerThread::run() luaL_checktype(L, -1, LUA_TFUNCTION); // Call it - lua_pushlstring(L, toProcess.serializedFunction.data(), + lua_pushlstring(L, + toProcess.serializedFunction.data(), toProcess.serializedFunction.size()); - lua_pushlstring(L, toProcess.serializedParams.data(), + lua_pushlstring(L, + toProcess.serializedParams.data(), toProcess.serializedParams.size()); int result = lua_pcall(L, 2, 1, error_handler); @@ -273,13 +276,14 @@ void *AsyncWorkerThread::run() toProcess.serializedResult = std::string(retval, length); } - lua_pop(L, 1); // Pop retval + lua_pop(L, 1); // Pop retval // Put job result jobDispatcher->putJobResult(toProcess); } - lua_pop(L, 2); // Pop core and error handler + lua_pop(L, 2); // Pop core and error handler return 0; } + diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index 1dc4145ba..b1f4bf45f 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -31,6 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Forward declarations class AsyncEngine; + // Declarations // Data required to queue a job @@ -51,10 +52,9 @@ struct LuaJobInfo }; // Asynchronous working environment -class AsyncWorkerThread : public Thread, public ScriptApiBase -{ +class AsyncWorkerThread : public Thread, public ScriptApiBase { public: - AsyncWorkerThread(AsyncEngine *jobDispatcher, const std::string &name); + AsyncWorkerThread(AsyncEngine* jobDispatcher, const std::string &name); virtual ~AsyncWorkerThread(); void *run(); @@ -64,11 +64,9 @@ class AsyncWorkerThread : public Thread, public ScriptApiBase }; // Asynchornous thread and job management -class AsyncEngine -{ +class AsyncEngine { friend class AsyncWorkerThread; typedef void (*StateInitializer)(lua_State *L, int top); - public: AsyncEngine() = default; ~AsyncEngine(); @@ -127,7 +125,7 @@ class AsyncEngine * @param L Lua stack to initialize * @param top Stack position */ - void prepareEnvironment(lua_State *L, int top); + void prepareEnvironment(lua_State* L, int top); private: // Variable locking the engine against further modification @@ -151,7 +149,7 @@ class AsyncEngine std::deque resultQueue; // List of current worker threads - std::vector workerThreads; + std::vector workerThreads; // Counter semaphore for job dispatching Semaphore jobQueueCounter; diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index 72774f6ca..1d62d8b65 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -32,10 +32,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #endif + extern "C" { #include "lualib.h" #if USE_LUAJIT -#include "luajit.h" + #include "luajit.h" #endif } @@ -44,13 +45,14 @@ extern "C" { #include "script/common/c_content.h" #include + class ModNameStorer { private: lua_State *L; - public: - ModNameStorer(lua_State *L_, const std::string &mod_name) : L(L_) + ModNameStorer(lua_State *L_, const std::string &mod_name): + L(L_) { // Store current mod name in registry lua_pushstring(L, mod_name.c_str()); @@ -64,11 +66,13 @@ class ModNameStorer } }; + /* ScriptApiBase */ -ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) +ScriptApiBase::ScriptApiBase(ScriptingType type): + m_type(type) { #ifdef SCRIPTAPI_LOCK_DEBUG m_lock_recursion_count = 0; @@ -82,7 +86,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) /*if (m_type == ScriptingType::Client) clientOpenLibs(m_luastack); else*/ - luaL_openlibs(m_luastack); + luaL_openlibs(m_luastack); // Make the ScriptApiBase* accessible to ModApiBase #if INDIRECT_SCRIPTAPI_RIDX @@ -101,7 +105,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) // If we are using LuaJIT add a C++ wrapper function to catch // exceptions thrown in Lua -> C++ calls #if USE_LUAJIT - lua_pushlightuserdata(m_luastack, (void *)script_exception_wrapper); + lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper); luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); lua_pop(m_luastack, 1); #endif @@ -132,7 +136,7 @@ int ScriptApiBase::luaPanic(lua_State *L) { std::ostringstream oss; oss << "LUA PANIC: unprotected error in call to Lua API (" - << readParam(L, -1) << ")"; + << readParam(L, -1) << ")"; FATAL_ERROR(oss.str().c_str()); // NOTREACHED return 0; @@ -141,25 +145,26 @@ int ScriptApiBase::luaPanic(lua_State *L) void ScriptApiBase::clientOpenLibs(lua_State *L) { static const std::vector> m_libs = { - {"", luaopen_base}, - {LUA_TABLIBNAME, luaopen_table}, - {LUA_OSLIBNAME, luaopen_os}, - {LUA_STRLIBNAME, luaopen_string}, - {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, + { "", luaopen_base }, + { LUA_TABLIBNAME, luaopen_table }, + { LUA_OSLIBNAME, luaopen_os }, + { LUA_STRLIBNAME, luaopen_string }, + { LUA_MATHLIBNAME, luaopen_math }, + { LUA_DBLIBNAME, luaopen_debug }, #if USE_LUAJIT - {LUA_JITLIBNAME, luaopen_jit}, + { LUA_JITLIBNAME, luaopen_jit }, #endif }; for (const std::pair &lib : m_libs) { - lua_pushcfunction(L, lib.second); - lua_pushstring(L, lib.first.c_str()); - lua_call(L, 1, 0); + lua_pushcfunction(L, lib.second); + lua_pushstring(L, lib.first.c_str()); + lua_call(L, 1, 0); } } -void ScriptApiBase::loadMod(const std::string &script_path, const std::string &mod_name) +void ScriptApiBase::loadMod(const std::string &script_path, + const std::string &mod_name) { ModNameStorer mod_name_storer(getStack(), mod_name); @@ -186,8 +191,8 @@ void ScriptApiBase::loadScript(const std::string &script_path) if (!error_msg) error_msg = "(error object is not a string)"; lua_pop(L, 2); // Pop error message and error handler - throw ModError("Failed to load and run script from " + script_path + - ":\n" + error_msg); + throw ModError("Failed to load and run script from " + + script_path + ":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } @@ -220,8 +225,8 @@ void ScriptApiBase::loadModFromMemory(const std::string &mod_name) if (!error_msg) error_msg = "(error object is not a string)"; lua_pop(L, 2); // Pop error message and error handler - throw ModError("Failed to load and run mod \"" + mod_name + "\":\n" + - error_msg); + throw ModError("Failed to load and run mod \"" + + mod_name + "\":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } @@ -235,13 +240,14 @@ void ScriptApiBase::loadModFromMemory(const std::string &mod_name) // computed depending on mode // This function must only be called with scriptlock held (i.e. inside of a // code block with SCRIPTAPI_PRECHECKHEADER declared) -void ScriptApiBase::runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn) +void ScriptApiBase::runCallbacksRaw(int nargs, + RunCallbacksMode mode, const char *fxn) { #ifndef SERVER // Hard fail for bad guarded callbacks // Only run callbacks when the scripting enviroment is loaded - FATAL_ERROR_IF(m_type == ScriptingType::Client && !getClient()->modsLoaded(), - fxn); + FATAL_ERROR_IF(m_type == ScriptingType::Client && + !getClient()->modsLoaded(), fxn); #endif #ifdef SCRIPTAPI_LOCK_DEBUG @@ -294,25 +300,24 @@ void ScriptApiBase::scriptError(int result, const char *fxn) void ScriptApiBase::stackDump(std::ostream &o) { int top = lua_gettop(m_luastack); - for (int i = 1; i <= top; i++) { /* repeat for each level */ + for (int i = 1; i <= top; i++) { /* repeat for each level */ int t = lua_type(m_luastack, i); switch (t) { - case LUA_TSTRING: /* strings */ - o << "\"" << readParam(m_luastack, i) << "\""; - break; - case LUA_TBOOLEAN: /* booleans */ - o << (readParam(m_luastack, i) ? "true" : "false"); - break; - case LUA_TNUMBER: /* numbers */ { - char buf[10]; - porting::mt_snprintf(buf, sizeof(buf), "%lf", - lua_tonumber(m_luastack, i)); - o << buf; - break; - } - default: /* other values */ - o << lua_typename(m_luastack, t); - break; + case LUA_TSTRING: /* strings */ + o << "\"" << readParam(m_luastack, i) << "\""; + break; + case LUA_TBOOLEAN: /* booleans */ + o << (readParam(m_luastack, i) ? "true" : "false"); + break; + case LUA_TNUMBER: /* numbers */ { + char buf[10]; + porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i)); + o << buf; + break; + } + default: /* other values */ + o << lua_typename(m_luastack, t); + break; } o << " "; } @@ -329,10 +334,9 @@ void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) #ifdef SCRIPTAPI_DEBUG lua_State *L = getStack(); - m_last_run_mod = lua_istable(L, index) ? getstringfield_default(L, index, - "mod_origin", "") - : ""; - // printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str()); + m_last_run_mod = lua_istable(L, index) ? + getstringfield_default(L, index, "mod_origin", "") : ""; + //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str()); #endif } @@ -353,7 +357,7 @@ void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER - // infostream<<"scriptapi_add_object_reference: id="<getId()<getId() == 0) { ObjectRef::create(L, cobj); @@ -404,13 +409,12 @@ void ScriptApiBase::objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj) push_objectRef(L, cobj->getId()); if (cobj->isGone()) warningstream << "ScriptApiBase::objectrefGetOrCreate(): " - << "Pushing ObjectRef to removed/deactivated object" - << ", this is probably a bug." << std::endl; + << "Pushing ObjectRef to removed/deactivated object" + << ", this is probably a bug." << std::endl; } } -void ScriptApiBase::pushPlayerHPChangeReason( - lua_State *L, const PlayerHPChangeReason &reason) +void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason) { if (reason.hasLuaReference()) lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference); @@ -438,12 +442,12 @@ void ScriptApiBase::pushPlayerHPChangeReason( } } -Server *ScriptApiBase::getServer() +Server* ScriptApiBase::getServer() { return dynamic_cast(m_gamedef); } #ifndef SERVER -Client *ScriptApiBase::getClient() +Client* ScriptApiBase::getClient() { return dynamic_cast(m_gamedef); } diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index d2081ad5c..36331ad37 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -45,20 +45,20 @@ extern "C" { // use that name to bypass security! #define BUILTIN_MOD_NAME "*builtin*" -#define PCALL_RES(RES) \ - { \ - int result_ = (RES); \ - if (result_ != 0) { \ - scriptError(result_, __FUNCTION__); \ - } \ - } +#define PCALL_RES(RES) { \ + int result_ = (RES); \ + if (result_ != 0) { \ + scriptError(result_, __FUNCTION__); \ + } \ +} -#define runCallbacks(nargs, mode) runCallbacksRaw((nargs), (mode), __FUNCTION__) +#define runCallbacks(nargs, mode) \ + runCallbacksRaw((nargs), (mode), __FUNCTION__) -#define setOriginFromTable(index) setOriginFromTableRaw(index, __FUNCTION__) +#define setOriginFromTable(index) \ + setOriginFromTableRaw(index, __FUNCTION__) -enum class ScriptingType : u8 -{ +enum class ScriptingType: u8 { Async, Client, MainMenu, @@ -76,13 +76,14 @@ class GUIEngine; class ServerActiveObject; struct PlayerHPChangeReason; -class ScriptApiBase : protected LuaHelper -{ +class ScriptApiBase : protected LuaHelper { public: ScriptApiBase(ScriptingType type); - // fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually - // inherit from this one. - ScriptApiBase() { FATAL_ERROR("ScriptApiBase created without ScriptingType!"); } + // fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually inherit from this one. + ScriptApiBase() + { + FATAL_ERROR("ScriptApiBase created without ScriptingType!"); + } virtual ~ScriptApiBase(); DISABLE_CLASS_COPY(ScriptApiBase); @@ -94,17 +95,18 @@ class ScriptApiBase : protected LuaHelper void loadModFromMemory(const std::string &mod_name); #endif - void runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn); + void runCallbacksRaw(int nargs, + RunCallbacksMode mode, const char *fxn); /* object */ void addObjectReference(ServerActiveObject *cobj); void removeObjectReference(ServerActiveObject *cobj); IGameDef *getGameDef() { return m_gamedef; } - Server *getServer(); + Server* getServer(); ScriptingType getType() { return m_type; } #ifndef SERVER - Client *getClient(); + Client* getClient(); Game *getGame() { return m_game; } #endif @@ -124,49 +126,50 @@ class ScriptApiBase : protected LuaHelper friend class ModApiEnvMod; friend class LuaVoxelManip; - lua_State *getStack() { return m_luastack; } + lua_State* getStack() + { return m_luastack; } void realityCheck(); void scriptError(int result, const char *fxn); void stackDump(std::ostream &o); - void setGameDef(IGameDef *gamedef) { m_gamedef = gamedef; } + void setGameDef(IGameDef* gamedef) { m_gamedef = gamedef; } #ifndef SERVER void setGame(Game *game) { m_game = game; } #endif - Environment *getEnv() { return m_environment; } - void setEnv(Environment *env) { m_environment = env; } + Environment* getEnv() { return m_environment; } + void setEnv(Environment* env) { m_environment = env; } #ifndef SERVER - GUIEngine *getGuiEngine() { return m_guiengine; } - void setGuiEngine(GUIEngine *guiengine) { m_guiengine = guiengine; } + GUIEngine* getGuiEngine() { return m_guiengine; } + void setGuiEngine(GUIEngine* guiengine) { m_guiengine = guiengine; } #endif void objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj); - void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason); + void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason& reason); std::recursive_mutex m_luastackmutex; - std::string m_last_run_mod; - bool m_secure = false; + std::string m_last_run_mod; + bool m_secure = false; #ifdef SCRIPTAPI_LOCK_DEBUG - int m_lock_recursion_count{}; + int m_lock_recursion_count{}; std::thread::id m_owning_thread; #endif private: static int luaPanic(lua_State *L); - lua_State *m_luastack = nullptr; + lua_State *m_luastack = nullptr; - IGameDef *m_gamedef = nullptr; + IGameDef *m_gamedef = nullptr; #ifndef SERVER - Game *m_game = nullptr; + Game *m_game = nullptr; #endif - Environment *m_environment = nullptr; + Environment *m_environment = nullptr; #ifndef SERVER - GUIEngine *m_guiengine = nullptr; + GUIEngine *m_guiengine = nullptr; #endif - ScriptingType m_type; + ScriptingType m_type; }; diff --git a/src/script/cpp_api/s_client.cpp b/src/script/cpp_api/s_client.cpp index e6c9eea1a..dd9019d4d 100644 --- a/src/script/cpp_api/s_client.cpp +++ b/src/script/cpp_api/s_client.cpp @@ -120,13 +120,13 @@ void ScriptApiClient::environment_step(float dtime) try { runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getClient()->setFatalError(std::string("Client environment_step: ") + - e.what() + "\n" + script_get_backtrace(L)); + getClient()->setFatalError(std::string("Client environment_step: ") + e.what() + "\n" + + script_get_backtrace(L)); } } -void ScriptApiClient::on_formspec_input( - const std::string &formname, const StringMap &fields) +void ScriptApiClient::on_formspec_input(const std::string &formname, + const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -187,8 +187,7 @@ bool ScriptApiClient::on_punchnode(v3s16 p, MapNode node) return readParam(L, -1); } -bool ScriptApiClient::on_placenode( - const PointedThing &pointed, const ItemDefinition &item) +bool ScriptApiClient::on_placenode(const PointedThing &pointed, const ItemDefinition &item) { SCRIPTAPI_PRECHECKHEADER @@ -238,11 +237,11 @@ bool ScriptApiClient::on_inventory_open(Inventory *inventory) void ScriptApiClient::open_enderchest() { SCRIPTAPI_PRECHECKHEADER - + PUSH_ERROR_HANDLER(L); int error_handler = lua_gettop(L) - 1; lua_insert(L, error_handler); - + lua_getglobal(L, "core"); lua_getfield(L, -1, "open_enderchest"); if (lua_isfunction(L, -1)) diff --git a/src/script/cpp_api/s_entity.cpp b/src/script/cpp_api/s_entity.cpp index baf455e1b..ea9320051 100644 --- a/src/script/cpp_api/s_entity.cpp +++ b/src/script/cpp_api/s_entity.cpp @@ -29,8 +29,8 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) { SCRIPTAPI_PRECHECKHEADER - verbosestream << "scriptapi_luaentity_add: id=" << id << " name=\"" << name - << "\"" << std::endl; + verbosestream<<"scriptapi_luaentity_add: id="<setAsyncFatalError(std::string("environment_Step: ") + - e.what() + "\n" + - script_get_backtrace(L)); + getServer()->setAsyncFatalError( + std::string("environment_Step: ") + e.what() + "\n" + + script_get_backtrace(L)); } } @@ -71,13 +72,14 @@ void ScriptApiEnv::player_event(ServerActiveObject *player, const std::string &t lua_getfield(L, -1, "registered_playerevents"); // Call callbacks - objectrefGetOrCreate(L, player); // player - lua_pushstring(L, type.c_str()); // event type + objectrefGetOrCreate(L, player); // player + lua_pushstring(L,type.c_str()); // event type try { runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getServer()->setAsyncFatalError(std::string("player_event: ") + e.what() + - "\n" + script_get_backtrace(L)); + getServer()->setAsyncFatalError( + std::string("player_event: ") + e.what() + "\n" + + script_get_backtrace(L) ); } } @@ -114,8 +116,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) while (lua_next(L, table)) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); - trigger_contents.emplace_back( - readParam(L, -1)); + trigger_contents.emplace_back(readParam(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -132,8 +133,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) while (lua_next(L, table)) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); - required_neighbors.emplace_back( - readParam(L, -1)); + required_neighbors.emplace_back(readParam(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -156,7 +156,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) lua_pop(L, 1); LuaABM *abm = new LuaABM(L, id, trigger_contents, required_neighbors, - trigger_interval, trigger_chance, simple_catch_up); + trigger_interval, trigger_chance, simple_catch_up); env->addActiveBlockModifier(abm); @@ -201,15 +201,15 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) std::string name; getstringfield(L, current_lbm, "name", name); - bool run_at_every_load = getboolfield_default( - L, current_lbm, "run_at_every_load", false); + bool run_at_every_load = getboolfield_default(L, current_lbm, + "run_at_every_load", false); lua_getfield(L, current_lbm, "action"); luaL_checktype(L, current_lbm + 1, LUA_TFUNCTION); lua_pop(L, 1); - LuaLBM *lbm = new LuaLBM( - L, id, trigger_contents, name, run_at_every_load); + LuaLBM *lbm = new LuaLBM(L, id, trigger_contents, name, + run_at_every_load); env->addLoadingBlockModifierDef(lbm); @@ -220,7 +220,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) } void ScriptApiEnv::on_emerge_area_completion( - v3s16 blockpos, int action, ScriptCallbackState *state) + v3s16 blockpos, int action, ScriptCallbackState *state) { Server *server = getServer(); @@ -249,8 +249,9 @@ void ScriptApiEnv::on_emerge_area_completion( try { PCALL_RES(lua_pcall(L, 4, 0, error_handler)); } catch (LuaError &e) { - server->setAsyncFatalError(std::string("on_emerge_area_completion: ") + - e.what() + "\n" + script_get_backtrace(L)); + server->setAsyncFatalError( + std::string("on_emerge_area_completion: ") + e.what() + "\n" + + script_get_backtrace(L)); } lua_pop(L, 1); // Pop error handler diff --git a/src/script/cpp_api/s_env.h b/src/script/cpp_api/s_env.h index 1848c7a94..232a08aaf 100644 --- a/src/script/cpp_api/s_env.h +++ b/src/script/cpp_api/s_env.h @@ -38,8 +38,8 @@ class ScriptApiEnv : virtual public ScriptApiBase void player_event(ServerActiveObject *player, const std::string &type); // Called after emerge of a block queued from core.emerge_area() - void on_emerge_area_completion( - v3s16 blockpos, int action, ScriptCallbackState *state); + void on_emerge_area_completion(v3s16 blockpos, int action, + ScriptCallbackState *state); void initializeEnvironment(ServerEnvironment *env); }; diff --git a/src/script/cpp_api/s_internal.h b/src/script/cpp_api/s_internal.h index 858b827de..83b3b9d27 100644 --- a/src/script/cpp_api/s_internal.h +++ b/src/script/cpp_api/s_internal.h @@ -34,14 +34,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifdef SCRIPTAPI_LOCK_DEBUG #include -class LockChecker -{ +class LockChecker { public: LockChecker(int *recursion_counter, std::thread::id *owning_thread) { m_lock_recursion_counter = recursion_counter; - m_owning_thread = owning_thread; - m_original_level = *recursion_counter; + m_owning_thread = owning_thread; + m_original_level = *recursion_counter; if (*m_lock_recursion_counter > 0) { assert(*m_owning_thread == std::this_thread::get_id()); @@ -68,18 +67,19 @@ class LockChecker std::thread::id *m_owning_thread; }; -#define SCRIPTAPI_LOCK_CHECK \ - LockChecker scriptlock_checker( \ - &this->m_lock_recursion_count, &this->m_owning_thread) +#define SCRIPTAPI_LOCK_CHECK \ + LockChecker scriptlock_checker( \ + &this->m_lock_recursion_count, \ + &this->m_owning_thread) #else -#define SCRIPTAPI_LOCK_CHECK while (0) + #define SCRIPTAPI_LOCK_CHECK while(0) #endif -#define SCRIPTAPI_PRECHECKHEADER \ - RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \ - SCRIPTAPI_LOCK_CHECK; \ - realityCheck(); \ - lua_State *L = getStack(); \ - assert(lua_checkstack(L, 20)); \ - StackUnroller stack_unroller(L); +#define SCRIPTAPI_PRECHECKHEADER \ + RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \ + SCRIPTAPI_LOCK_CHECK; \ + realityCheck(); \ + lua_State *L = getStack(); \ + assert(lua_checkstack(L, 20)); \ + StackUnroller stack_unroller(L); diff --git a/src/script/cpp_api/s_inventory.cpp b/src/script/cpp_api/s_inventory.cpp index e4d3f990d..e9c09f72e 100644 --- a/src/script/cpp_api/s_inventory.cpp +++ b/src/script/cpp_api/s_inventory.cpp @@ -26,7 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., // Return number of accepted items to be moved int ScriptApiDetached::detached_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -40,15 +41,14 @@ int ScriptApiDetached::detached_inventory_AllowMove( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 1, error_handler)); - if (!lua_isnumber(L, -1)) - throw LuaError("allow_move should return a number. name=" + - ma.from_inv.name); + if(!lua_isnumber(L, -1)) + throw LuaError("allow_move should return a number. name=" + ma.from_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -56,7 +56,8 @@ int ScriptApiDetached::detached_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiDetached::detached_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -67,15 +68,14 @@ int ScriptApiDetached::detached_inventory_AllowPut( return stack.count; // All will be accepted // Call function(inv, listname, index, stack, player) - InvRef::create(L, ma.to_inv); // inv + InvRef::create(L, ma.to_inv); // inv lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) - throw LuaError("allow_put should return a number. name=" + - ma.to_inv.name); + throw LuaError("allow_put should return a number. name=" + ma.to_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -83,7 +83,8 @@ int ScriptApiDetached::detached_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiDetached::detached_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -94,15 +95,14 @@ int ScriptApiDetached::detached_inventory_AllowTake( return stack.count; // All will be accepted // Call function(inv, listname, index, stack, player) - InvRef::create(L, ma.from_inv); // inv + InvRef::create(L, ma.from_inv); // inv lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) - throw LuaError("allow_take should return a number. name=" + - ma.from_inv.name); + throw LuaError("allow_take should return a number. name=" + ma.from_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -110,7 +110,8 @@ int ScriptApiDetached::detached_inventory_AllowTake( // Report moved items void ScriptApiDetached::detached_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -124,18 +125,19 @@ void ScriptApiDetached::detached_inventory_OnMove( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report put items void ScriptApiDetached::detached_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -150,15 +152,16 @@ void ScriptApiDetached::detached_inventory_OnPut( InvRef::create(L, ma.to_inv); lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report taken items void ScriptApiDetached::detached_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -172,11 +175,11 @@ void ScriptApiDetached::detached_inventory_OnTake( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Retrieves core.detached_inventories[name][callbackname] @@ -196,8 +199,7 @@ bool ScriptApiDetached::getDetachedInventoryCallback( lua_remove(L, -2); // Should be a table if (lua_type(L, -1) != LUA_TTABLE) { - errorstream << "Detached inventory \"" << name << "\" not defined" - << std::endl; + errorstream<<"Detached inventory \""<(L, -1, false); } -void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, - const StringMap &fields, ServerActiveObject *sender) +void ScriptApiNode::node_on_receive_fields(v3s16 p, + const std::string &formname, + const StringMap &fields, + ServerActiveObject *sender) { SCRIPTAPI_PRECHECKHEADER @@ -246,9 +255,9 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, return; // Call function - push_v3s16(L, p); // pos + push_v3s16(L, p); // pos lua_pushstring(L, formname.c_str()); // formname - lua_newtable(L); // fields + lua_newtable(L); // fields StringMap::const_iterator it; for (it = fields.begin(); it != fields.end(); ++it) { const std::string &name = it->first; @@ -257,7 +266,7 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, lua_pushlstring(L, value.c_str(), value.size()); lua_settable(L, -3); } - objectrefGetOrCreate(L, sender); // player + objectrefGetOrCreate(L, sender); // player PCALL_RES(lua_pcall(L, 4, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } diff --git a/src/script/cpp_api/s_node.h b/src/script/cpp_api/s_node.h index 8f4e41479..81b44f0f0 100644 --- a/src/script/cpp_api/s_node.h +++ b/src/script/cpp_api/s_node.h @@ -27,23 +27,27 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MapNode; class ServerActiveObject; -class ScriptApiNode : virtual public ScriptApiBase, public ScriptApiNodemeta +class ScriptApiNode + : virtual public ScriptApiBase, + public ScriptApiNodemeta { public: ScriptApiNode() = default; virtual ~ScriptApiNode() = default; - bool node_on_punch(v3s16 p, MapNode node, ServerActiveObject *puncher, - const PointedThing &pointed); - bool node_on_dig(v3s16 p, MapNode node, ServerActiveObject *digger); + bool node_on_punch(v3s16 p, MapNode node, + ServerActiveObject *puncher, const PointedThing &pointed); + bool node_on_dig(v3s16 p, MapNode node, + ServerActiveObject *digger); void node_on_construct(v3s16 p, MapNode node); void node_on_destruct(v3s16 p, MapNode node); bool node_on_flood(v3s16 p, MapNode node, MapNode newnode); void node_after_destruct(v3s16 p, MapNode node); bool node_on_timer(v3s16 p, MapNode node, f32 dtime); - void node_on_receive_fields(v3s16 p, const std::string &formname, - const StringMap &fields, ServerActiveObject *sender); - + void node_on_receive_fields(v3s16 p, + const std::string &formname, + const StringMap &fields, + ServerActiveObject *sender); public: static struct EnumString es_DrawType[]; static struct EnumString es_ContentParamType[]; diff --git a/src/script/cpp_api/s_nodemeta.cpp b/src/script/cpp_api/s_nodemeta.cpp index b7bd5f7c8..c081e9fc4 100644 --- a/src/script/cpp_api/s_nodemeta.cpp +++ b/src/script/cpp_api/s_nodemeta.cpp @@ -28,7 +28,8 @@ with this program; if not, write to the Free Software Foundation, Inc., // Return number of accepted items to be moved int ScriptApiNodemeta::nodemeta_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -43,23 +44,21 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowMove( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", - &ma.to_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", &ma.to_inv.p)) return count; // function(pos, from_list, from_index, to_list, to_index, count, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 1, error_handler)); if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_move should" - " return a number, guilty node: " + - nodename); + " return a number, guilty node: " + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -67,7 +66,8 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiNodemeta::nodemeta_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -82,21 +82,19 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowPut( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", - &ma.to_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", &ma.to_inv.p)) return stack.count; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); - if (!lua_isnumber(L, -1)) + if(!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_put should" - " return a number, guilty node: " + - nodename); + " return a number, guilty node: " + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -104,7 +102,8 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiNodemeta::nodemeta_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -119,21 +118,19 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowTake( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", - &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", &ma.from_inv.p)) return stack.count; // Call function(pos, listname, index, count, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_take should" - " return a number, guilty node: " + - nodename); + " return a number, guilty node: " + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -141,7 +138,8 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowTake( // Report moved items void ScriptApiNodemeta::nodemeta_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -156,25 +154,25 @@ void ScriptApiNodemeta::nodemeta_inventory_OnMove( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", - &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", &ma.from_inv.p)) return; // function(pos, from_list, from_index, to_list, to_index, count, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report put items void ScriptApiNodemeta::nodemeta_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -193,18 +191,19 @@ void ScriptApiNodemeta::nodemeta_inventory_OnPut( return; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report taken items void ScriptApiNodemeta::nodemeta_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -219,16 +218,15 @@ void ScriptApiNodemeta::nodemeta_inventory_OnTake( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", - &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", &ma.from_inv.p)) return; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } diff --git a/src/script/cpp_api/s_nodemeta.h b/src/script/cpp_api/s_nodemeta.h index 609898a30..8c7cdd93e 100644 --- a/src/script/cpp_api/s_nodemeta.h +++ b/src/script/cpp_api/s_nodemeta.h @@ -26,7 +26,9 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MoveAction; struct ItemStack; -class ScriptApiNodemeta : virtual public ScriptApiBase, public ScriptApiItem +class ScriptApiNodemeta + : virtual public ScriptApiBase, + public ScriptApiItem { public: ScriptApiNodemeta() = default; @@ -34,22 +36,28 @@ class ScriptApiNodemeta : virtual public ScriptApiBase, public ScriptApiItem // Return number of accepted items to be moved int nodemeta_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Return number of accepted items to be put - int nodemeta_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, + int nodemeta_inventory_AllowPut( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Return number of accepted items to be taken - int nodemeta_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, + int nodemeta_inventory_AllowTake( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report moved items void nodemeta_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Report put items - void nodemeta_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, + void nodemeta_inventory_OnPut( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report taken items - void nodemeta_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, + void nodemeta_inventory_OnTake( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); - private: + }; diff --git a/src/script/cpp_api/s_player.cpp b/src/script/cpp_api/s_player.cpp index c9ab81db9..712120c61 100644 --- a/src/script/cpp_api/s_player.cpp +++ b/src/script/cpp_api/s_player.cpp @@ -39,8 +39,7 @@ void ScriptApiPlayer::on_newplayer(ServerActiveObject *player) runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_dieplayer( - ServerActiveObject *player, const PlayerHPChangeReason &reason) +void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player, const PlayerHPChangeReason &reason) { SCRIPTAPI_PRECHECKHEADER @@ -57,8 +56,11 @@ void ScriptApiPlayer::on_dieplayer( } bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, - ServerActiveObject *hitter, float time_from_last_punch, - const ToolCapabilities *toolcap, v3f dir, s16 damage) + ServerActiveObject *hitter, + float time_from_last_punch, + const ToolCapabilities *toolcap, + v3f dir, + s16 damage) { SCRIPTAPI_PRECHECKHEADER // Get core.registered_on_punchplayers @@ -75,8 +77,8 @@ bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, return readParam(L, -1); } -s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, s32 hp_change, - const PlayerHPChangeReason &reason) +s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, + s32 hp_change, const PlayerHPChangeReason &reason) { SCRIPTAPI_PRECHECKHEADER @@ -113,7 +115,9 @@ bool ScriptApiPlayer::on_respawnplayer(ServerActiveObject *player) } bool ScriptApiPlayer::on_prejoinplayer( - const std::string &name, const std::string &ip, std::string *reason) + const std::string &name, + const std::string &ip, + std::string *reason) { SCRIPTAPI_PRECHECKHEADER @@ -159,7 +163,8 @@ void ScriptApiPlayer::on_joinplayer(ServerActiveObject *player, s64 last_login) runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, bool timeout) +void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, + bool timeout) { SCRIPTAPI_PRECHECKHEADER @@ -172,7 +177,8 @@ void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, bool timeout) runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_cheat(ServerActiveObject *player, const std::string &cheat_type) +void ScriptApiPlayer::on_cheat(ServerActiveObject *player, + const std::string &cheat_type) { SCRIPTAPI_PRECHECKHEADER @@ -188,7 +194,8 @@ void ScriptApiPlayer::on_cheat(ServerActiveObject *player, const std::string &ch } void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, - const std::string &formname, const StringMap &fields) + const std::string &formname, + const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -213,8 +220,7 @@ void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC); } -void ScriptApiPlayer::on_authplayer( - const std::string &name, const std::string &ip, bool is_success) +void ScriptApiPlayer::on_authplayer(const std::string &name, const std::string &ip, bool is_success) { SCRIPTAPI_PRECHECKHEADER @@ -230,12 +236,13 @@ void ScriptApiPlayer::on_authplayer( } void ScriptApiPlayer::pushMoveArguments( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { lua_State *L = getStack(); objectrefGetOrCreate(L, player); // player - lua_pushstring(L, "move"); // action - InvRef::create(L, ma.from_inv); // inventory + lua_pushstring(L, "move"); // action + InvRef::create(L, ma.from_inv); // inventory lua_newtable(L); { // Table containing the action information @@ -254,14 +261,15 @@ void ScriptApiPlayer::pushMoveArguments( } } -void ScriptApiPlayer::pushPutTakeArguments(const char *method, - const InventoryLocation &loc, const std::string &listname, int index, - const ItemStack &stack, ServerActiveObject *player) +void ScriptApiPlayer::pushPutTakeArguments( + const char *method, const InventoryLocation &loc, + const std::string &listname, int index, const ItemStack &stack, + ServerActiveObject *player) { lua_State *L = getStack(); objectrefGetOrCreate(L, player); // player - lua_pushstring(L, method); // action - InvRef::create(L, loc); // inventory + lua_pushstring(L, method); // action + InvRef::create(L, loc); // inventory lua_newtable(L); { // Table containing the action information @@ -278,7 +286,8 @@ void ScriptApiPlayer::pushPutTakeArguments(const char *method, // Return number of accepted items to be moved int ScriptApiPlayer::player_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -292,7 +301,8 @@ int ScriptApiPlayer::player_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiPlayer::player_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -306,7 +316,8 @@ int ScriptApiPlayer::player_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiPlayer::player_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -320,7 +331,8 @@ int ScriptApiPlayer::player_inventory_AllowTake( // Report moved items void ScriptApiPlayer::player_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -332,7 +344,8 @@ void ScriptApiPlayer::player_inventory_OnMove( // Report put items void ScriptApiPlayer::player_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -344,7 +357,8 @@ void ScriptApiPlayer::player_inventory_OnPut( // Report taken items void ScriptApiPlayer::player_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/cpp_api/s_player.h b/src/script/cpp_api/s_player.h index 5a1cf15b8..a337f975b 100644 --- a/src/script/cpp_api/s_player.h +++ b/src/script/cpp_api/s_player.h @@ -51,33 +51,38 @@ class ScriptApiPlayer : virtual public ScriptApiBase const PlayerHPChangeReason &reason); void on_playerReceiveFields(ServerActiveObject *player, const std::string &formname, const StringMap &fields); - void on_authplayer( - const std::string &name, const std::string &ip, bool is_success); + void on_authplayer(const std::string &name, const std::string &ip, bool is_success); // Player inventory callbacks // Return number of accepted items to be moved int player_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Return number of accepted items to be put - int player_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + int player_inventory_AllowPut( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Return number of accepted items to be taken - int player_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + int player_inventory_AllowTake( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Report moved items void player_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Report put items - void player_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + void player_inventory_OnPut( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Report taken items - void player_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); - + void player_inventory_OnTake( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); private: - void pushPutTakeArguments(const char *method, const InventoryLocation &loc, - const std::string &listname, int index, const ItemStack &stack, - ServerActiveObject *player); - void pushMoveArguments( - const MoveAction &ma, int count, ServerActiveObject *player); + void pushPutTakeArguments( + const char *method, const InventoryLocation &loc, + const std::string &listname, int index, const ItemStack &stack, + ServerActiveObject *player); + void pushMoveArguments(const MoveAction &ma, + int count, ServerActiveObject *player); }; diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index 21bc7eb0a..9d65819c0 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -29,20 +29,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -#define SECURE_API(lib, name) \ - lua_pushcfunction(L, sl_##lib##_##name); \ + +#define SECURE_API(lib, name) \ + lua_pushcfunction(L, sl_##lib##_##name); \ lua_setfield(L, -2, #name); -static inline void copy_safe(lua_State *L, const char *list[], unsigned len, - int from = -2, int to = -1) + +static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1) { - if (from < 0) - from = lua_gettop(L) + from + 1; - if (to < 0) - to = lua_gettop(L) + to + 1; + if (from < 0) from = lua_gettop(L) + from + 1; + if (to < 0) to = lua_gettop(L) + to + 1; for (unsigned i = 0; i < (len / sizeof(list[0])); i++) { lua_getfield(L, from, list[i]); - lua_setfield(L, to, list[i]); + lua_setfield(L, to, list[i]); } } @@ -51,90 +50,91 @@ static inline void push_original(lua_State *L, const char *lib, const char *func { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); lua_getfield(L, -1, lib); - lua_remove(L, -2); // Remove globals_backup + lua_remove(L, -2); // Remove globals_backup lua_getfield(L, -1, func); - lua_remove(L, -2); // Remove lib + lua_remove(L, -2); // Remove lib } + void ScriptApiSecurity::initializeSecurity() { static const char *whitelist[] = { - "assert", - "core", - "collectgarbage", - "DIR_DELIM", - "error", - "getfenv", - "getmetatable", - "ipairs", - "next", - "pairs", - "pcall", - "print", - "rawequal", - "rawget", - "rawset", - "select", - "setfenv", - "setmetatable", - "tonumber", - "tostring", - "type", - "unpack", - "_VERSION", - "xpcall", - // Completely safe libraries - "coroutine", - "string", - "table", - "math", + "assert", + "core", + "collectgarbage", + "DIR_DELIM", + "error", + "getfenv", + "getmetatable", + "ipairs", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawset", + "select", + "setfenv", + "setmetatable", + "tonumber", + "tostring", + "type", + "unpack", + "_VERSION", + "xpcall", + // Completely safe libraries + "coroutine", + "string", + "table", + "math", }; static const char *io_whitelist[] = { - "open", - "close", - "flush", - "read", - "type", - "write", + "open", + "close", + "flush", + "read", + "type", + "write", }; static const char *os_whitelist[] = { - "clock", - "date", - "difftime", - "getenv", - "setlocale", - "time", - "tmpname", + "clock", + "date", + "difftime", + "getenv", + "setlocale", + "time", + "tmpname", }; static const char *debug_whitelist[] = { - "gethook", - "traceback", - "getinfo", - "getmetatable", - "setupvalue", - "setmetatable", - "upvalueid", - "sethook", - "debug", - "setlocal", + "gethook", + "traceback", + "getinfo", + "getmetatable", + "setupvalue", + "setmetatable", + "upvalueid", + "sethook", + "debug", + "setlocal", }; static const char *package_whitelist[] = { - "config", - "cpath", - "path", - "searchpath", + "config", + "cpath", + "path", + "searchpath", }; #if USE_LUAJIT static const char *jit_whitelist[] = { - "arch", - "flush", - "off", - "on", - "opt", - "os", - "status", - "version", - "version_num", + "arch", + "flush", + "off", + "on", + "opt", + "os", + "status", + "version", + "version_num", }; #endif m_secure = true; @@ -154,6 +154,7 @@ void ScriptApiSecurity::initializeSecurity() lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); int old_globals = lua_gettop(L); + // Copy safe base functions lua_getglobal(L, "_G"); copy_safe(L, whitelist, sizeof(whitelist)); @@ -166,19 +167,21 @@ void ScriptApiSecurity::initializeSecurity() SECURE_API(g, require); lua_pop(L, 1); + // Copy safe IO functions lua_getfield(L, old_globals, "io"); lua_newtable(L); copy_safe(L, io_whitelist, sizeof(io_whitelist)); // And replace unsafe ones - // SECURE_API(io, open); + //SECURE_API(io, open); SECURE_API(io, input); SECURE_API(io, output); SECURE_API(io, lines); lua_setglobal(L, "io"); - lua_pop(L, 1); // Pop old IO + lua_pop(L, 1); // Pop old IO + // Copy safe OS functions lua_getfield(L, old_globals, "os"); @@ -190,21 +193,23 @@ void ScriptApiSecurity::initializeSecurity() SECURE_API(os, rename); lua_setglobal(L, "os"); - lua_pop(L, 1); // Pop old OS + lua_pop(L, 1); // Pop old OS + // Copy safe debug functions lua_getfield(L, old_globals, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); lua_setglobal(L, "debug"); - lua_pop(L, 1); // Pop old debug + lua_pop(L, 1); // Pop old debug + // Copy safe package fields lua_getfield(L, old_globals, "package"); lua_newtable(L); copy_safe(L, package_whitelist, sizeof(package_whitelist)); lua_setglobal(L, "package"); - lua_pop(L, 1); // Pop old package + lua_pop(L, 1); // Pop old package #if USE_LUAJIT // Copy safe jit functions, if they exist @@ -214,7 +219,7 @@ void ScriptApiSecurity::initializeSecurity() copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); lua_setglobal(L, "jit"); } - lua_pop(L, 1); // Pop old jit + lua_pop(L, 1); // Pop old jit #endif lua_pop(L, 1); // Pop globals_backup @@ -223,49 +228,57 @@ void ScriptApiSecurity::initializeSecurity() void ScriptApiSecurity::initializeSecurityClient() { static const char *whitelist[] = { - "assert", - "core", - "collectgarbage", - "DIR_DELIM", - "error", - "getfenv", - "ipairs", - "next", - "pairs", - "pcall", - "print", - "rawequal", - "rawget", - "rawset", - "select", - "setfenv", - // getmetatable can be used to escape the sandbox - "setmetatable", - "tonumber", - "tostring", - "type", - "unpack", - "_VERSION", - "xpcall", - // Completely safe libraries - "coroutine", - "string", - "table", - "math", + "assert", + "core", + "collectgarbage", + "DIR_DELIM", + "error", + "getfenv", + "ipairs", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawset", + "select", + "setfenv", + // getmetatable can be used to escape the sandbox + "setmetatable", + "tonumber", + "tostring", + "type", + "unpack", + "_VERSION", + "xpcall", + // Completely safe libraries + "coroutine", + "string", + "table", + "math", + }; + static const char *os_whitelist[] = { + "clock", + "date", + "difftime", + "time" + }; + static const char *debug_whitelist[] = { + "getinfo", + "traceback" }; - static const char *os_whitelist[] = {"clock", "date", "difftime", "time"}; - static const char *debug_whitelist[] = {"getinfo", "traceback"}; #if USE_LUAJIT static const char *jit_whitelist[] = { - "arch", - "flush", - "off", - "on", - "opt", - "os", - "status", - "version", - "version_num", + "arch", + "flush", + "off", + "on", + "opt", + "os", + "status", + "version", + "version_num", }; #endif @@ -299,14 +312,16 @@ void ScriptApiSecurity::initializeSecurityClient() lua_newtable(L); copy_safe(L, os_whitelist, sizeof(os_whitelist)); lua_setfield(L, -3, "os"); - lua_pop(L, 1); // Pop old OS + lua_pop(L, 1); // Pop old OS + // Copy safe debug functions lua_getglobal(L, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); lua_setfield(L, -3, "debug"); - lua_pop(L, 1); // Pop old debug + lua_pop(L, 1); // Pop old debug + #if USE_LUAJIT // Copy safe jit functions, if they exist @@ -314,7 +329,7 @@ void ScriptApiSecurity::initializeSecurityClient() lua_newtable(L); copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); lua_setfield(L, -3, "jit"); - lua_pop(L, 1); // Pop old jit + lua_pop(L, 1); // Pop old jit #endif // Set the environment to the one we created earlier @@ -324,9 +339,9 @@ void ScriptApiSecurity::initializeSecurityClient() int ScriptApiSecurity::getThread(lua_State *L) { #if LUA_VERSION_NUM <= 501 - int is_main = lua_pushthread(L); // Push the main thread + int is_main = lua_pushthread(L); // Push the main thread FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state " - "isn't the main Lua thread!"); + "isn't the main Lua thread!"); return lua_gettop(L); #endif return 0; @@ -334,21 +349,21 @@ int ScriptApiSecurity::getThread(lua_State *L) void ScriptApiSecurity::createEmptyEnv(lua_State *L) { - lua_newtable(L); // Create new environment + lua_newtable(L); // Create new environment lua_pushvalue(L, -1); - lua_setfield(L, -2, "_G"); // Create the _G loop + lua_setfield(L, -2, "_G"); // Create the _G loop } void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread) { -#if LUA_VERSION_NUM >= 502 // Lua >= 5.2 +#if LUA_VERSION_NUM >= 502 // Lua >= 5.2 // Set the global environment lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); -#else // Lua <= 5.1 - // Set the environment of the main thread +#else // Lua <= 5.1 + // Set the environment of the main thread FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set " - "environment of the main Lua thread!"); - lua_pop(L, 1); // Pop thread + "environment of the main Lua thread!"); + lua_pop(L, 1); // Pop thread #endif } @@ -360,8 +375,7 @@ bool ScriptApiSecurity::isSecure(lua_State *L) return secure; } -bool ScriptApiSecurity::safeLoadString( - lua_State *L, const std::string &code, const char *chunk_name) +bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name) { if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) { lua_pushliteral(L, "Bytecode prohibited when mod security is enabled."); @@ -372,8 +386,7 @@ bool ScriptApiSecurity::safeLoadString( return true; } -bool ScriptApiSecurity::safeLoadFile( - lua_State *L, const char *path, const char *display_name) +bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name) { FILE *fp; char *chunk_name; @@ -398,8 +411,7 @@ bool ScriptApiSecurity::safeLoadFile( int c = std::getc(fp); if (c == '#') { // Skip the first line - while ((c = std::getc(fp)) != EOF && c != '\n') { - } + while ((c = std::getc(fp)) != EOF && c != '\n') {} if (c == '\n') std::getc(fp); start = std::ftell(fp); @@ -411,7 +423,7 @@ bool ScriptApiSecurity::safeLoadFile( lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete[] chunk_name; + delete [] chunk_name; } return false; } @@ -423,7 +435,7 @@ bool ScriptApiSecurity::safeLoadFile( lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete[] chunk_name; + delete [] chunk_name; } return false; } @@ -434,31 +446,31 @@ bool ScriptApiSecurity::safeLoadFile( if (num_read != size) { lua_pushliteral(L, "Error reading file to load."); if (path) - delete[] chunk_name; + delete [] chunk_name; return false; } bool result = safeLoadString(L, code, chunk_name); if (path) - delete[] chunk_name; + delete [] chunk_name; return result; } -bool ScriptApiSecurity::checkPath( - lua_State *L, const char *path, bool write_required, bool *write_allowed) + +bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, + bool write_required, bool *write_allowed) { if (write_allowed) *write_allowed = false; - std::string str; // Transient + std::string str; // Transient std::string abs_path = fs::AbsolutePath(path); if (!abs_path.empty()) { // Don't allow accessing the settings file str = fs::AbsolutePath(g_settings_path); - if (str == abs_path) - return false; + if (str == abs_path) return false; } // If we couldn't find the absolute path (path doesn't exist) then @@ -470,18 +482,15 @@ bool ScriptApiSecurity::checkPath( std::string component; cur_path = fs::RemoveLastPathComponent(cur_path, &component); if (component == "..") { - // Parent components can't be allowed or we could allow something - // like + // Parent components can't be allowed or we could allow something like // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd. - // If we have previous non-relative elements in the path we might - // be able to remove them so that things like - // worlds/foo/noexist/../auth.txt could be allowed, but those - // paths will be interpreted as nonexistent by the operating - // system anyways. + // If we have previous non-relative elements in the path we might be + // able to remove them so that things like worlds/foo/noexist/../auth.txt + // could be allowed, but those paths will be interpreted as nonexistent + // by the operating system anyways. return false; } - removed.append(component).append( - removed.empty() ? "" : DIR_DELIM + removed); + removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed); abs_path = fs::AbsolutePath(cur_path); } if (abs_path.empty()) @@ -495,9 +504,9 @@ bool ScriptApiSecurity::checkPath( lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *script; #if INDIRECT_SCRIPTAPI_RIDX - script = (ScriptApiBase *)*(void **)(lua_touserdata(L, -1)); + script = (ScriptApiBase *) *(void**)(lua_touserdata(L, -1)); #else - script = (ScriptApiBase *)lua_touserdata(L, -1); + script = (ScriptApiBase *) lua_touserdata(L, -1); #endif lua_pop(L, 1); const IGameDef *gamedef = script->getGameDef(); @@ -511,27 +520,24 @@ bool ScriptApiSecurity::checkPath( // Builtin can access anything if (mod_name == BUILTIN_MOD_NAME) { - if (write_allowed) - *write_allowed = true; + if (write_allowed) *write_allowed = true; return true; } // Allow paths in mod path - // Don't bother if write access isn't important, since it will be handled - // later + // Don't bother if write access isn't important, since it will be handled later if (write_required || write_allowed != NULL) { const ModSpec *mod = gamedef->getModSpec(mod_name); if (mod) { str = fs::AbsolutePath(mod->path); if (!str.empty() && fs::PathStartsWith(abs_path, str)) { - if (write_allowed) - *write_allowed = true; + if (write_allowed) *write_allowed = true; return true; } } } } - lua_pop(L, 1); // Pop mod name + lua_pop(L, 1); // Pop mod name // Allow read-only access to all mod directories if (!write_required) { @@ -558,8 +564,7 @@ bool ScriptApiSecurity::checkPath( } // Allow all other paths in world path if (fs::PathStartsWith(abs_path, str)) { - if (write_allowed) - *write_allowed = true; + if (write_allowed) *write_allowed = true; return true; } } @@ -568,6 +573,7 @@ bool ScriptApiSecurity::checkPath( return false; } + int ScriptApiSecurity::sl_g_dofile(lua_State *L) { int nret = sl_g_loadfile(L); @@ -582,6 +588,7 @@ int ScriptApiSecurity::sl_g_dofile(lua_State *L) return lua_gettop(L) - (top_precall - 1); } + int ScriptApiSecurity::sl_g_load(lua_State *L) { size_t len; @@ -620,11 +627,12 @@ int ScriptApiSecurity::sl_g_load(lua_State *L) return 1; } + int ScriptApiSecurity::sl_g_loadfile(lua_State *L) { #ifndef SERVER lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); - ScriptApiBase *script = (ScriptApiBase *)lua_touserdata(L, -1); + ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1); lua_pop(L, 1); // Client implementation @@ -664,6 +672,7 @@ int ScriptApiSecurity::sl_g_loadfile(lua_State *L) return 1; } + int ScriptApiSecurity::sl_g_loadstring(lua_State *L) { const char *chunk_name = "=(load)"; @@ -686,12 +695,14 @@ int ScriptApiSecurity::sl_g_loadstring(lua_State *L) return 1; } + int ScriptApiSecurity::sl_g_require(lua_State *L) { lua_pushliteral(L, "require() is disabled when mod security is on."); return lua_error(L); } + int ScriptApiSecurity::sl_io_open(lua_State *L) { bool with_mode = lua_gettop(L) > 1; @@ -704,7 +715,8 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) luaL_checktype(L, 2, LUA_TSTRING); const char *mode = lua_tostring(L, 2); write_requested = strchr(mode, 'w') != NULL || - strchr(mode, '+') != NULL || strchr(mode, 'a') != NULL; + strchr(mode, '+') != NULL || + strchr(mode, 'a') != NULL; } CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL); @@ -718,6 +730,7 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) return 2; } + int ScriptApiSecurity::sl_io_input(lua_State *L) { if (lua_isstring(L, 1)) { @@ -731,6 +744,7 @@ int ScriptApiSecurity::sl_io_input(lua_State *L) return 1; } + int ScriptApiSecurity::sl_io_output(lua_State *L) { if (lua_isstring(L, 1)) { @@ -744,6 +758,7 @@ int ScriptApiSecurity::sl_io_output(lua_State *L) return 1; } + int ScriptApiSecurity::sl_io_lines(lua_State *L) { if (lua_isstring(L, 1)) { @@ -760,6 +775,7 @@ int ScriptApiSecurity::sl_io_lines(lua_State *L) return lua_gettop(L) - top_precall; } + int ScriptApiSecurity::sl_os_rename(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -777,6 +793,7 @@ int ScriptApiSecurity::sl_os_rename(lua_State *L) return 2; } + int ScriptApiSecurity::sl_os_remove(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -788,3 +805,4 @@ int ScriptApiSecurity::sl_os_remove(lua_State *L) lua_call(L, 1, 2); return 2; } + diff --git a/src/script/cpp_api/s_security.h b/src/script/cpp_api/s_security.h index 075950845..73e763548 100644 --- a/src/script/cpp_api/s_security.h +++ b/src/script/cpp_api/s_security.h @@ -21,20 +21,22 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_base.h" -#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \ - if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \ - throw LuaError(std::string("Mod security: Blocked attempted ") + \ - (write_required ? "write to " : "read from ") + path); \ + +#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \ + if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \ + throw LuaError(std::string("Mod security: Blocked attempted ") + \ + (write_required ? "write to " : "read from ") + path); \ } -#define CHECK_SECURE_PATH(L, path, write_required) \ - if (ScriptApiSecurity::isSecure(L)) { \ - CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \ +#define CHECK_SECURE_PATH(L, path, write_required) \ + if (ScriptApiSecurity::isSecure(L)) { \ + CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \ } -#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \ - if (ScriptApiSecurity::isSecure(L)) { \ - CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \ +#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \ + if (ScriptApiSecurity::isSecure(L)) { \ + CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \ } + class ScriptApiSecurity : virtual public ScriptApiBase { public: @@ -49,14 +51,12 @@ class ScriptApiSecurity : virtual public ScriptApiBase // Checks if the Lua state has been secured static bool isSecure(lua_State *L); // Loads a string as Lua code safely (doesn't allow bytecode). - static bool safeLoadString( - lua_State *L, const std::string &code, const char *chunk_name); + static bool safeLoadString(lua_State *L, const std::string &code, const char *chunk_name); // Loads a file as Lua code safely (doesn't allow bytecode). - static bool safeLoadFile( - lua_State *L, const char *path, const char *display_name = NULL); + static bool safeLoadFile(lua_State *L, const char *path, const char *display_name = NULL); // Checks if mods are allowed to read (and optionally write) to the path static bool checkPath(lua_State *L, const char *path, bool write_required, - bool *write_allowed = NULL); + bool *write_allowed=NULL); private: // Syntax: "sl_" '_' diff --git a/src/script/cpp_api/s_server.cpp b/src/script/cpp_api/s_server.cpp index 1cb3f99f1..96cb28b28 100644 --- a/src/script/cpp_api/s_server.cpp +++ b/src/script/cpp_api/s_server.cpp @@ -21,8 +21,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_internal.h" #include "common/c_converter.h" -bool ScriptApiServer::getAuth(const std::string &playername, std::string *dst_password, - std::set *dst_privs, s64 *dst_last_login) +bool ScriptApiServer::getAuth(const std::string &playername, + std::string *dst_password, + std::set *dst_privs, + s64 *dst_last_login) { SCRIPTAPI_PRECHECKHEADER @@ -52,10 +54,10 @@ bool ScriptApiServer::getAuth(const std::string &playername, std::string *dst_pa throw LuaError("Authentication handler didn't return privilege table"); if (dst_privs) readPrivileges(-1, *dst_privs); - lua_pop(L, 1); // Remove key from privs table + lua_pop(L, 1); // Remove key from privs table s64 last_login; - if (!getintfield(L, -1, "last_login", last_login)) + if(!getintfield(L, -1, "last_login", last_login)) throw LuaError("Authentication handler didn't return last_login"); if (dst_last_login) *dst_last_login = (s64)last_login; @@ -69,7 +71,7 @@ void ScriptApiServer::getAuthHandler() lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_auth_handler"); - if (lua_isnil(L, -1)) { + if (lua_isnil(L, -1)){ lua_pop(L, 1); lua_getfield(L, -1, "builtin_auth_handler"); } @@ -100,8 +102,8 @@ void ScriptApiServer::readPrivileges(int index, std::set &result) } } -void ScriptApiServer::createAuth( - const std::string &playername, const std::string &password) +void ScriptApiServer::createAuth(const std::string &playername, + const std::string &password) { SCRIPTAPI_PRECHECKHEADER @@ -117,8 +119,8 @@ void ScriptApiServer::createAuth( lua_pop(L, 1); // Pop error handler } -bool ScriptApiServer::setPassword( - const std::string &playername, const std::string &password) +bool ScriptApiServer::setPassword(const std::string &playername, + const std::string &password) { SCRIPTAPI_PRECHECKHEADER @@ -135,7 +137,8 @@ bool ScriptApiServer::setPassword( return lua_toboolean(L, -1); } -bool ScriptApiServer::on_chat_message(const std::string &name, const std::string &message) +bool ScriptApiServer::on_chat_message(const std::string &name, + const std::string &message) { SCRIPTAPI_PRECHECKHEADER @@ -171,8 +174,8 @@ void ScriptApiServer::on_shutdown() runCallbacks(0, RUN_CALLBACKS_MODE_FIRST); } -std::string ScriptApiServer::formatChatMessage( - const std::string &name, const std::string &message) +std::string ScriptApiServer::formatChatMessage(const std::string &name, + const std::string &message) { SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/cpp_api/s_server.h b/src/script/cpp_api/s_server.h index db574bd56..d8639cba7 100644 --- a/src/script/cpp_api/s_server.h +++ b/src/script/cpp_api/s_server.h @@ -22,7 +22,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_base.h" #include -class ScriptApiServer : virtual public ScriptApiBase +class ScriptApiServer + : virtual public ScriptApiBase { public: // Calls on_chat_message handlers @@ -36,15 +37,18 @@ class ScriptApiServer : virtual public ScriptApiBase void on_shutdown(); // Calls core.format_chat_message - std::string formatChatMessage( - const std::string &name, const std::string &message); + std::string formatChatMessage(const std::string &name, + const std::string &message); /* auth */ - bool getAuth(const std::string &playername, std::string *dst_password, - std::set *dst_privs, s64 *dst_last_login = nullptr); - void createAuth(const std::string &playername, const std::string &password); - bool setPassword(const std::string &playername, const std::string &password); - + bool getAuth(const std::string &playername, + std::string *dst_password, + std::set *dst_privs, + s64 *dst_last_login = nullptr); + void createAuth(const std::string &playername, + const std::string &password); + bool setPassword(const std::string &playername, + const std::string &password); private: void getAuthHandler(); void readPrivileges(int index, std::set &result); diff --git a/src/script/lua_api/l_areastore.cpp b/src/script/lua_api/l_areastore.cpp index d043bfc90..908c766b0 100644 --- a/src/script/lua_api/l_areastore.cpp +++ b/src/script/lua_api/l_areastore.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_areastore.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" @@ -26,8 +27,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "filesys.h" #include -static inline void get_data_and_border_flags( - lua_State *L, u8 start_i, bool *borders, bool *data) +static inline void get_data_and_border_flags(lua_State *L, u8 start_i, + bool *borders, bool *data) { if (!lua_isboolean(L, start_i)) return; @@ -37,8 +38,8 @@ static inline void get_data_and_border_flags( *data = lua_toboolean(L, start_i + 1); } -static void push_area( - lua_State *L, const Area *a, bool include_borders, bool include_data) +static void push_area(lua_State *L, const Area *a, + bool include_borders, bool include_data) { if (!include_borders && !include_data) { lua_pushboolean(L, true); @@ -57,8 +58,8 @@ static void push_area( } } -static inline void push_areas( - lua_State *L, const std::vector &areas, bool borders, bool data) +static inline void push_areas(lua_State *L, const std::vector &areas, + bool borders, bool data) { lua_newtable(L); size_t cnt = areas.size(); @@ -70,7 +71,8 @@ static inline void push_areas( } // Deserializes value and handles errors -static int deserialization_helper(lua_State *L, AreaStore *as, std::istream &is) +static int deserialization_helper(lua_State *L, AreaStore *as, + std::istream &is) { try { as->deserialize(is); @@ -326,9 +328,9 @@ int LuaAreaStore::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; - LuaAreaStore *o = (lua_isstring(L, 1)) - ? new LuaAreaStore(readParam(L, 1)) - : new LuaAreaStore(); + LuaAreaStore *o = (lua_isstring(L, 1)) ? + new LuaAreaStore(readParam(L, 1)) : + new LuaAreaStore(); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); @@ -346,7 +348,7 @@ LuaAreaStore *LuaAreaStore::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaAreaStore **)ud; // unbox pointer + return *(LuaAreaStore **)ud; // unbox pointer } void LuaAreaStore::Register(lua_State *L) @@ -358,7 +360,7 @@ void LuaAreaStore::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -368,22 +370,27 @@ void LuaAreaStore::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (AreaStore()) lua_register(L, className, create_object); } const char LuaAreaStore::className[] = "AreaStore"; -const luaL_Reg LuaAreaStore::methods[] = {luamethod(LuaAreaStore, get_area), - luamethod(LuaAreaStore, get_areas_for_pos), - luamethod(LuaAreaStore, get_areas_in_area), - luamethod(LuaAreaStore, insert_area), luamethod(LuaAreaStore, reserve), - luamethod(LuaAreaStore, remove_area), - luamethod(LuaAreaStore, set_cache_params), - luamethod(LuaAreaStore, to_string), luamethod(LuaAreaStore, to_file), - luamethod(LuaAreaStore, from_string), luamethod(LuaAreaStore, from_file), - {0, 0}}; +const luaL_Reg LuaAreaStore::methods[] = { + luamethod(LuaAreaStore, get_area), + luamethod(LuaAreaStore, get_areas_for_pos), + luamethod(LuaAreaStore, get_areas_in_area), + luamethod(LuaAreaStore, insert_area), + luamethod(LuaAreaStore, reserve), + luamethod(LuaAreaStore, remove_area), + luamethod(LuaAreaStore, set_cache_params), + luamethod(LuaAreaStore, to_string), + luamethod(LuaAreaStore, to_file), + luamethod(LuaAreaStore, from_string), + luamethod(LuaAreaStore, from_file), + {0,0} +}; diff --git a/src/script/lua_api/l_base.cpp b/src/script/lua_api/l_base.cpp index 8ae03d6c8..011434845 100644 --- a/src/script/lua_api/l_base.cpp +++ b/src/script/lua_api/l_base.cpp @@ -32,9 +32,9 @@ ScriptApiBase *ModApiBase::getScriptApiBase(lua_State *L) lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *sapi_ptr; #if INDIRECT_SCRIPTAPI_RIDX - sapi_ptr = (ScriptApiBase *)*(void **)(lua_touserdata(L, -1)); + sapi_ptr = (ScriptApiBase*) *(void**)(lua_touserdata(L, -1)); #else - sapi_ptr = (ScriptApiBase *)lua_touserdata(L, -1); + sapi_ptr = (ScriptApiBase*) lua_touserdata(L, -1); #endif lua_pop(L, 1); return sapi_ptr; @@ -93,8 +93,9 @@ std::string ModApiBase::getCurrentModPath(lua_State *L) return mod->path; } -bool ModApiBase::registerFunction( - lua_State *L, const char *name, lua_CFunction func, int top) + +bool ModApiBase::registerFunction(lua_State *L, const char *name, + lua_CFunction func, int top) { // TODO: Check presence first! @@ -125,7 +126,7 @@ int ModApiBase::l_deprecated_function(lua_State *L) // Get parent class to get the wrappers map luaL_checktype(L, 1, LUA_TUSERDATA); void *ud = lua_touserdata(L, 1); - ModApiBase *o = *(ModApiBase **)ud; + ModApiBase *o = *(ModApiBase**)ud; // New function and new function name auto it = o->m_deprecated_wrappers.find(ar.name); @@ -135,13 +136,12 @@ int ModApiBase::l_deprecated_function(lua_State *L) backtrace.append(":").append(std::to_string(ar.currentline)); u64 hash = murmur_hash_64_ua(backtrace.data(), backtrace.length(), 0xBADBABE); - if (std::find(deprecated_logged.begin(), deprecated_logged.end(), hash) == - deprecated_logged.end()) { + if (std::find(deprecated_logged.begin(), deprecated_logged.end(), hash) + == deprecated_logged.end()) { deprecated_logged.emplace_back(hash); - warningstream << "Call to deprecated function '" << ar.name - << "', please use '" << it->second.name << "' at " - << backtrace << std::endl; + warningstream << "Call to deprecated function '" << ar.name << "', please use '" + << it->second.name << "' at " << backtrace << std::endl; if (m_error_deprecated_calls) script_error(L, LUA_ERRRUN, NULL, NULL); @@ -172,8 +172,8 @@ void ModApiBase::markAliasDeprecated(luaL_Reg *reg) // Do not inline struct. Breaks MSVC or is error-prone original_reg.name = last_name; original_reg.func = reg->func; - m_deprecated_wrappers.emplace(std::pair( - reg->name, original_reg)); + m_deprecated_wrappers.emplace( + std::pair(reg->name, original_reg)); reg->func = l_deprecated_function; } diff --git a/src/script/lua_api/l_base.h b/src/script/lua_api/l_base.h index bb806d631..0cbee7756 100644 --- a/src/script/lua_api/l_base.h +++ b/src/script/lua_api/l_base.h @@ -41,44 +41,43 @@ class Server; class Environment; class ServerInventoryManager; -class ModApiBase : protected LuaHelper -{ +class ModApiBase : protected LuaHelper { public: - static ScriptApiBase *getScriptApiBase(lua_State *L); - static Server *getServer(lua_State *L); + static ScriptApiBase* getScriptApiBase(lua_State *L); + static Server* getServer(lua_State *L); static ServerInventoryManager *getServerInventoryMgr(lua_State *L); -#ifndef SERVER - static Client *getClient(lua_State *L); - static Game *getGame(lua_State *L); - static GUIEngine *getGuiEngine(lua_State *L); -#endif // !SERVER + #ifndef SERVER + static Client* getClient(lua_State *L); + static Game* getGame(lua_State *L); + static GUIEngine* getGuiEngine(lua_State *L); + #endif // !SERVER - static IGameDef *getGameDef(lua_State *L); - static Environment *getEnv(lua_State *L); + static IGameDef* getGameDef(lua_State *L); + static Environment* getEnv(lua_State *L); // When we are not loading the mod, this function returns "." - static std::string getCurrentModPath(lua_State *L); + static std::string getCurrentModPath(lua_State *L); // Get an arbitrary subclass of ScriptApiBase // by using dynamic_cast<> on getScriptApiBase() - template static T *getScriptApi(lua_State *L) - { + template + static T* getScriptApi(lua_State *L) { ScriptApiBase *scriptIface = getScriptApiBase(L); - T *scriptIfaceDowncast = dynamic_cast(scriptIface); + T *scriptIfaceDowncast = dynamic_cast(scriptIface); if (!scriptIfaceDowncast) { - throw LuaError("Requested unavailable ScriptApi - core engine " - "bug!"); + throw LuaError("Requested unavailable ScriptApi - core engine bug!"); } return scriptIfaceDowncast; } - static bool registerFunction( - lua_State *L, const char *name, lua_CFunction func, int top); + static bool registerFunction(lua_State *L, + const char* name, + lua_CFunction func, + int top); static int l_deprecated_function(lua_State *L); static void markAliasDeprecated(luaL_Reg *reg); - private: // = { , } static std::unordered_map m_deprecated_wrappers; diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index 1bc4829d4..9961471ff 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -38,12 +38,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "client/keycode.h" -#define checkCSMRestrictionFlag(flag) \ - (getClient(L)->checkCSMRestrictionFlag(CSMRestrictionFlags::flag)) +#define checkCSMRestrictionFlag(flag) \ + ( getClient(L)->checkCSMRestrictionFlag(CSMRestrictionFlags::flag) ) // Not the same as FlagDesc, which contains an `u32 flag` -struct CSMFlagDesc -{ +struct CSMFlagDesc { const char *name; u64 flag; }; @@ -54,12 +53,14 @@ struct CSMFlagDesc in network/networkprotocol.h */ const static CSMFlagDesc flagdesc_csm_restriction[] = { - {"load_client_mods", CSM_RF_LOAD_CLIENT_MODS}, - {"chat_messages", CSM_RF_CHAT_MESSAGES}, - {"read_itemdefs", CSM_RF_READ_ITEMDEFS}, - {"read_nodedefs", CSM_RF_READ_NODEDEFS}, - {"lookup_nodes", CSM_RF_LOOKUP_NODES}, - {"read_playerinfo", CSM_RF_READ_PLAYERINFO}, {NULL, 0}}; + {"load_client_mods", CSM_RF_LOAD_CLIENT_MODS}, + {"chat_messages", CSM_RF_CHAT_MESSAGES}, + {"read_itemdefs", CSM_RF_READ_ITEMDEFS}, + {"read_nodedefs", CSM_RF_READ_NODEDEFS}, + {"lookup_nodes", CSM_RF_LOOKUP_NODES}, + {"read_playerinfo", CSM_RF_READ_PLAYERINFO}, + {NULL, 0} +}; // get_current_modname() int ModApiClient::l_get_current_modname(lua_State *L) @@ -421,7 +422,7 @@ int ModApiClient::l_send_damage(lua_State *L) { u16 damage = luaL_checknumber(L, 1); getClient(L)->sendDamage(damage); - return 0; + return 0; } // place_node(pos) @@ -432,8 +433,7 @@ int ModApiClient::l_place_node(lua_State *L) LocalPlayer *player = client->getEnv().getLocalPlayer(); ItemStack selected_item, hand_item; player->getWieldedItem(&selected_item, &hand_item); - const ItemDefinition &selected_def = - selected_item.getDefinition(getGameDef(L)->idef()); + const ItemDefinition &selected_def = selected_item.getDefinition(getGameDef(L)->idef()); v3s16 pos = read_v3s16(L, 1); PointedThing pointed; pointed.type = POINTEDTHING_NODE; @@ -465,7 +465,7 @@ int ModApiClient::l_get_inventory(lua_State *L) InventoryLocation inventory_location; Inventory *inventory; std::string location; - + location = readParam(L, 1); try { @@ -475,7 +475,7 @@ int ModApiClient::l_get_inventory(lua_State *L) } catch (SerializationError &) { lua_pushnil(L); } - + return 1; } @@ -508,17 +508,17 @@ int ModApiClient::l_drop_selected_item(lua_State *L) int ModApiClient::l_get_objects_inside_radius(lua_State *L) { ClientEnvironment &env = getClient(L)->getEnv(); - + v3f pos = checkFloatPos(L, 1); float radius = readParam(L, 2) * BS; - + std::vector objs; env.getActiveObjects(pos, radius, objs); - + int i = 0; lua_createtable(L, objs.size(), 0); for (const auto obj : objs) { - ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate + ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate lua_rawseti(L, -2, ++i); } return 1; diff --git a/src/script/lua_api/l_clientobject.cpp b/src/script/lua_api/l_clientobject.cpp index 05b3e2850..d88b538a1 100644 --- a/src/script/lua_api/l_clientobject.cpp +++ b/src/script/lua_api/l_clientobject.cpp @@ -146,7 +146,7 @@ int ClientObjectRef::l_punch(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); + PointedThing pointed(gcao->getId(), v3f(0,0,0), v3s16(0,0,0), 0); getClient(L)->interact(INTERACT_START_DIGGING, pointed); return 0; } @@ -155,7 +155,7 @@ int ClientObjectRef::l_rightclick(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); + PointedThing pointed(gcao->getId(), v3f(0,0,0), v3s16(0,0,0), 0); getClient(L)->interact(INTERACT_PLACE, pointed); return 0; } @@ -223,5 +223,6 @@ luaL_Reg ClientObjectRef::methods[] = {luamethod(ClientObjectRef, get_pos), luamethod(ClientObjectRef, get_attach), luamethod(ClientObjectRef, get_nametag), luamethod(ClientObjectRef, get_item_textures), - luamethod(ClientObjectRef, get_max_hp), luamethod(ClientObjectRef, punch), + luamethod(ClientObjectRef, get_max_hp), + luamethod(ClientObjectRef, punch), luamethod(ClientObjectRef, rightclick), {0, 0}}; diff --git a/src/script/lua_api/l_clientobject.h b/src/script/lua_api/l_clientobject.h index a4516e047..521591444 100644 --- a/src/script/lua_api/l_clientobject.h +++ b/src/script/lua_api/l_clientobject.h @@ -60,7 +60,7 @@ class ClientObjectRef : public ModApiBase // is_player(self) static int l_is_player(lua_State *L); - + // is_local_player(self) static int l_is_local_player(lua_State *L); diff --git a/src/script/lua_api/l_craft.cpp b/src/script/lua_api/l_craft.cpp index 07b45eaff..18622ee00 100644 --- a/src/script/lua_api/l_craft.cpp +++ b/src/script/lua_api/l_craft.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_craft.h" #include "lua_api/l_internal.h" #include "lua_api/l_item.h" @@ -25,45 +26,46 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "craftdef.h" -struct EnumString ModApiCraft::es_CraftMethod[] = { - {CRAFT_METHOD_NORMAL, "normal"}, - {CRAFT_METHOD_COOKING, "cooking"}, - {CRAFT_METHOD_FUEL, "fuel"}, - {0, NULL}, +struct EnumString ModApiCraft::es_CraftMethod[] = +{ + {CRAFT_METHOD_NORMAL, "normal"}, + {CRAFT_METHOD_COOKING, "cooking"}, + {CRAFT_METHOD_FUEL, "fuel"}, + {0, NULL}, }; // helper for register_craft -bool ModApiCraft::readCraftRecipeShaped( - lua_State *L, int index, int &width, std::vector &recipe) +bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index, + int &width, std::vector &recipe) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); int rowcount = 0; - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ int colcount = 0; // key at index -2 and value at index -1 - if (!lua_istable(L, -1)) + if(!lua_istable(L, -1)) return false; int table2 = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table2) != 0) { + while(lua_next(L, table2) != 0){ // key at index -2 and value at index -1 - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; recipe.emplace_back(readParam(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); colcount++; } - if (rowcount == 0) { + if(rowcount == 0){ width = colcount; } else { - if (colcount != width) + if(colcount != width) return false; } // removes value, keeps key for next iteration @@ -74,19 +76,19 @@ bool ModApiCraft::readCraftRecipeShaped( } // helper for register_craft -bool ModApiCraft::readCraftRecipeShapeless( - lua_State *L, int index, std::vector &recipe) +bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index, + std::vector &recipe) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; recipe.emplace_back(readParam(L, -1)); // removes value, keeps key for next iteration @@ -96,27 +98,27 @@ bool ModApiCraft::readCraftRecipeShapeless( } // helper for register_craft -bool ModApiCraft::readCraftReplacements( - lua_State *L, int index, CraftReplacements &replacements) +bool ModApiCraft::readCraftReplacements(lua_State *L, int index, + CraftReplacements &replacements) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 - if (!lua_istable(L, -1)) + if(!lua_istable(L, -1)) return false; lua_rawgeti(L, -1, 1); - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; std::string replace_from = readParam(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; std::string replace_to = readParam(L, -1); lua_pop(L, 1); @@ -130,19 +132,20 @@ bool ModApiCraft::readCraftReplacements( int ModApiCraft::l_register_craft(lua_State *L) { NO_MAP_LOCK_REQUIRED; - // infostream<<"register_craft"<getWritableCraftDefManager(); + IWritableCraftDefManager *craftdef = + getServer(L)->getWritableCraftDefManager(); std::string type = getstringfield_default(L, table, "type", "shaped"); /* CraftDefinitionShaped */ - if (type == "shaped") { + if(type == "shaped"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition is missing an output"); @@ -150,22 +153,20 @@ int ModApiCraft::l_register_craft(lua_State *L) int width = 0; std::vector recipe; lua_getfield(L, table, "recipe"); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) throw LuaError("Crafting definition is missing a recipe" - " (output=\"" + - output + "\")"); - if (!readCraftRecipeShaped(L, -1, width, recipe)) + " (output=\"" + output + "\")"); + if(!readCraftRecipeShaped(L, -1, width, recipe)) throw LuaError("Invalid crafting recipe" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShaped( @@ -175,31 +176,29 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionShapeless */ - else if (type == "shapeless") { + else if(type == "shapeless"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (shapeless)" - " is missing an output"); + " is missing an output"); std::vector recipe; lua_getfield(L, table, "recipe"); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) throw LuaError("Crafting definition (shapeless)" - " is missing a recipe" - " (output=\"" + - output + "\")"); - if (!readCraftRecipeShapeless(L, -1, recipe)) + " is missing a recipe" + " (output=\"" + output + "\")"); + if(!readCraftRecipeShapeless(L, -1, recipe)) throw LuaError("Invalid crafting recipe" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShapeless( @@ -209,38 +208,38 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionToolRepair */ - else if (type == "toolrepair") { - float additional_wear = - getfloatfield_default(L, table, "additional_wear", 0.0); + else if(type == "toolrepair"){ + float additional_wear = getfloatfield_default(L, table, + "additional_wear", 0.0); - CraftDefinition *def = new CraftDefinitionToolRepair(additional_wear); + CraftDefinition *def = new CraftDefinitionToolRepair( + additional_wear); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionCooking */ - else if (type == "cooking") { + else if(type == "cooking"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (cooking)" - " is missing an output"); + " is missing an output"); std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (cooking)" - " is missing a recipe" - " (output=\"" + - output + "\")"); + " is missing a recipe" + " (output=\"" + output + "\")"); float cooktime = getfloatfield_default(L, table, "cooktime", 3.0); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (cooking output=\"" + - output + "\")"); + " (cooking output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionCooking( @@ -250,27 +249,29 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionFuel */ - else if (type == "fuel") { + else if(type == "fuel"){ std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (fuel)" - " is missing a recipe"); + " is missing a recipe"); float burntime = getfloatfield_default(L, table, "burntime", 1.0); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (fuel recipe=\"" + - recipe + "\")"); + " (fuel recipe=\"" + recipe + "\")"); } - CraftDefinition *def = - new CraftDefinitionFuel(recipe, burntime, replacements); + CraftDefinition *def = new CraftDefinitionFuel( + recipe, burntime, replacements); craftdef->registerCraft(def, getServer(L)); - } else { + } + else + { throw LuaError("Unknown crafting definition type: \"" + type + "\""); } @@ -286,7 +287,8 @@ int ModApiCraft::l_clear_craft(lua_State *L) int table = 1; // Get the writable craft definition manager from the server - IWritableCraftDefManager *craftdef = getServer(L)->getWritableCraftDefManager(); + IWritableCraftDefManager *craftdef = + getServer(L)->getWritableCraftDefManager(); std::string output = getstringfield_default(L, table, "output", ""); std::string type = getstringfield_default(L, table, "type", "shaped"); @@ -332,7 +334,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (cooking)" - " is missing a recipe"); + " is missing a recipe"); recipe.push_back(rec); } /* @@ -343,7 +345,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (fuel)" - " is missing a recipe"); + " is missing a recipe"); recipe.push_back(rec); } else { throw LuaError("Unknown crafting definition type: \"" + type + "\""); @@ -372,15 +374,15 @@ int ModApiCraft::l_get_craft_result(lua_State *L) int input_i = 1; std::string method_s = getstringfield_default(L, input_i, "method", "normal"); - enum CraftMethod method = (CraftMethod)getenumfield( - L, input_i, "method", es_CraftMethod, CRAFT_METHOD_NORMAL); + enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method", + es_CraftMethod, CRAFT_METHOD_NORMAL); int width = 1; lua_getfield(L, input_i, "width"); - if (lua_isnumber(L, -1)) + if(lua_isnumber(L, -1)) width = luaL_checkinteger(L, -1); lua_pop(L, 1); lua_getfield(L, input_i, "items"); - std::vector items = read_items(L, -1, getServer(L)); + std::vector items = read_items(L, -1,getServer(L)); lua_pop(L, 1); // items IGameDef *gdef = getServer(L); @@ -415,7 +417,9 @@ int ModApiCraft::l_get_craft_result(lua_State *L) return 2; } -static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinition *recipe, + +static void push_craft_recipe(lua_State *L, IGameDef *gdef, + const CraftDefinition *recipe, const CraftOutput &tmpout) { CraftInput input = recipe->getInput(tmpout, gdef); @@ -458,7 +462,8 @@ static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinitio } static void push_craft_recipes(lua_State *L, IGameDef *gdef, - const std::vector &recipes, const CraftOutput &output) + const std::vector &recipes, + const CraftOutput &output) { lua_createtable(L, recipes.size(), 0); @@ -467,7 +472,7 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, return; } - std::vector::const_iterator it = recipes.begin(); + std::vector::const_iterator it = recipes.begin(); for (unsigned i = 0; it != recipes.end(); ++it) { lua_newtable(L); push_craft_recipe(L, gdef, *it, output); @@ -475,6 +480,7 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, } } + // get_craft_recipe(result item) int ModApiCraft::l_get_craft_recipe(lua_State *L) { @@ -483,8 +489,8 @@ int ModApiCraft::l_get_craft_recipe(lua_State *L) std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); - std::vector recipes = - server->cdef()->getCraftRecipes(output, server, 1); + std::vector recipes = server->cdef() + ->getCraftRecipes(output, server, 1); lua_createtable(L, 1, 0); @@ -506,8 +512,8 @@ int ModApiCraft::l_get_all_craft_recipes(lua_State *L) std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); - std::vector recipes = - server->cdef()->getCraftRecipes(output, server); + std::vector recipes = server->cdef() + ->getCraftRecipes(output, server); push_craft_recipes(L, server, recipes, output); return 1; diff --git a/src/script/lua_api/l_craft.h b/src/script/lua_api/l_craft.h index 5ba3d18fe..9002b23ef 100644 --- a/src/script/lua_api/l_craft.h +++ b/src/script/lua_api/l_craft.h @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., struct CraftReplacements; -class ModApiCraft : public ModApiBase -{ +class ModApiCraft : public ModApiBase { private: static int l_register_craft(lua_State *L); static int l_get_craft_recipe(lua_State *L); @@ -35,12 +34,12 @@ class ModApiCraft : public ModApiBase static int l_get_craft_result(lua_State *L); static int l_clear_craft(lua_State *L); - static bool readCraftReplacements( - lua_State *L, int index, CraftReplacements &replacements); - static bool readCraftRecipeShapeless( - lua_State *L, int index, std::vector &recipe); - static bool readCraftRecipeShaped(lua_State *L, int index, int &width, + static bool readCraftReplacements(lua_State *L, int index, + CraftReplacements &replacements); + static bool readCraftRecipeShapeless(lua_State *L, int index, std::vector &recipe); + static bool readCraftRecipeShaped(lua_State *L, int index, + int &width, std::vector &recipe); static struct EnumString es_CraftMethod[]; diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 2c612eb9a..ee384ad10 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -46,16 +46,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #endif -struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = { - {CLEAR_OBJECTS_MODE_FULL, "full"}, - {CLEAR_OBJECTS_MODE_QUICK, "quick"}, - {0, NULL}, +struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = +{ + {CLEAR_OBJECTS_MODE_FULL, "full"}, + {CLEAR_OBJECTS_MODE_QUICK, "quick"}, + {0, NULL}, }; /////////////////////////////////////////////////////////////////////////////// -void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, - u32 active_object_count_wider) + +void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, + u32 active_object_count, u32 active_object_count_wider) { ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); @@ -75,7 +77,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_obje // Get registered_abms[m_id] lua_pushinteger(L, m_id); lua_gettable(L, -2); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) FATAL_ERROR(""); lua_remove(L, -2); // Remove registered_abms @@ -118,8 +120,7 @@ void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n) // Get registered_lbms[m_id] lua_pushinteger(L, m_id); lua_gettable(L, -2); - FATAL_ERROR_IF(lua_isnil(L, -1), - "Entry with given id not found in registered_lbms table"); + FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table"); lua_remove(L, -2); // Remove registered_lbms scriptIface->setOriginFromTable(-1); @@ -175,9 +176,10 @@ int LuaRaycast::create_object(lua_State *L) liquids = readParam(L, 4); } - LuaRaycast *o = new LuaRaycast(core::line3d(pos1, pos2), objects, liquids); + LuaRaycast *o = new LuaRaycast(core::line3d(pos1, pos2), + objects, liquids); - *(void **)(lua_newuserdata(L, sizeof(void *))) = o; + *(void **) (lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; @@ -191,12 +193,12 @@ LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg) void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(LuaRaycast **)ud; + return *(LuaRaycast **) ud; } int LuaRaycast::gc_object(lua_State *L) { - LuaRaycast *o = *(LuaRaycast **)(lua_touserdata(L, 1)); + LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1)); delete o; return 0; } @@ -233,7 +235,11 @@ void LuaRaycast::Register(lua_State *L) } const char LuaRaycast::className[] = "Raycast"; -const luaL_Reg LuaRaycast::methods[] = {luamethod(LuaRaycast, next), {0, 0}}; +const luaL_Reg LuaRaycast::methods[] = +{ + luamethod(LuaRaycast, next), + { 0, 0 } +}; void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param) { @@ -385,7 +391,7 @@ int ModApiEnvMod::l_get_node_light(lua_State *L) // Do it v3s16 pos = read_v3s16(L, 1); u32 time_of_day = env->getTimeOfDay(); - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) time_of_day = 24000.0 * lua_tonumber(L, 2); time_of_day %= 24000; u32 dnr = time_to_daynight_ratio(time_of_day, true); @@ -417,7 +423,7 @@ int ModApiEnvMod::l_place_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n_old = env->getMap().getNode(pos); - if (n_old.getContent() == CONTENT_IGNORE) { + if(n_old.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -427,7 +433,7 @@ int ModApiEnvMod::l_place_node(lua_State *L) PointedThing pointed; pointed.type = POINTEDTHING_NODE; pointed.node_abovesurface = pos; - pointed.node_undersurface = pos + v3s16(0, -1, 0); + pointed.node_undersurface = pos + v3s16(0,-1,0); // Place it with a NULL placer (appears in Lua as nil) bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed); lua_pushboolean(L, success); @@ -446,7 +452,7 @@ int ModApiEnvMod::l_dig_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNode(pos); - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -469,7 +475,7 @@ int ModApiEnvMod::l_punch_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNode(pos); - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -513,7 +519,7 @@ int ModApiEnvMod::l_set_node_level(lua_State *L) v3s16 pos = read_v3s16(L, 1); u8 level = 1; - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNode(pos); lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level)); @@ -530,7 +536,7 @@ int ModApiEnvMod::l_add_node_level(lua_State *L) v3s16 pos = read_v3s16(L, 1); s16 level = 1; - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNode(pos); lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level)); @@ -544,7 +550,7 @@ int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L) GET_PLAIN_ENV_PTR; std::vector positions = env->getMap().findNodesWithMetadata( - check_v3s16(L, 1), check_v3s16(L, 2)); + check_v3s16(L, 1), check_v3s16(L, 2)); lua_createtable(L, positions.size(), 0); for (size_t i = 0; i != positions.size(); i++) { @@ -590,7 +596,7 @@ int ModApiEnvMod::l_add_entity(lua_State *L) ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata); int objectid = env->addActiveObject(obj); // If failed to add, return nothing (reads as nil) - if (objectid == 0) + if(objectid == 0) return 0; // If already deleted (can happen in on_activate), return nil @@ -607,10 +613,10 @@ int ModApiEnvMod::l_add_item(lua_State *L) GET_ENV_PTR; // pos - // v3f pos = checkFloatPos(L, 1); + //v3f pos = checkFloatPos(L, 1); // item - ItemStack item = read_item(L, 2, getServer(L)->idef()); - if (item.empty() || !item.isKnown(getServer(L)->idef())) + ItemStack item = read_item(L, 2,getServer(L)->idef()); + if(item.empty() || !item.isKnown(getServer(L)->idef())) return 0; int error_handler = PUSH_ERROR_HANDLER(L); @@ -619,7 +625,7 @@ int ModApiEnvMod::l_add_item(lua_State *L) lua_getglobal(L, "core"); lua_getfield(L, -1, "spawn_item"); lua_remove(L, -2); // Remove core - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) return 0; lua_pushvalue(L, 1); lua_pushstring(L, item.getItemString().c_str()); @@ -633,10 +639,10 @@ int ModApiEnvMod::l_add_item(lua_State *L) // get_connected_players() int ModApiEnvMod::l_get_connected_players(lua_State *L) { - ServerEnvironment *env = (ServerEnvironment *)getEnv(L); + ServerEnvironment *env = (ServerEnvironment *) getEnv(L); if (!env) { log_deprecated(L, "Calling get_connected_players() at mod load time" - " is deprecated"); + " is deprecated"); lua_createtable(L, 0, 0); return 1; } @@ -684,7 +690,7 @@ int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L) float radius = readParam(L, 2) * BS; std::vector objs; - auto include_obj_cb = [](ServerActiveObject *obj) { return !obj->isGone(); }; + auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); }; env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb); int i = 0; @@ -710,7 +716,7 @@ int ModApiEnvMod::l_set_timeofday(lua_State *L) // This should be set directly in the environment but currently // such changes aren't immediately sent to the clients, so call // the server instead. - // env->setTimeOfDay(timeofday_mh); + //env->setTimeOfDay(timeofday_mh); getServer(L)->setTimeOfDay(timeofday_mh); return 0; } @@ -747,7 +753,7 @@ int ModApiEnvMod::l_get_gametime(lua_State *L) } void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef, - std::vector &filter) + std::vector &filter) { if (lua_istable(L, idx)) { lua_pushnil(L); @@ -819,13 +825,13 @@ int ModApiEnvMod::l_find_nodes_near(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -869,13 +875,13 @@ int ModApiEnvMod::l_find_nodes_near_under_air(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -923,13 +929,13 @@ int ModApiEnvMod::l_find_nodes_near_under_air_except(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -980,7 +986,7 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) { luaL_error(L, "find_nodes_in_area(): area volume" - " exceeds allowed value of 4096000"); + " exceeds allowed value of 4096000"); return 0; } @@ -1002,21 +1008,18 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - content_t c = map.getNode(p).getContent(); - - auto it = std::find( - filter.begin(), filter.end(), c); - if (it != filter.end()) { - // Calculate index of the table and append - // the position - u32 filt_index = it - filter.begin(); - push_v3s16(L, p); - lua_rawseti(L, base + 1 + filt_index, - ++idx[filt_index]); - } - } + for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + content_t c = map.getNode(p).getContent(); + + auto it = std::find(filter.begin(), filter.end(), c); + if (it != filter.end()) { + // Calculate index of the table and append the position + u32 filt_index = it - filter.begin(); + push_v3s16(L, p); + lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]); + } + } // last filter table is at top of stack u32 i = filter.size() - 1; @@ -1040,21 +1043,19 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) u32 i = 0; v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - content_t c = env->getMap().getNode(p) - .getContent(); - - auto it = std::find( - filter.begin(), filter.end(), c); - if (it != filter.end()) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - - u32 filt_index = it - filter.begin(); - individual_count[filt_index]++; - } - } + for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + content_t c = env->getMap().getNode(p).getContent(); + + auto it = std::find(filter.begin(), filter.end(), c); + if (it != filter.end()) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); + + u32 filt_index = it - filter.begin(); + individual_count[filt_index]++; + } + } lua_createtable(L, 0, filter.size()); for (u32 i = 0; i < filter.size(); i++) { @@ -1096,7 +1097,7 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) { luaL_error(L, "find_nodes_in_area_under_air(): area volume" - " exceeds allowed value of 4096000"); + " exceeds allowed value of 4096000"); return 0; } @@ -1107,20 +1108,20 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) u32 i = 0; v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - p.Y = minp.Y; - content_t c = map.getNode(p).getContent(); - for (; p.Y <= maxp.Y; p.Y++) { - v3s16 psurf(p.X, p.Y + 1, p.Z); - content_t csurf = map.getNode(psurf).getContent(); - if (c != CONTENT_AIR && csurf == CONTENT_AIR && - CONTAINS(filter, c)) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - } - c = csurf; + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + p.Y = minp.Y; + content_t c = map.getNode(p).getContent(); + for (; p.Y <= maxp.Y; p.Y++) { + v3s16 psurf(p.X, p.Y + 1, p.Z); + content_t csurf = map.getNode(psurf).getContent(); + if (c != CONTENT_AIR && csurf == CONTENT_AIR && + CONTAINS(filter, c)) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); } + c = csurf; } + } return 1; } @@ -1135,10 +1136,10 @@ int ModApiEnvMod::l_get_perlin(lua_State *L) if (lua_istable(L, 1)) { read_noiseparams(L, 1, ¶ms); } else { - params.seed = luaL_checkint(L, 1); + params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam(L, 3); - params.spread = v3f(1, 1, 1) * readParam(L, 4); + params.spread = v3f(1, 1, 1) * readParam(L, 4); } params.seed += (int)env->getServerMap().getSeed(); @@ -1176,10 +1177,9 @@ int ModApiEnvMod::l_get_voxel_manip(lua_State *L) GET_ENV_PTR; Map *map = &(env->getMap()); - LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) - ? new LuaVoxelManip(map, read_v3s16(L, 1), - read_v3s16(L, 2)) - : new LuaVoxelManip(map); + LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ? + new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) : + new LuaVoxelManip(map); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); @@ -1196,8 +1196,8 @@ int ModApiEnvMod::l_clear_objects(lua_State *L) ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK; if (lua_istable(L, 1)) { - mode = (ClearObjectsMode)getenumfield( - L, 1, "mode", ModApiEnvMod::es_ClearObjectsMode, mode); + mode = (ClearObjectsMode)getenumfield(L, 1, "mode", + ModApiEnvMod::es_ClearObjectsMode, mode); } env->clearObjects(mode); @@ -1237,12 +1237,10 @@ int ModApiEnvMod::l_fix_light(lua_State *L) bool success = true; v3s16 blockpos; for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++) - for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++) - for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; - blockpos.Z++) { - success = success & map.repairBlockLight(blockpos, - &modified_blocks); - } + for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++) + for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) { + success = success & map.repairBlockLight(blockpos, &modified_blocks); + } if (!modified_blocks.empty()) { MapEditEvent event; event.type = MEET_OTHER; @@ -1276,10 +1274,10 @@ int ModApiEnvMod::l_load_area(lua_State *L) v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2)); sortBoxVerticies(bp1, bp2); for (s16 z = bp1.Z; z <= bp2.Z; z++) - for (s16 y = bp1.Y; y <= bp2.Y; y++) - for (s16 x = bp1.X; x <= bp2.X; x++) { - map->emergeBlock(v3s16(x, y, z)); - } + for (s16 y = bp1.Y; y <= bp2.Y; y++) + for (s16 x = bp1.X; x <= bp2.X; x++) { + map->emergeBlock(v3s16(x, y, z)); + } } return 0; @@ -1313,22 +1311,19 @@ int ModApiEnvMod::l_emerge_area(lua_State *L) int args_ref = luaL_ref(L, LUA_REGISTRYINDEX); state = new ScriptCallbackState; - state->script = getServer(L)->getScriptIface(); + state->script = getServer(L)->getScriptIface(); state->callback_ref = callback_ref; - state->args_ref = args_ref; - state->refcount = num_blocks; - state->origin = getScriptApiBase(L)->getOrigin(); + state->args_ref = args_ref; + state->refcount = num_blocks; + state->origin = getScriptApiBase(L)->getOrigin(); } for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - emerge->enqueueBlockEmergeEx(v3s16(x, y, z), - PEER_ID_INEXISTENT, - BLOCK_EMERGE_ALLOW_GEN | - BLOCK_EMERGE_FORCE_QUEUE, - callback, state); - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT, + BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state); + } return 0; } @@ -1350,16 +1345,16 @@ int ModApiEnvMod::l_delete_area(lua_State *L) bool success = true; for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - v3s16 bp(x, y, z); - if (map.deleteBlock(bp)) { - env->setStaticForActiveObjectsInBlock(bp, false); - event.modified_blocks.insert(bp); - } else { - success = false; - } - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + v3s16 bp(x, y, z); + if (map.deleteBlock(bp)) { + env->setStaticForActiveObjectsInBlock(bp, false); + event.modified_blocks.insert(bp); + } else { + success = false; + } + } map.dispatchEvent(event); lua_pushboolean(L, success); @@ -1372,14 +1367,14 @@ int ModApiEnvMod::l_find_path(lua_State *L) { Environment *env = getEnv(L); - v3s16 pos1 = read_v3s16(L, 1); - v3s16 pos2 = read_v3s16(L, 2); + v3s16 pos1 = read_v3s16(L, 1); + v3s16 pos2 = read_v3s16(L, 2); unsigned int searchdistance = luaL_checkint(L, 3); - unsigned int max_jump = luaL_checkint(L, 4); - unsigned int max_drop = luaL_checkint(L, 5); - PathAlgorithm algo = PA_PLAIN_NP; + unsigned int max_jump = luaL_checkint(L, 4); + unsigned int max_drop = luaL_checkint(L, 5); + PathAlgorithm algo = PA_PLAIN_NP; if (!lua_isnoneornil(L, 6)) { - std::string algorithm = luaL_checkstring(L, 6); + std::string algorithm = luaL_checkstring(L,6); if (algorithm == "A*") algo = PA_PLAIN; @@ -1387,16 +1382,16 @@ int ModApiEnvMod::l_find_path(lua_State *L) if (algorithm == "Dijkstra") algo = PA_DIJKSTRA; } - - std::vector path = get_path(&env->getMap(), env->getGameDef()->ndef(), - pos1, pos2, searchdistance, max_jump, max_drop, algo); + + std::vector path = get_path(&env->getMap(), env->getGameDef()->ndef(), pos1, pos2, + searchdistance, max_jump, max_drop, algo); if (!path.empty()) { lua_createtable(L, path.size(), 0); int top = lua_gettop(L); unsigned int index = 1; for (const v3s16 &i : path) { - lua_pushnumber(L, index); + lua_pushnumber(L,index); push_v3s16(L, i); lua_settable(L, top); index++; @@ -1415,23 +1410,24 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) v3s16 p0 = read_v3s16(L, 1); treegen::TreeDef tree_def; - std::string trunk, leaves, fruit; + std::string trunk,leaves,fruit; const NodeDefManager *ndef = env->getGameDef()->ndef(); - if (lua_istable(L, 2)) { + if(lua_istable(L, 2)) + { getstringfield(L, 2, "axiom", tree_def.initial_axiom); getstringfield(L, 2, "rules_a", tree_def.rules_a); getstringfield(L, 2, "rules_b", tree_def.rules_b); getstringfield(L, 2, "rules_c", tree_def.rules_c); getstringfield(L, 2, "rules_d", tree_def.rules_d); getstringfield(L, 2, "trunk", trunk); - tree_def.trunknode = ndef->getId(trunk); + tree_def.trunknode=ndef->getId(trunk); getstringfield(L, 2, "leaves", leaves); - tree_def.leavesnode = ndef->getId(leaves); - tree_def.leaves2_chance = 0; + tree_def.leavesnode=ndef->getId(leaves); + tree_def.leaves2_chance=0; getstringfield(L, 2, "leaves2", leaves); if (!leaves.empty()) { - tree_def.leaves2node = ndef->getId(leaves); + tree_def.leaves2node=ndef->getId(leaves); getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance); } getintfield(L, 2, "angle", tree_def.angle); @@ -1440,22 +1436,22 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) tree_def.iterations_random_level = 0; getstringfield(L, 2, "trunk_type", tree_def.trunk_type); getboolfield(L, 2, "thin_branches", tree_def.thin_branches); - tree_def.fruit_chance = 0; + tree_def.fruit_chance=0; getstringfield(L, 2, "fruit", fruit); if (!fruit.empty()) { - tree_def.fruitnode = ndef->getId(fruit); - getintfield(L, 2, "fruit_chance", tree_def.fruit_chance); + tree_def.fruitnode=ndef->getId(fruit); + getintfield(L, 2, "fruit_chance",tree_def.fruit_chance); } tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed); - } else + } + else return 0; ServerMap *map = &env->getServerMap(); treegen::error e; - if ((e = treegen::spawn_ltree(map, p0, ndef, tree_def)) != treegen::SUCCESS) { + if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) { if (e == treegen::UNBALANCED_BRACKETS) { - luaL_error(L, "spawn_tree(): closing ']' has no matching opening " - "bracket"); + luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket"); } else { luaL_error(L, "spawn_tree(): unknown error"); } @@ -1497,14 +1493,14 @@ int ModApiEnvMod::l_forceload_free_block(lua_State *L) } // get_translated_string(lang_code, string) -int ModApiEnvMod::l_get_translated_string(lua_State *L) +int ModApiEnvMod::l_get_translated_string(lua_State * L) { GET_ENV_PTR; std::string lang_code = luaL_checkstring(L, 1); std::string string = luaL_checkstring(L, 2); getServer(L)->loadTranslationLanguage(lang_code); - string = wide_to_utf8(translate_string( - utf8_to_wide(string), &(*g_server_translations)[lang_code])); + string = wide_to_utf8(translate_string(utf8_to_wide(string), + &(*g_server_translations)[lang_code])); lua_pushstring(L, string.c_str()); return 1; } diff --git a/src/script/lua_api/l_env.h b/src/script/lua_api/l_env.h index 43388475e..e1b89494b 100644 --- a/src/script/lua_api/l_env.h +++ b/src/script/lua_api/l_env.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverenvironment.h" #include "raycast.h" -class ModApiEnvMod : public ModApiBase -{ +class ModApiEnvMod : public ModApiBase { private: // set_node(pos, node) // pos = {x=num, y=num, z=num} @@ -127,17 +126,17 @@ class ModApiEnvMod : public ModApiBase // find_node_near(pos, radius, nodenames, search_center) -> pos or nil // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_node_near(lua_State *L); - + // find_nodes_near(pos, radius, nodenames, search_center) -> list of positions // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near(lua_State *L); - - // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of - // positions nodenames: eg. {"ignore", "group:tree"} or "default:dirt" + + // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of positions + // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near_under_air(lua_State *L); - - // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of - // positions nodenames: eg. {"ignore", "group:tree"} or "default:dirt" + + // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of positions + // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near_under_air_except(lua_State *L); // find_nodes_in_area(minp, maxp, nodenames) -> list of positions @@ -201,12 +200,12 @@ class ModApiEnvMod : public ModApiBase static int l_forceload_free_block(lua_State *L); // Get a string translated server side - static int l_get_translated_string(lua_State *L); + static int l_get_translated_string(lua_State * L); /* Helpers */ - static void collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef, - std::vector &filter); + static void collectNodeIds(lua_State *L, int idx, + const NodeDefManager *ndef, std::vector &filter); public: static void Initialize(lua_State *L, int top); @@ -215,8 +214,7 @@ class ModApiEnvMod : public ModApiBase static struct EnumString es_ClearObjectsMode[]; }; -class LuaABM : public ActiveBlockModifier -{ +class LuaABM : public ActiveBlockModifier { private: int m_id; @@ -225,18 +223,17 @@ class LuaABM : public ActiveBlockModifier float m_trigger_interval; u32 m_trigger_chance; bool m_simple_catch_up; - public: - LuaABM(lua_State *L, int id, const std::vector &trigger_contents, + LuaABM(lua_State *L, int id, + const std::vector &trigger_contents, const std::vector &required_neighbors, - float trigger_interval, u32 trigger_chance, - bool simple_catch_up) : - m_id(id), - m_trigger_contents(trigger_contents), - m_required_neighbors(required_neighbors), - m_trigger_interval(trigger_interval), - m_trigger_chance(trigger_chance), - m_simple_catch_up(simple_catch_up) + float trigger_interval, u32 trigger_chance, bool simple_catch_up): + m_id(id), + m_trigger_contents(trigger_contents), + m_required_neighbors(required_neighbors), + m_trigger_interval(trigger_interval), + m_trigger_chance(trigger_chance), + m_simple_catch_up(simple_catch_up) { } virtual const std::vector &getTriggerContents() const @@ -247,9 +244,18 @@ class LuaABM : public ActiveBlockModifier { return m_required_neighbors; } - virtual float getTriggerInterval() { return m_trigger_interval; } - virtual u32 getTriggerChance() { return m_trigger_chance; } - virtual bool getSimpleCatchUp() { return m_simple_catch_up; } + virtual float getTriggerInterval() + { + return m_trigger_interval; + } + virtual u32 getTriggerChance() + { + return m_trigger_chance; + } + virtual bool getSimpleCatchUp() + { + return m_simple_catch_up; + } virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, u32 active_object_count_wider); }; @@ -258,11 +264,12 @@ class LuaLBM : public LoadingBlockModifierDef { private: int m_id; - public: - LuaLBM(lua_State *L, int id, const std::set &trigger_contents, - const std::string &name, bool run_at_every_load) : - m_id(id) + LuaLBM(lua_State *L, int id, + const std::set &trigger_contents, + const std::string &name, + bool run_at_every_load): + m_id(id) { this->run_at_every_load = run_at_every_load; this->trigger_contents = trigger_contents; @@ -290,14 +297,14 @@ class LuaRaycast : public ModApiBase * Returns the next pointed thing on the ray. */ static int l_next(lua_State *L); - public: //! Constructor with the same arguments as RaycastState. - LuaRaycast(const core::line3d &shootline, bool objects_pointable, - bool liquids_pointable) : - state(shootline, objects_pointable, liquids_pointable) - { - } + LuaRaycast( + const core::line3d &shootline, + bool objects_pointable, + bool liquids_pointable) : + state(shootline, objects_pointable, liquids_pointable) + {} //! Creates a LuaRaycast and leaves it on top of the stack. static int create_object(lua_State *L); @@ -312,8 +319,7 @@ class LuaRaycast : public ModApiBase static void Register(lua_State *L); }; -struct ScriptCallbackState -{ +struct ScriptCallbackState { ServerScripting *script; int callback_ref; int args_ref; diff --git a/src/script/lua_api/l_http.cpp b/src/script/lua_api/l_http.cpp index 21d000d25..84837e71b 100644 --- a/src/script/lua_api/l_http.cpp +++ b/src/script/lua_api/l_http.cpp @@ -30,9 +30,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -#define HTTP_API(name) \ - lua_pushstring(L, #name); \ - lua_pushcfunction(L, l_http_##name); \ +#define HTTP_API(name) \ + lua_pushstring(L, #name); \ + lua_pushcfunction(L, l_http_##name); \ lua_settable(L, -3); #if USE_CURL @@ -54,8 +54,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2) != 0) { - req.post_fields[readParam(L, -2)] = - readParam(L, -1); + req.post_fields[readParam(L, -2)] = readParam(L, -1); lua_pop(L, 1); } } else if (lua_isstring(L, 2)) { @@ -74,8 +73,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) lua_pop(L, 1); } -void ModApiHttp::push_http_fetch_result( - lua_State *L, HTTPFetchResult &res, bool completed) +void ModApiHttp::push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed) { lua_newtable(L); setboolfield(L, -1, "succeeded", res.succeeded); @@ -173,19 +171,15 @@ int ModApiHttp::l_request_http_api(lua_State *L) std::string mod_name = readParam(L, -1); std::string http_mods = g_settings->get("secure.http_mods"); - http_mods.erase(std::remove(http_mods.begin(), http_mods.end(), ' '), - http_mods.end()); + http_mods.erase(std::remove(http_mods.begin(), http_mods.end(), ' '), http_mods.end()); std::vector mod_list_http = str_split(http_mods, ','); std::string trusted_mods = g_settings->get("secure.trusted_mods"); - trusted_mods.erase(std::remove(trusted_mods.begin(), trusted_mods.end(), ' '), - trusted_mods.end()); + trusted_mods.erase(std::remove(trusted_mods.begin(), trusted_mods.end(), ' '), trusted_mods.end()); std::vector mod_list_trusted = str_split(trusted_mods, ','); - mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), - mod_list_trusted.end()); - if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == - mod_list_http.end()) { + mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), mod_list_trusted.end()); + if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == mod_list_http.end()) { lua_pushnil(L); return 1; } diff --git a/src/script/lua_api/l_http.h b/src/script/lua_api/l_http.h index f2c72eafb..de6e51b37 100644 --- a/src/script/lua_api/l_http.h +++ b/src/script/lua_api/l_http.h @@ -25,14 +25,12 @@ with this program; if not, write to the Free Software Foundation, Inc., struct HTTPFetchRequest; struct HTTPFetchResult; -class ModApiHttp : public ModApiBase -{ +class ModApiHttp : public ModApiBase { private: #if USE_CURL // Helpers for HTTP fetch functions static void read_http_fetch_request(lua_State *L, HTTPFetchRequest &req); - static void push_http_fetch_result( - lua_State *L, HTTPFetchResult &res, bool completed = true); + static void push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed = true); // http_fetch_sync({url=, timeout=, post_data=}) static int l_http_fetch_sync(lua_State *L); diff --git a/src/script/lua_api/l_internal.h b/src/script/lua_api/l_internal.h index 378d19cd0..a86eeaf79 100644 --- a/src/script/lua_api/l_internal.h +++ b/src/script/lua_api/l_internal.h @@ -28,12 +28,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_internal.h" -#define luamethod(class, name) \ - { \ -#name, class ::l_##name \ - } -#define luamethod_aliased(class, name, alias) \ - {#name, class ::l_##name}, { #alias, class ::l_##name } +#define luamethod(class, name) {#name, class::l_##name} +#define luamethod_aliased(class, name, alias) {#name, class::l_##name}, {#alias, class::l_##name} #define API_FCT(name) registerFunction(L, #name, l_##name, top) // For future use @@ -43,33 +39,32 @@ with this program; if not, write to the Free Software Foundation, Inc., /* In debug mode ensure no code tries to retrieve the server env when it isn't * actually available (in CSM) */ #if !defined(SERVER) && !defined(NDEBUG) -#define DEBUG_ASSERT_NO_CLIENTAPI \ - FATAL_ERROR_IF(getClient(L) != nullptr, \ - "Tried " \ - "to retrieve ServerEnvironment on client") +#define DEBUG_ASSERT_NO_CLIENTAPI \ + FATAL_ERROR_IF(getClient(L) != nullptr, "Tried " \ + "to retrieve ServerEnvironment on client") #else #define DEBUG_ASSERT_NO_CLIENTAPI ((void)0) #endif // Retrieve ServerEnvironment pointer as `env` (no map lock) -#define GET_ENV_PTR_NO_MAP_LOCK \ - DEBUG_ASSERT_NO_CLIENTAPI; \ - ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ - if (env == NULL) \ - return 0 +#define GET_ENV_PTR_NO_MAP_LOCK \ + DEBUG_ASSERT_NO_CLIENTAPI; \ + ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ + if (env == NULL) \ + return 0 // Retrieve ServerEnvironment pointer as `env` -#define GET_ENV_PTR \ - MAP_LOCK_REQUIRED; \ +#define GET_ENV_PTR \ + MAP_LOCK_REQUIRED; \ GET_ENV_PTR_NO_MAP_LOCK // Retrieve Environment pointer as `env` (no map lock) -#define GET_PLAIN_ENV_PTR_NO_MAP_LOCK \ - Environment *env = (Environment *)getEnv(L); \ - if (env == NULL) \ - return 0 +#define GET_PLAIN_ENV_PTR_NO_MAP_LOCK \ + Environment *env = (Environment *)getEnv(L); \ + if (env == NULL) \ + return 0 // Retrieve Environment pointer as `env` -#define GET_PLAIN_ENV_PTR \ - MAP_LOCK_REQUIRED; \ +#define GET_PLAIN_ENV_PTR \ + MAP_LOCK_REQUIRED; \ GET_PLAIN_ENV_PTR_NO_MAP_LOCK diff --git a/src/script/lua_api/l_inventory.cpp b/src/script/lua_api/l_inventory.cpp index d75d96ef3..e41b5cb41 100644 --- a/src/script/lua_api/l_inventory.cpp +++ b/src/script/lua_api/l_inventory.cpp @@ -29,25 +29,25 @@ with this program; if not, write to the Free Software Foundation, Inc., /* InvRef */ -InvRef *InvRef::checkobject(lua_State *L, int narg) +InvRef* InvRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(InvRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(InvRef**)ud; // unbox pointer } -Inventory *InvRef::getinv(lua_State *L, InvRef *ref) +Inventory* InvRef::getinv(lua_State *L, InvRef *ref) { return getServerInventoryMgr(L)->getInventory(ref->m_loc); } -InventoryList *InvRef::getlist(lua_State *L, InvRef *ref, const char *listname) +InventoryList* InvRef::getlist(lua_State *L, InvRef *ref, + const char *listname) { NO_MAP_LOCK_REQUIRED; Inventory *inv = getinv(L, ref); - if (!inv) + if(!inv) return NULL; return inv->getList(listname); } @@ -61,8 +61,7 @@ void InvRef::reportInventoryChange(lua_State *L, InvRef *ref) // Exported functions // garbage collector -int InvRef::gc_object(lua_State *L) -{ +int InvRef::gc_object(lua_State *L) { InvRef *o = *(InvRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -75,7 +74,7 @@ int InvRef::l_is_empty(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list && list->getUsedSlots() > 0) { + if(list && list->getUsedSlots() > 0){ lua_pushboolean(L, false); } else { lua_pushboolean(L, true); @@ -90,7 +89,7 @@ int InvRef::l_get_size(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushinteger(L, list->getSize()); } else { lua_pushinteger(L, 0); @@ -105,7 +104,7 @@ int InvRef::l_get_width(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushinteger(L, list->getWidth()); } else { lua_pushinteger(L, 0); @@ -127,22 +126,23 @@ int InvRef::l_set_size(lua_State *L) } Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ lua_pushboolean(L, false); return 1; } - if (newsize == 0) { + if(newsize == 0){ inv->deleteList(listname); reportInventoryChange(L, ref); lua_pushboolean(L, true); return 1; } InventoryList *list = inv->getList(listname); - if (list) { + if(list){ list->setSize(newsize); } else { list = inv->addList(listname, newsize); - if (!list) { + if (!list) + { lua_pushboolean(L, false); return 1; } @@ -160,11 +160,11 @@ int InvRef::l_set_width(lua_State *L) const char *listname = luaL_checkstring(L, 2); int newwidth = luaL_checknumber(L, 3); Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); - if (list) { + if(list){ list->setWidth(newwidth); } else { return 0; @@ -182,7 +182,7 @@ int InvRef::l_get_stack(lua_State *L) int i = luaL_checknumber(L, 3) - 1; InventoryList *list = getlist(L, ref, listname); ItemStack item; - if (list != NULL && i >= 0 && i < (int)list->getSize()) + if(list != NULL && i >= 0 && i < (int) list->getSize()) item = list->getItem(i); LuaItemStack::create(L, item); return 1; @@ -197,7 +197,7 @@ int InvRef::l_set_stack(lua_State *L) int i = luaL_checknumber(L, 3) - 1; ItemStack newitem = read_item(L, 4, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list != NULL && i >= 0 && i < (int)list->getSize()) { + if(list != NULL && i >= 0 && i < (int) list->getSize()){ list->changeItem(i, newitem); reportInventoryChange(L, ref); lua_pushboolean(L, true); @@ -214,7 +214,7 @@ int InvRef::l_get_list(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); - if (inv) { + if(inv){ push_inventory_list(L, inv, listname); } else { lua_pushnil(L); @@ -229,12 +229,13 @@ int InvRef::l_set_list(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); - if (list) - read_inventory_list(L, 3, inv, listname, getServer(L), list->getSize()); + if(list) + read_inventory_list(L, 3, inv, listname, + getServer(L), list->getSize()); else read_inventory_list(L, 3, inv, listname, getServer(L)); reportInventoryChange(L, ref); @@ -250,11 +251,11 @@ int InvRef::l_get_lists(lua_State *L) if (!inv) { return 0; } - std::vector lists = inv->getLists(); - std::vector::iterator iter = lists.begin(); + std::vector lists = inv->getLists(); + std::vector::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); for (; iter != lists.end(); iter++) { - const char *name = (*iter)->getName().c_str(); + const char* name = (*iter)->getName().c_str(); lua_pushstring(L, name); push_inventory_list(L, inv, name); lua_rawset(L, -3); @@ -297,9 +298,9 @@ int InvRef::l_add_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ ItemStack leftover = list->addItem(item); - if (leftover.count != item.count) + if(leftover.count != item.count) reportInventoryChange(L, ref); LuaItemStack::create(L, leftover); } else { @@ -317,7 +318,7 @@ int InvRef::l_room_for_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushboolean(L, list->roomForItem(item)); } else { lua_pushboolean(L, false); @@ -325,8 +326,8 @@ int InvRef::l_room_for_item(lua_State *L) return 1; } -// contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> -// true/false Returns true if the list contains the given count of the given item +// contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> true/false +// Returns true if the list contains the given count of the given item int InvRef::l_contains_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -354,9 +355,9 @@ int InvRef::l_remove_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ ItemStack removed = list->removeItem(item); - if (!removed.empty()) + if(!removed.empty()) reportInventoryChange(L, ref); LuaItemStack::create(L, removed); } else { @@ -371,7 +372,7 @@ int InvRef::l_get_location(lua_State *L) NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const InventoryLocation &loc = ref->m_loc; - switch (loc.type) { + switch(loc.type){ case InventoryLocation::PLAYER: lua_newtable(L); lua_pushstring(L, "player"); @@ -403,7 +404,9 @@ int InvRef::l_get_location(lua_State *L) return 1; } -InvRef::InvRef(const InventoryLocation &loc) : m_loc(loc) + +InvRef::InvRef(const InventoryLocation &loc): + m_loc(loc) { } @@ -440,7 +443,7 @@ void InvRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -450,25 +453,35 @@ void InvRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char InvRef::className[] = "InvRef"; -const luaL_Reg InvRef::methods[] = {luamethod(InvRef, is_empty), - luamethod(InvRef, get_size), luamethod(InvRef, set_size), - luamethod(InvRef, get_width), luamethod(InvRef, set_width), - luamethod(InvRef, get_stack), luamethod(InvRef, set_stack), - luamethod(InvRef, get_list), luamethod(InvRef, set_list), - luamethod(InvRef, get_lists), luamethod(InvRef, set_lists), - luamethod(InvRef, add_item), luamethod(InvRef, room_for_item), - luamethod(InvRef, contains_item), luamethod(InvRef, remove_item), - luamethod(InvRef, get_location), {0, 0}}; +const luaL_Reg InvRef::methods[] = { + luamethod(InvRef, is_empty), + luamethod(InvRef, get_size), + luamethod(InvRef, set_size), + luamethod(InvRef, get_width), + luamethod(InvRef, set_width), + luamethod(InvRef, get_stack), + luamethod(InvRef, set_stack), + luamethod(InvRef, get_list), + luamethod(InvRef, set_list), + luamethod(InvRef, get_lists), + luamethod(InvRef, set_lists), + luamethod(InvRef, add_item), + luamethod(InvRef, room_for_item), + luamethod(InvRef, contains_item), + luamethod(InvRef, remove_item), + luamethod(InvRef, get_location), + {0,0} +}; // get_inventory(location) int ModApiInventory::l_get_inventory(lua_State *L) @@ -479,7 +492,7 @@ int ModApiInventory::l_get_inventory(lua_State *L) std::string type = luaL_checkstring(L, -1); lua_pop(L, 1); - if (type == "node") { + if(type == "node"){ MAP_LOCK_REQUIRED; lua_getfield(L, 1, "pos"); v3s16 pos = check_v3s16(L, -1); @@ -509,6 +522,7 @@ int ModApiInventory::l_get_inventory(lua_State *L) lua_pushnil(L); return 1; // END NO_MAP_LOCK_REQUIRED; + } // create_detached_inventory_raw(name, [player_name]) @@ -517,8 +531,7 @@ int ModApiInventory::l_create_detached_inventory_raw(lua_State *L) NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); std::string player = readParam(L, 2, ""); - if (getServerInventoryMgr(L)->createDetachedInventory( - name, getServer(L)->idef(), player) != NULL) { + if (getServerInventoryMgr(L)->createDetachedInventory(name, getServer(L)->idef(), player) != NULL) { InventoryLocation loc; loc.setDetached(name); InvRef::create(L, loc); diff --git a/src/script/lua_api/l_inventory.h b/src/script/lua_api/l_inventory.h index fa8a77ae2..94f670c9d 100644 --- a/src/script/lua_api/l_inventory.h +++ b/src/script/lua_api/l_inventory.h @@ -30,8 +30,7 @@ class RemotePlayer; InvRef */ -class InvRef : public ModApiBase -{ +class InvRef : public ModApiBase { private: InventoryLocation m_loc; @@ -40,9 +39,10 @@ class InvRef : public ModApiBase static InvRef *checkobject(lua_State *L, int narg); - static Inventory *getinv(lua_State *L, InvRef *ref); + static Inventory* getinv(lua_State *L, InvRef *ref); - static InventoryList *getlist(lua_State *L, InvRef *ref, const char *listname); + static InventoryList* getlist(lua_State *L, InvRef *ref, + const char *listname); static void reportInventoryChange(lua_State *L, InvRef *ref); @@ -88,17 +88,16 @@ class InvRef : public ModApiBase // Returns the leftover stack static int l_add_item(lua_State *L); - // room_for_item(self, listname, itemstack or itemstring or table or nil) -> - // true/false Returns true if the item completely fits into the list + // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false + // Returns true if the item completely fits into the list static int l_room_for_item(lua_State *L); - // contains_item(self, listname, itemstack or itemstring or table or nil, - // [match_meta]) -> true/false Returns true if the list contains the given count - // of the given item name + // contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> true/false + // Returns true if the list contains the given count of the given item name static int l_contains_item(lua_State *L); - // remove_item(self, listname, itemstack or itemstring or table or nil) -> - // itemstack Returns the items that were actually removed + // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack + // Returns the items that were actually removed static int l_remove_item(lua_State *L); // get_location() -> location (like get_inventory(location)) @@ -117,8 +116,7 @@ class InvRef : public ModApiBase static void Register(lua_State *L); }; -class ModApiInventory : public ModApiBase -{ +class ModApiInventory : public ModApiBase { private: static int l_create_detached_inventory_raw(lua_State *L); diff --git a/src/script/lua_api/l_inventoryaction.cpp b/src/script/lua_api/l_inventoryaction.cpp index f65137465..f3037ba83 100644 --- a/src/script/lua_api/l_inventoryaction.cpp +++ b/src/script/lua_api/l_inventoryaction.cpp @@ -43,9 +43,9 @@ int LuaInventoryAction::l_apply(lua_State *L) std::ostringstream os(std::ios::binary); o->m_action->serialize(os); - + std::istringstream is(os.str(), std::ios_base::binary); - + InventoryAction *a = InventoryAction::deSerialize(is); getClient(L)->inventoryAction(a); @@ -69,30 +69,29 @@ int LuaInventoryAction::l_to(lua_State *L) int LuaInventoryAction::l_craft(lua_State *L) { LuaInventoryAction *o = checkobject(L, 1); - + if (o->m_action->getType() != IAction::Craft) return 0; - + std::string locStr; InventoryLocation loc; - + locStr = readParam(L, 2); - + try { loc.deSerialize(locStr); dynamic_cast(o->m_action)->craft_inv = loc; - } catch (SerializationError &) { - } - + } catch (SerializationError &) {} + return 0; } int LuaInventoryAction::l_set_count(lua_State *L) { LuaInventoryAction *o = checkobject(L, 1); - + s16 count = luaL_checkinteger(L, 2); - + switch (o->m_action->getType()) { case IAction::Move: ((IMoveAction *)o->m_action)->count = count; @@ -104,7 +103,7 @@ int LuaInventoryAction::l_set_count(lua_State *L) ((ICraftAction *)o->m_action)->count = count; break; } - + return 0; } @@ -128,25 +127,23 @@ LuaInventoryAction::~LuaInventoryAction() delete m_action; } -void LuaInventoryAction::readFullInventoryLocationInto( - lua_State *L, InventoryLocation *loc, std::string *list, s16 *index) +void LuaInventoryAction::readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, std::string *list, s16 *index) { try { loc->deSerialize(readParam(L, 2)); std::string l = readParam(L, 3); *list = l; *index = luaL_checkinteger(L, 4) - 1; - } catch (SerializationError &) { - } + } catch (SerializationError &) {} } int LuaInventoryAction::create_object(lua_State *L) { IAction type; std::string typeStr; - + typeStr = readParam(L, 1); - + if (typeStr == "move") type = IAction::Move; else if (typeStr == "drop") @@ -209,7 +206,11 @@ void LuaInventoryAction::Register(lua_State *L) } const char LuaInventoryAction::className[] = "InventoryAction"; -const luaL_Reg LuaInventoryAction::methods[] = {luamethod(LuaInventoryAction, apply), - luamethod(LuaInventoryAction, from), luamethod(LuaInventoryAction, to), - luamethod(LuaInventoryAction, craft), - luamethod(LuaInventoryAction, set_count), {0, 0}}; +const luaL_Reg LuaInventoryAction::methods[] = { + luamethod(LuaInventoryAction, apply), + luamethod(LuaInventoryAction, from), + luamethod(LuaInventoryAction, to), + luamethod(LuaInventoryAction, craft), + luamethod(LuaInventoryAction, set_count), + {0,0} +}; diff --git a/src/script/lua_api/l_inventoryaction.h b/src/script/lua_api/l_inventoryaction.h index a4cc6cbe5..c1a96d010 100644 --- a/src/script/lua_api/l_inventoryaction.h +++ b/src/script/lua_api/l_inventoryaction.h @@ -20,46 +20,44 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventorymanager.h" #include "lua_api/l_base.h" -#define GET_MOVE_ACTION \ - LuaInventoryAction *o = checkobject(L, 1); \ - if (o->m_action->getType() == IAction::Craft) \ - return 0; \ +#define GET_MOVE_ACTION \ + LuaInventoryAction *o = checkobject(L, 1); \ + if (o->m_action->getType() == IAction::Craft) \ + return 0; \ MoveAction *act = dynamic_cast(o->m_action); -class LuaInventoryAction : public ModApiBase -{ +class LuaInventoryAction : public ModApiBase { private: InventoryAction *m_action; - - static void readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, - std::string *list, s16 *index); - + + static void readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, std::string *list, s16 *index); + static const char className[]; static const luaL_Reg methods[]; - + // Exported functions - + // garbage collector static int gc_object(lua_State *L); // __tostring metamethod static int mt_tostring(lua_State *L); - + // apply(self) static int l_apply(lua_State *L); - + // from(self, location, list, index) static int l_from(lua_State *L); - + // to(self, location, list, index) static int l_to(lua_State *L); - + // craft(self, location) static int l_craft(lua_State *L); // set_count(self, count) static int l_set_count(lua_State *L); - + public: LuaInventoryAction(const IAction &type); ~LuaInventoryAction(); @@ -69,6 +67,6 @@ class LuaInventoryAction : public ModApiBase static int create_object(lua_State *L); // Not callable from Lua static int create(lua_State *L, const IAction &type); - static LuaInventoryAction *checkobject(lua_State *L, int narg); + static LuaInventoryAction* checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; diff --git a/src/script/lua_api/l_item.cpp b/src/script/lua_api/l_item.cpp index 9bbf9826b..bea7d122f 100644 --- a/src/script/lua_api/l_item.cpp +++ b/src/script/lua_api/l_item.cpp @@ -234,9 +234,12 @@ int LuaItemStack::l_to_table(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); const ItemStack &item = o->m_stack; - if (item.empty()) { + if(item.empty()) + { lua_pushnil(L); - } else { + } + else + { lua_newtable(L); lua_pushstring(L, item.name.c_str()); lua_setfield(L, -2, "name"); @@ -311,7 +314,8 @@ int LuaItemStack::l_get_definition(lua_State *L) lua_getfield(L, -1, "registered_items"); luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, item.name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) + { lua_pop(L, 1); lua_getfield(L, -1, "unknown"); } @@ -326,7 +330,8 @@ int LuaItemStack::l_get_tool_capabilities(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; - const ToolCapabilities &prop = item.getToolCapabilities(getGameDef(L)->idef()); + const ToolCapabilities &prop = + item.getToolCapabilities(getGameDef(L)->idef()); push_tool_capabilities(L, prop); return 1; } @@ -370,8 +375,8 @@ int LuaItemStack::l_item_fits(lua_State *L) ItemStack newitem = read_item(L, 2, getGameDef(L)->idef()); ItemStack restitem; bool fits = item.itemFits(newitem, &restitem, getGameDef(L)->idef()); - lua_pushboolean(L, fits); // first return value - create(L, restitem); // second return value + lua_pushboolean(L, fits); // first return value + create(L, restitem); // second return value return 2; } @@ -382,7 +387,7 @@ int LuaItemStack::l_take_item(lua_State *L) LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 takecount = 1; - if (!lua_isnone(L, 2)) + if(!lua_isnone(L, 2)) takecount = luaL_checkinteger(L, 2); ItemStack taken = item.takeItem(takecount); create(L, taken); @@ -396,22 +401,23 @@ int LuaItemStack::l_peek_item(lua_State *L) LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 peekcount = 1; - if (!lua_isnone(L, 2)) + if(!lua_isnone(L, 2)) peekcount = lua_tointeger(L, 2); ItemStack peekaboo = item.peekItem(peekcount); create(L, peekaboo); return 1; } -LuaItemStack::LuaItemStack(const ItemStack &item) : m_stack(item) +LuaItemStack::LuaItemStack(const ItemStack &item): + m_stack(item) { } -const ItemStack &LuaItemStack::getItem() const +const ItemStack& LuaItemStack::getItem() const { return m_stack; } -ItemStack &LuaItemStack::getItem() +ItemStack& LuaItemStack::getItem() { return m_stack; } @@ -470,32 +476,44 @@ void LuaItemStack::Register(lua_State *L) lua_pushcfunction(L, mt_tostring); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (ItemStack(itemstack or itemstring or table or nil)) lua_register(L, className, create_object); } const char LuaItemStack::className[] = "ItemStack"; -const luaL_Reg LuaItemStack::methods[] = {luamethod(LuaItemStack, is_empty), - luamethod(LuaItemStack, get_name), luamethod(LuaItemStack, set_name), - luamethod(LuaItemStack, get_count), luamethod(LuaItemStack, set_count), - luamethod(LuaItemStack, get_wear), luamethod(LuaItemStack, set_wear), - luamethod(LuaItemStack, get_meta), luamethod(LuaItemStack, get_metadata), - luamethod(LuaItemStack, set_metadata), - luamethod(LuaItemStack, get_description), luamethod(LuaItemStack, clear), - luamethod(LuaItemStack, replace), luamethod(LuaItemStack, to_string), - luamethod(LuaItemStack, to_table), luamethod(LuaItemStack, get_stack_max), - luamethod(LuaItemStack, get_free_space), - luamethod(LuaItemStack, is_known), - luamethod(LuaItemStack, get_definition), - luamethod(LuaItemStack, get_tool_capabilities), - luamethod(LuaItemStack, add_wear), luamethod(LuaItemStack, add_item), - luamethod(LuaItemStack, item_fits), luamethod(LuaItemStack, take_item), - luamethod(LuaItemStack, peek_item), {0, 0}}; +const luaL_Reg LuaItemStack::methods[] = { + luamethod(LuaItemStack, is_empty), + luamethod(LuaItemStack, get_name), + luamethod(LuaItemStack, set_name), + luamethod(LuaItemStack, get_count), + luamethod(LuaItemStack, set_count), + luamethod(LuaItemStack, get_wear), + luamethod(LuaItemStack, set_wear), + luamethod(LuaItemStack, get_meta), + luamethod(LuaItemStack, get_metadata), + luamethod(LuaItemStack, set_metadata), + luamethod(LuaItemStack, get_description), + luamethod(LuaItemStack, clear), + luamethod(LuaItemStack, replace), + luamethod(LuaItemStack, to_string), + luamethod(LuaItemStack, to_table), + luamethod(LuaItemStack, get_stack_max), + luamethod(LuaItemStack, get_free_space), + luamethod(LuaItemStack, is_known), + luamethod(LuaItemStack, get_definition), + luamethod(LuaItemStack, get_tool_capabilities), + luamethod(LuaItemStack, add_wear), + luamethod(LuaItemStack, add_item), + luamethod(LuaItemStack, item_fits), + luamethod(LuaItemStack, take_item), + luamethod(LuaItemStack, peek_item), + {0,0} +}; /* ItemDefinition @@ -509,13 +527,15 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) int table = 1; // Get the writable item and node definition managers from the server - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); - NodeDefManager *ndef = getGameDef(L)->getWritableNodeDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); + NodeDefManager *ndef = + getGameDef(L)->getWritableNodeDefManager(); // Check if name is defined std::string name; lua_getfield(L, table, "name"); - if (lua_isstring(L, -1)) { + if(lua_isstring(L, -1)){ name = readParam(L, -1); } else { throw LuaError("register_item_raw: name is not defined or not a string"); @@ -532,8 +552,8 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) // Default to having client-side placement prediction for nodes // ("" in item definition sets it off) - if (def.node_placement_prediction == "__default") { - if (def.type == ITEM_NODE) + if(def.node_placement_prediction == "__default"){ + if(def.type == ITEM_NODE) def.node_placement_prediction = name; else def.node_placement_prediction = ""; @@ -553,12 +573,13 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) content_t id = ndef->set(f.name, f); if (id > MAX_REGISTERED_CONTENT) { - throw LuaError("Number of registerable nodes (" + - itos(MAX_REGISTERED_CONTENT + 1) + - ") exceeded (" + name + ")"); + throw LuaError("Number of registerable nodes (" + + itos(MAX_REGISTERED_CONTENT+1) + + ") exceeded (" + name + ")"); } + } - + return 0; /* number of results */ } @@ -568,11 +589,13 @@ int ModApiItemMod::l_unregister_item_raw(lua_State *L) NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); // Unregister the node if (idef->get(name).type == ITEM_NODE) { - NodeDefManager *ndef = getGameDef(L)->getWritableNodeDefManager(); + NodeDefManager *ndef = + getGameDef(L)->getWritableNodeDefManager(); ndef->removeNode(name); } @@ -589,7 +612,8 @@ int ModApiItemMod::l_register_alias_raw(lua_State *L) std::string convert_to = luaL_checkstring(L, 2); // Get the writable item definition manager from the server - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); idef->registerAlias(name, convert_to); @@ -612,8 +636,8 @@ int ModApiItemMod::l_get_content_id(lua_State *L) content_t content_id; if (alias_name != name) { if (!ndef->getId(alias_name, content_id)) - throw LuaError("Unknown node: " + alias_name + " (from alias " + - name + ")"); + throw LuaError("Unknown node: " + alias_name + + " (from alias " + name + ")"); } else if (!ndef->getId(name, content_id)) { throw LuaError("Unknown node: " + name); } diff --git a/src/script/lua_api/l_item.h b/src/script/lua_api/l_item.h index 21110b83a..98744c071 100644 --- a/src/script/lua_api/l_item.h +++ b/src/script/lua_api/l_item.h @@ -20,10 +20,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include "lua_api/l_base.h" -#include "inventory.h" // ItemStack +#include "inventory.h" // ItemStack -class LuaItemStack : public ModApiBase -{ +class LuaItemStack : public ModApiBase { private: ItemStack m_stack; @@ -115,8 +114,8 @@ class LuaItemStack : public ModApiBase // Returns leftover item stack static int l_add_item(lua_State *L); - // item_fits(self, itemstack or itemstring or table or nil) -> true/false, - // itemstack First return value is true iff the new item fits fully into the stack + // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack + // First return value is true iff the new item fits fully into the stack // Second return value is the would-be-left-over item stack static int l_item_fits(lua_State *L); @@ -130,27 +129,26 @@ class LuaItemStack : public ModApiBase LuaItemStack(const ItemStack &item); ~LuaItemStack() = default; - const ItemStack &getItem() const; - ItemStack &getItem(); + const ItemStack& getItem() const; + ItemStack& getItem(); // LuaItemStack(itemstack or itemstring or table or nil) // Creates an LuaItemStack and leaves it on top of stack static int create_object(lua_State *L); // Not callable from Lua static int create(lua_State *L, const ItemStack &item); - static LuaItemStack *checkobject(lua_State *L, int narg); + static LuaItemStack* checkobject(lua_State *L, int narg); static void Register(lua_State *L); + }; -class ModApiItemMod : public ModApiBase -{ +class ModApiItemMod : public ModApiBase { private: static int l_register_item_raw(lua_State *L); static int l_unregister_item_raw(lua_State *L); static int l_register_alias_raw(lua_State *L); static int l_get_content_id(lua_State *L); static int l_get_name_from_content_id(lua_State *L); - public: static void Initialize(lua_State *L, int top); }; diff --git a/src/script/lua_api/l_itemstackmeta.cpp b/src/script/lua_api/l_itemstackmeta.cpp index 5a5c9934a..d1ba1bda4 100644 --- a/src/script/lua_api/l_itemstackmeta.cpp +++ b/src/script/lua_api/l_itemstackmeta.cpp @@ -26,17 +26,17 @@ with this program; if not, write to the Free Software Foundation, Inc., /* NodeMetaRef */ -ItemStackMetaRef *ItemStackMetaRef::checkobject(lua_State *L, int narg) +ItemStackMetaRef* ItemStackMetaRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(ItemStackMetaRef **)ud; // unbox pointer + return *(ItemStackMetaRef**)ud; // unbox pointer } -Metadata *ItemStackMetaRef::getmeta(bool auto_create) +Metadata* ItemStackMetaRef::getmeta(bool auto_create) { return &istack->metadata; } @@ -68,8 +68,7 @@ int ItemStackMetaRef::l_set_tool_capabilities(lua_State *L) } // garbage collector -int ItemStackMetaRef::gc_object(lua_State *L) -{ +int ItemStackMetaRef::gc_object(lua_State *L) { ItemStackMetaRef *o = *(ItemStackMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -80,7 +79,7 @@ int ItemStackMetaRef::gc_object(lua_State *L) void ItemStackMetaRef::create(lua_State *L, ItemStack *istack) { ItemStackMetaRef *o = new ItemStackMetaRef(istack); - // infostream<<"NodeMetaRef::create: o="<metadata.setToolCapabilities(caps); } - void clearToolCapabilities() { istack->metadata.clearToolCapabilities(); } + void clearToolCapabilities() + { + istack->metadata.clearToolCapabilities(); + } // Exported functions static int l_set_tool_capabilities(lua_State *L); // garbage collector static int gc_object(lua_State *L); - public: - ItemStackMetaRef(ItemStack *istack) : istack(istack) {} + ItemStackMetaRef(ItemStack *istack): istack(istack) {} ~ItemStackMetaRef() = default; // Creates an ItemStackMetaRef and leaves it on top of stack diff --git a/src/script/lua_api/l_localplayer.cpp b/src/script/lua_api/l_localplayer.cpp index 789b3a3f0..e40dd7b37 100644 --- a/src/script/lua_api/l_localplayer.cpp +++ b/src/script/lua_api/l_localplayer.cpp @@ -66,10 +66,10 @@ int LuaLocalPlayer::l_get_velocity(lua_State *L) int LuaLocalPlayer::l_set_velocity(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + v3f pos = checkFloatPos(L, 2); player->setSpeed(pos); - + return 0; } @@ -91,7 +91,7 @@ int LuaLocalPlayer::l_set_yaw(lua_State *L) g_game->cam_view.camera_yaw = yaw; g_game->cam_view_target.camera_yaw = yaw; } - + return 0; } @@ -125,7 +125,7 @@ int LuaLocalPlayer::l_set_wield_index(lua_State *L) { LocalPlayer *player = getobject(L, 1); u32 index = luaL_checkinteger(L, 2) - 1; - + player->setWieldIndex(index); g_game->processItemSelection(&g_game->runData.new_playeritem); ItemStack selected_item, hand_item; @@ -266,7 +266,7 @@ int LuaLocalPlayer::l_get_control(lua_State *L) LocalPlayer *player = getobject(L, 1); const PlayerControl &c = player->getPlayerControl(); - auto set = [L](const char *name, bool value) { + auto set = [L] (const char *name, bool value) { lua_pushboolean(L, value); lua_setfield(L, -2, name); }; @@ -308,7 +308,7 @@ int LuaLocalPlayer::l_get_pos(lua_State *L) int LuaLocalPlayer::l_set_pos(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + v3f pos = checkFloatPos(L, 2); player->setPosition(pos); getClient(L)->sendPlayerPos(); @@ -522,10 +522,13 @@ void LuaLocalPlayer::Register(lua_State *L) } const char LuaLocalPlayer::className[] = "LocalPlayer"; -const luaL_Reg LuaLocalPlayer::methods[] = {luamethod(LuaLocalPlayer, get_velocity), +const luaL_Reg LuaLocalPlayer::methods[] = { + luamethod(LuaLocalPlayer, get_velocity), luamethod(LuaLocalPlayer, set_velocity), - luamethod(LuaLocalPlayer, get_yaw), luamethod(LuaLocalPlayer, set_yaw), - luamethod(LuaLocalPlayer, get_hp), luamethod(LuaLocalPlayer, get_name), + luamethod(LuaLocalPlayer, get_yaw), + luamethod(LuaLocalPlayer, set_yaw), + luamethod(LuaLocalPlayer, get_hp), + luamethod(LuaLocalPlayer, get_name), luamethod(LuaLocalPlayer, get_wield_index), luamethod(LuaLocalPlayer, set_wield_index), luamethod(LuaLocalPlayer, get_wielded_item), @@ -544,14 +547,18 @@ const luaL_Reg LuaLocalPlayer::methods[] = {luamethod(LuaLocalPlayer, get_veloci luamethod(LuaLocalPlayer, get_last_look_vertical), // luamethod(LuaLocalPlayer, get_control), - luamethod(LuaLocalPlayer, get_breath), luamethod(LuaLocalPlayer, get_pos), + luamethod(LuaLocalPlayer, get_breath), + luamethod(LuaLocalPlayer, get_pos), luamethod(LuaLocalPlayer, set_pos), luamethod(LuaLocalPlayer, get_movement_acceleration), luamethod(LuaLocalPlayer, get_movement_speed), luamethod(LuaLocalPlayer, get_movement), luamethod(LuaLocalPlayer, get_armor_groups), - luamethod(LuaLocalPlayer, hud_add), luamethod(LuaLocalPlayer, hud_remove), - luamethod(LuaLocalPlayer, hud_change), luamethod(LuaLocalPlayer, hud_get), + luamethod(LuaLocalPlayer, hud_add), + luamethod(LuaLocalPlayer, hud_remove), + luamethod(LuaLocalPlayer, hud_change), + luamethod(LuaLocalPlayer, hud_get), luamethod(LuaLocalPlayer, get_object), - {0, 0}}; + {0, 0} +}; diff --git a/src/script/lua_api/l_mainmenu.cpp b/src/script/lua_api/l_mainmenu.cpp index 78a33b755..f32c477c2 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -41,6 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/renderingengine.h" #include "network/networkprotocol.h" + /******************************************************************************/ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) { @@ -48,39 +49,39 @@ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) return ""; return luaL_checkstring(L, -1); } /******************************************************************************/ -int ModApiMainMenu::getIntegerData(lua_State *L, std::string name, bool &valid) +int ModApiMainMenu::getIntegerData(lua_State *L, std::string name,bool& valid) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) { valid = false; return -1; - } + } valid = true; return luaL_checkinteger(L, -1); } /******************************************************************************/ -int ModApiMainMenu::getBoolData(lua_State *L, std::string name, bool &valid) +int ModApiMainMenu::getBoolData(lua_State *L, std::string name,bool& valid) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) { valid = false; return false; - } + } valid = true; return readParam(L, -1); @@ -89,13 +90,13 @@ int ModApiMainMenu::getBoolData(lua_State *L, std::string name, bool &valid) /******************************************************************************/ int ModApiMainMenu::l_update_formspec(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); if (engine->m_startgame) return 0; - // read formspec + //read formspec std::string formspec(luaL_checkstring(L, 1)); if (engine->m_formspecgui != 0) { @@ -123,28 +124,28 @@ int ModApiMainMenu::l_set_formspec_prepend(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_start(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - // update c++ gamedata from lua table + //update c++ gamedata from lua table bool valid = false; MainMenuData *data = engine->m_data; - data->selected_world = getIntegerData(L, "selected_world", valid) - 1; - data->simple_singleplayer_mode = getBoolData(L, "singleplayer", valid); + data->selected_world = getIntegerData(L, "selected_world",valid) -1; + data->simple_singleplayer_mode = getBoolData(L,"singleplayer",valid); data->do_reconnect = getBoolData(L, "do_reconnect", valid); if (!data->do_reconnect) { - data->name = getTextData(L, "playername"); - data->password = getTextData(L, "password"); - data->address = getTextData(L, "address"); - data->port = getTextData(L, "port"); + data->name = getTextData(L,"playername"); + data->password = getTextData(L,"password"); + data->address = getTextData(L,"address"); + data->port = getTextData(L,"port"); } - data->serverdescription = getTextData(L, "serverdescription"); - data->servername = getTextData(L, "servername"); + data->serverdescription = getTextData(L,"serverdescription"); + data->servername = getTextData(L,"servername"); - // close menu next time + //close menu next time engine->m_startgame = true; return 0; } @@ -152,7 +153,7 @@ int ModApiMainMenu::l_start(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_close(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); engine->m_kill = true; @@ -162,14 +163,14 @@ int ModApiMainMenu::l_close(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_set_background(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string backgroundlevel(luaL_checkstring(L, 1)); std::string texturename(luaL_checkstring(L, 2)); bool tile_image = false; - bool retval = false; + bool retval = false; unsigned int minsize = 16; if (!lua_isnone(L, 3)) { @@ -181,36 +182,36 @@ int ModApiMainMenu::l_set_background(lua_State *L) } if (backgroundlevel == "background") { - retval |= engine->setTexture( - TEX_LAYER_BACKGROUND, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_BACKGROUND, texturename, + tile_image, minsize); } if (backgroundlevel == "overlay") { - retval |= engine->setTexture( - TEX_LAYER_OVERLAY, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_OVERLAY, texturename, + tile_image, minsize); } if (backgroundlevel == "header") { - retval |= engine->setTexture( - TEX_LAYER_HEADER, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_HEADER, texturename, + tile_image, minsize); } if (backgroundlevel == "footer") { - retval |= engine->setTexture( - TEX_LAYER_FOOTER, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_FOOTER, texturename, + tile_image, minsize); } - lua_pushboolean(L, retval); + lua_pushboolean(L,retval); return 1; } /******************************************************************************/ int ModApiMainMenu::l_set_clouds(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - bool value = readParam(L, 1); + bool value = readParam(L,1); engine->m_clouds_enabled = value; @@ -227,7 +228,7 @@ int ModApiMainMenu::l_get_textlist_index(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_table_index(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string tablename(luaL_checkstring(L, 1)); @@ -251,20 +252,20 @@ int ModApiMainMenu::l_get_worlds(lua_State *L) unsigned int index = 1; for (const WorldSpec &world : worlds) { - lua_pushnumber(L, index); + lua_pushnumber(L,index); lua_newtable(L); int top_lvl2 = lua_gettop(L); - lua_pushstring(L, "path"); + lua_pushstring(L,"path"); lua_pushstring(L, world.path.c_str()); lua_settable(L, top_lvl2); - lua_pushstring(L, "name"); + lua_pushstring(L,"name"); lua_pushstring(L, world.name.c_str()); lua_settable(L, top_lvl2); - lua_pushstring(L, "gameid"); + lua_pushstring(L,"gameid"); lua_pushstring(L, world.gameid.c_str()); lua_settable(L, top_lvl2); @@ -285,7 +286,7 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) std::vector servers; - if (listtype == "online") { + if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); @@ -304,8 +305,8 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) if (!server["clients"].asString().empty()) { std::string clients_raw = server["clients"].asString(); - char *endptr = 0; - int numbervalue = strtol(clients_raw.c_str(), &endptr, 10); + char* endptr = 0; + int numbervalue = strtol(clients_raw.c_str(), &endptr,10); if ((!clients_raw.empty()) && (*endptr == 0)) { lua_pushstring(L, "clients"); @@ -317,8 +318,8 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) if (!server["clients_max"].asString().empty()) { std::string clients_max_raw = server["clients_max"].asString(); - char *endptr = 0; - int numbervalue = strtol(clients_max_raw.c_str(), &endptr, 10); + char* endptr = 0; + int numbervalue = strtol(clients_max_raw.c_str(), &endptr,10); if ((!clients_max_raw.empty()) && (*endptr == 0)) { lua_pushstring(L, "clients_max"); @@ -449,22 +450,25 @@ int ModApiMainMenu::l_delete_favorite(lua_State *L) std::string listtype = "local"; - if (!lua_isnone(L, 2)) { - listtype = luaL_checkstring(L, 2); + if (!lua_isnone(L,2)) { + listtype = luaL_checkstring(L,2); } - if ((listtype != "local") && (listtype != "online")) + if ((listtype != "local") && + (listtype != "online")) return 0; - if (listtype == "online") { + + if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); } - int fav_idx = luaL_checkinteger(L, 1) - 1; + int fav_idx = luaL_checkinteger(L,1) -1; - if ((fav_idx >= 0) && (fav_idx < (int)servers.size())) { + if ((fav_idx >= 0) && + (fav_idx < (int) servers.size())) { ServerList::deleteEntry(servers[fav_idx]); } @@ -486,37 +490,37 @@ int ModApiMainMenu::l_get_games(lua_State *L) lua_newtable(L); int top_lvl2 = lua_gettop(L); - lua_pushstring(L, "id"); - lua_pushstring(L, game.id.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "id"); + lua_pushstring(L, game.id.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "path"); - lua_pushstring(L, game.path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "path"); + lua_pushstring(L, game.path.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "type"); - lua_pushstring(L, "game"); - lua_settable(L, top_lvl2); + lua_pushstring(L, "type"); + lua_pushstring(L, "game"); + lua_settable(L, top_lvl2); - lua_pushstring(L, "gamemods_path"); - lua_pushstring(L, game.gamemods_path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "gamemods_path"); + lua_pushstring(L, game.gamemods_path.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "name"); - lua_pushstring(L, game.name.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "name"); + lua_pushstring(L, game.name.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "author"); - lua_pushstring(L, game.author.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "author"); + lua_pushstring(L, game.author.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "release"); + lua_pushstring(L, "release"); lua_pushinteger(L, game.release); - lua_settable(L, top_lvl2); + lua_settable(L, top_lvl2); - lua_pushstring(L, "menuicon_path"); - lua_pushstring(L, game.menuicon_path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "menuicon_path"); + lua_pushstring(L, game.menuicon_path.c_str()); + lua_settable(L, top_lvl2); lua_pushstring(L, "addon_mods_paths"); lua_newtable(L); @@ -525,7 +529,7 @@ int ModApiMainMenu::l_get_games(lua_State *L) for (const std::string &addon_mods_path : game.addon_mods_paths) { lua_pushnumber(L, internal_index); lua_pushstring(L, addon_mods_path.c_str()); - lua_settable(L, table2); + lua_settable(L, table2); internal_index++; } lua_settable(L, top_lvl2); @@ -594,11 +598,13 @@ int ModApiMainMenu::l_get_content_info(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_show_keys_menu(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(), - engine->m_parent, -1, engine->m_menumanager, + engine->m_parent, + -1, + engine->m_menumanager, engine->m_texture_source); kmenu->drop(); return 0; @@ -607,14 +613,17 @@ int ModApiMainMenu::l_show_keys_menu(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_create_world(lua_State *L) { - const char *name = luaL_checkstring(L, 1); - int gameidx = luaL_checkinteger(L, 2) - 1; + const char *name = luaL_checkstring(L, 1); + int gameidx = luaL_checkinteger(L,2) -1; - std::string path = porting::path_user + DIR_DELIM "worlds" + DIR_DELIM + name; + std::string path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + + name; std::vector games = getAvailableGames(); - if ((gameidx >= 0) && (gameidx < (int)games.size())) { + if ((gameidx >= 0) && + (gameidx < (int) games.size())) { // Create world if it doesn't exist if (!loadGameConfAndInitWorld(path, games[gameidx])) { @@ -633,7 +642,7 @@ int ModApiMainMenu::l_delete_world(lua_State *L) { int world_id = luaL_checkinteger(L, 1) - 1; std::vector worlds = getAvailableWorlds(); - if (world_id < 0 || world_id >= (int)worlds.size()) { + if (world_id < 0 || world_id >= (int) worlds.size()) { lua_pushstring(L, "Invalid world index"); return 1; } @@ -648,12 +657,12 @@ int ModApiMainMenu::l_delete_world(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_set_topleft_text(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string text; - if (!lua_isnone(L, 1) && !lua_isnil(L, 1)) + if (!lua_isnone(L,1) && !lua_isnil(L,1)) text = luaL_checkstring(L, 1); engine->setTopleftText(text); @@ -676,11 +685,12 @@ int ModApiMainMenu::l_get_mapgen_names(lua_State *L) return 1; } + /******************************************************************************/ int ModApiMainMenu::l_get_modpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); + porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } @@ -689,7 +699,7 @@ int ModApiMainMenu::l_get_modpath(lua_State *L) int ModApiMainMenu::l_get_clientmodpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); + porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } @@ -698,7 +708,7 @@ int ModApiMainMenu::l_get_clientmodpath(lua_State *L) int ModApiMainMenu::l_get_gamepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "games" + DIR_DELIM); + porting::path_user + DIR_DELIM + "games" + DIR_DELIM); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -707,7 +717,7 @@ int ModApiMainMenu::l_get_gamepath(lua_State *L) int ModApiMainMenu::l_get_texturepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "textures"); + porting::path_user + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -715,7 +725,7 @@ int ModApiMainMenu::l_get_texturepath(lua_State *L) int ModApiMainMenu::l_get_texturepath_share(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_share + DIR_DELIM + "textures"); + porting::path_share + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -727,8 +737,7 @@ int ModApiMainMenu::l_get_cache_path(lua_State *L) } /******************************************************************************/ -int ModApiMainMenu::l_create_dir(lua_State *L) -{ +int ModApiMainMenu::l_create_dir(lua_State *L) { const char *path = luaL_checkstring(L, 1); if (ModApiMainMenu::mayModifyPath(path)) { @@ -759,37 +768,38 @@ int ModApiMainMenu::l_delete_dir(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_copy_dir(lua_State *L) { - const char *source = luaL_checkstring(L, 1); - const char *destination = luaL_checkstring(L, 2); + const char *source = luaL_checkstring(L, 1); + const char *destination = luaL_checkstring(L, 2); bool keep_source = true; - if ((!lua_isnone(L, 3)) && (!lua_isnil(L, 3))) { - keep_source = readParam(L, 3); + if ((!lua_isnone(L,3)) && + (!lua_isnil(L,3))) { + keep_source = readParam(L,3); } std::string absolute_destination = fs::RemoveRelativePathComponents(destination); std::string absolute_source = fs::RemoveRelativePathComponents(source); if ((ModApiMainMenu::mayModifyPath(absolute_destination))) { - bool retval = fs::CopyDir(absolute_source, absolute_destination); + bool retval = fs::CopyDir(absolute_source,absolute_destination); if (retval && (!keep_source)) { retval &= fs::RecursiveDelete(absolute_source); } - lua_pushboolean(L, retval); + lua_pushboolean(L,retval); return 1; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_extract_zip(lua_State *L) { - const char *zipfile = luaL_checkstring(L, 1); - const char *destination = luaL_checkstring(L, 2); + const char *zipfile = luaL_checkstring(L, 1); + const char *destination = luaL_checkstring(L, 2); std::string absolute_destination = fs::RemoveRelativePathComponents(destination); @@ -799,7 +809,7 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) io::IFileSystem *fs = RenderingEngine::get_filesystem(); if (!fs->addFileArchive(zipfile, false, false, io::EFAT_ZIP)) { - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } @@ -808,36 +818,33 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) /**********************************************************************/ /* WARNING this is not threadsafe!! */ /**********************************************************************/ - io::IFileArchive *opened_zip = - fs->getFileArchive(fs->getFileArchiveCount() - 1); + io::IFileArchive* opened_zip = + fs->getFileArchive(fs->getFileArchiveCount()-1); - const io::IFileList *files_in_zip = opened_zip->getFileList(); + const io::IFileList* files_in_zip = opened_zip->getFileList(); unsigned int number_of_files = files_in_zip->getFileCount(); - for (unsigned int i = 0; i < number_of_files; i++) { + for (unsigned int i=0; i < number_of_files; i++) { std::string fullpath = destination; fullpath += DIR_DELIM; fullpath += files_in_zip->getFullFileName(i).c_str(); std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath); if (!files_in_zip->isDirectory(i)) { - if (!fs::PathExists(fullpath_dir) && - !fs::CreateAllDirs(fullpath_dir)) { - fs->removeFileArchive( - fs->getFileArchiveCount() - 1); - lua_pushboolean(L, false); + if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) { + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } - io::IReadFile *toread = opened_zip->createAndOpenFile(i); + io::IReadFile* toread = opened_zip->createAndOpenFile(i); - FILE *targetfile = fopen(fullpath.c_str(), "wb"); + FILE *targetfile = fopen(fullpath.c_str(),"wb"); if (targetfile == NULL) { - fs->removeFileArchive( - fs->getFileArchiveCount() - 1); - lua_pushboolean(L, false); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } @@ -846,18 +853,14 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) while (total_read < toread->getSize()) { - unsigned int bytes_read = toread->read( - read_buffer, sizeof(read_buffer)); - if ((bytes_read == 0) || - (fwrite(read_buffer, 1, - bytes_read, - targetfile) != - bytes_read)) { + unsigned int bytes_read = + toread->read(read_buffer,sizeof(read_buffer)); + if ((bytes_read == 0 ) || + (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read)) + { fclose(targetfile); - fs->removeFileArchive( - fs->getFileArchiveCount() - - 1); - lua_pushboolean(L, false); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } total_read += bytes_read; @@ -865,24 +868,25 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) fclose(targetfile); } + } - fs->removeFileArchive(fs->getFileArchiveCount() - 1); - lua_pushboolean(L, true); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,true); return 1; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_mainmenu_path(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - lua_pushstring(L, engine->getScriptDir().c_str()); + lua_pushstring(L,engine->getScriptDir().c_str()); return 1; } @@ -892,31 +896,25 @@ bool ModApiMainMenu::mayModifyPath(const std::string &path) if (fs::PathStartsWith(path, fs::TempPath())) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + - DIR_DELIM "games"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "games"))) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + - DIR_DELIM "mods"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "mods"))) return true; - if (fs::PathStartsWith(path, - fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM "textures"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "textures"))) return true; - if (fs::PathStartsWith(path, - fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM "worlds"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "worlds"))) return true; - if (fs::PathStartsWith( - path, fs::RemoveRelativePathComponents(porting::path_cache))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_cache))) return true; return false; } + /******************************************************************************/ int ModApiMainMenu::l_may_modify_path(lua_State *L) { @@ -929,16 +927,21 @@ int ModApiMainMenu::l_may_modify_path(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - const char *formname = luaL_checkstring(L, 1); - const char *title = luaL_checkstring(L, 2); + const char *formname= luaL_checkstring(L, 1); + const char *title = luaL_checkstring(L, 2); bool is_file_select = readParam(L, 3); - GUIFileSelectMenu *fileOpenMenu = new GUIFileSelectMenu( - RenderingEngine::get_gui_env(), engine->m_parent, -1, - engine->m_menumanager, title, formname, is_file_select); + GUIFileSelectMenu* fileOpenMenu = + new GUIFileSelectMenu(RenderingEngine::get_gui_env(), + engine->m_parent, + -1, + engine->m_menumanager, + title, + formname, + is_file_select); fileOpenMenu->setTextDest(engine->m_buttonhandler); fileOpenMenu->drop(); return 0; @@ -947,36 +950,34 @@ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_download_file(lua_State *L) { - const char *url = luaL_checkstring(L, 1); + const char *url = luaL_checkstring(L, 1); const char *target = luaL_checkstring(L, 2); - // check path + //check path std::string absolute_destination = fs::RemoveRelativePathComponents(target); if (ModApiMainMenu::mayModifyPath(absolute_destination)) { - if (GUIEngine::downloadFile(url, absolute_destination)) { - lua_pushboolean(L, true); + if (GUIEngine::downloadFile(url,absolute_destination)) { + lua_pushboolean(L,true); return 1; } } else { errorstream << "DOWNLOAD denied: " << absolute_destination - << " isn't a allowed path" << std::endl; + << " isn't a allowed path" << std::endl; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_video_drivers(lua_State *L) { - std::vector drivers = - RenderingEngine::getSupportedVideoDrivers(); + std::vector drivers = RenderingEngine::getSupportedVideoDrivers(); lua_newtable(L); for (u32 i = 0; i != drivers.size(); i++) { - const char *name = RenderingEngine::getVideoDriverName(drivers[i]); - const char *fname = - RenderingEngine::getVideoDriverFriendlyName(drivers[i]); + const char *name = RenderingEngine::getVideoDriverName(drivers[i]); + const char *fname = RenderingEngine::getVideoDriverFriendlyName(drivers[i]); lua_newtable(L); lua_pushstring(L, name); @@ -993,8 +994,8 @@ int ModApiMainMenu::l_get_video_drivers(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_video_modes(lua_State *L) { - std::vector> videomodes = - RenderingEngine::getSupportedVideoModes(); + std::vector > videomodes + = RenderingEngine::getSupportedVideoModes(); lua_newtable(L); for (u32 i = 0; i != videomodes.size(); i++) { @@ -1026,24 +1027,24 @@ int ModApiMainMenu::l_get_screen_info(lua_State *L) { lua_newtable(L); int top = lua_gettop(L); - lua_pushstring(L, "density"); - lua_pushnumber(L, RenderingEngine::getDisplayDensity()); + lua_pushstring(L,"density"); + lua_pushnumber(L,RenderingEngine::getDisplayDensity()); lua_settable(L, top); - lua_pushstring(L, "display_width"); - lua_pushnumber(L, RenderingEngine::getDisplaySize().X); + lua_pushstring(L,"display_width"); + lua_pushnumber(L,RenderingEngine::getDisplaySize().X); lua_settable(L, top); - lua_pushstring(L, "display_height"); - lua_pushnumber(L, RenderingEngine::getDisplaySize().Y); + lua_pushstring(L,"display_height"); + lua_pushnumber(L,RenderingEngine::getDisplaySize().Y); lua_settable(L, top); const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - lua_pushstring(L, "window_width"); + lua_pushstring(L,"window_width"); lua_pushnumber(L, window_size.X); lua_settable(L, top); - lua_pushstring(L, "window_height"); + lua_pushstring(L,"window_height"); lua_pushnumber(L, window_size.Y); lua_settable(L, top); return 1; @@ -1073,12 +1074,12 @@ int ModApiMainMenu::l_open_url(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_do_async_callback(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); size_t func_length, param_length; - const char *serialized_func_raw = luaL_checklstring(L, 1, &func_length); + const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length); - const char *serialized_param_raw = luaL_checklstring(L, 2, ¶m_length); + const char* serialized_param_raw = luaL_checklstring(L, 2, ¶m_length); sanity_check(serialized_func_raw != NULL); sanity_check(serialized_param_raw != NULL); @@ -1152,8 +1153,8 @@ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); - // API_FCT(extract_zip); //TODO remove dependency to GuiEngine + //API_FCT(extract_zip); //TODO remove dependency to GuiEngine API_FCT(may_modify_path); API_FCT(download_file); - // API_FCT(gettext); (gettext lib isn't threadsafe) + //API_FCT(gettext); (gettext lib isn't threadsafe) } diff --git a/src/script/lua_api/l_mainmenu.h b/src/script/lua_api/l_mainmenu.h index c5875e797..5a16b3bfe 100644 --- a/src/script/lua_api/l_mainmenu.h +++ b/src/script/lua_api/l_mainmenu.h @@ -24,7 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class AsyncEngine; /** Implementation of lua api support for mainmenu */ -class ModApiMainMenu : public ModApiBase +class ModApiMainMenu: public ModApiBase { private: @@ -42,7 +42,7 @@ class ModApiMainMenu : public ModApiBase * @param name name of variable to read * @return integer value of requested variable */ - static int getIntegerData(lua_State *L, std::string name, bool &valid); + static int getIntegerData(lua_State *L, std::string name,bool& valid); /** * read a bool variable from gamedata table within lua stack @@ -50,7 +50,7 @@ class ModApiMainMenu : public ModApiBase * @param name name of variable to read * @return bool value of requested variable */ - static int getBoolData(lua_State *L, std::string name, bool &valid); + static int getBoolData(lua_State *L, std::string name,bool& valid); /** * Checks if a path may be modified. Paths in the temp directory or the user @@ -60,7 +60,7 @@ class ModApiMainMenu : public ModApiBase */ static bool mayModifyPath(const std::string &path); - // api calls + //api calls static int l_start(lua_State *L); @@ -80,13 +80,13 @@ class ModApiMainMenu : public ModApiBase static int l_gettext(lua_State *L); - // packages + //packages static int l_get_games(lua_State *L); static int l_get_content_info(lua_State *L); - // gui + //gui static int l_show_keys_menu(lua_State *L); @@ -108,7 +108,7 @@ class ModApiMainMenu : public ModApiBase static int l_get_screen_info(lua_State *L); - // filesystem + //filesystem static int l_get_mainmenu_path(lua_State *L); @@ -140,7 +140,7 @@ class ModApiMainMenu : public ModApiBase static int l_get_video_modes(lua_State *L); - // version compatibility + //version compatibility static int l_get_min_supp_proto(lua_State *L); static int l_get_max_supp_proto(lua_State *L); @@ -148,10 +148,12 @@ class ModApiMainMenu : public ModApiBase // other static int l_open_url(lua_State *L); + // async static int l_do_async_callback(lua_State *L); public: + /** * initialize this API module * @param L lua stack to initialize @@ -160,4 +162,5 @@ class ModApiMainMenu : public ModApiBase static void Initialize(lua_State *L, int top); static void InitializeAsync(lua_State *L, int top); + }; diff --git a/src/script/lua_api/l_mapgen.cpp b/src/script/lua_api/l_mapgen.cpp index d52191a29..834938e56 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -37,73 +37,81 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "log.h" -struct EnumString ModApiMapgen::es_BiomeTerrainType[] = { - {BIOMETYPE_NORMAL, "normal"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_BiomeTerrainType[] = +{ + {BIOMETYPE_NORMAL, "normal"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_DecorationType[] = { - {DECO_SIMPLE, "simple"}, - {DECO_SCHEMATIC, "schematic"}, - {DECO_LSYSTEM, "lsystem"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_DecorationType[] = +{ + {DECO_SIMPLE, "simple"}, + {DECO_SCHEMATIC, "schematic"}, + {DECO_LSYSTEM, "lsystem"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_MapgenObject[] = { - {MGOBJ_VMANIP, "voxelmanip"}, - {MGOBJ_HEIGHTMAP, "heightmap"}, - {MGOBJ_BIOMEMAP, "biomemap"}, - {MGOBJ_HEATMAP, "heatmap"}, - {MGOBJ_HUMIDMAP, "humiditymap"}, - {MGOBJ_GENNOTIFY, "gennotify"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_MapgenObject[] = +{ + {MGOBJ_VMANIP, "voxelmanip"}, + {MGOBJ_HEIGHTMAP, "heightmap"}, + {MGOBJ_BIOMEMAP, "biomemap"}, + {MGOBJ_HEATMAP, "heatmap"}, + {MGOBJ_HUMIDMAP, "humiditymap"}, + {MGOBJ_GENNOTIFY, "gennotify"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_OreType[] = { - {ORE_SCATTER, "scatter"}, - {ORE_SHEET, "sheet"}, - {ORE_PUFF, "puff"}, - {ORE_BLOB, "blob"}, - {ORE_VEIN, "vein"}, - {ORE_STRATUM, "stratum"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_OreType[] = +{ + {ORE_SCATTER, "scatter"}, + {ORE_SHEET, "sheet"}, + {ORE_PUFF, "puff"}, + {ORE_BLOB, "blob"}, + {ORE_VEIN, "vein"}, + {ORE_STRATUM, "stratum"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_Rotation[] = { - {ROTATE_0, "0"}, - {ROTATE_90, "90"}, - {ROTATE_180, "180"}, - {ROTATE_270, "270"}, - {ROTATE_RAND, "random"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_Rotation[] = +{ + {ROTATE_0, "0"}, + {ROTATE_90, "90"}, + {ROTATE_180, "180"}, + {ROTATE_270, "270"}, + {ROTATE_RAND, "random"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_SchematicFormatType[] = { - {SCHEM_FMT_HANDLE, "handle"}, - {SCHEM_FMT_MTS, "mts"}, - {SCHEM_FMT_LUA, "lua"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_SchematicFormatType[] = +{ + {SCHEM_FMT_HANDLE, "handle"}, + {SCHEM_FMT_MTS, "mts"}, + {SCHEM_FMT_LUA, "lua"}, + {0, NULL}, }; ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr); -Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr); +Biome *get_or_load_biome(lua_State *L, int index, + BiomeManager *biomemgr); Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef); -size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, - std::unordered_set *biome_id_list); +size_t get_biome_list(lua_State *L, int index, + BiomeManager *biomemgr, std::unordered_set *biome_id_list); -Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, - StringMap *replace_names); +Schematic *get_or_load_schematic(lua_State *L, int index, + SchematicManager *schemmgr, StringMap *replace_names); Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names); -Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names); -bool read_schematic_def(lua_State *L, int index, Schematic *schem, - std::vector *names); + StringMap *replace_names); +Schematic *load_schematic_from_def(lua_State *L, int index, + const NodeDefManager *ndef, StringMap *replace_names); +bool read_schematic_def(lua_State *L, int index, + Schematic *schem, std::vector *names); bool read_deco_simple(lua_State *L, DecoSimple *deco); bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco); + /////////////////////////////////////////////////////////////////////////////// ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr) @@ -124,8 +132,8 @@ ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr) /////////////////////////////////////////////////////////////////////////////// -Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, - StringMap *replace_names) +Schematic *get_or_load_schematic(lua_State *L, int index, + SchematicManager *schemmgr, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -134,7 +142,8 @@ Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *sche if (schem) return schem; - schem = load_schematic(L, index, schemmgr->getNodeDef(), replace_names); + schem = load_schematic(L, index, schemmgr->getNodeDef(), + replace_names); if (!schem) return NULL; @@ -146,8 +155,9 @@ Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *sche return schem; } + Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names) + StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -155,7 +165,8 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, Schematic *schem = NULL; if (lua_istable(L, index)) { - schem = load_schematic_from_def(L, index, ndef, replace_names); + schem = load_schematic_from_def(L, index, ndef, + replace_names); if (!schem) { delete schem; return NULL; @@ -167,10 +178,10 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, std::string filepath = lua_tostring(L, index); if (!fs::IsPathAbsolute(filepath)) - filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + - filepath; + filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath; - if (!schem->loadSchematicFromFile(filepath, ndef, replace_names)) { + if (!schem->loadSchematicFromFile(filepath, ndef, + replace_names)) { delete schem; return NULL; } @@ -179,8 +190,9 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, return schem; } -Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names) + +Schematic *load_schematic_from_def(lua_State *L, int index, + const NodeDefManager *ndef, StringMap *replace_names) { Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL); @@ -195,8 +207,7 @@ Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager if (replace_names) { for (size_t i = 0; i != num_nodes; i++) { - StringMap::iterator it = - replace_names->find(schem->m_nodenames[i]); + StringMap::iterator it = replace_names->find(schem->m_nodenames[i]); if (it != replace_names->end()) schem->m_nodenames[i] = it->second; } @@ -208,8 +219,9 @@ Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager return schem; } -bool read_schematic_def(lua_State *L, int index, Schematic *schem, - std::vector *names) + +bool read_schematic_def(lua_State *L, int index, + Schematic *schem, std::vector *names) { if (!lua_istable(L, index)) return false; @@ -239,21 +251,19 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, //// Read name std::string name; if (!getstringfield(L, -1, "name", name)) - throw LuaError("Schematic data definition with missing name " - "field"); + throw LuaError("Schematic data definition with missing name field"); //// Read param1/prob u8 param1; if (!getintfield(L, -1, "param1", param1) && - !getintfield(L, -1, "prob", param1)) + !getintfield(L, -1, "prob", param1)) param1 = MTSCHEM_PROB_ALWAYS_OLD; //// Read param2 u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping - std::unordered_map::iterator it = - name_id_map.find(name); + std::unordered_map::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; @@ -274,14 +284,14 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " - "nodes provided in raw schematic data (got " - << i << ", expected " << numnodes << ")." << std::endl; + "nodes provided in raw schematic data (got " << i << + ", expected " << numnodes << ")." << std::endl; return false; } //// Get Y-slice probability values (if present) schem->slice_probs = new u8[size.Y]; - for (i = 0; i != (u32)size.Y; i++) + for (i = 0; i != (u32) size.Y; i++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); @@ -289,8 +299,7 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { u16 ypos; if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) || - !getintfield(L, -1, "prob", - schem->slice_probs[ypos])) + !getintfield(L, -1, "prob", schem->slice_probs[ypos])) continue; schem->slice_probs[ypos] >>= 1; @@ -300,6 +309,7 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, return true; } + void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) @@ -313,25 +323,21 @@ void read_schematic_replacements(lua_State *L, int index, StringMap *replace_nam if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format lua_rawgeti(L, -1, 1); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_from field is not a " - "string"); + throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_to field is not a " - "string"); + throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); lua_pop(L, 1); } else { // New {x = "y", ...} format if (!lua_isstring(L, -2)) - throw LuaError("schematics: replace_from field is not a " - "string"); + throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -2); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_to field is not a " - "string"); + throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); } @@ -363,41 +369,42 @@ Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr) return biome; } + Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef) { if (!lua_istable(L, index)) return NULL; BiomeType biometype = (BiomeType)getenumfield(L, index, "type", - ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); + ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); Biome *b = BiomeManager::create(biometype); - b->name = getstringfield_default(L, index, "name", ""); - b->depth_top = getintfield_default(L, index, "depth_top", 0); - b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); - b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); - b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); - b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); - b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); - b->vertical_blend = getintfield_default(L, index, "vertical_blend", 0); - b->flags = 0; // reserved + b->name = getstringfield_default(L, index, "name", ""); + b->depth_top = getintfield_default(L, index, "depth_top", 0); + b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); + b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); + b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); + b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); + b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); + b->vertical_blend = getintfield_default(L, index, "vertical_blend", 0); + b->flags = 0; // reserved b->min_pos = getv3s16field_default( - L, index, "min_pos", v3s16(-31000, -31000, -31000)); + L, index, "min_pos", v3s16(-31000, -31000, -31000)); getintfield(L, index, "y_min", b->min_pos.Y); b->max_pos = getv3s16field_default( - L, index, "max_pos", v3s16(31000, 31000, 31000)); + L, index, "max_pos", v3s16(31000, 31000, 31000)); getintfield(L, index, "y_max", b->max_pos.Y); std::vector &nn = b->m_nodenames; - nn.push_back(getstringfield_default(L, index, "node_top", "")); - nn.push_back(getstringfield_default(L, index, "node_filler", "")); - nn.push_back(getstringfield_default(L, index, "node_stone", "")); - nn.push_back(getstringfield_default(L, index, "node_water_top", "")); - nn.push_back(getstringfield_default(L, index, "node_water", "")); - nn.push_back(getstringfield_default(L, index, "node_river_water", "")); - nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); - nn.push_back(getstringfield_default(L, index, "node_dust", "")); + nn.push_back(getstringfield_default(L, index, "node_top", "")); + nn.push_back(getstringfield_default(L, index, "node_filler", "")); + nn.push_back(getstringfield_default(L, index, "node_stone", "")); + nn.push_back(getstringfield_default(L, index, "node_water_top", "")); + nn.push_back(getstringfield_default(L, index, "node_water", "")); + nn.push_back(getstringfield_default(L, index, "node_river_water", "")); + nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); + nn.push_back(getstringfield_default(L, index, "node_dust", "")); size_t nnames = getstringlistfield(L, index, "node_cave_liquid", &nn); // If no cave liquids defined, set list to "ignore" to trigger old hardcoded @@ -408,16 +415,17 @@ Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef) } b->m_nnlistsizes.push_back(nnames); - nn.push_back(getstringfield_default(L, index, "node_dungeon", "")); - nn.push_back(getstringfield_default(L, index, "node_dungeon_alt", "")); + nn.push_back(getstringfield_default(L, index, "node_dungeon", "")); + nn.push_back(getstringfield_default(L, index, "node_dungeon_alt", "")); nn.push_back(getstringfield_default(L, index, "node_dungeon_stair", "")); ndef->pendNodeResolve(b); return b; } -size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, - std::unordered_set *biome_id_list) + +size_t get_biome_list(lua_State *L, int index, + BiomeManager *biomemgr, std::unordered_set *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -436,9 +444,8 @@ size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, Biome *biome = get_or_load_biome(L, index, biomemgr); if (!biome) { infostream << "get_biome_list: failed to get biome '" - << (lua_isstring(L, index) ? lua_tostring(L, index) - : "") - << "'." << std::endl; + << (lua_isstring(L, index) ? lua_tostring(L, index) : "") + << "'." << std::endl; return 1; } @@ -456,8 +463,8 @@ size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, if (!biome) { fail_count++; infostream << "get_biome_list: failed to get biome '" - << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") - << "'" << std::endl; + << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") + << "'" << std::endl; continue; } @@ -492,6 +499,7 @@ int ModApiMapgen::l_get_biome_id(lua_State *L) return 1; } + // get_biome_name(biome_id) // returns the biome name string int ModApiMapgen::l_get_biome_name(lua_State *L) @@ -510,6 +518,7 @@ int ModApiMapgen::l_get_biome_name(lua_State *L) return 1; } + // get_heat(pos) // returns the heat at the position int ModApiMapgen::l_get_heat(lua_State *L) @@ -522,11 +531,12 @@ int ModApiMapgen::l_get_heat(lua_State *L) NoiseParams np_heat_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", &np_heat) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_heat_blend", &np_heat_blend)) + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", + &np_heat) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", + &np_heat_blend)) return 0; std::string value; @@ -547,6 +557,7 @@ int ModApiMapgen::l_get_heat(lua_State *L) return 1; } + // get_humidity(pos) // returns the humidity at the position int ModApiMapgen::l_get_humidity(lua_State *L) @@ -559,12 +570,12 @@ int ModApiMapgen::l_get_humidity(lua_State *L) NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - if (!settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity", &np_humidity) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity_blend", &np_humidity_blend)) + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", + &np_humidity) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", + &np_humidity_blend)) return 0; std::string value; @@ -578,14 +589,15 @@ int ModApiMapgen::l_get_humidity(lua_State *L) if (!bmgr) return 0; - float humidity = bmgr->getHumidityAtPosOriginal( - pos, np_humidity, np_humidity_blend, seed); + float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, + np_humidity_blend, seed); lua_pushnumber(L, humidity); return 1; } + // get_biome_data(pos) // returns a table containing the biome id, heat and humidity at the position int ModApiMapgen::l_get_biome_data(lua_State *L) @@ -600,15 +612,16 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; - - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", &np_heat) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_heat_blend", &np_heat_blend) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity", &np_humidity) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity_blend", &np_humidity_blend)) + getServer(L)->getEmergeManager()->map_settings_mgr; + + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", + &np_heat) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", + &np_heat_blend) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", + &np_humidity) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", + &np_humidity_blend)) return 0; std::string value; @@ -626,8 +639,8 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) if (!heat) return 0; - float humidity = bmgr->getHumidityAtPosOriginal( - pos, np_humidity, np_humidity_blend, seed); + float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, + np_humidity_blend, seed); if (!humidity) return 0; @@ -649,6 +662,7 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) return 1; } + // get_mapgen_object(objectname) // returns the requested object used during map generation int ModApiMapgen::l_get_mapgen_object(lua_State *L) @@ -742,7 +756,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L) return 1; } case MGOBJ_GENNOTIFY: { - std::map> event_map; + std::map >event_map; mg->gennotify.getEvents(event_map); @@ -765,6 +779,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L) return 0; } + // get_spawn_level(x = num, z = num) int ModApiMapgen::l_get_spawn_level(lua_State *L) { @@ -785,17 +800,18 @@ int ModApiMapgen::l_get_spawn_level(lua_State *L) return 1; } + int ModApiMapgen::l_get_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "get_mapgen_params is deprecated; " - "use get_mapgen_setting instead"); + "use get_mapgen_setting instead"); std::string value; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; lua_newtable(L); @@ -825,6 +841,7 @@ int ModApiMapgen::l_get_mapgen_params(lua_State *L) return 1; } + // set_mapgen_params(params) // set mapgen parameters int ModApiMapgen::l_set_mapgen_params(lua_State *L) @@ -832,18 +849,17 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) NO_MAP_LOCK_REQUIRED; log_deprecated(L, "set_mapgen_params is deprecated; " - "use set_mapgen_setting instead"); + "use set_mapgen_setting instead"); if (!lua_istable(L, 1)) return 0; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; lua_getfield(L, 1, "mgname"); if (lua_isstring(L, -1)) - settingsmgr->setMapSetting( - "mg_name", readParam(L, -1), true); + settingsmgr->setMapSetting("mg_name", readParam(L, -1), true); lua_getfield(L, 1, "seed"); if (lua_isnumber(L, -1)) @@ -851,21 +867,18 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) lua_getfield(L, 1, "water_level"); if (lua_isnumber(L, -1)) - settingsmgr->setMapSetting( - "water_level", readParam(L, -1), true); + settingsmgr->setMapSetting("water_level", readParam(L, -1), true); lua_getfield(L, 1, "chunksize"); if (lua_isnumber(L, -1)) - settingsmgr->setMapSetting( - "chunksize", readParam(L, -1), true); + settingsmgr->setMapSetting("chunksize", readParam(L, -1), true); warn_if_field_exists(L, 1, "flagmask", - "Obsolete: flags field now includes unset flags."); + "Obsolete: flags field now includes unset flags."); lua_getfield(L, 1, "flags"); if (lua_isstring(L, -1)) - settingsmgr->setMapSetting( - "mg_flags", readParam(L, -1), true); + settingsmgr->setMapSetting("mg_flags", readParam(L, -1), true); return 0; } @@ -877,7 +890,7 @@ int ModApiMapgen::l_get_mapgen_setting(lua_State *L) std::string value; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSetting(name, &value)) @@ -894,7 +907,7 @@ int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L) NoiseParams np; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSettingNoiseParams(name, &np)) @@ -911,20 +924,21 @@ int ModApiMapgen::l_set_mapgen_setting(lua_State *L) NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - const char *name = luaL_checkstring(L, 1); - const char *value = luaL_checkstring(L, 2); + const char *name = luaL_checkstring(L, 1); + const char *value = luaL_checkstring(L, 2); bool override_meta = readParam(L, 3, false); if (!settingsmgr->setMapSetting(name, value, override_meta)) { - errorstream << "set_mapgen_setting: cannot set '" << name - << "' after initialization" << std::endl; + errorstream << "set_mapgen_setting: cannot set '" + << name << "' after initialization" << std::endl; } return 0; } + // set_mapgen_setting_noiseparams(name, noiseparams, set_default) // set mapgen config values for noise parameters int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) @@ -932,27 +946,28 @@ int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name - << "'; invalid noiseparams table" << std::endl; + << "'; invalid noiseparams table" << std::endl; return 0; } bool override_meta = readParam(L, 3, false); if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { - errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name - << "' after initialization" << std::endl; + errorstream << "set_mapgen_setting_noiseparams: cannot set '" + << name << "' after initialization" << std::endl; } return 0; } + // set_noiseparams(name, noiseparams, set_default) // set global config values for noise parameters int ModApiMapgen::l_set_noiseparams(lua_State *L) @@ -964,7 +979,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_noiseparams: cannot set '" << name - << "'; invalid noiseparams table" << std::endl; + << "'; invalid noiseparams table" << std::endl; return 0; } @@ -975,6 +990,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) return 0; } + // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { @@ -990,6 +1006,7 @@ int ModApiMapgen::l_get_noiseparams(lua_State *L) return 1; } + // set_gen_notify(flags, {deco_id_table}) int ModApiMapgen::l_set_gen_notify(lua_State *L) { @@ -1007,8 +1024,7 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) lua_pushnil(L); while (lua_next(L, 2)) { if (lua_isnumber(L, -1)) - emerge->gen_notify_on_deco_ids.insert( - (u32)lua_tonumber(L, -1)); + emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1)); lua_pop(L, 1); } } @@ -1016,6 +1032,7 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) return 0; } + // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { @@ -1023,7 +1040,7 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L) EmergeManager *emerge = getServer(L)->getEmergeManager(); push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on, - emerge->gen_notify_on); + emerge->gen_notify_on); lua_newtable(L); int i = 1; @@ -1034,6 +1051,7 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L) return 2; } + // get_decoration_id(decoration_name) // returns the decoration ID as used in gennotify int ModApiMapgen::l_get_decoration_id(lua_State *L) @@ -1045,7 +1063,7 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 0; const DecorationManager *dmgr = - getServer(L)->getEmergeManager()->getDecorationManager(); + getServer(L)->getEmergeManager()->getDecorationManager(); if (!dmgr) return 0; @@ -1060,6 +1078,7 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 1; } + // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { @@ -1085,6 +1104,7 @@ int ModApiMapgen::l_register_biome(lua_State *L) return 1; } + // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { @@ -1093,33 +1113,32 @@ int ModApiMapgen::l_register_decoration(lua_State *L) int index = 1; luaL_checktype(L, index, LUA_TTABLE); - const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); + const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); DecorationManager *decomgr = emerge->getWritableDecorationManager(); - BiomeManager *biomemgr = emerge->getWritableBiomeManager(); + BiomeManager *biomemgr = emerge->getWritableBiomeManager(); SchematicManager *schemmgr = emerge->getWritableSchematicManager(); - enum DecorationType decotype = (DecorationType)getenumfield( - L, index, "deco_type", es_DecorationType, -1); + enum DecorationType decotype = (DecorationType)getenumfield(L, index, + "deco_type", es_DecorationType, -1); Decoration *deco = decomgr->create(decotype); if (!deco) { errorstream << "register_decoration: decoration placement type " - << decotype << " not implemented" << std::endl; + << decotype << " not implemented" << std::endl; return 0; } - deco->name = getstringfield_default(L, index, "name", ""); - deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); - deco->y_min = getintfield_default(L, index, "y_min", -31000); - deco->y_max = getintfield_default(L, index, "y_max", 31000); - deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); + deco->name = getstringfield_default(L, index, "name", ""); + deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); + deco->y_min = getintfield_default(L, index, "y_min", -31000); + deco->y_max = getintfield_default(L, index, "y_max", 31000); + deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); deco->place_offset_y = getintfield_default(L, index, "place_offset_y", 0); - deco->sidelen = getintfield_default(L, index, "sidelen", 8); + deco->sidelen = getintfield_default(L, index, "sidelen", 8); if (deco->sidelen <= 0) { errorstream << "register_decoration: sidelen must be " - "greater than 0" - << std::endl; + "greater than 0" << std::endl; delete deco; return 0; } @@ -1140,8 +1159,7 @@ int ModApiMapgen::l_register_decoration(lua_State *L) //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, biomemgr, &deco->biomes)) - infostream << "register_decoration: couldn't get all biomes " - << std::endl; + infostream << "register_decoration: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get node name(s) to 'spawn by' @@ -1149,8 +1167,7 @@ int ModApiMapgen::l_register_decoration(lua_State *L) deco->m_nnlistsizes.push_back(nnames); if (nnames == 0 && deco->nspawnby != -1) { errorstream << "register_decoration: no spawn_by nodes defined," - " but num_spawn_by specified" - << std::endl; + " but num_spawn_by specified" << std::endl; } //// Handle decoration type-specific parameters @@ -1183,19 +1200,19 @@ int ModApiMapgen::l_register_decoration(lua_State *L) return 1; } + bool read_deco_simple(lua_State *L, DecoSimple *deco) { int index = 1; int param2; int param2_max; - deco->deco_height = getintfield_default(L, index, "height", 1); + deco->deco_height = getintfield_default(L, index, "height", 1); deco->deco_height_max = getintfield_default(L, index, "height_max", 0); if (deco->deco_height <= 0) { errorstream << "register_decoration: simple decoration height" - " must be greater than 0" - << std::endl; + " must be greater than 0" << std::endl; return false; } @@ -1204,8 +1221,7 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) if (nnames == 0) { errorstream << "register_decoration: no decoration nodes " - "defined" - << std::endl; + "defined" << std::endl; return false; } @@ -1213,9 +1229,8 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) param2_max = getintfield_default(L, index, "param2_max", 0); if (param2 < 0 || param2 > 255 || param2_max < 0 || param2_max > 255) { - errorstream << "register_decoration: param2 or param2_max out of bounds " - "(0-255)" - << std::endl; + errorstream << "register_decoration: param2 or param2_max out of bounds (0-255)" + << std::endl; return false; } @@ -1225,12 +1240,13 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) return true; } + bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco) { int index = 1; - deco->rotation = (Rotation)getenumfield( - L, index, "rotation", ModApiMapgen::es_Rotation, ROTATE_0); + deco->rotation = (Rotation)getenumfield(L, index, "rotation", + ModApiMapgen::es_Rotation, ROTATE_0); StringMap replace_names; lua_getfield(L, index, "replacements"); @@ -1246,6 +1262,7 @@ bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic return schem != NULL; } + // register_ore({lots of stuff}) int ModApiMapgen::l_register_ore(lua_State *L) { @@ -1256,29 +1273,28 @@ int ModApiMapgen::l_register_ore(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); - BiomeManager *bmgr = emerge->getWritableBiomeManager(); - OreManager *oremgr = emerge->getWritableOreManager(); + BiomeManager *bmgr = emerge->getWritableBiomeManager(); + OreManager *oremgr = emerge->getWritableOreManager(); - enum OreType oretype = (OreType)getenumfield( - L, index, "ore_type", es_OreType, ORE_SCATTER); + enum OreType oretype = (OreType)getenumfield(L, index, + "ore_type", es_OreType, ORE_SCATTER); Ore *ore = oremgr->create(oretype); if (!ore) { - errorstream << "register_ore: ore_type " << oretype - << " not implemented\n"; + errorstream << "register_ore: ore_type " << oretype << " not implemented\n"; return 0; } - ore->name = getstringfield_default(L, index, "name", ""); - ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); + ore->name = getstringfield_default(L, index, "name", ""); + ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1); ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1); - ore->clust_size = getintfield_default(L, index, "clust_size", 0); - ore->noise = NULL; - ore->flags = 0; + ore->clust_size = getintfield_default(L, index, "clust_size", 0); + ore->noise = NULL; + ore->flags = 0; //// Get noise_threshold warn_if_field_exists(L, index, "noise_threshhold", - "Deprecated: new name is \"noise_threshold\"."); + "Deprecated: new name is \"noise_threshold\"."); float nthresh; if (!getfloatfield(L, index, "noise_threshold", nthresh) && @@ -1287,25 +1303,24 @@ int ModApiMapgen::l_register_ore(lua_State *L) ore->nthresh = nthresh; //// Get y_min/y_max - warn_if_field_exists( - L, index, "height_min", "Deprecated: new name is \"y_min\"."); - warn_if_field_exists( - L, index, "height_max", "Deprecated: new name is \"y_max\"."); + warn_if_field_exists(L, index, "height_min", + "Deprecated: new name is \"y_min\"."); + warn_if_field_exists(L, index, "height_max", + "Deprecated: new name is \"y_max\"."); int ymin, ymax; if (!getintfield(L, index, "y_min", ymin) && - !getintfield(L, index, "height_min", ymin)) + !getintfield(L, index, "height_min", ymin)) ymin = -31000; if (!getintfield(L, index, "y_max", ymax) && - !getintfield(L, index, "height_max", ymax)) + !getintfield(L, index, "height_max", ymax)) ymax = 31000; ore->y_min = ymin; ore->y_max = ymax; if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) { errorstream << "register_ore: clust_scarcity and clust_num_ores" - "must be greater than 0" - << std::endl; + "must be greater than 0" << std::endl; delete ore; return 0; } @@ -1325,8 +1340,7 @@ int ModApiMapgen::l_register_ore(lua_State *L) ore->flags |= OREFLAG_USE_NOISE; } else if (ore->NEEDS_NOISE) { errorstream << "register_ore: specified ore type requires valid " - "'noise_params' parameter" - << std::endl; + "'noise_params' parameter" << std::endl; delete ore; return 0; } @@ -1334,54 +1348,54 @@ int ModApiMapgen::l_register_ore(lua_State *L) //// Get type-specific parameters switch (oretype) { - case ORE_SHEET: { - OreSheet *oresheet = (OreSheet *)ore; + case ORE_SHEET: { + OreSheet *oresheet = (OreSheet *)ore; - oresheet->column_height_min = - getintfield_default(L, index, "column_height_min", 1); - oresheet->column_height_max = getintfield_default( - L, index, "column_height_max", ore->clust_size); - oresheet->column_midpoint_factor = getfloatfield_default( - L, index, "column_midpoint_factor", 0.5f); + oresheet->column_height_min = getintfield_default(L, index, + "column_height_min", 1); + oresheet->column_height_max = getintfield_default(L, index, + "column_height_max", ore->clust_size); + oresheet->column_midpoint_factor = getfloatfield_default(L, index, + "column_midpoint_factor", 0.5f); - break; - } - case ORE_PUFF: { - OrePuff *orepuff = (OrePuff *)ore; + break; + } + case ORE_PUFF: { + OrePuff *orepuff = (OrePuff *)ore; - lua_getfield(L, index, "np_puff_top"); - read_noiseparams(L, -1, &orepuff->np_puff_top); - lua_pop(L, 1); + lua_getfield(L, index, "np_puff_top"); + read_noiseparams(L, -1, &orepuff->np_puff_top); + lua_pop(L, 1); - lua_getfield(L, index, "np_puff_bottom"); - read_noiseparams(L, -1, &orepuff->np_puff_bottom); - lua_pop(L, 1); + lua_getfield(L, index, "np_puff_bottom"); + read_noiseparams(L, -1, &orepuff->np_puff_bottom); + lua_pop(L, 1); - break; - } - case ORE_VEIN: { - OreVein *orevein = (OreVein *)ore; + break; + } + case ORE_VEIN: { + OreVein *orevein = (OreVein *)ore; - orevein->random_factor = - getfloatfield_default(L, index, "random_factor", 1.f); + orevein->random_factor = getfloatfield_default(L, index, + "random_factor", 1.f); - break; - } - case ORE_STRATUM: { - OreStratum *orestratum = (OreStratum *)ore; + break; + } + case ORE_STRATUM: { + OreStratum *orestratum = (OreStratum *)ore; - lua_getfield(L, index, "np_stratum_thickness"); - if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness)) - ore->flags |= OREFLAG_USE_NOISE2; - lua_pop(L, 1); + lua_getfield(L, index, "np_stratum_thickness"); + if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness)) + ore->flags |= OREFLAG_USE_NOISE2; + lua_pop(L, 1); - orestratum->stratum_thickness = - getintfield_default(L, index, "stratum_thickness", 8); + orestratum->stratum_thickness = getintfield_default(L, index, + "stratum_thickness", 8); - break; - } - default: - break; + break; + } + default: + break; } ObjDefHandle handle = oremgr->add(ore); @@ -1401,19 +1415,21 @@ int ModApiMapgen::l_register_ore(lua_State *L) return 1; } + // register_schematic({schematic}, replacements={}) int ModApiMapgen::l_register_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getWritableSchematicManager(); + getServer(L)->getEmergeManager()->getWritableSchematicManager(); StringMap replace_names; if (lua_istable(L, 2)) read_schematic_replacements(L, 2, &replace_names); - Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), &replace_names); + Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), + &replace_names); if (!schem) return 0; @@ -1427,48 +1443,55 @@ int ModApiMapgen::l_register_schematic(lua_State *L) return 1; } + // clear_registered_biomes() int ModApiMapgen::l_clear_registered_biomes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - BiomeManager *bmgr = getServer(L)->getEmergeManager()->getWritableBiomeManager(); + BiomeManager *bmgr = + getServer(L)->getEmergeManager()->getWritableBiomeManager(); bmgr->clear(); return 0; } + // clear_registered_decorations() int ModApiMapgen::l_clear_registered_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; DecorationManager *dmgr = - getServer(L)->getEmergeManager()->getWritableDecorationManager(); + getServer(L)->getEmergeManager()->getWritableDecorationManager(); dmgr->clear(); return 0; } + // clear_registered_ores() int ModApiMapgen::l_clear_registered_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; - OreManager *omgr = getServer(L)->getEmergeManager()->getWritableOreManager(); + OreManager *omgr = + getServer(L)->getEmergeManager()->getWritableOreManager(); omgr->clear(); return 0; } + // clear_registered_schematics() int ModApiMapgen::l_clear_registered_schematics(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *smgr = - getServer(L)->getEmergeManager()->getWritableSchematicManager(); + getServer(L)->getEmergeManager()->getWritableSchematicManager(); smgr->clear(); return 0; } + // generate_ores(vm, p1, p2, [ore_id]) int ModApiMapgen::l_generate_ores(lua_State *L) { @@ -1478,15 +1501,13 @@ int ModApiMapgen::l_generate_ores(lua_State *L) Mapgen mg; mg.seed = emerge->mgparams->seed; - mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; + mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) - : mg.vm->m_area.MinEdge + - v3s16(1, 1, 1) * MAP_BLOCKSIZE; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) - : mg.vm->m_area.MaxEdge - - v3s16(1, 1, 1) * MAP_BLOCKSIZE; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : + mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : + mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); @@ -1496,6 +1517,7 @@ int ModApiMapgen::l_generate_ores(lua_State *L) return 0; } + // generate_decorations(vm, p1, p2, [deco_id]) int ModApiMapgen::l_generate_decorations(lua_State *L) { @@ -1505,15 +1527,13 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) Mapgen mg; mg.seed = emerge->mgparams->seed; - mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; + mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) - : mg.vm->m_area.MinEdge + - v3s16(1, 1, 1) * MAP_BLOCKSIZE; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) - : mg.vm->m_area.MaxEdge - - v3s16(1, 1, 1) * MAP_BLOCKSIZE; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : + mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : + mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); @@ -1523,6 +1543,7 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) return 0; } + // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list) int ModApiMapgen::l_create_schematic(lua_State *L) { @@ -1540,7 +1561,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L) v3s16 p2 = check_v3s16(L, 2); sortBoxVerticies(p1, p2); - std::vector> prob_list; + std::vector > prob_list; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3)) { @@ -1549,8 +1570,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L) v3s16 pos = check_v3s16(L, -1); lua_pop(L, 1); - u8 prob = getintfield_default( - L, -1, "prob", MTSCHEM_PROB_ALWAYS); + u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); prob_list.emplace_back(pos, prob); } @@ -1558,14 +1578,13 @@ int ModApiMapgen::l_create_schematic(lua_State *L) } } - std::vector> slice_prob_list; + std::vector > slice_prob_list; if (lua_istable(L, 5)) { lua_pushnil(L); while (lua_next(L, 5)) { if (lua_istable(L, -1)) { s16 ypos = getintfield_default(L, -1, "ypos", 0); - u8 prob = getintfield_default( - L, -1, "prob", MTSCHEM_PROB_ALWAYS); + u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); slice_prob_list.emplace_back(ypos, prob); } @@ -1575,21 +1594,21 @@ int ModApiMapgen::l_create_schematic(lua_State *L) if (!schem.getSchematicFromMap(map, p1, p2)) { errorstream << "create_schematic: failed to get schematic " - "from map" - << std::endl; + "from map" << std::endl; return 0; } schem.applyProbabilities(p1, &prob_list, &slice_prob_list); schem.saveSchematicToFile(filename, ndef); - actionstream << "create_schematic: saved schematic file '" << filename << "'." - << std::endl; + actionstream << "create_schematic: saved schematic file '" + << filename << "'." << std::endl; lua_pushboolean(L, true); return 1; } + // place_schematic(p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic(lua_State *L) @@ -1637,6 +1656,7 @@ int ModApiMapgen::l_place_schematic(lua_State *L) return 1; } + // place_schematic_on_vmanip(vm, p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) @@ -1679,19 +1699,19 @@ int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) read_flags(L, 7, flagdesc_deco, &flags, NULL); bool schematic_did_fit = schem->placeOnVManip( - vm, p, flags, (Rotation)rot, force_placement); + vm, p, flags, (Rotation)rot, force_placement); lua_pushboolean(L, schematic_did_fit); return 1; } + // serialize_schematic(schematic, format, options={...}) int ModApiMapgen::l_serialize_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getSchematicManager(); + const SchematicManager *schemmgr = getServer(L)->getEmergeManager()->getSchematicManager(); //// Read options bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false); @@ -1705,8 +1725,7 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) was_loaded = true; } if (!schem) { - errorstream << "serialize_schematic: failed to get schematic" - << std::endl; + errorstream << "serialize_schematic: failed to get schematic" << std::endl; return 0; } @@ -1723,8 +1742,8 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) schem->serializeToMts(&os, schem->m_nodenames); break; case SCHEM_FMT_LUA: - schem->serializeToLua( - &os, schem->m_nodenames, use_comments, indent_spaces); + schem->serializeToLua(&os, schem->m_nodenames, + use_comments, indent_spaces); break; default: return 0; @@ -1744,11 +1763,10 @@ int ModApiMapgen::l_read_schematic(lua_State *L) NO_MAP_LOCK_REQUIRED; const SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getSchematicManager(); + getServer(L)->getEmergeManager()->getSchematicManager(); //// Read options - std::string write_yslice = - getstringfield_default(L, 2, "write_yslice_prob", "all"); + std::string write_yslice = getstringfield_default(L, 2, "write_yslice_prob", "all"); //// Get schematic bool was_loaded = false; @@ -1794,7 +1812,7 @@ int ModApiMapgen::l_read_schematic(lua_State *L) lua_createtable(L, numnodes, 0); // data table for (u32 i = 0; i < numnodes; ++i) { MapNode node = schem->schemdata[i]; - u8 probability = node.param1 & MTSCHEM_PROB_MASK; + u8 probability = node.param1 & MTSCHEM_PROB_MASK; bool force_place = node.param1 & MTSCHEM_FORCE_PLACE; lua_createtable(L, 0, force_place ? 4 : 3); lua_pushstring(L, names[schem->schemdata[i].getContent()].c_str()); @@ -1817,6 +1835,7 @@ int ModApiMapgen::l_read_schematic(lua_State *L) return 1; } + void ModApiMapgen::Initialize(lua_State *L, int top) { API_FCT(get_biome_id); diff --git a/src/script/lua_api/l_mapgen.h b/src/script/lua_api/l_mapgen.h index ebc49a5ec..0bdc56fc5 100644 --- a/src/script/lua_api/l_mapgen.h +++ b/src/script/lua_api/l_mapgen.h @@ -21,7 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_base.h" -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class ModApiMapgen : public ModApiBase { diff --git a/src/script/lua_api/l_metadata.cpp b/src/script/lua_api/l_metadata.cpp index 3c9670c22..21002e6a7 100644 --- a/src/script/lua_api/l_metadata.cpp +++ b/src/script/lua_api/l_metadata.cpp @@ -26,14 +26,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" // LUALIB_API -void *luaL_checkudata_is_metadataref(lua_State *L, int ud) -{ +void *luaL_checkudata_is_metadataref(lua_State *L, int ud) { void *p = lua_touserdata(L, ud); - if (p != NULL && // value is a userdata? - lua_getmetatable(L, ud)) { // does it have a metatable? + if (p != NULL && // value is a userdata? + lua_getmetatable(L, ud)) { // does it have a metatable? lua_getfield(L, -1, "metadata_class"); - if (lua_type(L, -1) == - LUA_TSTRING) { // does it have a metadata_class field? + if (lua_type(L, -1) == LUA_TSTRING) { // does it have a metadata_class field? return p; } } @@ -41,14 +39,14 @@ void *luaL_checkudata_is_metadataref(lua_State *L, int ud) return NULL; } -MetaDataRef *MetaDataRef::checkobject(lua_State *L, int narg) +MetaDataRef* MetaDataRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata_is_metadataref(L, narg); if (!ud) luaL_typerror(L, narg, "MetaDataRef"); - return *(MetaDataRef **)ud; // unbox pointer + return *(MetaDataRef**)ud; // unbox pointer } // Exported functions diff --git a/src/script/lua_api/l_minimap.cpp b/src/script/lua_api/l_minimap.cpp index 1c429bdcb..5fba76eb8 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_minimap.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" @@ -98,11 +99,12 @@ int LuaMinimap::l_set_mode(lua_State *L) Minimap *m = getobject(ref); s32 mode = lua_tointeger(L, 2); - if (mode < MINIMAP_MODE_OFF || mode >= MINIMAP_MODE_COUNT) { + if (mode < MINIMAP_MODE_OFF || + mode >= MINIMAP_MODE_COUNT) { return 0; } - m->setMinimapMode((MinimapMode)mode); + m->setMinimapMode((MinimapMode) mode); return 1; } @@ -170,16 +172,15 @@ LuaMinimap *LuaMinimap::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaMinimap **)ud; // unbox pointer + return *(LuaMinimap **)ud; // unbox pointer } -Minimap *LuaMinimap::getobject(LuaMinimap *ref) +Minimap* LuaMinimap::getobject(LuaMinimap *ref) { return ref->m_minimap; } -int LuaMinimap::gc_object(lua_State *L) -{ +int LuaMinimap::gc_object(lua_State *L) { LuaMinimap *o = *(LuaMinimap **)(lua_touserdata(L, 1)); delete o; return 0; @@ -194,7 +195,7 @@ void LuaMinimap::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -204,16 +205,23 @@ void LuaMinimap::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } const char LuaMinimap::className[] = "Minimap"; -const luaL_Reg LuaMinimap::methods[] = {luamethod(LuaMinimap, show), - luamethod(LuaMinimap, hide), luamethod(LuaMinimap, get_pos), - luamethod(LuaMinimap, set_pos), luamethod(LuaMinimap, get_angle), - luamethod(LuaMinimap, set_angle), luamethod(LuaMinimap, get_mode), - luamethod(LuaMinimap, set_mode), luamethod(LuaMinimap, set_shape), - luamethod(LuaMinimap, get_shape), {0, 0}}; +const luaL_Reg LuaMinimap::methods[] = { + luamethod(LuaMinimap, show), + luamethod(LuaMinimap, hide), + luamethod(LuaMinimap, get_pos), + luamethod(LuaMinimap, set_pos), + luamethod(LuaMinimap, get_angle), + luamethod(LuaMinimap, set_angle), + luamethod(LuaMinimap, get_mode), + luamethod(LuaMinimap, set_mode), + luamethod(LuaMinimap, set_shape), + luamethod(LuaMinimap, get_shape), + {0,0} +}; diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index 934c08796..57052cb42 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -29,16 +29,15 @@ with this program; if not, write to the Free Software Foundation, Inc., /* NodeMetaRef */ -NodeMetaRef *NodeMetaRef::checkobject(lua_State *L, int narg) +NodeMetaRef* NodeMetaRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(NodeMetaRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(NodeMetaRef**)ud; // unbox pointer } -Metadata *NodeMetaRef::getmeta(bool auto_create) +Metadata* NodeMetaRef::getmeta(bool auto_create) { if (m_is_local) return m_meta; @@ -65,7 +64,7 @@ void NodeMetaRef::reportMetadataChange(const std::string *name) SANITY_CHECK(!m_is_local); // NOTE: This same code is in rollback_interface.cpp // Inform other things that the metadata has changed - NodeMetadata *meta = dynamic_cast(m_meta); + NodeMetadata *meta = dynamic_cast(m_meta); MapEditEvent event; event.type = MEET_BLOCK_NODE_METADATA_CHANGED; @@ -77,8 +76,7 @@ void NodeMetaRef::reportMetadataChange(const std::string *name) // Exported functions // garbage collector -int NodeMetaRef::gc_object(lua_State *L) -{ +int NodeMetaRef::gc_object(lua_State *L) { NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -90,7 +88,7 @@ int NodeMetaRef::l_get_inventory(lua_State *L) MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); - ref->getmeta(true); // try to ensure the metadata exists + ref->getmeta(true); // try to ensure the metadata exists InvRef::createNodeMeta(L, ref->m_p); return 1; } @@ -101,7 +99,7 @@ int NodeMetaRef::l_mark_as_private(lua_State *L) MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); - NodeMetadata *meta = dynamic_cast(ref->getmeta(true)); + NodeMetadata *meta = dynamic_cast(ref->getmeta(true)); assert(meta); if (lua_istable(L, 2)) { @@ -126,15 +124,15 @@ void NodeMetaRef::handleToTable(lua_State *L, Metadata *_meta) // fields MetaDataRef::handleToTable(L, _meta); - NodeMetadata *meta = (NodeMetadata *)_meta; + NodeMetadata *meta = (NodeMetadata*) _meta; // inventory lua_newtable(L); Inventory *inv = meta->getInventory(); if (inv) { std::vector lists = inv->getLists(); - for (std::vector::const_iterator i = lists.begin(); - i != lists.end(); ++i) { + for(std::vector::const_iterator + i = lists.begin(); i != lists.end(); ++i) { push_inventory_list(L, inv, (*i)->getName().c_str()); lua_setfield(L, -2, (*i)->getName().c_str()); } @@ -149,7 +147,7 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) if (!MetaDataRef::handleFromTable(L, table, _meta)) return false; - NodeMetadata *meta = (NodeMetadata *)_meta; + NodeMetadata *meta = (NodeMetadata*) _meta; // inventory Inventory *inv = meta->getInventory(); @@ -169,11 +167,16 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) return true; } -NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env) : m_p(p), m_env(env) + +NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env): + m_p(p), + m_env(env) { } -NodeMetaRef::NodeMetaRef(Metadata *meta) : m_meta(meta), m_is_local(true) +NodeMetaRef::NodeMetaRef(Metadata *meta): + m_meta(meta), + m_is_local(true) { } @@ -182,7 +185,7 @@ NodeMetaRef::NodeMetaRef(Metadata *meta) : m_meta(meta), m_is_local(true) void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) { NodeMetaRef *o = new NodeMetaRef(p, env); - // infostream<<"NodeMetaRef::create: o="<(L, 2); - f32 e = readParam(L, 3); + f32 t = readParam(L,2); + f32 e = readParam(L,3); o->m_map->setNodeTimer(NodeTimer(t, e, o->m_p)); return 0; } @@ -52,7 +51,7 @@ int NodeTimerRef::l_start(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); - f32 t = readParam(L, 2); + f32 t = readParam(L,2); o->m_map->setNodeTimer(NodeTimer(t, 0, o->m_p)); return 0; } @@ -70,7 +69,7 @@ int NodeTimerRef::l_is_started(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushboolean(L, (t.timeout != 0)); + lua_pushboolean(L,(t.timeout != 0)); return 1; } @@ -79,7 +78,7 @@ int NodeTimerRef::l_get_timeout(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushnumber(L, t.timeout); + lua_pushnumber(L,t.timeout); return 1; } @@ -88,7 +87,7 @@ int NodeTimerRef::l_get_elapsed(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushnumber(L, t.elapsed); + lua_pushnumber(L,t.elapsed); return 1; } @@ -111,7 +110,7 @@ void NodeTimerRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -121,17 +120,22 @@ void NodeTimerRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char NodeTimerRef::className[] = "NodeTimerRef"; -const luaL_Reg NodeTimerRef::methods[] = {luamethod(NodeTimerRef, start), - luamethod(NodeTimerRef, set), luamethod(NodeTimerRef, stop), - luamethod(NodeTimerRef, is_started), luamethod(NodeTimerRef, get_timeout), - luamethod(NodeTimerRef, get_elapsed), {0, 0}}; +const luaL_Reg NodeTimerRef::methods[] = { + luamethod(NodeTimerRef, start), + luamethod(NodeTimerRef, set), + luamethod(NodeTimerRef, stop), + luamethod(NodeTimerRef, is_started), + luamethod(NodeTimerRef, get_timeout), + luamethod(NodeTimerRef, get_elapsed), + {0,0} +}; diff --git a/src/script/lua_api/l_noise.cpp b/src/script/lua_api/l_noise.cpp index 0e9ece82b..9aeb15709 100644 --- a/src/script/lua_api/l_noise.cpp +++ b/src/script/lua_api/l_noise.cpp @@ -30,10 +30,12 @@ with this program; if not, write to the Free Software Foundation, Inc., LuaPerlinNoise */ -LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : np(*params) +LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : + np(*params) { } + int LuaPerlinNoise::l_get_2d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -44,6 +46,7 @@ int LuaPerlinNoise::l_get_2d(lua_State *L) return 1; } + int LuaPerlinNoise::l_get_3d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -54,6 +57,7 @@ int LuaPerlinNoise::l_get_3d(lua_State *L) return 1; } + int LuaPerlinNoise::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -63,10 +67,10 @@ int LuaPerlinNoise::create_object(lua_State *L) if (lua_istable(L, 1)) { read_noiseparams(L, 1, ¶ms); } else { - params.seed = luaL_checkint(L, 1); + params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam(L, 3); - params.spread = v3f(1, 1, 1) * readParam(L, 4); + params.spread = v3f(1, 1, 1) * readParam(L, 4); } LuaPerlinNoise *o = new LuaPerlinNoise(¶ms); @@ -77,6 +81,7 @@ int LuaPerlinNoise::create_object(lua_State *L) return 1; } + int LuaPerlinNoise::gc_object(lua_State *L) { LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1)); @@ -84,6 +89,7 @@ int LuaPerlinNoise::gc_object(lua_State *L) return 0; } + LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) { NO_MAP_LOCK_REQUIRED; @@ -94,6 +100,7 @@ LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) return *(LuaPerlinNoise **)ud; } + void LuaPerlinNoise::Register(lua_State *L) { lua_newtable(L); @@ -122,9 +129,13 @@ void LuaPerlinNoise::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPerlinNoise::className[] = "PerlinNoise"; -luaL_Reg LuaPerlinNoise::methods[] = {luamethod_aliased(LuaPerlinNoise, get_2d, get2d), - luamethod_aliased(LuaPerlinNoise, get_3d, get3d), {0, 0}}; +luaL_Reg LuaPerlinNoise::methods[] = { + luamethod_aliased(LuaPerlinNoise, get_2d, get2d), + luamethod_aliased(LuaPerlinNoise, get_3d, get3d), + {0,0} +}; /////////////////////////////////////// /* @@ -142,11 +153,13 @@ LuaPerlinNoiseMap::LuaPerlinNoiseMap(NoiseParams *params, s32 seed, v3s16 size) } } + LuaPerlinNoiseMap::~LuaPerlinNoiseMap() { delete noise; } + int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -170,6 +183,7 @@ int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -195,6 +209,7 @@ int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -225,13 +240,14 @@ int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3f p = check_v3f(L, 2); - bool use_buffer = lua_istable(L, 3); + v3f p = check_v3f(L, 2); + bool use_buffer = lua_istable(L, 3); if (!o->m_is3d) return 0; @@ -253,6 +269,7 @@ int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_calc_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -271,7 +288,7 @@ int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3f p = check_v3f(L, 2); + v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; @@ -282,14 +299,15 @@ int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) return 0; } + int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3s16 slice_offset = read_v3s16(L, 2); - v3s16 slice_size = read_v3s16(L, 3); - bool use_buffer = lua_istable(L, 4); + v3s16 slice_offset = read_v3s16(L, 2); + v3s16 slice_size = read_v3s16(L, 3); + bool use_buffer = lua_istable(L, 4); Noise *n = o->noise; @@ -298,13 +316,15 @@ int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) else lua_newtable(L); - write_array_slice_float(L, lua_gettop(L), n->result, v3u16(n->sx, n->sy, n->sz), - v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), - v3u16(slice_size.X, slice_size.Y, slice_size.Z)); + write_array_slice_float(L, lua_gettop(L), n->result, + v3u16(n->sx, n->sy, n->sz), + v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), + v3u16(slice_size.X, slice_size.Y, slice_size.Z)); return 1; } + int LuaPerlinNoiseMap::create_object(lua_State *L) { NoiseParams np; @@ -319,6 +339,7 @@ int LuaPerlinNoiseMap::create_object(lua_State *L) return 1; } + int LuaPerlinNoiseMap::gc_object(lua_State *L) { LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1)); @@ -326,6 +347,7 @@ int LuaPerlinNoiseMap::gc_object(lua_State *L) return 0; } + LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -337,6 +359,7 @@ LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) return *(LuaPerlinNoiseMap **)ud; } + void LuaPerlinNoiseMap::Register(lua_State *L) { lua_newtable(L); @@ -365,15 +388,18 @@ void LuaPerlinNoiseMap::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap"; luaL_Reg LuaPerlinNoiseMap::methods[] = { - luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), - luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), - luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), {0, 0}}; + luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), + luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), + luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), + {0,0} +}; /////////////////////////////////////// /* @@ -393,22 +419,22 @@ int LuaPseudoRandom::l_next(lua_State *L) if (lua_isnumber(L, 3)) max = luaL_checkinteger(L, 3); if (max < min) { - errorstream << "PseudoRandom.next(): max=" << max << " min=" << min - << std::endl; + errorstream<<"PseudoRandom.next(): max="< 32767 / 5) + if(max - min != 32767 && max - min > 32767/5) throw LuaError("PseudoRandom.next() max-min is not 32767" - " and is > 32768/5. This is disallowed due to" - " the bad random distribution the" - " implementation would otherwise make."); + " and is > 32768/5. This is disallowed due to" + " the bad random distribution the" + " implementation would otherwise make."); PseudoRandom &pseudo = o->m_pseudo; int val = pseudo.next(); - val = (val % (max - min + 1)) + min; + val = (val % (max-min+1)) + min; lua_pushinteger(L, val); return 1; } + int LuaPseudoRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -421,6 +447,7 @@ int LuaPseudoRandom::create_object(lua_State *L) return 1; } + int LuaPseudoRandom::gc_object(lua_State *L) { LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1)); @@ -428,6 +455,7 @@ int LuaPseudoRandom::gc_object(lua_State *L) return 0; } + LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -437,6 +465,7 @@ LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) return *(LuaPseudoRandom **)ud; } + void LuaPseudoRandom::Register(lua_State *L) { lua_newtable(L); @@ -464,8 +493,12 @@ void LuaPseudoRandom::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPseudoRandom::className[] = "PseudoRandom"; -const luaL_Reg LuaPseudoRandom::methods[] = {luamethod(LuaPseudoRandom, next), {0, 0}}; +const luaL_Reg LuaPseudoRandom::methods[] = { + luamethod(LuaPseudoRandom, next), + {0,0} +}; /////////////////////////////////////// /* @@ -484,6 +517,7 @@ int LuaPcgRandom::l_next(lua_State *L) return 1; } + int LuaPcgRandom::l_rand_normal_dist(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -497,19 +531,22 @@ int LuaPcgRandom::l_rand_normal_dist(lua_State *L) return 1; } + int LuaPcgRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; u64 seed = luaL_checknumber(L, 1); - LuaPcgRandom *o = lua_isnumber(L, 2) ? new LuaPcgRandom(seed, lua_tointeger(L, 2)) - : new LuaPcgRandom(seed); + LuaPcgRandom *o = lua_isnumber(L, 2) ? + new LuaPcgRandom(seed, lua_tointeger(L, 2)) : + new LuaPcgRandom(seed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } + int LuaPcgRandom::gc_object(lua_State *L) { LuaPcgRandom *o = *(LuaPcgRandom **)(lua_touserdata(L, 1)); @@ -517,6 +554,7 @@ int LuaPcgRandom::gc_object(lua_State *L) return 0; } + LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -526,6 +564,7 @@ LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) return *(LuaPcgRandom **)ud; } + void LuaPcgRandom::Register(lua_State *L) { lua_newtable(L); @@ -553,9 +592,13 @@ void LuaPcgRandom::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPcgRandom::className[] = "PcgRandom"; -const luaL_Reg LuaPcgRandom::methods[] = {luamethod(LuaPcgRandom, next), - luamethod(LuaPcgRandom, rand_normal_dist), {0, 0}}; +const luaL_Reg LuaPcgRandom::methods[] = { + luamethod(LuaPcgRandom, next), + luamethod(LuaPcgRandom, rand_normal_dist), + {0,0} +}; /////////////////////////////////////// /* @@ -590,8 +633,7 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) // Refill buffer and copy over the remainder of what was requested o->fillRandBuf(); - memcpy(output_buf + count_remaining, o->m_rand_buf, - count - count_remaining); + memcpy(output_buf + count_remaining, o->m_rand_buf, count - count_remaining); // Update index o->m_rand_idx = count - count_remaining; @@ -602,6 +644,7 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) return 1; } + int LuaSecureRandom::create_object(lua_State *L) { LuaSecureRandom *o = new LuaSecureRandom(); @@ -618,6 +661,7 @@ int LuaSecureRandom::create_object(lua_State *L) return 1; } + int LuaSecureRandom::gc_object(lua_State *L) { LuaSecureRandom *o = *(LuaSecureRandom **)(lua_touserdata(L, 1)); @@ -625,6 +669,7 @@ int LuaSecureRandom::gc_object(lua_State *L) return 0; } + LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -634,6 +679,7 @@ LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) return *(LuaSecureRandom **)ud; } + void LuaSecureRandom::Register(lua_State *L) { lua_newtable(L); @@ -663,4 +709,6 @@ void LuaSecureRandom::Register(lua_State *L) const char LuaSecureRandom::className[] = "SecureRandom"; const luaL_Reg LuaSecureRandom::methods[] = { - luamethod(LuaSecureRandom, next_bytes), {0, 0}}; + luamethod(LuaSecureRandom, next_bytes), + {0,0} +}; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 5d48ee93d..e7394133a 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -39,16 +39,16 @@ with this program; if not, write to the Free Software Foundation, Inc., ObjectRef */ -ObjectRef *ObjectRef::checkobject(lua_State *L, int narg) + +ObjectRef* ObjectRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(ObjectRef **)ud; // unbox pointer + if (!ud) luaL_typerror(L, narg, className); + return *(ObjectRef**)ud; // unbox pointer } -ServerActiveObject *ObjectRef::getobject(ObjectRef *ref) +ServerActiveObject* ObjectRef::getobject(ObjectRef *ref) { ServerActiveObject *co = ref->m_object; if (co && co->isGone()) @@ -56,24 +56,24 @@ ServerActiveObject *ObjectRef::getobject(ObjectRef *ref) return co; } -LuaEntitySAO *ObjectRef::getluaobject(ObjectRef *ref) +LuaEntitySAO* ObjectRef::getluaobject(ObjectRef *ref) { ServerActiveObject *obj = getobject(ref); if (obj == NULL) return NULL; if (obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY) return NULL; - return (LuaEntitySAO *)obj; + return (LuaEntitySAO*)obj; } -PlayerSAO *ObjectRef::getplayersao(ObjectRef *ref) +PlayerSAO* ObjectRef::getplayersao(ObjectRef *ref) { ServerActiveObject *obj = getobject(ref); if (obj == NULL) return NULL; if (obj->getType() != ACTIVEOBJECT_TYPE_PLAYER) return NULL; - return (PlayerSAO *)obj; + return (PlayerSAO*)obj; } RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) @@ -87,10 +87,9 @@ RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) // Exported functions // garbage collector -int ObjectRef::gc_object(lua_State *L) -{ +int ObjectRef::gc_object(lua_State *L) { ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1)); - // infostream<<"ObjectRef::gc_object: o="<(L, -1))) { + !reason.setTypeFromString(readParam(L, -1))) { errorstream << "Bad type given!" << std::endl; } lua_pop(L, 1); @@ -295,8 +287,7 @@ int ObjectRef::l_get_inventory(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it InventoryLocation loc = co->getInventoryLocation(); if (getServerInventoryMgr(L)->getInventory(loc) != NULL) @@ -356,8 +347,7 @@ int ObjectRef::l_set_wielded_item(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it ItemStack item = read_item(L, 2, getServer(L)->idef()); bool success = co->setWieldedItem(item); @@ -374,8 +364,7 @@ int ObjectRef::l_set_armor_groups(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it ItemGroupList groups; read_groups(L, 2, groups); @@ -402,9 +391,8 @@ int ObjectRef::l_set_physics_override(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = (PlayerSAO *)getobject(ref); - if (co == NULL) - return 0; + PlayerSAO *co = (PlayerSAO *) getobject(ref); + if (co == NULL) return 0; // Do it if (lua_istable(L, 2)) { co->m_physics_override_speed = getfloatfield_default( @@ -415,8 +403,8 @@ int ObjectRef::l_set_physics_override(lua_State *L) L, 2, "gravity", co->m_physics_override_gravity); co->m_physics_override_sneak = getboolfield_default( L, 2, "sneak", co->m_physics_override_sneak); - co->m_physics_override_sneak_glitch = getboolfield_default(L, 2, - "sneak_glitch", co->m_physics_override_sneak_glitch); + co->m_physics_override_sneak_glitch = getboolfield_default( + L, 2, "sneak_glitch", co->m_physics_override_sneak_glitch); co->m_physics_override_new_move = getboolfield_default( L, 2, "new_move", co->m_physics_override_new_move); co->m_physics_override_sent = false; @@ -469,8 +457,7 @@ int ObjectRef::l_set_animation(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v2f frames = v2f(1, 1); if (!lua_isnil(L, 2)) @@ -497,7 +484,7 @@ int ObjectRef::l_get_animation(lua_State *L) if (co == NULL) return 0; // Do it - v2f frames = v2f(1, 1); + v2f frames = v2f(1,1); float frame_speed = 15; float frame_blend = 0; bool frame_loop = true; @@ -520,9 +507,9 @@ int ObjectRef::l_set_local_animation(lua_State *L) return 0; // Do it v2s32 frames[4]; - for (int i = 0; i < 4; i++) { - if (!lua_isnil(L, 2 + 1)) - frames[i] = read_v2s32(L, 2 + i); + for (int i=0;i<4;i++) { + if (!lua_isnil(L, 2+1)) + frames[i] = read_v2s32(L, 2+i); } float frame_speed = 30; if (!lua_isnil(L, 6)) @@ -572,10 +559,10 @@ int ObjectRef::l_set_eye_offset(lua_State *L) offset_third = read_v3f(L, 3); // Prevent abuse of offset values (keep player always visible) - offset_third.X = rangelim(offset_third.X, -10, 10); - offset_third.Z = rangelim(offset_third.Z, -5, 5); + offset_third.X = rangelim(offset_third.X,-10,10); + offset_third.Z = rangelim(offset_third.Z,-5,5); /* TODO: if possible: improve the camera colision detetion to allow Y <= -1.5) */ - offset_third.Y = rangelim(offset_third.Y, -10, 15); // 1.5*BS + offset_third.Y = rangelim(offset_third.Y,-10,15); //1.5*BS getServer(L)->setPlayerEyeOffset(player, offset_first, offset_third); lua_pushboolean(L, true); @@ -640,8 +627,7 @@ int ObjectRef::l_set_bone_position(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string bone; if (!lua_isnil(L, 2)) @@ -694,8 +680,7 @@ int ObjectRef::l_set_attach(lua_State *L) return 0; if (co == parent) - throw LuaError("ObjectRef::set_attach: attaching object to itself is not " - "allowed."); + throw LuaError("ObjectRef::set_attach: attaching object to itself is not allowed."); // Do it int parent_id = 0; @@ -866,8 +851,7 @@ int ObjectRef::l_set_velocity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; v3f pos = checkFloatPos(L, 2); // Do it co->setVelocity(pos); @@ -894,8 +878,7 @@ int ObjectRef::l_get_velocity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v3f v = co->getVelocity(); pushFloatPos(L, v); @@ -908,8 +891,7 @@ int ObjectRef::l_set_acceleration(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // Do it @@ -923,8 +905,7 @@ int ObjectRef::l_get_acceleration(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v3f v = co->getAcceleration(); pushFloatPos(L, v); @@ -970,8 +951,7 @@ int ObjectRef::l_set_yaw(lua_State *L) ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; if (isNaN(L, 2)) throw LuaError("ObjectRef::set_yaw: NaN value is not allowed."); @@ -1000,8 +980,7 @@ int ObjectRef::l_set_texture_mod(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string mod = luaL_checkstring(L, 2); co->setTextureMod(mod); @@ -1014,8 +993,7 @@ int ObjectRef::l_get_texture_mod(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string mod = co->getTextureMod(); lua_pushstring(L, mod.c_str()); @@ -1029,10 +1007,9 @@ int ObjectRef::l_set_sprite(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it - v2s16 p(0, 0); + v2s16 p(0,0); if (!lua_isnil(L, 2)) p = readParam(L, 2); int num_frames = 1; @@ -1055,9 +1032,8 @@ int ObjectRef::l_get_entity_name(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - log_deprecated(L, "Deprecated call to \"get_entity_name"); - if (co == NULL) - return 0; + log_deprecated(L,"Deprecated call to \"get_entity_name"); + if (co == NULL) return 0; // Do it std::string name = co->getName(); lua_pushstring(L, name.c_str()); @@ -1070,8 +1046,7 @@ int ObjectRef::l_get_luaentity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it luaentity_get(L, co->getId()); return 1; @@ -1085,7 +1060,7 @@ int ObjectRef::l_is_player_connected(lua_State *L) NO_MAP_LOCK_REQUIRED; // This method was once added for a bugfix, but never documented log_deprecated(L, "is_player_connected is undocumented and " - "will be removed in a future release"); + "will be removed in a future release"); ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); lua_pushboolean(L, (player != NULL && player->getPeerId() != PEER_ID_INEXISTENT)); @@ -1144,14 +1119,13 @@ int ObjectRef::l_get_look_dir(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it float pitch = co->getRadLookPitchDep(); float yaw = co->getRadYawDep(); - v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), - std::cos(pitch) * std::sin(yaw)); + v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), std::cos(pitch) * + std::sin(yaw)); push_v3f(L, v); return 1; } @@ -1162,13 +1136,12 @@ int ObjectRef::l_get_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to get_look_pitch, use get_look_vertical " - "instead"); + log_deprecated(L, + "Deprecated call to get_look_pitch, use get_look_vertical instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitchDep()); return 1; @@ -1180,13 +1153,12 @@ int ObjectRef::l_get_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to get_look_yaw, use get_look_horizontal " - "instead"); + log_deprecated(L, + "Deprecated call to get_look_yaw, use get_look_horizontal instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadYawDep()); return 1; @@ -1197,9 +1169,8 @@ int ObjectRef::l_get_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitch()); return 1; @@ -1210,9 +1181,8 @@ int ObjectRef::l_get_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadRotation().Y); return 1; @@ -1223,9 +1193,8 @@ int ObjectRef::l_set_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float pitch = readParam(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); @@ -1237,9 +1206,8 @@ int ObjectRef::l_set_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float yaw = readParam(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); @@ -1252,13 +1220,12 @@ int ObjectRef::l_set_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to set_look_pitch, use set_look_vertical " - "instead."); + log_deprecated(L, + "Deprecated call to set_look_pitch, use set_look_vertical instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float pitch = readParam(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); @@ -1271,13 +1238,12 @@ int ObjectRef::l_set_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to set_look_yaw, use set_look_horizontal " - "instead."); + log_deprecated(L, + "Deprecated call to set_look_yaw, use set_look_horizontal instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float yaw = readParam(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); @@ -1293,10 +1259,11 @@ int ObjectRef::l_set_fov(lua_State *L) if (!player) return 0; - player->setFov({static_cast(luaL_checknumber(L, 2)), - readParam(L, 3, false), - lua_isnumber(L, 4) ? static_cast(luaL_checknumber(L, 4)) - : 0.0f}); + player->setFov({ + static_cast(luaL_checknumber(L, 2)), + readParam(L, 3, false), + lua_isnumber(L, 4) ? static_cast(luaL_checknumber(L, 4)) : 0.0f + }); getServer(L)->SendPlayerFov(player->getPeerId()); return 0; @@ -1324,9 +1291,8 @@ int ObjectRef::l_set_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; u16 breath = luaL_checknumber(L, 2); co->setBreath(breath); @@ -1338,23 +1304,22 @@ int ObjectRef::l_get_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it u16 breath = co->getBreath(); - lua_pushinteger(L, breath); + lua_pushinteger (L, breath); return 1; } // set_attribute(self, attribute, value) int ObjectRef::l_set_attribute(lua_State *L) { - log_deprecated(L, "Deprecated call to set_attribute, use MetaDataRef methods " - "instead."); + log_deprecated(L, + "Deprecated call to set_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); + PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; @@ -1371,11 +1336,11 @@ int ObjectRef::l_set_attribute(lua_State *L) // get_attribute(self, attribute) int ObjectRef::l_get_attribute(lua_State *L) { - log_deprecated(L, "Deprecated call to get_attribute, use MetaDataRef methods " - "instead."); + log_deprecated(L, + "Deprecated call to get_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); + PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; @@ -1390,6 +1355,7 @@ int ObjectRef::l_get_attribute(lua_State *L) return 0; } + // get_meta(self, attribute) int ObjectRef::l_get_meta(lua_State *L) { @@ -1402,14 +1368,14 @@ int ObjectRef::l_get_meta(lua_State *L) return 1; } + // set_inventory_formspec(self, formspec) int ObjectRef::l_set_inventory_formspec(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) - return 0; + if (player == NULL) return 0; std::string formspec = luaL_checkstring(L, 2); player->inventory_formspec = formspec; @@ -1424,8 +1390,7 @@ int ObjectRef::l_get_inventory_formspec(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) - return 0; + if (player == NULL) return 0; std::string formspec = player->inventory_formspec; lua_pushlstring(L, formspec.c_str(), formspec.size()); @@ -1456,7 +1421,7 @@ int ObjectRef::l_get_formspec_prepend(lua_State *L) ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) - return 0; + return 0; std::string formspec = player->formspec_prepend; lua_pushlstring(L, formspec.c_str(), formspec.size()); @@ -1608,14 +1573,14 @@ int ObjectRef::l_hud_set_flags(lua_State *L) return 0; u32 flags = 0; - u32 mask = 0; + u32 mask = 0; bool flag; const EnumString *esp = es_HudBuiltinElement; for (int i = 0; esp[i].str; i++) { if (getboolfield(L, 2, esp[i].str, flag)) { flags |= esp[i].num * flag; - mask |= esp[i].num; + mask |= esp[i].num; } } if (!getServer(L)->hudSetFlags(player, flags, mask)) @@ -1770,8 +1735,7 @@ int ObjectRef::l_set_sky(lua_State *L) lua_pushnil(L); while (lua_next(L, -2) != 0) { // Key is at index -2 and value at index -1 - skybox_params.textures.emplace_back( - readParam(L, -1)); + skybox_params.textures.emplace_back(readParam(L, -1)); // Removes the value, but keeps the key for iteration lua_pop(L, 1); } @@ -1784,12 +1748,11 @@ int ObjectRef::l_set_sky(lua_State *L) using "regular" or "plain" skybox modes as textures aren't needed. */ - if (skybox_params.textures.size() != 6 && - skybox_params.textures.size() > 0) + if (skybox_params.textures.size() != 6 && skybox_params.textures.size() > 0) throw LuaError("Skybox expects 6 textures!"); - skybox_params.clouds = getboolfield_default( - L, 2, "clouds", skybox_params.clouds); + skybox_params.clouds = getboolfield_default(L, 2, + "clouds", skybox_params.clouds); lua_getfield(L, 2, "sky_color"); if (lua_istable(L, -1)) { @@ -1873,10 +1836,9 @@ int ObjectRef::l_set_sky(lua_State *L) if (lua_istable(L, 4)) { lua_pushnil(L); while (lua_next(L, 4) != 0) { - // Key at index -2, and value at index -1 + // Key at index -2, and value at index -1 if (lua_isstring(L, -1)) - skybox_params.textures.emplace_back( - readParam(L, -1)); + skybox_params.textures.emplace_back(readParam(L, -1)); else skybox_params.textures.emplace_back(""); // Remove the value, keep the key for the next iteration @@ -1916,7 +1878,7 @@ int ObjectRef::l_get_sky(lua_State *L) lua_newtable(L); s16 i = 1; - for (const std::string &texture : skybox_params.textures) { + for (const std::string& texture : skybox_params.textures) { lua_pushlstring(L, texture.c_str(), texture.size()); lua_rawseti(L, -2, i++); } @@ -1934,7 +1896,7 @@ int ObjectRef::l_get_sky_color(lua_State *L) if (!player) return 0; - const SkyboxParams &skybox_params = player->getSkyParams(); + const SkyboxParams& skybox_params = player->getSkyParams(); lua_newtable(L); if (skybox_params.type == "regular") { @@ -1976,20 +1938,25 @@ int ObjectRef::l_set_sun(lua_State *L) SunParams sun_params = player->getSunParams(); - sun_params.visible = getboolfield_default(L, 2, "visible", sun_params.visible); - sun_params.texture = getstringfield_default(L, 2, "texture", sun_params.texture); - sun_params.tonemap = getstringfield_default(L, 2, "tonemap", sun_params.tonemap); - sun_params.sunrise = getstringfield_default(L, 2, "sunrise", sun_params.sunrise); - sun_params.sunrise_visible = getboolfield_default( - L, 2, "sunrise_visible", sun_params.sunrise_visible); - sun_params.scale = getfloatfield_default(L, 2, "scale", sun_params.scale); + sun_params.visible = getboolfield_default(L, 2, + "visible", sun_params.visible); + sun_params.texture = getstringfield_default(L, 2, + "texture", sun_params.texture); + sun_params.tonemap = getstringfield_default(L, 2, + "tonemap", sun_params.tonemap); + sun_params.sunrise = getstringfield_default(L, 2, + "sunrise", sun_params.sunrise); + sun_params.sunrise_visible = getboolfield_default(L, 2, + "sunrise_visible", sun_params.sunrise_visible); + sun_params.scale = getfloatfield_default(L, 2, + "scale", sun_params.scale); getServer(L)->setSun(player, sun_params); lua_pushboolean(L, true); return 1; } -// get_sun(self) +//get_sun(self) int ObjectRef::l_get_sun(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -2029,12 +1996,14 @@ int ObjectRef::l_set_moon(lua_State *L) MoonParams moon_params = player->getMoonParams(); - moon_params.visible = getboolfield_default(L, 2, "visible", moon_params.visible); - moon_params.texture = - getstringfield_default(L, 2, "texture", moon_params.texture); - moon_params.tonemap = - getstringfield_default(L, 2, "tonemap", moon_params.tonemap); - moon_params.scale = getfloatfield_default(L, 2, "scale", moon_params.scale); + moon_params.visible = getboolfield_default(L, 2, + "visible", moon_params.visible); + moon_params.texture = getstringfield_default(L, 2, + "texture", moon_params.texture); + moon_params.tonemap = getstringfield_default(L, 2, + "tonemap", moon_params.tonemap); + moon_params.scale = getfloatfield_default(L, 2, + "scale", moon_params.scale); getServer(L)->setMoon(player, moon_params); lua_pushboolean(L, true); @@ -2077,15 +2046,18 @@ int ObjectRef::l_set_stars(lua_State *L) StarParams star_params = player->getStarParams(); - star_params.visible = getboolfield_default(L, 2, "visible", star_params.visible); - star_params.count = getintfield_default(L, 2, "count", star_params.count); + star_params.visible = getboolfield_default(L, 2, + "visible", star_params.visible); + star_params.count = getintfield_default(L, 2, + "count", star_params.count); lua_getfield(L, 2, "star_color"); if (!lua_isnil(L, -1)) read_color(L, -1, &star_params.starcolor); lua_pop(L, 1); - star_params.scale = getfloatfield_default(L, 2, "scale", star_params.scale); + star_params.scale = getfloatfield_default(L, 2, + "scale", star_params.scale); getServer(L)->setStars(player, star_params); lua_pushboolean(L, true); @@ -2128,8 +2100,7 @@ int ObjectRef::l_set_clouds(lua_State *L) CloudParams cloud_params = player->getCloudParams(); - cloud_params.density = - getfloatfield_default(L, 2, "density", cloud_params.density); + cloud_params.density = getfloatfield_default(L, 2, "density", cloud_params.density); lua_getfield(L, 2, "color"); if (!lua_isnil(L, -1)) @@ -2140,9 +2111,8 @@ int ObjectRef::l_set_clouds(lua_State *L) read_color(L, -1, &cloud_params.color_ambient); lua_pop(L, 1); - cloud_params.height = getfloatfield_default(L, 2, "height", cloud_params.height); - cloud_params.thickness = - getfloatfield_default(L, 2, "thickness", cloud_params.thickness); + cloud_params.height = getfloatfield_default(L, 2, "height", cloud_params.height ); + cloud_params.thickness = getfloatfield_default(L, 2, "thickness", cloud_params.thickness); lua_getfield(L, 2, "speed"); if (lua_istable(L, -1)) { @@ -2188,6 +2158,7 @@ int ObjectRef::l_get_clouds(lua_State *L) return 1; } + // override_day_night_ratio(self, brightness=0...1) int ObjectRef::l_override_day_night_ratio(lua_State *L) { @@ -2230,9 +2201,10 @@ int ObjectRef::l_get_day_night_ratio(lua_State *L) return 1; } -ObjectRef::ObjectRef(ServerActiveObject *object) : m_object(object) +ObjectRef::ObjectRef(ServerActiveObject *object): + m_object(object) { - // infostream<<"ObjectRef created for id="<getId()< 1) // deprecated { log_deprecated(L, "Deprecated add_particle call with " - "individual parameters instead of definition"); + "individual parameters instead of definition"); p.pos = check_v3f(L, 1); p.vel = check_v3f(L, 2); p.acc = check_v3f(L, 3); @@ -59,7 +59,9 @@ int ModApiParticles::l_add_particle(lua_State *L) p.texture = luaL_checkstring(L, 7); if (lua_gettop(L) == 8) // only spawn for a single player playername = luaL_checkstring(L, 8); - } else if (lua_istable(L, 1)) { + } + else if (lua_istable(L, 1)) + { lua_getfield(L, 1, "pos"); if (lua_istable(L, -1)) p.pos = check_v3f(L, -1); @@ -69,7 +71,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_istable(L, -1)) { p.vel = check_v3f(L, -1); log_deprecated(L, "The use of vel is deprecated. " - "Use velocity instead"); + "Use velocity instead"); } lua_pop(L, 1); @@ -82,7 +84,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_istable(L, -1)) { p.acc = check_v3f(L, -1); log_deprecated(L, "The use of acc is deprecated. " - "Use acceleration instead"); + "Use acceleration instead"); } lua_pop(L, 1); @@ -91,15 +93,15 @@ int ModApiParticles::l_add_particle(lua_State *L) p.acc = check_v3f(L, -1); lua_pop(L, 1); - p.expirationtime = getfloatfield_default( - L, 1, "expirationtime", p.expirationtime); + p.expirationtime = getfloatfield_default(L, 1, "expirationtime", + p.expirationtime); p.size = getfloatfield_default(L, 1, "size", p.size); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); p.vertical = getboolfield_default(L, 1, "vertical", p.vertical); lua_getfield(L, 1, "animation"); @@ -154,10 +156,10 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) ServerActiveObject *attached = NULL; std::string playername; - if (lua_gettop(L) > 1) // deprecated + if (lua_gettop(L) > 1) //deprecated { log_deprecated(L, "Deprecated add_particlespawner call with " - "individual parameters instead of definition"); + "individual parameters instead of definition"); p.amount = luaL_checknumber(L, 1); p.time = luaL_checknumber(L, 2); p.minpos = check_v3f(L, 3); @@ -174,7 +176,9 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) p.texture = luaL_checkstring(L, 14); if (lua_gettop(L) == 15) // only spawn for a single player playername = luaL_checkstring(L, 15); - } else if (lua_istable(L, 1)) { + } + else if (lua_istable(L, 1)) + { p.amount = getintfield_default(L, 1, "amount", p.amount); p.time = getfloatfield_default(L, 1, "time", p.time); @@ -212,12 +216,12 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) p.maxexptime = getfloatfield_default(L, 1, "maxexptime", p.maxexptime); p.minsize = getfloatfield_default(L, 1, "minsize", p.minsize); p.maxsize = getfloatfield_default(L, 1, "maxsize", p.maxsize); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); lua_getfield(L, 1, "animation"); p.animation = read_animation_definition(L, -1); @@ -272,3 +276,4 @@ void ModApiParticles::Initialize(lua_State *L, int top) API_FCT(add_particlespawner); API_FCT(delete_particlespawner); } + diff --git a/src/script/lua_api/l_particles.h b/src/script/lua_api/l_particles.h index 8734e5516..122810b6d 100644 --- a/src/script/lua_api/l_particles.h +++ b/src/script/lua_api/l_particles.h @@ -21,8 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_base.h" -class ModApiParticles : public ModApiBase -{ +class ModApiParticles : public ModApiBase { private: static int l_add_particle(lua_State *L); static int l_add_particlespawner(lua_State *L); diff --git a/src/script/lua_api/l_particles_local.cpp b/src/script/lua_api/l_particles_local.cpp index 498376d40..cc68b13a5 100644 --- a/src/script/lua_api/l_particles_local.cpp +++ b/src/script/lua_api/l_particles_local.cpp @@ -49,15 +49,15 @@ int ModApiParticlesLocal::l_add_particle(lua_State *L) p.acc = check_v3f(L, -1); lua_pop(L, 1); - p.expirationtime = - getfloatfield_default(L, 1, "expirationtime", p.expirationtime); + p.expirationtime = getfloatfield_default(L, 1, "expirationtime", + p.expirationtime); p.size = getfloatfield_default(L, 1, "size", p.size); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); p.vertical = getboolfield_default(L, 1, "vertical", p.vertical); lua_getfield(L, 1, "animation"); @@ -75,7 +75,7 @@ int ModApiParticlesLocal::l_add_particle(lua_State *L) p.node_tile = getintfield_default(L, 1, "node_tile", p.node_tile); ClientEvent *event = new ClientEvent(); - event->type = CE_SPAWN_PARTICLE; + event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); getClient(L)->pushToEventQueue(event); @@ -126,12 +126,12 @@ int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) p.maxexptime = getfloatfield_default(L, 1, "maxexptime", p.maxexptime); p.minsize = getfloatfield_default(L, 1, "minsize", p.minsize); p.maxsize = getfloatfield_default(L, 1, "maxsize", p.maxsize); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); lua_getfield(L, 1, "animation"); p.animation = read_animation_definition(L, -1); @@ -151,10 +151,10 @@ int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) u64 id = getClient(L)->getParticleManager()->generateSpawnerId(); auto event = new ClientEvent(); - event->type = CE_ADD_PARTICLESPAWNER; - event->add_particlespawner.p = new ParticleSpawnerParameters(p); + event->type = CE_ADD_PARTICLESPAWNER; + event->add_particlespawner.p = new ParticleSpawnerParameters(p); event->add_particlespawner.attached_id = 0; - event->add_particlespawner.id = id; + event->add_particlespawner.id = id; getClient(L)->pushToEventQueue(event); lua_pushnumber(L, id); @@ -168,7 +168,7 @@ int ModApiParticlesLocal::l_delete_particlespawner(lua_State *L) u32 id = luaL_checknumber(L, 1); ClientEvent *event = new ClientEvent(); - event->type = CE_DELETE_PARTICLESPAWNER; + event->type = CE_DELETE_PARTICLESPAWNER; event->delete_particlespawner.id = id; getClient(L)->pushToEventQueue(event); diff --git a/src/script/lua_api/l_rollback.cpp b/src/script/lua_api/l_rollback.cpp index 09da123c3..482b0cbf5 100644 --- a/src/script/lua_api/l_rollback.cpp +++ b/src/script/lua_api/l_rollback.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "rollback_interface.h" + void push_RollbackNode(lua_State *L, RollbackNode &node) { lua_createtable(L, 0, 3); @@ -34,15 +35,14 @@ void push_RollbackNode(lua_State *L, RollbackNode &node) lua_setfield(L, -2, "param2"); } -// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, -// newnode}, ...} +// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, newnode}, ...} int ModApiRollback::l_rollback_get_node_actions(lua_State *L) { NO_MAP_LOCK_REQUIRED; v3s16 pos = read_v3s16(L, 1); int range = luaL_checknumber(L, 2); - time_t seconds = (time_t)luaL_checknumber(L, 3); + time_t seconds = (time_t) luaL_checknumber(L, 3); int limit = luaL_checknumber(L, 4); Server *server = getServer(L); IRollbackManager *rollback = server->getRollbackManager(); @@ -50,8 +50,7 @@ int ModApiRollback::l_rollback_get_node_actions(lua_State *L) return 0; } - std::list actions = - rollback->getNodeActors(pos, range, seconds, limit); + std::list actions = rollback->getNodeActors(pos, range, seconds, limit); std::list::iterator iter = actions.begin(); lua_createtable(L, actions.size(), 0); @@ -102,8 +101,8 @@ int ModApiRollback::l_rollback_revert_actions_by(lua_State *L) lua_pushboolean(L, success); lua_createtable(L, log.size(), 0); unsigned long i = 0; - for (std::list::const_iterator iter = log.begin(); iter != log.end(); - ++i, ++iter) { + for(std::list::const_iterator iter = log.begin(); + iter != log.end(); ++i, ++iter) { lua_pushnumber(L, i); lua_pushstring(L, iter->c_str()); lua_settable(L, -3); diff --git a/src/script/lua_api/l_rollback.h b/src/script/lua_api/l_rollback.h index 74d8ce10e..c26ff634e 100644 --- a/src/script/lua_api/l_rollback.h +++ b/src/script/lua_api/l_rollback.h @@ -24,8 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class ModApiRollback : public ModApiBase { private: - // rollback_get_node_actions(pos, range, seconds) -> {{actor, pos, time, oldnode, - // newnode}, ...} + // rollback_get_node_actions(pos, range, seconds) -> {{actor, pos, time, oldnode, newnode}, ...} static int l_rollback_get_node_actions(lua_State *L); // rollback_revert_actions_by(actor, seconds) -> bool, log messages diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index f4362dd7f..64ae924d2 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -56,6 +56,7 @@ int ModApiServer::l_get_server_uptime(lua_State *L) return 1; } + // print(text) int ModApiServer::l_print(lua_State *L) { @@ -115,14 +116,15 @@ int ModApiServer::l_get_player_privs(lua_State *L) int ModApiServer::l_get_player_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *name = luaL_checkstring(L, 1); - RemotePlayer *player = - dynamic_cast(getEnv(L))->getPlayer(name); - if (player == NULL) { + const char * name = luaL_checkstring(L, 1); + RemotePlayer *player = dynamic_cast(getEnv(L))->getPlayer(name); + if(player == NULL) + { lua_pushnil(L); // no such player return 1; } - try { + try + { Address addr = getServer(L)->getPeerAddress(player->getPeerId()); std::string ip_str = addr.serializeString(); lua_pushstring(L, ip_str.c_str()); @@ -164,19 +166,21 @@ int ModApiServer::l_get_player_information(lua_State *L) u8 ser_vers, major, minor, patch; std::string vers_string, lang_code; - auto getConInfo = [&](con::rtt_stat_type type, float *value) -> bool { + auto getConInfo = [&] (con::rtt_stat_type type, float *value) -> bool { return server->getClientConInfo(player->getPeerId(), type, value); }; - bool have_con_info = getConInfo(con::MIN_RTT, &min_rtt) && - getConInfo(con::MAX_RTT, &max_rtt) && - getConInfo(con::AVG_RTT, &avg_rtt) && - getConInfo(con::MIN_JITTER, &min_jitter) && - getConInfo(con::MAX_JITTER, &max_jitter) && - getConInfo(con::AVG_JITTER, &avg_jitter); - - bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, &ser_vers, - &prot_vers, &major, &minor, &patch, &vers_string, &lang_code); + bool have_con_info = + getConInfo(con::MIN_RTT, &min_rtt) && + getConInfo(con::MAX_RTT, &max_rtt) && + getConInfo(con::AVG_RTT, &avg_rtt) && + getConInfo(con::MIN_JITTER, &min_jitter) && + getConInfo(con::MAX_JITTER, &max_jitter) && + getConInfo(con::AVG_JITTER, &avg_jitter); + + bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, + &ser_vers, &prot_vers, &major, &minor, &patch, &vers_string, + &lang_code); if (!r) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushnil(L); // error @@ -186,11 +190,11 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_newtable(L); int table = lua_gettop(L); - lua_pushstring(L, "address"); + lua_pushstring(L,"address"); lua_pushstring(L, addr.serializeString().c_str()); lua_settable(L, table); - lua_pushstring(L, "ip_version"); + lua_pushstring(L,"ip_version"); if (addr.getFamily() == AF_INET) { lua_pushnumber(L, 4); } else if (addr.getFamily() == AF_INET6) { @@ -226,11 +230,11 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); } - lua_pushstring(L, "connection_uptime"); + lua_pushstring(L,"connection_uptime"); lua_pushnumber(L, uptime); lua_settable(L, table); - lua_pushstring(L, "protocol_version"); + lua_pushstring(L,"protocol_version"); lua_pushnumber(L, prot_vers); lua_settable(L, table); @@ -243,28 +247,28 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); #ifndef NDEBUG - lua_pushstring(L, "serialization_version"); + lua_pushstring(L,"serialization_version"); lua_pushnumber(L, ser_vers); lua_settable(L, table); - lua_pushstring(L, "major"); + lua_pushstring(L,"major"); lua_pushnumber(L, major); lua_settable(L, table); - lua_pushstring(L, "minor"); + lua_pushstring(L,"minor"); lua_pushnumber(L, minor); lua_settable(L, table); - lua_pushstring(L, "patch"); + lua_pushstring(L,"patch"); lua_pushnumber(L, patch); lua_settable(L, table); - lua_pushstring(L, "version_string"); + lua_pushstring(L,"version_string"); lua_pushstring(L, vers_string.c_str()); lua_settable(L, table); - lua_pushstring(L, "state"); - lua_pushstring(L, ClientInterface::state2Name(state).c_str()); + lua_pushstring(L,"state"); + lua_pushstring(L,ClientInterface::state2Name(state).c_str()); lua_settable(L, table); #endif @@ -283,9 +287,8 @@ int ModApiServer::l_get_ban_list(lua_State *L) int ModApiServer::l_get_ban_description(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *ip_or_name = luaL_checkstring(L, 1); - lua_pushstring(L, - getServer(L)->getBanDescription(std::string(ip_or_name)).c_str()); + const char * ip_or_name = luaL_checkstring(L, 1); + lua_pushstring(L, getServer(L)->getBanDescription(std::string(ip_or_name)).c_str()); return 1; } @@ -293,21 +296,19 @@ int ModApiServer::l_get_ban_description(lua_State *L) int ModApiServer::l_ban_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *name = luaL_checkstring(L, 1); - RemotePlayer *player = - dynamic_cast(getEnv(L))->getPlayer(name); + const char * name = luaL_checkstring(L, 1); + RemotePlayer *player = dynamic_cast(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // no such player return 1; } - try { + try + { Address addr = getServer(L)->getPeerAddress( - dynamic_cast(getEnv(L)) - ->getPlayer(name) - ->getPeerId()); + dynamic_cast(getEnv(L))->getPlayer(name)->getPeerId()); std::string ip_str = addr.serializeString(); getServer(L)->setIpBanned(ip_str, name); - } catch (const con::PeerNotFoundException &) { + } catch(const con::PeerNotFoundException &) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushboolean(L, false); // error return 1; @@ -327,8 +328,7 @@ int ModApiServer::l_kick_player(lua_State *L) else message.append("."); - RemotePlayer *player = - dynamic_cast(getEnv(L))->getPlayer(name); + RemotePlayer *player = dynamic_cast(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // No such player return 1; @@ -359,7 +359,7 @@ int ModApiServer::l_remove_player(lua_State *L) int ModApiServer::l_unban_player_or_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *ip_or_name = luaL_checkstring(L, 1); + const char * ip_or_name = luaL_checkstring(L, 1); getServer(L)->unsetIpBanned(ip_or_name); lua_pushboolean(L, true); return 1; @@ -373,9 +373,10 @@ int ModApiServer::l_show_formspec(lua_State *L) const char *formname = luaL_checkstring(L, 2); const char *formspec = luaL_checkstring(L, 3); - if (getServer(L)->showFormspec(playername, formspec, formname)) { + if(getServer(L)->showFormspec(playername,formspec,formname)) + { lua_pushboolean(L, true); - } else { + }else{ lua_pushboolean(L, false); } return 1; @@ -479,8 +480,7 @@ int ModApiServer::l_dynamic_add_media(lua_State *L) // Reject adding media before the server has started up if (!getEnv(L)) - throw LuaError("Dynamic media cannot be added before server has started " - "up"); + throw LuaError("Dynamic media cannot be added before server has started up"); std::string filepath = readParam(L, 1); CHECK_SECURE_PATH(L, filepath.c_str(), false); @@ -503,7 +503,7 @@ int ModApiServer::l_notify_authentication_modified(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name; - if (lua_isstring(L, 1)) + if(lua_isstring(L, 1)) name = readParam(L, 1); getServer(L)->reportPrivsModified(name); return 0; @@ -529,7 +529,7 @@ int ModApiServer::l_set_last_run_mod(lua_State *L) #ifdef SCRIPTAPI_DEBUG const char *mod = lua_tostring(L, 1); getScriptApiBase(L)->setOriginDirect(mod); - // printf(">>>> last mod set from Lua: %s\n", mod); + //printf(">>>> last mod set from Lua: %s\n", mod); #endif return 0; } diff --git a/src/script/lua_api/l_settings.cpp b/src/script/lua_api/l_settings.cpp index cc4b23ee4..33eb02392 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -25,20 +25,23 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "noise.h" #include "log.h" -#define SET_SECURITY_CHECK(L, name) \ - if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ - name.compare(0, 7, "secure.") == 0) { \ - throw LuaError("Attempt to set secure setting."); \ + +#define SET_SECURITY_CHECK(L, name) \ + if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ + name.compare(0, 7, "secure.") == 0) { \ + throw LuaError("Attempt to set secure setting."); \ } LuaSettings::LuaSettings(Settings *settings, const std::string &filename) : - m_settings(settings), m_filename(filename) + m_settings(settings), + m_filename(filename) { } LuaSettings::LuaSettings(const std::string &filename, bool write_allowed) : - m_filename(filename), m_is_own_settings(true), - m_write_allowed(write_allowed) + m_filename(filename), + m_is_own_settings(true), + m_write_allowed(write_allowed) { m_settings = new Settings(); m_settings->readConfigFile(filename.c_str()); @@ -50,7 +53,9 @@ LuaSettings::~LuaSettings() delete m_settings; } -void LuaSettings::create(lua_State *L, Settings *settings, const std::string &filename) + +void LuaSettings::create(lua_State *L, Settings *settings, + const std::string &filename) { LuaSettings *o = new LuaSettings(settings, filename); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; @@ -58,19 +63,21 @@ void LuaSettings::create(lua_State *L, Settings *settings, const std::string &fi lua_setmetatable(L, -2); } + // garbage collector -int LuaSettings::gc_object(lua_State *L) +int LuaSettings::gc_object(lua_State* L) { - LuaSettings *o = *(LuaSettings **)(lua_touserdata(L, 1)); + LuaSettings* o = *(LuaSettings **)(lua_touserdata(L, 1)); delete o; return 0; } + // get(self, key) -> value -int LuaSettings::l_get(lua_State *L) +int LuaSettings::l_get(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { @@ -84,10 +91,10 @@ int LuaSettings::l_get(lua_State *L) } // get_bool(self, key) -> boolean -int LuaSettings::l_get_bool(lua_State *L) +int LuaSettings::l_get_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { @@ -146,13 +153,13 @@ int LuaSettings::l_get_flags(lua_State *L) } // set(self, key, value) -int LuaSettings::l_set(lua_State *L) +int LuaSettings::l_set(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); - const char *value = luaL_checkstring(L, 3); + const char* value = luaL_checkstring(L, 3); SET_SECURITY_CHECK(L, key); @@ -163,10 +170,10 @@ int LuaSettings::l_set(lua_State *L) } // set_bool(self, key, value) -int LuaSettings::l_set_bool(lua_State *L) +int LuaSettings::l_set_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); bool value = readParam(L, 3); @@ -196,10 +203,10 @@ int LuaSettings::l_set_np_group(lua_State *L) } // remove(self, key) -> success -int LuaSettings::l_remove(lua_State *L) +int LuaSettings::l_remove(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); @@ -212,15 +219,16 @@ int LuaSettings::l_remove(lua_State *L) } // get_names(self) -> {key1, ...} -int LuaSettings::l_get_names(lua_State *L) +int LuaSettings::l_get_names(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::vector keys = o->m_settings->getNames(); lua_newtable(L); - for (unsigned int i = 0; i < keys.size(); i++) { + for (unsigned int i=0; i < keys.size(); i++) + { lua_pushstring(L, keys[i].c_str()); lua_rawseti(L, -2, i + 1); } @@ -229,10 +237,10 @@ int LuaSettings::l_get_names(lua_State *L) } // write(self) -> success -int LuaSettings::l_write(lua_State *L) +int LuaSettings::l_write(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); if (!o->m_write_allowed) { throw LuaError("Settings: writing " + o->m_filename + @@ -246,10 +254,10 @@ int LuaSettings::l_write(lua_State *L) } // to_table(self) -> {[key1]=value1,...} -int LuaSettings::l_to_table(lua_State *L) +int LuaSettings::l_to_table(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::vector keys = o->m_settings->getNames(); @@ -262,7 +270,8 @@ int LuaSettings::l_to_table(lua_State *L) return 1; } -void LuaSettings::Register(lua_State *L) + +void LuaSettings::Register(lua_State* L) { lua_newtable(L); int methodtable = lua_gettop(L); @@ -271,7 +280,7 @@ void LuaSettings::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -281,10 +290,10 @@ void LuaSettings::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (Settings(filename)) lua_register(L, className, create_object); @@ -292,33 +301,41 @@ void LuaSettings::Register(lua_State *L) // LuaSettings(filename) // Creates a LuaSettings and leaves it on top of the stack -int LuaSettings::create_object(lua_State *L) +int LuaSettings::create_object(lua_State* L) { NO_MAP_LOCK_REQUIRED; bool write_allowed = true; - const char *filename = luaL_checkstring(L, 1); + const char* filename = luaL_checkstring(L, 1); CHECK_SECURE_PATH_POSSIBLE_WRITE(L, filename, &write_allowed); - LuaSettings *o = new LuaSettings(filename, write_allowed); + LuaSettings* o = new LuaSettings(filename, write_allowed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } -LuaSettings *LuaSettings::checkobject(lua_State *L, int narg) +LuaSettings* LuaSettings::checkobject(lua_State* L, int narg) { NO_MAP_LOCK_REQUIRED; luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(LuaSettings **)ud; // unbox pointer + return *(LuaSettings**) ud; // unbox pointer } const char LuaSettings::className[] = "Settings"; -const luaL_Reg LuaSettings::methods[] = {luamethod(LuaSettings, get), - luamethod(LuaSettings, get_bool), luamethod(LuaSettings, get_np_group), - luamethod(LuaSettings, get_flags), luamethod(LuaSettings, set), - luamethod(LuaSettings, set_bool), luamethod(LuaSettings, set_np_group), - luamethod(LuaSettings, remove), luamethod(LuaSettings, get_names), - luamethod(LuaSettings, write), luamethod(LuaSettings, to_table), {0, 0}}; +const luaL_Reg LuaSettings::methods[] = { + luamethod(LuaSettings, get), + luamethod(LuaSettings, get_bool), + luamethod(LuaSettings, get_np_group), + luamethod(LuaSettings, get_flags), + luamethod(LuaSettings, set), + luamethod(LuaSettings, set_bool), + luamethod(LuaSettings, set_np_group), + luamethod(LuaSettings, remove), + luamethod(LuaSettings, get_names), + luamethod(LuaSettings, write), + luamethod(LuaSettings, to_table), + {0,0} +}; diff --git a/src/script/lua_api/l_sound.cpp b/src/script/lua_api/l_sound.cpp index bd9ec2543..b86eda53e 100644 --- a/src/script/lua_api/l_sound.cpp +++ b/src/script/lua_api/l_sound.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_content.h" #include "gui/guiEngine.h" + int ModApiSound::l_sound_play(lua_State *L) { SimpleSoundSpec spec; diff --git a/src/script/lua_api/l_storage.cpp b/src/script/lua_api/l_storage.cpp index fe3b4d74c..cba34fb63 100644 --- a/src/script/lua_api/l_storage.cpp +++ b/src/script/lua_api/l_storage.cpp @@ -53,7 +53,8 @@ void ModApiStorage::Initialize(lua_State *L, int top) API_FCT(get_mod_storage); } -StorageRef::StorageRef(ModMetadata *object) : m_object(object) +StorageRef::StorageRef(ModMetadata *object): + m_object(object) { } @@ -89,7 +90,7 @@ void StorageRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); @@ -107,28 +108,27 @@ void StorageRef::Register(lua_State *L) lua_pushcfunction(L, l_equals); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } -StorageRef *StorageRef::checkobject(lua_State *L, int narg) +StorageRef* StorageRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(StorageRef **)ud; // unbox pointer + if (!ud) luaL_typerror(L, narg, className); + return *(StorageRef**)ud; // unbox pointer } -ModMetadata *StorageRef::getobject(StorageRef *ref) +ModMetadata* StorageRef::getobject(StorageRef *ref) { ModMetadata *co = ref->m_object; return co; } -Metadata *StorageRef::getmeta(bool auto_create) +Metadata* StorageRef::getmeta(bool auto_create) { return m_object; } @@ -139,10 +139,17 @@ void StorageRef::clearMeta() } const char StorageRef::className[] = "StorageRef"; -const luaL_Reg StorageRef::methods[] = {luamethod(MetaDataRef, contains), - luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), - luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), - luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), - luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), - luamethod(MetaDataRef, from_table), luamethod(MetaDataRef, equals), - {0, 0}}; +const luaL_Reg StorageRef::methods[] = { + luamethod(MetaDataRef, contains), + luamethod(MetaDataRef, get), + luamethod(MetaDataRef, get_string), + luamethod(MetaDataRef, set_string), + luamethod(MetaDataRef, get_int), + luamethod(MetaDataRef, set_int), + luamethod(MetaDataRef, get_float), + luamethod(MetaDataRef, set_float), + luamethod(MetaDataRef, to_table), + luamethod(MetaDataRef, from_table), + luamethod(MetaDataRef, equals), + {0,0} +}; diff --git a/src/script/lua_api/l_util.cpp b/src/script/lua_api/l_util.cpp index b77e26886..4595dc1c1 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -41,6 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/sha1.h" #include + // log([level,] text) // Writes a line to the logger. // The one-argument version logs to LL_NONE. @@ -64,7 +65,7 @@ int ModApiUtil::l_log(lua_State *L) level = Logger::stringToLevel(name); if (level == LL_MAX) { warningstream << "Tried to log at unknown level '" << name - << "'. Defaulting to \"none\"." << std::endl; + << "'. Defaulting to \"none\"." << std::endl; level = LL_NONE; } } @@ -108,10 +109,8 @@ int ModApiUtil::l_parse_json(lua_State *L) size_t jlen = strlen(jsonstr); if (jlen > 100) { errorstream << "Data (" << jlen - << " bytes) printed to warningstream." - << std::endl; - warningstream << "data: \"" << jsonstr << "\"" - << std::endl; + << " bytes) printed to warningstream." << std::endl; + warningstream << "data: \"" << jsonstr << "\"" << std::endl; } else { errorstream << "data: \"" << jsonstr << "\"" << std::endl; } @@ -122,7 +121,7 @@ int ModApiUtil::l_parse_json(lua_State *L) if (!push_json_value(L, root, nullindex)) { errorstream << "Failed to parse json data, " - << "depth exceeds lua stack limit" << std::endl; + << "depth exceeds lua stack limit" << std::endl; errorstream << "data: \"" << jsonstr << "\"" << std::endl; lua_pushnil(L); } @@ -177,7 +176,7 @@ int ModApiUtil::l_get_hit_params(lua_State *L) std::unordered_map groups; read_groups(L, 1, groups); ToolCapabilities tp = read_tool_capabilities(L, 2); - if (lua_isnoneornil(L, 3)) + if(lua_isnoneornil(L, 3)) push_hit_params(L, getHitParams(groups, &tp)); else push_hit_params(L, getHitParams(groups, &tp, readParam(L, 3))); @@ -229,9 +228,9 @@ int ModApiUtil::l_is_yes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - lua_getglobal(L, "tostring"); // function to be called - lua_pushvalue(L, 1); // 1st argument - lua_call(L, 1, 1); // execute function + lua_getglobal(L, "tostring"); // function to be called + lua_pushvalue(L, 1); // 1st argument + lua_call(L, 1, 1); // execute function std::string str = readParam(L, -1); // get result lua_pop(L, 1); @@ -346,7 +345,7 @@ int ModApiUtil::l_get_dir_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *path = luaL_checkstring(L, 1); - bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all + bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all bool list_dirs = readParam(L, 2); // true: list dirs, false: list files CHECK_SECURE_PATH(L, path, false); @@ -417,11 +416,12 @@ int ModApiUtil::l_request_insecure_environment(lua_State *L) // Check secure.trusted_mods std::string mod_name = readParam(L, -1); std::string trusted_mods = g_settings->get("secure.trusted_mods"); - trusted_mods.erase(std::remove_if(trusted_mods.begin(), trusted_mods.end(), - static_cast(&std::isspace)), + trusted_mods.erase(std::remove_if(trusted_mods.begin(), + trusted_mods.end(), static_cast(&std::isspace)), trusted_mods.end()); std::vector mod_list = str_split(trusted_mods, ','); - if (std::find(mod_list.begin(), mod_list.end(), mod_name) == mod_list.end()) { + if (std::find(mod_list.begin(), mod_list.end(), mod_name) == + mod_list.end()) { return 0; } @@ -463,7 +463,7 @@ int ModApiUtil::l_sha1(lua_State *L) SHA1 ctx; ctx.addBytes(data, size); unsigned char *data_tmpdigest = ctx.getDigest(); - data_sha1.assign((char *)data_tmpdigest, 20); + data_sha1.assign((char*) data_tmpdigest, 20); free(data_tmpdigest); } @@ -527,7 +527,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(is_yes); API_FCT(is_nan); - + API_FCT(compress); API_FCT(decompress); @@ -538,7 +538,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(get_version); API_FCT(sha1); - + LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } @@ -571,3 +571,4 @@ void ModApiUtil::InitializeAsync(lua_State *L, int top) LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } + diff --git a/src/script/lua_api/l_vmanip.cpp b/src/script/lua_api/l_vmanip.cpp index 17fb830f9..b99b1d98c 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_vmanip.h" #include "lua_api/l_internal.h" #include "common/c_content.h" @@ -62,7 +63,7 @@ int LuaVoxelManip::l_get_data(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool use_buffer = lua_istable(L, 2); + bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; @@ -116,7 +117,8 @@ int LuaVoxelManip::l_write_to_map(lua_State *L) if (o->is_mapgen_vm || !update_light) { o->vm->blitBackAll(&(o->modified_blocks)); } else { - voxalgo::blit_back_with_light(map, o->vm, &(o->modified_blocks)); + voxalgo::blit_back_with_light(map, o->vm, + &(o->modified_blocks)); } MapEditEvent event; @@ -137,7 +139,7 @@ int LuaVoxelManip::l_get_node_at(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); - v3s16 pos = check_v3s16(L, 2); + v3s16 pos = check_v3s16(L, 2); pushnode(L, o->vm->getNodeNoExNoEmerge(pos), ndef); return 1; @@ -150,8 +152,8 @@ int LuaVoxelManip::l_set_node_at(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); - v3s16 pos = check_v3s16(L, 2); - MapNode n = readnode(L, 3, ndef); + v3s16 pos = check_v3s16(L, 2); + MapNode n = readnode(L, 3, ndef); o->vm->setNodeNoEmerge(pos, n); @@ -169,11 +171,11 @@ int LuaVoxelManip::l_update_liquids(lua_State *L) MMVManip *vm = o->vm; Mapgen mg; - mg.vm = vm; + mg.vm = vm; mg.ndef = ndef; - mg.updateLiquid(&map->m_transforming_liquid, vm->m_area.MinEdge, - vm->m_area.MaxEdge); + mg.updateLiquid(&map->m_transforming_liquid, + vm->m_area.MinEdge, vm->m_area.MaxEdge); return 0; } @@ -185,8 +187,7 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:calc_lighting called for a non-mapgen " - "VoxelManip object" - << std::endl; + "VoxelManip object" << std::endl; return 0; } @@ -195,10 +196,10 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) MMVManip *vm = o->vm; v3s16 yblock = v3s16(0, 1, 0) * MAP_BLOCKSIZE; - v3s16 fpmin = vm->m_area.MinEdge; - v3s16 fpmax = vm->m_area.MaxEdge; - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; + v3s16 fpmin = vm->m_area.MinEdge; + v3s16 fpmax = vm->m_area.MaxEdge; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; bool propagate_shadow = !lua_isboolean(L, 4) || readParam(L, 4); sortBoxVerticies(pmin, pmax); @@ -206,8 +207,8 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) throw LuaError("Specified voxel area out of VoxelManipulator bounds"); Mapgen mg; - mg.vm = vm; - mg.ndef = ndef; + mg.vm = vm; + mg.ndef = ndef; mg.water_level = emerge->mgparams->water_level; mg.calcLighting(pmin, pmax, fpmin, fpmax, propagate_shadow); @@ -222,8 +223,7 @@ int LuaVoxelManip::l_set_lighting(lua_State *L) LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:set_lighting called for a non-mapgen " - "VoxelManip object" - << std::endl; + "VoxelManip object" << std::endl; return 0; } @@ -231,7 +231,7 @@ int LuaVoxelManip::l_set_lighting(lua_State *L) throw LuaError("VoxelManip:set_lighting called with missing parameter"); u8 light; - light = (getintfield_default(L, 2, "day", 0) & 0x0F); + light = (getintfield_default(L, 2, "day", 0) & 0x0F); light |= (getintfield_default(L, 2, "night", 0) & 0x0F) << 4; MMVManip *vm = o->vm; @@ -280,7 +280,7 @@ int LuaVoxelManip::l_set_light_data(lua_State *L) if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_light_data called with missing " - "parameter"); + "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { @@ -300,7 +300,7 @@ int LuaVoxelManip::l_get_param2_data(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool use_buffer = lua_istable(L, 2); + bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; @@ -329,7 +329,7 @@ int LuaVoxelManip::l_set_param2_data(lua_State *L) if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_param2_data called with missing " - "parameter"); + "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { @@ -374,7 +374,8 @@ int LuaVoxelManip::l_get_emerged_area(lua_State *L) } LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : - is_mapgen_vm(is_mg_vm), vm(mmvm) + is_mapgen_vm(is_mg_vm), + vm(mmvm) { } @@ -405,10 +406,9 @@ int LuaVoxelManip::create_object(lua_State *L) GET_ENV_PTR; Map *map = &(env->getMap()); - LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) - ? new LuaVoxelManip(map, check_v3s16(L, 1), - check_v3s16(L, 2)) - : new LuaVoxelManip(map); + LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ? + new LuaVoxelManip(map, check_v3s16(L, 1), check_v3s16(L, 2)) : + new LuaVoxelManip(map); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); @@ -426,7 +426,7 @@ LuaVoxelManip *LuaVoxelManip::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaVoxelManip **)ud; // unbox pointer + return *(LuaVoxelManip **)ud; // unbox pointer } void LuaVoxelManip::Register(lua_State *L) @@ -438,7 +438,7 @@ void LuaVoxelManip::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -448,28 +448,32 @@ void LuaVoxelManip::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (VoxelManip()) lua_register(L, className, create_object); } const char LuaVoxelManip::className[] = "VoxelManip"; -const luaL_Reg LuaVoxelManip::methods[] = {luamethod(LuaVoxelManip, read_from_map), - luamethod(LuaVoxelManip, get_data), luamethod(LuaVoxelManip, set_data), - luamethod(LuaVoxelManip, get_node_at), - luamethod(LuaVoxelManip, set_node_at), - luamethod(LuaVoxelManip, write_to_map), - luamethod(LuaVoxelManip, update_map), - luamethod(LuaVoxelManip, update_liquids), - luamethod(LuaVoxelManip, calc_lighting), - luamethod(LuaVoxelManip, set_lighting), - luamethod(LuaVoxelManip, get_light_data), - luamethod(LuaVoxelManip, set_light_data), - luamethod(LuaVoxelManip, get_param2_data), - luamethod(LuaVoxelManip, set_param2_data), - luamethod(LuaVoxelManip, was_modified), - luamethod(LuaVoxelManip, get_emerged_area), {0, 0}}; +const luaL_Reg LuaVoxelManip::methods[] = { + luamethod(LuaVoxelManip, read_from_map), + luamethod(LuaVoxelManip, get_data), + luamethod(LuaVoxelManip, set_data), + luamethod(LuaVoxelManip, get_node_at), + luamethod(LuaVoxelManip, set_node_at), + luamethod(LuaVoxelManip, write_to_map), + luamethod(LuaVoxelManip, update_map), + luamethod(LuaVoxelManip, update_liquids), + luamethod(LuaVoxelManip, calc_lighting), + luamethod(LuaVoxelManip, set_lighting), + luamethod(LuaVoxelManip, get_light_data), + luamethod(LuaVoxelManip, set_light_data), + luamethod(LuaVoxelManip, get_param2_data), + luamethod(LuaVoxelManip, set_param2_data), + luamethod(LuaVoxelManip, was_modified), + luamethod(LuaVoxelManip, get_emerged_area), + {0,0} +}; diff --git a/src/script/scripting_client.cpp b/src/script/scripting_client.cpp index 011c93b43..729645678 100644 --- a/src/script/scripting_client.cpp +++ b/src/script/scripting_client.cpp @@ -41,7 +41,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_settings.h" #include "lua_api/l_http.h" -ClientScripting::ClientScripting(Client *client) : ScriptApiBase(ScriptingType::Client) +ClientScripting::ClientScripting(Client *client): + ScriptApiBase(ScriptingType::Client) { setGameDef(client); setGame(g_game); diff --git a/src/script/scripting_client.h b/src/script/scripting_client.h index b8dd257a9..e162f8bcf 100644 --- a/src/script/scripting_client.h +++ b/src/script/scripting_client.h @@ -31,11 +31,12 @@ class LocalPlayer; class Camera; class Minimap; -class ClientScripting : virtual public ScriptApiBase, - public ScriptApiSecurity, - public ScriptApiClient, - public ScriptApiModChannels, - public ScriptApiCheats +class ClientScripting: + virtual public ScriptApiBase, + public ScriptApiSecurity, + public ScriptApiClient, + public ScriptApiModChannels, + public ScriptApiCheats { public: ClientScripting(Client *client); diff --git a/src/script/scripting_mainmenu.cpp b/src/script/scripting_mainmenu.cpp index 835368776..0f672f917 100644 --- a/src/script/scripting_mainmenu.cpp +++ b/src/script/scripting_mainmenu.cpp @@ -34,7 +34,8 @@ extern "C" { #define MAINMENU_NUM_ASYNC_THREADS 4 -MainMenuScripting::MainMenuScripting(GUIEngine *guiengine) : + +MainMenuScripting::MainMenuScripting(GUIEngine* guiengine): ScriptApiBase(ScriptingType::MainMenu) { setGuiEngine(guiengine); @@ -75,7 +76,7 @@ void MainMenuScripting::initializeModApi(lua_State *L, int top) asyncEngine.registerStateInitializer(ModApiHttp::InitializeAsync); // Initialize async environment - // TODO possibly make number of async threads configurable + //TODO possibly make number of async threads configurable asyncEngine.initialize(MAINMENU_NUM_ASYNC_THREADS); } @@ -92,8 +93,9 @@ void MainMenuScripting::step() } /******************************************************************************/ -unsigned int MainMenuScripting::queueAsync( - const std::string &serialized_func, const std::string &serialized_param) +unsigned int MainMenuScripting::queueAsync(const std::string &serialized_func, + const std::string &serialized_param) { return asyncEngine.queueAsyncJob(serialized_func, serialized_param); } + diff --git a/src/script/scripting_mainmenu.h b/src/script/scripting_mainmenu.h index 16d0a0cc0..9e23bdc1b 100644 --- a/src/script/scripting_mainmenu.h +++ b/src/script/scripting_mainmenu.h @@ -27,10 +27,12 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Scripting <-> Main Menu Interface */ /*****************************************************************************/ -class MainMenuScripting : virtual public ScriptApiBase, public ScriptApiMainMenu +class MainMenuScripting + : virtual public ScriptApiBase, + public ScriptApiMainMenu { public: - MainMenuScripting(GUIEngine *guiengine); + MainMenuScripting(GUIEngine* guiengine); // Global step handler to pass back async events void step(); @@ -38,7 +40,6 @@ class MainMenuScripting : virtual public ScriptApiBase, public ScriptApiMainMenu // Pass async events from engine to async threads unsigned int queueAsync(const std::string &serialized_func, const std::string &serialized_params); - private: void initializeModApi(lua_State *L, int top); static void registerLuaClasses(lua_State *L, int top); diff --git a/src/script/scripting_server.cpp b/src/script/scripting_server.cpp index 604607e78..85411ded4 100644 --- a/src/script/scripting_server.cpp +++ b/src/script/scripting_server.cpp @@ -50,7 +50,8 @@ extern "C" { #include "lualib.h" } -ServerScripting::ServerScripting(Server *server) : ScriptApiBase(ScriptingType::Server) +ServerScripting::ServerScripting(Server* server): + ScriptApiBase(ScriptingType::Server) { setGameDef(server); @@ -62,12 +63,9 @@ ServerScripting::ServerScripting(Server *server) : ScriptApiBase(ScriptingType:: if (g_settings->getBool("secure.enable_security")) { initializeSecurity(); } else { - warningstream << "\\!/ Mod security should never be disabled, as it " - "allows any mod to " - << "access the host machine." - << "Mods should use " - "minetest.request_insecure_environment() instead \\!/" - << std::endl; + warningstream << "\\!/ Mod security should never be disabled, as it allows any mod to " + << "access the host machine." + << "Mods should use minetest.request_insecure_environment() instead \\!/" << std::endl; } lua_getglobal(L, "core"); diff --git a/src/script/scripting_server.h b/src/script/scripting_server.h index b0619f449..bf06ab197 100644 --- a/src/script/scripting_server.h +++ b/src/script/scripting_server.h @@ -32,18 +32,19 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Scripting <-> Server Game Interface */ /*****************************************************************************/ -class ServerScripting : virtual public ScriptApiBase, - public ScriptApiDetached, - public ScriptApiEntity, - public ScriptApiEnv, - public ScriptApiModChannels, - public ScriptApiNode, - public ScriptApiPlayer, - public ScriptApiServer, - public ScriptApiSecurity +class ServerScripting: + virtual public ScriptApiBase, + public ScriptApiDetached, + public ScriptApiEntity, + public ScriptApiEnv, + public ScriptApiModChannels, + public ScriptApiNode, + public ScriptApiPlayer, + public ScriptApiServer, + public ScriptApiSecurity { public: - ServerScripting(Server *server); + ServerScripting(Server* server); // use ScriptApiBase::loadMod() to load mods diff --git a/src/serialization.cpp b/src/serialization.cpp index 64d5cefcc..310604f54 100644 --- a/src/serialization.cpp +++ b/src/serialization.cpp @@ -26,29 +26,29 @@ with this program; if not, write to the Free Software Foundation, Inc., /* report a zlib or i/o error */ void zerr(int ret) { - dstream << "zerr: "; - switch (ret) { - case Z_ERRNO: - if (ferror(stdin)) - dstream << "error reading stdin" << std::endl; - if (ferror(stdout)) - dstream << "error writing stdout" << std::endl; - break; - case Z_STREAM_ERROR: - dstream << "invalid compression level" << std::endl; - break; - case Z_DATA_ERROR: - dstream << "invalid or incomplete deflate data" << std::endl; - break; - case Z_MEM_ERROR: - dstream << "out of memory" << std::endl; - break; - case Z_VERSION_ERROR: - dstream << "zlib version mismatch!" << std::endl; + dstream<<"zerr: "; + switch (ret) { + case Z_ERRNO: + if (ferror(stdin)) + dstream<<"error reading stdin"< &data, std::ostream &os, u8 version) { - if (version >= 11) { - compressZlib(*data, data.getSize(), os); + if(version >= 11) + { + compressZlib(*data ,data.getSize(), os); return; } - if (data.getSize() == 0) + if(data.getSize() == 0) return; // Write length (u32) u8 tmp[4]; writeU32(tmp, data.getSize()); - os.write((char *)tmp, 4); + os.write((char*)tmp, 4); // We will be writing 8-bit pairs of more_count and byte u8 more_count = 0; u8 current_byte = data[0]; - for (u32 i = 1; i < data.getSize(); i++) { - if (data[i] != current_byte || more_count == 255) { + for(u32 i=1; i= 11) { + if(version >= 11) + { decompressZlib(is, os); return; } @@ -236,28 +251,31 @@ void decompress(std::istream &is, std::ostream &os, u8 version) // Read length (u32) u8 tmp[4]; - is.read((char *)tmp, 4); + is.read((char*)tmp, 4); u32 len = readU32(tmp); // We will be reading 8-bit pairs of more_count and byte u32 count = 0; - for (;;) { - u8 more_count = 0; - u8 byte = 0; + for(;;) + { + u8 more_count=0; + u8 byte=0; - is.read((char *)&more_count, 1); + is.read((char*)&more_count, 1); - is.read((char *)&byte, 1); + is.read((char*)&byte, 1); - if (is.eof()) + if(is.eof()) throw SerializationError("decompress: stream ended halfway"); - for (s32 i = 0; i < (u16)more_count + 1; i++) - os.write((char *)&byte, 1); + for(s32 i=0; i<(u16)more_count+1; i++) + os.write((char*)&byte, 1); - count += (u16)more_count + 1; + count += (u16)more_count+1; - if (count == len) + if(count == len) break; } } + + diff --git a/src/serialization.h b/src/serialization.h index b53564c78..f399983c4 100644 --- a/src/serialization.h +++ b/src/serialization.h @@ -77,8 +77,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // in memory; conversion just won't work in this direction. #define SER_FMT_VER_LOWEST_WRITE 24 -inline bool ser_ver_supported(s32 v) -{ +inline bool ser_ver_supported(s32 v) { return v >= SER_FMT_VER_LOWEST_READ && v <= SER_FMT_VER_HIGHEST_READ; } @@ -92,5 +91,5 @@ void decompressZlib(std::istream &is, std::ostream &os, size_t limit = 0); // These choose between zlib and a self-made one according to version void compress(const SharedBuffer &data, std::ostream &os, u8 version); -// void compress(const std::string &data, std::ostream &os, u8 version); +//void compress(const std::string &data, std::ostream &os, u8 version); void decompress(std::istream &is, std::ostream &os, u8 version); diff --git a/src/server.cpp b/src/server.cpp index b9c68654a..fe2bb3840 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -70,13 +70,19 @@ with this program; if not, write to the Free Software Foundation, Inc., class ClientNotFoundException : public BaseException { public: - ClientNotFoundException(const char *s) : BaseException(s) {} + ClientNotFoundException(const char *s): + BaseException(s) + {} }; class ServerThread : public Thread { public: - ServerThread(Server *server) : Thread("Server"), m_server(server) {} + + ServerThread(Server *server): + Thread("Server"), + m_server(server) + {} void *run(); @@ -106,13 +112,13 @@ void *ServerThread::run() m_server->Receive(); } catch (con::PeerNotFoundException &e) { - infostream << "Server: PeerNotFoundException" << std::endl; + infostream<<"Server: PeerNotFoundException"<setAsyncFatalError(e.what()); } catch (LuaError &e) { - m_server->setAsyncFatalError("ServerThread::run Lua: " + - std::string(e.what())); + m_server->setAsyncFatalError( + "ServerThread::run Lua: " + std::string(e.what())); } } @@ -123,27 +129,23 @@ void *ServerThread::run() v3f ServerSoundParams::getPos(ServerEnvironment *env, bool *pos_exists) const { - if (pos_exists) - *pos_exists = false; - switch (type) { + if(pos_exists) *pos_exists = false; + switch(type){ case SSP_LOCAL: - return v3f(0, 0, 0); + return v3f(0,0,0); case SSP_POSITIONAL: - if (pos_exists) - *pos_exists = true; + if(pos_exists) *pos_exists = true; return pos; case SSP_OBJECT: { - if (object == 0) - return v3f(0, 0, 0); + if(object == 0) + return v3f(0,0,0); ServerActiveObject *sao = env->getActiveObject(object); - if (!sao) - return v3f(0, 0, 0); - if (pos_exists) - *pos_exists = true; - return sao->getBasePosition(); - } + if(!sao) + return v3f(0,0,0); + if(pos_exists) *pos_exists = true; + return sao->getBasePosition(); } } - return v3f(0, 0, 0); + return v3f(0,0,0); } void Server::ShutdownState::reset() @@ -167,8 +169,10 @@ void Server::ShutdownState::tick(float dtime, Server *server) return; // Timed shutdown - static const float shutdown_msg_times[] = {1, 2, 3, 4, 5, 10, 20, 40, 60, 120, - 180, 300, 600, 1200, 1800, 3600}; + static const float shutdown_msg_times[] = + { + 1, 2, 3, 4, 5, 10, 20, 40, 60, 120, 180, 300, 600, 1200, 1800, 3600 + }; // Automated messages if (m_timer < shutdown_msg_times[ARRLEN(shutdown_msg_times) - 1]) { @@ -177,8 +181,7 @@ void Server::ShutdownState::tick(float dtime, Server *server) if (m_timer > t && m_timer - dtime < t) { std::wstring periodicMsg = getShutdownTimerMessage(); - infostream << wide_to_utf8(periodicMsg).c_str() - << std::endl; + infostream << wide_to_utf8(periodicMsg).c_str() << std::endl; server->SendChatMessage(PEER_ID_INEXISTENT, periodicMsg); break; } @@ -196,7 +199,7 @@ std::wstring Server::ShutdownState::getShutdownTimerMessage() const { std::wstringstream ws; ws << L"*** Server shutting down in " - << duration_to_string(myround(m_timer)).c_str() << "."; + << duration_to_string(myround(m_timer)).c_str() << "."; return ws.str(); } @@ -204,19 +207,32 @@ std::wstring Server::ShutdownState::getShutdownTimerMessage() const Server */ -Server::Server(const std::string &path_world, const SubgameSpec &gamespec, - bool simple_singleplayer_mode, Address bind_addr, bool dedicated, - ChatInterface *iface) : - m_bind_addr(bind_addr), - m_path_world(path_world), m_gamespec(gamespec), - m_simple_singleplayer_mode(simple_singleplayer_mode), - m_dedicated(dedicated), m_async_fatal_error(""), - m_con(std::make_shared(PROTOCOL_ID, 512, - CONNECTION_TIMEOUT, m_bind_addr.isIPv6(), this)), - m_itemdef(createItemDefManager()), m_nodedef(createNodeDefManager()), - m_craftdef(createCraftDefManager()), m_thread(new ServerThread(this)), - m_clients(m_con), m_admin_chat(iface), - m_modchannel_mgr(new ModChannelMgr()) +Server::Server( + const std::string &path_world, + const SubgameSpec &gamespec, + bool simple_singleplayer_mode, + Address bind_addr, + bool dedicated, + ChatInterface *iface + ): + m_bind_addr(bind_addr), + m_path_world(path_world), + m_gamespec(gamespec), + m_simple_singleplayer_mode(simple_singleplayer_mode), + m_dedicated(dedicated), + m_async_fatal_error(""), + m_con(std::make_shared(PROTOCOL_ID, + 512, + CONNECTION_TIMEOUT, + m_bind_addr.isIPv6(), + this)), + m_itemdef(createItemDefManager()), + m_nodedef(createNodeDefManager()), + m_craftdef(createCraftDefManager()), + m_thread(new ServerThread(this)), + m_clients(m_con), + m_admin_chat(iface), + m_modchannel_mgr(new ModChannelMgr()) { if (m_path_world.empty()) throw ServerError("Supplied empty world path"); @@ -225,30 +241,29 @@ Server::Server(const std::string &path_world, const SubgameSpec &gamespec, throw ServerError("Supplied invalid gamespec"); #if USE_PROMETHEUS - m_metrics_backend = - std::unique_ptr(createPrometheusMetricsBackend()); + m_metrics_backend = std::unique_ptr(createPrometheusMetricsBackend()); #else m_metrics_backend = std::unique_ptr(new MetricsBackend()); #endif - m_uptime_counter = m_metrics_backend->addCounter( - "minetest_core_server_uptime", "Server uptime (in seconds)"); - m_player_gauge = m_metrics_backend->addGauge( - "minetest_core_player_number", "Number of connected players"); + m_uptime_counter = m_metrics_backend->addCounter("minetest_core_server_uptime", "Server uptime (in seconds)"); + m_player_gauge = m_metrics_backend->addGauge("minetest_core_player_number", "Number of connected players"); m_timeofday_gauge = m_metrics_backend->addGauge( - "minetest_core_timeofday", "Time of day value"); + "minetest_core_timeofday", + "Time of day value"); m_lag_gauge = m_metrics_backend->addGauge( - "minetest_core_latency", "Latency value (in seconds)"); + "minetest_core_latency", + "Latency value (in seconds)"); - m_aom_buffer_counter = - m_metrics_backend->addCounter("minetest_core_aom_generated_count", - "Number of active object messages generated"); + m_aom_buffer_counter = m_metrics_backend->addCounter( + "minetest_core_aom_generated_count", + "Number of active object messages generated"); - m_packet_recv_counter = - m_metrics_backend->addCounter("minetest_core_server_packet_recv", - "Processable packets received"); + m_packet_recv_counter = m_metrics_backend->addCounter( + "minetest_core_server_packet_recv", + "Processable packets received"); m_packet_recv_processed_counter = m_metrics_backend->addCounter( "minetest_core_server_packet_recv_processed", @@ -262,7 +277,7 @@ Server::~Server() // Send shutdown message SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(CHATMESSAGE_TYPE_ANNOUNCE, - L"*** Server shutting down")); + L"*** Server shutting down")); if (m_env) { MutexAutoLock envlock(m_env_mutex); @@ -281,7 +296,8 @@ Server::~Server() kick_msg = g_settings->get("kick_msg_shutdown"); } m_env->saveLoadedPlayers(true); - m_env->kickAllPlayers(SERVER_ACCESSDENIED_SHUTDOWN, kick_msg, reconnect); + m_env->kickAllPlayers(SERVER_ACCESSDENIED_SHUTDOWN, + kick_msg, reconnect); } actionstream << "Server: Shutting down" << std::endl; @@ -357,12 +373,11 @@ void Server::init() m_modmgr->printUnsatisfiedModsError(); } - // lock environment + //lock environment MutexAutoLock envlock(m_env_mutex); // Create the Map (loads map_meta.txt, overriding configured mapgen params) - ServerMap *servermap = new ServerMap( - m_path_world, this, m_emerge, m_metrics_backend.get()); + ServerMap *servermap = new ServerMap(m_path_world, this, m_emerge, m_metrics_backend.get()); // Initialize scripting infostream << "Server: Initializing Lua" << std::endl; @@ -370,8 +385,7 @@ void Server::init() m_script = new ServerScripting(this); // Must be created before mod loading because we have some inventory creation - m_inventory_mgr = std::unique_ptr( - new ServerInventoryManager()); + m_inventory_mgr = std::unique_ptr(new ServerInventoryManager()); m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME); @@ -390,8 +404,7 @@ void Server::init() for (const std::string &path : paths) { TextureOverrideSource override_source(path + DIR_DELIM + "override.txt"); m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides()); - m_itemdef->applyTextureOverrides( - override_source.getItemTextureOverrides()); + m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides()); } m_nodedef->setNodeRegistrationStatus(true); @@ -442,8 +455,8 @@ void Server::start() { init(); - infostream << "Starting server on " << m_bind_addr.serializeString() << "..." - << std::endl; + infostream << "Starting server on " << m_bind_addr.serializeString() + << "..." << std::endl; // Stop thread if already running m_thread->stop(); @@ -456,32 +469,30 @@ void Server::start() m_thread->start(); // ASCII art for the win! - std::cerr << " .__ __ __ " << std::endl - << " _____ |__| ____ _____/ |_ ____ _______/ |_ " << std::endl - << " / \\| |/ \\_/ __ \\ __\\/ __ \\ / ___/\\ __\\" - << std::endl - << "| Y Y \\ | | \\ ___/| | \\ ___/ \\___ \\ | | " - << std::endl - << "|__|_| /__|___| /\\___ >__| \\___ >____ > |__| " << std::endl - << " \\/ \\/ \\/ \\/ \\/ " - << std::endl; + std::cerr + << " .__ __ __ " << std::endl + << " _____ |__| ____ _____/ |_ ____ _______/ |_ " << std::endl + << " / \\| |/ \\_/ __ \\ __\\/ __ \\ / ___/\\ __\\" << std::endl + << "| Y Y \\ | | \\ ___/| | \\ ___/ \\___ \\ | | " << std::endl + << "|__|_| /__|___| /\\___ >__| \\___ >____ > |__| " << std::endl + << " \\/ \\/ \\/ \\/ \\/ " << std::endl; actionstream << "World at [" << m_path_world << "]" << std::endl; - actionstream << "Server for gameid=\"" << m_gamespec.id << "\" listening on " - << m_bind_addr.serializeString() << ":" << m_bind_addr.getPort() - << "." << std::endl; + actionstream << "Server for gameid=\"" << m_gamespec.id + << "\" listening on " << m_bind_addr.serializeString() << ":" + << m_bind_addr.getPort() << "." << std::endl; } void Server::stop() { - infostream << "Server: Stopping and waiting threads" << std::endl; + infostream<<"Server: Stopping and waiting threads"<stop(); - // m_emergethread.setRun(false); + //m_emergethread.setRun(false); m_thread->wait(); - // m_emergethread.stop(); + //m_emergethread.stop(); - infostream << "Server: Threads stopped" << std::endl; + infostream<<"Server: Threads stopped"<kickAllPlayers(SERVER_ACCESSDENIED_CRASH, - g_settings->get("kick_msg_crash"), - g_settings->getBool("ask_reconnect_on_crash")); + g_settings->get("kick_msg_crash"), + g_settings->getBool("ask_reconnect_on_crash")); } throw ServerError("AsyncErr: " + async_err); } @@ -519,7 +530,7 @@ void Server::AsyncRunStep(bool initial_step) SendBlocks(dtime); } - if ((dtime < 0.001) && !initial_step) + if((dtime < 0.001) && !initial_step) return; ScopeProfiler sp(g_profiler, "Server::AsyncRunStep()", SPT_AVG); @@ -560,10 +571,10 @@ void Server::AsyncRunStep(bool initial_step) // Figure out and report maximum lag to environment float max_lag = m_env->getMaxLagEstimate(); max_lag *= 0.9998; // Decrease slowly (about half per 5 minutes) - if (dtime > max_lag) { - if (dtime > 0.1 && dtime > max_lag * 2.0) - infostream << "Server: Maximum lag peaked to " << dtime - << " s" << std::endl; + if(dtime > max_lag){ + if(dtime > 0.1 && dtime > max_lag * 2.0) + infostream<<"Server: Maximum lag peaked to "<reportMaxLagEstimate(max_lag); @@ -572,13 +583,14 @@ void Server::AsyncRunStep(bool initial_step) } static const float map_timer_and_unload_dtime = 2.92; - if (m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) { + if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) + { MutexAutoLock lock(m_env_mutex); // Run Map's timers and unload unused data ScopeProfiler sp(g_profiler, "Server: map timer and unload"); m_env->getMap().timerUpdate(map_timer_and_unload_dtime, - g_settings->getFloat("server_unload_unused_data_timeout"), - U32_MAX); + g_settings->getFloat("server_unload_unused_data_timeout"), + U32_MAX); } /* @@ -588,14 +600,13 @@ void Server::AsyncRunStep(bool initial_step) if (!m_admin_chat->command_queue.empty()) { MutexAutoLock lock(m_env_mutex); while (!m_admin_chat->command_queue.empty()) { - ChatEvent *evt = m_admin_chat->command_queue - .pop_frontNoEx(); + ChatEvent *evt = m_admin_chat->command_queue.pop_frontNoEx(); handleChatInterfaceEvent(evt); delete evt; } } - m_admin_chat->outgoing_queue.push_back(new ChatEventTimeInfo( - m_env->getGameTime(), m_env->getTimeOfDay())); + m_admin_chat->outgoing_queue.push_back( + new ChatEventTimeInfo(m_env->getGameTime(), m_env->getTimeOfDay())); } /* @@ -604,14 +615,15 @@ void Server::AsyncRunStep(bool initial_step) /* Transform liquids */ m_liquid_transform_timer += dtime; - if (m_liquid_transform_timer >= m_liquid_transform_every) { + if(m_liquid_transform_timer >= m_liquid_transform_every) + { m_liquid_transform_timer -= m_liquid_transform_every; MutexAutoLock lock(m_env_mutex); ScopeProfiler sp(g_profiler, "Server: liquid transform"); - std::map modified_blocks; + std::map modified_blocks; m_env->getMap().transformLiquids(modified_blocks, m_env); /* @@ -623,20 +635,24 @@ void Server::AsyncRunStep(bool initial_step) } m_clients.step(dtime); - m_lag_gauge->increment((m_lag_gauge->get() > dtime ? -1 : 1) * dtime / 100); + m_lag_gauge->increment((m_lag_gauge->get() > dtime ? -1 : 1) * dtime/100); #if USE_CURL // send masterserver announce { float &counter = m_masterserver_timer; if (!isSingleplayer() && (!counter || counter >= 300.0) && g_settings->getBool("server_announce")) { - ServerList::sendAnnounce(counter ? ServerList::AA_UPDATE - : ServerList::AA_START, - m_bind_addr.getPort(), m_clients.getPlayerNames(), - m_uptime_counter->get(), m_env->getGameTime(), - m_lag_gauge->get(), m_gamespec.id, + ServerList::sendAnnounce(counter ? ServerList::AA_UPDATE : + ServerList::AA_START, + m_bind_addr.getPort(), + m_clients.getPlayerNames(), + m_uptime_counter->get(), + m_env->getGameTime(), + m_lag_gauge->get(), + m_gamespec.id, Mapgen::getMapgenName(m_emerge->mgparams->mgtype), - m_modmgr->getMods(), m_dedicated); + m_modmgr->getMods(), + m_dedicated); counter = 0.01; } counter += dtime; @@ -647,8 +663,7 @@ void Server::AsyncRunStep(bool initial_step) Check added and deleted active objects */ { - // infostream<<"Server: Checking added and deleted active - // objects"<getFloat("server_map_save_interval"); + m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval"); int n = 0; - for (std::unordered_map::const_iterator it = - m_mod_storages.begin(); - it != m_mod_storages.end(); ++it) { + for (std::unordered_map::const_iterator + it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) { if (it->second->isModified()) { it->second->save(getModStoragePath()); n++; } } if (n > 0) - infostream << "Saved " << n << " modified mod storages." - << std::endl; + infostream << "Saved " << n << " modified mod storages." << std::endl; } } @@ -704,17 +715,16 @@ void Server::AsyncRunStep(bool initial_step) // Key = object id // Value = data sent by object - std::unordered_map *> - buffered_messages; + std::unordered_map*> buffered_messages; // Get active object messages from environment ActiveObjectMessage aom(0); u32 aom_count = 0; - for (;;) { + for(;;) { if (!m_env->getActiveObjectMessage(&aom)) break; - std::vector *message_list = nullptr; + std::vector* message_list = nullptr; auto n = buffered_messages.find(aom.id); if (n == buffered_messages.end()) { message_list = new std::vector; @@ -739,44 +749,33 @@ void Server::AsyncRunStep(bool initial_step) PlayerSAO *player = getPlayerSAO(client->peer_id); // Go through all objects in message buffer for (const auto &buffered_message : buffered_messages) { - // If object does not exist or is not known by client, - // skip it + // If object does not exist or is not known by client, skip it u16 id = buffered_message.first; ServerActiveObject *sao = m_env->getActiveObject(id); - if (!sao || client->m_known_objects.find(id) == - client->m_known_objects - .end()) + if (!sao || client->m_known_objects.find(id) == client->m_known_objects.end()) continue; // Get message list of object - std::vector *list = - buffered_message.second; + std::vector* list = buffered_message.second; // Go through every message for (const ActiveObjectMessage &aom : *list) { - // Send position updates to players who do not see - // the attachment + // Send position updates to players who do not see the attachment if (aom.datastring[0] == AO_CMD_UPDATE_POSITION) { if (sao->getId() == player->getId()) continue; - // Do not send position updates for - // attached players as long the parent is - // known to the client - ServerActiveObject *parent = - sao->getParent(); - if (parent && client->m_known_objects.find( - parent->getId()) != - client->m_known_objects - .end()) + // Do not send position updates for attached players + // as long the parent is known to the client + ServerActiveObject *parent = sao->getParent(); + if (parent && client->m_known_objects.find(parent->getId()) != + client->m_known_objects.end()) continue; } // Add full new data to appropriate buffer - std::string &buffer = - aom.reliable ? reliable_data - : unreliable_data; + std::string &buffer = aom.reliable ? reliable_data : unreliable_data; char idbuf[2]; - writeU16((u8 *)idbuf, aom.id); + writeU16((u8*) idbuf, aom.id); // u16 id // std::string data buffer.append(idbuf, sizeof(idbuf)); @@ -792,8 +791,7 @@ void Server::AsyncRunStep(bool initial_step) } if (!unreliable_data.empty()) { - SendActiveObjectMessages( - client->peer_id, unreliable_data, false); + SendActiveObjectMessages(client->peer_id, unreliable_data, false); } } m_clients.unlock(); @@ -812,11 +810,11 @@ void Server::AsyncRunStep(bool initial_step) MutexAutoLock lock(m_env_mutex); // Don't send too many at a time - // u32 count = 0; + //u32 count = 0; // Single change sending is disabled if queue size is not small bool disable_single_change_sending = false; - if (m_unsent_map_edit_queue.size() >= 4) + if(m_unsent_map_edit_queue.size() >= 4) disable_single_change_sending = true; int event_count = m_unsent_map_edit_queue.size(); @@ -827,7 +825,7 @@ void Server::AsyncRunStep(bool initial_step) std::list node_meta_updates; while (!m_unsent_map_edit_queue.empty()) { - MapEditEvent *event = m_unsent_map_edit_queue.front(); + MapEditEvent* event = m_unsent_map_edit_queue.front(); m_unsent_map_edit_queue.pop(); // Players far away from the change are stored here. @@ -851,30 +849,28 @@ void Server::AsyncRunStep(bool initial_step) case MEET_BLOCK_NODE_METADATA_CHANGED: { prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1); if (!event->is_private_change) { - // Don't send the change yet. Collect them to - // eliminate dupes. + // Don't send the change yet. Collect them to eliminate dupes. node_meta_updates.remove(event->p); node_meta_updates.push_back(event->p); } if (MapBlock *block = m_env->getMap().getBlockNoCreateNoEx( - getNodeBlockPos(event->p))) { + getNodeBlockPos(event->p))) { block->raiseModified(MOD_STATE_WRITE_NEEDED, - MOD_REASON_REPORT_META_CHANGE); + MOD_REASON_REPORT_META_CHANGE); } break; } case MEET_OTHER: prof.add("MEET_OTHER", 1); - for (const v3s16 &modified_block : - event->modified_blocks) { + for (const v3s16 &modified_block : event->modified_blocks) { m_clients.markBlockposAsNotSent(modified_block); } break; default: prof.add("unknown", 1); warningstream << "Server: Unknown MapEditEvent " - << ((u32)event->type) << std::endl; + << ((u32)event->type) << std::endl; break; } @@ -883,19 +879,16 @@ void Server::AsyncRunStep(bool initial_step) */ if (!far_players.empty()) { // Convert list format to that wanted by SetBlocksNotSent - std::map modified_blocks2; - for (const v3s16 &modified_block : - event->modified_blocks) { + std::map modified_blocks2; + for (const v3s16 &modified_block : event->modified_blocks) { modified_blocks2[modified_block] = - m_env->getMap().getBlockNoCreateNoEx( - modified_block); + m_env->getMap().getBlockNoCreateNoEx(modified_block); } // Set blocks not sent for (const u16 far_player : far_players) { if (RemoteClient *client = getClient(far_player)) - client->SetBlocksNotSent( - modified_blocks2); + client->SetBlocksNotSent(modified_blocks2); } } @@ -934,7 +927,7 @@ void Server::AsyncRunStep(bool initial_step) float &counter = m_savemap_timer; counter += dtime; static thread_local const float save_interval = - g_settings->getFloat("server_map_save_interval"); + g_settings->getFloat("server_map_save_interval"); if (counter >= save_interval) { counter = 0.0; MutexAutoLock lock(m_env_mutex); @@ -970,9 +963,8 @@ void Server::Receive() peer_id = 0; try { /* - In the first iteration *wait* for a packet, afterwards - process all packets that are immediately available (no - waiting). + In the first iteration *wait* for a packet, afterwards process + all packets that are immediately available (no waiting). */ if (first) { m_con->Receive(&pkt); @@ -987,18 +979,15 @@ void Server::Receive() ProcessData(&pkt); m_packet_recv_processed_counter->increment(); } catch (const con::InvalidIncomingDataException &e) { - infostream << "Server::Receive(): InvalidIncomingDataException: " - "what()=" - << e.what() << std::endl; + infostream << "Server::Receive(): InvalidIncomingDataException: what()=" + << e.what() << std::endl; } catch (const SerializationError &e) { infostream << "Server::Receive(): SerializationError: what()=" - << e.what() << std::endl; + << e.what() << std::endl; } catch (const ClientStateError &e) { - errorstream << "ProcessData: peer=" << peer_id - << " what()=" << e.what() << std::endl; - DenyAccess_Legacy(peer_id, - L"Your client sent something server didn't " - L"expect." + errorstream << "ProcessData: peer=" << peer_id << " what()=" + << e.what() << std::endl; + DenyAccess_Legacy(peer_id, L"Your client sent something server didn't expect." L"Try reconnecting or updating your client"); } catch (const con::PeerNotFoundException &e) { // Do nothing @@ -1008,18 +997,16 @@ void Server::Receive() } } -PlayerSAO *Server::StageTwoClientInit(session_t peer_id) +PlayerSAO* Server::StageTwoClientInit(session_t peer_id) { std::string playername; PlayerSAO *playersao = NULL; m_clients.lock(); try { - RemoteClient *client = - m_clients.lockedGetClientNoEx(peer_id, CS_InitDone); + RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_InitDone); if (client) { playername = client->getName(); - playersao = emergePlayer(playername.c_str(), peer_id, - client->net_proto_version); + playersao = emergePlayer(playername.c_str(), peer_id, client->net_proto_version); } } catch (std::exception &e) { m_clients.unlock(); @@ -1033,16 +1020,13 @@ PlayerSAO *Server::StageTwoClientInit(session_t peer_id) if (!playersao || !player) { if (player && player->getPeerId() != PEER_ID_INEXISTENT) { actionstream << "Server: Failed to emerge player \"" << playername - << "\" (player allocated to an another client)" - << std::endl; - DenyAccess_Legacy(peer_id, - L"Another client is connected with this " - L"name. If your client closed unexpectedly, try " - L"again in " + << "\" (player allocated to an another client)" << std::endl; + DenyAccess_Legacy(peer_id, L"Another client is connected with this " + L"name. If your client closed unexpectedly, try again in " L"a minute."); } else { - errorstream << "Server: " << playername - << ": Failed to emerge player" << std::endl; + errorstream << "Server: " << playername << ": Failed to emerge player" + << std::endl; DenyAccess_Legacy(peer_id, L"Could not allocate player."); } return NULL; @@ -1064,7 +1048,7 @@ PlayerSAO *Server::StageTwoClientInit(session_t peer_id) // Send HP or death screen if (playersao->isDead()) - SendDeathscreen(peer_id, false, v3f(0, 0, 0)); + SendDeathscreen(peer_id, false, v3f(0,0,0)); else SendPlayerHPOrDie(playersao, PlayerHPChangeReason(PlayerHPChangeReason::SET_HP)); @@ -1080,14 +1064,13 @@ PlayerSAO *Server::StageTwoClientInit(session_t peer_id) std::string ip_str = addr.serializeString(); const std::vector &names = m_clients.getPlayerNames(); - actionstream << player->getName() << " [" << ip_str - << "] joins game. List of players: "; + actionstream << player->getName() << " [" << ip_str << "] joins game. List of players: "; for (const std::string &name : names) { actionstream << name << " "; } - actionstream << player->getName() << std::endl; + actionstream << player->getName() <isIpBanned(addr_s)) { + if(m_banmanager->isIpBanned(addr_s)) { std::string ban_name = m_banmanager->getBanName(addr_s); infostream << "Server: A banned client tried to connect from " - << addr_s << "; banned name was " << ban_name - << std::endl; + << addr_s << "; banned name was " + << ban_name << std::endl; // This actually doesn't seem to transfer to the client - DenyAccess_Legacy( - peer_id, L"Your ip is banned. Banned name was " + - utf8_to_wide(ban_name)); + DenyAccess_Legacy(peer_id, L"Your ip is banned. Banned name was " + + utf8_to_wide(ban_name)); return; } - } catch (con::PeerNotFoundException &e) { + } + catch(con::PeerNotFoundException &e) { /* * no peer for this packet found * most common reason is peer timeout, e.g. peer didn't * respond for some time, your server was overloaded or * things like that. */ - infostream << "Server::ProcessData(): Canceling: peer " << peer_id - << " not found" << std::endl; + infostream << "Server::ProcessData(): Canceling: peer " + << peer_id << " not found" << std::endl; return; } try { - ToServerCommand command = (ToServerCommand)pkt->getCommand(); + ToServerCommand command = (ToServerCommand) pkt->getCommand(); // Command must be handled into ToServerCommandHandler if (command >= TOSERVER_NUM_MSG_TYPES) { - infostream << "Server: Ignoring unknown command " << command - << std::endl; + infostream << "Server: Ignoring unknown command " + << command << std::endl; return; } @@ -1150,11 +1133,10 @@ void Server::ProcessData(NetworkPacket *pkt) u8 peer_ser_ver = getClient(peer_id, CS_InitDone)->serialization_version; - if (peer_ser_ver == SER_FMT_VER_INVALID) { + if(peer_ser_ver == SER_FMT_VER_INVALID) { errorstream << "Server::ProcessData(): Cancelling: Peer" - " serialization format invalid or not initialized." - " Skipping incoming command=" - << command << std::endl; + " serialization format invalid or not initialized." + " Skipping incoming command=" << command << std::endl; return; } @@ -1165,23 +1147,23 @@ void Server::ProcessData(NetworkPacket *pkt) } if (m_clients.getClientState(peer_id) < CS_Active) { - if (command == TOSERVER_PLAYERPOS) - return; + if (command == TOSERVER_PLAYERPOS) return; - errorstream << "Got packet command: " << command - << " for peer id " << peer_id - << " but client isn't active yet. Dropping packet " - << std::endl; + errorstream << "Got packet command: " << command << " for peer id " + << peer_id << " but client isn't active yet. Dropping packet " + << std::endl; return; } handleCommand(pkt); } catch (SendFailedException &e) { errorstream << "Server::ProcessData(): SendFailedException: " - << "what=" << e.what() << std::endl; + << "what=" << e.what() + << std::endl; } catch (PacketError &e) { actionstream << "Server::ProcessData(): PacketError: " - << "what=" << e.what() << std::endl; + << "what=" << e.what() + << std::endl; } } @@ -1199,47 +1181,57 @@ void Server::onMapEditEvent(const MapEditEvent &event) m_unsent_map_edit_queue.push(new MapEditEvent(event)); } -void Server::SetBlocksNotSent(std::map &block) +void Server::SetBlocksNotSent(std::map& block) { std::vector clients = m_clients.getClientIDs(); m_clients.lock(); // Set the modified blocks unsent for all the clients for (const session_t client_id : clients) { - if (RemoteClient *client = m_clients.lockedGetClientNoEx(client_id)) - client->SetBlocksNotSent(block); + if (RemoteClient *client = m_clients.lockedGetClientNoEx(client_id)) + client->SetBlocksNotSent(block); } m_clients.unlock(); } void Server::peerAdded(con::Peer *peer) { - verbosestream << "Server::peerAdded(): peer->id=" << peer->id << std::endl; + verbosestream<<"Server::peerAdded(): peer->id=" + <id<id, false)); } void Server::deletingPeer(con::Peer *peer, bool timeout) { - verbosestream << "Server::deletingPeer(): peer->id=" << peer->id - << ", timeout=" << timeout << std::endl; + verbosestream<<"Server::deletingPeer(): peer->id=" + <id<<", timeout="<id, CSE_Disconnect); m_peer_change_queue.push(con::PeerChange(con::PEER_REMOVED, peer->id, timeout)); } -bool Server::getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval) +bool Server::getClientConInfo(session_t peer_id, con::rtt_stat_type type, float* retval) { - *retval = m_con->getPeerStat(peer_id, type); + *retval = m_con->getPeerStat(peer_id,type); return *retval != -1; } -bool Server::getClientInfo(session_t peer_id, ClientState *state, u32 *uptime, - u8 *ser_vers, u16 *prot_vers, u8 *major, u8 *minor, u8 *patch, - std::string *vers_string, std::string *lang_code) +bool Server::getClientInfo( + session_t peer_id, + ClientState* state, + u32* uptime, + u8* ser_vers, + u16* prot_vers, + u8* major, + u8* minor, + u8* patch, + std::string* vers_string, + std::string* lang_code + ) { *state = m_clients.getClientState(peer_id); m_clients.lock(); - RemoteClient *client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid); + RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid); if (!client) { m_clients.unlock(); @@ -1263,21 +1255,23 @@ bool Server::getClientInfo(session_t peer_id, ClientState *state, u32 *uptime, void Server::handlePeerChanges() { - while (!m_peer_change_queue.empty()) { + while(!m_peer_change_queue.empty()) + { con::PeerChange c = m_peer_change_queue.front(); m_peer_change_queue.pop(); - verbosestream << "Server: Handling peer change: " - << "id=" << c.peer_id << ", timeout=" << c.timeout - << std::endl; + verbosestream<<"Server: Handling peer change: " + <<"id="<getCommand()].channel, pkt, - clientCommandFactoryTable[pkt->getCommand()].reliable); + m_clients.send(peer_id, + clientCommandFactoryTable[pkt->getCommand()].channel, + pkt, + clientCommandFactoryTable[pkt->getCommand()].reliable); } void Server::SendMovement(session_t peer_id) @@ -1354,7 +1350,7 @@ void Server::SendHP(session_t peer_id, u16 hp) void Server::SendBreath(session_t peer_id, u16 breath) { NetworkPacket pkt(TOCLIENT_BREATH, 2, peer_id); - pkt << (u16)breath; + pkt << (u16) breath; Send(&pkt); } @@ -1373,23 +1369,23 @@ void Server::SendAccessDenied(session_t peer_id, AccessDeniedCode reason, Send(&pkt); } -void Server::SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason) +void Server::SendAccessDenied_Legacy(session_t peer_id,const std::wstring &reason) { NetworkPacket pkt(TOCLIENT_ACCESS_DENIED_LEGACY, 0, peer_id); pkt << reason; Send(&pkt); } -void Server::SendDeathscreen( - session_t peer_id, bool set_camera_point_target, v3f camera_point_target) +void Server::SendDeathscreen(session_t peer_id, bool set_camera_point_target, + v3f camera_point_target) { NetworkPacket pkt(TOCLIENT_DEATHSCREEN, 1 + sizeof(v3f), peer_id); pkt << set_camera_point_target << camera_point_target; Send(&pkt); } -void Server::SendItemDef( - session_t peer_id, IItemDefManager *itemdef, u16 protocol_version) +void Server::SendItemDef(session_t peer_id, + IItemDefManager *itemdef, u16 protocol_version) { NetworkPacket pkt(TOCLIENT_ITEMDEF, 0, peer_id); @@ -1406,13 +1402,13 @@ void Server::SendItemDef( // Make data buffer verbosestream << "Server: Sending item definitions to id(" << peer_id - << "): size=" << pkt.getSize() << std::endl; + << "): size=" << pkt.getSize() << std::endl; Send(&pkt); } -void Server::SendNodeDef( - session_t peer_id, const NodeDefManager *nodedef, u16 protocol_version) +void Server::SendNodeDef(session_t peer_id, + const NodeDefManager *nodedef, u16 protocol_version) { NetworkPacket pkt(TOCLIENT_NODEDEF, 0, peer_id); @@ -1430,7 +1426,7 @@ void Server::SendNodeDef( // Make data buffer verbosestream << "Server: Sending node definitions to id(" << peer_id - << "): size=" << pkt.getSize() << std::endl; + << "): size=" << pkt.getSize() << std::endl; Send(&pkt); } @@ -1469,8 +1465,7 @@ void Server::SendChatMessage(session_t peer_id, const ChatMessage &message) NetworkPacket pkt(TOCLIENT_CHAT_MESSAGE, 0, peer_id); u8 version = 1; u8 type = message.type; - pkt << version << type << std::wstring(L"") << message.message - << (u64)message.timestamp; + pkt << version << type << std::wstring(L"") << message.message << (u64)message.timestamp; if (peer_id != PEER_ID_INEXISTENT) { RemotePlayer *player = m_env->getPlayer(peer_id); @@ -1484,12 +1479,12 @@ void Server::SendChatMessage(session_t peer_id, const ChatMessage &message) } void Server::SendShowFormspecMessage(session_t peer_id, const std::string &formspec, - const std::string &formname) + const std::string &formname) { NetworkPacket pkt(TOCLIENT_SHOW_FORMSPEC, 0, peer_id); - if (formspec.empty()) { - // the client should close the formspec - // but make sure there wasn't another one open in meantime + if (formspec.empty()){ + //the client should close the formspec + //but make sure there wasn't another one open in meantime const auto it = m_formspec_state_data.find(peer_id); if (it != m_formspec_state_data.end() && it->second == formname) { m_formspec_state_data.erase(peer_id); @@ -1505,12 +1500,11 @@ void Server::SendShowFormspecMessage(session_t peer_id, const std::string &forms } // Spawns a particle on peer with peer_id -void Server::SendSpawnParticle( - session_t peer_id, u16 protocol_version, const ParticleParameters &p) +void Server::SendSpawnParticle(session_t peer_id, u16 protocol_version, + const ParticleParameters &p) { static thread_local const float radius = - g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE * - BS; + g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE * BS; if (peer_id == PEER_ID_INEXISTENT) { std::vector clients = m_clients.getClientIDs(); @@ -1550,11 +1544,10 @@ void Server::SendSpawnParticle( // Adds a ParticleSpawner on peer with peer_id void Server::SendAddParticleSpawner(session_t peer_id, u16 protocol_version, - const ParticleSpawnerParameters &p, u16 attached_id, u32 id) + const ParticleSpawnerParameters &p, u16 attached_id, u32 id) { static thread_local const float radius = - g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE * - BS; + g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE * BS; if (peer_id == PEER_ID_INEXISTENT) { std::vector clients = m_clients.getClientIDs(); @@ -1573,13 +1566,12 @@ void Server::SendAddParticleSpawner(session_t peer_id, u16 protocol_version, PlayerSAO *sao = player->getPlayerSAO(); if (!sao) continue; - if (sao->getBasePosition().getDistanceFromSQ(pos) > - radius_sq) + if (sao->getBasePosition().getDistanceFromSQ(pos) > radius_sq) continue; } - SendAddParticleSpawner(client_id, player->protocol_version, p, - attached_id, id); + SendAddParticleSpawner(client_id, player->protocol_version, + p, attached_id, id); } return; } @@ -1587,9 +1579,9 @@ void Server::SendAddParticleSpawner(session_t peer_id, u16 protocol_version, NetworkPacket pkt(TOCLIENT_ADD_PARTICLESPAWNER, 100, peer_id); - pkt << p.amount << p.time << p.minpos << p.maxpos << p.minvel << p.maxvel - << p.minacc << p.maxacc << p.minexptime << p.maxexptime << p.minsize - << p.maxsize << p.collisiondetection; + pkt << p.amount << p.time << p.minpos << p.maxpos << p.minvel + << p.maxvel << p.minacc << p.maxacc << p.minexptime << p.maxexptime + << p.minsize << p.maxsize << p.collisiondetection; pkt.putLongString(p.texture); @@ -1615,16 +1607,17 @@ void Server::SendDeleteParticleSpawner(session_t peer_id, u32 id) Send(&pkt); else m_clients.sendToAll(&pkt); + } void Server::SendHUDAdd(session_t peer_id, u32 id, HudElement *form) { - NetworkPacket pkt(TOCLIENT_HUDADD, 0, peer_id); + NetworkPacket pkt(TOCLIENT_HUDADD, 0 , peer_id); - pkt << id << (u8)form->type << form->pos << form->name << form->scale - << form->text << form->number << form->item << form->dir << form->align - << form->offset << form->world_pos << form->size << form->z_index - << form->text2; + pkt << id << (u8) form->type << form->pos << form->name << form->scale + << form->text << form->number << form->item << form->dir + << form->align << form->offset << form->world_pos << form->size + << form->z_index << form->text2; Send(&pkt); } @@ -1639,32 +1632,32 @@ void Server::SendHUDRemove(session_t peer_id, u32 id) void Server::SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value) { NetworkPacket pkt(TOCLIENT_HUDCHANGE, 0, peer_id); - pkt << id << (u8)stat; + pkt << id << (u8) stat; switch (stat) { - case HUD_STAT_POS: - case HUD_STAT_SCALE: - case HUD_STAT_ALIGN: - case HUD_STAT_OFFSET: - pkt << *(v2f *)value; - break; - case HUD_STAT_NAME: - case HUD_STAT_TEXT: - case HUD_STAT_TEXT2: - pkt << *(std::string *)value; - break; - case HUD_STAT_WORLD_POS: - pkt << *(v3f *)value; - break; - case HUD_STAT_SIZE: - pkt << *(v2s32 *)value; - break; - case HUD_STAT_NUMBER: - case HUD_STAT_ITEM: - case HUD_STAT_DIR: - default: - pkt << *(u32 *)value; - break; + case HUD_STAT_POS: + case HUD_STAT_SCALE: + case HUD_STAT_ALIGN: + case HUD_STAT_OFFSET: + pkt << *(v2f *) value; + break; + case HUD_STAT_NAME: + case HUD_STAT_TEXT: + case HUD_STAT_TEXT2: + pkt << *(std::string *) value; + break; + case HUD_STAT_WORLD_POS: + pkt << *(v3f *) value; + break; + case HUD_STAT_SIZE: + pkt << *(v2s32 *) value; + break; + case HUD_STAT_NUMBER: + case HUD_STAT_ITEM: + case HUD_STAT_DIR: + default: + pkt << *(u32 *) value; + break; } Send(&pkt); @@ -1694,26 +1687,26 @@ void Server::SendSetSky(session_t peer_id, const SkyboxParams ¶ms) // Handle prior clients here if (m_clients.getProtocolVersion(peer_id) < 39) { - pkt << params.bgcolor << params.type << (u16)params.textures.size(); + pkt << params.bgcolor << params.type << (u16) params.textures.size(); - for (const std::string &texture : params.textures) + for (const std::string& texture : params.textures) pkt << texture; pkt << params.clouds; } else { // Handle current clients and future clients - pkt << params.bgcolor << params.type << params.clouds - << params.fog_sun_tint << params.fog_moon_tint - << params.fog_tint_type; + pkt << params.bgcolor << params.type + << params.clouds << params.fog_sun_tint + << params.fog_moon_tint << params.fog_tint_type; if (params.type == "skybox") { - pkt << (u16)params.textures.size(); + pkt << (u16) params.textures.size(); for (const std::string &texture : params.textures) pkt << texture; } else if (params.type == "regular") { pkt << params.sky_color.day_sky << params.sky_color.day_horizon - << params.sky_color.dawn_sky << params.sky_color.dawn_horizon - << params.sky_color.night_sky - << params.sky_color.night_horizon << params.sky_color.indoors; + << params.sky_color.dawn_sky << params.sky_color.dawn_horizon + << params.sky_color.night_sky << params.sky_color.night_horizon + << params.sky_color.indoors; } } @@ -1723,8 +1716,9 @@ void Server::SendSetSky(session_t peer_id, const SkyboxParams ¶ms) void Server::SendSetSun(session_t peer_id, const SunParams ¶ms) { NetworkPacket pkt(TOCLIENT_SET_SUN, 0, peer_id); - pkt << params.visible << params.texture << params.tonemap << params.sunrise - << params.sunrise_visible << params.scale; + pkt << params.visible << params.texture + << params.tonemap << params.sunrise + << params.sunrise_visible << params.scale; Send(&pkt); } @@ -1732,7 +1726,8 @@ void Server::SendSetMoon(session_t peer_id, const MoonParams ¶ms) { NetworkPacket pkt(TOCLIENT_SET_MOON, 0, peer_id); - pkt << params.visible << params.texture << params.tonemap << params.scale; + pkt << params.visible << params.texture + << params.tonemap << params.scale; Send(&pkt); } @@ -1740,7 +1735,8 @@ void Server::SendSetStars(session_t peer_id, const StarParams ¶ms) { NetworkPacket pkt(TOCLIENT_SET_STARS, 0, peer_id); - pkt << params.visible << params.count << params.starcolor << params.scale; + pkt << params.visible << params.count + << params.starcolor << params.scale; Send(&pkt); } @@ -1749,15 +1745,17 @@ void Server::SendCloudParams(session_t peer_id, const CloudParams ¶ms) { NetworkPacket pkt(TOCLIENT_CLOUD_PARAMS, 0, peer_id); pkt << params.density << params.color_bright << params.color_ambient - << params.height << params.thickness << params.speed; + << params.height << params.thickness << params.speed; Send(&pkt); } -void Server::SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio) +void Server::SendOverrideDayNightRatio(session_t peer_id, bool do_override, + float ratio) { - NetworkPacket pkt(TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO, 1 + 2, peer_id); + NetworkPacket pkt(TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO, + 1 + 2, peer_id); - pkt << do_override << (u16)(ratio * 65535); + pkt << do_override << (u16) (ratio * 65535); Send(&pkt); } @@ -1769,7 +1767,8 @@ void Server::SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed) if (peer_id == PEER_ID_INEXISTENT) { m_clients.sendToAll(&pkt); - } else { + } + else { Send(&pkt); } } @@ -1780,7 +1779,7 @@ void Server::SendPlayerHP(session_t peer_id) assert(playersao); SendHP(peer_id, playersao->getHP()); - m_script->player_event(playersao, "health_changed"); + m_script->player_event(playersao,"health_changed"); // Send to other clients playersao->sendPunchCommand(); @@ -1807,9 +1806,10 @@ void Server::SendMovePlayer(session_t peer_id) { v3f pos = sao->getBasePosition(); verbosestream << "Server: Sending TOCLIENT_MOVE_PLAYER" - << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" - << " pitch=" << sao->getLookPitch() - << " yaw=" << sao->getRotation().Y << std::endl; + << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" + << " pitch=" << sao->getLookPitch() + << " yaw=" << sao->getRotation().Y + << std::endl; } Send(&pkt); @@ -1825,13 +1825,14 @@ void Server::SendPlayerFov(session_t peer_id) Send(&pkt); } -void Server::SendLocalPlayerAnimations( - session_t peer_id, v2s32 animation_frames[4], f32 animation_speed) +void Server::SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4], + f32 animation_speed) { - NetworkPacket pkt(TOCLIENT_LOCAL_PLAYER_ANIMATIONS, 0, peer_id); + NetworkPacket pkt(TOCLIENT_LOCAL_PLAYER_ANIMATIONS, 0, + peer_id); pkt << animation_frames[0] << animation_frames[1] << animation_frames[2] - << animation_frames[3] << animation_speed; + << animation_frames[3] << animation_speed; Send(&pkt); } @@ -1847,14 +1848,14 @@ void Server::SendPlayerPrivileges(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); assert(player); - if (player->getPeerId() == PEER_ID_INEXISTENT) + if(player->getPeerId() == PEER_ID_INEXISTENT) return; std::set privs; m_script->getAuth(player->getName(), NULL, &privs); NetworkPacket pkt(TOCLIENT_PRIVILEGES, 0, peer_id); - pkt << (u16)privs.size(); + pkt << (u16) privs.size(); for (const std::string &priv : privs) { pkt << priv; @@ -1892,20 +1893,18 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa { // Radius inside which objects are active static thread_local const s16 radius = - g_settings->getS16("active_object_send_range_blocks") * - MAP_BLOCKSIZE; + g_settings->getS16("active_object_send_range_blocks") * MAP_BLOCKSIZE; // Radius inside which players are active static thread_local const bool is_transfer_limited = - g_settings->exists("unlimited_player_transfer_distance") && - !g_settings->getBool("unlimited_player_transfer_distance"); + g_settings->exists("unlimited_player_transfer_distance") && + !g_settings->getBool("unlimited_player_transfer_distance"); static thread_local const s16 player_transfer_dist = - g_settings->getS16("player_transfer_distance") * MAP_BLOCKSIZE; + g_settings->getS16("player_transfer_distance") * MAP_BLOCKSIZE; - s16 player_radius = player_transfer_dist == 0 && is_transfer_limited - ? radius - : player_transfer_dist; + s16 player_radius = player_transfer_dist == 0 && is_transfer_limited ? + radius : player_transfer_dist; s16 my_radius = MYMIN(radius, playersao->getWantedRange() * MAP_BLOCKSIZE); if (my_radius <= 0) @@ -1913,12 +1912,12 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa std::queue removed_objects, added_objects; m_env->getRemovedActiveObjects(playersao, my_radius, player_radius, - client->m_known_objects, removed_objects); + client->m_known_objects, removed_objects); m_env->getAddedActiveObjects(playersao, my_radius, player_radius, - client->m_known_objects, added_objects); + client->m_known_objects, added_objects); int removed_count = removed_objects.size(); - int added_count = added_objects.size(); + int added_count = added_objects.size(); if (removed_objects.empty() && added_objects.empty()) return; @@ -1927,15 +1926,15 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa std::string data; // Handle removed objects - writeU16((u8 *)buf, removed_objects.size()); + writeU16((u8*)buf, removed_objects.size()); data.append(buf, 2); while (!removed_objects.empty()) { // Get object u16 id = removed_objects.front(); - ServerActiveObject *obj = m_env->getActiveObject(id); + ServerActiveObject* obj = m_env->getActiveObject(id); // Add to data buffer for sending - writeU16((u8 *)buf, id); + writeU16((u8*)buf, id); data.append(buf, 2); // Remove from known objects @@ -1948,7 +1947,7 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa } // Handle added objects - writeU16((u8 *)buf, added_objects.size()); + writeU16((u8*)buf, added_objects.size()); data.append(buf, 2); while (!added_objects.empty()) { // Get object @@ -1957,8 +1956,8 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa added_objects.pop(); if (!obj) { - warningstream << FUNCTION_NAME << ": NULL object id=" << (int)id - << std::endl; + warningstream << FUNCTION_NAME << ": NULL object id=" + << (int)id << std::endl; continue; } @@ -1966,13 +1965,13 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa u8 type = obj->getSendType(); // Add to data buffer for sending - writeU16((u8 *)buf, id); + writeU16((u8*)buf, id); data.append(buf, 2); - writeU8((u8 *)buf, type); + writeU8((u8*)buf, type); data.append(buf, 1); - data.append(serializeLongString(obj->getClientInitializationData( - client->net_proto_version))); + data.append(serializeLongString( + obj->getClientInitializationData(client->net_proto_version))); // Add to known objects client->m_known_objects.insert(id); @@ -1980,35 +1979,32 @@ void Server::SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersa obj->m_known_by_count++; } - NetworkPacket pkt( - TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD, data.size(), client->peer_id); + NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD, data.size(), client->peer_id); pkt.putRawString(data.c_str(), data.size()); Send(&pkt); - verbosestream << "Server::SendActiveObjectRemoveAdd: " << removed_count - << " removed, " << added_count << " added, " - << "packet size is " << pkt.getSize() << std::endl; + verbosestream << "Server::SendActiveObjectRemoveAdd: " + << removed_count << " removed, " << added_count << " added, " + << "packet size is " << pkt.getSize() << std::endl; } -void Server::SendActiveObjectMessages( - session_t peer_id, const std::string &datas, bool reliable) +void Server::SendActiveObjectMessages(session_t peer_id, const std::string &datas, + bool reliable) { - NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_MESSAGES, datas.size(), peer_id); + NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_MESSAGES, + datas.size(), peer_id); pkt.putRawString(datas.c_str(), datas.size()); m_clients.send(pkt.getPeerId(), - reliable ? clientCommandFactoryTable[pkt.getCommand()].channel - : 1, + reliable ? clientCommandFactoryTable[pkt.getCommand()].channel : 1, &pkt, reliable); } void Server::SendCSMRestrictionFlags(session_t peer_id) { NetworkPacket pkt(TOCLIENT_CSM_RESTRICTION_FLAGS, - sizeof(m_csm_restriction_flags) + - sizeof(m_csm_restriction_noderange), - peer_id); + sizeof(m_csm_restriction_flags) + sizeof(m_csm_restriction_noderange), peer_id); pkt << m_csm_restriction_flags << m_csm_restriction_noderange; Send(&pkt); } @@ -2030,28 +2026,28 @@ inline s32 Server::nextSoundId() return ret; } -s32 Server::playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms, - bool ephemeral) +s32 Server::playSound(const SimpleSoundSpec &spec, + const ServerSoundParams ¶ms, bool ephemeral) { // Find out initial position of sound bool pos_exists = false; v3f pos = params.getPos(m_env, &pos_exists); // If position is not found while it should be, cancel sound - if (pos_exists != (params.type != ServerSoundParams::SSP_LOCAL)) + if(pos_exists != (params.type != ServerSoundParams::SSP_LOCAL)) return -1; // Filter destination clients std::vector dst_clients; if (!params.to_player.empty()) { RemotePlayer *player = m_env->getPlayer(params.to_player.c_str()); - if (!player) { - infostream << "Server::playSound: Player \"" << params.to_player - << "\" not found" << std::endl; + if(!player){ + infostream<<"Server::playSound: Player \""<getPeerId() == PEER_ID_INEXISTENT) { - infostream << "Server::playSound: Player \"" << params.to_player - << "\" not connected" << std::endl; + infostream<<"Server::playSound: Player \""<getPeerId()); @@ -2071,7 +2067,7 @@ s32 Server::playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ continue; if (pos_exists) { - if (sao->getBasePosition().getDistanceFrom(pos) > + if(sao->getBasePosition().getDistanceFrom(pos) > params.max_hear_distance) continue; } @@ -2079,7 +2075,7 @@ s32 Server::playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ } } - if (dst_clients.empty()) + if(dst_clients.empty()) return -1; // Create the sound @@ -2098,8 +2094,10 @@ s32 Server::playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ float gain = params.gain * spec.gain; NetworkPacket pkt(TOCLIENT_PLAY_SOUND, 0); - pkt << id << spec.name << gain << (u8)params.type << pos << params.object - << params.loop << params.fade << params.pitch << ephemeral; + pkt << id << spec.name << gain + << (u8) params.type << pos << params.object + << params.loop << params.fade << params.pitch + << ephemeral; bool as_reliable = !ephemeral; @@ -2114,7 +2112,7 @@ void Server::stopSound(s32 handle) { // Get sound reference std::unordered_map::iterator i = - m_playing_sounds.find(handle); + m_playing_sounds.find(handle); if (i == m_playing_sounds.end()) return; ServerPlayingSound &psound = i->second; @@ -2135,7 +2133,7 @@ void Server::fadeSound(s32 handle, float step, float gain) { // Get sound reference std::unordered_map::iterator i = - m_playing_sounds.find(handle); + m_playing_sounds.find(handle); if (i == m_playing_sounds.end()) return; @@ -2177,8 +2175,8 @@ void Server::fadeSound(s32 handle, float step, float gain) } } -void Server::sendRemoveNode( - v3s16 p, std::unordered_set *far_players, float far_d_nodes) +void Server::sendRemoveNode(v3s16 p, std::unordered_set *far_players, + float far_d_nodes) { float maxd = far_d_nodes * BS; v3f p_f = intToFloat(p, BS); @@ -2199,9 +2197,8 @@ void Server::sendRemoveNode( PlayerSAO *sao = player ? player->getPlayerSAO() : nullptr; // If player is far away, only set modified blocks not sent - if (!client->isBlockSent(block_pos) || - (sao && sao->getBasePosition().getDistanceFrom(p_f) > - maxd)) { + if (!client->isBlockSent(block_pos) || (sao && + sao->getBasePosition().getDistanceFrom(p_f) > maxd)) { if (far_players) far_players->emplace(client_id); else @@ -2224,7 +2221,8 @@ void Server::sendAddNode(v3s16 p, MapNode n, std::unordered_set *far_player v3s16 block_pos = getNodeBlockPos(p); NetworkPacket pkt(TOCLIENT_ADDNODE, 6 + 2 + 1 + 1 + 1); - pkt << p << n.param0 << n.param1 << n.param2 << (u8)(remove_metadata ? 0 : 1); + pkt << p << n.param0 << n.param1 << n.param2 + << (u8) (remove_metadata ? 0 : 1); std::vector clients = m_clients.getClientIDs(); m_clients.lock(); @@ -2238,9 +2236,8 @@ void Server::sendAddNode(v3s16 p, MapNode n, std::unordered_set *far_player PlayerSAO *sao = player ? player->getPlayerSAO() : nullptr; // If player is far away, only set modified blocks not sent - if (!client->isBlockSent(block_pos) || - (sao && sao->getBasePosition().getDistanceFrom(p_f) > - maxd)) { + if (!client->isBlockSent(block_pos) || (sao && + sao->getBasePosition().getDistanceFrom(p_f) > maxd)) { if (far_players) far_players->emplace(client_id); else @@ -2278,9 +2275,8 @@ void Server::sendMetadataChanged(const std::list &meta_updates, float far continue; v3s16 block_pos = getNodeBlockPos(pos); - if (!client->isBlockSent(block_pos) || - (player && player_pos.getDistanceFrom(intToFloat( - pos, BS)) > maxd)) { + if (!client->isBlockSent(block_pos) || (player && + player_pos.getDistanceFrom(intToFloat(pos, BS)) > maxd)) { client->SetBlockNotSent(block_pos); continue; } @@ -2307,8 +2303,8 @@ void Server::sendMetadataChanged(const std::list &meta_updates, float far m_clients.unlock(); } -void Server::SendBlockNoLock( - session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version) +void Server::SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, + u16 net_proto_version) { /* Create a packet with the block in the right format @@ -2329,7 +2325,7 @@ void Server::SendBlockNoLock( void Server::SendBlocks(float dtime) { MutexAutoLock envlock(m_env_mutex); - // TODO check if one big lock could be faster then multiple small ones + //TODO check if one big lock could be faster then multiple small ones std::vector queue; @@ -2342,14 +2338,13 @@ void Server::SendBlocks(float dtime) m_clients.lock(); for (const session_t client_id : clients) { - RemoteClient *client = m_clients.lockedGetClientNoEx( - client_id, CS_Active); + RemoteClient *client = m_clients.lockedGetClientNoEx(client_id, CS_Active); if (!client) continue; total_sending += client->getSendingCount(); - client->GetNextBlocks(m_env, m_emerge, dtime, queue); + client->GetNextBlocks(m_env,m_emerge, dtime, queue); } m_clients.unlock(); } @@ -2363,12 +2358,8 @@ void Server::SendBlocks(float dtime) // Maximal total count calculation // The per-client block sends is halved with the maximal online users - u32 max_blocks_to_send = - (m_env->getPlayerCount() + g_settings->getU32("max_users")) * - g_settings->getU32("max_simultaneous_block_sends_" - "per_client") / - 4 + - 1; + u32 max_blocks_to_send = (m_env->getPlayerCount() + g_settings->getU32("max_users")) * + g_settings->getU32("max_simultaneous_block_sends_per_client") / 4 + 1; ScopeProfiler sp(g_profiler, "Server::SendBlocks(): Send to clients"); Map &map = m_env->getMap(); @@ -2381,13 +2372,13 @@ void Server::SendBlocks(float dtime) if (!block) continue; - RemoteClient *client = m_clients.lockedGetClientNoEx( - block_to_send.peer_id, CS_Active); + RemoteClient *client = m_clients.lockedGetClientNoEx(block_to_send.peer_id, + CS_Active); if (!client) continue; - SendBlockNoLock(block_to_send.peer_id, block, - client->serialization_version, client->net_proto_version); + SendBlockNoLock(block_to_send.peer_id, block, client->serialization_version, + client->net_proto_version); client->SentBlock(block_to_send.pos); total_sending++; @@ -2414,23 +2405,29 @@ bool Server::SendBlock(session_t peer_id, const v3s16 &blockpos) return true; } -bool Server::addMediaFile(const std::string &filename, const std::string &filepath, - std::string *filedata_to, std::string *digest_to) +bool Server::addMediaFile(const std::string &filename, + const std::string &filepath, std::string *filedata_to, + std::string *digest_to) { // If name contains illegal characters, ignore the file if (!string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)) { - infostream << "Server: ignoring illegal file name: \"" << filename << "\"" - << std::endl; + infostream << "Server: ignoring illegal file name: \"" + << filename << "\"" << std::endl; return false; } // If name is not in a supported format, ignore it - const char *supported_ext[] = {".png", ".jpg", ".bmp", ".tga", ".pcx", ".ppm", - ".psd", ".wal", ".rgb", ".ogg", ".x", ".b3d", ".md2", ".obj", - // Custom translation file format - ".tr", NULL}; + const char *supported_ext[] = { + ".png", ".jpg", ".bmp", ".tga", + ".pcx", ".ppm", ".psd", ".wal", ".rgb", + ".ogg", + ".x", ".b3d", ".md2", ".obj", + // Custom translation file format + ".tr", + NULL + }; if (removeStringEnd(filename, supported_ext).empty()) { infostream << "Server: ignoring unsupported file extension: \"" - << filename << "\"" << std::endl; + << filename << "\"" << std::endl; return false; } // Ok, attempt to load the file and add to cache @@ -2438,8 +2435,8 @@ bool Server::addMediaFile(const std::string &filename, const std::string &filepa // Read data std::ifstream fis(filepath.c_str(), std::ios_base::binary); if (!fis.good()) { - errorstream << "Server::addMediaFile(): Could not open \"" << filename - << "\" for reading" << std::endl; + errorstream << "Server::addMediaFile(): Could not open \"" + << filename << "\" for reading" << std::endl; return false; } std::string filedata; @@ -2457,12 +2454,12 @@ bool Server::addMediaFile(const std::string &filename, const std::string &filepa } } if (bad) { - errorstream << "Server::addMediaFile(): Failed to read \"" << filename - << "\"" << std::endl; + errorstream << "Server::addMediaFile(): Failed to read \"" + << filename << "\"" << std::endl; return false; } else if (filedata.empty()) { - errorstream << "Server::addMediaFile(): Empty file \"" << filepath << "\"" - << std::endl; + errorstream << "Server::addMediaFile(): Empty file \"" + << filepath << "\"" << std::endl; return false; } @@ -2471,14 +2468,15 @@ bool Server::addMediaFile(const std::string &filename, const std::string &filepa unsigned char *digest = sha1.getDigest(); std::string sha1_base64 = base64_encode(digest, 20); - std::string sha1_hex = hex_encode((char *)digest, 20); + std::string sha1_hex = hex_encode((char*) digest, 20); if (digest_to) - *digest_to = std::string((char *)digest, 20); + *digest_to = std::string((char*) digest, 20); free(digest); // Put in list m_media[filename] = MediaInfo(filepath, sha1_base64); - verbosestream << "Server: " << sha1_hex << " is " << filename << std::endl; + verbosestream << "Server: " << sha1_hex << " is " << filename + << std::endl; if (filedata_to) *filedata_to = std::move(filedata); @@ -2493,8 +2491,7 @@ void Server::fillMediaCache() std::vector paths; m_modmgr->getModsMediaPaths(paths); fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures"); - fs::GetRecursiveDirs(paths, porting::path_user + DIR_DELIM + "textures" + - DIR_DELIM + "server"); + fs::GetRecursiveDirs(paths, porting::path_user + DIR_DELIM + "textures" + DIR_DELIM + "server"); // Collect media file information from paths into cache for (const std::string &mediapath : paths) { @@ -2508,8 +2505,7 @@ void Server::fillMediaCache() } } - infostream << "Server: " << m_media.size() << " media files collected" - << std::endl; + infostream << "Server: " << m_media.size() << " media files collected" << std::endl; } void Server::sendMediaAnnouncement(session_t peer_id, const std::string &lang_code) @@ -2538,8 +2534,7 @@ void Server::sendMediaAnnouncement(session_t peer_id, const std::string &lang_co Send(&pkt); verbosestream << "Server: Announcing files to id(" << peer_id - << "): count=" << media_sent << " size=" << pkt.getSize() - << std::endl; + << "): count=" << media_sent << " size=" << pkt.getSize() << std::endl; } struct SendableMedia @@ -2548,77 +2543,78 @@ struct SendableMedia std::string path; std::string data; - SendableMedia(const std::string &name_ = "", const std::string &path_ = "", - const std::string &data_ = "") : - name(name_), - path(path_), data(data_) - { - } + SendableMedia(const std::string &name_="", const std::string &path_="", + const std::string &data_=""): + name(name_), + path(path_), + data(data_) + {} }; -void Server::sendRequestedMedia(session_t peer_id, const std::vector &tosend) +void Server::sendRequestedMedia(session_t peer_id, + const std::vector &tosend) { - verbosestream << "Server::sendRequestedMedia(): " - << "Sending files to client" << std::endl; + verbosestream<<"Server::sendRequestedMedia(): " + <<"Sending files to client"<> file_bunches; + std::vector< std::vector > file_bunches; file_bunches.emplace_back(); u32 file_size_bunch_total = 0; for (const std::string &name : tosend) { if (m_media.find(name) == m_media.end()) { - errorstream << "Server::sendRequestedMedia(): Client asked for " - << "unknown file \"" << (name) << "\"" << std::endl; + errorstream<<"Server::sendRequestedMedia(): Client asked for " + <<"unknown file \""<<(name)<<"\""<= bytes_per_bunch) { + if(file_size_bunch_total >= bytes_per_bunch) { file_bunches.emplace_back(); file_size_bunch_total = 0; } + } /* Create and send packets */ @@ -2639,22 +2635,22 @@ void Server::sendRequestedMedia(session_t peer_id, const std::vectorgetPlayer()->getName() - << " dies" << std::endl; + infostream << "Server::DiePlayer(): Player " + << playersao->getPlayer()->getName() + << " dies" << std::endl; playersao->setHP(0, reason); playersao->clearParentAttachment(); @@ -2715,7 +2711,7 @@ void Server::DiePlayer(session_t peer_id, const PlayerHPChangeReason &reason) m_script->on_dieplayer(playersao, reason); SendPlayerHP(peer_id); - SendDeathscreen(peer_id, false, v3f(0, 0, 0)); + SendDeathscreen(peer_id, false, v3f(0,0,0)); } void Server::RespawnPlayer(session_t peer_id) @@ -2724,7 +2720,8 @@ void Server::RespawnPlayer(session_t peer_id) assert(playersao); infostream << "Server::RespawnPlayer(): Player " - << playersao->getPlayer()->getName() << " respawns" << std::endl; + << playersao->getPlayer()->getName() + << " respawns" << std::endl; playersao->setHP(playersao->accessObjectProperties()->hp_max, PlayerHPChangeReason(PlayerHPChangeReason::RESPAWN)); @@ -2739,14 +2736,16 @@ void Server::RespawnPlayer(session_t peer_id) SendPlayerHP(peer_id); } + void Server::DenySudoAccess(session_t peer_id) { NetworkPacket pkt(TOCLIENT_DENY_SUDO_MODE, 0, peer_id); Send(&pkt); } -void Server::DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, - AccessDeniedCode reason, const std::string &str_reason, bool reconnect) + +void Server::DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason, + const std::string &str_reason, bool reconnect) { SendAccessDenied(peer_id, reason, str_reason, reconnect); @@ -2754,6 +2753,7 @@ void Server::DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, DisconnectPeer(peer_id); } + void Server::DenyAccess(session_t peer_id, AccessDeniedCode reason, const std::string &custom_reason) { @@ -2780,7 +2780,7 @@ void Server::DisconnectPeer(session_t peer_id) void Server::acceptAuth(session_t peer_id, bool forSudoMode) { if (!forSudoMode) { - RemoteClient *client = getClient(peer_id, CS_Invalid); + RemoteClient* client = getClient(peer_id, CS_Invalid); NetworkPacket resp_pkt(TOCLIENT_AUTH_ACCEPT, 1 + 6 + 8 + 4, peer_id); @@ -2788,9 +2788,9 @@ void Server::acceptAuth(session_t peer_id, bool forSudoMode) u32 sudo_auth_mechs = client->allowed_auth_mechs; client->allowed_sudo_mechs = sudo_auth_mechs; - resp_pkt << v3f(0, 0, 0) << (u64)m_env->getServerMap().getSeed() - << g_settings->getFloat("dedicated_server_step") - << sudo_auth_mechs; + resp_pkt << v3f(0,0,0) << (u64) m_env->getServerMap().getSeed() + << g_settings->getFloat("dedicated_server_step") + << sudo_auth_mechs; Send(&resp_pkt); m_clients.event(peer_id, CSE_AuthAccept); @@ -2813,9 +2813,8 @@ void Server::DeleteClient(session_t peer_id, ClientDeletionReason reason) /* Clear references to playing sounds */ - for (std::unordered_map::iterator i = - m_playing_sounds.begin(); - i != m_playing_sounds.end();) { + for (std::unordered_map::iterator + i = m_playing_sounds.begin(); i != m_playing_sounds.end();) { ServerPlayingSound &psound = i->second; psound.clients.erase(peer_id); if (psound.clients.empty()) @@ -2839,11 +2838,9 @@ void Server::DeleteClient(session_t peer_id, ClientDeletionReason reason) // inform connected clients const std::string &player_name = player->getName(); - NetworkPacket notice(TOCLIENT_UPDATE_PLAYER_LIST, 0, - PEER_ID_INEXISTENT); - // (u16) 1 + std::string represents a vector serialization - // representation - notice << (u8)PLAYER_LIST_REMOVE << (u16)1 << player_name; + NetworkPacket notice(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT); + // (u16) 1 + std::string represents a vector serialization representation + notice << (u8) PLAYER_LIST_REMOVE << (u16) 1 << player_name; m_clients.sendToAll(¬ice); // run scripts m_script->on_leaveplayer(playersao, reason == CDR_TIMEOUT); @@ -2861,8 +2858,7 @@ void Server::DeleteClient(session_t peer_id, ClientDeletionReason reason) for (const session_t client_id : clients) { // Get player - RemotePlayer *player = - m_env->getPlayer(client_id); + RemotePlayer *player = m_env->getPlayer(client_id); if (!player) continue; @@ -2872,14 +2868,11 @@ void Server::DeleteClient(session_t peer_id, ClientDeletionReason reason) std::string name = player->getName(); actionstream << name << " " - << (reason == CDR_TIMEOUT ? "times out." - : "leaves game.") - << " List of players: " << os.str() - << std::endl; + << (reason == CDR_TIMEOUT ? "times out." : "leaves game.") + << " List of players: " << os.str() << std::endl; if (m_admin_chat) m_admin_chat->outgoing_queue.push_back( - new ChatEventNick(CET_NICK_REMOVE, - name)); + new ChatEventNick(CET_NICK_REMOVE, name)); } } { @@ -2910,8 +2903,8 @@ void Server::UpdateCrafting(RemotePlayer *player) loc.setPlayer(player->getName()); std::vector output_replacements; getCraftingResult(&player->inventory, preview, output_replacements, false, this); - m_env->getScriptIface()->item_CraftPredict( - preview, player->getPlayerSAO(), clist, loc); + m_env->getScriptIface()->item_CraftPredict(preview, player->getPlayerSAO(), + clist, loc); InventoryList *plist = player->inventory.getList("craftpreview"); if (plist && plist->getSize() >= 1) { @@ -2927,17 +2920,11 @@ void Server::handleChatInterfaceEvent(ChatEvent *evt) m_admin_nick = ((ChatEventNick *)evt)->nick; if (!m_script->getAuth(m_admin_nick, NULL, NULL)) { errorstream << "You haven't set up an account." << std::endl - << "Please log in using the client as '" - << m_admin_nick << "' with a secure password." - << std::endl - << "Until then, you can't execute admin tasks via " - "the console," - << std::endl - << "and everybody can claim the user account instead " - "of you," - << std::endl - << "giving them full control over this server." - << std::endl; + << "Please log in using the client as '" + << m_admin_nick << "' with a secure password." << std::endl + << "Until then, you can't execute admin tasks via the console," << std::endl + << "and everybody can claim the user account instead of you," << std::endl + << "giving them full control over this server." << std::endl; } } else { assert(evt->type == CET_CHAT); @@ -2946,10 +2933,11 @@ void Server::handleChatInterfaceEvent(ChatEvent *evt) } std::wstring Server::handleChat(const std::string &name, const std::wstring &wname, - std::wstring wmessage, bool check_shout_priv, RemotePlayer *player) + std::wstring wmessage, bool check_shout_priv, RemotePlayer *player) { // If something goes wrong, this player is to blame - RollbackScopeActor rollback_scope(m_rollback, std::string("player:") + name); + RollbackScopeActor rollback_scope(m_rollback, + std::string("player:") + name); if (g_settings->getBool("strip_color_codes")) wmessage = unescape_enriched(wmessage); @@ -2959,8 +2947,8 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna case RPLAYER_CHATRESULT_FLOODING: { std::wstringstream ws; ws << L"You cannot send more messages. You are limited to " - << g_settings->getFloat("chat_message_limit_per_10sec") - << L" messages per 10 seconds."; + << g_settings->getFloat("chat_message_limit_per_10sec") + << L" messages per 10 seconds."; return ws.str(); } case RPLAYER_CHATRESULT_KICK: @@ -2974,11 +2962,10 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna } } - if (m_max_chatmessage_length > 0 && - wmessage.length() > m_max_chatmessage_length) { - return L"Your message exceed the maximum chat message limit set on the " - L"server. " - L"It was refused. Send a shorter message"; + if (m_max_chatmessage_length > 0 + && wmessage.length() > m_max_chatmessage_length) { + return L"Your message exceed the maximum chat message limit set on the server. " + L"It was refused. Send a shorter message"; } auto message = trim(wide_to_utf8(wmessage)); @@ -3006,8 +2993,8 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna #ifdef __ANDROID__ line += L"<" + wname + L"> " + wmessage; #else - line += narrow_to_wide(m_script->formatChatMessage( - name, wide_to_narrow(wmessage))); + line += narrow_to_wide(m_script->formatChatMessage(name, + wide_to_narrow(wmessage))); #endif } @@ -3030,7 +3017,7 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna */ session_t peer_id_to_avoid_sending = - (player ? player->getPeerId() : PEER_ID_INEXISTENT); + (player ? player->getPeerId() : PEER_ID_INEXISTENT); if (player && player->protocol_version >= 29) peer_id_to_avoid_sending = PEER_ID_INEXISTENT; @@ -3058,8 +3045,8 @@ void Server::handleAdminChat(const ChatEventChat *evt) RemoteClient *Server::getClient(session_t peer_id, ClientState state_min) { - RemoteClient *client = getClientNoEx(peer_id, state_min); - if (!client) + RemoteClient *client = getClientNoEx(peer_id,state_min); + if(!client) throw ClientNotFoundException("Client not found"); return client; @@ -3073,7 +3060,7 @@ std::string Server::getPlayerName(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); if (!player) - return "[id=" + itos(peer_id) + "]"; + return "[id="+itos(peer_id)+"]"; return player->getName(); } @@ -3120,12 +3107,11 @@ std::wstring Server::getStatusString() } os << L"}"; - if (m_env && !((ServerMap *)(&m_env->getMap()))->isSavingEnabled()) + if (m_env && !((ServerMap*)(&m_env->getMap()))->isSavingEnabled()) os << std::endl << L"# Server: " << " WARNING: Map saving is disabled."; if (!g_settings->get("motd").empty()) - os << std::endl - << L"# Server: " << narrow_to_wide(g_settings->get("motd")); + os << std::endl << L"# Server: " << narrow_to_wide(g_settings->get("motd")); return os.str(); } @@ -3157,9 +3143,11 @@ void Server::reportPrivsModified(const std::string &name) return; SendPlayerPrivileges(player->getPeerId()); PlayerSAO *sao = player->getPlayerSAO(); - if (!sao) + if(!sao) return; - sao->updatePrivileges(getPlayerEffectivePrivs(name), isSingleplayer()); + sao->updatePrivileges( + getPlayerEffectivePrivs(name), + isSingleplayer()); } } @@ -3216,7 +3204,7 @@ void Server::notifyPlayer(const char *name, const std::wstring &msg) } bool Server::showFormspec(const char *playername, const std::string &formspec, - const std::string &formname) + const std::string &formname) { // m_env will be NULL if the server is initializing if (!m_env) @@ -3242,12 +3230,11 @@ u32 Server::hudAdd(RemotePlayer *player, HudElement *form) return id; } -bool Server::hudRemove(RemotePlayer *player, u32 id) -{ +bool Server::hudRemove(RemotePlayer *player, u32 id) { if (!player) return false; - HudElement *todel = player->removeHud(id); + HudElement* todel = player->removeHud(id); if (!todel) return false; @@ -3276,7 +3263,7 @@ bool Server::hudSetFlags(RemotePlayer *player, u32 flags, u32 mask) player->hud_flags &= ~mask; player->hud_flags |= flags; - PlayerSAO *playersao = player->getPlayerSAO(); + PlayerSAO* playersao = player->getPlayerSAO(); if (!playersao) return false; @@ -3323,8 +3310,8 @@ Address Server::getPeerAddress(session_t peer_id) return m_con->GetPeerAddress(peer_id); } -void Server::setLocalPlayerAnimations( - RemotePlayer *player, v2s32 animation_frames[4], f32 frame_speed) +void Server::setLocalPlayerAnimations(RemotePlayer *player, + v2s32 animation_frames[4], f32 frame_speed) { sanity_check(player); player->setLocalAnimations(animation_frames, frame_speed); @@ -3374,7 +3361,8 @@ void Server::setClouds(RemotePlayer *player, const CloudParams ¶ms) SendCloudParams(player->getPeerId(), params); } -void Server::overrideDayNightRatio(RemotePlayer *player, bool do_override, float ratio) +void Server::overrideDayNightRatio(RemotePlayer *player, bool do_override, + float ratio) { sanity_check(player); player->overrideDayNightRatio(do_override, ratio); @@ -3386,7 +3374,8 @@ void Server::notifyPlayers(const std::wstring &msg) SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(msg)); } -void Server::spawnParticle(const std::string &playername, const ParticleParameters &p) +void Server::spawnParticle(const std::string &playername, + const ParticleParameters &p) { // m_env will be NULL if the server is initializing if (!m_env) @@ -3406,7 +3395,7 @@ void Server::spawnParticle(const std::string &playername, const ParticleParamete } u32 Server::addParticleSpawner(const ParticleSpawnerParameters &p, - ServerActiveObject *attached, const std::string &playername) + ServerActiveObject *attached, const std::string &playername) { // m_env will be NULL if the server is initializing if (!m_env) @@ -3438,8 +3427,7 @@ void Server::deleteParticleSpawner(const std::string &playername, u32 id) { // m_env will be NULL if the server is initializing if (!m_env) - throw ServerError( - "Can't delete particle spawners during initialisation!"); + throw ServerError("Can't delete particle spawners during initialisation!"); session_t peer_id = PEER_ID_INEXISTENT; if (!playername.empty()) { @@ -3458,7 +3446,7 @@ bool Server::dynamicAddMedia(const std::string &filepath) std::string filename = fs::GetFilenameFromPath(filepath.c_str()); if (m_media.find(filename) != m_media.end()) { errorstream << "Server::dynamicAddMedia(): file \"" << filename - << "\" already exists in media cache" << std::endl; + << "\" already exists in media cache" << std::endl; return false; } @@ -3470,16 +3458,17 @@ bool Server::dynamicAddMedia(const std::string &filepath) // Push file to existing clients NetworkPacket pkt(TOCLIENT_MEDIA_PUSH, 0); - pkt << raw_hash << filename << (bool)true; + pkt << raw_hash << filename << (bool) true; pkt.putLongString(filedata); auto client_ids = m_clients.getClientIDs(CS_DefinitionsSent); for (session_t client_id : client_ids) { /* - The network layer only guarantees ordered delivery inside a - channel. Since the very next packet could be one that uses the media, - we have to push the media over ALL channels to ensure it is processed - before it is used. In practice this means we have to send it twice: + The network layer only guarantees ordered delivery inside a channel. + Since the very next packet could be one that uses the media, we have + to push the media over ALL channels to ensure it is processed before + it is used. + In practice this means we have to send it twice: - channel 1 (HUD) - channel 0 (everything else: e.g. play_sound, object messages) */ @@ -3492,12 +3481,11 @@ bool Server::dynamicAddMedia(const std::string &filepath) // actions: time-reversed list // Return value: success/failure -bool Server::rollbackRevertActions( - const std::list &actions, std::list *log) +bool Server::rollbackRevertActions(const std::list &actions, + std::list *log) { - infostream << "Server::rollbackRevertActions(len=" << actions.size() << ")" - << std::endl; - ServerMap *map = (ServerMap *)(&m_env->getMap()); + infostream<<"Server::rollbackRevertActions(len="<getMap()); // Fail if no actions to handle if (actions.empty()) { @@ -3512,31 +3500,27 @@ bool Server::rollbackRevertActions( for (const RollbackAction &action : actions) { num_tried++; bool success = action.applyRevert(map, m_inventory_mgr.get(), this); - if (!success) { + if(!success){ num_failed++; std::ostringstream os; - os << "Revert of step (" << num_tried << ") " << action.toString() - << " failed"; - infostream << "Map::rollbackRevertActions(): " << os.str() - << std::endl; + os<<"Revert of step ("<push_back(os.str()); - } else { + }else{ std::ostringstream os; - os << "Successfully reverted step (" << num_tried << ") " - << action.toString(); - infostream << "Map::rollbackRevertActions(): " << os.str() - << std::endl; + os<<"Successfully reverted step ("<push_back(os.str()); } } - infostream << "Map::rollbackRevertActions(): " << num_failed << "/" << num_tried - << " failed" << std::endl; + infostream<<"Map::rollbackRevertActions(): "< &Server::getMods() const +const std::vector & Server::getMods() const { return m_modmgr->getMods(); } @@ -3616,8 +3600,9 @@ v3f Server::findSpawnPos() for (s32 i = 0; i < 4000 && !is_good; i++) { s32 range = MYMIN(1 + i, range_max); // We're going to try to throw the player to this position - v2s16 nodepos2d = v2s16(-range + (myrand() % (range * 2)), - -range + (myrand() % (range * 2))); + v2s16 nodepos2d = v2s16( + -range + (myrand() % (range * 2)), + -range + (myrand() % (range * 2))); // Get spawn level at point s16 spawn_level = m_emerge->getSpawnLevelAtPoint(nodepos2d); // Continue if MAX_MAP_GENERATION_LIMIT was returned by the mapgen to @@ -3640,10 +3625,9 @@ v3f Server::findSpawnPos() map.emergeBlock(blockpos, true); content_t c = map.getNode(nodepos).getContent(); - // In generated mapblocks allow spawn in all 'airlike' drawtype - // nodes. In ungenerated mapblocks allow spawn in 'ignore' nodes. - if (m_nodedef->get(c).drawtype == NDT_AIRLIKE || - c == CONTENT_IGNORE) { + // In generated mapblocks allow spawn in all 'airlike' drawtype nodes. + // In ungenerated mapblocks allow spawn in 'ignore' nodes. + if (m_nodedef->get(c).drawtype == NDT_AIRLIKE || c == CONTENT_IGNORE) { air_count++; if (air_count >= 2) { // Spawn in lower empty node @@ -3651,12 +3635,10 @@ v3f Server::findSpawnPos() nodeposf = intToFloat(nodepos, BS); // Don't spawn the player outside map boundaries if (objectpos_over_limit(nodeposf)) - // Exit this loop, positions above are - // probably over limit + // Exit this loop, positions above are probably over limit break; - // Good position found, cause an exit from main - // loop + // Good position found, cause an exit from main loop is_good = true; break; } @@ -3677,7 +3659,7 @@ v3f Server::findSpawnPos() void Server::requestShutdown(const std::string &msg, bool reconnect, float delay) { if (delay == 0.0f) { - // No delay, shutdown immediately + // No delay, shutdown immediately m_shutdown_state.is_requested = true; // only print to the infostream, a chat message saying // "Server Shutting Down" is sent when the server destructs. @@ -3694,11 +3676,12 @@ void Server::requestShutdown(const std::string &msg, bool reconnect, float delay // m_shutdown_* are already handled, skip. return; } else if (delay > 0.0f) { - // Positive delay, tell the clients when the server will shut down + // Positive delay, tell the clients when the server will shut down std::wstringstream ws; ws << L"*** Server shutting down in " - << duration_to_string(myround(delay)).c_str() << "."; + << duration_to_string(myround(delay)).c_str() + << "."; infostream << wide_to_utf8(ws.str()).c_str() << std::endl; SendChatMessage(PEER_ID_INEXISTENT, ws.str()); @@ -3707,7 +3690,7 @@ void Server::requestShutdown(const std::string &msg, bool reconnect, float delay m_shutdown_state.trigger(delay, msg, reconnect); } -PlayerSAO *Server::emergePlayer(const char *name, session_t peer_id, u16 proto_version) +PlayerSAO* Server::emergePlayer(const char *name, session_t peer_id, u16 proto_version) { /* Try to get an existing player @@ -3716,7 +3699,7 @@ PlayerSAO *Server::emergePlayer(const char *name, session_t peer_id, u16 proto_v // If player is already connected, cancel if (player && player->getPeerId() != PEER_ID_INEXISTENT) { - infostream << "emergePlayer(): Player already connected" << std::endl; + infostream<<"emergePlayer(): Player already connected"<getPlayer(peer_id)) { - infostream << "emergePlayer(): Player with wrong name but same" - " peer_id already exists" - << std::endl; + infostream<<"emergePlayer(): Player with wrong name but same" + " peer_id already exists"<loadPlayer(player, &newplayer, peer_id, isSingleplayer()); + PlayerSAO *playersao = m_env->loadPlayer(player, &newplayer, peer_id, isSingleplayer()); // Complete init with server parts playersao->finalize(player, getPlayerEffectivePrivs(player->getName())); @@ -3756,7 +3737,7 @@ bool Server::registerModStorage(ModMetadata *storage) { if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) { errorstream << "Unable to register same mod storage twice. Storage name: " - << storage->getModName() << std::endl; + << storage->getModName() << std::endl; return false; } @@ -3766,8 +3747,7 @@ bool Server::registerModStorage(ModMetadata *storage) void Server::unregisterModStorage(const std::string &name) { - std::unordered_map::const_iterator it = - m_mod_storages.find(name); + std::unordered_map::const_iterator it = m_mod_storages.find(name); if (it != m_mod_storages.end()) { // Save unconditionaly on unregistration it->second->save(getModStoragePath()); @@ -3777,7 +3757,7 @@ void Server::unregisterModStorage(const std::string &name) void dedicated_server_loop(Server &server, bool &kill) { - verbosestream << "dedicated_server_loop()" << std::endl; + verbosestream<<"dedicated_server_loop()"<print(infostream); g_profiler->clear(); } @@ -3815,8 +3796,8 @@ void dedicated_server_loop(Server &server, bool &kill) infostream << "Dedicated server quitting" << std::endl; #if USE_CURL if (g_settings->getBool("server_announce")) - ServerList::sendAnnounce( - ServerList::AA_DELETE, server.m_bind_addr.getPort()); + ServerList::sendAnnounce(ServerList::AA_DELETE, + server.m_bind_addr.getPort()); #endif } @@ -3824,10 +3805,11 @@ void dedicated_server_loop(Server &server, bool &kill) * Mod channels */ + bool Server::joinModChannel(const std::string &channel) { return m_modchannel_mgr->joinChannel(channel, PEER_ID_SERVER) && - m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE); + m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE); } bool Server::leaveModChannel(const std::string &channel) @@ -3844,7 +3826,7 @@ bool Server::sendModChannelMessage(const std::string &channel, const std::string return true; } -ModChannel *Server::getModChannel(const std::string &channel) +ModChannel* Server::getModChannel(const std::string &channel) { return m_modchannel_mgr->getModChannel(channel); } @@ -3858,8 +3840,8 @@ void Server::broadcastModChannelMessage(const std::string &channel, if (message.size() > STRING_MAX_LEN) { warningstream << "ModChannel message too long, dropping before sending " - << " (" << message.size() << " > " << STRING_MAX_LEN - << ", channel: " << channel << ")" << std::endl; + << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: " + << channel << ")" << std::endl; return; } @@ -3894,7 +3876,7 @@ void Server::loadTranslationLanguage(const std::string &lang_code) if (str_ends_with(i.first, suffix)) { std::ifstream t(i.second.path); std::string data((std::istreambuf_iterator(t)), - std::istreambuf_iterator()); + std::istreambuf_iterator()); (*g_server_translations)[lang_code].loadTranslation(data); } diff --git a/src/server.h b/src/server.h index 51566e9f3..f44716531 100644 --- a/src/server.h +++ b/src/server.h @@ -28,7 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventorymanager.h" #include "content/subgames.h" #include "tileanimation.h" // TileAnimationParams -#include "particles.h" // ParticleParams +#include "particles.h" // ParticleParams #include "network/peerhandler.h" #include "network/address.h" #include "util/numeric.h" @@ -71,8 +71,7 @@ class ServerThread; class ServerModManager; class ServerInventoryManager; -enum ClientDeletionReason -{ +enum ClientDeletionReason { CDR_LEAVE, CDR_TIMEOUT, CDR_DENY @@ -83,16 +82,17 @@ struct MediaInfo std::string path; std::string sha1_digest; - MediaInfo(const std::string &path_ = "", const std::string &sha1_digest_ = "") : - path(path_), sha1_digest(sha1_digest_) + MediaInfo(const std::string &path_="", + const std::string &sha1_digest_=""): + path(path_), + sha1_digest(sha1_digest_) { } }; struct ServerSoundParams { - enum Type - { + enum Type { SSP_LOCAL, SSP_POSITIONAL, SSP_OBJECT @@ -117,16 +117,22 @@ struct ServerPlayingSound std::unordered_set clients; // peer ids }; -class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef +class Server : public con::PeerHandler, public MapEventReceiver, + public IGameDef { public: /* NOTE: Every public method should be thread-safe */ - Server(const std::string &path_world, const SubgameSpec &gamespec, - bool simple_singleplayer_mode, Address bind_addr, bool dedicated, - ChatInterface *iface = nullptr); + Server( + const std::string &path_world, + const SubgameSpec &gamespec, + bool simple_singleplayer_mode, + Address bind_addr, + bool dedicated, + ChatInterface *iface = nullptr + ); ~Server(); DISABLE_CLASS_COPY(Server); @@ -136,40 +142,40 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef // Actual processing is done in an another thread. void step(float dtime); // This is run by ServerThread and does the actual processing - void AsyncRunStep(bool initial_step = false); + void AsyncRunStep(bool initial_step=false); void Receive(); - PlayerSAO *StageTwoClientInit(session_t peer_id); + PlayerSAO* StageTwoClientInit(session_t peer_id); /* * Command Handlers */ - void handleCommand(NetworkPacket *pkt); + void handleCommand(NetworkPacket* pkt); - void handleCommand_Null(NetworkPacket *pkt){}; - void handleCommand_Deprecated(NetworkPacket *pkt); - void handleCommand_Init(NetworkPacket *pkt); - void handleCommand_Init2(NetworkPacket *pkt); + void handleCommand_Null(NetworkPacket* pkt) {}; + void handleCommand_Deprecated(NetworkPacket* pkt); + void handleCommand_Init(NetworkPacket* pkt); + void handleCommand_Init2(NetworkPacket* pkt); void handleCommand_ModChannelJoin(NetworkPacket *pkt); void handleCommand_ModChannelLeave(NetworkPacket *pkt); void handleCommand_ModChannelMsg(NetworkPacket *pkt); - void handleCommand_RequestMedia(NetworkPacket *pkt); - void handleCommand_ClientReady(NetworkPacket *pkt); - void handleCommand_GotBlocks(NetworkPacket *pkt); - void handleCommand_PlayerPos(NetworkPacket *pkt); - void handleCommand_DeletedBlocks(NetworkPacket *pkt); - void handleCommand_InventoryAction(NetworkPacket *pkt); - void handleCommand_ChatMessage(NetworkPacket *pkt); - void handleCommand_Damage(NetworkPacket *pkt); - void handleCommand_PlayerItem(NetworkPacket *pkt); - void handleCommand_Respawn(NetworkPacket *pkt); - void handleCommand_Interact(NetworkPacket *pkt); - void handleCommand_RemovedSounds(NetworkPacket *pkt); - void handleCommand_NodeMetaFields(NetworkPacket *pkt); - void handleCommand_InventoryFields(NetworkPacket *pkt); - void handleCommand_FirstSrp(NetworkPacket *pkt); - void handleCommand_SrpBytesA(NetworkPacket *pkt); - void handleCommand_SrpBytesM(NetworkPacket *pkt); + void handleCommand_RequestMedia(NetworkPacket* pkt); + void handleCommand_ClientReady(NetworkPacket* pkt); + void handleCommand_GotBlocks(NetworkPacket* pkt); + void handleCommand_PlayerPos(NetworkPacket* pkt); + void handleCommand_DeletedBlocks(NetworkPacket* pkt); + void handleCommand_InventoryAction(NetworkPacket* pkt); + void handleCommand_ChatMessage(NetworkPacket* pkt); + void handleCommand_Damage(NetworkPacket* pkt); + void handleCommand_PlayerItem(NetworkPacket* pkt); + void handleCommand_Respawn(NetworkPacket* pkt); + void handleCommand_Interact(NetworkPacket* pkt); + void handleCommand_RemovedSounds(NetworkPacket* pkt); + void handleCommand_NodeMetaFields(NetworkPacket* pkt); + void handleCommand_InventoryFields(NetworkPacket* pkt); + void handleCommand_FirstSrp(NetworkPacket* pkt); + void handleCommand_SrpBytesA(NetworkPacket* pkt); + void handleCommand_SrpBytesM(NetworkPacket* pkt); void ProcessData(NetworkPacket *pkt); @@ -177,8 +183,8 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef void Send(session_t peer_id, NetworkPacket *pkt); // Helper for handleCommand_PlayerPos and handleCommand_Interact - void process_PlayerPos( - RemotePlayer *player, PlayerSAO *playersao, NetworkPacket *pkt); + void process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao, + NetworkPacket *pkt); // Both setter and getter need no envlock, // can be called freely from threads @@ -204,14 +210,14 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef // Returns -1 if failed, sound handle on success // Envlock s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms, - bool ephemeral = false); + bool ephemeral=false); void stopSound(s32 handle); void fadeSound(s32 handle, float step, float gain); // Envlock std::set getPlayerEffectivePrivs(const std::string &name); bool checkPriv(const std::string &name, const std::string &priv); - void reportPrivsModified(const std::string &name = ""); // ""=all + void reportPrivsModified(const std::string &name=""); // ""=all void reportInventoryFormspecModified(const std::string &name); void reportFormspecPrependModified(const std::string &name); @@ -222,21 +228,21 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef void notifyPlayer(const char *name, const std::wstring &msg); void notifyPlayers(const std::wstring &msg); - void spawnParticle(const std::string &playername, const ParticleParameters &p); + void spawnParticle(const std::string &playername, + const ParticleParameters &p); u32 addParticleSpawner(const ParticleSpawnerParameters &p, - ServerActiveObject *attached, const std::string &playername); + ServerActiveObject *attached, const std::string &playername); void deleteParticleSpawner(const std::string &playername, u32 id); bool dynamicAddMedia(const std::string &filepath); ServerInventoryManager *getInventoryMgr() const { return m_inventory_mgr.get(); } - void sendDetachedInventory( - Inventory *inventory, const std::string &name, session_t peer_id); + void sendDetachedInventory(Inventory *inventory, const std::string &name, session_t peer_id); // Envlock and conlock should be locked when using scriptapi - ServerScripting *getScriptIface() { return m_script; } + ServerScripting *getScriptIface(){ return m_script; } // actions: time-reversed list // Return value: success/failure @@ -245,35 +251,33 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef // IGameDef interface // Under envlock - virtual IItemDefManager *getItemDefManager(); - virtual const NodeDefManager *getNodeDefManager(); - virtual ICraftDefManager *getCraftDefManager(); + virtual IItemDefManager* getItemDefManager(); + virtual const NodeDefManager* getNodeDefManager(); + virtual ICraftDefManager* getCraftDefManager(); virtual u16 allocateUnknownNodeId(const std::string &name); IRollbackManager *getRollbackManager() { return m_rollback; } virtual EmergeManager *getEmergeManager() { return m_emerge; } - IWritableItemDefManager *getWritableItemDefManager(); - NodeDefManager *getWritableNodeDefManager(); - IWritableCraftDefManager *getWritableCraftDefManager(); + IWritableItemDefManager* getWritableItemDefManager(); + NodeDefManager* getWritableNodeDefManager(); + IWritableCraftDefManager* getWritableCraftDefManager(); virtual const std::vector &getMods() const; - virtual const ModSpec *getModSpec(const std::string &modname) const; + virtual const ModSpec* getModSpec(const std::string &modname) const; void getModNames(std::vector &modlist); std::string getBuiltinLuaPath(); virtual std::string getWorldPath() const { return m_path_world; } virtual std::string getModStoragePath() const; - inline bool isSingleplayer() { return m_simple_singleplayer_mode; } + inline bool isSingleplayer() + { return m_simple_singleplayer_mode; } inline void setAsyncFatalError(const std::string &error) - { - m_async_fatal_error.set(error); - } + { m_async_fatal_error.set(error); } - bool showFormspec(const char *name, const std::string &formspec, - const std::string &formname); - Map &getMap() { return m_env->getMap(); } - ServerEnvironment &getEnv() { return *m_env; } + bool showFormspec(const char *name, const std::string &formspec, const std::string &formname); + Map & getMap() { return m_env->getMap(); } + ServerEnvironment & getEnv() { return *m_env; } v3f findSpawnPos(); u32 hudAdd(RemotePlayer *player, HudElement *element); @@ -286,8 +290,8 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef Address getPeerAddress(session_t peer_id); - void setLocalPlayerAnimations( - RemotePlayer *player, v2s32 animation_frames[4], f32 frame_speed); + void setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4], + f32 frame_speed); void setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third); void setSky(RemotePlayer *player, const SkyboxParams ¶ms); @@ -297,26 +301,24 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef void setClouds(RemotePlayer *player, const CloudParams ¶ms); - void overrideDayNightRatio( - RemotePlayer *player, bool do_override, float brightness); + void overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness); /* con::PeerHandler implementation. */ void peerAdded(con::Peer *peer); void deletingPeer(con::Peer *peer, bool timeout); void DenySudoAccess(session_t peer_id); - void DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, - AccessDeniedCode reason, const std::string &str_reason = "", - bool reconnect = false); + void DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason, + const std::string &str_reason = "", bool reconnect = false); void DenyAccess(session_t peer_id, AccessDeniedCode reason, - const std::string &custom_reason = ""); + const std::string &custom_reason = ""); void acceptAuth(session_t peer_id, bool forSudoMode); void DenyAccess_Legacy(session_t peer_id, const std::wstring &reason); void DisconnectPeer(session_t peer_id); bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval); bool getClientInfo(session_t peer_id, ClientState *state, u32 *uptime, - u8 *ser_vers, u16 *prot_vers, u8 *major, u8 *minor, u8 *patch, - std::string *vers_string, std::string *lang_code); + u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch, + std::string* vers_string, std::string* lang_code); void printToConsoleOnly(const std::string &text); @@ -334,8 +336,7 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef bool joinModChannel(const std::string &channel); bool leaveModChannel(const std::string &channel); - bool sendModChannelMessage( - const std::string &channel, const std::string &message); + bool sendModChannelMessage(const std::string &channel, const std::string &message); ModChannel *getModChannel(const std::string &channel); // Send block to specific player only @@ -355,23 +356,20 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef friend class RemoteClient; friend class TestServerShutdownState; - struct ShutdownState - { + struct ShutdownState { friend class TestServerShutdownState; - - public: - bool is_requested = false; - bool should_reconnect = false; - std::string message; - - void reset(); - void trigger(float delay, const std::string &msg, bool reconnect); - void tick(float dtime, Server *server); - std::wstring getShutdownTimerMessage() const; - bool isTimerRunning() const { return m_timer > 0.0f; } - - private: - float m_timer = 0.0f; + public: + bool is_requested = false; + bool should_reconnect = false; + std::string message; + + void reset(); + void trigger(float delay, const std::string &msg, bool reconnect); + void tick(float dtime, Server *server); + std::wstring getShutdownTimerMessage() const; + bool isTimerRunning() const { return m_timer > 0.0f; } + private: + float m_timer = 0.0f; }; void init(); @@ -380,30 +378,30 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef void SendHP(session_t peer_id, u16 hp); void SendBreath(session_t peer_id, u16 breath); void SendAccessDenied(session_t peer_id, AccessDeniedCode reason, - const std::string &custom_reason, bool reconnect = false); + const std::string &custom_reason, bool reconnect = false); void SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason); void SendDeathscreen(session_t peer_id, bool set_camera_point_target, - v3f camera_point_target); - void SendItemDef(session_t peer_id, IItemDefManager *itemdef, - u16 protocol_version); + v3f camera_point_target); + void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version); void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef, - u16 protocol_version); + u16 protocol_version); /* mark blocks not sent for all clients */ - void SetBlocksNotSent(std::map &block); + void SetBlocksNotSent(std::map& block); + virtual void SendChatMessage(session_t peer_id, const ChatMessage &message); void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed); void SendPlayerHP(session_t peer_id); void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4], - f32 animation_speed); + f32 animation_speed); void SendEyeOffset(session_t peer_id, v3f first, v3f third); void SendPlayerPrivileges(session_t peer_id); void SendPlayerInventoryFormspec(session_t peer_id); void SendPlayerFormspecPrepend(session_t peer_id); void SendShowFormspecMessage(session_t peer_id, const std::string &formspec, - const std::string &formname); + const std::string &formname); void SendHUDAdd(session_t peer_id, u32 id, HudElement *form); void SendHUDRemove(session_t peer_id, u32 id); void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value); @@ -430,12 +428,11 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef std::unordered_set *far_players = nullptr, float far_d_nodes = 100, bool remove_metadata = true); - void sendMetadataChanged( - const std::list &meta_updates, float far_d_nodes = 100); + void sendMetadataChanged(const std::list &meta_updates, + float far_d_nodes = 100); // Environment and Connection must be locked when called - void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, - u16 net_proto_version); + void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version); // Sends blocks to clients (locks env and con on its own) void SendBlocks(float dtime); @@ -444,22 +441,22 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef std::string *filedata = nullptr, std::string *digest = nullptr); void fillMediaCache(); void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code); - void sendRequestedMedia( - session_t peer_id, const std::vector &tosend); + void sendRequestedMedia(session_t peer_id, + const std::vector &tosend); // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all) void SendAddParticleSpawner(session_t peer_id, u16 protocol_version, - const ParticleSpawnerParameters &p, u16 attached_id, u32 id); + const ParticleSpawnerParameters &p, u16 attached_id, u32 id); void SendDeleteParticleSpawner(session_t peer_id, u32 id); // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all) void SendSpawnParticle(session_t peer_id, u16 protocol_version, - const ParticleParameters &p); + const ParticleParameters &p); void SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersao); void SendActiveObjectMessages(session_t peer_id, const std::string &datas, - bool reliable = true); + bool reliable = true); void SendCSMRestrictionFlags(session_t peer_id); /* @@ -470,20 +467,20 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef void RespawnPlayer(session_t peer_id); void DeleteClient(session_t peer_id, ClientDeletionReason reason); void UpdateCrafting(RemotePlayer *player); - bool checkInteractDistance( - RemotePlayer *player, const f32 d, const std::string &what); + bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what); void handleChatInterfaceEvent(ChatEvent *evt); // This returns the answer to the sender of wmessage, or "" if there is none std::wstring handleChat(const std::string &name, const std::wstring &wname, - std::wstring wmessage_input, bool check_shout_priv = false, - RemotePlayer *player = NULL); + std::wstring wmessage_input, + bool check_shout_priv = false, + RemotePlayer *player = NULL); void handleAdminChat(const ChatEventChat *evt); // When called, connection mutex should be locked - RemoteClient *getClient(session_t peer_id, ClientState state_min = CS_Active); - RemoteClient *getClientNoEx(session_t peer_id, ClientState state_min = CS_Active); + RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active); + RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active); // When called, environment mutex should be locked std::string getPlayerName(session_t peer_id); @@ -577,7 +574,7 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef float m_time_of_day_send_timer = 0.0f; /* - Client interface + Client interface */ ClientInterface m_clients; @@ -612,7 +609,7 @@ class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef Queue of map edits from the environment for sending to the clients This is behind m_env_mutex */ - std::queue m_unsent_map_edit_queue; + std::queue m_unsent_map_edit_queue; /* If a non-empty area, map edit events contained within are left unsent. Done at map generation time to speed up editing of the diff --git a/src/server/luaentity_sao.cpp b/src/server/luaentity_sao.cpp index d04516414..d504c42ca 100644 --- a/src/server/luaentity_sao.cpp +++ b/src/server/luaentity_sao.cpp @@ -26,8 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "serverenvironment.h" -LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &data) : - UnitSAO(env, pos) +LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &data) + : UnitSAO(env, pos) { std::string name; std::string state; @@ -37,9 +37,8 @@ LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &d while (!data.empty()) { // breakable, run for one iteration std::istringstream is(data, std::ios::binary); - // 'version' does not allow to incrementally extend the parameter list - // thus we need another variable to build on top of 'version=1'. Ugly hack - // but works™ + // 'version' does not allow to incrementally extend the parameter list thus + // we need another variable to build on top of 'version=1'. Ugly hack but works™ u8 version2 = 0; u8 version = readU8(is); @@ -70,8 +69,8 @@ LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &d break; } // create object - infostream << "LuaEntitySAO::create(name=\"" << name << "\" state=\"" << state - << "\")" << std::endl; + infostream << "LuaEntitySAO::create(name=\"" << name << "\" state=\"" + << state << "\")" << std::endl; m_init_name = name; m_init_state = state; @@ -82,7 +81,7 @@ LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &d LuaEntitySAO::~LuaEntitySAO() { - if (m_registered) { + if(m_registered){ m_env->getScriptIface()->luaentity_Remove(m_id); } @@ -96,15 +95,18 @@ void LuaEntitySAO::addedToEnvironment(u32 dtime_s) ServerActiveObject::addedToEnvironment(dtime_s); // Create entity from name - m_registered = m_env->getScriptIface()->luaentity_Add(m_id, m_init_name.c_str()); + m_registered = m_env->getScriptIface()-> + luaentity_Add(m_id, m_init_name.c_str()); - if (m_registered) { + if(m_registered){ // Get properties - m_env->getScriptIface()->luaentity_GetProperties(m_id, this, &m_prop); + m_env->getScriptIface()-> + luaentity_GetProperties(m_id, this, &m_prop); // Initialize HP from properties m_hp = m_prop.hp_max; // Activate entity, supplying serialized state - m_env->getScriptIface()->luaentity_Activate(m_id, m_init_state, dtime_s); + m_env->getScriptIface()-> + luaentity_Activate(m_id, m_init_state, dtime_s); } else { m_prop.infotext = m_init_name; } @@ -112,7 +114,8 @@ void LuaEntitySAO::addedToEnvironment(u32 dtime_s) void LuaEntitySAO::step(float dtime, bool send_recommended) { - if (!m_properties_sent) { + if(!m_properties_sent) + { m_properties_sent = true; std::string str = getPropertyPacket(); // create message and add to list @@ -122,9 +125,8 @@ void LuaEntitySAO::step(float dtime, bool send_recommended) // If attached, check that our parent is still there. If it isn't, detach. if (m_attachment_parent_id && !isAttached()) { // This is handled when objects are removed from the map - warningstream << "LuaEntitySAO::step() id=" << m_id - << " is attached to nonexistent parent. This is a bug." - << std::endl; + warningstream << "LuaEntitySAO::step() id=" << m_id << + " is attached to nonexistent parent. This is a bug." << std::endl; clearParentAttachment(); sendPosition(false, true); } @@ -133,28 +135,29 @@ void LuaEntitySAO::step(float dtime, bool send_recommended) collisionMoveResult moveresult, *moveresult_p = nullptr; - // Each frame, parent position is copied if the object is attached, otherwise it's - // calculated normally If the object gets detached this comes into effect - // automatically from the last known origin - if (isAttached()) { - v3f pos = m_env->getActiveObject(m_attachment_parent_id) - ->getBasePosition(); + // Each frame, parent position is copied if the object is attached, otherwise it's calculated normally + // If the object gets detached this comes into effect automatically from the last known origin + if(isAttached()) + { + v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition(); m_base_position = pos; - m_velocity = v3f(0, 0, 0); - m_acceleration = v3f(0, 0, 0); - } else { - if (m_prop.physical) { + m_velocity = v3f(0,0,0); + m_acceleration = v3f(0,0,0); + } + else + { + if(m_prop.physical){ aabb3f box = m_prop.collisionbox; box.MinEdge *= BS; box.MaxEdge *= BS; - f32 pos_max_d = BS * 0.25; // Distance per iteration + f32 pos_max_d = BS*0.25; // Distance per iteration v3f p_pos = m_base_position; v3f p_velocity = m_velocity; v3f p_acceleration = m_acceleration; moveresult = collisionMoveSimple(m_env, m_env->getGameDef(), - pos_max_d, box, m_prop.stepheight, dtime, &p_pos, - &p_velocity, p_acceleration, this, - m_prop.collideWithObjects); + pos_max_d, box, m_prop.stepheight, dtime, + &p_pos, &p_velocity, p_acceleration, + this, m_prop.collideWithObjects); moveresult_p = &moveresult; // Apply results @@ -162,24 +165,22 @@ void LuaEntitySAO::step(float dtime, bool send_recommended) m_velocity = p_velocity; m_acceleration = p_acceleration; } else { - m_base_position += dtime * m_velocity + - 0.5 * dtime * dtime * m_acceleration; + m_base_position += dtime * m_velocity + 0.5 * dtime + * dtime * m_acceleration; m_velocity += dtime * m_acceleration; } if (m_prop.automatic_face_movement_dir && - (fabs(m_velocity.Z) > 0.001 || - fabs(m_velocity.X) > 0.001)) { - float target_yaw = - atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI + - m_prop.automatic_face_movement_dir_offset; + (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) { + float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI + + m_prop.automatic_face_movement_dir_offset; float max_rotation_per_sec = m_prop.automatic_face_movement_max_rotation_per_sec; if (max_rotation_per_sec > 0) { m_rotation.Y = wrapDegrees_0_360(m_rotation.Y); wrappedApproachShortest(m_rotation.Y, target_yaw, - dtime * max_rotation_per_sec, 360.f); + dtime * max_rotation_per_sec, 360.f); } else { // Negative values of max_rotation_per_sec mean disabled. m_rotation.Y = target_yaw; @@ -187,20 +188,21 @@ void LuaEntitySAO::step(float dtime, bool send_recommended) } } - if (m_registered) { + if(m_registered) { m_env->getScriptIface()->luaentity_Step(m_id, dtime, moveresult_p); } if (!send_recommended) return; - if (!isAttached()) { + if(!isAttached()) + { // TODO: force send when acceleration changes enough? - float minchange = 0.2 * BS; - if (m_last_sent_position_timer > 1.0) { - minchange = 0.01 * BS; - } else if (m_last_sent_position_timer > 0.2) { - minchange = 0.05 * BS; + float minchange = 0.2*BS; + if(m_last_sent_position_timer > 1.0){ + minchange = 0.01*BS; + } else if(m_last_sent_position_timer > 0.2){ + minchange = 0.05*BS; } float move_d = m_base_position.getDistanceFrom(m_last_sent_position); move_d += m_last_sent_move_precision; @@ -222,22 +224,21 @@ std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version) std::ostringstream os(std::ios::binary); // PROTOCOL_VERSION >= 37 - writeU8(os, 1); // version + writeU8(os, 1); // version os << serializeString(""); // name - writeU8(os, 0); // is_player - writeU16(os, getId()); // id + writeU8(os, 0); // is_player + writeU16(os, getId()); //id writeV3F32(os, m_base_position); writeV3F32(os, m_rotation); writeU16(os, m_hp); std::ostringstream msg_os(std::ios::binary); - msg_os << serializeLongString(getPropertyPacket()); // message 1 + msg_os << serializeLongString(getPropertyPacket()); // message 1 msg_os << serializeLongString(generateUpdateArmorGroupsCommand()); // 2 - msg_os << serializeLongString(generateUpdateAnimationCommand()); // 3 + msg_os << serializeLongString(generateUpdateAnimationCommand()); // 3 for (const auto &bone_pos : m_bone_position) { msg_os << serializeLongString(generateUpdateBonePositionCommand( - bone_pos.first, bone_pos.second.X, - bone_pos.second.Y)); // m_bone_position.size + bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // m_bone_position.size } msg_os << serializeLongString(generateUpdateAttachmentCommand()); // 4 @@ -247,7 +248,7 @@ std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version) if (ServerActiveObject *obj = m_env->getActiveObject(id)) { message_count++; msg_os << serializeLongString(obj->generateUpdateInfantCommand( - id, protocol_version)); + id, protocol_version)); } } @@ -264,19 +265,19 @@ std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version) void LuaEntitySAO::getStaticData(std::string *result) const { - verbosestream << FUNCTION_NAME << std::endl; + verbosestream<getScriptIface()->luaentity_GetStaticdata(m_id); - os << serializeLongString(state); + if(m_registered){ + std::string state = m_env->getScriptIface()-> + luaentity_GetStaticdata(m_id); + os<getWieldedItem(&selected_item, &hand_item); PunchDamageResult result = getPunchDamage( - m_armor_groups, toolcap, &tool_item, time_from_last_punch); + m_armor_groups, + toolcap, + &tool_item, + time_from_last_punch); bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher, - time_from_last_punch, toolcap, dir, - result.did_punch ? result.damage : 0); + time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0); if (!damage_handled) { if (result.did_punch) { setHP((s32)getHP() - result.damage, - PlayerHPChangeReason(PlayerHPChangeReason:: - PLAYER_PUNCH, - puncher)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher)); // create message and add to list sendPunchCommand(); @@ -335,11 +338,11 @@ u16 LuaEntitySAO::punch(v3f dir, const ToolCapabilities *toolcap, m_pending_removal = true; } - actionstream << puncher->getDescription() << " (id=" << puncher->getId() - << ", hp=" << puncher->getHP() << ") punched " << getDescription() - << " (id=" << m_id << ", hp=" << m_hp - << "), damage=" << (old_hp - (s32)getHP()) - << (damage_handled ? " (handled by Lua)" : "") << std::endl; + actionstream << puncher->getDescription() << " (id=" << puncher->getId() << + ", hp=" << puncher->getHP() << ") punched " << + getDescription() << " (id=" << m_id << ", hp=" << m_hp << + "), damage=" << (old_hp - (s32)getHP()) << + (damage_handled ? " (handled by Lua)" : "") << std::endl; // TODO: give Lua control over wear return result.wear; @@ -355,7 +358,7 @@ void LuaEntitySAO::rightClick(ServerActiveObject *clicker) void LuaEntitySAO::setPos(const v3f &pos) { - if (isAttached()) + if(isAttached()) return; m_base_position = pos; sendPosition(false, true); @@ -363,10 +366,10 @@ void LuaEntitySAO::setPos(const v3f &pos) void LuaEntitySAO::moveTo(v3f pos, bool continuous) { - if (isAttached()) + if(isAttached()) return; m_base_position = pos; - if (!continuous) + if(!continuous) sendPosition(true, true); } @@ -426,6 +429,7 @@ std::string LuaEntitySAO::getTextureMod() const return m_current_texture_modifier; } + std::string LuaEntitySAO::generateSetTextureModCommand() const { std::ostringstream os(std::ios::binary); @@ -436,8 +440,8 @@ std::string LuaEntitySAO::generateSetTextureModCommand() const return os.str(); } -std::string LuaEntitySAO::generateSetSpriteCommand( - v2s16 p, u16 num_frames, f32 framelength, bool select_horiz_by_yawpitch) +std::string LuaEntitySAO::generateSetSpriteCommand(v2s16 p, u16 num_frames, + f32 framelength, bool select_horiz_by_yawpitch) { std::ostringstream os(std::ios::binary); // command @@ -450,11 +454,15 @@ std::string LuaEntitySAO::generateSetSpriteCommand( return os.str(); } -void LuaEntitySAO::setSprite( - v2s16 p, int num_frames, float framelength, bool select_horiz_by_yawpitch) +void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength, + bool select_horiz_by_yawpitch) { std::string str = generateSetSpriteCommand( - p, num_frames, framelength, select_horiz_by_yawpitch); + p, + num_frames, + framelength, + select_horiz_by_yawpitch + ); // create message and add to list m_messages_out.emplace(getId(), true, str); } @@ -471,32 +479,38 @@ std::string LuaEntitySAO::getPropertyPacket() void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end) { - // If the object is attached client-side, don't waste bandwidth sending its - // position to clients - if (isAttached()) + // If the object is attached client-side, don't waste bandwidth sending its position to clients + if(isAttached()) return; - m_last_sent_move_precision = - m_base_position.getDistanceFrom(m_last_sent_position); + m_last_sent_move_precision = m_base_position.getDistanceFrom( + m_last_sent_position); m_last_sent_position_timer = 0; m_last_sent_position = m_base_position; m_last_sent_velocity = m_velocity; - // m_last_sent_acceleration = m_acceleration; + //m_last_sent_acceleration = m_acceleration; m_last_sent_rotation = m_rotation; float update_interval = m_env->getSendRecommendedInterval(); - std::string str = generateUpdatePositionCommand(m_base_position, m_velocity, - m_acceleration, m_rotation, do_interpolate, is_movement_end, - update_interval); + std::string str = generateUpdatePositionCommand( + m_base_position, + m_velocity, + m_acceleration, + m_rotation, + do_interpolate, + is_movement_end, + update_interval + ); // create message and add to list m_messages_out.emplace(getId(), false, str); } bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const { - if (m_prop.physical) { - // update collision box + if (m_prop.physical) + { + //update collision box toset->MinEdge = m_prop.collisionbox.MinEdge * BS; toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS; diff --git a/src/server/player_sao.cpp b/src/server/player_sao.cpp index 1aa1a3f9b..3d9f08bfa 100644 --- a/src/server/player_sao.cpp +++ b/src/server/player_sao.cpp @@ -26,9 +26,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverenvironment.h" PlayerSAO::PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, session_t peer_id_, - bool is_singleplayer) : - UnitSAO(env_, v3f(0, 0, 0)), - m_player(player_), m_peer_id(peer_id_), m_is_singleplayer(is_singleplayer) + bool is_singleplayer): + UnitSAO(env_, v3f(0,0,0)), + m_player(player_), + m_peer_id(peer_id_), + m_is_singleplayer(is_singleplayer) { SANITY_CHECK(m_peer_id != PEER_ID_INEXISTENT); @@ -46,7 +48,7 @@ PlayerSAO::PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, session_t p m_prop.textures.emplace_back("player_back.png"); m_prop.colors.clear(); m_prop.colors.emplace_back(255, 255, 255, 255); - m_prop.spritediv = v2s16(1, 1); + m_prop.spritediv = v2s16(1,1); m_prop.eye_height = 1.625f; // End of default appearance m_prop.is_visible = true; @@ -106,24 +108,23 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version) std::ostringstream os(std::ios::binary); // Protocol >= 15 - writeU8(os, 1); // version + writeU8(os, 1); // version os << serializeString(m_player->getName()); // name - writeU8(os, 1); // is_player - writeS16(os, getId()); // id + writeU8(os, 1); // is_player + writeS16(os, getId()); // id writeV3F32(os, m_base_position); writeV3F32(os, m_rotation); writeU16(os, getHP()); std::ostringstream msg_os(std::ios::binary); - msg_os << serializeLongString(getPropertyPacket()); // message 1 + msg_os << serializeLongString(getPropertyPacket()); // message 1 msg_os << serializeLongString(generateUpdateArmorGroupsCommand()); // 2 - msg_os << serializeLongString(generateUpdateAnimationCommand()); // 3 + msg_os << serializeLongString(generateUpdateAnimationCommand()); // 3 for (const auto &bone_pos : m_bone_position) { msg_os << serializeLongString(generateUpdateBonePositionCommand( - bone_pos.first, bone_pos.second.X, - bone_pos.second.Y)); // m_bone_position.size + bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // m_bone_position.size } - msg_os << serializeLongString(generateUpdateAttachmentCommand()); // 4 + msg_os << serializeLongString(generateUpdateAttachmentCommand()); // 4 msg_os << serializeLongString(generateUpdatePhysicsOverrideCommand()); // 5 int message_count = 5 + m_bone_position.size(); @@ -132,7 +133,7 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version) if (ServerActiveObject *obj = m_env->getActiveObject(id)) { message_count++; msg_os << serializeLongString(obj->generateUpdateInfantCommand( - id, protocol_version)); + id, protocol_version)); } } @@ -144,7 +145,7 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version) return os.str(); } -void PlayerSAO::getStaticData(std::string *result) const +void PlayerSAO::getStaticData(std::string * result) const { FATAL_ERROR("Obsolete function"); } @@ -163,8 +164,7 @@ void PlayerSAO::step(float dtime, bool send_recommended) // No more breath, damage player if (m_breath == 0) { - PlayerHPChangeReason reason( - PlayerHPChangeReason::DROWNING); + PlayerHPChangeReason reason(PlayerHPChangeReason::DROWNING); setHP(m_hp - c.drowning, reason); m_env->getGameDef()->SendPlayerHPOrDie(this, reason); } @@ -176,8 +176,7 @@ void PlayerSAO::step(float dtime, bool send_recommended) v3s16 p = floatToInt(getEyePosition(), BS); MapNode n = m_env->getMap().getNode(p); const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n); - // If player is alive & not drowning & not in ignore & not immortal, - // breathe + // If player is alive & not drowning & not in ignore & not immortal, breathe if (m_breath < m_prop.breath_max && c.drowning == 0 && n.getContent() != CONTENT_IGNORE && m_hp > 0) setBreath(m_breath + 1); @@ -192,9 +191,8 @@ void PlayerSAO::step(float dtime, bool send_recommended) // Sequence of damage points, starting 0.1 above feet and progressing // upwards in 1 node intervals, stopping below top damage point. for (float dam_height = 0.1f; dam_height < dam_top; dam_height++) { - v3s16 p = floatToInt(m_base_position + v3f(0.0f, dam_height * BS, - 0.0f), - BS); + v3s16 p = floatToInt(m_base_position + + v3f(0.0f, dam_height * BS, 0.0f), BS); MapNode n = m_env->getMap().getNode(p); const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n); if (c.damage_per_second > damage_per_second) { @@ -204,8 +202,8 @@ void PlayerSAO::step(float dtime, bool send_recommended) } // Top damage point - v3s16 ptop = floatToInt( - m_base_position + v3f(0.0f, dam_top * BS, 0.0f), BS); + v3s16 ptop = floatToInt(m_base_position + + v3f(0.0f, dam_top * BS, 0.0f), BS); MapNode ntop = m_env->getMap().getNode(ptop); const ContentFeatures &c = m_env->getGameDef()->ndef()->get(ntop); if (c.damage_per_second > damage_per_second) { @@ -215,8 +213,7 @@ void PlayerSAO::step(float dtime, bool send_recommended) if (damage_per_second != 0 && m_hp > 0) { s32 newhp = (s32)m_hp - (s32)damage_per_second; - PlayerHPChangeReason reason( - PlayerHPChangeReason::NODE_DAMAGE, nodename); + PlayerHPChangeReason reason(PlayerHPChangeReason::NODE_DAMAGE, nodename); setHP(newhp, reason); m_env->getGameDef()->SendPlayerHPOrDie(this, reason); } @@ -233,20 +230,19 @@ void PlayerSAO::step(float dtime, bool send_recommended) // If attached, check that our parent is still there. If it isn't, detach. if (m_attachment_parent_id && !isAttached()) { // This is handled when objects are removed from the map - warningstream << "PlayerSAO::step() id=" << m_id - << " is attached to nonexistent parent. This is a bug." - << std::endl; + warningstream << "PlayerSAO::step() id=" << m_id << + " is attached to nonexistent parent. This is a bug." << std::endl; clearParentAttachment(); setBasePosition(m_last_good_position); m_env->getGameDef()->SendMovePlayer(m_peer_id); } - // dstream<<"PlayerSAO::step: dtime: "<getMaxLagEstimate() * 2.0f; - if (lag_pool_max < LAG_POOL_MIN) + if(lag_pool_max < LAG_POOL_MIN) lag_pool_max = LAG_POOL_MIN; m_dig_pool.setMax(lag_pool_max); m_move_pool.setMax(lag_pool_max); @@ -264,8 +260,7 @@ void PlayerSAO::step(float dtime, bool send_recommended) // If the object gets detached this comes into effect automatically from // the last known origin. if (isAttached()) { - v3f pos = m_env->getActiveObject(m_attachment_parent_id) - ->getBasePosition(); + v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition(); m_last_good_position = pos; setBasePosition(pos); } @@ -284,9 +279,15 @@ void PlayerSAO::step(float dtime, bool send_recommended) else pos = m_base_position; - std::string str = generateUpdatePositionCommand(pos, - v3f(0.0f, 0.0f, 0.0f), v3f(0.0f, 0.0f, 0.0f), m_rotation, - true, false, update_interval); + std::string str = generateUpdatePositionCommand( + pos, + v3f(0.0f, 0.0f, 0.0f), + v3f(0.0f, 0.0f, 0.0f), + m_rotation, + true, + false, + update_interval + ); // create message and add to list m_messages_out.emplace(getId(), false, str); } @@ -294,8 +295,7 @@ void PlayerSAO::step(float dtime, bool send_recommended) if (!m_physics_override_sent) { m_physics_override_sent = true; // create message and add to list - m_messages_out.emplace( - getId(), true, generateUpdatePhysicsOverrideCommand()); + m_messages_out.emplace(getId(), true, generateUpdatePhysicsOverrideCommand()); } sendOutdatedData(); @@ -333,12 +333,11 @@ void PlayerSAO::setBasePosition(const v3f &position) void PlayerSAO::setPos(const v3f &pos) { - if (isAttached()) + if(isAttached()) return; // Send mapblock of target location - v3s16 blockpos = v3s16(pos.X / MAP_BLOCKSIZE, pos.Y / MAP_BLOCKSIZE, - pos.Z / MAP_BLOCKSIZE); + v3s16 blockpos = v3s16(pos.X / MAP_BLOCKSIZE, pos.Y / MAP_BLOCKSIZE, pos.Z / MAP_BLOCKSIZE); m_env->getGameDef()->SendBlock(m_peer_id, blockpos); setBasePosition(pos); @@ -351,7 +350,7 @@ void PlayerSAO::setPos(const v3f &pos) void PlayerSAO::moveTo(v3f pos, bool continuous) { - if (isAttached()) + if(isAttached()) return; setBasePosition(pos); @@ -408,8 +407,10 @@ void PlayerSAO::setLookPitchAndSend(const float pitch) m_env->getGameDef()->SendMovePlayer(m_peer_id); } -u16 PlayerSAO::punch(v3f dir, const ToolCapabilities *toolcap, - ServerActiveObject *puncher, float time_from_last_punch) +u16 PlayerSAO::punch(v3f dir, + const ToolCapabilities *toolcap, + ServerActiveObject *puncher, + float time_from_last_punch) { if (!toolcap) return 0; @@ -426,17 +427,18 @@ u16 PlayerSAO::punch(v3f dir, const ToolCapabilities *toolcap, } s32 old_hp = getHP(); - HitParams hitparams = getHitParams(m_armor_groups, toolcap, time_from_last_punch); + HitParams hitparams = getHitParams(m_armor_groups, toolcap, + time_from_last_punch); PlayerSAO *playersao = m_player->getPlayerSAO(); - bool damage_handled = m_env->getScriptIface()->on_punchplayer(playersao, puncher, - time_from_last_punch, toolcap, dir, hitparams.hp); + bool damage_handled = m_env->getScriptIface()->on_punchplayer(playersao, + puncher, time_from_last_punch, toolcap, dir, + hitparams.hp); if (!damage_handled) { setHP((s32)getHP() - (s32)hitparams.hp, - PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, - puncher)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher)); } else { // override client prediction if (puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) { // create message and add to list @@ -444,11 +446,11 @@ u16 PlayerSAO::punch(v3f dir, const ToolCapabilities *toolcap, } } - actionstream << puncher->getDescription() << " (id=" << puncher->getId() - << ", hp=" << puncher->getHP() << ") punched " << getDescription() - << " (id=" << m_id << ", hp=" << m_hp - << "), damage=" << (old_hp - (s32)getHP()) - << (damage_handled ? " (handled by Lua)" : "") << std::endl; + actionstream << puncher->getDescription() << " (id=" << puncher->getId() << + ", hp=" << puncher->getHP() << ") punched " << + getDescription() << " (id=" << m_id << ", hp=" << m_hp << + "), damage=" << (old_hp - (s32)getHP()) << + (damage_handled ? " (handled by Lua)" : "") << std::endl; return hitparams.wear; } @@ -457,11 +459,10 @@ void PlayerSAO::setHP(s32 hp, const PlayerHPChangeReason &reason) { s32 oldhp = m_hp; - // hp = rangelim(hp, 0, m_prop.hp_max); + //hp = rangelim(hp, 0, m_prop.hp_max); if (oldhp != hp) { - s32 hp_change = m_env->getScriptIface()->on_player_hpchange( - this, hp - oldhp, reason); + s32 hp_change = m_env->getScriptIface()->on_player_hpchange(this, hp - oldhp, reason); if (hp_change == 0) return; @@ -576,8 +577,7 @@ bool PlayerSAO::checkMovementCheat() float override_max_H, override_max_V; if (m_max_speed_override_time > 0.0f) { - override_max_H = MYMAX(fabs(m_max_speed_override.X), - fabs(m_max_speed_override.Z)); + override_max_H = MYMAX(fabs(m_max_speed_override.X), fabs(m_max_speed_override.Z)); override_max_V = fabs(m_max_speed_override.Y); } else { override_max_H = override_max_V = 0.0f; @@ -627,9 +627,8 @@ bool PlayerSAO::checkMovementCheat() lag_pool_max = MYMAX(lag_pool_max, LAG_POOL_MIN); if (m_time_from_last_teleport > lag_pool_max) { actionstream << "Server: " << m_player->getName() - << " moved too fast: V=" << d_vert - << ", H=" << d_horiz << "; resetting position." - << std::endl; + << " moved too fast: V=" << d_vert << ", H=" << d_horiz + << "; resetting position." << std::endl; cheated = true; } setBasePosition(m_last_good_position); @@ -639,7 +638,7 @@ bool PlayerSAO::checkMovementCheat() bool PlayerSAO::getCollisionBox(aabb3f *toset) const { - // update collision box + //update collision box toset->MinEdge = m_prop.collisionbox.MinEdge * BS; toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS; diff --git a/src/server/serveractiveobject.cpp b/src/server/serveractiveobject.cpp index 3acf4cece..3341dc008 100644 --- a/src/server/serveractiveobject.cpp +++ b/src/server/serveractiveobject.cpp @@ -23,14 +23,16 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "constants.h" // BS #include "log.h" -ServerActiveObject::ServerActiveObject(ServerEnvironment *env, v3f pos) : - ActiveObject(0), m_env(env), m_base_position(pos) +ServerActiveObject::ServerActiveObject(ServerEnvironment *env, v3f pos): + ActiveObject(0), + m_env(env), + m_base_position(pos) { } float ServerActiveObject::getMinimumSavedMovement() { - return 2.0 * BS; + return 2.0*BS; } ItemStack ServerActiveObject::getWieldedItem(ItemStack *selected, ItemStack *hand) const @@ -47,8 +49,7 @@ bool ServerActiveObject::setWieldedItem(const ItemStack &item) return false; } -std::string ServerActiveObject::generateUpdateInfantCommand( - u16 infant_id, u16 protocol_version) +std::string ServerActiveObject::generateUpdateInfantCommand(u16 infant_id, u16 protocol_version) { std::ostringstream os(std::ios::binary); // command diff --git a/src/server/serveractiveobject.h b/src/server/serveractiveobject.h index 7af1c24c4..927009aef 100644 --- a/src/server/serveractiveobject.h +++ b/src/server/serveractiveobject.h @@ -58,7 +58,8 @@ class ServerActiveObject : public ActiveObject ServerActiveObject(ServerEnvironment *env, v3f pos); virtual ~ServerActiveObject() = default; - virtual ActiveObjectType getSendType() const { return getType(); } + virtual ActiveObjectType getSendType() const + { return getType(); } // Called after id has been set and has been inserted in environment virtual void addedToEnvironment(u32 dtime_s){}; @@ -66,31 +67,35 @@ class ServerActiveObject : public ActiveObject virtual void removingFromEnvironment(){}; // Returns true if object's deletion is the job of the // environment - virtual bool environmentDeletes() const { return true; } + virtual bool environmentDeletes() const + { return true; } // Create a certain type of ServerActiveObject - static ServerActiveObject *create(ActiveObjectType type, ServerEnvironment *env, - u16 id, v3f pos, const std::string &data); + static ServerActiveObject* create(ActiveObjectType type, + ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); /* Some simple getters/setters */ v3f getBasePosition() const { return m_base_position; } - void setBasePosition(v3f pos) { m_base_position = pos; } - ServerEnvironment *getEnv() { return m_env; } + void setBasePosition(v3f pos){ m_base_position = pos; } + ServerEnvironment* getEnv(){ return m_env; } /* Some more dynamic interface */ - virtual void setPos(const v3f &pos) { setBasePosition(pos); } + virtual void setPos(const v3f &pos) + { setBasePosition(pos); } // continuous: if true, object does not stop immediately at pos - virtual void moveTo(v3f pos, bool continuous) { setBasePosition(pos); } + virtual void moveTo(v3f pos, bool continuous) + { setBasePosition(pos); } // If object has moved less than this and data has not changed, // saving to disk may be omitted virtual float getMinimumSavedMovement(); - virtual std::string getDescription() { return "SAO"; } + virtual std::string getDescription(){return "SAO";} /* Step object in time. @@ -102,16 +107,13 @@ class ServerActiveObject : public ActiveObject same time so that the data can be combined in a single packet. */ - virtual void step(float dtime, bool send_recommended) {} + virtual void step(float dtime, bool send_recommended){} /* The return value of this is passed to the client-side object when it is created */ - virtual std::string getClientInitializationData(u16 protocol_version) - { - return ""; - } + virtual std::string getClientInitializationData(u16 protocol_version) {return "";} /* The return value of this is passed to the server-side object @@ -127,65 +129,59 @@ class ServerActiveObject : public ActiveObject Return false in here to never save and instead remove object on unload. getStaticData() will not be called in that case. */ - virtual bool isStaticAllowed() const { return true; } + virtual bool isStaticAllowed() const + {return true;} // Returns tool wear - virtual u16 punch(v3f dir, const ToolCapabilities *toolcap = nullptr, + virtual u16 punch(v3f dir, + const ToolCapabilities *toolcap = nullptr, ServerActiveObject *puncher = nullptr, float time_from_last_punch = 1000000.0f) - { - return 0; - } - virtual void rightClick(ServerActiveObject *clicker) {} - virtual void setHP(s32 hp, const PlayerHPChangeReason &reason) {} - virtual u16 getHP() const { return 0; } - - virtual void setArmorGroups(const ItemGroupList &armor_groups) {} + { return 0; } + virtual void rightClick(ServerActiveObject *clicker) + {} + virtual void setHP(s32 hp, const PlayerHPChangeReason &reason) + {} + virtual u16 getHP() const + { return 0; } + + virtual void setArmorGroups(const ItemGroupList &armor_groups) + {} virtual const ItemGroupList &getArmorGroups() const - { - static ItemGroupList rv; - return rv; - } - virtual void setPhysicsOverride(float physics_override_speed, - float physics_override_jump, float physics_override_gravity) - { - } - virtual void setAnimation( - v2f frames, float frame_speed, float frame_blend, bool frame_loop) - { - } - virtual void getAnimation(v2f *frames, float *frame_speed, float *frame_blend, - bool *frame_loop) - { - } - virtual void setAnimationSpeed(float frame_speed) {} + { static ItemGroupList rv; return rv; } + virtual void setPhysicsOverride(float physics_override_speed, float physics_override_jump, float physics_override_gravity) + {} + virtual void setAnimation(v2f frames, float frame_speed, float frame_blend, bool frame_loop) + {} + virtual void getAnimation(v2f *frames, float *frame_speed, float *frame_blend, bool *frame_loop) + {} + virtual void setAnimationSpeed(float frame_speed) + {} virtual void setBonePosition(const std::string &bone, v3f position, v3f rotation) - { - } - virtual void getBonePosition( - const std::string &bone, v3f *position, v3f *lotation) - { - } + {} + virtual void getBonePosition(const std::string &bone, v3f *position, v3f *lotation) + {} virtual const std::unordered_set &getAttachmentChildIds() const - { - static std::unordered_set rv; - return rv; - } + { static std::unordered_set rv; return rv; } virtual ServerActiveObject *getParent() const { return nullptr; } - virtual ObjectProperties *accessObjectProperties() { return NULL; } - virtual void notifyObjectPropertiesModified() {} + virtual ObjectProperties* accessObjectProperties() + { return NULL; } + virtual void notifyObjectPropertiesModified() + {} // Inventory and wielded item - virtual Inventory *getInventory() const { return NULL; } + virtual Inventory *getInventory() const + { return NULL; } virtual InventoryLocation getInventoryLocation() const - { - return InventoryLocation(); - } - virtual void setInventoryModified() {} - virtual std::string getWieldList() const { return ""; } - virtual u16 getWieldIndex() const { return 0; } - virtual ItemStack getWieldedItem( - ItemStack *selected, ItemStack *hand = nullptr) const; + { return InventoryLocation(); } + virtual void setInventoryModified() + {} + virtual std::string getWieldList() const + { return ""; } + virtual u16 getWieldIndex() const + { return 0; } + virtual ItemStack getWieldedItem(ItemStack *selected, + ItemStack *hand = nullptr) const; virtual bool setWieldedItem(const ItemStack &item); inline void attachParticleSpawner(u32 id) { @@ -197,8 +193,7 @@ class ServerActiveObject : public ActiveObject } std::string generateUpdateInfantCommand(u16 infant_id, u16 protocol_version); - std::string generateUpdateNametagAttributesCommand( - const video::SColor &color) const; + std::string generateUpdateNametagAttributesCommand(const video::SColor &color) const; void dumpAOMessagesToQueue(std::queue &queue); @@ -232,7 +227,8 @@ class ServerActiveObject : public ActiveObject A getter that unifies the above to answer the question: "Can the environment still interact with this object?" */ - inline bool isGone() const { return m_pending_removal || m_pending_deactivation; } + inline bool isGone() const + { return m_pending_removal || m_pending_deactivation; } /* Whether the object's static data has been stored to a block @@ -242,7 +238,7 @@ class ServerActiveObject : public ActiveObject The block from which the object was loaded from, and in which a copy of the static data resides. */ - v3s16 m_static_block = v3s16(1337, 1337, 1337); + v3s16 m_static_block = v3s16(1337,1337,1337); protected: virtual void onAttach(int parent_id) {} diff --git a/src/serverenvironment.cpp b/src/serverenvironment.cpp index dbbfd2c63..ad2ffc9a4 100644 --- a/src/serverenvironment.cpp +++ b/src/serverenvironment.cpp @@ -52,21 +52,21 @@ with this program; if not, write to the Free Software Foundation, Inc., #define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:" -// A number that is much smaller than the timeout for particle spawners should/could ever -// be +// A number that is much smaller than the timeout for particle spawners should/could ever be #define PARTICLE_SPAWNER_NO_EXPIRY -1024.f /* ABMWithState */ -ABMWithState::ABMWithState(ActiveBlockModifier *abm_) : abm(abm_) +ABMWithState::ABMWithState(ActiveBlockModifier *abm_): + abm(abm_) { // Initialize timer to random value to spread processing float itv = abm->getTriggerInterval(); - itv = MYMAX(0.001, itv); // No less than 1ms - int minval = MYMAX(-0.51 * itv, -60); // Clamp to - int maxval = MYMIN(0.51 * itv, 60); // +-60 seconds + itv = MYMAX(0.001, itv); // No less than 1ms + int minval = MYMAX(-0.51*itv, -60); // Clamp to + int maxval = MYMIN(0.51*itv, 60); // +-60 seconds timer = myrand_range(minval, maxval); } @@ -89,16 +89,15 @@ void LBMContentMapping::addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamed lbm_list.push_back(lbm_def); - for (const std::string &nodeTrigger : lbm_def->trigger_contents) { + for (const std::string &nodeTrigger: lbm_def->trigger_contents) { std::vector c_ids; bool found = nodedef->getIds(nodeTrigger, c_ids); if (!found) { content_t c_id = gamedef->allocateUnknownNodeId(nodeTrigger); if (c_id == CONTENT_IGNORE) { // Seems it can't be allocated. - warningstream << "Could not internalize node name \"" - << nodeTrigger << "\" while loading LBM \"" - << lbm_def->name << "\"." << std::endl; + warningstream << "Could not internalize node name \"" << nodeTrigger + << "\" while loading LBM \"" << lbm_def->name << "\"." << std::endl; continue; } c_ids.push_back(c_id); @@ -110,7 +109,8 @@ void LBMContentMapping::addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamed } } -const std::vector *LBMContentMapping::lookup(content_t c) const +const std::vector * +LBMContentMapping::lookup(content_t c) const { lbm_map::const_iterator it = map.find(c); if (it == map.end()) @@ -135,19 +135,20 @@ LBMManager::~LBMManager() void LBMManager::addLBMDef(LoadingBlockModifierDef *lbm_def) { // Precondition, in query mode the map isn't used anymore - FATAL_ERROR_IF(m_query_mode, "attempted to modify LBMManager in query mode"); + FATAL_ERROR_IF(m_query_mode, + "attempted to modify LBMManager in query mode"); if (!string_allowed(lbm_def->name, LBM_NAME_ALLOWED_CHARS)) { throw ModError("Error adding LBM \"" + lbm_def->name + - "\": Does not follow naming conventions: " + "\": Does not follow naming conventions: " "Only characters [a-z0-9_:] are allowed."); } m_lbm_defs[lbm_def->name] = lbm_def; } -void LBMManager::loadIntroductionTimes( - const std::string ×, IGameDef *gamedef, u32 now) +void LBMManager::loadIntroductionTimes(const std::string ×, + IGameDef *gamedef, u32 now) { m_query_mode = true; @@ -169,8 +170,8 @@ void LBMManager::loadIntroductionTimes( std::string entry = times.substr(idx, idx_new - idx); std::vector components = str_split(entry, '~'); if (components.size() != 2) - throw SerializationError("Introduction times entry \"" + entry + - "\" requires exactly one '~'!"); + throw SerializationError("Introduction times entry \"" + + entry + "\" requires exactly one '~'!"); const std::string &name = components[0]; u32 time = from_string(components[1]); introduction_times[name] = time; @@ -179,12 +180,12 @@ void LBMManager::loadIntroductionTimes( // Put stuff from introduction_times into m_lbm_lookup for (std::map::const_iterator it = introduction_times.begin(); - it != introduction_times.end(); ++it) { + it != introduction_times.end(); ++it) { const std::string &name = it->first; u32 time = it->second; std::map::iterator def_it = - m_lbm_defs.find(name); + m_lbm_defs.find(name); if (def_it == m_lbm_defs.end()) { // This seems to be an LBM entry for // an LBM we haven't loaded. Discard it. @@ -230,13 +231,12 @@ std::string LBMManager::createIntroductionTimesString() { // Precondition, we must be in query mode FATAL_ERROR_IF(!m_query_mode, - "attempted to query on non fully set up LBMManager"); + "attempted to query on non fully set up LBMManager"); std::ostringstream oss; for (const auto &it : m_lbm_lookup) { u32 time = it.first; - const std::vector &lbm_list = - it.second.lbm_list; + const std::vector &lbm_list = it.second.lbm_list; for (const auto &lbm_def : lbm_list) { // Don't add if the LBM runs at every load, // then introducement time is hardcoded @@ -253,15 +253,15 @@ void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp) { // Precondition, we need m_lbm_lookup to be initialized FATAL_ERROR_IF(!m_query_mode, - "attempted to query on non fully set up LBMManager"); + "attempted to query on non fully set up LBMManager"); v3s16 pos_of_block = block->getPosRelative(); v3s16 pos; MapNode n; content_t c; lbm_lookup_map::const_iterator it = getLBMsIntroducedAfter(stamp); for (; it != m_lbm_lookup.end(); ++it) { - // Cache previous version to speedup lookup which has a very high - // performance penalty on each call + // Cache previous version to speedup lookup which has a very high performance + // penalty on each call content_t previous_c{}; std::vector *lbm_list = nullptr; @@ -271,22 +271,17 @@ void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp) n = block->getNodeNoEx(pos); c = n.getContent(); - // If content_t are not matching perform an LBM - // lookup + // If content_t are not matching perform an LBM lookup if (previous_c != c) { - lbm_list = (std::vector< - LoadingBlockModifierDef *> - *)it - ->second - .lookup(c); + lbm_list = (std::vector *) + it->second.lookup(c); previous_c = c; } if (!lbm_list) continue; for (auto lbmdef : *lbm_list) { - lbmdef->trigger(env, pos + pos_of_block, - n); + lbmdef->trigger(env, pos + pos_of_block, n); } } } @@ -299,9 +294,10 @@ void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp) void fillRadiusBlock(v3s16 p0, s16 r, std::set &list) { v3s16 p; - for (p.X = p0.X - r; p.X <= p0.X + r; p.X++) - for (p.Y = p0.Y - r; p.Y <= p0.Y + r; p.Y++) - for (p.Z = p0.Z - r; p.Z <= p0.Z + r; p.Z++) { + for(p.X=p0.X-r; p.X<=p0.X+r; p.X++) + for(p.Y=p0.Y-r; p.Y<=p0.Y+r; p.Y++) + for(p.Z=p0.Z-r; p.Z<=p0.Z+r; p.Z++) + { // limit to a sphere if (p.getDistanceFrom(p0) <= r) { // Set in list @@ -310,24 +306,29 @@ void fillRadiusBlock(v3s16 p0, s16 r, std::set &list) } } -void fillViewConeBlock(v3s16 p0, const s16 r, const v3f camera_pos, const v3f camera_dir, - const float camera_fov, std::set &list) +void fillViewConeBlock(v3s16 p0, + const s16 r, + const v3f camera_pos, + const v3f camera_dir, + const float camera_fov, + std::set &list) { v3s16 p; const s16 r_nodes = r * BS * MAP_BLOCKSIZE; - for (p.X = p0.X - r; p.X <= p0.X + r; p.X++) - for (p.Y = p0.Y - r; p.Y <= p0.Y + r; p.Y++) - for (p.Z = p0.Z - r; p.Z <= p0.Z + r; p.Z++) { - if (isBlockInSight(p, camera_pos, camera_dir, camera_fov, - r_nodes)) { - list.insert(p); - } - } + for (p.X = p0.X - r; p.X <= p0.X+r; p.X++) + for (p.Y = p0.Y - r; p.Y <= p0.Y+r; p.Y++) + for (p.Z = p0.Z - r; p.Z <= p0.Z+r; p.Z++) { + if (isBlockInSight(p, camera_pos, camera_dir, camera_fov, r_nodes)) { + list.insert(p); + } + } } -void ActiveBlockList::update(std::vector &active_players, - s16 active_block_range, s16 active_object_range, - std::set &blocks_removed, std::set &blocks_added) +void ActiveBlockList::update(std::vector &active_players, + s16 active_block_range, + s16 active_object_range, + std::set &blocks_removed, + std::set &blocks_added) { /* Create the new list @@ -339,16 +340,18 @@ void ActiveBlockList::update(std::vector &active_players, fillRadiusBlock(pos, active_block_range, m_abm_list); fillRadiusBlock(pos, active_block_range, newlist); - s16 player_ao_range = std::min( - active_object_range, playersao->getWantedRange()); + s16 player_ao_range = std::min(active_object_range, playersao->getWantedRange()); // only do this if this would add blocks if (player_ao_range > active_block_range) { - v3f camera_dir = v3f(0, 0, 1); + v3f camera_dir = v3f(0,0,1); camera_dir.rotateYZBy(playersao->getLookPitch()); camera_dir.rotateXZBy(playersao->getRotation().Y); - fillViewConeBlock(pos, player_ao_range, - playersao->getEyePosition(), camera_dir, - playersao->getFov(), newlist); + fillViewConeBlock(pos, + player_ao_range, + playersao->getEyePosition(), + camera_dir, + playersao->getFov(), + newlist); } } @@ -368,7 +371,7 @@ void ActiveBlockList::update(std::vector &active_players, // Go through new list for (v3s16 p : newlist) { // If not on old list, it's been added - if (m_list.find(p) == m_list.end()) + if(m_list.find(p) == m_list.end()) blocks_added.insert(p); } @@ -388,11 +391,15 @@ void ActiveBlockList::update(std::vector &active_players, // Random device to seed pseudo random generators. static std::random_device seed; -ServerEnvironment::ServerEnvironment(ServerMap *map, ServerScripting *scriptIface, - Server *server, const std::string &path_world) : - Environment(server), - m_map(map), m_script(scriptIface), m_server(server), - m_path_world(path_world), m_rgen(seed()) +ServerEnvironment::ServerEnvironment(ServerMap *map, + ServerScripting *scriptIface, Server *server, + const std::string &path_world): + Environment(server), + m_map(map), + m_script(scriptIface), + m_server(server), + m_path_world(path_world), + m_rgen(seed()) { // Determine which database backend to use std::string conf_path = path_world + DIR_DELIM + "world.mt"; @@ -417,7 +424,7 @@ ServerEnvironment::ServerEnvironment(ServerMap *map, ServerScripting *scriptIfac if (!conf.updateConfigFile(conf_path.c_str())) { errorstream << "ServerEnvironment::ServerEnvironment(): " - << "Failed to update world.mt!" << std::endl; + << "Failed to update world.mt!" << std::endl; } } else { conf.getNoEx("player_backend", player_backend_name); @@ -430,7 +437,7 @@ ServerEnvironment::ServerEnvironment(ServerMap *map, ServerScripting *scriptIfac if (!conf.updateConfigFile(conf_path.c_str())) { errorstream << "ServerEnvironment::ServerEnvironment(): " - << "Failed to update world.mt!" << std::endl; + << "Failed to update world.mt!" << std::endl; } } else { conf.getNoEx("auth_backend", auth_backend_name); @@ -439,22 +446,16 @@ ServerEnvironment::ServerEnvironment(ServerMap *map, ServerScripting *scriptIfac if (player_backend_name == "files") { warningstream << "/!\\ You are using old player file backend. " - << "This backend is deprecated and will be removed in a " - "future release /!\\" - << std::endl - << "Switching to SQLite3 or PostgreSQL is advised, " - << "please read http://wiki.minetest.net/Database_backends." - << std::endl; + << "This backend is deprecated and will be removed in a future release /!\\" + << std::endl << "Switching to SQLite3 or PostgreSQL is advised, " + << "please read http://wiki.minetest.net/Database_backends." << std::endl; } if (auth_backend_name == "files") { warningstream << "/!\\ You are using old auth file backend. " - << "This backend is deprecated and will be removed in a " - "future release /!\\" - << std::endl - << "Switching to SQLite3 is advised, " - << "please read http://wiki.minetest.net/Database_backends." - << std::endl; + << "This backend is deprecated and will be removed in a future release /!\\" + << std::endl << "Switching to SQLite3 is advised, " + << "please read http://wiki.minetest.net/Database_backends." << std::endl; } m_player_database = openPlayerDatabase(player_backend_name, path_world, conf); @@ -487,12 +488,12 @@ ServerEnvironment::~ServerEnvironment() delete m_auth_database; } -Map &ServerEnvironment::getMap() +Map & ServerEnvironment::getMap() { return *m_map; } -ServerMap &ServerEnvironment::getServerMap() +ServerMap & ServerEnvironment::getServerMap() { return *m_map; } @@ -506,7 +507,7 @@ RemotePlayer *ServerEnvironment::getPlayer(const session_t peer_id) return NULL; } -RemotePlayer *ServerEnvironment::getPlayer(const char *name) +RemotePlayer *ServerEnvironment::getPlayer(const char* name) { for (RemotePlayer *player : m_players) { if (strcmp(player->getName(), name) == 0) @@ -524,8 +525,7 @@ void ServerEnvironment::addPlayer(RemotePlayer *player) */ // If peer id is non-zero, it has to be unique. if (player->getPeerId() != PEER_ID_INEXISTENT) - FATAL_ERROR_IF(getPlayer(player->getPeerId()) != NULL, - "Peer id not unique"); + FATAL_ERROR_IF(getPlayer(player->getPeerId()) != NULL, "Peer id not unique"); // Name has to be unique. FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique"); // Add. @@ -535,7 +535,7 @@ void ServerEnvironment::addPlayer(RemotePlayer *player) void ServerEnvironment::removePlayer(RemotePlayer *player) { for (std::vector::iterator it = m_players.begin(); - it != m_players.end(); ++it) { + it != m_players.end(); ++it) { if ((*it) == player) { delete *it; m_players.erase(it); @@ -549,29 +549,25 @@ bool ServerEnvironment::removePlayerFromDatabase(const std::string &name) return m_player_database->removePlayer(name); } -void ServerEnvironment::kickAllPlayers( - AccessDeniedCode reason, const std::string &str_reason, bool reconnect) +void ServerEnvironment::kickAllPlayers(AccessDeniedCode reason, + const std::string &str_reason, bool reconnect) { for (RemotePlayer *player : m_players) { m_server->DenyAccessVerCompliant(player->getPeerId(), - player->protocol_version, reason, str_reason, reconnect); + player->protocol_version, reason, str_reason, reconnect); } } void ServerEnvironment::saveLoadedPlayers(bool force) { for (RemotePlayer *player : m_players) { - if (force || player->checkModified() || - (player->getPlayerSAO() && - player->getPlayerSAO() - ->getMeta() - .isModified())) { + if (force || player->checkModified() || (player->getPlayerSAO() && + player->getPlayerSAO()->getMeta().isModified())) { try { m_player_database->savePlayer(player); } catch (DatabaseException &e) { - errorstream << "Failed to save player " - << player->getName() - << " exception: " << e.what() << std::endl; + errorstream << "Failed to save player " << player->getName() << " exception: " + << e.what() << std::endl; throw; } } @@ -583,14 +579,14 @@ void ServerEnvironment::savePlayer(RemotePlayer *player) try { m_player_database->savePlayer(player); } catch (DatabaseException &e) { - errorstream << "Failed to save player " << player->getName() - << " exception: " << e.what() << std::endl; + errorstream << "Failed to save player " << player->getName() << " exception: " + << e.what() << std::endl; throw; } } PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player, - session_t peer_id, bool is_singleplayer) + session_t peer_id, bool is_singleplayer) { PlayerSAO *playersao = new PlayerSAO(this, player, peer_id, is_singleplayer); // Create player if it doesn't exist @@ -598,7 +594,7 @@ PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player, *new_player = true; // Set player position infostream << "Server: Finding spawn place for player \"" - << player->getName() << "\"" << std::endl; + << player->getName() << "\"" << std::endl; playersao->setBasePosition(m_server->findSpawnPos()); // Make sure the player is saved @@ -609,8 +605,7 @@ PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player, // to the environment if (objectpos_over_limit(playersao->getBasePosition())) { actionstream << "Respawn position for player \"" - << player->getName() - << "\" outside limits, resetting" << std::endl; + << player->getName() << "\" outside limits, resetting" << std::endl; playersao->setBasePosition(m_server->findSpawnPos()); } } @@ -642,14 +637,16 @@ void ServerEnvironment::saveMeta() args.setU64("time_of_day", getTimeOfDay()); args.setU64("last_clear_objects_time", m_last_clear_objects_time); args.setU64("lbm_introduction_times_version", 1); - args.set("lbm_introduction_times", m_lbm_mgr.createIntroductionTimesString()); + args.set("lbm_introduction_times", + m_lbm_mgr.createIntroductionTimesString()); args.setU64("day_count", m_day_count); args.writeLines(ss); - ss << "EnvArgsEnd\n"; + ss<<"EnvArgsEnd\n"; - if (!fs::safeWriteToFile(path, ss.str())) { - infostream << "ServerEnvironment::saveMeta(): Failed to write " << path - << std::endl; + if(!fs::safeWriteToFile(path, ss.str())) + { + infostream<<"ServerEnvironment::saveMeta(): Failed to write " + < *> m_aabms; - public: - ABMHandler(std::vector &abms, float dtime_s, ServerEnvironment *env, - bool use_timers) : - m_env(env) + ABMHandler(std::vector &abms, + float dtime_s, ServerEnvironment *env, + bool use_timers): + m_env(env) { - if (dtime_s < 0.001) + if(dtime_s < 0.001) return; const NodeDefManager *ndef = env->getGameDef()->ndef(); for (ABMWithState &abmws : abms) { ActiveBlockModifier *abm = abmws.abm; float trigger_interval = abm->getTriggerInterval(); - if (trigger_interval < 0.001) + if(trigger_interval < 0.001) trigger_interval = 0.001; float actual_interval = dtime_s; - if (use_timers) { + if(use_timers){ abmws.timer += dtime_s; - if (abmws.timer < trigger_interval) + if(abmws.timer < trigger_interval) continue; abmws.timer -= trigger_interval; actual_interval = trigger_interval; } float chance = abm->getTriggerChance(); - if (chance == 0) + if(chance == 0) chance = 1; ActiveABM aabm; aabm.abm = abm; if (abm->getSimpleCatchUp()) { float intervals = actual_interval / trigger_interval; - if (intervals == 0) + if(intervals == 0) continue; aabm.chance = chance / intervals; - if (aabm.chance == 0) + if(aabm.chance == 0) aabm.chance = 1; } else { aabm.chance = chance; @@ -783,17 +777,14 @@ class ABMHandler // Trigger neighbors const std::vector &required_neighbors_s = - abm->getRequiredNeighbors(); - for (const std::string &required_neighbor_s : - required_neighbors_s) { - ndef->getIds(required_neighbor_s, - aabm.required_neighbors); + abm->getRequiredNeighbors(); + for (const std::string &required_neighbor_s : required_neighbors_s) { + ndef->getIds(required_neighbor_s, aabm.required_neighbors); } aabm.check_required_neighbors = !required_neighbors_s.empty(); // Trigger contents - const std::vector &contents_s = - abm->getTriggerContents(); + const std::vector &contents_s = abm->getTriggerContents(); for (const std::string &content_s : contents_s) { std::vector ids; ndef->getIds(content_s, ids); @@ -818,33 +809,33 @@ class ABMHandler // Returns the number of objects in the block, and also in 'wider' the // number of objects in the block and all its neighbours. The latter // may an estimate if any neighbours are unloaded. - u32 countObjects(MapBlock *block, ServerMap *map, u32 &wider) + u32 countObjects(MapBlock *block, ServerMap * map, u32 &wider) { wider = 0; u32 wider_unknown_count = 0; - for (s16 x = -1; x <= 1; x++) - for (s16 y = -1; y <= 1; y++) - for (s16 z = -1; z <= 1; z++) { + for(s16 x=-1; x<=1; x++) + for(s16 y=-1; y<=1; y++) + for(s16 z=-1; z<=1; z++) + { MapBlock *block2 = map->getBlockNoCreateNoEx( - block->getPos() + v3s16(x, y, z)); - if (block2 == NULL) { + block->getPos() + v3s16(x,y,z)); + if(block2==NULL){ wider_unknown_count++; continue; } - wider += block2->m_static_objects.m_active - .size() + - block2->m_static_objects.m_stored.size(); + wider += block2->m_static_objects.m_active.size() + + block2->m_static_objects.m_stored.size(); } // Extrapolate u32 active_object_count = block->m_static_objects.m_active.size(); - u32 wider_known_count = 3 * 3 * 3 - wider_unknown_count; + u32 wider_known_count = 3*3*3 - wider_unknown_count; wider += wider_unknown_count * wider / wider_known_count; return active_object_count; + } - void apply(MapBlock *block, int &blocks_scanned, int &abms_run, - int &blocks_cached) + void apply(MapBlock *block, int &blocks_scanned, int &abms_run, int &blocks_cached) { - if (m_aabms.empty() || block->isDummy()) + if(m_aabms.empty() || block->isDummy()) return; // Check the content type cache first @@ -870,95 +861,75 @@ class ABMHandler ServerMap *map = &m_env->getServerMap(); u32 active_object_count_wider; - u32 active_object_count = - this->countObjects(block, map, active_object_count_wider); + u32 active_object_count = this->countObjects(block, map, active_object_count_wider); m_env->m_added_objects = 0; v3s16 p0; - for (p0.X = 0; p0.X < MAP_BLOCKSIZE; p0.X++) - for (p0.Y = 0; p0.Y < MAP_BLOCKSIZE; p0.Y++) - for (p0.Z = 0; p0.Z < MAP_BLOCKSIZE; p0.Z++) { - const MapNode &n = block->getNodeUnsafe(p0); - content_t c = n.getContent(); - // Cache content types as we go - if (!block->contents_cached && - !block->do_not_cache_contents) { - block->contents.insert(c); - if (block->contents.size() > 64) { - // Too many different nodes... - // don't try to cache - block->do_not_cache_contents = - true; - block->contents.clear(); - } - } + for(p0.X=0; p0.XgetNodeUnsafe(p0); + content_t c = n.getContent(); + // Cache content types as we go + if (!block->contents_cached && !block->do_not_cache_contents) { + block->contents.insert(c); + if (block->contents.size() > 64) { + // Too many different nodes... don't try to cache + block->do_not_cache_contents = true; + block->contents.clear(); + } + } - if (c >= m_aabms.size() || !m_aabms[c]) - continue; + if (c >= m_aabms.size() || !m_aabms[c]) + continue; - v3s16 p = p0 + block->getPosRelative(); - for (ActiveABM &aabm : *m_aabms[c]) { - if (myrand() % aabm.chance != 0) - continue; + v3s16 p = p0 + block->getPosRelative(); + for (ActiveABM &aabm : *m_aabms[c]) { + if (myrand() % aabm.chance != 0) + continue; - // Check neighbors - if (aabm.check_required_neighbors) { - v3s16 p1; - for (p1.X = p0.X - 1; - p1.X <= p0.X + 1; - p1.X++) - for (p1.Y = p0.Y - 1; - p1.Y <= - p0.Y + 1; - p1.Y++) - for (p1.Z = p0.Z - - 1; - p1.Z <= - p0.Z + 1; - p1.Z++) { - if (p1 == p0) - continue; - content_t c; - if (block->isValidPosition( - p1)) { - // if the neighbor is found on the same map block - // get it straight from there - const MapNode &n = block->getNodeUnsafe( - p1); - c = n.getContent(); - } else { - // otherwise consult the map - MapNode n = map->getNode( - p1 + - block->getPosRelative()); - c = n.getContent(); - } - if (CONTAINS(aabm.required_neighbors, - c)) - goto neighbor_found; - } - // No required neighbor found + // Check neighbors + if (aabm.check_required_neighbors) { + v3s16 p1; + for(p1.X = p0.X-1; p1.X <= p0.X+1; p1.X++) + for(p1.Y = p0.Y-1; p1.Y <= p0.Y+1; p1.Y++) + for(p1.Z = p0.Z-1; p1.Z <= p0.Z+1; p1.Z++) + { + if(p1 == p0) continue; + content_t c; + if (block->isValidPosition(p1)) { + // if the neighbor is found on the same map block + // get it straight from there + const MapNode &n = block->getNodeUnsafe(p1); + c = n.getContent(); + } else { + // otherwise consult the map + MapNode n = map->getNode(p1 + block->getPosRelative()); + c = n.getContent(); } - neighbor_found: - - abms_run++; - // Call all the trigger variations - aabm.abm->trigger(m_env, p, n); - aabm.abm->trigger(m_env, p, n, - active_object_count, - active_object_count_wider); - - // Count surrounding objects again if the - // abms added any - if (m_env->m_added_objects > 0) { - active_object_count = countObjects( - block, map, - active_object_count_wider); - m_env->m_added_objects = 0; - } + if (CONTAINS(aabm.required_neighbors, c)) + goto neighbor_found; } + // No required neighbor found + continue; } + neighbor_found: + + abms_run++; + // Call all the trigger variations + aabm.abm->trigger(m_env, p, n); + aabm.abm->trigger(m_env, p, n, + active_object_count, active_object_count_wider); + + // Count surrounding objects again if the abms added any + if(m_env->m_added_objects > 0) { + active_object_count = countObjects(block, map, active_object_count_wider); + m_env->m_added_objects = 0; + } + } + } block->contents_cached = !block->do_not_cache_contents; } }; @@ -1002,7 +973,8 @@ void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime) m_lbm_mgr.applyLBMs(this, block, stamp); // Run node timers - std::vector elapsed_timers = block->m_node_timers.step((float)dtime_s); + std::vector elapsed_timers = + block->m_node_timers.step((float)dtime_s); if (!elapsed_timers.empty()) { MapNode n; for (const NodeTimer &elapsed_timer : elapsed_timers) { @@ -1010,7 +982,7 @@ void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime) v3s16 p = elapsed_timer.position + block->getPosRelative(); if (m_script->node_on_timer(p, n, elapsed_timer.elapsed)) block->setNodeTimer(NodeTimer(elapsed_timer.timeout, 0, - elapsed_timer.position)); + elapsed_timer.position)); } } } @@ -1097,8 +1069,8 @@ bool ServerEnvironment::swapNode(v3s16 p, const MapNode &n) void ServerEnvironment::clearObjects(ClearObjectsMode mode) { infostream << "ServerEnvironment::clearObjects(): " - << "Removing all active objects" << std::endl; - auto cb_removal = [this](ServerActiveObject *obj, u16 id) { + << "Removing all active objects" << std::endl; + auto cb_removal = [this] (ServerActiveObject *obj, u16 id) { if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER) return false; @@ -1128,28 +1100,28 @@ void ServerEnvironment::clearObjects(ClearObjectsMode mode) // Get list of loaded blocks std::vector loaded_blocks; infostream << "ServerEnvironment::clearObjects(): " - << "Listing all loaded blocks" << std::endl; + << "Listing all loaded blocks" << std::endl; m_map->listAllLoadedBlocks(loaded_blocks); infostream << "ServerEnvironment::clearObjects(): " - << "Done listing all loaded blocks: " << loaded_blocks.size() - << std::endl; + << "Done listing all loaded blocks: " + << loaded_blocks.size()< loadable_blocks; if (mode == CLEAR_OBJECTS_MODE_FULL) { infostream << "ServerEnvironment::clearObjects(): " - << "Listing all loadable blocks" << std::endl; + << "Listing all loadable blocks" << std::endl; m_map->listAllLoadableBlocks(loadable_blocks); infostream << "ServerEnvironment::clearObjects(): " - << "Done listing all loadable blocks: " - << loadable_blocks.size() << std::endl; + << "Done listing all loadable blocks: " + << loadable_blocks.size() << std::endl; } else { loadable_blocks = loaded_blocks; } actionstream << "ServerEnvironment::clearObjects(): " - << "Now clearing objects in " << loadable_blocks.size() << " blocks" - << std::endl; + << "Now clearing objects in " << loadable_blocks.size() + << " blocks" << std::endl; // Grab a reference on each loaded block to avoid unloading it for (v3s16 p : loaded_blocks) { @@ -1161,20 +1133,20 @@ void ServerEnvironment::clearObjects(ClearObjectsMode mode) // Remove objects in all loadable blocks u32 unload_interval = U32_MAX; if (mode == CLEAR_OBJECTS_MODE_FULL) { - unload_interval = g_settings->getS32( - "max_clearobjects_extra_loaded_blocks"); + unload_interval = g_settings->getS32("max_clearobjects_extra_loaded_blocks"); unload_interval = MYMAX(unload_interval, 1); } u32 report_interval = loadable_blocks.size() / 10; u32 num_blocks_checked = 0; u32 num_blocks_cleared = 0; u32 num_objs_cleared = 0; - for (auto i = loadable_blocks.begin(); i != loadable_blocks.end(); ++i) { + for (auto i = loadable_blocks.begin(); + i != loadable_blocks.end(); ++i) { v3s16 p = *i; MapBlock *block = m_map->emergeBlock(p, false); if (!block) { errorstream << "ServerEnvironment::clearObjects(): " - << "Failed to emerge block " << PP(p) << std::endl; + << "Failed to emerge block " << PP(p) << std::endl; continue; } u32 num_stored = block->m_static_objects.m_stored.size(); @@ -1183,19 +1155,20 @@ void ServerEnvironment::clearObjects(ClearObjectsMode mode) block->m_static_objects.m_stored.clear(); block->m_static_objects.m_active.clear(); block->raiseModified(MOD_STATE_WRITE_NEEDED, - MOD_REASON_CLEAR_ALL_OBJECTS); + MOD_REASON_CLEAR_ALL_OBJECTS); num_objs_cleared += num_stored + num_active; num_blocks_cleared++; } num_blocks_checked++; - if (report_interval != 0 && num_blocks_checked % report_interval == 0) { + if (report_interval != 0 && + num_blocks_checked % report_interval == 0) { float percent = 100.0 * (float)num_blocks_checked / - loadable_blocks.size(); + loadable_blocks.size(); actionstream << "ServerEnvironment::clearObjects(): " - << "Cleared " << num_objs_cleared << " objects" - << " in " << num_blocks_cleared << " blocks (" - << percent << "%)" << std::endl; + << "Cleared " << num_objs_cleared << " objects" + << " in " << num_blocks_cleared << " blocks (" + << percent << "%)" << std::endl; } if (num_blocks_checked % unload_interval == 0) { m_map->unloadUnreferencedBlocks(); @@ -1213,8 +1186,8 @@ void ServerEnvironment::clearObjects(ClearObjectsMode mode) m_last_clear_objects_time = m_game_time; actionstream << "ServerEnvironment::clearObjects(): " - << "Finished: Cleared " << num_objs_cleared << " objects" - << " in " << num_blocks_cleared << " blocks" << std::endl; + << "Finished: Cleared " << num_objs_cleared << " objects" + << " in " << num_blocks_cleared << " blocks" << std::endl; } void ServerEnvironment::step(float dtime) @@ -1258,14 +1231,13 @@ void ServerEnvironment::step(float dtime) /* Manage active block list */ - if (m_active_blocks_management_interval.step( - dtime, m_cache_active_block_mgmt_interval)) { + if (m_active_blocks_management_interval.step(dtime, m_cache_active_block_mgmt_interval)) { ScopeProfiler sp(g_profiler, "ServerEnv: update active blocks", SPT_AVG); /* Get player block positions */ - std::vector players; - for (RemotePlayer *player : m_players) { + std::vector players; + for (RemotePlayer *player: m_players) { // Ignore disconnected players if (player->getPeerId() == PEER_ID_INEXISTENT) continue; @@ -1288,7 +1260,7 @@ void ServerEnvironment::step(float dtime) std::set blocks_removed; std::set blocks_added; m_active_blocks.update(players, active_block_range, active_object_range, - blocks_removed, blocks_added); + blocks_removed, blocks_added); /* Handle removed blocks @@ -1297,7 +1269,7 @@ void ServerEnvironment::step(float dtime) // Convert active objects that are no more in active blocks to static deactivateFarObjects(false); - for (const v3s16 &p : blocks_removed) { + for (const v3s16 &p: blocks_removed) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); if (!block) continue; @@ -1310,7 +1282,7 @@ void ServerEnvironment::step(float dtime) Handle added blocks */ - for (const v3s16 &p : blocks_added) { + for (const v3s16 &p: blocks_added) { MapBlock *block = m_map->getBlockOrEmerge(p); if (!block) { m_active_blocks.m_list.erase(p); @@ -1325,13 +1297,12 @@ void ServerEnvironment::step(float dtime) /* Mess around in active blocks */ - if (m_active_blocks_nodemetadata_interval.step( - dtime, m_cache_nodetimer_interval)) { + if (m_active_blocks_nodemetadata_interval.step(dtime, m_cache_nodetimer_interval)) { ScopeProfiler sp(g_profiler, "ServerEnv: Run node timers", SPT_AVG); float dtime = m_cache_nodetimer_interval; - for (const v3s16 &p : m_active_blocks.m_list) { + for (const v3s16 &p: m_active_blocks.m_list) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); if (!block) continue; @@ -1343,25 +1314,21 @@ void ServerEnvironment::step(float dtime) block->setTimestampNoChangedFlag(m_game_time); // If time has changed much from the one on disk, // set block to be saved when it is unloaded - if (block->getTimestamp() > block->getDiskTimestamp() + 60) + if(block->getTimestamp() > block->getDiskTimestamp() + 60) block->raiseModified(MOD_STATE_WRITE_AT_UNLOAD, - MOD_REASON_BLOCK_EXPIRED); + MOD_REASON_BLOCK_EXPIRED); // Run node timers - std::vector elapsed_timers = - block->m_node_timers.step(dtime); + std::vector elapsed_timers = block->m_node_timers.step(dtime); if (!elapsed_timers.empty()) { MapNode n; v3s16 p2; - for (const NodeTimer &elapsed_timer : elapsed_timers) { + for (const NodeTimer &elapsed_timer: elapsed_timers) { n = block->getNodeNoEx(elapsed_timer.position); - p2 = elapsed_timer.position + - block->getPosRelative(); - if (m_script->node_on_timer(p2, n, - elapsed_timer.elapsed)) { + p2 = elapsed_timer.position + block->getPosRelative(); + if (m_script->node_on_timer(p2, n, elapsed_timer.elapsed)) { block->setNodeTimer(NodeTimer( - elapsed_timer.timeout, 0, - elapsed_timer.position)); + elapsed_timer.timeout, 0, elapsed_timer.position)); } } } @@ -1369,8 +1336,7 @@ void ServerEnvironment::step(float dtime) } if (m_active_block_modifier_interval.step(dtime, m_cache_abm_interval)) { - ScopeProfiler sp(g_profiler, "SEnv: modify in blocks avg per interval", - SPT_AVG); + ScopeProfiler sp(g_profiler, "SEnv: modify in blocks avg per interval", SPT_AVG); TimeTaker timer("modify in active blocks per interval"); // Initialize handling of ActiveBlockModifiers @@ -1384,8 +1350,7 @@ void ServerEnvironment::step(float dtime) // Shuffle the active blocks so that each block gets an equal chance // of having its ABMs run. - std::copy(m_active_blocks.m_abm_list.begin(), - m_active_blocks.m_abm_list.end(), output.begin()); + std::copy(m_active_blocks.m_abm_list.begin(), m_active_blocks.m_abm_list.end(), output.begin()); std::shuffle(output.begin(), output.end(), m_rgen); int i = 0; @@ -1407,18 +1372,15 @@ void ServerEnvironment::step(float dtime) u32 time_ms = timer.getTimerTime(); if (time_ms > max_time_ms) { - warningstream << "active block modifiers took " << time_ms - << "ms (processed " << i << " of " - << output.size() << " active blocks)" - << std::endl; + warningstream << "active block modifiers took " + << time_ms << "ms (processed " << i << " of " + << output.size() << " active blocks)" << std::endl; break; } } - g_profiler->avg("ServerEnv: active blocks", - m_active_blocks.m_abm_list.size()); + g_profiler->avg("ServerEnv: active blocks", m_active_blocks.m_abm_list.size()); g_profiler->avg("ServerEnv: active blocks cached", blocks_cached); - g_profiler->avg("ServerEnv: active blocks scanned for ABMs", - blocks_scanned); + g_profiler->avg("ServerEnv: active blocks scanned for ABMs", blocks_scanned); g_profiler->avg("ServerEnv: ABMs run", abms_run); timer.stop(true); @@ -1443,7 +1405,7 @@ void ServerEnvironment::step(float dtime) send_recommended = true; } - auto cb_state = [this, dtime, send_recommended](ServerActiveObject *obj) { + auto cb_state = [this, dtime, send_recommended] (ServerActiveObject *obj) { if (obj->isGone()) return; @@ -1466,10 +1428,9 @@ void ServerEnvironment::step(float dtime) Manage particle spawner expiration */ if (m_particle_management_interval.step(dtime, 1.0)) { - for (std::unordered_map::iterator i = - m_particle_spawners.begin(); - i != m_particle_spawners.end();) { - // non expiring spawners + for (std::unordered_map::iterator i = m_particle_spawners.begin(); + i != m_particle_spawners.end(); ) { + //non expiring spawners if (i->second == PARTICLE_SPAWNER_NO_EXPIRY) { ++i; continue; @@ -1540,7 +1501,7 @@ void ServerEnvironment::deleteParticleSpawner(u32 id, bool remove_from_object) u16 ServerEnvironment::addActiveObject(ServerActiveObject *object) { - assert(object); // Pre-condition + assert(object); // Pre-condition m_added_objects++; u16 id = addActiveObjectRaw(object, true, 0); return id; @@ -1551,8 +1512,9 @@ u16 ServerEnvironment::addActiveObject(ServerActiveObject *object) inside a radius around a position */ void ServerEnvironment::getAddedActiveObjects(PlayerSAO *playersao, s16 radius, - s16 player_radius, std::set ¤t_objects, - std::queue &added_objects) + s16 player_radius, + std::set ¤t_objects, + std::queue &added_objects) { f32 radius_f = radius * BS; f32 player_radius_f = player_radius * BS; @@ -1560,8 +1522,8 @@ void ServerEnvironment::getAddedActiveObjects(PlayerSAO *playersao, s16 radius, if (player_radius_f < 0.0f) player_radius_f = 0.0f; - m_ao_manager.getAddedActiveObjectsAroundPos(playersao->getBasePosition(), - radius_f, player_radius_f, current_objects, added_objects); + m_ao_manager.getAddedActiveObjectsAroundPos(playersao->getBasePosition(), radius_f, + player_radius_f, current_objects, added_objects); } /* @@ -1569,8 +1531,9 @@ void ServerEnvironment::getAddedActiveObjects(PlayerSAO *playersao, s16 radius, inside a radius around a position */ void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius, - s16 player_radius, std::set ¤t_objects, - std::queue &removed_objects) + s16 player_radius, + std::set ¤t_objects, + std::queue &removed_objects) { f32 radius_f = radius * BS; f32 player_radius_f = player_radius * BS; @@ -1590,7 +1553,7 @@ void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius if (object == NULL) { infostream << "ServerEnvironment::getRemovedActiveObjects():" - << " object in current_objects is NULL" << std::endl; + << " object in current_objects is NULL" << std::endl; removed_objects.push(id); continue; } @@ -1600,8 +1563,7 @@ void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius continue; } - f32 distance_f = object->getBasePosition().getDistanceFrom( - playersao->getBasePosition()); + f32 distance_f = object->getBasePosition().getDistanceFrom(playersao->getBasePosition()); if (object->getType() == ACTIVEOBJECT_TYPE_PLAYER) { if (distance_f <= player_radius_f || player_radius_f == 0) continue; @@ -1614,7 +1576,7 @@ void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius } void ServerEnvironment::setStaticForActiveObjectsInBlock( - v3s16 blockpos, bool static_exists, v3s16 static_block) + v3s16 blockpos, bool static_exists, v3s16 static_block) { MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos); if (!block) @@ -1626,20 +1588,19 @@ void ServerEnvironment::setStaticForActiveObjectsInBlock( if (!sao) { // If this ever happens, there must be some kind of nasty bug. errorstream << "ServerEnvironment::setStaticForObjectsInBlock(): " - "Object from MapBlock::m_static_objects::m_active " - "not found " - "in m_active_objects"; + "Object from MapBlock::m_static_objects::m_active not found " + "in m_active_objects"; continue; } sao->m_static_exists = static_exists; - sao->m_static_block = static_block; + sao->m_static_block = static_block; } } bool ServerEnvironment::getActiveObjectMessage(ActiveObjectMessage *dest) { - if (m_active_object_messages.empty()) + if(m_active_object_messages.empty()) return false; *dest = std::move(m_active_object_messages.front()); @@ -1648,12 +1609,12 @@ bool ServerEnvironment::getActiveObjectMessage(ActiveObjectMessage *dest) } void ServerEnvironment::getSelectedActiveObjects( - const core::line3d &shootline_on_map, - std::vector &objects) + const core::line3d &shootline_on_map, + std::vector &objects) { std::vector objs; getObjectsInsideRadius(objs, shootline_on_map.start, - shootline_on_map.getLength() + 10.0f, nullptr); + shootline_on_map.getLength() + 10.0f, nullptr); const v3f line_vector = shootline_on_map.getVector(); for (auto obj : objs) { @@ -1665,27 +1626,26 @@ void ServerEnvironment::getSelectedActiveObjects( v3f pos = obj->getBasePosition(); - aabb3f offsetted_box( - selection_box.MinEdge + pos, selection_box.MaxEdge + pos); + aabb3f offsetted_box(selection_box.MinEdge + pos, + selection_box.MaxEdge + pos); v3f current_intersection; v3s16 current_normal; if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector, - ¤t_intersection, ¤t_normal)) { - objects.emplace_back((s16)obj->getId(), current_intersection, - current_normal, - (current_intersection - shootline_on_map.start) - .getLengthSQ()); + ¤t_intersection, ¤t_normal)) { + objects.emplace_back( + (s16) obj->getId(), current_intersection, current_normal, + (current_intersection - shootline_on_map.start).getLengthSQ()); } } } /* - ************ Private methods ************* - */ + ************ Private methods ************* +*/ -u16 ServerEnvironment::addActiveObjectRaw( - ServerActiveObject *object, bool set_changed, u32 dtime_s) +u16 ServerEnvironment::addActiveObjectRaw(ServerActiveObject *object, + bool set_changed, u32 dtime_s) { if (!m_ao_manager.registerObject(object)) { return 0; @@ -1704,20 +1664,19 @@ u16 ServerEnvironment::addActiveObjectRaw( // Add to the block where the object is located in v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS)); MapBlock *block = m_map->emergeBlock(blockpos); - if (block) { + if(block){ block->m_static_objects.m_active[object->getId()] = s_obj; object->m_static_exists = true; object->m_static_block = blockpos; - if (set_changed) + if(set_changed) block->raiseModified(MOD_STATE_WRITE_NEEDED, - MOD_REASON_ADD_ACTIVE_OBJECT_RAW); + MOD_REASON_ADD_ACTIVE_OBJECT_RAW); } else { v3s16 p = floatToInt(objectpos, BS); - errorstream << "ServerEnvironment::addActiveObjectRaw(): " - << "could not emerge block for storing id=" - << object->getId() << " statically (pos=" << PP(p) - << ")" << std::endl; + errorstream<<"ServerEnvironment::addActiveObjectRaw(): " + <<"could not emerge block for storing id="<getId() + <<" statically (pos="<m_static_block) - << std::endl; + warningstream << "ServerEnvironment::removeRemovedObjects(): " + << "id=" << id << " m_static_exists=true but " + << "static data doesn't actually exist in " + << PP(obj->m_static_block) << std::endl; } } else { - infostream << "Failed to emerge block from which an " - "object to " - << "be deactivated was loaded from. id=" << id - << std::endl; + infostream << "Failed to emerge block from which an object to " + << "be deactivated was loaded from. id=" << id << std::endl; } } @@ -1807,46 +1757,45 @@ void ServerEnvironment::removeRemovedObjects() static void print_hexdump(std::ostream &o, const std::string &data) { const int linelength = 16; - for (int l = 0;; l++) { + for(int l=0; ; l++){ int i0 = linelength * l; bool at_end = false; int thislinelength = linelength; - if (i0 + thislinelength > (int)data.size()) { + if(i0 + thislinelength > (int)data.size()){ thislinelength = data.size() - i0; at_end = true; } - for (int di = 0; di < linelength; di++) { + for(int di=0; di= 32) - o << data[i]; + if(data[i] >= 32) + o<getPos()) << " (" - << block->m_static_objects.m_stored.size() << " objects)" - << std::endl; - bool large_amount = (block->m_static_objects.m_stored.size() > - g_settings->getU16("max_objects_per_block")); + verbosestream<<"ServerEnvironment::activateObjects(): " + <<"activating objects of block "<getPos()) + <<" ("<m_static_objects.m_stored.size() + <<" objects)"<m_static_objects.m_stored.size() > g_settings->getU16("max_objects_per_block")); if (large_amount) { - errorstream << "suspiciously large amount of objects detected: " - << block->m_static_objects.m_stored.size() << " in " - << PP(block->getPos()) << "; removing all of them." - << std::endl; + errorstream<<"suspiciously large amount of objects detected: " + <m_static_objects.m_stored.size()<<" in " + <getPos()) + <<"; removing all of them."<m_static_objects.m_stored.clear(); - block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_TOO_MANY_OBJECTS); + block->raiseModified(MOD_STATE_WRITE_NEEDED, + MOD_REASON_TOO_MANY_OBJECTS); return; } @@ -1884,24 +1833,22 @@ void ServerEnvironment::activateObjects(MapBlock *block, u32 dtime_s) std::vector new_stored; for (const StaticObject &s_obj : block->m_static_objects.m_stored) { // Create an active object from the data - ServerActiveObject *obj = createSAO( - (ActiveObjectType)s_obj.type, s_obj.pos, s_obj.data); + ServerActiveObject *obj = createSAO((ActiveObjectType) s_obj.type, s_obj.pos, + s_obj.data); // If couldn't create object, store static data back. if (!obj) { - errorstream << "ServerEnvironment::activateObjects(): " - << "failed to create active object from static " - "object " - << "in block " << PP(s_obj.pos / BS) - << " type=" << (int)s_obj.type - << " data:" << std::endl; + errorstream<<"ServerEnvironment::activateObjects(): " + <<"failed to create active object from static object " + <<"in block "<m_known_by_count > 0 && !force_delete); @@ -1997,45 +1942,33 @@ void ServerEnvironment::deactivateFarObjects(bool _force_delete) if (obj->m_static_block == blockpos_o) stays_in_same_block = true; - MapBlock *block = m_map->emergeBlock( - obj->m_static_block, false); + MapBlock *block = m_map->emergeBlock(obj->m_static_block, false); if (block) { - const auto n = block->m_static_objects.m_active - .find(id); + const auto n = block->m_static_objects.m_active.find(id); if (n != block->m_static_objects.m_active.end()) { StaticObject static_old = n->second; - float save_movem = - obj->getMinimumSavedMovement(); + float save_movem = obj->getMinimumSavedMovement(); if (static_old.data == s_obj.data && - (static_old.pos - objectpos).getLength() < - save_movem) + (static_old.pos - objectpos).getLength() < save_movem) data_changed = false; } else { - warningstream << "ServerEnvironment::" - "deactivateFarObjects():" - " " - << "id=" << id - << " m_static_exists=true " - "but " - << "static data doesn't " - "actually exist in " - << PP(obj->m_static_block) - << std::endl; + warningstream << "ServerEnvironment::deactivateFarObjects(): " + << "id=" << id << " m_static_exists=true but " + << "static data doesn't actually exist in " + << PP(obj->m_static_block) << std::endl; } } } /* - While changes are always saved, blocks are only marked as - modified if the object has moved or different staticdata. (see - above) + While changes are always saved, blocks are only marked as modified + if the object has moved or different staticdata. (see above) */ bool shall_be_written = (!stays_in_same_block || data_changed); - u32 reason = shall_be_written ? MOD_REASON_STATIC_DATA_CHANGED - : MOD_REASON_UNKNOWN; + u32 reason = shall_be_written ? MOD_REASON_STATIC_DATA_CHANGED : MOD_REASON_UNKNOWN; // Delete old static object deleteStaticFromBlock(obj, id, reason, false); @@ -2053,16 +1986,16 @@ void ServerEnvironment::deactivateFarObjects(bool _force_delete) */ if (pending_delete && !force_delete) { verbosestream << "ServerEnvironment::deactivateFarObjects(): " - << "object id=" << id << " is known by clients" - << "; not deleting yet" << std::endl; + << "object id=" << id << " is known by clients" + << "; not deleting yet" << std::endl; obj->m_pending_deactivation = true; return false; } verbosestream << "ServerEnvironment::deactivateFarObjects(): " - << "object id=" << id << " is not known by clients" - << "; deleting" << std::endl; + << "object id=" << id << " is not known by clients" + << "; deleting" << std::endl; // Tell the object about removal obj->removingFromEnvironment(); @@ -2092,10 +2025,8 @@ void ServerEnvironment::deleteStaticFromBlock( block = m_map->emergeBlock(obj->m_static_block, false); if (!block) { if (!no_emerge) - errorstream << "ServerEnv: Failed to emerge block " - << PP(obj->m_static_block) - << " when deleting static data of object from it. id=" - << id << std::endl; + errorstream << "ServerEnv: Failed to emerge block " << PP(obj->m_static_block) + << " when deleting static data of object from it. id=" << id << std::endl; return; } @@ -2106,8 +2037,10 @@ void ServerEnvironment::deleteStaticFromBlock( obj->m_static_exists = false; } -bool ServerEnvironment::saveStaticToBlock(v3s16 blockpos, u16 store_id, - ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason) +bool ServerEnvironment::saveStaticToBlock( + v3s16 blockpos, u16 store_id, + ServerActiveObject *obj, const StaticObject &s_obj, + u32 mod_reason) { MapBlock *block = nullptr; try { @@ -2119,19 +2052,16 @@ bool ServerEnvironment::saveStaticToBlock(v3s16 blockpos, u16 store_id, } if (!block) { - errorstream << "ServerEnv: Failed to emerge block " - << PP(obj->m_static_block) - << " when saving static data of object to it. id=" << store_id - << std::endl; + errorstream << "ServerEnv: Failed to emerge block " << PP(obj->m_static_block) + << " when saving static data of object to it. id=" << store_id << std::endl; return false; } - if (block->m_static_objects.m_stored.size() >= - g_settings->getU16("max_objects_per_block")) { + if (block->m_static_objects.m_stored.size() >= g_settings->getU16("max_objects_per_block")) { warningstream << "ServerEnv: Trying to store id = " << store_id - << " statically but block " << PP(blockpos) - << " already contains " - << block->m_static_objects.m_stored.size() << " objects." - << std::endl; + << " statically but block " << PP(blockpos) + << " already contains " + << block->m_static_objects.m_stored.size() + << " objects." << std::endl; return false; } @@ -2145,8 +2075,8 @@ bool ServerEnvironment::saveStaticToBlock(v3s16 blockpos, u16 store_id, return true; } -PlayerDatabase *ServerEnvironment::openPlayerDatabase( - const std::string &name, const std::string &savedir, const Settings &conf) +PlayerDatabase *ServerEnvironment::openPlayerDatabase(const std::string &name, + const std::string &savedir, const Settings &conf) { if (name == "sqlite3") @@ -2174,8 +2104,8 @@ PlayerDatabase *ServerEnvironment::openPlayerDatabase( throw BaseException(std::string("Database backend ") + name + " not supported."); } -bool ServerEnvironment::migratePlayersDatabase( - const GameParams &game_params, const Settings &cmd_args) +bool ServerEnvironment::migratePlayersDatabase(const GameParams &game_params, + const Settings &cmd_args) { std::string migrate_to = cmd_args.get("migrate-players"); Settings world_mt; @@ -2187,22 +2117,21 @@ bool ServerEnvironment::migratePlayersDatabase( if (!world_mt.exists("player_backend")) { errorstream << "Please specify your current backend in world.mt:" - << std::endl - << " player_backend = " - "{files|sqlite3|leveldb|postgresql}" - << std::endl; + << std::endl + << " player_backend = {files|sqlite3|leveldb|postgresql}" + << std::endl; return false; } std::string backend = world_mt.get("player_backend"); if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" - << " as the old one" << std::endl; + << " as the old one" << std::endl; return false; } - const std::string players_backup_path = - game_params.world_path + DIR_DELIM + "players.bak"; + const std::string players_backup_path = game_params.world_path + DIR_DELIM + + "players.bak"; if (backend == "files") { // Create backup directory @@ -2210,15 +2139,15 @@ bool ServerEnvironment::migratePlayersDatabase( } try { - PlayerDatabase *srcdb = ServerEnvironment::openPlayerDatabase( - backend, game_params.world_path, world_mt); - PlayerDatabase *dstdb = ServerEnvironment::openPlayerDatabase( - migrate_to, game_params.world_path, world_mt); + PlayerDatabase *srcdb = ServerEnvironment::openPlayerDatabase(backend, + game_params.world_path, world_mt); + PlayerDatabase *dstdb = ServerEnvironment::openPlayerDatabase(migrate_to, + game_params.world_path, world_mt); std::vector player_list; srcdb->listPlayers(player_list); for (std::vector::const_iterator it = player_list.begin(); - it != player_list.end(); ++it) { + it != player_list.end(); ++it) { actionstream << "Migrating player " << it->c_str() << std::endl; RemotePlayer player(it->c_str(), NULL); PlayerSAO playerSAO(NULL, &player, 15000, false); @@ -2232,34 +2161,31 @@ bool ServerEnvironment::migratePlayersDatabase( // For files source, move player files to backup dir if (backend == "files") { - fs::Rename(game_params.world_path + DIR_DELIM + - "players" + DIR_DELIM + - (*it), - players_backup_path + DIR_DELIM + (*it)); + fs::Rename( + game_params.world_path + DIR_DELIM + "players" + DIR_DELIM + (*it), + players_backup_path + DIR_DELIM + (*it)); } } - actionstream << "Successfully migrated " << player_list.size() - << " players" << std::endl; + actionstream << "Successfully migrated " << player_list.size() << " players" + << std::endl; world_mt.set("player_backend", migrate_to); if (!world_mt.updateConfigFile(world_mt_path.c_str())) errorstream << "Failed to update world.mt!" << std::endl; else actionstream << "world.mt updated" << std::endl; - // When migration is finished from file backend, remove players directory - // if empty + // When migration is finished from file backend, remove players directory if empty if (backend == "files") { - fs::DeleteSingleFileOrEmptyDirectory( - game_params.world_path + DIR_DELIM + "players"); + fs::DeleteSingleFileOrEmptyDirectory(game_params.world_path + DIR_DELIM + + "players"); } delete srcdb; delete dstdb; } catch (BaseException &e) { - errorstream << "An error occurred during migration: " << e.what() - << std::endl; + errorstream << "An error occurred during migration: " << e.what() << std::endl; return false; } return true; @@ -2306,22 +2232,19 @@ bool ServerEnvironment::migrateAuthDatabase( backend = world_mt.get("auth_backend"); else warningstream << "No auth_backend found in world.mt, " - "assuming \"files\"." - << std::endl; + "assuming \"files\"." << std::endl; if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" - << " as the old one" << std::endl; + << " as the old one" << std::endl; return false; } try { - const std::unique_ptr srcdb( - ServerEnvironment::openAuthDatabase(backend, - game_params.world_path, world_mt)); - const std::unique_ptr dstdb( - ServerEnvironment::openAuthDatabase(migrate_to, - game_params.world_path, world_mt)); + const std::unique_ptr srcdb(ServerEnvironment::openAuthDatabase( + backend, game_params.world_path, world_mt)); + const std::unique_ptr dstdb(ServerEnvironment::openAuthDatabase( + migrate_to, game_params.world_path, world_mt)); std::vector names_list; srcdb->listNames(names_list); @@ -2336,7 +2259,7 @@ bool ServerEnvironment::migrateAuthDatabase( } actionstream << "Successfully migrated " << names_list.size() - << " auth entries" << std::endl; + << " auth entries" << std::endl; world_mt.set("auth_backend", migrate_to); if (!world_mt.updateConfigFile(world_mt_path.c_str())) errorstream << "Failed to update world.mt!" << std::endl; @@ -2352,15 +2275,13 @@ bool ServerEnvironment::migrateAuthDatabase( if (!fs::PathExists(auth_bak_path)) if (fs::Rename(auth_txt_path, auth_bak_path)) actionstream << "Renamed auth.txt to auth.txt.bak" - << std::endl; + << std::endl; else errorstream << "Could not rename auth.txt to " - "auth.txt.bak" - << std::endl; + "auth.txt.bak" << std::endl; else warningstream << "auth.txt.bak already exists, auth.txt " - "not renamed" - << std::endl; + "not renamed" << std::endl; } } catch (BaseException &e) { diff --git a/src/serverenvironment.h b/src/serverenvironment.h index d4e6bdad2..af742e290 100644 --- a/src/serverenvironment.h +++ b/src/serverenvironment.h @@ -70,7 +70,7 @@ class ActiveBlockModifier // This is called usually at interval for 1/chance of the nodes virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){}; virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n, - u32 active_object_count, u32 active_object_count_wider){}; + u32 active_object_count, u32 active_object_count_wider){}; }; struct ABMWithState @@ -95,8 +95,7 @@ struct LoadingBlockModifierDef struct LBMContentMapping { - typedef std::unordered_map> - lbm_map; + typedef std::unordered_map> lbm_map; lbm_map map; std::vector lbm_list; @@ -118,7 +117,8 @@ class LBMManager // Don't call this after loadIntroductionTimes() ran. void addLBMDef(LoadingBlockModifierDef *lbm_def); - void loadIntroductionTimes(const std::string ×, IGameDef *gamedef, u32 now); + void loadIntroductionTimes(const std::string ×, + IGameDef *gamedef, u32 now); // Don't call this before loadIntroductionTimes() ran. std::string createIntroductionTimesString(); @@ -147,9 +147,7 @@ class LBMManager // after the given time. This is guaranteed to return // valid values for everything lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time) - { - return m_lbm_lookup.lower_bound(time); - } + { return m_lbm_lookup.lower_bound(time); } }; /* @@ -159,13 +157,19 @@ class LBMManager class ActiveBlockList { public: - void update(std::vector &active_players, s16 active_block_range, - s16 active_object_range, std::set &blocks_removed, - std::set &blocks_added); - - bool contains(v3s16 p) { return (m_list.find(p) != m_list.end()); } + void update(std::vector &active_players, + s16 active_block_range, + s16 active_object_range, + std::set &blocks_removed, + std::set &blocks_added); + + bool contains(v3s16 p){ + return (m_list.find(p) != m_list.end()); + } - void clear() { m_list.clear(); } + void clear(){ + m_list.clear(); + } std::set m_list; std::set m_abm_list; @@ -177,14 +181,13 @@ class ActiveBlockList /* Operation mode for ServerEnvironment::clearObjects() */ -enum ClearObjectsMode -{ +enum ClearObjectsMode { // Load and go through every mapblock, clearing objects - CLEAR_OBJECTS_MODE_FULL, + CLEAR_OBJECTS_MODE_FULL, // Clear objects immediately in loaded mapblocks; // clear objects in unloaded mapblocks only when the mapblocks are next activated. - CLEAR_OBJECTS_MODE_QUICK, + CLEAR_OBJECTS_MODE_QUICK, }; /* @@ -198,28 +201,31 @@ typedef std::unordered_map ServerActiveObjectMap; class ServerEnvironment : public Environment { public: - ServerEnvironment(ServerMap *map, ServerScripting *scriptIface, Server *server, - const std::string &path_world); + ServerEnvironment(ServerMap *map, ServerScripting *scriptIface, + Server *server, const std::string &path_world); ~ServerEnvironment(); - Map &getMap(); + Map & getMap(); - ServerMap &getServerMap(); + ServerMap & getServerMap(); - // TODO find way to remove this fct! - ServerScripting *getScriptIface() { return m_script; } + //TODO find way to remove this fct! + ServerScripting* getScriptIface() + { return m_script; } - Server *getGameDef() { return m_server; } + Server *getGameDef() + { return m_server; } - float getSendRecommendedInterval() { return m_recommended_send_interval; } + float getSendRecommendedInterval() + { return m_recommended_send_interval; } - void kickAllPlayers(AccessDeniedCode reason, const std::string &str_reason, - bool reconnect); + void kickAllPlayers(AccessDeniedCode reason, + const std::string &str_reason, bool reconnect); // Save players void saveLoadedPlayers(bool force = false); void savePlayer(RemotePlayer *player); PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id, - bool is_singleplayer); + bool is_singleplayer); void addPlayer(RemotePlayer *player); void removePlayer(RemotePlayer *player); bool removePlayerFromDatabase(const std::string &name); @@ -239,7 +245,7 @@ class ServerEnvironment : public Environment ------------------------------------------- */ - ServerActiveObject *getActiveObject(u16 id) + ServerActiveObject* getActiveObject(u16 id) { return m_ao_manager.getActiveObject(id); } @@ -261,21 +267,25 @@ class ServerEnvironment : public Environment Return value: true if succeeded, false if failed. (note: not used, pending removal from engine) */ - // bool addActiveObjectAsStatic(ServerActiveObject *object); + //bool addActiveObjectAsStatic(ServerActiveObject *object); /* Find out what new objects have been added to inside a radius around a position */ - void getAddedActiveObjects(PlayerSAO *playersao, s16 radius, s16 player_radius, - std::set ¤t_objects, std::queue &added_objects); + void getAddedActiveObjects(PlayerSAO *playersao, s16 radius, + s16 player_radius, + std::set ¤t_objects, + std::queue &added_objects); /* Find out what new objects have been removed from inside a radius around a position */ - void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius, s16 player_radius, - std::set ¤t_objects, std::queue &removed_objects); + void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius, + s16 player_radius, + std::set ¤t_objects, + std::queue &removed_objects); /* Get the next message emitted by some active object. @@ -283,14 +293,16 @@ class ServerEnvironment : public Environment */ bool getActiveObjectMessage(ActiveObjectMessage *dest); - virtual void getSelectedActiveObjects(const core::line3d &shootline_on_map, - std::vector &objects); + virtual void getSelectedActiveObjects( + const core::line3d &shootline_on_map, + std::vector &objects + ); /* Activate objects and dynamically modify for the dtime determined from timestamp and additional_dtime */ - void activateBlock(MapBlock *block, u32 additional_dtime = 0); + void activateBlock(MapBlock *block, u32 additional_dtime=0); /* {Active,Loading}BlockModifiers @@ -311,12 +323,10 @@ class ServerEnvironment : public Environment bool swapNode(v3s16 p, const MapNode &n); // Find all active objects inside a radius around a point - void getObjectsInsideRadius(std::vector &objects, - const v3f &pos, float radius, + void getObjectsInsideRadius(std::vector &objects, const v3f &pos, float radius, std::function include_obj_cb) { - return m_ao_manager.getObjectsInsideRadius( - pos, radius, objects, include_obj_cb); + return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb); } // Clear objects, loading and going through every MapBlock @@ -330,29 +340,26 @@ class ServerEnvironment : public Environment void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; } float getMaxLagEstimate() { return m_max_lag_estimate; } - std::set *getForceloadedBlocks() - { - return &m_active_blocks.m_forceloaded_list; - }; + std::set* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; }; // Sets the static object status all the active objects in the specified block // This is only really needed for deleting blocks from the map - void setStaticForActiveObjectsInBlock(v3s16 blockpos, bool static_exists, - v3s16 static_block = v3s16(0, 0, 0)); + void setStaticForActiveObjectsInBlock(v3s16 blockpos, + bool static_exists, v3s16 static_block=v3s16(0,0,0)); RemotePlayer *getPlayer(const session_t peer_id); - RemotePlayer *getPlayer(const char *name); + RemotePlayer *getPlayer(const char* name); const std::vector getPlayers() const { return m_players; } u32 getPlayerCount() const { return m_players.size(); } - static bool migratePlayersDatabase( - const GameParams &game_params, const Settings &cmd_args); + static bool migratePlayersDatabase(const GameParams &game_params, + const Settings &cmd_args); AuthDatabase *getAuthDatabase() { return m_auth_database; } - static bool migrateAuthDatabase( - const GameParams &game_params, const Settings &cmd_args); - + static bool migrateAuthDatabase(const GameParams &game_params, + const Settings &cmd_args); private: + /** * called if env_meta.txt doesn't exist (e.g. new world) */ @@ -405,8 +412,8 @@ class ServerEnvironment : public Environment */ void deleteStaticFromBlock( ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge); - bool saveStaticToBlock(v3s16 blockpos, u16 store_id, ServerActiveObject *obj, - const StaticObject &s_obj, u32 mod_reason); + bool saveStaticToBlock(v3s16 blockpos, u16 store_id, + ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason); /* Member variables @@ -415,7 +422,7 @@ class ServerEnvironment : public Environment // The map ServerMap *m_map; // Lua state - ServerScripting *m_script; + ServerScripting* m_script; // Server definition Server *m_server; // Active Object Manager @@ -452,7 +459,7 @@ class ServerEnvironment : public Environment float m_max_lag_estimate = 0.1f; // peer_ids in here should be unique, except that there may be many 0s - std::vector m_players; + std::vector m_players; PlayerDatabase *m_player_database = nullptr; AuthDatabase *m_auth_database = nullptr; @@ -465,6 +472,5 @@ class ServerEnvironment : public Environment std::unordered_map m_particle_spawners; std::unordered_map m_particle_spawner_attachments; - ServerActiveObject *createSAO( - ActiveObjectType type, v3f pos, const std::string &data); + ServerActiveObject* createSAO(ActiveObjectType type, v3f pos, const std::string &data); }; diff --git a/src/serverlist.cpp b/src/serverlist.cpp index a10e59c12..18264e933 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -42,11 +42,12 @@ std::string getFilePath() std::string serverlist_file = g_settings->get("serverlist_file"); std::string dir_path = "client" DIR_DELIM "serverlist" DIR_DELIM; - fs::CreateDir(porting::path_user + DIR_DELIM "client"); + fs::CreateDir(porting::path_user + DIR_DELIM "client"); fs::CreateDir(porting::path_user + DIR_DELIM + dir_path); return porting::path_user + DIR_DELIM + dir_path + serverlist_file; } + std::vector getLocal() { std::string path = ServerList::getFilePath(); @@ -64,15 +65,16 @@ std::vector getLocal() return deSerialize(liststring); } + std::vector getOnline() { std::ostringstream geturl; u16 proto_version_min = CLIENT_PROTOCOL_VERSION_MIN; - geturl << g_settings->get("serverlist_url") - << "/list?proto_version_min=" << proto_version_min - << "&proto_version_max=" << CLIENT_PROTOCOL_VERSION_MAX; + geturl << g_settings->get("serverlist_url") << + "/list?proto_version_min=" << proto_version_min << + "&proto_version_max=" << CLIENT_PROTOCOL_VERSION_MAX; Json::Value root = fetchJsonValue(geturl.str(), NULL); std::vector server_list; @@ -95,6 +97,7 @@ std::vector getOnline() return server_list; } + // Delete a server from the local favorites list bool deleteEntry(const ServerListSpec &server) { @@ -154,8 +157,8 @@ std::vector deSerialize(const std::string &liststring) server["port"] = tmp; bool unique = true; for (const ServerListSpec &added : serverlist) { - if (server["name"] == added["name"] && - server["port"] == added["port"]) { + if (server["name"] == added["name"] + && server["port"] == added["port"]) { unique = false; break; } @@ -196,11 +199,17 @@ const std::string serializeJson(const std::vector &serverlist) return fastWriteJson(root); } + #if USE_CURL -void sendAnnounce(AnnounceAction action, const u16 port, - const std::vector &clients_names, const double uptime, - const u32 game_time, const float lag, const std::string &gameid, - const std::string &mg_name, const std::vector &mods, +void sendAnnounce(AnnounceAction action, + const u16 port, + const std::vector &clients_names, + const double uptime, + const u32 game_time, + const float lag, + const std::string &gameid, + const std::string &mg_name, + const std::vector &mods, bool dedicated) { static const char *aa_names[] = {"start", "update", "delete"}; @@ -211,24 +220,21 @@ void sendAnnounce(AnnounceAction action, const u16 port, server["address"] = g_settings->get("server_address"); } if (action != AA_DELETE) { - bool strict_checking = - g_settings->getBool("strict_protocol_version_checking"); - server["name"] = g_settings->get("server_name"); - server["description"] = g_settings->get("server_description"); - server["version"] = g_version_string; - server["proto_min"] = strict_checking ? LATEST_PROTOCOL_VERSION - : SERVER_PROTOCOL_VERSION_MIN; - server["proto_max"] = strict_checking ? LATEST_PROTOCOL_VERSION - : SERVER_PROTOCOL_VERSION_MAX; - server["url"] = g_settings->get("server_url"); - server["creative"] = g_settings->getBool("creative_mode"); - server["damage"] = g_settings->getBool("enable_damage"); - server["password"] = g_settings->getBool("disallow_empty_password"); - server["pvp"] = g_settings->getBool("enable_pvp"); - server["uptime"] = (int)uptime; - server["game_time"] = game_time; - server["clients"] = (int)clients_names.size(); - server["clients_max"] = g_settings->getU16("max_users"); + bool strict_checking = g_settings->getBool("strict_protocol_version_checking"); + server["name"] = g_settings->get("server_name"); + server["description"] = g_settings->get("server_description"); + server["version"] = g_version_string; + server["proto_min"] = strict_checking ? LATEST_PROTOCOL_VERSION : SERVER_PROTOCOL_VERSION_MIN; + server["proto_max"] = strict_checking ? LATEST_PROTOCOL_VERSION : SERVER_PROTOCOL_VERSION_MAX; + server["url"] = g_settings->get("server_url"); + server["creative"] = g_settings->getBool("creative_mode"); + server["damage"] = g_settings->getBool("enable_damage"); + server["password"] = g_settings->getBool("disallow_empty_password"); + server["pvp"] = g_settings->getBool("enable_pvp"); + server["uptime"] = (int) uptime; + server["game_time"] = game_time; + server["clients"] = (int) clients_names.size(); + server["clients_max"] = g_settings->getU16("max_users"); server["clients_list"] = Json::Value(Json::arrayValue); for (const std::string &clients_name : clients_names) { server["clients_list"].append(clients_name); @@ -238,18 +244,16 @@ void sendAnnounce(AnnounceAction action, const u16 port, } if (action == AA_START) { - server["dedicated"] = dedicated; - server["rollback"] = g_settings->getBool("enable_rollback_recording"); - server["mapgen"] = mg_name; - server["privs"] = g_settings->get("default_privs"); - server["can_see_far_names"] = - g_settings->getS16("player_transfer_distance") <= 0; - server["mods"] = Json::Value(Json::arrayValue); + server["dedicated"] = dedicated; + server["rollback"] = g_settings->getBool("enable_rollback_recording"); + server["mapgen"] = mg_name; + server["privs"] = g_settings->get("default_privs"); + server["can_see_far_names"] = g_settings->getS16("player_transfer_distance") <= 0; + server["mods"] = Json::Value(Json::arrayValue); for (const ModSpec &mod : mods) { server["mods"].append(mod.name); } - actionstream << "Announcing to " << g_settings->get("serverlist_url") - << std::endl; + actionstream << "Announcing to " << g_settings->get("serverlist_url") << std::endl; } else if (action == AA_UPDATE) { if (lag) server["lag"] = lag; @@ -264,3 +268,4 @@ void sendAnnounce(AnnounceAction action, const u16 port, #endif } // namespace ServerList + diff --git a/src/serverlist.h b/src/serverlist.h index 3e2745fc5..2b82b7431 100644 --- a/src/serverlist.h +++ b/src/serverlist.h @@ -40,15 +40,9 @@ std::vector deSerializeJson(const std::string &liststring); const std::string serializeJson(const std::vector &serverlist); #if USE_CURL -enum AnnounceAction -{ - AA_START, - AA_UPDATE, - AA_DELETE -}; +enum AnnounceAction {AA_START, AA_UPDATE, AA_DELETE}; void sendAnnounce(AnnounceAction, u16 port, - const std::vector &clients_names = - std::vector(), + const std::vector &clients_names = std::vector(), double uptime = 0, u32 game_time = 0, float lag = 0, const std::string &gameid = "", const std::string &mg_name = "", const std::vector &mods = std::vector(), diff --git a/src/settings.cpp b/src/settings.cpp index 4f8b7b617..55404319e 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -42,14 +42,16 @@ Settings::~Settings() clear(); } -Settings &Settings::operator+=(const Settings &other) + +Settings & Settings::operator += (const Settings &other) { update(other); return *this; } -Settings &Settings::operator=(const Settings &other) + +Settings & Settings::operator = (const Settings &other) { if (&other == this) return *this; @@ -63,6 +65,7 @@ Settings &Settings::operator=(const Settings &other) return *this; } + bool Settings::checkNameValid(const std::string &name) { bool valid = name.find_first_of("=\"{}#") == std::string::npos; @@ -70,19 +73,20 @@ bool Settings::checkNameValid(const std::string &name) valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end(); if (!valid) { - errorstream << "Invalid setting name \"" << name << "\"" << std::endl; + errorstream << "Invalid setting name \"" << name << "\"" + << std::endl; return false; } return true; } + bool Settings::checkValueValid(const std::string &value) { if (value.substr(0, 3) == "\"\"\"" || - value.find("\n\"\"\"") != std::string::npos) { + value.find("\n\"\"\"") != std::string::npos) { errorstream << "Invalid character sequence '\"\"\"' found in" - " setting value!" - << std::endl; + " setting value!" << std::endl; return false; } return true; @@ -113,6 +117,7 @@ std::string Settings::getMultiline(std::istream &is, size_t *num_lines) return value; } + bool Settings::readConfigFile(const char *filename) { std::ifstream is(filename); @@ -122,6 +127,7 @@ bool Settings::readConfigFile(const char *filename) return parseConfigLines(is, ""); } + bool Settings::parseConfigLines(std::istream &is, const std::string &end) { MutexAutoLock lock(m_mutex); @@ -160,6 +166,7 @@ bool Settings::parseConfigLines(std::istream &is, const std::string &end) return end.empty(); } + void Settings::writeLines(std::ostream &os, u32 tab_depth) const { MutexAutoLock lock(m_mutex); @@ -168,8 +175,9 @@ void Settings::writeLines(std::ostream &os, u32 tab_depth) const printEntry(os, setting_it.first, setting_it.second, tab_depth); } + void Settings::printEntry(std::ostream &os, const std::string &name, - const SettingsEntry &entry, u32 tab_depth) + const SettingsEntry &entry, u32 tab_depth) { for (u32 i = 0; i != tab_depth; i++) os << "\t"; @@ -192,8 +200,9 @@ void Settings::printEntry(std::ostream &os, const std::string &name, } } -bool Settings::updateConfigObject( - std::istream &is, std::ostream &os, const std::string &end, u32 tab_depth) + +bool Settings::updateConfigObject(std::istream &is, std::ostream &os, + const std::string &end, u32 tab_depth) { SettingEntries::const_iterator it; std::set present_entries; @@ -218,8 +227,7 @@ bool Settings::updateConfigObject( case SPE_KVPAIR: it = m_settings.find(name); if (it != m_settings.end() && - (it->second.is_group || - it->second.value != value)) { + (it->second.is_group || it->second.value != value)) { printEntry(os, name, it->second, tab_depth); was_modified = true; } else if (it == m_settings.end()) { @@ -238,15 +246,14 @@ bool Settings::updateConfigObject( if (it != m_settings.end() && it->second.is_group) { os << line << "\n"; sanity_check(it->second.group != NULL); - was_modified |= it->second.group->updateConfigObject( - is, os, "}", tab_depth + 1); + was_modified |= it->second.group->updateConfigObject(is, os, + "}", tab_depth + 1); } else if (it == m_settings.end()) { // Remove by skipping was_modified = true; Settings removed_group; // Move 'is' to group end std::stringstream ss; - removed_group.updateConfigObject( - is, ss, "}", tab_depth + 1); + removed_group.updateConfigObject(is, ss, "}", tab_depth + 1); break; } else { printEntry(os, name, it->second, tab_depth); @@ -272,6 +279,7 @@ bool Settings::updateConfigObject( return was_modified; } + bool Settings::updateConfigFile(const char *filename) { MutexAutoLock lock(m_mutex); @@ -286,31 +294,32 @@ bool Settings::updateConfigFile(const char *filename) return true; if (!fs::safeWriteToFile(filename, os.str())) { - errorstream << "Error writing configuration file: \"" << filename << "\"" - << std::endl; + errorstream << "Error writing configuration file: \"" + << filename << "\"" << std::endl; return false; } return true; } -bool Settings::parseCommandLine( - int argc, char *argv[], std::map &allowed_options) + +bool Settings::parseCommandLine(int argc, char *argv[], + std::map &allowed_options) { int nonopt_index = 0; for (int i = 1; i < argc; i++) { std::string arg_name = argv[i]; if (arg_name.substr(0, 2) != "--") { // If option doesn't start with -, read it in as nonoptX - if (arg_name[0] != '-') { + if (arg_name[0] != '-'){ std::string name = "nonopt"; name += itos(nonopt_index); set(name, arg_name); nonopt_index++; continue; } - errorstream << "Invalid command-line parameter \"" << arg_name - << "\": --