From 4faaadc8d50d6ab7a19d22bd5a760c4b8321a51f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Sun, 18 Jun 2017 19:55:15 +0200 Subject: [PATCH 01/53] Cpp11 patchset 11: continue working on constructor style migration (#6004) --- src/mesh_generator_thread.cpp | 18 ------------- src/mesh_generator_thread.h | 33 +++++++++++------------ src/mg_biome.h | 4 +-- src/mg_decoration.cpp | 22 --------------- src/mg_decoration.h | 16 +++++------ src/mg_ore.cpp | 11 -------- src/mg_ore.h | 14 +++++----- src/mg_schematic.cpp | 8 ++---- src/mg_schematic.h | 6 ++--- src/minimap.cpp | 8 +++--- src/minimap.h | 22 +++++++-------- src/modalMenu.h | 6 +---- src/mods.cpp | 4 +-- src/mods.h | 14 +++------- src/nameidmapping.h | 1 + src/nodedef.cpp | 5 ---- src/nodedef.h | 28 ++++++++------------ src/nodetimer.h | 22 +++++++-------- src/noise.cpp | 4 --- src/noise.h | 43 +++++++++--------------------- src/object_properties.cpp | 22 +-------------- src/object_properties.h | 38 +++++++++++++------------- src/particles.cpp | 3 --- src/particles.h | 6 ++--- src/player.cpp | 6 +---- src/player.h | 50 +++++++++++++---------------------- src/profiler.cpp | 2 +- src/profiler.h | 8 +++--- src/reflowscan.cpp | 3 +-- src/reflowscan.h | 6 ++--- src/remoteplayer.cpp | 10 +------ src/remoteplayer.h | 16 +++++------ src/rollback.cpp | 3 +-- src/rollback.h | 4 +-- src/rollback_interface.h | 18 +++++-------- src/server.cpp | 24 +---------------- src/server.h | 48 ++++++++++++++++----------------- src/serverenvironment.cpp | 13 ++------- src/serverenvironment.h | 27 +++++++++---------- 39 files changed, 200 insertions(+), 396 deletions(-) diff --git a/src/mesh_generator_thread.cpp b/src/mesh_generator_thread.cpp index d95506de..f06bddb5 100644 --- a/src/mesh_generator_thread.cpp +++ b/src/mesh_generator_thread.cpp @@ -28,14 +28,6 @@ with this program; if not, write to the Free Software Foundation, Inc., CachedMapBlockData */ -CachedMapBlockData::CachedMapBlockData(): - p(-1337,-1337,-1337), - data(NULL), - refcount_from_queue(0), - last_used_timestamp(time(0)) -{ -} - CachedMapBlockData::~CachedMapBlockData() { assert(refcount_from_queue == 0); @@ -47,16 +39,6 @@ CachedMapBlockData::~CachedMapBlockData() QueuedMeshUpdate */ -QueuedMeshUpdate::QueuedMeshUpdate(): - p(-1337,-1337,-1337), - ack_block_to_server(false), - urgent(false), - crack_level(-1), - crack_pos(0,0,0), - data(NULL) -{ -} - QueuedMeshUpdate::~QueuedMeshUpdate() { delete data; diff --git a/src/mesh_generator_thread.h b/src/mesh_generator_thread.h index 3ac086e3..77b34a3c 100644 --- a/src/mesh_generator_thread.h +++ b/src/mesh_generator_thread.h @@ -27,25 +27,25 @@ with this program; if not, write to the Free Software Foundation, Inc., struct CachedMapBlockData { - v3s16 p; - MapNode *data; // A copy of the MapBlock's data member - int refcount_from_queue; - int last_used_timestamp; + v3s16 p = v3s16(-1337, -1337, -1337); + MapNode *data = nullptr; // A copy of the MapBlock's data member + int refcount_from_queue = 0; + int last_used_timestamp = std::time(0); - CachedMapBlockData(); + CachedMapBlockData() {} ~CachedMapBlockData(); }; struct QueuedMeshUpdate { - v3s16 p; - bool ack_block_to_server; - bool urgent; - int crack_level; + v3s16 p = v3s16(-1337, -1337, -1337); + bool ack_block_to_server = false; + bool urgent = false; + int crack_level = -1; v3s16 crack_pos; - MeshMakeData *data; // This is generated in MeshUpdateQueue::pop() + MeshMakeData *data = nullptr; // This is generated in MeshUpdateQueue::pop() - QueuedMeshUpdate(); + QueuedMeshUpdate(){}; ~QueuedMeshUpdate(); }; @@ -101,14 +101,11 @@ private: struct MeshUpdateResult { - v3s16 p; - MapBlockMesh *mesh; - bool ack_block_to_server; + v3s16 p = v3s16(-1338, -1338, -1338); + MapBlockMesh *mesh = nullptr; + bool ack_block_to_server = false; - MeshUpdateResult() - : p(-1338, -1338, -1338), mesh(NULL), ack_block_to_server(false) - { - } + MeshUpdateResult() {} }; class MeshUpdateThread : public UpdateThread diff --git a/src/mg_biome.h b/src/mg_biome.h index 2e07fd9c..854ada50 100644 --- a/src/mg_biome.h +++ b/src/mg_biome.h @@ -117,10 +117,10 @@ public: virtual Biome *getBiomeAtIndex(size_t index, s16 y) const = 0; // Result of calcBiomes bulk computation. - biome_t *biomemap; + biome_t *biomemap = nullptr; protected: - BiomeManager *m_bmgr; + BiomeManager *m_bmgr = nullptr; v3s16 m_pmin; v3s16 m_csize; }; diff --git a/src/mg_decoration.cpp b/src/mg_decoration.cpp index 1a469cd9..b13ddbad 100644 --- a/src/mg_decoration.cpp +++ b/src/mg_decoration.cpp @@ -67,21 +67,6 @@ size_t DecorationManager::placeAllDecos(Mapgen *mg, u32 blockseed, /////////////////////////////////////////////////////////////////////////////// - -Decoration::Decoration() -{ - mapseed = 0; - fill_ratio = 0; - sidelen = 1; - flags = 0; -} - - -Decoration::~Decoration() -{ -} - - void Decoration::resolveNodeNames() { getIdsFromNrBacklog(&c_place_on); @@ -330,13 +315,6 @@ int DecoSimple::getHeight() /////////////////////////////////////////////////////////////////////////////// - -DecoSchematic::DecoSchematic() -{ - schematic = NULL; -} - - size_t DecoSchematic::generate(MMVManip *vm, PcgRandom *pr, v3s16 p) { // Schematic could have been unloaded but not the decoration diff --git a/src/mg_decoration.h b/src/mg_decoration.h index 6a48796d..968c7861 100644 --- a/src/mg_decoration.h +++ b/src/mg_decoration.h @@ -64,8 +64,8 @@ struct CutoffData { class Decoration : public ObjDef, public NodeResolver { public: - Decoration(); - virtual ~Decoration(); + Decoration() {}; + virtual ~Decoration() {}; virtual void resolveNodeNames(); @@ -76,13 +76,13 @@ public: virtual size_t generate(MMVManip *vm, PcgRandom *pr, v3s16 p) = 0; virtual int getHeight() = 0; - u32 flags; - int mapseed; + u32 flags = 0; + int mapseed = 0; std::vector c_place_on; - s16 sidelen; + s16 sidelen = 1; s16 y_min; s16 y_max; - float fill_ratio; + float fill_ratio = 0.0f; NoiseParams np; std::vector c_spawnby; s16 nspawnby; @@ -104,13 +104,13 @@ public: class DecoSchematic : public Decoration { public: - DecoSchematic(); + DecoSchematic() {}; virtual size_t generate(MMVManip *vm, PcgRandom *pr, v3s16 p); virtual int getHeight(); Rotation rotation; - Schematic *schematic; + Schematic *schematic = nullptr; }; diff --git a/src/mg_ore.cpp b/src/mg_ore.cpp index 6275de31..f959ca9e 100644 --- a/src/mg_ore.cpp +++ b/src/mg_ore.cpp @@ -72,14 +72,6 @@ void OreManager::clear() /////////////////////////////////////////////////////////////////////////////// - -Ore::Ore() -{ - flags = 0; - noise = NULL; -} - - Ore::~Ore() { delete noise; @@ -232,8 +224,6 @@ void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, OrePuff::OrePuff() : Ore() { - noise_puff_top = NULL; - noise_puff_bottom = NULL; } @@ -385,7 +375,6 @@ void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, OreVein::OreVein() : Ore() { - noise2 = NULL; } diff --git a/src/mg_ore.h b/src/mg_ore.h index 77025e1b..4b052e07 100644 --- a/src/mg_ore.h +++ b/src/mg_ore.h @@ -62,13 +62,13 @@ public: s16 y_min; s16 y_max; u8 ore_param2; // to set node-specific attributes - u32 flags; // attributes for this ore + 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; + Noise *noise = nullptr; std::unordered_set biomes; - Ore(); + Ore() {}; virtual ~Ore(); virtual void resolveNodeNames(); @@ -104,8 +104,8 @@ public: NoiseParams np_puff_top; NoiseParams np_puff_bottom; - Noise *noise_puff_top; - Noise *noise_puff_bottom; + Noise *noise_puff_top = nullptr; + Noise *noise_puff_bottom = nullptr; OrePuff(); virtual ~OrePuff(); @@ -127,7 +127,7 @@ public: static const bool NEEDS_NOISE = true; float random_factor; - Noise *noise2; + Noise *noise2 = nullptr; OreVein(); virtual ~OreVein(); @@ -160,7 +160,7 @@ public: case ORE_VEIN: return new OreVein; default: - return NULL; + return nullptr; } } diff --git a/src/mg_schematic.cpp b/src/mg_schematic.cpp index 3cea3c32..c50e90b3 100644 --- a/src/mg_schematic.cpp +++ b/src/mg_schematic.cpp @@ -37,9 +37,9 @@ with this program; if not, write to the Free Software Foundation, Inc., SchematicManager::SchematicManager(Server *server) : - ObjDefManager(server, OBJDEF_SCHEMATIC) + ObjDefManager(server, OBJDEF_SCHEMATIC), + m_server(server) { - m_server = server; } @@ -69,10 +69,6 @@ void SchematicManager::clear() Schematic::Schematic() { - schemdata = NULL; - slice_probs = NULL; - flags = 0; - size = v3s16(0, 0, 0); } diff --git a/src/mg_schematic.h b/src/mg_schematic.h index db040343..16e967a7 100644 --- a/src/mg_schematic.h +++ b/src/mg_schematic.h @@ -117,10 +117,10 @@ public: std::vector > *splist); std::vector c_nodes; - u32 flags; + u32 flags = 0; v3s16 size; - MapNode *schemdata; - u8 *slice_probs; + MapNode *schemdata = nullptr; + u8 *slice_probs = nullptr; }; class SchematicManager : public ObjDefManager { diff --git a/src/minimap.cpp b/src/minimap.cpp index 500f4982..9b17cbc6 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -204,8 +204,6 @@ Minimap::Minimap(IrrlichtDevice *device, Client *client) data->mode = MINIMAP_MODE_OFF; data->is_radar = false; data->map_invalidated = true; - data->heightmap_image = NULL; - data->minimap_image = NULL; data->texture = NULL; data->heightmap_texture = NULL; data->minimap_shape_round = g_settings->getBool("minimap_shape_round"); @@ -275,14 +273,14 @@ void Minimap::toggleMinimapShape() void Minimap::setMinimapShape(MinimapShape shape) { MutexAutoLock lock(m_mutex); - + if (shape == MINIMAP_SHAPE_SQUARE) data->minimap_shape_round = false; else if (shape == MINIMAP_SHAPE_ROUND) data->minimap_shape_round = true; - + g_settings->setBool("minimap_shape_round", data->minimap_shape_round); - m_minimap_update_thread->deferUpdate(); + m_minimap_update_thread->deferUpdate(); } MinimapShape Minimap::getMinimapShape() diff --git a/src/minimap.h b/src/minimap.h index 58d05d66..04ac27a0 100644 --- a/src/minimap.h +++ b/src/minimap.h @@ -78,21 +78,19 @@ struct MinimapData { MinimapPixel minimap_scan[MINIMAP_MAX_SX * MINIMAP_MAX_SY]; bool map_invalidated; bool minimap_shape_round; - video::IImage *minimap_image; - video::IImage *heightmap_image; - video::IImage *minimap_mask_round; - video::IImage *minimap_mask_square; - video::ITexture *texture; - video::ITexture *heightmap_texture; - video::ITexture *minimap_overlay_round; - video::ITexture *minimap_overlay_square; - video::ITexture *player_marker; - video::ITexture *object_marker_red; + video::IImage *minimap_mask_round = nullptr; + video::IImage *minimap_mask_square = nullptr; + video::ITexture *texture = nullptr; + video::ITexture *heightmap_texture = nullptr; + video::ITexture *minimap_overlay_round = nullptr; + video::ITexture *minimap_overlay_square = nullptr; + video::ITexture *player_marker = nullptr; + video::ITexture *object_marker_red = nullptr; }; struct QueuedMinimapUpdate { v3s16 pos; - MinimapMapblock *data; + MinimapMapblock *data = nullptr; }; class MinimapUpdateThread : public UpdateThread { @@ -105,7 +103,7 @@ public: bool pushBlockUpdate(v3s16 pos, MinimapMapblock *data); bool popBlockUpdate(QueuedMinimapUpdate *update); - MinimapData *data; + MinimapData *data = nullptr; protected: virtual void doUpdate(); diff --git a/src/modalMenu.h b/src/modalMenu.h index 38a26535..7dbf36fb 100644 --- a/src/modalMenu.h +++ b/src/modalMenu.h @@ -48,11 +48,7 @@ public: IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, core::rect(0,0,100,100)) { - //m_force_regenerate_gui = false; - m_menumgr = menumgr; - m_allow_focus_removal = false; - m_screensize_old = v2u32(0,0); setVisible(true); Environment->setFocus(this); @@ -142,7 +138,7 @@ private: IMenuManager *m_menumgr; // This might be necessary to expose to the implementation if it // wants to launch other menus - bool m_allow_focus_removal; + bool m_allow_focus_removal = false; }; diff --git a/src/mods.cpp b/src/mods.cpp index 5a71ca2d..a555a5b1 100644 --- a/src/mods.cpp +++ b/src/mods.cpp @@ -385,10 +385,8 @@ Json::Value getModstoreUrl(const std::string &url) #endif ModMetadata::ModMetadata(const std::string &mod_name): - m_mod_name(mod_name), - m_modified(false) + m_mod_name(mod_name) { - m_stringvars.clear(); } void ModMetadata::clear() diff --git a/src/mods.h b/src/mods.h index 792280b8..1a5c3269 100644 --- a/src/mods.h +++ b/src/mods.h @@ -42,19 +42,13 @@ struct ModSpec std::unordered_set optdepends; std::unordered_set unsatisfied_depends; - bool part_of_modpack; - bool is_modpack; + bool part_of_modpack = false; + bool is_modpack = false; // if modpack: std::map modpack_content; ModSpec(const std::string &name_="", const std::string &path_=""): name(name_), - path(path_), - depends(), - optdepends(), - unsatisfied_depends(), - part_of_modpack(false), - is_modpack(false), - modpack_content() + path(path_) {} }; @@ -235,7 +229,7 @@ public: virtual bool setString(const std::string &name, const std::string &var); private: std::string m_mod_name; - bool m_modified; + bool m_modified = false; }; #endif diff --git a/src/nameidmapping.h b/src/nameidmapping.h index 38984306..90aadcf6 100644 --- a/src/nameidmapping.h +++ b/src/nameidmapping.h @@ -56,6 +56,7 @@ public: m_id_to_name.erase(id); m_name_to_id.erase(name); } + void eraseName(const std::string &name) { u16 id; diff --git a/src/nodedef.cpp b/src/nodedef.cpp index db7e3662..1b6c28cf 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -1923,11 +1923,6 @@ bool CNodeDefManager::nodeboxConnects(MapNode from, MapNode to, u8 connect_face) NodeResolver::NodeResolver() { - m_ndef = NULL; - m_nodenames_idx = 0; - m_nnlistsizes_idx = 0; - m_resolve_done = false; - m_nodenames.reserve(16); m_nnlistsizes.reserve(4); } diff --git a/src/nodedef.h b/src/nodedef.h index 4669df7f..97697e74 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -207,24 +207,18 @@ enum PlantlikeStyle { struct TileDef { - std::string name; - bool backface_culling; // Takes effect only in special cases - bool tileable_horizontal; - bool tileable_vertical; + std::string name = ""; + bool backface_culling = true; // Takes effect only in special cases + bool tileable_horizontal = true; + bool tileable_vertical = true; //! If true, the tile has its own color. - bool has_color; + bool has_color = false; //! The color of the tile. - video::SColor color; + video::SColor color = video::SColor(0xFFFFFFFF); struct TileAnimationParams animation; - TileDef() : - name(""), - backface_culling(true), - tileable_horizontal(true), - tileable_vertical(true), - has_color(false), - color(video::SColor(0xFFFFFFFF)) + TileDef() { animation.type = TAT_NONE; } @@ -514,12 +508,12 @@ public: void nodeResolveInternal(); - u32 m_nodenames_idx; - u32 m_nnlistsizes_idx; + u32 m_nodenames_idx = 0; + u32 m_nnlistsizes_idx = 0; std::vector m_nodenames; std::vector m_nnlistsizes; - INodeDefManager *m_ndef; - bool m_resolve_done; + INodeDefManager *m_ndef = nullptr; + bool m_resolve_done = false; }; #endif diff --git a/src/nodetimer.h b/src/nodetimer.h index 0fd43b2a..e6a8d760 100644 --- a/src/nodetimer.h +++ b/src/nodetimer.h @@ -36,18 +36,18 @@ with this program; if not, write to the Free Software Foundation, Inc., class NodeTimer { public: - NodeTimer(): timeout(0.), elapsed(0.) {} + NodeTimer() {} NodeTimer(const v3s16 &position_): - timeout(0.), elapsed(0.), position(position_) {} + position(position_) {} NodeTimer(f32 timeout_, f32 elapsed_, v3s16 position_): timeout(timeout_), elapsed(elapsed_), position(position_) {} ~NodeTimer() {} - + void serialize(std::ostream &os) const; void deSerialize(std::istream &is); - - f32 timeout; - f32 elapsed; + + f32 timeout = 0.0f; + f32 elapsed = 0.0f; v3s16 position; }; @@ -58,12 +58,12 @@ public: class NodeTimerList { public: - NodeTimerList(): m_next_trigger_time(-1.), m_time(0.) {} + NodeTimerList() {} ~NodeTimerList() {} - + void serialize(std::ostream &os, u8 map_format_version) const; void deSerialize(std::istream &is, u8 map_format_version); - + // Get timer NodeTimer get(const v3s16 &p) { std::map::iterator>::iterator n = @@ -128,8 +128,8 @@ public: private: std::multimap m_timers; std::map::iterator> m_iterators; - double m_next_trigger_time; - double m_time; + double m_next_trigger_time = -1.0; + double m_time = 0.0; }; #endif diff --git a/src/noise.cpp b/src/noise.cpp index b918c993..e75fb827 100644 --- a/src/noise.cpp +++ b/src/noise.cpp @@ -433,10 +433,6 @@ Noise::Noise(NoiseParams *np_, s32 seed, u32 sx, u32 sy, u32 sz) this->sy = sy; this->sz = sz; - this->persist_buf = NULL; - this->gradient_buf = NULL; - this->result = NULL; - allocBuffers(); } diff --git a/src/noise.h b/src/noise.h index 41b93ae0..d5aca4de 100644 --- a/src/noise.h +++ b/src/noise.h @@ -102,26 +102,16 @@ private: #define NOISE_FLAG_SIMPLEX 0x10 struct NoiseParams { - float offset; - float scale; - v3f spread; - s32 seed; - u16 octaves; - float persist; - float lacunarity; - u32 flags; + float offset = 0.0f; + float scale = 1.0f; + v3f spread = v3f(250, 250, 250); + s32 seed = 12345; + u16 octaves = 3; + float persist = 0.6f; + float lacunarity = 2.0f; + u32 flags = NOISE_FLAG_DEFAULTS; - NoiseParams() - { - offset = 0.0f; - scale = 1.0f; - spread = v3f(250, 250, 250); - seed = 12345; - octaves = 3; - persist = 0.6f; - lacunarity = 2.0f; - flags = NOISE_FLAG_DEFAULTS; - } + NoiseParams() {} NoiseParams(float offset_, float scale_, v3f spread_, s32 seed_, u16 octaves_, float persist_, float lacunarity_, @@ -138,13 +128,6 @@ struct NoiseParams { } }; - -// Convenience macros for getting/setting NoiseParams in Settings as a string -// WARNING: Deprecated, use Settings::getNoiseParamsFromValue() instead -#define NOISEPARAMS_FMT_STR "f,f,v3,s32,u16,f" -//#define getNoiseParams(x, y) getStruct((x), NOISEPARAMS_FMT_STR, &(y), sizeof(y)) -//#define setNoiseParams(x, y) setStruct((x), NOISEPARAMS_FMT_STR, &(y)) - class Noise { public: NoiseParams np; @@ -152,10 +135,10 @@ public: u32 sx; u32 sy; u32 sz; - float *noise_buf; - float *gradient_buf; - float *persist_buf; - float *result; + float *noise_buf = nullptr; + float *gradient_buf = nullptr; + float *persist_buf = nullptr; + float *result = nullptr; Noise(NoiseParams *np, s32 seed, u32 sx, u32 sy, u32 sz=1); ~Noise(); diff --git a/src/object_properties.cpp b/src/object_properties.cpp index a7736815..af442806 100644 --- a/src/object_properties.cpp +++ b/src/object_properties.cpp @@ -24,27 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/basic_macros.h" #include -ObjectProperties::ObjectProperties(): - hp_max(1), - physical(false), - collideWithObjects(true), - weight(5), - collisionbox(-0.5,-0.5,-0.5, 0.5,0.5,0.5), - visual("sprite"), - mesh(""), - visual_size(1,1), - spritediv(1,1), - initial_sprite_basepos(0,0), - is_visible(true), - makes_footstep_sound(false), - automatic_rotate(0), - stepheight(0), - automatic_face_movement_dir(false), - automatic_face_movement_dir_offset(0.0), - backface_culling(true), - nametag(""), - nametag_color(255, 255, 255, 255), - automatic_face_movement_max_rotation_per_sec(-1) +ObjectProperties::ObjectProperties() { textures.push_back("unknown_object.png"); colors.push_back(video::SColor(255,255,255,255)); diff --git a/src/object_properties.h b/src/object_properties.h index 908757a6..772807fd 100644 --- a/src/object_properties.h +++ b/src/object_properties.h @@ -29,28 +29,28 @@ with this program; if not, write to the Free Software Foundation, Inc., struct ObjectProperties { // Values are BS=1 - s16 hp_max; - bool physical; - bool collideWithObjects; - float weight; - aabb3f collisionbox; - std::string visual; - std::string mesh; - v2f visual_size; + s16 hp_max = 1; + bool physical = false; + bool collideWithObjects = true; + float weight = 5.0f; + aabb3f collisionbox = aabb3f(-0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f); + std::string visual = "sprite"; + std::string mesh = ""; + v2f visual_size = v2f(1, 1); std::vector textures; std::vector colors; - v2s16 spritediv; + v2s16 spritediv = v2s16(1, 1); v2s16 initial_sprite_basepos; - bool is_visible; - bool makes_footstep_sound; - float automatic_rotate; - f32 stepheight; - bool automatic_face_movement_dir; - f32 automatic_face_movement_dir_offset; - bool backface_culling; - std::string nametag; - video::SColor nametag_color; - f32 automatic_face_movement_max_rotation_per_sec; + bool is_visible = true; + bool makes_footstep_sound = false; + float automatic_rotate = 0.0f; + f32 stepheight = 0.0f; + bool automatic_face_movement_dir = false; + f32 automatic_face_movement_dir_offset = 0.0f; + bool backface_culling = true; + std::string nametag = ""; + video::SColor nametag_color = video::SColor(255, 255, 255, 255); + f32 automatic_face_movement_max_rotation_per_sec = -1.0f; std::string infotext; //! For dropped items, this contains item information. std::string wield_item; diff --git a/src/particles.cpp b/src/particles.cpp index fe681fe6..a02c32f2 100644 --- a/src/particles.cpp +++ b/src/particles.cpp @@ -76,8 +76,6 @@ Particle::Particle( m_texpos = texpos; m_texsize = texsize; m_animation = anim; - m_animation_frame = 0; - m_animation_time = 0.0; // Color m_base_color = color; @@ -88,7 +86,6 @@ Particle::Particle( m_velocity = velocity; m_acceleration = acceleration; m_expiration = expirationtime; - m_time = 0; m_player = player; m_size = size; m_collisiondetection = collisiondetection; diff --git a/src/particles.h b/src/particles.h index 87583aae..9b10afe4 100644 --- a/src/particles.h +++ b/src/particles.h @@ -86,7 +86,7 @@ private: void updateVertices(); video::S3DVertex m_vertices[4]; - float m_time; + float m_time = 0.0f; float m_expiration; ClientEnvironment *m_env; @@ -110,8 +110,8 @@ private: bool m_vertical; v3s16 m_camera_offset; struct TileAnimationParams m_animation; - float m_animation_time; - int m_animation_frame; + float m_animation_time = 0.0f; + int m_animation_frame = 0; u8 m_glow; }; diff --git a/src/player.cpp b/src/player.cpp index 85bc639e..53e17349 100644 --- a/src/player.cpp +++ b/src/player.cpp @@ -30,11 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., Player::Player(const char *name, IItemDefManager *idef): - inventory(idef), - peer_id(PEER_ID_INEXISTENT), - keyPressed(0), -// protected - m_speed(0,0,0) + inventory(idef) { strlcpy(m_name, name, PLAYERNAME_SIZE); diff --git a/src/player.h b/src/player.h index 00d27cb9..fc799afb 100644 --- a/src/player.h +++ b/src/player.h @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irrlichttypes_bloated.h" #include "inventory.h" +#include "constants.h" #include #include @@ -32,22 +33,7 @@ with this program; if not, write to the Free Software Foundation, Inc., struct PlayerControl { - PlayerControl() - { - up = false; - down = false; - left = false; - right = false; - jump = false; - aux1 = false; - sneak = false; - LMB = false; - RMB = false; - pitch = 0; - yaw = 0; - sidew_move_joystick_axis = .0f; - forw_move_joystick_axis = .0f; - } + PlayerControl() {} PlayerControl( bool a_up, @@ -81,20 +67,20 @@ struct PlayerControl sidew_move_joystick_axis = a_sidew_move_joystick_axis; forw_move_joystick_axis = a_forw_move_joystick_axis; } - bool up; - bool down; - bool left; - bool right; - bool jump; - bool aux1; - bool sneak; - bool zoom; - bool LMB; - bool RMB; - float pitch; - float yaw; - float sidew_move_joystick_axis; - float forw_move_joystick_axis; + bool up = false; + bool down = false; + bool left = false; + bool right = false; + bool jump = false; + bool aux1 = false; + bool sneak = false; + bool zoom = false; + bool LMB = false; + bool RMB = false; + float pitch = 0.0f; + float yaw = 0.0f; + float sidew_move_joystick_axis = 0.0f; + float forw_move_joystick_axis = 0.0f; }; class Map; @@ -161,14 +147,14 @@ public: v2s32 local_animations[4]; float local_animation_speed; - u16 peer_id; + u16 peer_id = PEER_ID_INEXISTENT; std::string inventory_formspec; PlayerControl control; const PlayerControl& getPlayerControl() { return control; } - u32 keyPressed; + u32 keyPressed = 0; HudElement* getHud(u32 id); u32 addHud(HudElement* hud); diff --git a/src/profiler.cpp b/src/profiler.cpp index 8e997442..738a5b7e 100644 --- a/src/profiler.cpp +++ b/src/profiler.cpp @@ -23,7 +23,7 @@ static Profiler main_profiler; Profiler *g_profiler = &main_profiler; ScopeProfiler::ScopeProfiler( Profiler *profiler, const std::string &name, ScopeProfilerType type) - : m_profiler(profiler), m_name(name), m_timer(NULL), m_type(type) + : m_profiler(profiler), m_name(name), m_type(type) { if (m_profiler) m_timer = new TimeTaker(m_name); diff --git a/src/profiler.h b/src/profiler.h index 2d70e8af..cade887e 100644 --- a/src/profiler.h +++ b/src/profiler.h @@ -42,9 +42,7 @@ extern Profiler *g_profiler; class Profiler { public: - Profiler() - { - } + Profiler() {} void add(const std::string &name, float value) { @@ -195,9 +193,9 @@ public: ScopeProfilerType type = SPT_ADD); ~ScopeProfiler(); private: - Profiler *m_profiler; + Profiler *m_profiler = nullptr; std::string m_name; - TimeTaker *m_timer; + TimeTaker *m_timer = nullptr; enum ScopeProfilerType m_type; }; diff --git a/src/reflowscan.cpp b/src/reflowscan.cpp index 439b7526..fd169f1a 100644 --- a/src/reflowscan.cpp +++ b/src/reflowscan.cpp @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., ReflowScan::ReflowScan(Map *map, INodeDefManager *ndef) : m_map(map), - m_ndef(ndef), - m_liquid_queue(nullptr) + m_ndef(ndef) { } diff --git a/src/reflowscan.h b/src/reflowscan.h index a6d289ad..5b1ef9b5 100644 --- a/src/reflowscan.h +++ b/src/reflowscan.h @@ -39,10 +39,10 @@ private: void scanColumn(int x, int z); private: - Map *m_map; - INodeDefManager *m_ndef; + Map *m_map = nullptr; + INodeDefManager *m_ndef = nullptr; v3s16 m_block_pos, m_rel_block_pos; - UniqueQueue *m_liquid_queue; + UniqueQueue *m_liquid_queue = nullptr; MapBlock *m_lookup[3 * 3 * 3]; u32 m_lookup_state_bitset; }; diff --git a/src/remoteplayer.cpp b/src/remoteplayer.cpp index 54013297..c276062c 100644 --- a/src/remoteplayer.cpp +++ b/src/remoteplayer.cpp @@ -36,15 +36,7 @@ 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), - protocol_version(0), - m_sao(NULL), - m_dirty(false), - m_last_chat_message_sent(time(NULL)), - m_chat_message_allowance(5.0f), - m_message_rate_overhead(0), - hud_hotbar_image(""), - hud_hotbar_selected_image("") + Player(name, idef) { if (!RemotePlayer::m_setting_cache_loaded) { RemotePlayer::m_setting_chat_message_limit_per_10sec = diff --git a/src/remoteplayer.h b/src/remoteplayer.h index ee0d625b..965dede5 100644 --- a/src/remoteplayer.h +++ b/src/remoteplayer.h @@ -134,7 +134,7 @@ public: void setDirty(bool dirty) { m_dirty = true; } - u16 protocol_version; + u16 protocol_version = 0; private: /* @@ -145,21 +145,21 @@ private: void serialize(std::ostream &os); void serializeExtraAttributes(std::string &output); - PlayerSAO *m_sao; - bool m_dirty; + PlayerSAO *m_sao = nullptr; + bool m_dirty = false; static bool m_setting_cache_loaded; static float m_setting_chat_message_limit_per_10sec; static u16 m_setting_chat_message_limit_trigger_kick; - u32 m_last_chat_message_sent; - float m_chat_message_allowance; - u16 m_message_rate_overhead; + u32 m_last_chat_message_sent = std::time(0); + float m_chat_message_allowance = 5.0f; + u16 m_message_rate_overhead = 0; bool m_day_night_ratio_do_override; float m_day_night_ratio; - std::string hud_hotbar_image; - std::string hud_hotbar_selected_image; + std::string hud_hotbar_image = ""; + std::string hud_hotbar_selected_image = ""; std::string m_sky_type; video::SColor m_sky_bgcolor; diff --git a/src/rollback.cpp b/src/rollback.cpp index 4d34decf..a77a9ee1 100644 --- a/src/rollback.cpp +++ b/src/rollback.cpp @@ -91,8 +91,7 @@ struct Entity { RollbackManager::RollbackManager(const std::string & world_path, IGameDef * gamedef_) : - gamedef(gamedef_), - current_actor_is_guess(false) + gamedef(gamedef_) { verbosestream << "RollbackManager::RollbackManager(" << world_path << ")" << std::endl; diff --git a/src/rollback.h b/src/rollback.h index a05ef8b7..e0b3c7c5 100644 --- a/src/rollback.h +++ b/src/rollback.h @@ -80,10 +80,10 @@ private: time_t suspect_t, v3s16 action_p, time_t action_t); - IGameDef * gamedef; + IGameDef *gamedef = nullptr; std::string current_actor; - bool current_actor_is_guess; + bool current_actor_is_guess = false; std::list action_todisk_buffer; std::list action_latest_buffer; diff --git a/src/rollback_interface.h b/src/rollback_interface.h index 92fab9b9..a5f0c34f 100644 --- a/src/rollback_interface.h +++ b/src/rollback_interface.h @@ -35,8 +35,8 @@ class InventoryManager; struct RollbackNode { std::string name; - int param1; - int param2; + int param1 = 0; + int param2 = 0; std::string meta; bool operator == (const RollbackNode &other) @@ -46,11 +46,7 @@ struct RollbackNode } bool operator != (const RollbackNode &other) { return !(*this == other); } - RollbackNode(): - param1(0), - param2(0) - {} - + RollbackNode() {} RollbackNode(Map *map, v3s16 p, IGameDef *gamedef); }; @@ -70,7 +66,7 @@ struct RollbackAction v3s16 p; RollbackNode n_old; RollbackNode n_new; - + std::string inventory_location; std::string inventory_list; u32 inventory_index; @@ -103,13 +99,13 @@ struct RollbackAction inventory_add = add_; inventory_stack = inventory_stack_; } - + // String should not contain newlines or nulls std::string toString() const; - + // Eg. flowing water level changes are not important bool isImportant(IGameDef *gamedef) const; - + bool getPosition(v3s16 *dst) const; bool applyRevert(Map *map, InventoryManager *imgr, IGameDef *gamedef) const; diff --git a/src/server.cpp b/src/server.cpp index b4b6882e..95d2371f 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -156,41 +156,19 @@ Server::Server( m_simple_singleplayer_mode(simple_singleplayer_mode), m_dedicated(dedicated), m_async_fatal_error(""), - m_env(NULL), m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this), - m_banmanager(NULL), - m_rollback(NULL), - m_enable_rollback_recording(false), - m_emerge(NULL), - m_script(NULL), m_itemdef(createItemDefManager()), m_nodedef(createNodeDefManager()), m_craftdef(createCraftDefManager()), m_event(new EventManager()), - m_thread(NULL), - m_time_of_day_send_timer(0), m_uptime(0), m_clients(&m_con), - m_shutdown_requested(false), - m_shutdown_ask_reconnect(false), - m_shutdown_timer(0.0f), - m_admin_chat(iface), - m_ignore_map_edit_events(false), - m_ignore_map_edit_events_peer_id(0), - m_next_sound_id(0), - m_mod_storage_save_timer(10.0f) + m_admin_chat(iface) { - m_liquid_transform_timer = 0.0; - m_liquid_transform_every = 1.0; - m_masterserver_timer = 0.0; - m_emergethread_trigger_timer = 0.0; - m_savemap_timer = 0.0; - - m_step_dtime = 0.0; m_lag = g_settings->getFloat("dedicated_server_step"); if(path_world == "") diff --git a/src/server.h b/src/server.h index 3086e876..b60482a7 100644 --- a/src/server.h +++ b/src/server.h @@ -113,8 +113,8 @@ struct ServerSoundParams float fade = 0.0f; float pitch = 1.0f; bool loop = false; - float max_hear_distance = 32*BS; - v3f pos = v3f(0, 0, 0); + float max_hear_distance = 32 * BS; + v3f pos; u16 object = 0; std::string to_player = ""; @@ -142,7 +142,7 @@ public: bool simple_singleplayer_mode, bool ipv6, bool dedicated, - ChatInterface *iface = NULL + ChatInterface *iface = nullptr ); ~Server(); DISABLE_CLASS_COPY(Server); @@ -521,32 +521,32 @@ private: MutexedVariable m_async_fatal_error; // Some timers - float m_liquid_transform_timer; - float m_liquid_transform_every; - float m_masterserver_timer; - float m_emergethread_trigger_timer; - float m_savemap_timer; + float m_liquid_transform_timer = 0.0f; + float m_liquid_transform_every = 1.0f; + float m_masterserver_timer = 0.0f; + float m_emergethread_trigger_timer = 0.0f; + float m_savemap_timer = 0.0f; IntervalLimiter m_map_timer_and_unload_interval; // Environment - ServerEnvironment *m_env; + ServerEnvironment *m_env = nullptr; // server connection con::Connection m_con; // Ban checking - BanManager *m_banmanager; + BanManager *m_banmanager = nullptr; // Rollback manager (behind m_env_mutex) - IRollbackManager *m_rollback; - bool m_enable_rollback_recording; // Updated once in a while + IRollbackManager *m_rollback = nullptr; + bool m_enable_rollback_recording = false; // Updated once in a while // Emerge manager - EmergeManager *m_emerge; + EmergeManager *m_emerge = nullptr; // Scripting // Envlock and conlock should be locked when using Lua - ServerScripting *m_script; + ServerScripting *m_script = nullptr; // Item definition manager IWritableItemDefManager *m_itemdef; @@ -569,21 +569,21 @@ private: // A buffer for time steps // step() increments and AsyncRunStep() run by m_thread reads it. - float m_step_dtime; + float m_step_dtime = 0.0f; std::mutex m_step_dtime_mutex; // current server step lag counter float m_lag; // The server mainly operates in this thread - ServerThread *m_thread; + ServerThread *m_thread = nullptr; /* Time related stuff */ // Timer for sending time of day over network - float m_time_of_day_send_timer; + float m_time_of_day_send_timer = 0.0f; // Uptime of server in seconds MutexedVariable m_uptime; /* @@ -602,10 +602,10 @@ private: Random stuff */ - bool m_shutdown_requested; + bool m_shutdown_requested = false; std::string m_shutdown_msg; - bool m_shutdown_ask_reconnect; - float m_shutdown_timer; + bool m_shutdown_ask_reconnect = false; + float m_shutdown_timer = 0.0f; ChatInterface *m_admin_chat; std::string m_admin_nick; @@ -629,7 +629,7 @@ private: all sending of information by itself. This is behind m_env_mutex */ - bool m_ignore_map_edit_events; + bool m_ignore_map_edit_events = false; /* If a non-empty area, map edit events contained within are left unsent. Done at map generation time to speed up editing of the @@ -642,7 +642,7 @@ private: this peed id as the disabled recipient This is behind m_env_mutex */ - u16 m_ignore_map_edit_events_peer_id; + u16 m_ignore_map_edit_events_peer_id = 0; // media files known to server std::unordered_map m_media; @@ -651,7 +651,7 @@ private: Sounds */ std::unordered_map m_playing_sounds; - s32 m_next_sound_id; + s32 m_next_sound_id = 0; /* Detached inventories (behind m_env_mutex) @@ -662,7 +662,7 @@ private: std::map m_detached_inventories_player; std::unordered_map m_mod_storages; - float m_mod_storage_save_timer; + float m_mod_storage_save_timer = 10.0f; }; /* diff --git a/src/serverenvironment.cpp b/src/serverenvironment.cpp index 161b24fd..e8bdd2a2 100644 --- a/src/serverenvironment.cpp +++ b/src/serverenvironment.cpp @@ -54,8 +54,7 @@ with this program; if not, write to the Free Software Foundation, Inc., */ ABMWithState::ABMWithState(ActiveBlockModifier *abm_): - abm(abm_), - timer(0) + abm(abm_) { // Initialize timer to random value to spread processing float itv = abm->getTriggerInterval(); @@ -365,15 +364,7 @@ ServerEnvironment::ServerEnvironment(ServerMap *map, m_map(map), m_script(scriptIface), m_server(server), - m_path_world(path_world), - m_send_recommended_timer(0), - m_active_block_interval_overload_skip(0), - m_game_time(0), - m_game_time_fraction_counter(0), - m_last_clear_objects_time(0), - m_recommended_send_interval(0.1), - m_max_lag_estimate(0.1), - m_player_database(NULL) + m_path_world(path_world) { // Determine which database backend to use std::string conf_path = path_world + DIR_DELIM + "world.mt"; diff --git a/src/serverenvironment.h b/src/serverenvironment.h index 3b7bf8fb..375b28f8 100644 --- a/src/serverenvironment.h +++ b/src/serverenvironment.h @@ -70,7 +70,7 @@ public: struct ABMWithState { ActiveBlockModifier *abm; - float timer; + float timer = 0.0f; ABMWithState(ActiveBlockModifier *abm_); }; @@ -80,7 +80,7 @@ struct LoadingBlockModifierDef // Set of contents to trigger on std::set trigger_contents; std::string name; - bool run_at_every_load; + bool run_at_every_load = false; virtual ~LoadingBlockModifierDef() {} virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){}; @@ -104,10 +104,7 @@ struct LBMContentMapping class LBMManager { public: - LBMManager(): - m_query_mode(false) - {} - + LBMManager() {} ~LBMManager(); // Don't call this after loadIntroductionTimes() ran. @@ -128,7 +125,7 @@ public: private: // Once we set this to true, we can only query, // not modify - bool m_query_mode; + bool m_query_mode = false; // For m_query_mode == false: // The key of the map is the LBM def's name. @@ -399,35 +396,35 @@ private: // Outgoing network message buffer for active objects std::queue m_active_object_messages; // Some timers - float m_send_recommended_timer; + float m_send_recommended_timer = 0.0f; IntervalLimiter m_object_management_interval; // List of active blocks ActiveBlockList m_active_blocks; IntervalLimiter m_active_blocks_management_interval; IntervalLimiter m_active_block_modifier_interval; IntervalLimiter m_active_blocks_nodemetadata_interval; - int m_active_block_interval_overload_skip; + int m_active_block_interval_overload_skip = 0; // Time from the beginning of the game in seconds. // Incremented in step(). - u32 m_game_time; + u32 m_game_time = 0; // A helper variable for incrementing the latter - float m_game_time_fraction_counter; + float m_game_time_fraction_counter = 0.0f; // Time of last clearObjects call (game time). // When a mapblock older than this is loaded, its objects are cleared. - u32 m_last_clear_objects_time; + u32 m_last_clear_objects_time = 0; // Active block modifiers std::vector m_abms; LBMManager m_lbm_mgr; // An interval for generally sending object positions and stuff - float m_recommended_send_interval; + float m_recommended_send_interval = 0.1f; // Estimate for general maximum lag as determined by server. // Can raise to high values like 15s with eg. map generation mods. - float m_max_lag_estimate; + 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; - PlayerDatabase *m_player_database; + PlayerDatabase *m_player_database = nullptr; // Particles IntervalLimiter m_particle_management_interval; From 8f2e60a9619f3db2dea752626e778f753c0714bc Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Mon, 19 Jun 2017 00:00:55 +0200 Subject: [PATCH 02/53] Client::makeScreenshot: remove device param We already have the device param as class member --- src/client.cpp | 4 ++-- src/client.h | 4 +--- src/game.cpp | 2 +- src/guiFormSpecMenu.cpp | 2 +- src/script/lua_api/l_client.cpp | 2 +- 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index aa6a5d30..9892e08c 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1740,9 +1740,9 @@ float Client::getCurRate() m_con.getLocalStat(con::CUR_DL_RATE)); } -void Client::makeScreenshot(IrrlichtDevice *device) +void Client::makeScreenshot() { - irr::video::IVideoDriver *driver = device->getVideoDriver(); + irr::video::IVideoDriver *driver = m_device->getVideoDriver(); irr::video::IImage* const raw_image = driver->createScreenShot(); if (!raw_image) diff --git a/src/client.h b/src/client.h index 7bfa26c0..ab47cfa4 100644 --- a/src/client.h +++ b/src/client.h @@ -507,7 +507,7 @@ public: LocalClientState getState() { return m_state; } - void makeScreenshot(IrrlichtDevice *device); + void makeScreenshot(); inline void pushToChatQueue(const std::wstring &input) { @@ -529,8 +529,6 @@ public: void showGameFog(const bool show = true); void showGameDebug(const bool show = true); - IrrlichtDevice *getDevice() const { return m_device; } - const Address getServerAddress() { return m_con.GetPeerAddress(PEER_ID_SERVER); diff --git a/src/game.cpp b/src/game.cpp index fc6df462..32555772 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -2524,7 +2524,7 @@ void Game::processKeyInput() } else if (wasKeyDown(KeyType::CINEMATIC)) { toggleCinematic(); } else if (wasKeyDown(KeyType::SCREENSHOT)) { - client->makeScreenshot(device); + client->makeScreenshot(); } else if (wasKeyDown(KeyType::TOGGLE_HUD)) { toggleHud(); } else if (wasKeyDown(KeyType::MINIMAP)) { diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index c6a917d1..d721c917 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -3282,7 +3282,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) return true; } else if (m_client != NULL && event.KeyInput.PressedDown && (kp == getKeySetting("keymap_screenshot"))) { - m_client->makeScreenshot(m_device); + m_client->makeScreenshot(); } if (event.KeyInput.PressedDown && (event.KeyInput.Key==KEY_RETURN || diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index b4dfe917..84eafd3f 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -327,7 +327,7 @@ int ModApiClient::l_get_node_def(lua_State *L) int ModApiClient::l_take_screenshot(lua_State *L) { Client *client = getClient(L); - client->makeScreenshot(client->getDevice()); + client->makeScreenshot(); return 0; } From ea4d407082dd120bb6b3b1e9c869e88f26b001b1 Mon Sep 17 00:00:00 2001 From: paramat Date: Sun, 11 Jun 2017 06:02:20 +0100 Subject: [PATCH 03/53] Mgv7 spawn search: Cope with extreme custom terrain and biome 'dust' Previously, maximum spawn level was set to 'water_level + 16'. This would result in spawn search failing if terrain had been customised to be much higher than 'water_level' at all points. Also raise spawn level by 1 node to avoid spawning half-buried in a biome 'dust' node such as 'default:snowblock'. --- src/mapgen_v7.cpp | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index 2048da1f..ad242ae4 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -202,10 +202,7 @@ void MapgenV7Params::writeParams(Settings *settings) const int MapgenV7::getSpawnLevelAtPoint(v2s16 p) { - // Base terrain calculation - s16 y = baseTerrainLevelAtPoint(p.X, p.Y); - - // If enabled, check if inside a river + // If rivers are enabled, first check if in a river if (spflags & MGV7_RIDGES) { float width = 0.2; float uwatern = NoisePerlin2D(&noise_ridge_uwater->np, p.X, p.Y, seed) * 2; @@ -213,28 +210,41 @@ int MapgenV7::getSpawnLevelAtPoint(v2s16 p) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point } - // If mountains are disabled, terrain level is base terrain level - // Avoids spawn on non-existant mountain terrain + // Terrain noise 'offset' is the average level of that terrain. + // At least 50% of terrain will be below the higher of base and alt terrain + // 'offset's. + // 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 = MYMAX(MYMAX(noise_terrain_alt->np.offset, + noise_terrain_base->np.offset), + water_level + 16); + // Base terrain calculation + s16 y = baseTerrainLevelAtPoint(p.X, p.Y); + + // If mountains are disabled, terrain level is base terrain level. + // Avoids mid-air spawn where mountain terrain would have been. if (!(spflags & MGV7_MOUNTAINS)) { - if (y <= water_level || y > water_level + 16) + if (y <= water_level || y > max_spawn_y) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point else - return y; + // + 1 to not be half-buried in a potential node-deep biome 'dust' + return y + 1; } - // Mountain terrain calculation - int iters = 128; - while (iters--) { + // Search upwards for first node without mountain terrain + int iters = 256; + while (iters > 0 && y <= max_spawn_y) { if (!getMountainTerrainAtPoint(p.X, y + 1, p.Y)) { // If air above - if (y <= water_level || y > water_level + 16) + if (y <= water_level || y > max_spawn_y) return MAX_MAP_GENERATION_LIMIT; // Unsuitable spawn point else - return y; + return y + 1; } y++; + iters--; } - // Unsuitable spawn point, no mountain surface found + // Unsuitable spawn point return MAX_MAP_GENERATION_LIMIT; } From 0c429bd1645d738e721f713429d8ba83c3964b8f Mon Sep 17 00:00:00 2001 From: paramat Date: Sun, 18 Jun 2017 02:11:05 +0100 Subject: [PATCH 04/53] Mgv7: Do not limit river generation if no floatlands Previously, the carving of rivers was disabled above 'shadow_limit' even if floatlands were disabled. This caused rivers to be unnecessarily disabled if mapgen was customised to have surface level above y = 1024. --- src/mapgen_v7.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index ad242ae4..e3922c53 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -519,7 +519,8 @@ int MapgenV7::generateTerrain() void MapgenV7::generateRidgeTerrain() { - if ((node_max.Y < water_level - 16) || (node_max.Y > shadow_limit)) + if (node_max.Y < water_level - 16 || + ((spflags & MGV7_FLOATLANDS) && node_max.Y > shadow_limit)) return; noise_ridge->perlinMap3D(node_min.X, node_min.Y - 1, node_min.Z); From 4dcc5985df4c94705ed7e4932a8b82a6e8c61f58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Mon, 19 Jun 2017 14:10:30 +0200 Subject: [PATCH 05/53] Verify HudSetParams input when hotbar textures are set (#6013) * Verify HudSetParams input when hotbar textures are set This fix #6011 --- src/network/clientpackethandler.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 6d648616..e6f0d709 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -1174,9 +1174,21 @@ void Client::handleCommand_HudSetParam(NetworkPacket* pkt) player->hud_hotbar_itemcount = hotbar_itemcount; } else if (param == HUD_PARAM_HOTBAR_IMAGE) { + // If value not empty verify image exists in texture source + if (value != "" && !getTextureSource()->isKnownSourceImage(value)) { + errorstream << "Server sent wrong Hud hotbar image (sent value: '" + << value << "')" << std::endl; + return; + } player->hotbar_image = value; } else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) { + // If value not empty verify image exists in texture source + if (value != "" && !getTextureSource()->isKnownSourceImage(value)) { + errorstream << "Server sent wrong Hud hotbar selected image (sent value: '" + << value << "')" << std::endl; + return; + } player->hotbar_selected_image = value; } } From 53acc32bee75e6eb8788ab5eb926243648ad191c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Mon, 19 Jun 2017 15:20:30 +0200 Subject: [PATCH 06/53] hud.cpp: fix wrong indent in drawItem --- src/hud.cpp | 140 ++++++++++++++++++++++++++-------------------------- 1 file changed, 70 insertions(+), 70 deletions(-) diff --git a/src/hud.cpp b/src/hud.cpp index b030215d..1b3b2f26 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -120,79 +120,79 @@ 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()); - draw2DImageFilterScaled(driver, texture, imgrect2, - 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); - 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); - driver->draw2DRectangle(c_outside, - 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); - driver->draw2DRectangle(c_outside, - core::rect( - v2s32(x2, y1), - v2s32(x2 + m_padding, y2) - ), NULL); - /*// Light inside borders - driver->draw2DRectangle(c_inside, - core::rect( - v2s32(x1 - padding/2, y1 - padding/2), - v2s32(x2 + padding/2, y1) - ), NULL); - driver->draw2DRectangle(c_inside, - core::rect( - v2s32(x1 - padding/2, y2), - v2s32(x2 + padding/2, y2 + padding/2) - ), NULL); - driver->draw2DRectangle(c_inside, - core::rect( - v2s32(x1 - padding/2, y1), - v2s32(x1, y2) - ), NULL); - driver->draw2DRectangle(c_inside, - core::rect( - v2s32(x2, y1), - v2s32(x2 + padding/2, y2) - ), NULL); - */ - } + /* 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()); + draw2DImageFilterScaled(driver, texture, imgrect2, + 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); + 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); + driver->draw2DRectangle(c_outside, + 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); + driver->draw2DRectangle(c_outside, + core::rect( + v2s32(x2, y1), + v2s32(x2 + m_padding, y2) + ), NULL); + /*// Light inside borders + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x1 - padding/2, y1 - padding/2), + v2s32(x2 + padding/2, y1) + ), NULL); + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x1 - padding/2, y2), + v2s32(x2 + padding/2, y2 + padding/2) + ), NULL); + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x1 - padding/2, y1), + v2s32(x1, y2) + ), NULL); + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x2, y1), + v2s32(x2 + padding/2, y2) + ), NULL); + */ } - - 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); } + 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); +} + //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) From 071736ba3f99c9827af074bed3b3ff84c05e0d51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Mon, 19 Jun 2017 15:41:33 +0200 Subject: [PATCH 07/53] hud.h: add missing false default state on use_hotbar_selected_image --- src/hud.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hud.h b/src/hud.h index 3377337c..dcbedf64 100644 --- a/src/hud.h +++ b/src/hud.h @@ -118,7 +118,7 @@ public: std::string hotbar_image = ""; bool use_hotbar_image = false; std::string hotbar_selected_image = ""; - bool use_hotbar_selected_image; + bool use_hotbar_selected_image = false; Hud(video::IVideoDriver *driver,scene::ISceneManager* smgr, gui::IGUIEnvironment* guienv, Client *client, LocalPlayer *player, From 6eb03c135f17f05d48dd13fe8957bfe0f9654b00 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Mon, 19 Jun 2017 16:30:26 +0200 Subject: [PATCH 08/53] find_nodes_in_area: Extend maximal count to U32_MAX (#5277) Extend documentation, limit area volume Remove u16 count limitation * Prevent integer overflow, replace minp/maxp with pos1/pos2 --- doc/lua_api.txt | 9 +++--- src/script/lua_api/l_env.cpp | 62 +++++++++++++++++++++++++----------- 2 files changed, 49 insertions(+), 22 deletions(-) diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 28067eef..a3413221 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -2465,12 +2465,13 @@ and `minetest.auth_reload` call the authetification handler. * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"` * `search_center` is an optional boolean (default: `false`) If true `pos` is also checked for the nodes -* `minetest.find_nodes_in_area(minp, maxp, nodenames)`: returns a list of positions - * returns as second value a table with the count of the individual nodes found +* `minetest.find_nodes_in_area(pos1, pos2, nodenames)`: returns a list of positions * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"` -* `minetest.find_nodes_in_area_under_air(minp, maxp, nodenames)`: returns a list of positions - * returned positions are nodes with a node air above + * First return value: Table with all node positions + * Second return value: Table with the count of each node with the node name as index +* `minetest.find_nodes_in_area_under_air(pos1, pos2, nodenames)`: returns a list of positions * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"` + * Return value: Table with all node positions with a node air above * `minetest.get_perlin(noiseparams)` * `minetest.get_perlin(seeddiff, octaves, persistence, scale)` * Return world-specific perlin noise (`int(worldseed)+seeddiff`) diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index b8b6bc5b..e7284b03 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -651,38 +651,51 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) INodeDefManager *ndef = getServer(L)->ndef(); v3s16 minp = read_v3s16(L, 1); v3s16 maxp = read_v3s16(L, 2); + sortBoxVerticies(minp, maxp); + + v3s16 cube = maxp - minp + 1; + + /* Limit for too large areas, assume default values + * and give tolerances of 1 node on each side + * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368 + */ + if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) { + luaL_error(L, "find_nodes_in_area(): area volume" + " exceeds allowed value of 551368"); + return 0; + } + std::set filter; - if(lua_istable(L, 3)) { - int table = 3; + if (lua_istable(L, 3)) { lua_pushnil(L); - while(lua_next(L, table) != 0) { + while (lua_next(L, 3) != 0) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); ndef->getIds(lua_tostring(L, -1), filter); // removes value, keeps key for next iteration lua_pop(L, 1); } - } else if(lua_isstring(L, 3)) { + } else if (lua_isstring(L, 3)) { ndef->getIds(lua_tostring(L, 3), filter); } - std::map individual_count; + std::unordered_map individual_count; lua_newtable(L); u64 i = 0; for (s16 x = minp.X; x <= maxp.X; x++) - for (s16 y = minp.Y; y <= maxp.Y; y++) - for (s16 z = minp.Z; z <= maxp.Z; z++) { - v3s16 p(x, y, z); - content_t c = env->getMap().getNodeNoEx(p).getContent(); - if (filter.count(c) != 0) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - individual_count[c]++; - } + for (s16 y = minp.Y; y <= maxp.Y; y++) + for (s16 z = minp.Z; z <= maxp.Z; z++) { + v3s16 p(x, y, z); + content_t c = env->getMap().getNodeNoEx(p).getContent(); + if (filter.count(c) != 0) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); + individual_count[c]++; + } } lua_newtable(L); - for (std::set::iterator it = filter.begin(); + for (std::set::const_iterator it = filter.begin(); it != filter.end(); ++it) { lua_pushnumber(L, individual_count[*it]); lua_setfield(L, -2, ndef->get(*it).name.c_str()); @@ -706,12 +719,25 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) INodeDefManager *ndef = getServer(L)->ndef(); v3s16 minp = read_v3s16(L, 1); v3s16 maxp = read_v3s16(L, 2); + sortBoxVerticies(minp, maxp); + + v3s16 cube = maxp - minp + 1; + + /* Limit for too large areas, assume default values + * and give tolerances of 1 node on each side + * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368 + */ + if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) { + luaL_error(L, "find_nodes_in_area_under_air(): area volume" + " exceeds allowed value of 551368"); + return 0; + } + std::set filter; if (lua_istable(L, 3)) { - int table = 3; lua_pushnil(L); - while(lua_next(L, table) != 0) { + while (lua_next(L, 3) != 0) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); ndef->getIds(lua_tostring(L, -1), filter); @@ -732,7 +758,7 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) for (; y <= maxp.Y; y++) { v3s16 psurf(x, y + 1, z); content_t csurf = env->getMap().getNodeNoEx(psurf).getContent(); - if(c != CONTENT_AIR && csurf == CONTENT_AIR && + if (c != CONTENT_AIR && csurf == CONTENT_AIR && filter.count(c) != 0) { push_v3s16(L, v3s16(x, y, z)); lua_rawseti(L, -2, ++i); From 4a789490834157baa8788a2f36c95b86c1e4440e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Mon, 19 Jun 2017 16:49:34 +0200 Subject: [PATCH 09/53] Remove IrrlichtDevice unused pointer from ClientActiveObject class & childs (#6010) --- src/clientenvironment.cpp | 2 +- src/clientobject.h | 5 ++--- src/content_cao.cpp | 20 +++++++------------- src/content_cao.h | 4 +--- 4 files changed, 11 insertions(+), 20 deletions(-) diff --git a/src/clientenvironment.cpp b/src/clientenvironment.cpp index 2a761ee1..e6b27308 100644 --- a/src/clientenvironment.cpp +++ b/src/clientenvironment.cpp @@ -458,7 +458,7 @@ u16 ClientEnvironment::addActiveObject(ClientActiveObject *object) infostream<<"ClientEnvironment::addActiveObject(): " <<"added (id="<getId()<<")"<getId()] = object; - object->addToScene(m_smgr, m_texturesource, m_irr); + object->addToScene(m_smgr, m_texturesource); { // Update lighting immediately u8 light = 0; bool pos_ok; diff --git a/src/clientobject.h b/src/clientobject.h index a3eb3e24..d81e8e7e 100644 --- a/src/clientobject.h +++ b/src/clientobject.h @@ -39,9 +39,8 @@ public: ClientActiveObject(u16 id, Client *client, ClientEnvironment *env); virtual ~ClientActiveObject(); - virtual void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc, - IrrlichtDevice *irr){} - virtual void removeFromScene(bool permanent){} + virtual void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc) {}; + virtual void removeFromScene(bool permanent) {} // 0 <= light_at_pos <= LIGHT_SUN virtual void updateLight(u8 light_at_pos){} virtual void updateLightNoCheck(u8 light_at_pos){} diff --git a/src/content_cao.cpp b/src/content_cao.cpp index ac7b48e0..e0ebc5fa 100644 --- a/src/content_cao.cpp +++ b/src/content_cao.cpp @@ -128,8 +128,7 @@ public: static ClientActiveObject* create(Client *client, ClientEnvironment *env); - void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc, - IrrlichtDevice *irr); + void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc); void removeFromScene(bool permanent); void updateLight(u8 light_at_pos); v3s16 getLightPosition(); @@ -165,8 +164,7 @@ ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env) return new TestCAO(client, env); } -void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc, - IrrlichtDevice *irr) +void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc) { if(m_node != NULL) return; @@ -272,8 +270,7 @@ public: static ClientActiveObject* create(Client *client, ClientEnvironment *env); - void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc, - IrrlichtDevice *irr); + void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc); void removeFromScene(bool permanent); void updateLight(u8 light_at_pos); v3s16 getLightPosition(); @@ -329,8 +326,7 @@ ClientActiveObject* ItemCAO::create(Client *client, ClientEnvironment *env) return new ItemCAO(client, env); } -void ItemCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc, - IrrlichtDevice *irr) +void ItemCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc) { if(m_node != NULL) return; @@ -721,11 +717,9 @@ void GenericCAO::removeFromScene(bool permanent) } } -void GenericCAO::addToScene(scene::ISceneManager *smgr, - ITextureSource *tsrc, IrrlichtDevice *irr) +void GenericCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc) { m_smgr = smgr; - m_irr = irr; if (getSceneNode() != NULL) { return; @@ -1034,7 +1028,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) } } - if(m_visuals_expired && m_smgr && m_irr){ + if (m_visuals_expired && m_smgr) { m_visuals_expired = false; // Attachments, part 1: All attached objects must be unparented first, @@ -1056,7 +1050,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) } removeFromScene(false); - addToScene(m_smgr, m_client->tsrc(), m_irr); + addToScene(m_smgr, m_client->tsrc()); // Attachments, part 2: Now that the parent has been refreshed, put its attachments back for (std::vector::size_type i = 0; i < m_children.size(); i++) { diff --git a/src/content_cao.h b/src/content_cao.h index e353b71d..66d5ca3f 100644 --- a/src/content_cao.h +++ b/src/content_cao.h @@ -65,7 +65,6 @@ private: ObjectProperties m_prop; // scene::ISceneManager *m_smgr = nullptr; - IrrlichtDevice *m_irr = nullptr; Client *m_client = nullptr; aabb3f m_selection_box = aabb3f(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.); scene::IMeshSceneNode *m_meshnode = nullptr; @@ -169,8 +168,7 @@ public: void removeFromScene(bool permanent); - void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc, - IrrlichtDevice *irr); + void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc); inline void expireVisuals() { From 4a5e8ad343079f6552fab639770e5771ed7c4e7a Mon Sep 17 00:00:00 2001 From: Vincent Glize Date: Mon, 19 Jun 2017 23:54:58 +0200 Subject: [PATCH 10/53] C++11 cleanup on constructors (#6000) * C++11 cleanup on constructors dir script --- src/script/cpp_api/s_async.cpp | 7 ------ src/script/cpp_api/s_async.h | 26 ++++++++------------- src/script/cpp_api/s_base.cpp | 12 +--------- src/script/cpp_api/s_base.h | 10 ++++---- src/script/lua_api/l_areastore.cpp | 7 +++--- src/script/lua_api/l_areastore.h | 2 +- src/script/lua_api/l_camera.cpp | 3 +-- src/script/lua_api/l_camera.h | 2 +- src/script/lua_api/l_itemstackmeta.h | 2 +- src/script/lua_api/l_localplayer.cpp | 3 +-- src/script/lua_api/l_localplayer.h | 2 +- src/script/lua_api/l_minimap.cpp | 3 +-- src/script/lua_api/l_minimap.h | 2 +- src/script/lua_api/l_nodemeta.cpp | 6 ++--- src/script/lua_api/l_nodemeta.h | 6 ++--- src/script/lua_api/l_nodetimer.h | 2 +- src/script/lua_api/l_object.h | 35 ++++++++++++++-------------- src/script/lua_api/l_settings.cpp | 4 +--- src/script/lua_api/l_settings.h | 6 ++--- src/script/lua_api/l_storage.h | 2 +- src/script/lua_api/l_vmanip.cpp | 11 +++------ src/script/lua_api/l_vmanip.h | 4 ++-- src/threading/thread.cpp | 6 ++--- src/threading/thread.h | 4 ++-- src/unittest/test.cpp | 20 ++++++++-------- src/unittest/test_connection.cpp | 11 +++------ src/util/areastore.cpp | 4 ++-- src/util/areastore.h | 25 +++++++++----------- src/util/auth.cpp | 6 ++--- src/util/enriched_string.cpp | 3 +-- src/util/enriched_string.h | 2 +- src/util/numeric.h | 4 ++-- src/util/pointedthing.cpp | 10 -------- src/util/pointedthing.h | 6 ++--- src/util/serialize.cpp | 6 ++--- src/util/serialize.h | 5 ++-- src/util/sha1.cpp | 9 ------- src/util/sha1.h | 10 +++++--- src/util/timetaker.cpp | 3 +-- src/util/timetaker.h | 6 ++--- 40 files changed, 117 insertions(+), 180 deletions(-) diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index 72235906..5cca5fc0 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -33,13 +33,6 @@ extern "C" { #include "porting.h" #include "common/c_internal.h" -/******************************************************************************/ -AsyncEngine::AsyncEngine() : - initDone(false), - jobIdCounter(0) -{ -} - /******************************************************************************/ AsyncEngine::~AsyncEngine() { diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index 45f935d0..94b55db6 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -39,24 +39,18 @@ class AsyncEngine; // Data required to queue a job struct LuaJobInfo { - LuaJobInfo() : - serializedFunction(""), - serializedParams(""), - serializedResult(""), - id(0), - valid(false) - {} + LuaJobInfo() {}; // Function to be called in async environment - std::string serializedFunction; + std::string serializedFunction = ""; // Parameter to be passed to function - std::string serializedParams; + std::string serializedParams = ""; // Result of function call - std::string serializedResult; + std::string serializedResult = ""; // JobID used to identify a job and match it to callback - unsigned int id; + unsigned int id = 0; - bool valid; + bool valid = false; }; // Asynchronous working environment @@ -68,7 +62,7 @@ public: void *run(); private: - AsyncEngine *jobDispatcher; + AsyncEngine *jobDispatcher = nullptr; }; // Asynchornous thread and job management @@ -76,7 +70,7 @@ class AsyncEngine { friend class AsyncWorkerThread; typedef void (*StateInitializer)(lua_State *L, int top); public: - AsyncEngine(); + AsyncEngine() {}; ~AsyncEngine(); /** @@ -137,13 +131,13 @@ protected: private: // Variable locking the engine against further modification - bool initDone; + bool initDone = false; // Internal store for registred state initializers std::vector stateInitializers; // Internal counter to create job IDs - unsigned int jobIdCounter; + unsigned int jobIdCounter = 0; // Mutex to protect job queue std::mutex jobQueueMutex; diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index 4d7461c5..aaf26a9c 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -71,9 +71,7 @@ public: ScriptApiBase */ -ScriptApiBase::ScriptApiBase() : - m_luastackmutex(), - m_gamedef(NULL) +ScriptApiBase::ScriptApiBase() { #ifdef SCRIPTAPI_LOCK_DEBUG m_lock_recursion_count = 0; @@ -111,14 +109,6 @@ ScriptApiBase::ScriptApiBase() : lua_pushstring(m_luastack, porting::getPlatformName()); lua_setglobal(m_luastack, "PLATFORM"); - - // m_secure gets set to true inside - // ScriptApiSecurity::initializeSecurity(), if neccessary. - // Default to false otherwise - m_secure = false; - - m_environment = NULL; - m_guiengine = NULL; } ScriptApiBase::~ScriptApiBase() diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index ed056db3..38ee9901 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -119,7 +119,7 @@ protected: std::recursive_mutex m_luastackmutex; std::string m_last_run_mod; - bool m_secure; + bool m_secure = false; #ifdef SCRIPTAPI_LOCK_DEBUG int m_lock_recursion_count; std::thread::id m_owning_thread; @@ -128,11 +128,11 @@ protected: private: static int luaPanic(lua_State *L); - lua_State* m_luastack; + lua_State *m_luastack = nullptr; - IGameDef* m_gamedef; - Environment* m_environment; - GUIEngine* m_guiengine; + IGameDef *m_gamedef = nullptr; + Environment *m_environment = nullptr; + GUIEngine *m_guiengine = nullptr; }; #endif /* S_BASE_H_ */ diff --git a/src/script/lua_api/l_areastore.cpp b/src/script/lua_api/l_areastore.cpp index b81985a7..1e30e704 100644 --- a/src/script/lua_api/l_areastore.cpp +++ b/src/script/lua_api/l_areastore.cpp @@ -300,20 +300,19 @@ int LuaAreaStore::l_from_file(lua_State *L) return deserialization_helper(L, o->as, is); } -LuaAreaStore::LuaAreaStore() +LuaAreaStore::LuaAreaStore() : as(AreaStore::getOptimalImplementation()) { - this->as = AreaStore::getOptimalImplementation(); } LuaAreaStore::LuaAreaStore(const std::string &type) { #if USE_SPATIAL if (type == "LibSpatial") { - this->as = new SpatialAreaStore(); + as = new SpatialAreaStore(); } else #endif { - this->as = new VectorAreaStore(); + as = new VectorAreaStore(); } } diff --git a/src/script/lua_api/l_areastore.h b/src/script/lua_api/l_areastore.h index 8292e771..9cb6249d 100644 --- a/src/script/lua_api/l_areastore.h +++ b/src/script/lua_api/l_areastore.h @@ -49,7 +49,7 @@ private: static int l_from_file(lua_State *L); public: - AreaStore *as; + AreaStore *as = nullptr; LuaAreaStore(); LuaAreaStore(const std::string &type); diff --git a/src/script/lua_api/l_camera.cpp b/src/script/lua_api/l_camera.cpp index 86238419..ef842a22 100644 --- a/src/script/lua_api/l_camera.cpp +++ b/src/script/lua_api/l_camera.cpp @@ -4,9 +4,8 @@ #include "content_cao.h" #include "camera.h" -LuaCamera::LuaCamera(Camera *m) +LuaCamera::LuaCamera(Camera *m) : m_camera(m) { - m_camera = m; } void LuaCamera::create(lua_State *L, Camera *m) diff --git a/src/script/lua_api/l_camera.h b/src/script/lua_api/l_camera.h index 04921ad0..c4a0f877 100644 --- a/src/script/lua_api/l_camera.h +++ b/src/script/lua_api/l_camera.h @@ -26,7 +26,7 @@ private: static int l_get_look_horizontal(lua_State *L); static int l_get_aspect_ratio(lua_State *L); - Camera *m_camera; + Camera *m_camera = nullptr; public: LuaCamera(Camera *m); diff --git a/src/script/lua_api/l_itemstackmeta.h b/src/script/lua_api/l_itemstackmeta.h index 4ef64a91..6e841d2d 100644 --- a/src/script/lua_api/l_itemstackmeta.h +++ b/src/script/lua_api/l_itemstackmeta.h @@ -28,7 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class ItemStackMetaRef : public MetaDataRef { private: - ItemStack *istack; + ItemStack *istack = nullptr; static const char className[]; static const luaL_Reg methods[]; diff --git a/src/script/lua_api/l_localplayer.cpp b/src/script/lua_api/l_localplayer.cpp index 7ec4eaa6..7f932cbc 100644 --- a/src/script/lua_api/l_localplayer.cpp +++ b/src/script/lua_api/l_localplayer.cpp @@ -21,9 +21,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "l_internal.h" #include "script/common/c_converter.h" -LuaLocalPlayer::LuaLocalPlayer(LocalPlayer *m) +LuaLocalPlayer::LuaLocalPlayer(LocalPlayer *m) : m_localplayer(m) { - m_localplayer = m; } void LuaLocalPlayer::create(lua_State *L, LocalPlayer *m) diff --git a/src/script/lua_api/l_localplayer.h b/src/script/lua_api/l_localplayer.h index e56ec808..e618e6be 100644 --- a/src/script/lua_api/l_localplayer.h +++ b/src/script/lua_api/l_localplayer.h @@ -67,7 +67,7 @@ private: static int l_get_movement(lua_State *L); - LocalPlayer *m_localplayer; + LocalPlayer *m_localplayer = nullptr; public: LuaLocalPlayer(LocalPlayer *m); diff --git a/src/script/lua_api/l_minimap.cpp b/src/script/lua_api/l_minimap.cpp index afb3766f..be981c88 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -24,9 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "minimap.h" #include "settings.h" -LuaMinimap::LuaMinimap(Minimap *m) +LuaMinimap::LuaMinimap(Minimap *m) : m_minimap(m) { - m_minimap = m; } void LuaMinimap::create(lua_State *L, Minimap *m) diff --git a/src/script/lua_api/l_minimap.h b/src/script/lua_api/l_minimap.h index ba702b0b..d4fbf633 100644 --- a/src/script/lua_api/l_minimap.h +++ b/src/script/lua_api/l_minimap.h @@ -48,7 +48,7 @@ private: static int l_set_shape(lua_State *L); static int l_get_shape(lua_State *L); - Minimap *m_minimap; + Minimap *m_minimap = nullptr; public: LuaMinimap(Minimap *m); diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index 5dfa6d52..aa8d1c45 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -171,14 +171,12 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env): m_p(p), - m_env(env), - m_is_local(false) + m_env(env) { } NodeMetaRef::NodeMetaRef(Metadata *meta): - m_meta(meta), - m_is_local(true) + m_meta(meta) { } diff --git a/src/script/lua_api/l_nodemeta.h b/src/script/lua_api/l_nodemeta.h index dd4260ff..72d26ef3 100644 --- a/src/script/lua_api/l_nodemeta.h +++ b/src/script/lua_api/l_nodemeta.h @@ -34,9 +34,9 @@ class NodeMetadata; class NodeMetaRef : public MetaDataRef { private: v3s16 m_p; - ServerEnvironment *m_env; - Metadata *m_meta; - bool m_is_local; + ServerEnvironment *m_env = nullptr; + Metadata *m_meta = nullptr; + bool m_is_local = false; static const char className[]; static const luaL_Reg methodsServer[]; diff --git a/src/script/lua_api/l_nodetimer.h b/src/script/lua_api/l_nodetimer.h index ae362d8b..df77ed98 100644 --- a/src/script/lua_api/l_nodetimer.h +++ b/src/script/lua_api/l_nodetimer.h @@ -29,7 +29,7 @@ class NodeTimerRef : public ModApiBase { private: v3s16 m_p; - ServerEnvironment *m_env; + ServerEnvironment *m_env = nullptr; static const char className[]; static const luaL_Reg methods[]; diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index 9801ce02..77874f00 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -33,16 +33,29 @@ class RemotePlayer; */ class ObjectRef : public ModApiBase { -private: - ServerActiveObject *m_object; - - static const char className[]; - static const luaL_Reg methods[]; public: + ObjectRef(ServerActiveObject *object); + + ~ObjectRef(); + + // Creates an ObjectRef and leaves it on top of stack + // Not callable from Lua; all references are created on the C side. + static void create(lua_State *L, ServerActiveObject *object); + + static void set_null(lua_State *L); + + static void Register(lua_State *L); + static ObjectRef *checkobject(lua_State *L, int narg); static ServerActiveObject* getobject(ObjectRef *ref); private: + ServerActiveObject *m_object = nullptr; + + static const char className[]; + static const luaL_Reg methods[]; + + static LuaEntitySAO* getluaobject(ObjectRef *ref); static PlayerSAO* getplayersao(ObjectRef *ref); @@ -319,18 +332,6 @@ private: // get_nametag_attributes(self) static int l_get_nametag_attributes(lua_State *L); -public: - ObjectRef(ServerActiveObject *object); - - ~ObjectRef(); - - // Creates an ObjectRef and leaves it on top of stack - // Not callable from Lua; all references are created on the C side. - static void create(lua_State *L, ServerActiveObject *object); - - static void set_null(lua_State *L); - - static void Register(lua_State *L); }; #endif /* L_OBJECT_H_ */ diff --git a/src/script/lua_api/l_settings.cpp b/src/script/lua_api/l_settings.cpp index 70807f3d..3dc5c957 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -32,9 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc., LuaSettings::LuaSettings(Settings *settings, const std::string &filename) : m_settings(settings), - m_filename(filename), - m_is_own_settings(false), - m_write_allowed(true) + m_filename(filename) { } diff --git a/src/script/lua_api/l_settings.h b/src/script/lua_api/l_settings.h index 54b003ab..a664b449 100644 --- a/src/script/lua_api/l_settings.h +++ b/src/script/lua_api/l_settings.h @@ -57,10 +57,10 @@ private: // to_table(self) -> {[key1]=value1,...} static int l_to_table(lua_State *L); - Settings *m_settings; + Settings *m_settings = nullptr; std::string m_filename; - bool m_is_own_settings; - bool m_write_allowed; + bool m_is_own_settings = false; + bool m_write_allowed = true; public: LuaSettings(Settings *settings, const std::string &filename); diff --git a/src/script/lua_api/l_storage.h b/src/script/lua_api/l_storage.h index ec6f8d94..eaf7ec9f 100644 --- a/src/script/lua_api/l_storage.h +++ b/src/script/lua_api/l_storage.h @@ -38,7 +38,7 @@ public: class StorageRef : public MetaDataRef { private: - ModMetadata *m_object; + ModMetadata *m_object = nullptr; static const char className[]; static const luaL_Reg methods[]; diff --git a/src/script/lua_api/l_vmanip.cpp b/src/script/lua_api/l_vmanip.cpp index 254a7e5a..ed5042bc 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -365,22 +365,17 @@ int LuaVoxelManip::l_get_emerged_area(lua_State *L) return 2; } -LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) +LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : vm(mmvm), is_mapgen_vm(is_mg_vm) { - this->vm = mmvm; - this->is_mapgen_vm = is_mg_vm; } -LuaVoxelManip::LuaVoxelManip(Map *map) +LuaVoxelManip::LuaVoxelManip(Map *map) : vm(new MMVManip(map)) { - this->vm = new MMVManip(map); - this->is_mapgen_vm = false; } LuaVoxelManip::LuaVoxelManip(Map *map, v3s16 p1, v3s16 p2) { - this->vm = new MMVManip(map); - this->is_mapgen_vm = false; + vm = new MMVManip(map); v3s16 bp1 = getNodeBlockPos(p1); v3s16 bp2 = getNodeBlockPos(p2); diff --git a/src/script/lua_api/l_vmanip.h b/src/script/lua_api/l_vmanip.h index b6a69f36..e706f372 100644 --- a/src/script/lua_api/l_vmanip.h +++ b/src/script/lua_api/l_vmanip.h @@ -35,7 +35,7 @@ class LuaVoxelManip : public ModApiBase { private: std::map modified_blocks; - bool is_mapgen_vm; + bool is_mapgen_vm = false; static const char className[]; static const luaL_Reg methods[]; @@ -65,7 +65,7 @@ private: static int l_get_emerged_area(lua_State *L); public: - MMVManip *vm; + MMVManip *vm = nullptr; LuaVoxelManip(MMVManip *mmvm, bool is_mapgen_vm); LuaVoxelManip(Map *map, v3s16 p1, v3s16 p2); diff --git a/src/threading/thread.cpp b/src/threading/thread.cpp index cc4d6565..8f54fb76 100644 --- a/src/threading/thread.cpp +++ b/src/threading/thread.cpp @@ -60,8 +60,6 @@ DEALINGS IN THE SOFTWARE. Thread::Thread(const std::string &name) : m_name(name), - m_retval(NULL), - m_joinable(false), m_request_stop(false), m_running(false) { @@ -130,7 +128,7 @@ bool Thread::wait() m_thread_obj->join(); delete m_thread_obj; - m_thread_obj = NULL; + m_thread_obj = nullptr; assert(m_running == false); m_joinable = false; @@ -162,7 +160,7 @@ bool Thread::kill() wait(); #endif - m_retval = NULL; + m_retval = nullptr; m_joinable = false; m_request_stop = false; diff --git a/src/threading/thread.h b/src/threading/thread.h index 284c8e46..dab5d0ec 100644 --- a/src/threading/thread.h +++ b/src/threading/thread.h @@ -145,8 +145,8 @@ private: static void threadProc(Thread *thr); - void *m_retval; - bool m_joinable; + void *m_retval = nullptr; + bool m_joinable = false; std::atomic m_request_stop; std::atomic m_running; std::mutex m_mutex; diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 570807ba..911b647f 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -70,16 +70,16 @@ public: virtual void unregisterModStorage(const std::string &name) {} private: - IItemDefManager *m_itemdef; - INodeDefManager *m_nodedef; - ICraftDefManager *m_craftdef; - ITextureSource *m_texturesrc; - IShaderSource *m_shadersrc; - ISoundManager *m_soundmgr; - MtEventManager *m_eventmgr; - scene::ISceneManager *m_scenemgr; - IRollbackManager *m_rollbackmgr; - EmergeManager *m_emergemgr; + IItemDefManager *m_itemdef = nullptr; + INodeDefManager *m_nodedef = nullptr; + ICraftDefManager *m_craftdef = nullptr; + ITextureSource *m_texturesrc = nullptr; + IShaderSource *m_shadersrc = nullptr; + ISoundManager *m_soundmgr = nullptr; + MtEventManager *m_eventmgr = nullptr; + scene::ISceneManager *m_scenemgr = nullptr; + IRollbackManager *m_rollbackmgr = nullptr; + EmergeManager *m_emergemgr = nullptr; }; diff --git a/src/unittest/test_connection.cpp b/src/unittest/test_connection.cpp index d63322d6..3ea3d744 100644 --- a/src/unittest/test_connection.cpp +++ b/src/unittest/test_connection.cpp @@ -53,12 +53,7 @@ void TestConnection::runTests(IGameDef *gamedef) struct Handler : public con::PeerHandler { - Handler(const char *a_name) - { - count = 0; - last_id = 0; - name = a_name; - } + Handler(const char *a_name) : name(a_name) {} void peerAdded(con::Peer *peer) { @@ -76,8 +71,8 @@ struct Handler : public con::PeerHandler count--; } - s32 count; - u16 last_id; + s32 count = 0; + u16 last_id = 0; const char *name; }; diff --git a/src/util/areastore.cpp b/src/util/areastore.cpp index cef67da2..c660502f 100644 --- a/src/util/areastore.cpp +++ b/src/util/areastore.cpp @@ -58,7 +58,7 @@ const Area *AreaStore::getArea(u32 id) const { AreaMap::const_iterator it = areas_map.find(id); if (it == areas_map.end()) - return NULL; + return nullptr; return &it->second; } @@ -239,7 +239,7 @@ bool SpatialAreaStore::insertArea(Area *a) if (!areas_map.insert(std::make_pair(a->id, *a)).second) // ID is not unique return false; - m_tree->insertData(0, NULL, get_spatial_region(a->minedge, a->maxedge), a->id); + m_tree->insertData(0, nullptr, get_spatial_region(a->minedge, a->maxedge), a->id); invalidateCache(); return true; } diff --git a/src/util/areastore.h b/src/util/areastore.h index bebecfd7..8c22c3ad 100644 --- a/src/util/areastore.h +++ b/src/util/areastore.h @@ -38,14 +38,14 @@ with this program; if not, write to the Free Software Foundation, Inc., struct Area { - Area() : id(U32_MAX) {} + Area() {} Area(const v3s16 &mine, const v3s16 &maxe) : - id(U32_MAX), minedge(mine), maxedge(maxe) + minedge(mine), maxedge(maxe) { sortBoxVerticies(minedge, maxedge); } - u32 id; + u32 id = U32_MAX; v3s16 minedge, maxedge; std::string data; }; @@ -54,10 +54,7 @@ struct Area { class AreaStore { public: AreaStore() : - m_cache_enabled(true), - m_cacheblock_radius(64), - m_res_cache(1000, &cacheMiss, this), - m_next_id(0) + m_res_cache(1000, &cacheMiss, this) {} virtual ~AreaStore() {} @@ -123,13 +120,13 @@ private: /// Called by the cache when a value isn't found in the cache. static void cacheMiss(void *data, const v3s16 &mpos, std::vector *dest); - bool m_cache_enabled; + bool m_cache_enabled = true; /// Range, in nodes, of the getAreasForPos cache. /// If you modify this, call invalidateCache() - u8 m_cacheblock_radius; + u8 m_cacheblock_radius = 64; LRUCache > m_res_cache; - u32 m_next_id; + u32 m_next_id = 0; }; @@ -165,8 +162,8 @@ protected: virtual void getAreasForPosImpl(std::vector *result, v3s16 pos); private: - SpatialIndex::ISpatialIndex *m_tree; - SpatialIndex::IStorageManager *m_storagemanager; + SpatialIndex::ISpatialIndex *m_tree = nullptr; + SpatialIndex::IStorageManager *m_storagemanager = nullptr; class VectorResultVisitor : public SpatialIndex::IVisitor { public: @@ -194,8 +191,8 @@ private: } private: - SpatialAreaStore *m_store; - std::vector *m_result; + SpatialAreaStore *m_store = nullptr; + std::vector *m_result = nullptr; }; }; diff --git a/src/util/auth.cpp b/src/util/auth.cpp index 91298725..c329e36e 100644 --- a/src/util/auth.cpp +++ b/src/util/auth.cpp @@ -71,7 +71,7 @@ std::string generate_srp_verifier(const std::string &name, // get modified if &salt_ptr isn't NULL. char *salt_ptr = (char *)salt.c_str(); - char *bytes_v = NULL; + char *bytes_v = nullptr; size_t verifier_len = 0; gen_srp_v(name, password, &salt_ptr, &salt_len, &bytes_v, &verifier_len); std::string verifier = std::string(bytes_v, verifier_len); @@ -84,9 +84,9 @@ void generate_srp_verifier_and_salt(const std::string &name, const std::string &password, std::string *verifier, std::string *salt) { - char *bytes_v = NULL; + char *bytes_v = nullptr; size_t verifier_len; - char *salt_ptr = NULL; + char *salt_ptr = nullptr; size_t salt_len; gen_srp_v(name, password, &salt_ptr, &salt_len, &bytes_v, &verifier_len); *verifier = std::string(bytes_v, verifier_len); diff --git a/src/util/enriched_string.cpp b/src/util/enriched_string.cpp index a7fc3a82..05d7b8c2 100644 --- a/src/util/enriched_string.cpp +++ b/src/util/enriched_string.cpp @@ -30,8 +30,7 @@ EnrichedString::EnrichedString() EnrichedString::EnrichedString(const std::wstring &string, const std::vector &colors): m_string(string), - m_colors(colors), - m_has_background(false) + m_colors(colors) {} EnrichedString::EnrichedString(const std::wstring &s, const SColor &color) diff --git a/src/util/enriched_string.h b/src/util/enriched_string.h index 1aca8948..a3b8feb2 100644 --- a/src/util/enriched_string.h +++ b/src/util/enriched_string.h @@ -84,7 +84,7 @@ public: private: std::wstring m_string; std::vector m_colors; - bool m_has_background; + bool m_has_background = false; irr::video::SColor m_background; }; diff --git a/src/util/numeric.h b/src/util/numeric.h index 3b1b85f6..5143c92e 100644 --- a/src/util/numeric.h +++ b/src/util/numeric.h @@ -282,7 +282,7 @@ inline aabb3f getNodeBox(v3s16 p, float d) class IntervalLimiter { public: - IntervalLimiter() : m_accumulator(0) {} + IntervalLimiter() {} /* dtime: time from last call to this method wanted_interval: interval wanted @@ -300,7 +300,7 @@ public: } private: - float m_accumulator; + float m_accumulator = 0.0f; }; diff --git a/src/util/pointedthing.cpp b/src/util/pointedthing.cpp index ed3d4bb6..f1f1d3f2 100644 --- a/src/util/pointedthing.cpp +++ b/src/util/pointedthing.cpp @@ -23,16 +23,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../exceptions.h" #include -PointedThing::PointedThing(): - type(POINTEDTHING_NOTHING), - node_undersurface(0,0,0), - node_abovesurface(0,0,0), - node_real_undersurface(0,0,0), - intersection_point(0,0,0), - intersection_normal(0,0,0), - object_id(-1) -{} - std::string PointedThing::dump() const { std::ostringstream os(std::ios::binary); diff --git a/src/util/pointedthing.h b/src/util/pointedthing.h index f695a4eb..92c33968 100644 --- a/src/util/pointedthing.h +++ b/src/util/pointedthing.h @@ -36,7 +36,7 @@ enum PointedThingType struct PointedThing { //! The type of the pointed object. - PointedThingType type; + PointedThingType type = POINTEDTHING_NOTHING; /*! * Only valid if type is POINTEDTHING_NODE. * The coordinates of the node which owns the @@ -74,9 +74,9 @@ struct PointedThing * Only valid if type is POINTEDTHING_OBJECT. * The ID of the object the ray hit. */ - s16 object_id; + s16 object_id = -1; - PointedThing(); + PointedThing() {}; std::string dump() const; void serialize(std::ostream &os) const; void deSerialize(std::istream &is); diff --git a/src/util/serialize.cpp b/src/util/serialize.cpp index 61d369bc..75843cb1 100644 --- a/src/util/serialize.cpp +++ b/src/util/serialize.cpp @@ -422,7 +422,7 @@ bool deSerializeStringToStruct(std::string valstr, char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos)) && s) { - fmt = NULL; + fmt = nullptr; bool is_unsigned = false; int width = 0; @@ -510,7 +510,7 @@ bool deSerializeStringToStruct(std::string valstr, bufpos += sizeof(std::string *); strs_alloced.push_back(str); - s = *snext ? snext + 1 : NULL; + s = *snext ? snext + 1 : nullptr; break; case 'v': while (*s == ' ' || *s == '\t') @@ -582,7 +582,7 @@ bool serializeStructToString(std::string *out, char *bufpos = (char *) value; char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos))) { - fmt = NULL; + fmt = nullptr; bool is_unsigned = false; int width = 0; char valtype = *f; diff --git a/src/util/serialize.h b/src/util/serialize.h index e2243419..f4348055 100644 --- a/src/util/serialize.h +++ b/src/util/serialize.h @@ -454,8 +454,7 @@ class BufReader { public: BufReader(const u8 *data_, size_t size_) : data(data_), - size(size_), - pos(0) + size(size_) { } @@ -515,7 +514,7 @@ public: const u8 *data; size_t size; - size_t pos; + size_t pos = 0; }; #undef MAKE_BUFREADER_GET_FXN diff --git a/src/util/sha1.cpp b/src/util/sha1.cpp index 6ed7385d..c04b6c0c 100644 --- a/src/util/sha1.cpp +++ b/src/util/sha1.cpp @@ -66,15 +66,6 @@ SHA1::SHA1() { // make sure that the data type is the right size assert( sizeof( Uint32 ) * 5 == 20 ); - - // initialize - H0 = 0x67452301; - H1 = 0xefcdab89; - H2 = 0x98badcfe; - H3 = 0x10325476; - H4 = 0xc3d2e1f0; - unprocessedBytes = 0; - size = 0; } // Destructor ******************************************************** diff --git a/src/util/sha1.h b/src/util/sha1.h index 0ac08c67..a55f94f4 100644 --- a/src/util/sha1.h +++ b/src/util/sha1.h @@ -31,10 +31,14 @@ class SHA1 { private: // fields - Uint32 H0, H1, H2, H3, H4; + Uint32 H0 = 0x67452301; + Uint32 H1 = 0xefcdab89; + Uint32 H2 = 0x98badcfe; + Uint32 H3 = 0x10325476; + Uint32 H4 = 0xc3d2e1f0; unsigned char bytes[64]; - int unprocessedBytes; - Uint32 size; + int unprocessedBytes = 0; + Uint32 size = 0; void process(); public: diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index ac686c3a..6079e5cc 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -27,7 +27,6 @@ TimeTaker::TimeTaker(const std::string &name, u64 *result, TimePrecision prec) { m_name = name; m_result = result; - m_running = true; m_precision = prec; m_time1 = porting::getTime(prec); } @@ -36,7 +35,7 @@ u64 TimeTaker::stop(bool quiet) { if (m_running) { u64 dtime = porting::getTime(m_precision) - m_time1; - if (m_result != NULL) { + if (m_result != nullptr) { (*m_result) += dtime; } else { if (!quiet) { diff --git a/src/util/timetaker.h b/src/util/timetaker.h index c10f4f53..34564ee4 100644 --- a/src/util/timetaker.h +++ b/src/util/timetaker.h @@ -30,7 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class TimeTaker { public: - TimeTaker(const std::string &name, u64 *result=NULL, + TimeTaker(const std::string &name, u64 *result=nullptr, TimePrecision prec=PRECISION_MILLI); ~TimeTaker() @@ -45,9 +45,9 @@ public: private: std::string m_name; u64 m_time1; - bool m_running; + bool m_running = true; TimePrecision m_precision; - u64 *m_result; + u64 *m_result = nullptr; }; #endif From b32f36bf34c9a3208b2c0261e0f541453b4459b6 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Tue, 20 Jun 2017 00:04:18 +0200 Subject: [PATCH 11/53] Fix 2 warnings reported by GCC * ClientEnvironment::m_irr is not used anymore since a recent cleanup * l_vmanip constructor ordering --- src/client.cpp | 2 +- src/clientenvironment.cpp | 6 ++---- src/clientenvironment.h | 5 +---- src/script/lua_api/l_vmanip.cpp | 4 +++- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/client.cpp b/src/client.cpp index 9892e08c..ebe1d9c8 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -81,7 +81,7 @@ Client::Client( device->getSceneManager()->getRootSceneNode(), device->getSceneManager(), 666), device->getSceneManager(), - tsrc, this, device + tsrc, this ), m_particle_manager(&m_env), m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this), diff --git a/src/clientenvironment.cpp b/src/clientenvironment.cpp index e6b27308..e0398a06 100644 --- a/src/clientenvironment.cpp +++ b/src/clientenvironment.cpp @@ -37,14 +37,12 @@ with this program; if not, write to the Free Software Foundation, Inc., */ ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr, - ITextureSource *texturesource, Client *client, - IrrlichtDevice *irr): + ITextureSource *texturesource, Client *client): Environment(client), m_map(map), m_smgr(smgr), m_texturesource(texturesource), - m_client(client), - m_irr(irr) + m_client(client) { char zero = 0; memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids)); diff --git a/src/clientenvironment.h b/src/clientenvironment.h index c8b192ee..9d893766 100644 --- a/src/clientenvironment.h +++ b/src/clientenvironment.h @@ -20,7 +20,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef CLIENT_ENVIRONMENT_HEADER #define CLIENT_ENVIRONMENT_HEADER -#include #include #include "environment.h" #include "clientobject.h" @@ -69,8 +68,7 @@ class ClientEnvironment : public Environment { public: ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr, - ITextureSource *texturesource, Client *client, - IrrlichtDevice *device); + ITextureSource *texturesource, Client *client); ~ClientEnvironment(); Map & getMap(); @@ -181,7 +179,6 @@ private: ITextureSource *m_texturesource; Client *m_client; ClientScripting *m_script = nullptr; - IrrlichtDevice *m_irr; ClientActiveObjectMap m_active_objects; std::vector m_simple_objects; std::queue m_client_event_queue; diff --git a/src/script/lua_api/l_vmanip.cpp b/src/script/lua_api/l_vmanip.cpp index ed5042bc..9e482873 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -365,7 +365,9 @@ int LuaVoxelManip::l_get_emerged_area(lua_State *L) return 2; } -LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : vm(mmvm), is_mapgen_vm(is_mg_vm) +LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : + is_mapgen_vm(is_mg_vm), + vm(mmvm) { } From b2977e769162e9dfc042e3c92932bfd42a86d2cb Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Tue, 20 Jun 2017 00:19:29 +0200 Subject: [PATCH 12/53] Fix 1 more warning reported by GCC We don't write in correct buffer size in analyze_block --- src/mapblock.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mapblock.cpp b/src/mapblock.cpp index 631e9db6..bf7f9dcd 100644 --- a/src/mapblock.cpp +++ b/src/mapblock.cpp @@ -971,8 +971,8 @@ std::string analyze_block(MapBlock *block) std::ostringstream desc; v3s16 p = block->getPos(); - char spos[20]; - snprintf(spos, 20, "(%2d,%2d,%2d), ", p.X, p.Y, p.Z); + char spos[25]; + snprintf(spos, sizeof(spos), "(%2d,%2d,%2d), ", p.X, p.Y, p.Z); desc<getModified()) From 7c07cb4ec23ebb0f3d5f3d913bea205660515836 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Tue, 20 Jun 2017 09:39:20 +0200 Subject: [PATCH 13/53] Add new travis required configuration for trusty --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 123705fe..eaa8fd1a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,7 @@ before_install: ./util/travis/before_install.sh script: ./util/travis/script.sh sudo: required dist: trusty +group: edge notifications: email: false matrix: From 0fcaf9fb1b61caaf8ed78a5d3005b1d9d1c43b57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1niel=20Juh=C3=A1sz?= Date: Tue, 20 Jun 2017 09:19:56 +0000 Subject: [PATCH 14/53] Automatic item and node colorization (#5640) * Automatic item and node colorization Now nodes with a palette yield colored item stacks, and colored items place colored nodes by default. The client predicts the colorization. * Backwards compatibility * Use nil * Style fixes * Fix code style * Document changes --- builtin/game/falling.lua | 6 ++-- builtin/game/item.lua | 50 +++++++++++++++++++++++--- doc/lua_api.txt | 13 ++++--- src/game.cpp | 57 ++++++++++++++++++++++-------- src/inventory.cpp | 8 ++--- src/inventory.h | 5 +-- src/script/lua_api/l_inventory.cpp | 11 +++--- src/script/lua_api/l_inventory.h | 2 +- 8 files changed, 114 insertions(+), 38 deletions(-) diff --git a/builtin/game/falling.lua b/builtin/game/falling.lua index b1beb1ab..1ac4f708 100644 --- a/builtin/game/falling.lua +++ b/builtin/game/falling.lua @@ -93,7 +93,7 @@ core.register_entity(":__builtin:falling_node", { core.remove_node(np) if nd and nd.buildable_to == false then -- Add dropped items - local drops = core.get_node_drops(n2.name, "") + local drops = core.get_node_drops(n2, "") for _, dropped_item in pairs(drops) do core.add_item(np, dropped_item) end @@ -145,9 +145,9 @@ function core.spawn_falling_node(pos) end local function drop_attached_node(p) - local nn = core.get_node(p).name + local n = core.get_node(p) core.remove_node(p) - for _, item in pairs(core.get_node_drops(nn, "")) do + for _, item in pairs(core.get_node_drops(n, "")) do local pos = { x = p.x + math.random()/2 - 0.25, y = p.y + math.random()/2 - 0.25, diff --git a/builtin/game/item.lua b/builtin/game/item.lua index e36745f9..f6de2c33 100644 --- a/builtin/game/item.lua +++ b/builtin/game/item.lua @@ -155,12 +155,35 @@ function core.yaw_to_dir(yaw) return {x = -math.sin(yaw), y = 0, z = math.cos(yaw)} end -function core.get_node_drops(nodename, toolname) +function core.get_node_drops(node, toolname) + -- Compatibility, if node is string + local nodename = node + local param2 = 0 + -- New format, if node is table + if (type(node) == "table") then + nodename = node.name + param2 = node.param2 + end local def = core.registered_nodes[nodename] local drop = def and def.drop if drop == nil then -- default drop - return {nodename} + local stack = ItemStack(nodename) + if def then + local type = def.paramtype2 + if (type == "color") or (type == "colorfacedir") or + (type == "colorwallmounted") then + local meta = stack:get_meta() + local color_part = param2 + if (type == "colorfacedir") then + color_part = math.floor(color_part / 32) * 32; + elseif (type == "colorwallmounted") then + color_part = math.floor(color_part / 8) * 8; + end + meta:set_int("palette_index", color_part) + end + end + return {stack:to_string()} elseif type(drop) == "string" then -- itemstring drop return {drop} @@ -258,7 +281,7 @@ function core.item_place_node(itemstack, placer, pointed_thing, param2) .. def.name .. " at " .. core.pos_to_string(place_to)) local oldnode = core.get_node(place_to) - local newnode = {name = def.name, param1 = 0, param2 = param2} + local newnode = {name = def.name, param1 = 0, param2 = param2 or 0} -- Calculate direction for wall mounted stuff like torches and signs if def.place_param2 ~= nil then @@ -286,6 +309,25 @@ function core.item_place_node(itemstack, placer, pointed_thing, param2) end end + local metatable = itemstack:get_meta():to_table().fields + + -- Transfer color information + if metatable.palette_index and not def.place_param2 then + local color_divisor = nil + if def.paramtype2 == "color" then + color_divisor = 1 + elseif def.paramtype2 == "colorwallmounted" then + color_divisor = 8 + elseif def.paramtype2 == "colorfacedir" then + color_divisor = 32 + end + if color_divisor then + local color = math.floor(metatable.palette_index / color_divisor) + local other = newnode.param2 % color_divisor + newnode.param2 = color * color_divisor + other + end + end + -- Check if the node is attached and if it can be placed there if core.get_item_group(def.name, "attached_node") ~= 0 and not builtin_shared.check_attached_node(place_to, newnode) then @@ -474,7 +516,7 @@ function core.node_dig(pos, node, digger) .. node.name .. " at " .. core.pos_to_string(pos)) local wielded = digger:get_wielded_item() - local drops = core.get_node_drops(node.name, wielded:get_name()) + local drops = core.get_node_drops(node, wielded:get_name()) local wdef = wielded:get_definition() local tp = wielded:get_tool_capabilities() diff --git a/doc/lua_api.txt b/doc/lua_api.txt index a3413221..9bd92b34 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -531,9 +531,11 @@ for conversion. If the `ItemStack`'s metadata contains the `color` field, it will be lost on placement, because nodes on the map can only use palettes. -If the `ItemStack`'s metadata contains the `palette_index` field, you -currently must manually convert between it and the node's `param2` with -custom `on_place` and `on_dig` callbacks. +If the `ItemStack`'s metadata contains the `palette_index` field, it is +automatically transferred between node and item forms by the engine, +when a player digs or places a colored node. +You can disable this feature by setting the `drop` field of the node +to itself (without metadata). ### Colored items in craft recipes Craft recipes only support item strings, but fortunately item strings @@ -3326,8 +3328,9 @@ An `InvRef` is a reference to an inventory. * `add_item(listname, stack)`: add item somewhere in list, returns leftover `ItemStack` * `room_for_item(listname, stack):` returns `true` if the stack of items can be fully added to the list -* `contains_item(listname, stack)`: returns `true` if the stack of items - can be fully taken from the list +* `contains_item(listname, stack, [match_meta])`: returns `true` if + the stack of items can be fully taken from the list. + If `match_meta` is false, only the items' names are compared (default: `false`). * `remove_item(listname, stack)`: take as many items as specified from the list, returns the items that were actually removed (as an `ItemStack`) -- note that any item metadata is ignored, so attempting to remove a specific unique diff --git a/src/game.cpp b/src/game.cpp index 32555772..b81efc33 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -774,8 +774,8 @@ public: }; -bool nodePlacementPrediction(Client &client, - const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos) +bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def, + const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos) { std::string prediction = playeritem_def.node_placement_prediction; INodeDefManager *nodedef = client.ndef(); @@ -818,11 +818,13 @@ bool nodePlacementPrediction(Client &client, return false; } + const ContentFeatures &predicted_f = nodedef->get(id); + // Predict param2 for facedir and wallmounted nodes u8 param2 = 0; - if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED || - nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) { + if (predicted_f.param_type_2 == CPT2_WALLMOUNTED || + predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) { v3s16 dir = nodepos - neighbourpos; if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) { @@ -834,8 +836,8 @@ bool nodePlacementPrediction(Client &client, } } - if (nodedef->get(id).param_type_2 == CPT2_FACEDIR || - nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) { + 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); if (abs(dir.X) > abs(dir.Z)) { @@ -848,7 +850,7 @@ bool nodePlacementPrediction(Client &client, assert(param2 <= 5); //Check attachment if node is in group attached_node - if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) { + if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) { static v3s16 wallmounted_dirs[8] = { v3s16(0, 1, 0), v3s16(0, -1, 0), @@ -859,8 +861,8 @@ bool nodePlacementPrediction(Client &client, }; v3s16 pp; - if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED || - nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) + if (predicted_f.param_type_2 == CPT2_WALLMOUNTED || + predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) pp = p + wallmounted_dirs[param2]; else pp = p + v3s16(0, -1, 0); @@ -869,6 +871,28 @@ bool nodePlacementPrediction(Client &client, return false; } + // 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 = playeritem.metadata.getString( + "palette_index", 0); + if (!indexstr.empty()) { + s32 index = mystoi(indexstr); + if (predicted_f.param_type_2 == CPT2_COLOR) { + param2 = index; + } else if (predicted_f.param_type_2 + == CPT2_COLORED_WALLMOUNTED) { + // param2 = pure palette index + other + param2 = (index & 0xf8) | (param2 & 0x07); + } else if (predicted_f.param_type_2 + == CPT2_COLORED_FACEDIR) { + // param2 = pure palette index + other + param2 = (index & 0xe0) | (param2 & 0x1f); + } + } + } + // Add node to client map MapNode n(id, 0, param2); @@ -1277,8 +1301,9 @@ protected: 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 ItemDefinition &playeritem_def, - const ToolCapabilities &playeritem_toolcap, f32 dtime); + void handlePointingAtNode(const PointedThing &pointed, + const ItemDefinition &playeritem_def, const ItemStack &playeritem, + const ToolCapabilities &playeritem_toolcap, 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, @@ -3599,7 +3624,8 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) { playeritem_toolcap = *hand_def.tool_capabilities; } - handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime); + handlePointingAtNode(pointed, playeritem_def, playeritem, + playeritem_toolcap, dtime); } else if (pointed.type == POINTEDTHING_OBJECT) { handlePointingAtObject(pointed, playeritem, player_position, show_debug); } else if (isLeftPressed()) { @@ -3734,8 +3760,9 @@ void Game::handlePointingAtNothing(const ItemStack &playerItem) } -void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def, - const ToolCapabilities &playeritem_toolcap, f32 dtime) +void Game::handlePointingAtNode(const PointedThing &pointed, + const ItemDefinition &playeritem_def, const ItemStack &playeritem, + const ToolCapabilities &playeritem_toolcap, f32 dtime) { v3s16 nodepos = pointed.node_undersurface; v3s16 neighbourpos = pointed.node_abovesurface; @@ -3795,7 +3822,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinitio // If the wielded item has node placement prediction, // make that happen bool placed = nodePlacementPrediction(*client, - playeritem_def, + playeritem_def, playeritem, nodepos, neighbourpos); if (placed) { diff --git a/src/inventory.cpp b/src/inventory.cpp index 25f52415..5ce82737 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -658,7 +658,7 @@ bool InventoryList::roomForItem(const ItemStack &item_) const return false; } -bool InventoryList::containsItem(const ItemStack &item) const +bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const { u32 count = item.count; if(count == 0) @@ -669,9 +669,9 @@ bool InventoryList::containsItem(const ItemStack &item) const { if(count == 0) break; - if(i->name == item.name) - { - if(i->count >= count) + if (i->name == item.name + && (!match_meta || (i->metadata == item.metadata))) { + if (i->count >= count) return true; else count -= i->count; diff --git a/src/inventory.h b/src/inventory.h index e3e81870..04c8156c 100644 --- a/src/inventory.h +++ b/src/inventory.h @@ -223,9 +223,10 @@ public: // Checks whether there is room for a given item bool roomForItem(const ItemStack &item) const; - // Checks whether the given count of the given item name + // Checks whether the given count of the given item // exists in this inventory list. - bool containsItem(const ItemStack &item) const; + // If match_meta is false, only the items' names are compared. + bool containsItem(const ItemStack &item, bool match_meta) const; // Removes the given count of the given item name from // this inventory list. Walks the list in reverse order. diff --git a/src/script/lua_api/l_inventory.cpp b/src/script/lua_api/l_inventory.cpp index f5e76a7b..e92197c1 100644 --- a/src/script/lua_api/l_inventory.cpp +++ b/src/script/lua_api/l_inventory.cpp @@ -325,8 +325,8 @@ int InvRef::l_room_for_item(lua_State *L) return 1; } -// contains_item(self, listname, itemstack or itemstring or table or nil) -> 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 int InvRef::l_contains_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -334,8 +334,11 @@ int InvRef::l_contains_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){ - lua_pushboolean(L, list->containsItem(item)); + bool match_meta = false; + if (lua_isboolean(L, 4)) + match_meta = lua_toboolean(L, 4); + if (list) { + lua_pushboolean(L, list->containsItem(item, match_meta)); } else { lua_pushboolean(L, false); } diff --git a/src/script/lua_api/l_inventory.h b/src/script/lua_api/l_inventory.h index 91d41c0d..502827a1 100644 --- a/src/script/lua_api/l_inventory.h +++ b/src/script/lua_api/l_inventory.h @@ -93,7 +93,7 @@ private: // 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) -> true/false + // 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); From 318106223fc7351bd879980c17ee9c4bee65a272 Mon Sep 17 00:00:00 2001 From: Zeno- Date: Tue, 20 Jun 2017 20:36:58 +1000 Subject: [PATCH 15/53] Fix console not being properly resized after window size changed (#6020) --- src/guiChatConsole.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp index f8c3ed4c..ecd280f5 100644 --- a/src/guiChatConsole.cpp +++ b/src/guiChatConsole.cpp @@ -213,6 +213,7 @@ void GUIChatConsole::reformatConsole() s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt if (cols <= 0 || rows <= 0) cols = rows = 0; + recalculateConsolePosition(); m_chat_backend->reformat(cols, rows); } From 16938adfc00b3c56a7b08a9eb97160b68902bae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Tue, 20 Jun 2017 17:18:34 +0200 Subject: [PATCH 16/53] Merge cguittfont lib in irrlicht change folder. (#6016) * Merge cguittfont lib in irrlicht change folder. This remove hack and static lib for FreeType --- src/CMakeLists.txt | 12 +------- src/cguittfont/CMakeLists.txt | 30 ------------------- src/cguittfont/xCGUITTFont.cpp | 5 ---- src/cguittfont/xCGUITTFont.h | 7 ----- src/fontengine.cpp | 2 +- src/guiChatConsole.cpp | 2 +- .../CGUITTFont.cpp | 0 .../CGUITTFont.h | 3 +- src/irrlicht_changes/CMakeLists.txt | 11 ++++++- .../irrUString.h | 2 ++ src/irrlicht_changes/static_text.cpp | 7 +---- util/travis/clang-format-whitelist.txt | 7 ++--- 12 files changed, 21 insertions(+), 67 deletions(-) delete mode 100644 src/cguittfont/CMakeLists.txt delete mode 100644 src/cguittfont/xCGUITTFont.cpp delete mode 100644 src/cguittfont/xCGUITTFont.h rename src/{cguittfont => irrlicht_changes}/CGUITTFont.cpp (100%) rename src/{cguittfont => irrlicht_changes}/CGUITTFont.h (99%) rename src/{cguittfont => irrlicht_changes}/irrUString.h (99%) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ad5639a4..9e53b0e2 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -151,8 +151,6 @@ if(ENABLE_FREETYPE) if(FREETYPE_FOUND) message(STATUS "Freetype enabled.") set(USE_FREETYPE TRUE) - set(CGUITTFONT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cguittfont") - set(CGUITTFONT_LIBRARY cguittfont) endif() endif(ENABLE_FREETYPE) @@ -560,7 +558,7 @@ include_directories( if(USE_FREETYPE) - include_directories(${FREETYPE_INCLUDE_DIRS} ${CGUITTFONT_INCLUDE_DIR}) + include_directories(${FREETYPE_INCLUDE_DIRS}) endif() if(USE_CURL) @@ -619,7 +617,6 @@ if(BUILD_CLIENT) target_link_libraries( ${PROJECT_NAME} ${FREETYPE_LIBRARY} - ${CGUITTFONT_LIBRARY} ) endif() if (USE_CURSES) @@ -878,10 +875,3 @@ if (USE_GETTEXT) add_custom_target(translations ALL COMMENT "mo update" DEPENDS ${MO_FILES}) endif() - - -# Subdirectories - -if (BUILD_CLIENT AND USE_FREETYPE) - add_subdirectory(cguittfont) -endif() diff --git a/src/cguittfont/CMakeLists.txt b/src/cguittfont/CMakeLists.txt deleted file mode 100644 index 6cd35f31..00000000 --- a/src/cguittfont/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# CGUITTFont authors, y u no include headers you use? -# Do not add CGUITTFont.cpp to the line below. -# xCGUITTFont.cpp is a wrapper file that includes -# additional required headers. -add_library(cguittfont STATIC xCGUITTFont.cpp) - -if(FREETYPE_PKGCONFIG_FOUND) - set_target_properties(cguittfont - PROPERTIES - COMPILE_FLAGS "${FREETYPE_CFLAGS_STR}" - LINK_FLAGS "${FREETYPE_LDFLAGS_STR}" - ) - - include_directories( - ${IRRLICHT_INCLUDE_DIR} - ) -else(FREETYPE_PKGCONFIG_FOUND) - include_directories( - ${IRRLICHT_INCLUDE_DIR} - ${FREETYPE_INCLUDE_DIRS} - ) -endif(FREETYPE_PKGCONFIG_FOUND) - -target_link_libraries( - cguittfont - ${IRRLICHT_LIBRARY} - ${FREETYPE_LIBRARY} - ${ZLIB_LIBRARIES} # needed by freetype, repeated here for safety - ) - diff --git a/src/cguittfont/xCGUITTFont.cpp b/src/cguittfont/xCGUITTFont.cpp deleted file mode 100644 index c51922e4..00000000 --- a/src/cguittfont/xCGUITTFont.cpp +++ /dev/null @@ -1,5 +0,0 @@ -// A wrapper source file to avoid hack with gcc and modifying -// the CGUITTFont files. - -#include "xCGUITTFont.h" -#include "CGUITTFont.cpp" diff --git a/src/cguittfont/xCGUITTFont.h b/src/cguittfont/xCGUITTFont.h deleted file mode 100644 index c3efe7f6..00000000 --- a/src/cguittfont/xCGUITTFont.h +++ /dev/null @@ -1,7 +0,0 @@ -// A wrapper header to avoid hack with gcc and modifying -// the CGUITTFont files. - -#include -#include -#include "irrUString.h" -#include "CGUITTFont.h" diff --git a/src/fontengine.cpp b/src/fontengine.cpp index 2c277a04..536828ed 100644 --- a/src/fontengine.cpp +++ b/src/fontengine.cpp @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #if USE_FREETYPE #include "gettext.h" -#include "xCGUITTFont.h" +#include "irrlicht_changes/CGUITTFont.h" #endif /** maximum size distance for getting a "similar" font size */ diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp index ecd280f5..7e90bf43 100644 --- a/src/guiChatConsole.cpp +++ b/src/guiChatConsole.cpp @@ -32,7 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #if USE_FREETYPE - #include "xCGUITTFont.h" + #include "irrlicht_changes/CGUITTFont.h" #endif inline u32 clamp_u8(s32 value) diff --git a/src/cguittfont/CGUITTFont.cpp b/src/irrlicht_changes/CGUITTFont.cpp similarity index 100% rename from src/cguittfont/CGUITTFont.cpp rename to src/irrlicht_changes/CGUITTFont.cpp diff --git a/src/cguittfont/CGUITTFont.h b/src/irrlicht_changes/CGUITTFont.h similarity index 99% rename from src/cguittfont/CGUITTFont.h rename to src/irrlicht_changes/CGUITTFont.h index 77c9e34f..7ce89836 100644 --- a/src/cguittfont/CGUITTFont.h +++ b/src/irrlicht_changes/CGUITTFont.h @@ -35,6 +35,7 @@ #include #include #include +#include "irrUString.h" #include "util/enriched_string.h" #include FT_FREETYPE_H @@ -268,7 +269,7 @@ namespace gui 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); diff --git a/src/irrlicht_changes/CMakeLists.txt b/src/irrlicht_changes/CMakeLists.txt index 3a265c99..d2f66ab7 100644 --- a/src/irrlicht_changes/CMakeLists.txt +++ b/src/irrlicht_changes/CMakeLists.txt @@ -1,7 +1,16 @@ if (BUILD_CLIENT) set(client_irrlicht_changes_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/static_text.cpp - PARENT_SCOPE ) + + if (ENABLE_FREETYPE) + set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} + ${CMAKE_CURRENT_SOURCE_DIR}/CGUITTFont.cpp + ) + endif() + + # CMake require us to set a local scope and then parent scope + # Else the last set win in parent scope + set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} PARENT_SCOPE) endif() diff --git a/src/cguittfont/irrUString.h b/src/irrlicht_changes/irrUString.h similarity index 99% rename from src/cguittfont/irrUString.h rename to src/irrlicht_changes/irrUString.h index eb7abe5a..2472eda4 100644 --- a/src/cguittfont/irrUString.h +++ b/src/irrlicht_changes/irrUString.h @@ -41,6 +41,8 @@ #include #include #include +#include + #ifdef _WIN32 #define __BYTE_ORDER 0 #define __LITTLE_ENDIAN 0 diff --git a/src/irrlicht_changes/static_text.cpp b/src/irrlicht_changes/static_text.cpp index 50c6c6a6..455dbf43 100644 --- a/src/irrlicht_changes/static_text.cpp +++ b/src/irrlicht_changes/static_text.cpp @@ -7,18 +7,13 @@ #include "static_text.h" #ifdef _IRR_COMPILE_WITH_GUI_ -#include -#include -#include -#include -#include #include #include #include #include #if USE_FREETYPE - #include "cguittfont/xCGUITTFont.h" + #include "CGUITTFont.h" #endif #ifndef _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX // newer Irrlicht versions no longer have this diff --git a/util/travis/clang-format-whitelist.txt b/util/travis/clang-format-whitelist.txt index 66e312cd..f276af28 100644 --- a/util/travis/clang-format-whitelist.txt +++ b/util/travis/clang-format-whitelist.txt @@ -3,10 +3,6 @@ src/ban.cpp src/camera.cpp src/camera.h src/cavegen.cpp -src/cguittfont/CGUITTFont.cpp -src/cguittfont/CGUITTFont.h -src/cguittfont/irrUString.h -src/cguittfont/xCGUITTFont.h src/chat.cpp src/chat.h src/chat_interface.h @@ -113,6 +109,9 @@ src/inventory.cpp src/inventory.h src/inventorymanager.cpp src/inventorymanager.h +src/irrlicht_changes/CGUITTFont.cpp +src/irrlicht_changes/CGUITTFont.h +src/irrlicht_changes/irrUString.h src/irrlicht_changes/static_text.cpp src/irrlicht_changes/static_text.h src/irrlichttypes.h From e6a9e6066afc369f01c046de8e3a90a4b042286c Mon Sep 17 00:00:00 2001 From: Jesse McDonald Date: Thu, 18 May 2017 22:56:49 -0500 Subject: [PATCH 17/53] Inventory: Make addItem for empty ItemStacks respect max stack size When adding items to an empty ItemStack, limit the number of items taken based on the maximum stack size in the item description. Likewise, when checking whether items will fit into an empty ItemStack, only absorb as many items as are allowed in a single stack and return the rest. --- src/inventory.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/inventory.cpp b/src/inventory.cpp index 5ce82737..24eebba8 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -267,8 +267,17 @@ ItemStack ItemStack::addItem(const ItemStack &newitem_, // If this is an empty item, it's an easy job. else if(empty()) { + const u16 stackMax = getStackMax(itemdef); + *this = newitem; - newitem.clear(); + + // If the item fits fully, delete it + if (count <= stackMax) { + newitem.clear(); + } else { // Else the item does not fit fully. Return the rest. + count = stackMax; + newitem.remove(count); + } } // If item name or metadata differs, bail out else if (name != newitem.name @@ -308,7 +317,14 @@ bool ItemStack::itemFits(const ItemStack &newitem_, // If this is an empty item, it's an easy job. else if(empty()) { - newitem.clear(); + const u16 stackMax = getStackMax(itemdef); + + // If the item fits fully, delete it + if (newitem.count <= stackMax) { + newitem.clear(); + } else { // Else the item does not fit fully. Return the rest. + newitem.remove(stackMax); + } } // If item name or metadata differs, bail out else if (name != newitem.name @@ -322,7 +338,6 @@ bool ItemStack::itemFits(const ItemStack &newitem_, newitem.clear(); } // Else the item does not fit fully. Return the rest. - // the rest. else { u16 freespace = freeSpace(itemdef); From b8237099b269011f16a8055a61745876768f3f4d Mon Sep 17 00:00:00 2001 From: paramat Date: Tue, 20 Jun 2017 04:55:32 +0100 Subject: [PATCH 18/53] Mgv5/v7/fractal: Add 'large_cave_depth' parameter to replace fixed value The value cannot be fixed because we can shift terrain vertically. This also makes these mapgens consistent with mgflat and mgvalleys which have 'large_cave_depth' parameters. --- builtin/settingtypes.txt | 9 +++++ minetest.conf.example | 12 +++++++ src/mapgen_fractal.cpp | 71 +++++++++++++++++++++------------------- src/mapgen_fractal.h | 4 +-- src/mapgen_v5.cpp | 5 ++- src/mapgen_v5.h | 4 +-- src/mapgen_v7.cpp | 5 ++- src/mapgen_v7.h | 2 ++ 8 files changed, 72 insertions(+), 40 deletions(-) diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 53fb2385..ebdc9f75 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -1028,6 +1028,9 @@ mgv5_spflags (Mapgen v5 specific flags) flags caverns caverns,nocaverns # Controls width of tunnels, a smaller value creates wider tunnels. mgv5_cave_width (Cave width) float 0.125 +# Y of upper limit of large pseudorandom caves. +mgv5_large_cave_depth (Large cave depth) int -256 + # Y-level of cavern upper limit. mgv5_cavern_limit (Cavern limit) int -256 @@ -1134,6 +1137,9 @@ mgv7_spflags (Mapgen v7 specific flags) flags mountains,ridges,nofloatlands,cave # Controls width of tunnels, a smaller value creates wider tunnels. mgv7_cave_width (Cave width) float 0.09 +# Y of upper limit of large pseudorandom caves. +mgv7_large_cave_depth (Large cave depth) int -33 + # Controls the density of floatland mountain terrain. # Is an offset added to the 'np_mountain' noise value. mgv7_float_mount_density (Floatland mountain density) float 0.6 @@ -1251,6 +1257,9 @@ mgflat_np_cave2 (Cave2 noise) noise_params 0, 12, (67, 67, 67), 10325, 3, 0.5, 2 # Controls width of tunnels, a smaller value creates wider tunnels. mgfractal_cave_width (Cave width) float 0.09 +# Y of upper limit of large pseudorandom caves. +mgfractal_large_cave_depth (Large cave depth) int -33 + # Choice of 18 fractals from 9 formulas. # 1 = 4D "Roundy" mandelbrot set. # 2 = 4D "Roundy" julia set. diff --git a/minetest.conf.example b/minetest.conf.example index d3831def..9a71ec56 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -1256,6 +1256,10 @@ # type: float # mgv5_cave_width = 0.125 +# Y of upper limit of large pseudorandom caves. +# type: int +# mgv5_large_cave_depth = -256 + # Y-level of cavern upper limit. # type: int # mgv5_cavern_limit = -256 @@ -1371,6 +1375,10 @@ # type: float # mgv7_cave_width = 0.09 +# Y of upper limit of large pseudorandom caves. +# type: int +# mgv7_large_cave_depth = -33 + # Controls the density of floatland mountain terrain. # Is an offset added to the 'np_mountain' noise value. # type: float @@ -1522,6 +1530,10 @@ # type: float # mgfractal_cave_width = 0.09 +# Y of upper limit of large pseudorandom caves. +# type: int +# mgfractal_large_cave_depth = -33 + # Choice of 18 fractals from 9 formulas. # 1 = 4D "Roundy" mandelbrot set. # 2 = 4D "Roundy" julia set. diff --git a/src/mapgen_fractal.cpp b/src/mapgen_fractal.cpp index 6806b8cb..a99b3006 100644 --- a/src/mapgen_fractal.cpp +++ b/src/mapgen_fractal.cpp @@ -49,17 +49,18 @@ FlagDesc flagdesc_mapgen_fractal[] = { MapgenFractal::MapgenFractal(int mapgenid, MapgenFractalParams *params, EmergeManager *emerge) : MapgenBasic(mapgenid, params, emerge) { - this->spflags = params->spflags; - this->cave_width = params->cave_width; - this->fractal = params->fractal; - this->iterations = params->iterations; - this->scale = params->scale; - this->offset = params->offset; - this->slice_w = params->slice_w; - this->julia_x = params->julia_x; - this->julia_y = params->julia_y; - this->julia_z = params->julia_z; - this->julia_w = params->julia_w; + this->spflags = params->spflags; + this->cave_width = params->cave_width; + this->large_cave_depth = params->large_cave_depth; + this->fractal = params->fractal; + this->iterations = params->iterations; + this->scale = params->scale; + this->offset = params->offset; + this->slice_w = params->slice_w; + this->julia_x = params->julia_x; + this->julia_y = params->julia_y; + this->julia_z = params->julia_z; + this->julia_w = params->julia_w; //// 2D terrain noise noise_seabed = new Noise(¶ms->np_seabed, seed, csize.X, csize.Z); @@ -91,17 +92,18 @@ MapgenFractalParams::MapgenFractalParams() void MapgenFractalParams::readParams(const Settings *settings) { - settings->getFlagStrNoEx("mgfractal_spflags", spflags, flagdesc_mapgen_fractal); - settings->getFloatNoEx("mgfractal_cave_width", cave_width); - 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->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_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); @@ -112,17 +114,18 @@ void MapgenFractalParams::readParams(const Settings *settings) void MapgenFractalParams::writeParams(Settings *settings) const { - settings->setFlagStr("mgfractal_spflags", spflags, flagdesc_mapgen_fractal, U32_MAX); - settings->setFloat("mgfractal_cave_width", cave_width); - 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->setFlagStr("mgfractal_spflags", spflags, flagdesc_mapgen_fractal, U32_MAX); + settings->setFloat("mgfractal_cave_width", cave_width); + settings->setS16("mgfractal_large_cave_depth", large_cave_depth); + 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); @@ -196,7 +199,7 @@ void MapgenFractal::makeChunk(BlockMakeData *data) MgStoneType stone_type = generateBiomes(); if (flags & MG_CAVES) - generateCaves(stone_surface_max_y, MGFRACTAL_LARGE_CAVE_DEPTH); + generateCaves(stone_surface_max_y, large_cave_depth); if (flags & MG_DUNGEONS) generateDungeons(stone_surface_max_y, stone_type); diff --git a/src/mapgen_fractal.h b/src/mapgen_fractal.h index afbdb0cb..688e41c0 100644 --- a/src/mapgen_fractal.h +++ b/src/mapgen_fractal.h @@ -26,8 +26,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen.h" -#define MGFRACTAL_LARGE_CAVE_DEPTH -33 - class BiomeManager; extern FlagDesc flagdesc_mapgen_fractal[]; @@ -36,6 +34,7 @@ struct MapgenFractalParams : public MapgenParams { u32 spflags = 0; float cave_width = 0.09f; + s16 large_cave_depth = -33; u16 fractal = 1; u16 iterations = 11; v3f scale = v3f(4096.0, 1024.0, 4096.0); @@ -74,6 +73,7 @@ private: u16 formula; bool julia; + s16 large_cave_depth; u16 fractal; u16 iterations; v3f scale; diff --git a/src/mapgen_v5.cpp b/src/mapgen_v5.cpp index 4f2f5885..ebf9424e 100644 --- a/src/mapgen_v5.cpp +++ b/src/mapgen_v5.cpp @@ -50,6 +50,7 @@ MapgenV5::MapgenV5(int mapgenid, MapgenV5Params *params, EmergeManager *emerge) { this->spflags = params->spflags; this->cave_width = params->cave_width; + this->large_cave_depth = params->large_cave_depth; this->cavern_limit = params->cavern_limit; this->cavern_taper = params->cavern_taper; this->cavern_threshold = params->cavern_threshold; @@ -94,6 +95,7 @@ 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->getS16NoEx("mgv5_cavern_limit", cavern_limit); settings->getS16NoEx("mgv5_cavern_taper", cavern_taper); settings->getFloatNoEx("mgv5_cavern_threshold", cavern_threshold); @@ -112,6 +114,7 @@ void MapgenV5Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv5_spflags", spflags, flagdesc_mapgen_v5, U32_MAX); settings->setFloat("mgv5_cave_width", cave_width); + settings->setS16("mgv5_large_cave_depth", large_cave_depth); settings->setS16("mgv5_cavern_limit", cavern_limit); settings->setS16("mgv5_cavern_taper", cavern_taper); settings->setFloat("mgv5_cavern_threshold", cavern_threshold); @@ -209,7 +212,7 @@ void MapgenV5::makeChunk(BlockMakeData *data) // large caverns and floating blobs of overgenerated liquid. generateCaves(stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); else - generateCaves(stone_surface_max_y, MGV5_LARGE_CAVE_DEPTH); + generateCaves(stone_surface_max_y, large_cave_depth); } // Generate dungeons and desert temples diff --git a/src/mapgen_v5.h b/src/mapgen_v5.h index c90853f7..9b3f98d7 100644 --- a/src/mapgen_v5.h +++ b/src/mapgen_v5.h @@ -23,8 +23,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen.h" -#define MGV5_LARGE_CAVE_DEPTH -256 - ///////// Mapgen V5 flags #define MGV5_CAVERNS 0x01 @@ -36,6 +34,7 @@ struct MapgenV5Params : public MapgenParams { u32 spflags = MGV5_CAVERNS; float cave_width = 0.125f; + s16 large_cave_depth = -256; s16 cavern_limit = -256; s16 cavern_taper = 256; float cavern_threshold = 0.7f; @@ -68,6 +67,7 @@ public: int generateBaseTerrain(); private: + s16 large_cave_depth; Noise *noise_factor; Noise *noise_height; Noise *noise_ground; diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index e3922c53..409863fa 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -56,6 +56,7 @@ MapgenV7::MapgenV7(int mapgenid, MapgenV7Params *params, EmergeManager *emerge) { this->spflags = params->spflags; this->cave_width = params->cave_width; + this->large_cave_depth = params->large_cave_depth; this->float_mount_density = params->float_mount_density; this->float_mount_height = params->float_mount_height; this->floatland_level = params->floatland_level; @@ -143,6 +144,7 @@ void MapgenV7Params::readParams(const Settings *settings) { settings->getFlagStrNoEx("mgv7_spflags", spflags, flagdesc_mapgen_v7); settings->getFloatNoEx("mgv7_cave_width", cave_width); + settings->getS16NoEx("mgv7_large_cave_depth", large_cave_depth); settings->getFloatNoEx("mgv7_float_mount_density", float_mount_density); settings->getFloatNoEx("mgv7_float_mount_height", float_mount_height); settings->getS16NoEx("mgv7_floatland_level", floatland_level); @@ -172,6 +174,7 @@ void MapgenV7Params::writeParams(Settings *settings) const { settings->setFlagStr("mgv7_spflags", spflags, flagdesc_mapgen_v7, U32_MAX); settings->setFloat("mgv7_cave_width", cave_width); + settings->setS16("mgv7_large_cave_depth", large_cave_depth); settings->setFloat("mgv7_float_mount_density", float_mount_density); settings->setFloat("mgv7_float_mount_height", float_mount_height); settings->setS16("mgv7_floatland_level", floatland_level); @@ -303,7 +306,7 @@ void MapgenV7::makeChunk(BlockMakeData *data) // large caverns and floating blobs of overgenerated liquid. generateCaves(stone_surface_max_y, -MAX_MAP_GENERATION_LIMIT); else - generateCaves(stone_surface_max_y, water_level); + generateCaves(stone_surface_max_y, large_cave_depth); } // Generate dungeons diff --git a/src/mapgen_v7.h b/src/mapgen_v7.h index 4f369acd..3b0d11ff 100644 --- a/src/mapgen_v7.h +++ b/src/mapgen_v7.h @@ -37,6 +37,7 @@ extern FlagDesc flagdesc_mapgen_v7[]; struct MapgenV7Params : public MapgenParams { u32 spflags = MGV7_MOUNTAINS | MGV7_RIDGES | MGV7_CAVERNS; float cave_width = 0.09f; + s16 large_cave_depth = -33; float float_mount_density = 0.6f; float float_mount_height = 128.0f; s16 floatland_level = 1280; @@ -88,6 +89,7 @@ public: void generateRidgeTerrain(); private: + s16 large_cave_depth; float float_mount_density; float float_mount_height; s16 floatland_level; From 76074ad81abe68aa2b7af4d072b659f60f1af38c Mon Sep 17 00:00:00 2001 From: Ezhh Date: Wed, 21 Jun 2017 06:50:57 +0100 Subject: [PATCH 19/53] Fix console resize issue when maximising game window (#6023) --- src/guiChatConsole.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp index 7e90bf43..0dbddf31 100644 --- a/src/guiChatConsole.cpp +++ b/src/guiChatConsole.cpp @@ -186,8 +186,8 @@ void GUIChatConsole::draw() // scale current console height to new window size if (m_screensize.Y != 0) m_height = m_height * screensize.Y / m_screensize.Y; - m_desired_height = m_desired_height_fraction * m_screensize.Y; m_screensize = screensize; + m_desired_height = m_desired_height_fraction * m_screensize.Y; reformatConsole(); } From af3badf7a9307acd4993764cd805718849e4f942 Mon Sep 17 00:00:00 2001 From: Vincent Glize Date: Wed, 21 Jun 2017 08:04:45 +0200 Subject: [PATCH 20/53] C++11 cleanup on constructors dir client (#6012) * C++11 cleanup on constructors dir client --- src/client/clientlauncher.cpp | 6 +-- src/client/clientlauncher.h | 54 +++++++------------- src/client/inputhandler.h | 48 +++++++----------- src/client/joystick_controller.cpp | 7 +-- src/client/joystick_controller.h | 2 +- src/client/tile.h | 79 +++++++++++------------------- 6 files changed, 71 insertions(+), 125 deletions(-) diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index 1a797087..9856c192 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -38,8 +38,8 @@ with this program; if not, write to the Free Software Foundation, Inc., /* mainmenumanager.h */ -gui::IGUIEnvironment *guienv = NULL; -gui::IGUIStaticText *guiroot = NULL; +gui::IGUIEnvironment *guienv = nullptr; +gui::IGUIStaticText *guiroot = nullptr; MainMenuManager g_menumgr; bool isMenuActive() @@ -48,7 +48,7 @@ bool isMenuActive() } // Passed to menus to allow disconnecting and exiting -MainGameCallback *g_gamecallback = NULL; +MainGameCallback *g_gamecallback = nullptr; ClientLauncher::~ClientLauncher() diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h index 4ff77bc0..9e0560b1 100644 --- a/src/client/clientlauncher.h +++ b/src/client/clientlauncher.h @@ -28,25 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class ClientLauncher { public: - ClientLauncher() : - list_video_modes(false), - skip_main_menu(false), - use_freetype(false), - random_input(false), - address(""), - playername(""), - password(""), - device(NULL), - input(NULL), - receiver(NULL), - skin(NULL), - font(NULL), - simple_singleplayer_mode(false), - current_playername("inv£lid"), - current_password(""), - current_address("does-not-exist"), - current_port(0) - {} + ClientLauncher() {} ~ClientLauncher(); @@ -66,29 +48,29 @@ protected: void speed_tests(); bool print_video_modes(); - bool list_video_modes; - bool skip_main_menu; - bool use_freetype; - bool random_input; - std::string address; - std::string playername; - std::string password; - IrrlichtDevice *device; - InputHandler *input; - MyEventReceiver *receiver; - gui::IGUISkin *skin; - gui::IGUIFont *font; - scene::ISceneManager *smgr; + bool list_video_modes = false; + bool skip_main_menu = false; + bool use_freetype = false; + bool random_input = false; + std::string address = ""; + std::string playername = ""; + std::string password = ""; + IrrlichtDevice *device = nullptr; + InputHandler *input = nullptr; + MyEventReceiver *receiver = nullptr; + gui::IGUISkin *skin = nullptr; + gui::IGUIFont *font = nullptr; + scene::ISceneManager *smgr = nullptr; SubgameSpec gamespec; WorldSpec worldspec; bool simple_singleplayer_mode; // These are set up based on the menu and other things // TODO: Are these required since there's already playername, password, etc - std::string current_playername; - std::string current_password; - std::string current_address; - int current_port; + std::string current_playername = "inv£lid"; + std::string current_password = ""; + std::string current_address = "does-not-exist"; + int current_port = 0; }; #endif diff --git a/src/client/inputhandler.h b/src/client/inputhandler.h index 7c422d18..19733e3e 100644 --- a/src/client/inputhandler.h +++ b/src/client/inputhandler.h @@ -141,24 +141,23 @@ public: MyEventReceiver() { - clearInput(); #ifdef HAVE_TOUCHSCREENGUI m_touchscreengui = NULL; #endif } - bool leftclicked; - bool rightclicked; - bool leftreleased; - bool rightreleased; + bool leftclicked = false; + bool rightclicked = false; + bool leftreleased = false; + bool rightreleased = false; - bool left_active; - bool middle_active; - bool right_active; + bool left_active = false; + bool middle_active = false; + bool right_active = false; - s32 mouse_wheel; + s32 mouse_wheel = 0; - JoystickController *joystick; + JoystickController *joystick = nullptr; #ifdef HAVE_TOUCHSCREENGUI TouchScreenGUI *m_touchscreengui; @@ -221,7 +220,7 @@ class RealInputHandler : public InputHandler { public: RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver) - : m_device(device), m_receiver(receiver), m_mousepos(0, 0) + : m_device(device), m_receiver(receiver) { m_receiver->joystick = &joystick; } @@ -277,24 +276,15 @@ public: } private: - IrrlichtDevice *m_device; - MyEventReceiver *m_receiver; + IrrlichtDevice *m_device = nullptr; + MyEventReceiver *m_receiver = nullptr; v2s32 m_mousepos; }; class RandomInputHandler : public InputHandler { public: - RandomInputHandler() - { - leftdown = false; - rightdown = false; - leftclicked = false; - rightclicked = false; - leftreleased = false; - rightreleased = false; - keydown.clear(); - } + RandomInputHandler() {} virtual bool isKeyDown(const KeyPress &keyCode) { return keydown[keyCode]; } virtual bool wasKeyDown(const KeyPress &keyCode) { return false; } virtual v2s32 getMousePos() { return mousepos; } @@ -390,12 +380,12 @@ private: KeyList keydown; v2s32 mousepos; v2s32 mousespeed; - bool leftdown; - bool rightdown; - bool leftclicked; - bool rightclicked; - bool leftreleased; - bool rightreleased; + bool leftdown = false; + bool rightdown = false; + bool leftclicked = false; + bool rightclicked = false; + bool leftreleased = false; + bool rightreleased = false; }; #endif diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp index 905ca642..5a3d35d7 100644 --- a/src/client/joystick_controller.cpp +++ b/src/client/joystick_controller.cpp @@ -154,12 +154,9 @@ JoystickLayout create_xbox_layout() return jlo; } -JoystickController::JoystickController() +JoystickController::JoystickController() : + doubling_dtime(g_settings->getFloat("repeat_joystick_button_time")) { - m_joystick_id = 0; - - doubling_dtime = g_settings->getFloat("repeat_joystick_button_time"); - for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) { m_past_pressed_time[i] = 0; } diff --git a/src/client/joystick_controller.h b/src/client/joystick_controller.h index 2c0e7b90..baec4e41 100644 --- a/src/client/joystick_controller.h +++ b/src/client/joystick_controller.h @@ -155,7 +155,7 @@ private: s16 m_axes_vals[JA_COUNT]; - u8 m_joystick_id; + u8 m_joystick_id = 0; std::bitset m_pressed_keys; diff --git a/src/client/tile.h b/src/client/tile.h index 23255c46..a810aa8e 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -69,7 +69,7 @@ void clearTextureNameCache(); namespace irr {namespace scene {class IMesh;}} struct TextureFromMeshParams { - scene::IMesh *mesh; + scene::IMesh *mesh = nullptr; core::dimension2d dim; std::string rtt_texture_name; bool delete_texture_on_shutdown; @@ -92,7 +92,7 @@ public: ISimpleTextureSource(){} virtual ~ISimpleTextureSource(){} virtual video::ITexture* getTexture( - const std::string &name, u32 *id = NULL) = 0; + const std::string &name, u32 *id = nullptr) = 0; }; class ITextureSource : public ISimpleTextureSource @@ -104,9 +104,9 @@ public: virtual std::string getTextureName(u32 id)=0; virtual video::ITexture* getTexture(u32 id)=0; virtual video::ITexture* getTexture( - const std::string &name, u32 *id = NULL)=0; + const std::string &name, u32 *id = nullptr)=0; virtual video::ITexture* getTextureForMesh( - const std::string &name, u32 *id = NULL) = 0; + const std::string &name, u32 *id = nullptr) = 0; /*! * Returns a palette from the given texture name. * The pointer is valid until the texture source is @@ -132,7 +132,7 @@ public: virtual std::string getTextureName(u32 id)=0; virtual video::ITexture* getTexture(u32 id)=0; virtual video::ITexture* getTexture( - const std::string &name, u32 *id = NULL)=0; + const std::string &name, u32 *id = nullptr)=0; virtual IrrlichtDevice* getDevice()=0; virtual bool isKnownSourceImage(const std::string &name)=0; virtual video::ITexture* generateTextureFromMesh( @@ -180,17 +180,11 @@ enum MaterialType{ */ struct FrameSpec { - FrameSpec(): - texture_id(0), - texture(NULL), - normal_texture(NULL), - flags_texture(NULL) - { - } - u32 texture_id; - video::ITexture *texture; - video::ITexture *normal_texture; - video::ITexture *flags_texture; + FrameSpec() {} + u32 texture_id = 0; + video::ITexture *texture = nullptr; + video::ITexture *normal_texture = nullptr; + video::ITexture *flags_texture = nullptr; }; #define MAX_TILE_LAYERS 2 @@ -198,25 +192,7 @@ struct FrameSpec //! Defines a layer of a tile. struct TileLayer { - TileLayer(): - texture(NULL), - normal_texture(NULL), - flags_texture(NULL), - shader_id(0), - texture_id(0), - animation_frame_length_ms(0), - animation_frame_count(1), - material_type(TILE_MATERIAL_BASIC), - material_flags( - //0 // <- DEBUG, Use the one below - MATERIAL_FLAG_BACKFACE_CULLING | - MATERIAL_FLAG_TILEABLE_HORIZONTAL| - MATERIAL_FLAG_TILEABLE_VERTICAL - ), - has_color(false), - color() - { - } + TileLayer() {} /*! * Two layers are equal if they can be merged. @@ -287,22 +263,26 @@ struct TileLayer // Ordered for size, please do not reorder - video::ITexture *texture; - video::ITexture *normal_texture; - video::ITexture *flags_texture; + video::ITexture *texture = nullptr; + video::ITexture *normal_texture = nullptr; + video::ITexture *flags_texture = nullptr; - u32 shader_id; + u32 shader_id = 0; - u32 texture_id; + u32 texture_id = 0; - u16 animation_frame_length_ms; - u8 animation_frame_count; + u16 animation_frame_length_ms = 0; + u8 animation_frame_count = 1; - u8 material_type; - u8 material_flags; + 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; //! If true, the tile has its own color. - bool has_color; + bool has_color = false; std::vector frames; @@ -318,10 +298,7 @@ struct TileLayer */ struct TileSpec { - TileSpec(): - rotation(0), - emissive_light(0) - { + TileSpec() { for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) layers[layer] = TileLayer(); } @@ -341,9 +318,9 @@ struct TileSpec && emissive_light == other.emissive_light; } - u8 rotation; + u8 rotation = 0; //! This much light does the tile emit. - u8 emissive_light; + u8 emissive_light = 0; //! The first is base texture, the second is overlay. TileLayer layers[MAX_TILE_LAYERS]; }; From 8daf5b5338647373baffe045d728ea1734c63789 Mon Sep 17 00:00:00 2001 From: Vincent Glize Date: Wed, 21 Jun 2017 08:28:57 +0200 Subject: [PATCH 21/53] C++11 cleanup on constructors dir network (#6021) * C++11 cleanup on constructors dir network --- src/network/connection.cpp | 91 +++--------------- src/network/connection.h | 169 ++++++++++++++++------------------ src/network/networkpacket.cpp | 4 +- src/network/networkpacket.h | 11 +-- 4 files changed, 98 insertions(+), 177 deletions(-) diff --git a/src/network/connection.cpp b/src/network/connection.cpp index 61b98b6d..d1ab948d 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -60,14 +60,6 @@ static inline float CALC_DTIME(u64 lasttime, u64 curtime) return MYMAX(MYMIN(value,0.1),0.0); } -/* maximum window size to use, 0xFFFF is theoretical maximum don't think about - * touching it, the less you're away from it the more likely data corruption - * will occur - */ -#define MAX_RELIABLE_WINDOW_SIZE 0x8000 - /* starting value for window size */ -#define MIN_RELIABLE_WINDOW_SIZE 0x40 - #define MAX_UDP_PEERS 65535 #define PING_TIMEOUT 5.0 @@ -209,8 +201,6 @@ SharedBuffer makeReliablePacket( ReliablePacketBuffer */ -ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0) {} - void ReliablePacketBuffer::print() { MutexAutoLock listlock(m_list_mutex); @@ -577,36 +567,6 @@ void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout) Channel */ -Channel::Channel() : - window_size(MIN_RELIABLE_WINDOW_SIZE), - next_incoming_seqnum(SEQNUM_INITIAL), - next_outgoing_seqnum(SEQNUM_INITIAL), - next_outgoing_split_seqnum(SEQNUM_INITIAL), - current_packet_loss(0), - current_packet_too_late(0), - current_packet_successfull(0), - packet_loss_counter(0), - current_bytes_transfered(0), - current_bytes_received(0), - current_bytes_lost(0), - max_kbps(0.0), - cur_kbps(0.0), - avg_kbps(0.0), - max_incoming_kbps(0.0), - cur_incoming_kbps(0.0), - avg_incoming_kbps(0.0), - max_kbps_lost(0.0), - cur_kbps_lost(0.0), - avg_kbps_lost(0.0), - bpm_counter(0.0), - rate_samples(0) -{ -} - -Channel::~Channel() -{ -} - u16 Channel::readNextIncomingSeqNum() { MutexAutoLock internal(m_internal_mutex); @@ -849,40 +809,26 @@ void Channel::UpdateTimers(float dtime,bool legacy_peer) Peer */ -PeerHelper::PeerHelper() : - m_peer(0) -{} - PeerHelper::PeerHelper(Peer* peer) : m_peer(peer) { - if (peer != NULL) - { - if (!peer->IncUseCount()) - { - m_peer = 0; - } - } + if (peer && !peer->IncUseCount()) + m_peer = nullptr; } PeerHelper::~PeerHelper() { - if (m_peer != 0) + if (m_peer) m_peer->DecUseCount(); - m_peer = 0; + m_peer = nullptr; } PeerHelper& PeerHelper::operator=(Peer* peer) { m_peer = peer; - if (peer != NULL) - { - if (!peer->IncUseCount()) - { - m_peer = 0; - } - } + if (peer && !peer->IncUseCount()) + m_peer = nullptr; return *this; } @@ -909,8 +855,7 @@ bool Peer::IncUseCount() { MutexAutoLock lock(m_exclusive_access_mutex); - if (!m_pending_deletion) - { + if (!m_pending_deletion) { this->m_usage++; return true; } @@ -1014,10 +959,7 @@ void Peer::Drop() } UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) : - Peer(a_address,a_id,connection), - m_pending_disconnect(false), - resend_timeout(0.5), - m_legacy_peer(true) + Peer(a_address,a_id,connection) { } @@ -1261,12 +1203,9 @@ SharedBuffer UDPPeer::addSpiltPacket(u8 channel, ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size, float timeout) : Thread("ConnectionSend"), - m_connection(NULL), m_max_packet_size(max_packet_size), m_timeout(timeout), - m_max_commands_per_iteration(1), - m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")), - m_max_packets_requeued(256) + m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")) { } @@ -2031,8 +1970,7 @@ void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum, } ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) : - Thread("ConnectionReceive"), - m_connection(NULL) + Thread("ConnectionReceive") { } @@ -2676,17 +2614,10 @@ SharedBuffer ConnectionReceiveThread::processPacket(Channel *channel, Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6, PeerHandler *peerhandler) : m_udpSocket(ipv6), - m_command_queue(), - m_event_queue(), - m_peer_id(0), m_protocol_id(protocol_id), m_sendThread(max_packet_size, timeout), m_receiveThread(max_packet_size), - m_info_mutex(), - m_bc_peerhandler(peerhandler), - m_bc_receive_timeout(0), - m_shutting_down(false), - m_next_remote_peer_id(2) + m_bc_peerhandler(peerhandler) { m_udpSocket.setTimeoutMs(5); diff --git a/src/network/connection.h b/src/network/connection.h index 51cf6aec..1ee4f676 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -165,19 +165,18 @@ inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size) struct BufferedPacket { BufferedPacket(u8 *a_data, u32 a_size): - data(a_data, a_size), time(0.0), totaltime(0.0), absolute_send_time(-1), - resend_count(0) + data(a_data, a_size) {} BufferedPacket(u32 a_size): data(a_size), time(0.0), totaltime(0.0), absolute_send_time(-1), resend_count(0) {} Buffer data; // Data of the packet, including headers - float time; // Seconds from buffering the packet or re-sending - float totaltime; // Seconds from buffering the packet - u64 absolute_send_time; + 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 - unsigned int resend_count; + unsigned int resend_count = 0; }; // This adds the base headers to the data and makes a packet out of it @@ -210,16 +209,12 @@ SharedBuffer makeReliablePacket( struct IncomingSplitPacket { - IncomingSplitPacket() - { - time = 0.0; - reliable = false; - } + IncomingSplitPacket() {} // Key is chunk number, value is data without headers std::map > chunks; u32 chunk_count; - float time; // Seconds from adding - bool reliable; // If true, isn't deleted on timeout + float time = 0.0f; // Seconds from adding + bool reliable = false; // If true, isn't deleted on timeout bool allReceived() { @@ -322,7 +317,7 @@ typedef std::list::iterator RPBSearchResult; class ReliablePacketBuffer { public: - ReliablePacketBuffer(); + ReliablePacketBuffer() {}; bool getFirstSeqnum(u16& result); @@ -345,7 +340,7 @@ private: RPBSearchResult findPacket(u16 seqnum); std::list m_list; - u32 m_list_size; + u32 m_list_size = 0; u16 m_oldest_non_answered_ack; @@ -409,15 +404,15 @@ enum ConnectionCommandType{ struct ConnectionCommand { - enum ConnectionCommandType type; + enum ConnectionCommandType type = CONNCMD_NONE; Address address; - u16 peer_id; + u16 peer_id = PEER_ID_INEXISTENT; u8 channelnum; Buffer data; - bool reliable; - bool raw; + bool reliable = false; + bool raw = false; - ConnectionCommand(): type(CONNCMD_NONE), peer_id(PEER_ID_INEXISTENT), reliable(false), raw(false) {} + ConnectionCommand() {} void serve(Address address_) { @@ -478,6 +473,14 @@ struct ConnectionCommand } }; +/* maximum window size to use, 0xFFFF is theoretical maximum don't think about + * touching it, the less you're away from it the more likely data corruption + * will occur + */ +#define MAX_RELIABLE_WINDOW_SIZE 0x8000 + /* starting value for window size */ +#define MIN_RELIABLE_WINDOW_SIZE 0x40 + class Channel { @@ -507,8 +510,8 @@ public: IncomingSplitBuffer incoming_splits; - Channel(); - ~Channel(); + Channel() {}; + ~Channel() {}; void UpdatePacketLossCounter(unsigned int count); void UpdatePacketTooLateCounter(); @@ -545,33 +548,33 @@ public: void setWindowSize(unsigned int size) { window_size = size; }; private: std::mutex m_internal_mutex; - int window_size; + int window_size = MIN_RELIABLE_WINDOW_SIZE; - u16 next_incoming_seqnum; + u16 next_incoming_seqnum = SEQNUM_INITIAL; - u16 next_outgoing_seqnum; - u16 next_outgoing_split_seqnum; + u16 next_outgoing_seqnum = SEQNUM_INITIAL; + u16 next_outgoing_split_seqnum = SEQNUM_INITIAL; - unsigned int current_packet_loss; - unsigned int current_packet_too_late; - unsigned int current_packet_successfull; - float packet_loss_counter; + unsigned int current_packet_loss = 0; + unsigned int current_packet_too_late = 0; + unsigned int current_packet_successfull = 0; + float packet_loss_counter = 0.0f; - unsigned int current_bytes_transfered; - unsigned int current_bytes_received; - unsigned int current_bytes_lost; - float max_kbps; - float cur_kbps; - float avg_kbps; - float max_incoming_kbps; - float cur_incoming_kbps; - float avg_incoming_kbps; - float max_kbps_lost; - float cur_kbps_lost; - float avg_kbps_lost; - float bpm_counter; + unsigned int current_bytes_transfered = 0; + unsigned int current_bytes_received = 0; + unsigned int current_bytes_lost = 0; + float max_kbps = 0.0f; + float cur_kbps = 0.0f; + float avg_kbps = 0.0f; + float max_incoming_kbps = 0.0f; + float cur_incoming_kbps = 0.0f; + float avg_incoming_kbps = 0.0f; + float max_kbps_lost = 0.0f; + float cur_kbps_lost = 0.0f; + float avg_kbps_lost = 0.0f; + float bpm_counter = 0.0f; - unsigned int rate_samples; + unsigned int rate_samples = 0; }; class Peer; @@ -614,7 +617,7 @@ public: class PeerHelper { public: - PeerHelper(); + PeerHelper() {}; PeerHelper(Peer* peer); ~PeerHelper(); @@ -625,7 +628,7 @@ public: bool operator!=(void* ptr); private: - Peer* m_peer; + Peer *m_peer = nullptr; }; class Connection; @@ -654,23 +657,10 @@ class Peer { Peer(Address address_,u16 id_,Connection* connection) : id(id_), - m_increment_packets_remaining(9), - m_increment_bytes_remaining(0), - m_pending_deletion(false), m_connection(connection), address(address_), - m_ping_timer(0.0), - m_last_rtt(-1.0), - m_usage(0), - m_timeout_counter(0.0), m_last_timeout_check(porting::getTimeMs()) { - m_rtt.avg_rtt = -1.0; - m_rtt.jitter_avg = -1.0; - m_rtt.jitter_max = 0.0; - m_rtt.max_rtt = 0.0; - m_rtt.jitter_min = FLT_MAX; - m_rtt.min_rtt = FLT_MAX; }; virtual ~Peer() { @@ -692,12 +682,12 @@ class Peer { { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; }; void ResetTimeout() - {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter=0.0; }; + {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; }; bool isTimedOut(float timeout); - unsigned int m_increment_packets_remaining; - unsigned int m_increment_bytes_remaining; + unsigned int m_increment_packets_remaining = 9; + unsigned int m_increment_bytes_remaining = 0; virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; }; virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {}; @@ -740,7 +730,7 @@ class Peer { std::mutex m_exclusive_access_mutex; - bool m_pending_deletion; + bool m_pending_deletion = false; Connection* m_connection; @@ -748,26 +738,28 @@ class Peer { Address address; // Ping timer - float m_ping_timer; + float m_ping_timer = 0.0f; private: struct rttstats { - float jitter_min; - float jitter_max; - float jitter_avg; - float min_rtt; - float max_rtt; - float avg_rtt; + 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() {}; }; rttstats m_rtt; - float m_last_rtt; + float m_last_rtt = -1.0f; // current usage count - unsigned int m_usage; + unsigned int m_usage = 0; // Seconds from last receive - float m_timeout_counter; + float m_timeout_counter = 0.0f; u64 m_last_timeout_check; }; @@ -822,16 +814,16 @@ protected: bool Ping(float dtime,SharedBuffer& data); Channel channels[CHANNEL_COUNT]; - bool m_pending_disconnect; + bool m_pending_disconnect = false; private: // This is changed dynamically - float resend_timeout; + float resend_timeout = 0.5; bool processReliableSendCommand( ConnectionCommand &c, unsigned int max_packet_size); - bool m_legacy_peer; + bool m_legacy_peer = true; }; /* @@ -848,14 +840,13 @@ enum ConnectionEventType{ struct ConnectionEvent { - enum ConnectionEventType type; - u16 peer_id; + enum ConnectionEventType type = CONNEVENT_NONE; + u16 peer_id = 0; Buffer data; - bool timeout; + bool timeout = false; Address address; - ConnectionEvent(): type(CONNEVENT_NONE), peer_id(0), - timeout(false) {} + ConnectionEvent() {} std::string describe() { @@ -946,16 +937,16 @@ private: bool packetsQueued(); - Connection* m_connection; + Connection *m_connection = nullptr; unsigned int m_max_packet_size; float m_timeout; std::queue m_outgoing_queue; Semaphore m_send_sleep_semaphore; unsigned int m_iteration_packets_avaialble; - unsigned int m_max_commands_per_iteration; + unsigned int m_max_commands_per_iteration = 1; unsigned int m_max_data_packets_per_iteration; - unsigned int m_max_packets_requeued; + unsigned int m_max_packets_requeued = 256; }; class ConnectionReceiveThread : public Thread { @@ -993,7 +984,7 @@ private: u8 channelnum, bool reliable); - Connection* m_connection; + Connection *m_connection = nullptr; }; class Connection @@ -1059,7 +1050,7 @@ private: MutexedQueue m_event_queue; - u16 m_peer_id; + u16 m_peer_id = 0; u32 m_protocol_id; std::map m_peers; @@ -1073,11 +1064,11 @@ private: // Backwards compatibility PeerHandler *m_bc_peerhandler; - int m_bc_receive_timeout; + int m_bc_receive_timeout = 0; - bool m_shutting_down; + bool m_shutting_down = false; - u16 m_next_remote_peer_id; + u16 m_next_remote_peer_id = 2; }; } // namespace diff --git a/src/network/networkpacket.cpp b/src/network/networkpacket.cpp index f7a6499d..48cf3a37 100644 --- a/src/network/networkpacket.cpp +++ b/src/network/networkpacket.cpp @@ -23,13 +23,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/serialize.h" NetworkPacket::NetworkPacket(u16 command, u32 datasize, u16 peer_id): -m_datasize(datasize), m_read_offset(0), m_command(command), m_peer_id(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_read_offset(0), m_command(command), m_peer_id(0) +m_datasize(datasize), m_command(command) { m_data.resize(m_datasize); } diff --git a/src/network/networkpacket.h b/src/network/networkpacket.h index 83dc33f6..3058a22c 100644 --- a/src/network/networkpacket.h +++ b/src/network/networkpacket.h @@ -30,8 +30,7 @@ class NetworkPacket public: NetworkPacket(u16 command, u32 datasize, u16 peer_id); NetworkPacket(u16 command, u32 datasize); - NetworkPacket(): m_datasize(0), m_read_offset(0), m_command(0), - m_peer_id(0) {} + NetworkPacket() {} ~NetworkPacket(); void putRawPacket(u8 *data, u32 datasize, u16 peer_id); @@ -126,10 +125,10 @@ private: } std::vector m_data; - u32 m_datasize; - u32 m_read_offset; - u16 m_command; - u16 m_peer_id; + u32 m_datasize = 0; + u32 m_read_offset = 0; + u16 m_command = 0; + u16 m_peer_id = 0; }; #endif From 12aad731adef495dec03f384d10b4f8f57b6a1d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1niel=20Juh=C3=A1sz?= Date: Wed, 21 Jun 2017 08:47:31 +0000 Subject: [PATCH 22/53] Fix render order of overlays (#6008) * Fix render order of overlays * Use C++11 loops * Fix time_t --- src/clientmap.cpp | 79 +++++++++++++++++++++-------------------------- 1 file changed, 36 insertions(+), 43 deletions(-) diff --git a/src/clientmap.cpp b/src/clientmap.cpp index 5e88cab4..73d600a7 100644 --- a/src/clientmap.cpp +++ b/src/clientmap.cpp @@ -283,49 +283,45 @@ void ClientMap::updateDrawList(video::IVideoDriver* driver) struct MeshBufList { - /*! - * Specifies in which layer the list is. - * All lists which are in a lower layer are rendered before this list. - */ - u8 layer; video::SMaterial m; std::vector bufs; }; struct MeshBufListList { - std::vector lists; + /*! + * Stores the mesh buffers of the world. + * The array index is the material's layer. + * The vector part groups vertices by material. + */ + std::vector lists[MAX_TILE_LAYERS]; void clear() { - lists.clear(); + for (int l = 0; l < MAX_TILE_LAYERS; l++) + lists[l].clear(); } void add(scene::IMeshBuffer *buf, u8 layer) { + // Append to the correct layer + std::vector &list = lists[layer]; const video::SMaterial &m = buf->getMaterial(); - for(std::vector::iterator i = lists.begin(); - i != lists.end(); ++i){ - MeshBufList &l = *i; - + for (MeshBufList &l : list) { // 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; - if(l.layer != layer) - continue; - if (l.m == m) { l.bufs.push_back(buf); return; } } MeshBufList l; - l.layer = layer; l.m = m; l.bufs.push_back(buf); - lists.push_back(l); + list.push_back(l); } }; @@ -353,7 +349,7 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) Measuring time is very useful for long delays when the machine is swapping a lot. */ - int time1 = time(0); + std::time_t time1 = time(0); /* Get animation parameters @@ -469,35 +465,32 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) } } - std::vector &lists = drawbufs.lists; + // Render all layers in order + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + std::vector &lists = drawbufs.lists[layer]; - int timecheck_counter = 0; - for (std::vector::iterator i = lists.begin(); - i != lists.end(); ++i) { - timecheck_counter++; - if (timecheck_counter > 50) { - timecheck_counter = 0; - int time2 = time(0); - if (time2 > time1 + 4) { - infostream << "ClientMap::renderMap(): " - "Rendering takes ages, returning." - << std::endl; - return; + int timecheck_counter = 0; + for (MeshBufList &list : lists) { + timecheck_counter++; + if (timecheck_counter > 50) { + timecheck_counter = 0; + std::time_t time2 = time(0); + if (time2 > time1 + 4) { + infostream << "ClientMap::renderMap(): " + "Rendering takes ages, returning." + << std::endl; + return; + } + } + + driver->setMaterial(list.m); + + for (scene::IMeshBuffer *buf : list.bufs) { + driver->drawMeshBuffer(buf); + vertex_count += buf->getVertexCount(); + meshbuffer_count++; } } - - MeshBufList &list = *i; - - driver->setMaterial(list.m); - - for (std::vector::iterator j = list.bufs.begin(); - j != list.bufs.end(); ++j) { - scene::IMeshBuffer *buf = *j; - driver->drawMeshBuffer(buf); - vertex_count += buf->getVertexCount(); - meshbuffer_count++; - } - } } // ScopeProfiler From 1425c6def156840b359b90b4f32b9c7b8f005731 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Wed, 21 Jun 2017 11:51:29 +0200 Subject: [PATCH 23/53] Cpp11 initializers: last src root changeset (#6022) * Cpp11 initializers: last src root changeset Finish to migrate all src root folder files to C++11 constructor initializers --- src/serverobject.cpp | 7 +------ src/serverobject.h | 10 ++++----- src/settings.h | 15 +++++--------- src/shader.h | 19 ++++++++--------- src/sky.cpp | 32 ++++++++++------------------- src/sky.h | 20 +++++++++--------- src/socket.cpp | 2 -- src/socket.h | 4 ++-- src/staticobject.h | 10 +++------ src/subgame.h | 16 +++++++-------- src/terminal_chat_console.h | 22 ++++++++------------ src/tool.h | 21 +++++++------------ src/touchscreengui.cpp | 22 +------------------- src/touchscreengui.h | 36 ++++++++++++++------------------ src/voxel.cpp | 8 +++----- src/voxel.h | 41 ++++++++++++------------------------- src/voxelalgorithms.cpp | 9 ++------ src/voxelalgorithms.h | 6 +++--- src/wieldmesh.cpp | 34 ++++++++++++++---------------- src/wieldmesh.h | 16 +++++++-------- 20 files changed, 127 insertions(+), 223 deletions(-) diff --git a/src/serverobject.cpp b/src/serverobject.cpp index 19124782..f477700d 100644 --- a/src/serverobject.cpp +++ b/src/serverobject.cpp @@ -24,11 +24,6 @@ with this program; if not, write to the Free Software Foundation, Inc., ServerActiveObject::ServerActiveObject(ServerEnvironment *env, v3f pos): ActiveObject(0), - m_known_by_count(0), - m_removed(false), - m_pending_deactivation(false), - m_static_exists(false), - m_static_block(1337,1337,1337), m_env(env), m_base_position(pos) { @@ -82,7 +77,7 @@ ItemStack ServerActiveObject::getWieldedItem() const if(inv) { const InventoryList *list = inv->getList(getWieldList()); - if(list && (getWieldIndex() < (s32)list->getSize())) + if(list && (getWieldIndex() < (s32)list->getSize())) return list->getItem(getWieldIndex()); } return ItemStack(); diff --git a/src/serverobject.h b/src/serverobject.h index 3041910d..cd1922c8 100644 --- a/src/serverobject.h +++ b/src/serverobject.h @@ -204,7 +204,7 @@ public: deleted until this is 0 to keep the id preserved for the right object. */ - u16 m_known_by_count; + u16 m_known_by_count = 0; /* - Whether this object is to be removed when nobody knows about @@ -215,7 +215,7 @@ public: to be deleted. - This can be set to true by anything else too. */ - bool m_removed; + bool m_removed = false; /* This is set to true when an object should be removed from the active @@ -226,17 +226,17 @@ public: m_known_by_count is true, object is deleted from the active object list. */ - bool m_pending_deactivation; + bool m_pending_deactivation = false; /* Whether the object's static data has been stored to a block */ - bool m_static_exists; + bool m_static_exists = false; /* The block from which the object was loaded from, and in which a copy of the static data resides. */ - v3s16 m_static_block; + v3s16 m_static_block = v3s16(1337,1337,1337); /* Queue of messages to be sent to the client diff --git a/src/settings.h b/src/settings.h index d1edca6b..c4b94d67 100644 --- a/src/settings.h +++ b/src/settings.h @@ -73,15 +73,10 @@ struct ValueSpec { }; struct SettingsEntry { - SettingsEntry() : - group(NULL), - is_group(false) - {} + SettingsEntry() {} SettingsEntry(const std::string &value_) : - value(value_), - group(NULL), - is_group(false) + value(value_) {} SettingsEntry(Settings *group_) : @@ -89,9 +84,9 @@ struct SettingsEntry { is_group(true) {} - std::string value; - Settings *group; - bool is_group; + std::string value = ""; + Settings *group = nullptr; + bool is_group = false; }; typedef std::unordered_map SettingEntries; diff --git a/src/shader.h b/src/shader.h index 4d31f705..979318c9 100644 --- a/src/shader.h +++ b/src/shader.h @@ -44,16 +44,13 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string &filename); struct ShaderInfo { - std::string name; - video::E_MATERIAL_TYPE base_material; - video::E_MATERIAL_TYPE material; - u8 drawtype; - u8 material_type; - s32 user_data; + std::string name = ""; + video::E_MATERIAL_TYPE base_material = video::EMT_SOLID; + video::E_MATERIAL_TYPE material = video::EMT_SOLID; + u8 drawtype = 0; + u8 material_type = 0; - ShaderInfo(): name(""), base_material(video::EMT_SOLID), - material(video::EMT_SOLID), - drawtype(0), material_type(0) {} + ShaderInfo() {} virtual ~ShaderInfo() {} }; @@ -85,11 +82,11 @@ template class CachedShaderSetting { const char *m_name; T m_sent[count]; - bool has_been_set; + bool has_been_set = false; bool is_pixel; protected: CachedShaderSetting(const char *name, bool is_pixel) : - m_name(name), has_been_set(false), is_pixel(is_pixel) + m_name(name), is_pixel(is_pixel) {} public: void set(const T value[count], video::IMaterialRendererServices *services) diff --git a/src/sky.cpp b/src/sky.cpp index b739fe1a..3176ea93 100644 --- a/src/sky.cpp +++ b/src/sky.cpp @@ -14,15 +14,7 @@ Sky::Sky(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id, ITextureSource *tsrc): - scene::ISceneNode(parent, mgr, id), - m_visible(true), - m_fallback_bg_color(255, 255, 255, 255), - m_first_update(true), - m_brightness(0.5), - m_cloud_brightness(0.5), - m_bgcolor_bright_f(1, 1, 1, 1), - m_skycolor_bright_f(1, 1, 1, 1), - m_cloudcolor_bright_f(1, 1, 1, 1) + scene::ISceneNode(parent, mgr, id) { setAutomaticCulling(scene::EAC_OFF); m_box.MaxEdge.set(0, 0, 0); @@ -85,8 +77,6 @@ Sky::Sky(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id, } m_directional_colored_fog = g_settings->getBool("directional_colored_fog"); - - m_clouds_enabled = true; } @@ -109,7 +99,7 @@ void Sky::render() if (!camera || !driver) return; - + ScopeProfiler sp(g_profiler, "Sky::render()", SPT_AVG); // Draw perspective skybox @@ -138,7 +128,7 @@ void Sky::render() float moonsize = 0.04; video::SColorf mooncolor_f(0.50, 0.57, 0.65, 1); video::SColorf mooncolor2_f(0.85, 0.875, 0.9, 1); - + float nightlength = 0.415; float wn = nightlength / 2; float wicked_time_of_day = 0; @@ -181,11 +171,11 @@ void Sky::render() const f32 o = 0.0f; static const u16 indices[4] = {0, 1, 2, 3}; video::S3DVertex vertices[4]; - + driver->setMaterial(m_materials[1]); - + video::SColor cloudyfogcolor = m_bgcolor; - + // Draw far cloudy fog thing blended with skycolor for (u32 j = 0; j < 4; j++) { video::SColor c = cloudyfogcolor.getInterpolated(m_skycolor, 0.45); @@ -361,7 +351,7 @@ void Sky::render() vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); - + d = moonsize * 1.3; c = mooncolor; c.setAlpha(0.15 * 255); @@ -466,7 +456,7 @@ void Sky::render() indices, SKY_STAR_COUNT, video::EVT_STANDARD, scene::EPT_QUADS, video::EIT_16BIT); } while(0); - + // Draw far cloudy fog thing below east and west horizons for (u32 j = 0; j < 2; j++) { video::SColor c = cloudyfogcolor; @@ -510,7 +500,7 @@ void Sky::update(float time_of_day, float time_brightness, m_time_of_day = time_of_day; m_time_brightness = time_brightness; m_sunlight_seen = sunlight_seen; - + bool is_dawn = (time_brightness >= 0.20 && time_brightness < 0.35); /* @@ -535,7 +525,7 @@ void Sky::update(float time_of_day, float time_brightness, video::SColorf skycolor_bright_normal_f = video::SColor(255, 140, 186, 250); video::SColorf skycolor_bright_dawn_f = video::SColor(255, 180, 186, 250); video::SColorf skycolor_bright_night_f = video::SColor(255, 0, 107, 255); - + // pure white: becomes "diffuse light component" for clouds video::SColorf cloudcolor_bright_normal_f = video::SColor(255, 255, 255, 255); // dawn-factoring version of pure white (note: R is above 1.0) @@ -555,7 +545,7 @@ void Sky::update(float time_of_day, float time_brightness, else m_brightness = m_brightness * 0.98 + direct_brightness * 0.02; } - + m_clouds_visible = true; float color_change_fraction = 0.98; if (sunlight_seen) { diff --git a/src/sky.h b/src/sky.h index a014a920..1fa25bd9 100644 --- a/src/sky.h +++ b/src/sky.h @@ -117,25 +117,25 @@ private: return result; } - bool m_visible; - video::SColor m_fallback_bg_color; // Used when m_visible=false - bool m_first_update; + bool m_visible = true; + // Used when m_visible=false + video::SColor m_fallback_bg_color = video::SColor(255, 255, 255, 255); + bool m_first_update = true; float m_time_of_day; float m_time_brightness; bool m_sunlight_seen; - float m_brightness; - float m_cloud_brightness; + float m_brightness = 0.5f; + float m_cloud_brightness = 0.5f; bool m_clouds_visible; // Whether clouds are disabled due to player underground - bool m_clouds_enabled; // Initialised to true, reset only by set_sky API + bool m_clouds_enabled = true; // Initialised to true, reset only by set_sky API bool m_directional_colored_fog; - video::SColorf m_bgcolor_bright_f; - video::SColorf m_skycolor_bright_f; - video::SColorf m_cloudcolor_bright_f; + video::SColorf m_bgcolor_bright_f = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); + video::SColorf m_skycolor_bright_f = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); + video::SColorf m_cloudcolor_bright_f = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); video::SColor m_bgcolor; video::SColor m_skycolor; video::SColorf m_cloudcolor_f; v3f m_stars[SKY_STAR_COUNT]; - video::S3DVertex m_star_vertices[SKY_STAR_COUNT * 4]; video::ITexture *m_sun_texture; video::ITexture *m_moon_texture; video::ITexture *m_sun_tonemap; diff --git a/src/socket.cpp b/src/socket.cpp index 17fa1924..d0ab16ca 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -90,9 +90,7 @@ void sockets_cleanup() Address::Address() { - m_addr_family = 0; memset(&m_address, 0, sizeof(m_address)); - m_port = 0; } Address::Address(u32 address, u16 port) diff --git a/src/socket.h b/src/socket.h index 8d1ad70f..77ce3192 100644 --- a/src/socket.h +++ b/src/socket.h @@ -103,13 +103,13 @@ public: void print(std::ostream *s) const; std::string serializeString() const; private: - unsigned int m_addr_family; + unsigned int m_addr_family = 0; union { struct sockaddr_in ipv4; struct sockaddr_in6 ipv6; } m_address; - u16 m_port; // Port is separate from sockaddr structures + u16 m_port = 0; // Port is separate from sockaddr structures }; class UDPSocket diff --git a/src/staticobject.h b/src/staticobject.h index 208fb2cc..fb73befd 100644 --- a/src/staticobject.h +++ b/src/staticobject.h @@ -29,15 +29,11 @@ with this program; if not, write to the Free Software Foundation, Inc., struct StaticObject { - u8 type; + u8 type = 0; v3f pos; std::string data; - StaticObject(): - type(0), - pos(0,0,0) - { - } + StaticObject() {} StaticObject(u8 type_, v3f pos_, const std::string &data_): type(type_), pos(pos_), @@ -88,7 +84,7 @@ public: void serialize(std::ostream &os); void deSerialize(std::istream &is); - + /* NOTE: When an object is transformed to active, it is removed from m_stored and inserted to m_active. diff --git a/src/subgame.h b/src/subgame.h index f3633ce2..dda249a9 100644 --- a/src/subgame.h +++ b/src/subgame.h @@ -26,8 +26,6 @@ with this program; if not, write to the Free Software Foundation, Inc., class Settings; -#define WORLDNAME_BLACKLISTED_CHARS "/\\" - struct SubgameSpec { std::string id; // "" = game does not exist @@ -37,15 +35,15 @@ struct SubgameSpec std::string name; std::string menuicon_path; - SubgameSpec(const std::string &id_="", - const std::string &path_="", - const std::string &gamemods_path_="", - const std::set &addon_mods_paths_=std::set(), - const std::string &name_="", - const std::string &menuicon_path_=""): + SubgameSpec(const std::string &id_ = "", + const std::string &path_ = "", + const std::string &gamemods_path_ = "", + const std::set &addon_mods_paths_ = std::set(), + const std::string &name_ = "", + const std::string &menuicon_path_ = ""): id(id_), path(path_), - gamemods_path(gamemods_path_), + gamemods_path(gamemods_path_), addon_mods_paths(addon_mods_paths_), name(name_), menuicon_path(menuicon_path_) diff --git a/src/terminal_chat_console.h b/src/terminal_chat_console.h index 2111b7ec..8f6abe29 100644 --- a/src/terminal_chat_console.h +++ b/src/terminal_chat_console.h @@ -52,13 +52,7 @@ class TerminalChatConsole : public Thread { public: TerminalChatConsole() : - Thread("TerminalThread"), - m_log_level(LL_ACTION), - m_utf8_bytes_to_wait(0), - m_kill_requested(NULL), - m_esc_mode(false), - m_game_time(0), - m_time_of_day(0) + Thread("TerminalThread") {} void setup( @@ -74,7 +68,7 @@ public: virtual void *run(); // Highly required! - void clearKillStatus() { m_kill_requested = NULL; } + void clearKillStatus() { m_kill_requested = nullptr; } void stopAndWaitforThread(); @@ -102,10 +96,10 @@ private: ~CursesInitHelper() { cons->deInitOfCurses(); } }; - int m_log_level; + int m_log_level = LL_ACTION; std::string m_nick; - u8 m_utf8_bytes_to_wait; + u8 m_utf8_bytes_to_wait = 0; std::string m_pending_utf8_bytes; std::list m_nicks; @@ -114,16 +108,16 @@ private: int m_rows; bool m_can_draw_text; - bool *m_kill_requested; + bool *m_kill_requested = nullptr; ChatBackend m_chat_backend; ChatInterface *m_chat_interface; TermLogOutput m_log_output; - bool m_esc_mode; + bool m_esc_mode = false; - u64 m_game_time; - u32 m_time_of_day; + u64 m_game_time = 0; + u32 m_time_of_day = 0; }; extern TerminalChatConsole g_term_console; diff --git a/src/tool.h b/src/tool.h index 083328d0..67631fe7 100644 --- a/src/tool.h +++ b/src/tool.h @@ -28,13 +28,10 @@ with this program; if not, write to the Free Software Foundation, Inc., struct ToolGroupCap { std::unordered_map times; - int maxlevel; - int uses; + int maxlevel = 1; + int uses = 20; - ToolGroupCap(): - maxlevel(1), - uses(20) - {} + ToolGroupCap() {} bool getTime(int rating, float *time) const { @@ -118,15 +115,11 @@ HitParams getHitParams(const ItemGroupList &armor_groups, struct PunchDamageResult { - bool did_punch; - int damage; - int wear; + bool did_punch = false; + int damage = 0; + int wear = 0; - PunchDamageResult(): - did_punch(false), - damage(0), - wear(0) - {} + PunchDamageResult() {} }; struct ItemStack; diff --git a/src/touchscreengui.cpp b/src/touchscreengui.cpp index 0139b8c4..9a1ef408 100644 --- a/src/touchscreengui.cpp +++ b/src/touchscreengui.cpp @@ -130,19 +130,10 @@ static void load_button_texture(button_info* btn, const char* path, AutoHideButtonBar::AutoHideButtonBar(IrrlichtDevice *device, IEventReceiver* receiver) : - m_texturesource(NULL), m_driver(device->getVideoDriver()), m_guienv(device->getGUIEnvironment()), - m_receiver(receiver), - m_active(false), - m_visible(true), - m_timeout(0), - m_timeout_value(3), - m_initialized(false), - m_dir(AHBB_Dir_Right_Left) + m_receiver(receiver) { - m_screensize = device->getVideoDriver()->getScreenSize(); - } void AutoHideButtonBar::init(ISimpleTextureSource* tsrc, @@ -416,16 +407,7 @@ void AutoHideButtonBar::show() TouchScreenGUI::TouchScreenGUI(IrrlichtDevice *device, IEventReceiver* receiver): m_device(device), m_guienv(device->getGUIEnvironment()), - m_camera_yaw_change(0.0), - m_camera_pitch(0.0), - m_visible(false), - m_move_id(-1), m_receiver(receiver), - m_move_has_really_moved(false), - m_move_downtime(0), - m_move_sent_as_mouse_event(false), - // use some downlocation way off screen as init value to avoid invalid behaviour - m_move_downlocation(v2s32(-10000, -10000)), m_settingsbar(device, receiver), m_rarecontrolsbar(device, receiver) { @@ -474,8 +456,6 @@ void TouchScreenGUI::init(ISimpleTextureSource* tsrc) u32 button_size = getGuiButtonSize(); m_visible = true; m_texturesource = tsrc; - m_control_pad_rect = rect(0, m_screensize.Y - 3 * button_size, - 3 * button_size, m_screensize.Y); /* draw control pad 0 1 2 diff --git a/src/touchscreengui.h b/src/touchscreengui.h index a8c59fa9..7d3e4e83 100644 --- a/src/touchscreengui.h +++ b/src/touchscreengui.h @@ -76,7 +76,7 @@ struct button_info float repeatdelay; irr::EKEY_CODE keycode; std::vector ids; - IGUIButton *guibutton = NULL; + IGUIButton *guibutton = nullptr; bool immediate_release; }; @@ -114,11 +114,10 @@ public: void show(); private: - ISimpleTextureSource *m_texturesource; + ISimpleTextureSource *m_texturesource = nullptr; irr::video::IVideoDriver *m_driver; IGUIEnvironment *m_guienv; IEventReceiver *m_receiver; - v2u32 m_screensize; button_info m_starter; std::vector m_buttons; @@ -126,15 +125,15 @@ private: v2s32 m_lower_right; /* show settings bar */ - bool m_active; + bool m_active = false; - bool m_visible; + bool m_visible = true; /* settings bar timeout */ - float m_timeout; - float m_timeout_value; - bool m_initialized; - autohide_button_bar_dir m_dir; + float m_timeout = 0.0f; + float m_timeout_value = 3.0f; + bool m_initialized = false; + autohide_button_bar_dir m_dir = AHBB_Dir_Right_Left; }; class TouchScreenGUI @@ -177,18 +176,16 @@ private: bool m_visible; // is the gui visible /* value in degree */ - double m_camera_yaw_change; - double m_camera_pitch; + double m_camera_yaw_change = 0.0; + double m_camera_pitch = 0.0; line3d m_shootline; - rect m_control_pad_rect; - - int m_move_id; - bool m_move_has_really_moved; - s64 m_move_downtime; - bool m_move_sent_as_mouse_event; - v2s32 m_move_downlocation; + int m_move_id = -1; + bool m_move_has_really_moved = false; + s64 m_move_downtime = 0; + bool m_move_sent_as_mouse_event = false; + v2s32 m_move_downlocation = v2s32(-10000, -10000); button_info m_buttons[after_last_element_id]; @@ -206,9 +203,6 @@ private: std::wstring caption, bool immediate_release, float repeat_delay = BUTTON_REPEAT_DELAY); - /* load texture */ - void loadButtonTexture(button_info *btn, const char *path, rect button_rect); - struct id_status { int id; diff --git a/src/voxel.cpp b/src/voxel.cpp index 78efde5b..08765c98 100644 --- a/src/voxel.cpp +++ b/src/voxel.cpp @@ -33,9 +33,7 @@ u64 emerge_load_time = 0; u64 clearflag_time = 0; -VoxelManipulator::VoxelManipulator(): - m_data(NULL), - m_flags(NULL) +VoxelManipulator::VoxelManipulator() { } @@ -49,9 +47,9 @@ void VoxelManipulator::clear() // Reset area to volume=0 m_area = VoxelArea(); delete[] m_data; - m_data = NULL; + m_data = nullptr; delete[] m_flags; - m_flags = NULL; + m_flags = nullptr; } void VoxelManipulator::print(std::ostream &o, INodeDefManager *ndef, diff --git a/src/voxel.h b/src/voxel.h index 3a64ccc7..8a7ad30a 100644 --- a/src/voxel.h +++ b/src/voxel.h @@ -60,11 +60,8 @@ class VoxelArea { public: // Starts as zero sized - VoxelArea(): - MinEdge(1,1,1), - MaxEdge(0,0,0) - { - } + VoxelArea() {} + VoxelArea(v3s16 min_edge, v3s16 max_edge): MinEdge(min_edge), MaxEdge(max_edge) @@ -325,22 +322,22 @@ public: } // Edges are inclusive - v3s16 MinEdge; + v3s16 MinEdge = v3s16(1,1,1); v3s16 MaxEdge; }; -// unused -#define VOXELFLAG_UNUSED (1<<0) +// unused +#define VOXELFLAG_UNUSED (1 << 0) // no data about that node -#define VOXELFLAG_NO_DATA (1<<1) +#define VOXELFLAG_NO_DATA (1 << 1) // Algorithm-dependent -#define VOXELFLAG_CHECKED1 (1<<2) +#define VOXELFLAG_CHECKED1 (1 << 2) // Algorithm-dependent -#define VOXELFLAG_CHECKED2 (1<<3) +#define VOXELFLAG_CHECKED2 (1 << 3) // Algorithm-dependent -#define VOXELFLAG_CHECKED3 (1<<4) +#define VOXELFLAG_CHECKED3 (1 << 4) // Algorithm-dependent -#define VOXELFLAG_CHECKED4 (1<<5) +#define VOXELFLAG_CHECKED4 (1 << 5) enum VoxelPrintMode { @@ -570,29 +567,17 @@ public: VoxelArea m_area; /* - NULL if data size is 0 (extent (0,0,0)) + nullptr if data size is 0 (extent (0,0,0)) Data is stored as [z*h*w + y*h + x] */ - MapNode *m_data; + MapNode *m_data = nullptr; /* Flags of all nodes */ - u8 *m_flags; + u8 *m_flags = nullptr; static const MapNode ContentIgnoreNode; - - //TODO: Use these or remove them - //TODO: Would these make any speed improvement? - //bool m_pressure_route_valid; - //v3s16 m_pressure_route_surface; - - /* - Some settings - */ - //bool m_disable_water_climb; - -private: }; #endif diff --git a/src/voxelalgorithms.cpp b/src/voxelalgorithms.cpp index 40f8595a..cea33955 100644 --- a/src/voxelalgorithms.cpp +++ b/src/voxelalgorithms.cpp @@ -1402,14 +1402,9 @@ void repair_block_light(ServerMap *map, MapBlock *block, modified_blocks); } -VoxelLineIterator::VoxelLineIterator( - const v3f &start_position, - const v3f &line_vector) : +VoxelLineIterator::VoxelLineIterator(const v3f &start_position, const v3f &line_vector) : m_start_position(start_position), - m_line_vector(line_vector), - m_next_intersection_multi(10000.0f, 10000.0f, 10000.0f), - m_intersection_multi_inc(10000.0f, 10000.0f, 10000.0f), - m_step_directions(1.0f, 1.0f, 1.0f) + m_line_vector(line_vector) { m_current_node_pos = floatToInt(m_start_position, 1); diff --git a/src/voxelalgorithms.h b/src/voxelalgorithms.h index 69962461..6e5fd525 100644 --- a/src/voxelalgorithms.h +++ b/src/voxelalgorithms.h @@ -123,17 +123,17 @@ public: * which multiplying the line's vector gives a vector that ends * on the intersection of two nodes. */ - v3f m_next_intersection_multi; + v3f m_next_intersection_multi = v3f(10000.0f, 10000.0f, 10000.0f); /*! * Each component stores the smallest positive number, by which * m_next_intersection_multi's components can be increased. */ - v3f m_intersection_multi_inc; + v3f m_intersection_multi_inc = v3f(10000.0f, 10000.0f, 10000.0f); /*! * Direction of the line. Each component can be -1 or 1 (if a * component of the line's vector is 0, then there will be 1). */ - v3s16 m_step_directions; + v3s16 m_step_directions = v3s16(1, 1, 1); //! Position of the current node. v3s16 m_current_node_pos; //! If true, the next node will intersect the line, too. diff --git a/src/wieldmesh.cpp b/src/wieldmesh.cpp index 7736ec2a..7da030df 100644 --- a/src/wieldmesh.cpp +++ b/src/wieldmesh.cpp @@ -199,10 +199,8 @@ WieldMeshSceneNode::WieldMeshSceneNode( bool lighting ): scene::ISceneNode(parent, mgr, id), - m_meshnode(NULL), m_material_type(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF), - m_lighting(lighting), - m_bounding_box(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + m_lighting(lighting) { m_enable_shaders = g_settings->getBool("enable_shaders"); m_anisotropic_filter = g_settings->getBool("anisotropic_filter"); @@ -211,7 +209,7 @@ WieldMeshSceneNode::WieldMeshSceneNode( // If this is the first wield mesh scene node, create a cache // for extrusion meshes (and a cube mesh), otherwise reuse it - if (g_extrusion_mesh_cache == NULL) + if (!g_extrusion_mesh_cache) g_extrusion_mesh_cache = new ExtrusionMeshCache(); else g_extrusion_mesh_cache->grab(); @@ -232,11 +230,11 @@ WieldMeshSceneNode::~WieldMeshSceneNode() { sanity_check(g_extrusion_mesh_cache); if (g_extrusion_mesh_cache->drop()) - g_extrusion_mesh_cache = NULL; + g_extrusion_mesh_cache = nullptr; } void WieldMeshSceneNode::setCube(const ContentFeatures &f, - v3f wield_scale, ITextureSource *tsrc) + v3f wield_scale) { scene::IMesh *cubemesh = g_extrusion_mesh_cache->createCube(); scene::SMesh *copy = cloneMesh(cubemesh); @@ -252,7 +250,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, { video::ITexture *texture = tsrc->getTexture(imagename); if (!texture) { - changeToMesh(NULL); + changeToMesh(nullptr); return; } @@ -335,13 +333,13 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) def.wield_scale * WIELD_SCALE_FACTOR / (BS * f.visual_scale)); } else if (f.drawtype == NDT_AIRLIKE) { - changeToMesh(NULL); + changeToMesh(nullptr); } else if (f.drawtype == NDT_PLANTLIKE) { setExtruded(tsrc->getTextureName(f.tiles[0].layers[0].texture_id), def.wield_scale, tsrc, f.tiles[0].layers[0].animation_frame_count); } else if (f.drawtype == NDT_NORMAL || f.drawtype == NDT_ALLFACES) { - setCube(f, def.wield_scale, tsrc); + setCube(f, def.wield_scale); } else { MeshMakeData mesh_make_data(client, false); MapNode mesh_make_node(id, 255, 0); @@ -373,14 +371,14 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) } // no wield mesh found - changeToMesh(NULL); + changeToMesh(nullptr); } void WieldMeshSceneNode::setColor(video::SColor c) { assert(!m_lighting); - scene::IMesh *mesh=m_meshnode->getMesh(); - if (mesh == NULL) + scene::IMesh *mesh = m_meshnode->getMesh(); + if (!mesh) return; u8 red = c.getRed(); @@ -408,7 +406,7 @@ void WieldMeshSceneNode::render() void WieldMeshSceneNode::changeToMesh(scene::IMesh *mesh) { - if (mesh == NULL) { + if (!mesh) { scene::IMesh *dummymesh = g_extrusion_mesh_cache->createCube(); m_meshnode->setVisible(false); m_meshnode->setMesh(dummymesh); @@ -438,7 +436,7 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) g_extrusion_mesh_cache->grab(); } - scene::SMesh *mesh = NULL; + scene::SMesh *mesh = nullptr; // Shading is on by default result->needs_shading = true; @@ -499,20 +497,18 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) rotateMeshXZby(mesh, -45); rotateMeshYZby(mesh, -30); - postProcessNodeMesh(mesh, f, false, false, NULL, - &result->buffer_colors); + postProcessNodeMesh(mesh, f, false, false, nullptr, &result->buffer_colors); } result->mesh = mesh; } -scene::SMesh * getExtrudedMesh(ITextureSource *tsrc, - const std::string &imagename) +scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename) { video::ITexture *texture = tsrc->getTextureForMesh(imagename); if (!texture) { - return NULL; + return nullptr; } core::dimension2d dim = texture->getSize(); diff --git a/src/wieldmesh.h b/src/wieldmesh.h index faedce48..8ef155df 100644 --- a/src/wieldmesh.h +++ b/src/wieldmesh.h @@ -38,13 +38,13 @@ struct ItemPartColor * will be used instead of the specific color of the * buffer. */ - bool override_base; + bool override_base = false; /*! * The color of the buffer. */ - video::SColor color; + video::SColor color = 0; - ItemPartColor() : override_base(false), color(0) {} + ItemPartColor() {} ItemPartColor(bool override, video::SColor color) : override_base(override), color(color) @@ -54,7 +54,7 @@ struct ItemPartColor struct ItemMesh { - scene::IMesh *mesh; + scene::IMesh *mesh = nullptr; /*! * Stores the color of each mesh buffer. */ @@ -63,9 +63,9 @@ struct ItemMesh * If false, all faces of the item should have the same brightness. * Disables shading based on normal vectors. */ - bool needs_shading; + bool needs_shading = true; - ItemMesh() : mesh(NULL), buffer_colors(), needs_shading(true) {} + ItemMesh() {} }; /* @@ -78,7 +78,7 @@ public: s32 id = -1, bool lighting = false); virtual ~WieldMeshSceneNode(); - void setCube(const ContentFeatures &f, v3f wield_scale, ITextureSource *tsrc); + void setCube(const ContentFeatures &f, v3f wield_scale); void setExtruded(const std::string &imagename, v3f wield_scale, ITextureSource *tsrc, u8 num_frames); void setItem(const ItemStack &item, Client *client); @@ -97,7 +97,7 @@ private: void changeToMesh(scene::IMesh *mesh); // Child scene node with the current wield mesh - scene::IMeshSceneNode *m_meshnode; + scene::IMeshSceneNode *m_meshnode = nullptr; video::E_MATERIAL_TYPE m_material_type; // True if EMF_LIGHTING should be enabled. From bc53c82bcf923d11725e3de8565eb4c7e435cd2b Mon Sep 17 00:00:00 2001 From: Gael-de-Sailly Date: Fri, 27 Feb 2015 20:51:55 +0100 Subject: [PATCH 24/53] Add minetest.rgba function that returns ColorString from RGBA or RGB values --- builtin/common/misc_helpers.lua | 6 ++++++ doc/client_lua_api.md | 4 ++++ doc/lua_api.txt | 6 +++++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/builtin/common/misc_helpers.lua b/builtin/common/misc_helpers.lua index f9b572d9..776be29d 100644 --- a/builtin/common/misc_helpers.lua +++ b/builtin/common/misc_helpers.lua @@ -511,6 +511,12 @@ function core.explode_scrollbar_event(evt) return retval end +-------------------------------------------------------------------------------- +function core.rgba(r, g, b, a) + return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or + string.format("#%02X%02X%02X", r, g, b) +end + -------------------------------------------------------------------------------- function core.pos_to_string(pos, decimal_places) local x = pos.x diff --git a/doc/client_lua_api.md b/doc/client_lua_api.md index 43b33ac9..3bd1e356 100644 --- a/doc/client_lua_api.md +++ b/doc/client_lua_api.md @@ -794,6 +794,10 @@ Call these functions only at load time! * See documentation on `minetest.compress()` for supported compression methods. * currently supported. * `...` indicates method-specific arguments. Currently, no methods use this. +* `minetest.rgba(red, green, blue[, alpha])`: returns a string + * Each argument is a 8 Bit unsigned integer + * Returns the ColorString from rgb or rgba values + * Example: `minetest.rgba(10, 20, 30, 40)`, returns `"#0A141E28"` * `minetest.encode_base64(string)`: returns string encoded in base64 * Encodes a string in base64. * `minetest.decode_base64(string)`: returns string diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 9bd92b34..664ad960 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -580,7 +580,7 @@ Example (colored grass block): description = "Dirt with Grass", -- Regular tiles, as usual -- The dirt tile disables palette coloring - tiles = {{name = "default_grass.png"}, + tiles = {{name = "default_grass.png"}, {name = "default_dirt.png", color = "white"}}, -- Overlay tiles: define them in the same style -- The top and bottom tile does not have overlay @@ -2958,6 +2958,10 @@ These functions return the leftover itemstack. * See documentation on `minetest.compress()` for supported compression methods. * currently supported. * `...` indicates method-specific arguments. Currently, no methods use this. +* `minetest.rgba(red, green, blue[, alpha])`: returns a string + * Each argument is a 8 Bit unsigned integer + * Returns the ColorString from rgb or rgba values + * Example: `minetest.rgba(10, 20, 30, 40)`, returns `"#0A141E28"` * `minetest.encode_base64(string)`: returns string encoded in base64 * Encodes a string in base64. * `minetest.decode_base64(string)`: returns string From 2652d8db19fb2758de1da4c04ce169f80c87e5c7 Mon Sep 17 00:00:00 2001 From: paramat Date: Wed, 21 Jun 2017 04:20:18 +0100 Subject: [PATCH 25/53] CavesRandomWalk: Make 'lava_depth' a mapgen parameter As with 'large_cave_depth', lava depth was previously a fixed y value and therefore incompatible with the ability to shift terrain vertically. Add 'lava_depth' mapgen parameter to mgflat, mgfractal, mgv5, mgv7. --- builtin/settingtypes.txt | 20 ++++++++++++++++---- minetest.conf.example | 24 ++++++++++++++++++++---- src/cavegen.cpp | 5 +++-- src/cavegen.h | 4 ++-- src/mapgen.cpp | 2 +- src/mapgen.h | 1 + src/mapgen_flat.cpp | 3 +++ src/mapgen_flat.h | 1 + src/mapgen_fractal.cpp | 3 +++ src/mapgen_fractal.h | 1 + src/mapgen_v5.cpp | 3 +++ src/mapgen_v5.h | 1 + src/mapgen_v7.cpp | 3 +++ src/mapgen_v7.h | 1 + 14 files changed, 59 insertions(+), 13 deletions(-) diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index ebdc9f75..f15fc679 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -1028,9 +1028,12 @@ mgv5_spflags (Mapgen v5 specific flags) flags caverns caverns,nocaverns # Controls width of tunnels, a smaller value creates wider tunnels. mgv5_cave_width (Cave width) float 0.125 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. mgv5_large_cave_depth (Large cave depth) int -256 +# Y of upper limit of lava in large caves. +mgv5_lava_depth (Lava depth) int -256 + # Y-level of cavern upper limit. mgv5_cavern_limit (Cavern limit) int -256 @@ -1137,9 +1140,12 @@ mgv7_spflags (Mapgen v7 specific flags) flags mountains,ridges,nofloatlands,cave # Controls width of tunnels, a smaller value creates wider tunnels. mgv7_cave_width (Cave width) float 0.09 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. mgv7_large_cave_depth (Large cave depth) int -33 +# Y of upper limit of lava in large caves. +mgv7_lava_depth (Lava depth) int -256 + # Controls the density of floatland mountain terrain. # Is an offset added to the 'np_mountain' noise value. mgv7_float_mount_density (Floatland mountain density) float 0.6 @@ -1218,9 +1224,12 @@ mgflat_spflags (Mapgen flat specific flags) flags nolakes,nohills lakes,hills,no # Y of flat ground. mgflat_ground_level (Ground level) int 8 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. mgflat_large_cave_depth (Large cave depth) int -33 +# Y of upper limit of lava in large caves. +mgflat_lava_depth (Lava depth) int -256 + # Controls width of tunnels, a smaller value creates wider tunnels. mgflat_cave_width (Cave width) float 0.09 @@ -1257,9 +1266,12 @@ mgflat_np_cave2 (Cave2 noise) noise_params 0, 12, (67, 67, 67), 10325, 3, 0.5, 2 # Controls width of tunnels, a smaller value creates wider tunnels. mgfractal_cave_width (Cave width) float 0.09 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. mgfractal_large_cave_depth (Large cave depth) int -33 +# Y of upper limit of lava in large caves. +mgfractal_lava_depth (Lava depth) int -256 + # Choice of 18 fractals from 9 formulas. # 1 = 4D "Roundy" mandelbrot set. # 2 = 4D "Roundy" julia set. diff --git a/minetest.conf.example b/minetest.conf.example index 9a71ec56..d0ed146e 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -1256,10 +1256,14 @@ # type: float # mgv5_cave_width = 0.125 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. # type: int # mgv5_large_cave_depth = -256 +# Y of upper limit of lava in large caves. +# type: int +# mgv5_lava_depth = -256 + # Y-level of cavern upper limit. # type: int # mgv5_cavern_limit = -256 @@ -1375,10 +1379,14 @@ # type: float # mgv7_cave_width = 0.09 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. # type: int # mgv7_large_cave_depth = -33 +# Y of upper limit of lava in large caves. +# type: int +# mgv7_lava_depth = -256 + # Controls the density of floatland mountain terrain. # Is an offset added to the 'np_mountain' noise value. # type: float @@ -1480,10 +1488,14 @@ # type: int # mgflat_ground_level = 8 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. # type: int # mgflat_large_cave_depth = -33 +# Y of upper limit of lava in large caves. +# type: int +# mgflat_lava_depth = -256 + # Controls width of tunnels, a smaller value creates wider tunnels. # type: float # mgflat_cave_width = 0.09 @@ -1530,10 +1542,14 @@ # type: float # mgfractal_cave_width = 0.09 -# Y of upper limit of large pseudorandom caves. +# Y of upper limit of large caves. # type: int # mgfractal_large_cave_depth = -33 +# Y of upper limit of lava in large caves. +# type: int +# mgfractal_lava_depth = -256 + # Choice of 18 fractals from 9 formulas. # 1 = 4D "Roundy" mandelbrot set. # 2 = 4D "Roundy" julia set. diff --git a/src/cavegen.cpp b/src/cavegen.cpp index dbed7995..a2ecca48 100644 --- a/src/cavegen.cpp +++ b/src/cavegen.cpp @@ -258,7 +258,8 @@ CavesRandomWalk::CavesRandomWalk( s32 seed, int water_level, content_t water_source, - content_t lava_source) + content_t lava_source, + int lava_depth) { assert(ndef); @@ -267,7 +268,7 @@ CavesRandomWalk::CavesRandomWalk( this->seed = seed; this->water_level = water_level; this->np_caveliquids = &nparams_caveliquids; - this->lava_depth = DEFAULT_LAVA_DEPTH; + this->lava_depth = lava_depth; c_water_source = water_source; if (c_water_source == CONTENT_IGNORE) diff --git a/src/cavegen.h b/src/cavegen.h index a1140594..7230cf6d 100644 --- a/src/cavegen.h +++ b/src/cavegen.h @@ -21,7 +21,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #define CAVEGEN_HEADER #define VMANIP_FLAG_CAVE VOXELFLAG_CHECKED1 -#define DEFAULT_LAVA_DEPTH (-256) class GenerateNotifier; @@ -157,7 +156,8 @@ public: CavesRandomWalk(INodeDefManager *ndef, GenerateNotifier *gennotify = NULL, s32 seed = 0, int water_level = 1, content_t water_source = CONTENT_IGNORE, - content_t lava_source = CONTENT_IGNORE); + content_t lava_source = CONTENT_IGNORE, + int lava_depth = -256); // vm and ps are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to diff --git a/src/mapgen.cpp b/src/mapgen.cpp index 70de8c8e..e40bf2a7 100644 --- a/src/mapgen.cpp +++ b/src/mapgen.cpp @@ -817,7 +817,7 @@ void MapgenBasic::generateCaves(s16 max_stone_y, s16 large_cave_depth) u32 bruises_count = ps.range(0, 2); for (u32 i = 0; i < bruises_count; i++) { CavesRandomWalk cave(ndef, &gennotify, seed, water_level, - c_water_source, CONTENT_IGNORE); + c_water_source, CONTENT_IGNORE, lava_depth); cave.makeCave(vm, node_min, node_max, &ps, true, max_stone_y, heightmap); } diff --git a/src/mapgen.h b/src/mapgen.h index dde4e5c2..9369a6c3 100644 --- a/src/mapgen.h +++ b/src/mapgen.h @@ -294,6 +294,7 @@ protected: float cavern_limit; float cavern_taper; float cavern_threshold; + int lava_depth; }; #endif diff --git a/src/mapgen_flat.cpp b/src/mapgen_flat.cpp index a6efcee2..e7f5f4df 100644 --- a/src/mapgen_flat.cpp +++ b/src/mapgen_flat.cpp @@ -54,6 +54,7 @@ MapgenFlat::MapgenFlat(int mapgenid, MapgenFlatParams *params, EmergeManager *em this->spflags = params->spflags; this->ground_level = params->ground_level; this->large_cave_depth = params->large_cave_depth; + this->lava_depth = params->lava_depth; this->cave_width = params->cave_width; this->lake_threshold = params->lake_threshold; this->lake_steepness = params->lake_steepness; @@ -94,6 +95,7 @@ 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->getS16NoEx("mgflat_lava_depth", lava_depth); settings->getFloatNoEx("mgflat_cave_width", cave_width); settings->getFloatNoEx("mgflat_lake_threshold", lake_threshold); settings->getFloatNoEx("mgflat_lake_steepness", lake_steepness); @@ -112,6 +114,7 @@ void MapgenFlatParams::writeParams(Settings *settings) const settings->setFlagStr("mgflat_spflags", spflags, flagdesc_mapgen_flat, U32_MAX); settings->setS16("mgflat_ground_level", ground_level); settings->setS16("mgflat_large_cave_depth", large_cave_depth); + settings->setS16("mgflat_lava_depth", lava_depth); settings->setFloat("mgflat_cave_width", cave_width); settings->setFloat("mgflat_lake_threshold", lake_threshold); settings->setFloat("mgflat_lake_steepness", lake_steepness); diff --git a/src/mapgen_flat.h b/src/mapgen_flat.h index ab353122..7c2929d3 100644 --- a/src/mapgen_flat.h +++ b/src/mapgen_flat.h @@ -36,6 +36,7 @@ struct MapgenFlatParams : public MapgenParams u32 spflags = 0; s16 ground_level = 8; s16 large_cave_depth = -33; + s16 lava_depth = -256; float cave_width = 0.09f; float lake_threshold = -0.45f; float lake_steepness = 48.0f; diff --git a/src/mapgen_fractal.cpp b/src/mapgen_fractal.cpp index a99b3006..b43dcd3f 100644 --- a/src/mapgen_fractal.cpp +++ b/src/mapgen_fractal.cpp @@ -52,6 +52,7 @@ MapgenFractal::MapgenFractal(int mapgenid, MapgenFractalParams *params, EmergeMa this->spflags = params->spflags; this->cave_width = params->cave_width; this->large_cave_depth = params->large_cave_depth; + this->lava_depth = params->lava_depth; this->fractal = params->fractal; this->iterations = params->iterations; this->scale = params->scale; @@ -95,6 +96,7 @@ 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->getS16NoEx("mgfractal_lava_depth", lava_depth); settings->getU16NoEx("mgfractal_fractal", fractal); settings->getU16NoEx("mgfractal_iterations", iterations); settings->getV3FNoEx("mgfractal_scale", scale); @@ -117,6 +119,7 @@ void MapgenFractalParams::writeParams(Settings *settings) const settings->setFlagStr("mgfractal_spflags", spflags, flagdesc_mapgen_fractal, U32_MAX); settings->setFloat("mgfractal_cave_width", cave_width); settings->setS16("mgfractal_large_cave_depth", large_cave_depth); + settings->setS16("mgfractal_lava_depth", lava_depth); settings->setU16("mgfractal_fractal", fractal); settings->setU16("mgfractal_iterations", iterations); settings->setV3F("mgfractal_scale", scale); diff --git a/src/mapgen_fractal.h b/src/mapgen_fractal.h index 688e41c0..a14c5c5e 100644 --- a/src/mapgen_fractal.h +++ b/src/mapgen_fractal.h @@ -35,6 +35,7 @@ struct MapgenFractalParams : public MapgenParams u32 spflags = 0; float cave_width = 0.09f; s16 large_cave_depth = -33; + s16 lava_depth = -256; u16 fractal = 1; u16 iterations = 11; v3f scale = v3f(4096.0, 1024.0, 4096.0); diff --git a/src/mapgen_v5.cpp b/src/mapgen_v5.cpp index ebf9424e..04482670 100644 --- a/src/mapgen_v5.cpp +++ b/src/mapgen_v5.cpp @@ -51,6 +51,7 @@ MapgenV5::MapgenV5(int mapgenid, MapgenV5Params *params, EmergeManager *emerge) this->spflags = params->spflags; this->cave_width = params->cave_width; this->large_cave_depth = params->large_cave_depth; + this->lava_depth = params->lava_depth; this->cavern_limit = params->cavern_limit; this->cavern_taper = params->cavern_taper; this->cavern_threshold = params->cavern_threshold; @@ -96,6 +97,7 @@ 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->getS16NoEx("mgv5_lava_depth", lava_depth); settings->getS16NoEx("mgv5_cavern_limit", cavern_limit); settings->getS16NoEx("mgv5_cavern_taper", cavern_taper); settings->getFloatNoEx("mgv5_cavern_threshold", cavern_threshold); @@ -115,6 +117,7 @@ void MapgenV5Params::writeParams(Settings *settings) const settings->setFlagStr("mgv5_spflags", spflags, flagdesc_mapgen_v5, U32_MAX); settings->setFloat("mgv5_cave_width", cave_width); settings->setS16("mgv5_large_cave_depth", large_cave_depth); + settings->setS16("mgv5_lava_depth", lava_depth); settings->setS16("mgv5_cavern_limit", cavern_limit); settings->setS16("mgv5_cavern_taper", cavern_taper); settings->setFloat("mgv5_cavern_threshold", cavern_threshold); diff --git a/src/mapgen_v5.h b/src/mapgen_v5.h index 9b3f98d7..3aaff587 100644 --- a/src/mapgen_v5.h +++ b/src/mapgen_v5.h @@ -35,6 +35,7 @@ struct MapgenV5Params : public MapgenParams u32 spflags = MGV5_CAVERNS; float cave_width = 0.125f; s16 large_cave_depth = -256; + s16 lava_depth = -256; s16 cavern_limit = -256; s16 cavern_taper = 256; float cavern_threshold = 0.7f; diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index 409863fa..5d150ee1 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -57,6 +57,7 @@ MapgenV7::MapgenV7(int mapgenid, MapgenV7Params *params, EmergeManager *emerge) this->spflags = params->spflags; this->cave_width = params->cave_width; this->large_cave_depth = params->large_cave_depth; + this->lava_depth = params->lava_depth; this->float_mount_density = params->float_mount_density; this->float_mount_height = params->float_mount_height; this->floatland_level = params->floatland_level; @@ -145,6 +146,7 @@ void MapgenV7Params::readParams(const Settings *settings) settings->getFlagStrNoEx("mgv7_spflags", spflags, flagdesc_mapgen_v7); settings->getFloatNoEx("mgv7_cave_width", cave_width); settings->getS16NoEx("mgv7_large_cave_depth", large_cave_depth); + settings->getS16NoEx("mgv7_lava_depth", lava_depth); settings->getFloatNoEx("mgv7_float_mount_density", float_mount_density); settings->getFloatNoEx("mgv7_float_mount_height", float_mount_height); settings->getS16NoEx("mgv7_floatland_level", floatland_level); @@ -175,6 +177,7 @@ void MapgenV7Params::writeParams(Settings *settings) const settings->setFlagStr("mgv7_spflags", spflags, flagdesc_mapgen_v7, U32_MAX); settings->setFloat("mgv7_cave_width", cave_width); settings->setS16("mgv7_large_cave_depth", large_cave_depth); + settings->setS16("mgv7_lava_depth", lava_depth); settings->setFloat("mgv7_float_mount_density", float_mount_density); settings->setFloat("mgv7_float_mount_height", float_mount_height); settings->setS16("mgv7_floatland_level", floatland_level); diff --git a/src/mapgen_v7.h b/src/mapgen_v7.h index 3b0d11ff..7b4364ef 100644 --- a/src/mapgen_v7.h +++ b/src/mapgen_v7.h @@ -38,6 +38,7 @@ struct MapgenV7Params : public MapgenParams { u32 spflags = MGV7_MOUNTAINS | MGV7_RIDGES | MGV7_CAVERNS; float cave_width = 0.09f; s16 large_cave_depth = -33; + s16 lava_depth = -256; float float_mount_density = 0.6f; float float_mount_height = 128.0f; s16 floatland_level = 1280; From 8b9f40d12f9542dac15fdf454b2e27c53f8a5019 Mon Sep 17 00:00:00 2001 From: red-001 Date: Thu, 22 Jun 2017 12:18:58 +0100 Subject: [PATCH 26/53] Fix CSM crash caused by move to C++11. (#6027) --- src/script/lua_api/l_nodemeta.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index aa8d1c45..c446a8f0 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -176,7 +176,8 @@ NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env): } NodeMetaRef::NodeMetaRef(Metadata *meta): - m_meta(meta) + m_meta(meta), + m_is_local(true) { } From 8dd548c0b46e1db4669c1ffb44d591fb8dc7740a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Thu, 22 Jun 2017 13:20:20 +0200 Subject: [PATCH 27/53] LINT fix --- src/cavegen.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cavegen.h b/src/cavegen.h index 7230cf6d..db3e091f 100644 --- a/src/cavegen.h +++ b/src/cavegen.h @@ -156,8 +156,7 @@ public: CavesRandomWalk(INodeDefManager *ndef, GenerateNotifier *gennotify = NULL, s32 seed = 0, int water_level = 1, content_t water_source = CONTENT_IGNORE, - content_t lava_source = CONTENT_IGNORE, - int lava_depth = -256); + content_t lava_source = CONTENT_IGNORE, int lava_depth = -256); // vm and ps are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to From 08f57e1e387580b0487d1da5c195e5bf532c672b Mon Sep 17 00:00:00 2001 From: Wuzzy Date: Fri, 23 Jun 2017 13:31:01 +0200 Subject: [PATCH 28/53] Show param1 and param2 in debug screen (#6031) * Show param1 and param2 in debug screen * Add units and some formatting to debug screen * Minor refactor of param1/param2 debug display --- src/game.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/game.cpp b/src/game.cpp index b81efc33..724c9991 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -4303,17 +4303,17 @@ void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation & std::ostringstream os(std::ios_base::binary); os << std::fixed << PROJECT_NAME_C " " << g_version_hash - << " FPS = " << fps - << " (R: range_all=" << draw_control->range_all << ")" + << "; " << fps << " FPS" + << ", (R: range_all=" << draw_control->range_all << ")" << std::setprecision(0) - << " drawtime = " << drawtime_avg + << ", drawtime = " << drawtime_avg << " ms" << std::setprecision(1) << ", dtime_jitter = " << (stats.dtime_jitter.max_fraction * 100.0) << " %" << std::setprecision(1) << ", v_range = " << draw_control->wanted_range << std::setprecision(3) - << ", RTT = " << client->getRTT(); + << ", RTT = " << client->getRTT() << " s"; setStaticText(guitext, utf8_to_wide(os.str()).c_str()); guitext->setVisible(true); } else { @@ -4334,7 +4334,7 @@ void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation & << "(" << (player_position.X / BS) << ", " << (player_position.Y / BS) << ", " << (player_position.Z / BS) - << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw)) + << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw)) << "°" << " " << yawToDirectionString(cam.camera_yaw) << ") (seed = " << ((u64)client->getMapSeed()) << ")"; @@ -4345,9 +4345,11 @@ void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation & MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface); if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") { const ContentFeatures &features = nodedef->get(n); - os << " (pointing_at = " << nodedef->get(n).name - << " - " << features.tiledef[0].name.c_str() - << ")"; + os << " (pointing_at = \"" << nodedef->get(n).name + << "\", param1 = " << (u64) n.getParam1() + << ", param2 = " << (u64) n.getParam2() + << ", tiledef[0] = \"" << features.tiledef[0].name.c_str() + << "\")"; } } From 9a77397fbfb95a0b45ed33831291259626968500 Mon Sep 17 00:00:00 2001 From: paramat Date: Thu, 22 Jun 2017 03:48:22 +0100 Subject: [PATCH 29/53] Mgvalleys: Use existing 'lava_max_height' value in CavesRandomWalk Now that lava depth in large caves is variable we can use the already present 'lava_max_height' value to set the lava depth in them. --- src/mapgen_valleys.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mapgen_valleys.cpp b/src/mapgen_valleys.cpp index 8e5f3d3a..cf982206 100644 --- a/src/mapgen_valleys.cpp +++ b/src/mapgen_valleys.cpp @@ -733,7 +733,7 @@ void MapgenValleys::generateCaves(s16 max_stone_y, s16 large_cave_depth) u32 bruises_count = ps.range(0, 2); for (u32 i = 0; i < bruises_count; i++) { CavesRandomWalk cave(ndef, &gennotify, seed, water_level, - c_water_source, c_lava_source); + c_water_source, c_lava_source, lava_max_height); cave.makeCave(vm, node_min, node_max, &ps, true, max_stone_y, heightmap); } From 34e8e0e5ce2887391f55d5d7285088ec2c0f5761 Mon Sep 17 00:00:00 2001 From: paramat Date: Fri, 23 Jun 2017 21:49:26 +0100 Subject: [PATCH 30/53] Mgv7: Avoid divide-by-zero errors Some settings of paramters can cause mgv7 variables to be -inf, nan or -nan. This can cause massive vertical columns of water to appear above sea level. --- src/mapgen_v7.cpp | 14 ++++++++------ src/mapgen_v7.h | 2 ++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index 5d150ee1..d74d050e 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -59,7 +59,7 @@ MapgenV7::MapgenV7(int mapgenid, MapgenV7Params *params, EmergeManager *emerge) this->large_cave_depth = params->large_cave_depth; this->lava_depth = params->lava_depth; this->float_mount_density = params->float_mount_density; - this->float_mount_height = params->float_mount_height; + float_mount_height_lim = MYMAX(params->float_mount_height, 1.0f); this->floatland_level = params->floatland_level; this->shadow_limit = params->shadow_limit; this->cavern_limit = params->cavern_limit; @@ -382,7 +382,8 @@ float MapgenV7::baseTerrainLevelFromMap(int index) bool MapgenV7::getMountainTerrainAtPoint(s16 x, s16 y, s16 z) { - float mnt_h_n = NoisePerlin2D(&noise_mount_height->np, x, z, seed); + float mnt_h_n = + MYMAX(NoisePerlin2D(&noise_mount_height->np, x, z, seed), 1.0f); float density_gradient = -((float)y / mnt_h_n); float mnt_n = NoisePerlin3D(&noise_mountain->np, x, y, z, seed); @@ -392,7 +393,7 @@ bool MapgenV7::getMountainTerrainAtPoint(s16 x, s16 y, s16 z) bool MapgenV7::getMountainTerrainFromMap(int idx_xyz, int idx_xz, s16 y) { - float mounthn = noise_mount_height->result[idx_xz]; + float mounthn = MYMAX(noise_mount_height->result[idx_xz], 1.0f); float density_gradient = -((float)y / mounthn); float mountn = noise_mountain->result[idx_xyz]; @@ -404,8 +405,8 @@ bool MapgenV7::getFloatlandMountainFromMap(int idx_xyz, int idx_xz, s16 y) { // Make rim 2 nodes thick to match floatland base terrain float density_gradient = (y >= floatland_level) ? - -pow((float)(y - floatland_level) / float_mount_height, 0.75f) : - -pow((float)(floatland_level - 1 - y) / float_mount_height, 0.75f); + -pow((float)(y - floatland_level) / float_mount_height_lim, 0.75f) : + -pow((float)(floatland_level - 1 - y) / float_mount_height_lim, 0.75f); float floatn = noise_mountain->result[idx_xyz] + float_mount_density; @@ -421,7 +422,8 @@ void MapgenV7::floatBaseExtentFromMap(s16 *float_base_min, s16 *float_base_max, float n_base = noise_floatland_base->result[idx_xz]; if (n_base > 0.0f) { - float n_base_height = noise_float_base_height->result[idx_xz]; + float n_base_height = + MYMAX(noise_float_base_height->result[idx_xz], 1.0f); float amp = n_base * n_base_height; float ridge = n_base_height / 3.0f; base_min = floatland_level - amp / 1.5f; diff --git a/src/mapgen_v7.h b/src/mapgen_v7.h index 7b4364ef..b88d90de 100644 --- a/src/mapgen_v7.h +++ b/src/mapgen_v7.h @@ -106,6 +106,8 @@ private: Noise *noise_float_base_height; Noise *noise_mountain; Noise *noise_ridge; + + float float_mount_height_lim; }; #endif From 8a84e8992231e934c1276ba9b43a9eeaa7184b59 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Sat, 24 Jun 2017 11:43:17 +0200 Subject: [PATCH 31/53] Game::showOverlayMessage: securise function Do wgettext call directly in the function instead of caller, as we destroy wstd inside it --- src/game.cpp | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/game.cpp b/src/game.cpp index 724c9991..cd407597 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -1316,7 +1316,7 @@ protected: // Misc void limitFps(FpsControl *fps_timings, f32 *dtime); - void showOverlayMessage(const wchar_t *msg, float dtime, int percent, + void showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds = true); static void settingChangedCallback(const std::string &setting_name, void *data); @@ -1729,7 +1729,7 @@ void Game::shutdown() if (current_formspec) current_formspec->quitMenu(); - showOverlayMessage(wgettext("Shutting down..."), 0, 0, false); + showOverlayMessage("Shutting down...", 0, 0, false); if (clouds) clouds->drop(); @@ -1781,7 +1781,7 @@ bool Game::init( { texture_src = createTextureSource(device); - showOverlayMessage(wgettext("Loading..."), 0, 0); + showOverlayMessage("Loading...", 0, 0); shader_src = createShaderSource(device); @@ -1837,7 +1837,7 @@ bool Game::initSound() bool Game::createSingleplayerServer(const std::string &map_dir, const SubgameSpec &gamespec, u16 port, std::string *address) { - showOverlayMessage(wgettext("Creating server..."), 0, 5); + showOverlayMessage("Creating server...", 0, 5); std::string bind_str = g_settings->get("bind_address"); Address bind_addr(0, 0, 0, 0, port); @@ -1873,7 +1873,7 @@ bool Game::createSingleplayerServer(const std::string &map_dir, bool Game::createClient(const std::string &playername, const std::string &password, std::string *address, u16 port) { - showOverlayMessage(wgettext("Creating client..."), 0, 10); + showOverlayMessage("Creating client...", 0, 10); draw_control = new MapDrawControl; if (!draw_control) @@ -2059,7 +2059,7 @@ bool Game::connectToServer(const std::string &playername, *aborted = false; bool local_server_mode = false; - showOverlayMessage(wgettext("Resolving address..."), 0, 15); + showOverlayMessage("Resolving address...", 0, 15); Address connect_address(0, 0, 0, 0, port); @@ -2181,7 +2181,7 @@ bool Game::connectToServer(const std::string &playername, } // Update status - showOverlayMessage(wgettext("Connecting to server..."), dtime, 20); + showOverlayMessage("Connecting to server...", dtime, 20); } } catch (con::PeerNotFoundException &e) { // TODO: Should something be done here? At least an info/error @@ -4466,15 +4466,13 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime) fps_timings->last_time = time; } -// Note: This will free (using delete[])! \p msg. If you want to use it later, -// pass a copy of it to this function -// Note: \p msg must be allocated using new (not malloc()) -void Game::showOverlayMessage(const wchar_t *msg, float dtime, +void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds) { - draw_load_screen(msg, device, guienv, texture_src, dtime, percent, + const wchar_t *wmsg = wgettext(msg); + draw_load_screen(wmsg, device, guienv, texture_src, dtime, percent, draw_clouds); - delete[] msg; + delete[] wmsg; } void Game::settingChangedCallback(const std::string &setting_name, void *data) From 9da5fb1583211b44afa4d28f3ccb64d768c56771 Mon Sep 17 00:00:00 2001 From: Vincent Glize Date: Sat, 24 Jun 2017 13:41:30 +0200 Subject: [PATCH 32/53] C++11 cleanup on constructors guiEngine (#6036) * C++11 cleanup on constructors guiEngine --- src/guiEngine.cpp | 40 ++++++++++++--------------------------- src/guiEngine.h | 48 +++++++++++++++++++++++------------------------ 2 files changed, 36 insertions(+), 52 deletions(-) diff --git a/src/guiEngine.cpp b/src/guiEngine.cpp index 0abb2479..d4b98c1c 100644 --- a/src/guiEngine.cpp +++ b/src/guiEngine.cpp @@ -45,14 +45,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #endif -/******************************************************************************/ -/** TextDestGuiEngine */ -/******************************************************************************/ -TextDestGuiEngine::TextDestGuiEngine(GUIEngine* engine) -{ - m_engine = engine; -} - /******************************************************************************/ void TextDestGuiEngine::gotText(const StringMap &fields) { @@ -65,14 +57,6 @@ void TextDestGuiEngine::gotText(const std::wstring &text) m_engine->getScriptIface()->handleMainMenuEvent(wide_to_utf8(text)); } -/******************************************************************************/ -/** MenuTextureSource */ -/******************************************************************************/ -MenuTextureSource::MenuTextureSource(video::IVideoDriver *driver) -{ - m_driver = driver; -} - /******************************************************************************/ MenuTextureSource::~MenuTextureSource() { @@ -85,7 +69,7 @@ MenuTextureSource::~MenuTextureSource() } /******************************************************************************/ -video::ITexture* MenuTextureSource::getTexture(const std::string &name, u32 *id) +video::ITexture *MenuTextureSource::getTexture(const std::string &name, u32 *id) { if(id) *id = 0; @@ -130,13 +114,13 @@ void MenuMusicFetcher::fetchSounds(const std::string &name, /******************************************************************************/ /** GUIEngine */ /******************************************************************************/ -GUIEngine::GUIEngine( irr::IrrlichtDevice* dev, - JoystickController *joystick, - gui::IGUIElement* parent, - IMenuManager *menumgr, - scene::ISceneManager* smgr, - MainMenuData* data, - bool& kill) : +GUIEngine::GUIEngine(irr::IrrlichtDevice *dev, + JoystickController *joystick, + gui::IGUIElement *parent, + IMenuManager *menumgr, + scene::ISceneManager *smgr, + MainMenuData *data, + bool &kill) : m_device(dev), m_parent(parent), m_menumanager(menumgr), @@ -388,7 +372,7 @@ void GUIEngine::cloudPostProcess() } /******************************************************************************/ -void GUIEngine::drawBackground(video::IVideoDriver* driver) +void GUIEngine::drawBackground(video::IVideoDriver *driver) { v2u32 screensize = driver->getScreenSize(); @@ -430,7 +414,7 @@ void GUIEngine::drawBackground(video::IVideoDriver* driver) } /******************************************************************************/ -void GUIEngine::drawOverlay(video::IVideoDriver* driver) +void GUIEngine::drawOverlay(video::IVideoDriver *driver) { v2u32 screensize = driver->getScreenSize(); @@ -449,7 +433,7 @@ void GUIEngine::drawOverlay(video::IVideoDriver* driver) } /******************************************************************************/ -void GUIEngine::drawHeader(video::IVideoDriver* driver) +void GUIEngine::drawHeader(video::IVideoDriver *driver) { core::dimension2d screensize = driver->getScreenSize(); @@ -483,7 +467,7 @@ void GUIEngine::drawHeader(video::IVideoDriver* driver) } /******************************************************************************/ -void GUIEngine::drawFooter(video::IVideoDriver* driver) +void GUIEngine::drawFooter(video::IVideoDriver *driver) { core::dimension2d screensize = driver->getScreenSize(); diff --git a/src/guiEngine.h b/src/guiEngine.h index e6cea6b4..cf2bade7 100644 --- a/src/guiEngine.h +++ b/src/guiEngine.h @@ -43,7 +43,7 @@ typedef enum { } texture_layer; typedef struct { - video::ITexture* texture; + video::ITexture *texture = nullptr; bool tile; unsigned int minsize; } image_definition; @@ -68,7 +68,7 @@ public: * default constructor * @param engine the engine data is transmitted for further processing */ - TextDestGuiEngine(GUIEngine* engine); + TextDestGuiEngine(GUIEngine* engine) : m_engine(engine) {}; /** * receive fields transmitted by guiFormSpecMenu @@ -84,7 +84,7 @@ public: private: /** target to transmit data to */ - GUIEngine* m_engine; + GUIEngine *m_engine = nullptr; }; /** GUIEngine specific implementation of ISimpleTextureSource */ @@ -95,7 +95,7 @@ public: * default constructor * @param driver the video driver to load textures from */ - MenuTextureSource(video::IVideoDriver *driver); + MenuTextureSource(video::IVideoDriver *driver) : m_driver(driver) {}; /** * destructor, removes all loaded textures @@ -107,11 +107,11 @@ public: * @param name path to the texture * @param id receives the texture ID, always 0 in this implementation */ - video::ITexture* getTexture(const std::string &name, u32 *id = NULL); + video::ITexture *getTexture(const std::string &name, u32 *id = NULL); private: /** driver to get textures from */ - video::IVideoDriver *m_driver; + video::IVideoDriver *m_driver = nullptr; /** set of texture names to delete */ std::set m_to_delete; }; @@ -150,13 +150,13 @@ public: * @param smgr scene manager to add scene elements to * @param data struct to transfer data to main game handling */ - GUIEngine(irr::IrrlichtDevice* dev, + GUIEngine(irr::IrrlichtDevice *dev, JoystickController *joystick, - gui::IGUIElement* parent, + gui::IGUIElement *parent, IMenuManager *menumgr, - scene::ISceneManager* smgr, - MainMenuData* data, - bool& kill); + scene::ISceneManager *smgr, + MainMenuData *data, + bool &kill); /** default destructor */ virtual ~GUIEngine(); @@ -164,7 +164,7 @@ public: /** * return MainMenuScripting interface */ - MainMenuScripting* getScriptIface() + MainMenuScripting *getScriptIface() { return m_script; } @@ -193,15 +193,15 @@ private: void updateTopLeftTextSize(); /** device to draw at */ - irr::IrrlichtDevice* m_device; + irr::IrrlichtDevice *m_device = nullptr; /** parent gui element */ - gui::IGUIElement* m_parent; + gui::IGUIElement *m_parent = nullptr; /** manager to add menus to */ - IMenuManager* m_menumanager; + IMenuManager *m_menumanager = nullptr; /** scene manager to add scene elements to */ - scene::ISceneManager* m_smgr; + scene::ISceneManager *m_smgr = nullptr; /** pointer to data beeing transfered back to main game handling */ - MainMenuData* m_data; + MainMenuData *m_data = nullptr; /** pointer to texture source */ ISimpleTextureSource *m_texture_source = nullptr; /** pointer to soundmanager*/ @@ -215,7 +215,7 @@ private: 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; @@ -230,22 +230,22 @@ private: * draw background layer * @param driver to use for drawing */ - void drawBackground(video::IVideoDriver* driver); + void drawBackground(video::IVideoDriver *driver); /** * draw overlay layer * @param driver to use for drawing */ - void drawOverlay(video::IVideoDriver* driver); + void drawOverlay(video::IVideoDriver *driver); /** * draw header layer * @param driver to use for drawing */ - void drawHeader(video::IVideoDriver* driver); + void drawHeader(video::IVideoDriver *driver); /** * draw footer layer * @param driver to use for drawing */ - void drawFooter(video::IVideoDriver* driver); + void drawFooter(video::IVideoDriver *driver); /** * load a texture for a specified layer @@ -290,9 +290,9 @@ private: /** absolute time of last cloud processing */ u32 lasttime; /** pointer to cloud class */ - Clouds* clouds; + Clouds *clouds = nullptr; /** camera required for drawing clouds */ - scene::ICameraSceneNode* camera; + scene::ICameraSceneNode *camera = nullptr; }; /** is drawing of clouds enabled atm */ From c2df1a08351101034f52fd2810051715714c9c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1niel=20Juh=C3=A1sz?= Date: Sat, 24 Jun 2017 18:15:00 +0000 Subject: [PATCH 33/53] Emit liquid sound if the player walks in liquid (#6040) --- src/localplayer.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/localplayer.cpp b/src/localplayer.cpp index aa38f338..a77dcab0 100644 --- a/src/localplayer.cpp +++ b/src/localplayer.cpp @@ -723,6 +723,9 @@ v3s16 LocalPlayer::getStandingNodePos() v3s16 LocalPlayer::getFootstepNodePos() { + if (in_liquid_stable) + // Emit swimming sound if the player is in liquid + return floatToInt(getPosition(), BS); if (touching_ground) // BS * 0.05 below the player's feet ensures a 1/16th height // nodebox is detected instead of the node below it. From 5a41a98ff6ac899038bfc359912ebb021479451b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1niel=20Juh=C3=A1sz?= Date: Sat, 24 Jun 2017 18:15:09 +0000 Subject: [PATCH 34/53] Helper methods for hardware colorization (#5870) --- builtin/game/item.lua | 12 ++++++++++++ doc/lua_api.txt | 21 ++++++++++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/builtin/game/item.lua b/builtin/game/item.lua index f6de2c33..59ec5ff6 100644 --- a/builtin/game/item.lua +++ b/builtin/game/item.lua @@ -572,6 +572,18 @@ function core.node_dig(pos, node, digger) end end +function core.itemstring_with_palette(item, palette_index) + local stack = ItemStack(item) -- convert to ItemStack + stack:get_meta():set_int("palette_index", palette_index) + return stack:to_string() +end + +function core.itemstring_with_color(item, colorstring) + local stack = ItemStack(item) -- convert to ItemStack + stack:get_meta():set_string("color", colorstring) + return stack:to_string() +end + -- This is used to allow mods to redefine core.item_place and so on -- NOTE: This is not the preferred way. Preferred way is to provide enough -- callbacks to not require redefining global functions. -celeron55 diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 664ad960..540bbe11 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -541,10 +541,8 @@ to itself (without metadata). Craft recipes only support item strings, but fortunately item strings can also contain metadata. Example craft recipe registration: - local stack = ItemStack("wool:block") - dyed:get_meta():set_int("palette_index", 3) -- add index minetest.register_craft({ - output = dyed:to_string(), -- convert to string + output = minetest.itemstring_with_palette("wool:block", 3), type = "shapeless", recipe = { "wool:block", @@ -552,6 +550,8 @@ can also contain metadata. Example craft recipe registration: }, }) +To set the `color` field, you can use `minetest.itemstring_with_color`. + Metadata field filtering in the `recipe` field are not supported yet, so the craft output is independent of the color of the ingredients. @@ -2728,6 +2728,21 @@ and `minetest.auth_reload` call the authetification handler. digger's inventory * Can be overridden to get different functionality (e.g. dropping items on ground) +* `minetest.itemstring_with_palette(item, palette_index)`: returns an item string + * Creates an item string which contains palette index information + for hardware colorization. You can use the returned string + as an output in a craft recipe. + * `item`: the item stack which becomes colored. Can be in string, + table and native form. + * `palette_index`: this index is added to the item stack +* `minetest.itemstring_with_color(item, colorstring)`: returns an item string + * Creates an item string which contains static color information + for hardware colorization. Use this method if you wish to colorize + an item that does not own a palette. You can use the returned string + as an output in a craft recipe. + * `item`: the item stack which becomes colored. Can be in string, + table and native form. + * `colorstring`: the new color of the item stack ### Rollback * `minetest.rollback_get_node_actions(pos, range, seconds, limit)`: From 90ed6fc732ca667ca970b7c38d39c809e5c3553e Mon Sep 17 00:00:00 2001 From: paramat Date: Thu, 22 Jun 2017 06:50:22 +0100 Subject: [PATCH 35/53] Ores: Make 'absheight' flag non-functional The 'absheight' flag was added years ago for the floatlands of 'indev' mapgen (now deleted). The feature mirrored all ore placement around y = 0 to place ores in floatlands. In MTG we now use dedicated ore registrations for floatlands. The feature is crude, inflexible, problematic and very rarely used, it also makes ore vertical range code more complex. Minetest 0.5 is a good chance to remove the feature. The flag itself remains to not break flag values. --- doc/lua_api.txt | 7 +------ src/mg_ore.cpp | 19 ++++--------------- src/mg_ore.h | 5 +---- 3 files changed, 6 insertions(+), 25 deletions(-) diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 540bbe11..63d090eb 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1076,12 +1076,7 @@ Ore attributes See section "Flag Specifier Format". Currently supported flags: -`absheight`, `puff_cliffs`, `puff_additive_composition`. - -### `absheight` -Also produce this same ore between the height range of `-y_max` and `-y_min`. - -Useful for having ore in sky realms without having to duplicate ore entries. +`puff_cliffs`, `puff_additive_composition`. ### `puff_cliffs` If set, puff ore generation will not taper down large differences in displacement diff --git a/src/mg_ore.cpp b/src/mg_ore.cpp index f959ca9e..73af2e2e 100644 --- a/src/mg_ore.cpp +++ b/src/mg_ore.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., FlagDesc flagdesc_ore[] = { - {"absheight", OREFLAG_ABSHEIGHT}, + {"absheight", OREFLAG_ABSHEIGHT}, // Non-functional {"puff_cliffs", OREFLAG_PUFF_CLIFFS}, {"puff_additive_composition", OREFLAG_PUFF_ADDITIVE}, {NULL, 0} @@ -87,22 +87,11 @@ void Ore::resolveNodeNames() size_t Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { - int in_range = 0; - - in_range |= (nmin.Y <= y_max && nmax.Y >= y_min); - if (flags & OREFLAG_ABSHEIGHT) - in_range |= (nmin.Y >= -y_max && nmax.Y <= -y_min) << 1; - if (!in_range) + if (!(nmin.Y <= y_max && nmax.Y >= y_min)) return 0; - int actual_ymin, actual_ymax; - if (in_range & ORE_RANGE_MIRROR) { - actual_ymin = MYMAX(nmin.Y, -y_max); - actual_ymax = MYMIN(nmax.Y, -y_min); - } else { - actual_ymin = MYMAX(nmin.Y, y_min); - actual_ymax = MYMIN(nmax.Y, y_max); - } + int actual_ymin = MYMAX(nmin.Y, y_min); + int actual_ymax = MYMIN(nmax.Y, y_max); if (clust_size >= actual_ymax - actual_ymin + 1) return 0; diff --git a/src/mg_ore.h b/src/mg_ore.h index 4b052e07..5aeb3631 100644 --- a/src/mg_ore.h +++ b/src/mg_ore.h @@ -32,14 +32,11 @@ class MMVManip; /////////////////// Ore generation flags -#define OREFLAG_ABSHEIGHT 0x01 +#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 ORE_RANGE_ACTUAL 1 -#define ORE_RANGE_MIRROR 2 - enum OreType { ORE_SCATTER, ORE_SHEET, From cad10ce3b747b721fd63784915e05f12bc488128 Mon Sep 17 00:00:00 2001 From: paramat Date: Sun, 25 Jun 2017 04:45:40 +0100 Subject: [PATCH 36/53] Mgv7: Clean up divide-by-zero fix --- src/mapgen_v7.cpp | 9 ++++++--- src/mapgen_v7.h | 2 -- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index d74d050e..4b1844a7 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -59,13 +59,16 @@ MapgenV7::MapgenV7(int mapgenid, MapgenV7Params *params, EmergeManager *emerge) this->large_cave_depth = params->large_cave_depth; this->lava_depth = params->lava_depth; this->float_mount_density = params->float_mount_density; - float_mount_height_lim = MYMAX(params->float_mount_height, 1.0f); this->floatland_level = params->floatland_level; this->shadow_limit = params->shadow_limit; this->cavern_limit = params->cavern_limit; this->cavern_taper = params->cavern_taper; this->cavern_threshold = params->cavern_threshold; + // This is to avoid a divide-by-zero. + // Parameter will be saved to map_meta.txt in limited form. + params->float_mount_height = MYMAX(params->float_mount_height, 1.0f); + // 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); @@ -405,8 +408,8 @@ bool MapgenV7::getFloatlandMountainFromMap(int idx_xyz, int idx_xz, s16 y) { // Make rim 2 nodes thick to match floatland base terrain float density_gradient = (y >= floatland_level) ? - -pow((float)(y - floatland_level) / float_mount_height_lim, 0.75f) : - -pow((float)(floatland_level - 1 - y) / float_mount_height_lim, 0.75f); + -pow((float)(y - floatland_level) / float_mount_height, 0.75f) : + -pow((float)(floatland_level - 1 - y) / float_mount_height, 0.75f); float floatn = noise_mountain->result[idx_xyz] + float_mount_density; diff --git a/src/mapgen_v7.h b/src/mapgen_v7.h index b88d90de..7b4364ef 100644 --- a/src/mapgen_v7.h +++ b/src/mapgen_v7.h @@ -106,8 +106,6 @@ private: Noise *noise_float_base_height; Noise *noise_mountain; Noise *noise_ridge; - - float float_mount_height_lim; }; #endif From c08cc0533fbf344be5243485f39a471268855149 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Sun, 25 Jun 2017 11:39:39 +0200 Subject: [PATCH 37/53] Inventory: Fix wrong stack size behaviour and item loss (#6039) Also fix itemFits and remove constness-nonsense --- src/database-postgresql.cpp | 2 +- src/database-sqlite3.cpp | 2 +- src/inventory.cpp | 12 ++++-------- src/inventory.h | 5 ++--- 4 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/database-postgresql.cpp b/src/database-postgresql.cpp index ac25afd4..3c54f48d 100644 --- a/src/database-postgresql.cpp +++ b/src/database-postgresql.cpp @@ -584,7 +584,7 @@ bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) if (itemStr.length() > 0) { ItemStack stack; stack.deSerialize(itemStr); - invList->addItem(pg_to_uint(results2, row2, 0), stack); + invList->changeItem(pg_to_uint(results2, row2, 0), stack); } } PQclear(results2); diff --git a/src/database-sqlite3.cpp b/src/database-sqlite3.cpp index 22765c8d..77451fad 100644 --- a/src/database-sqlite3.cpp +++ b/src/database-sqlite3.cpp @@ -565,7 +565,7 @@ bool PlayerDatabaseSQLite3::loadPlayer(RemotePlayer *player, PlayerSAO *sao) if (itemStr.length() > 0) { ItemStack stack; stack.deSerialize(itemStr); - invList->addItem(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); diff --git a/src/inventory.cpp b/src/inventory.cpp index 24eebba8..4da380a2 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -254,11 +254,8 @@ std::string ItemStack::getItemString() const } -ItemStack ItemStack::addItem(const ItemStack &newitem_, - IItemDefManager *itemdef) +ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef) { - ItemStack newitem = newitem_; - // If the item is empty or the position invalid, bail out if(newitem.empty()) { @@ -267,7 +264,7 @@ ItemStack ItemStack::addItem(const ItemStack &newitem_, // If this is an empty item, it's an easy job. else if(empty()) { - const u16 stackMax = getStackMax(itemdef); + const u16 stackMax = newitem.getStackMax(itemdef); *this = newitem; @@ -303,11 +300,10 @@ ItemStack ItemStack::addItem(const ItemStack &newitem_, return newitem; } -bool ItemStack::itemFits(const ItemStack &newitem_, +bool ItemStack::itemFits(ItemStack newitem, ItemStack *restitem, IItemDefManager *itemdef) const { - ItemStack newitem = newitem_; // If the item is empty or the position invalid, bail out if(newitem.empty()) @@ -317,7 +313,7 @@ bool ItemStack::itemFits(const ItemStack &newitem_, // If this is an empty item, it's an easy job. else if(empty()) { - const u16 stackMax = getStackMax(itemdef); + const u16 stackMax = newitem.getStackMax(itemdef); // If the item fits fully, delete it if (newitem.count <= stackMax) { diff --git a/src/inventory.h b/src/inventory.h index 04c8156c..2f8757f1 100644 --- a/src/inventory.h +++ b/src/inventory.h @@ -143,13 +143,12 @@ struct ItemStack // If cannot be added at all, returns the item back. // If can be added partly, decremented item is returned back. // If can be added fully, empty item is returned. - ItemStack addItem(const ItemStack &newitem, - IItemDefManager *itemdef); + ItemStack addItem(ItemStack newitem, IItemDefManager *itemdef); // Checks whether newitem could be added. // If restitem is non-NULL, it receives the part of newitem that // would be left over after adding. - bool itemFits(const ItemStack &newitem, + bool itemFits(ItemStack newitem, ItemStack *restitem, // may be NULL IItemDefManager *itemdef) const; From 1237206d4bdf840ae89018d14a0510035d54d0d3 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Sun, 25 Jun 2017 23:08:31 +0200 Subject: [PATCH 38/53] Revert "Ores: Make 'absheight' flag non-functional" This reverts commit 90ed6fc732ca667ca970b7c38d39c809e5c3553e. --- doc/lua_api.txt | 7 ++++++- src/mg_ore.cpp | 19 +++++++++++++++---- src/mg_ore.h | 5 ++++- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 63d090eb..540bbe11 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1076,7 +1076,12 @@ Ore attributes See section "Flag Specifier Format". Currently supported flags: -`puff_cliffs`, `puff_additive_composition`. +`absheight`, `puff_cliffs`, `puff_additive_composition`. + +### `absheight` +Also produce this same ore between the height range of `-y_max` and `-y_min`. + +Useful for having ore in sky realms without having to duplicate ore entries. ### `puff_cliffs` If set, puff ore generation will not taper down large differences in displacement diff --git a/src/mg_ore.cpp b/src/mg_ore.cpp index 73af2e2e..f959ca9e 100644 --- a/src/mg_ore.cpp +++ b/src/mg_ore.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., FlagDesc flagdesc_ore[] = { - {"absheight", OREFLAG_ABSHEIGHT}, // Non-functional + {"absheight", OREFLAG_ABSHEIGHT}, {"puff_cliffs", OREFLAG_PUFF_CLIFFS}, {"puff_additive_composition", OREFLAG_PUFF_ADDITIVE}, {NULL, 0} @@ -87,11 +87,22 @@ void Ore::resolveNodeNames() size_t Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { - if (!(nmin.Y <= y_max && nmax.Y >= y_min)) + int in_range = 0; + + in_range |= (nmin.Y <= y_max && nmax.Y >= y_min); + if (flags & OREFLAG_ABSHEIGHT) + in_range |= (nmin.Y >= -y_max && nmax.Y <= -y_min) << 1; + if (!in_range) return 0; - int actual_ymin = MYMAX(nmin.Y, y_min); - int actual_ymax = MYMIN(nmax.Y, y_max); + int actual_ymin, actual_ymax; + if (in_range & ORE_RANGE_MIRROR) { + actual_ymin = MYMAX(nmin.Y, -y_max); + actual_ymax = MYMIN(nmax.Y, -y_min); + } else { + actual_ymin = MYMAX(nmin.Y, y_min); + actual_ymax = MYMIN(nmax.Y, y_max); + } if (clust_size >= actual_ymax - actual_ymin + 1) return 0; diff --git a/src/mg_ore.h b/src/mg_ore.h index 5aeb3631..4b052e07 100644 --- a/src/mg_ore.h +++ b/src/mg_ore.h @@ -32,11 +32,14 @@ class MMVManip; /////////////////// Ore generation flags -#define OREFLAG_ABSHEIGHT 0x01 // Non-functional but kept to not break flags +#define OREFLAG_ABSHEIGHT 0x01 #define OREFLAG_PUFF_CLIFFS 0x02 #define OREFLAG_PUFF_ADDITIVE 0x04 #define OREFLAG_USE_NOISE 0x08 +#define ORE_RANGE_ACTUAL 1 +#define ORE_RANGE_MIRROR 2 + enum OreType { ORE_SCATTER, ORE_SHEET, From 936d67dad4c4939c9f7c30f489d8bfc74f47fcaf Mon Sep 17 00:00:00 2001 From: paramat Date: Thu, 22 Jun 2017 06:50:22 +0100 Subject: [PATCH 39/53] Ores: Make 'absheight' flag non-functional The 'absheight' flag was added years ago for the floatlands of 'indev' mapgen (now deleted). The feature mirrored all ore placement around y = 0 to place ores in floatlands. In MTG we now use dedicated ore registrations for floatlands. The feature is crude, inflexible, problematic and very rarely used, it also makes ore vertical range code more complex. Minetest 0.5 is a good chance to remove the feature. The flag itself remains to not break flag values. --- doc/lua_api.txt | 7 +------ src/mg_ore.cpp | 19 ++++--------------- src/mg_ore.h | 5 +---- 3 files changed, 6 insertions(+), 25 deletions(-) diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 540bbe11..63d090eb 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1076,12 +1076,7 @@ Ore attributes See section "Flag Specifier Format". Currently supported flags: -`absheight`, `puff_cliffs`, `puff_additive_composition`. - -### `absheight` -Also produce this same ore between the height range of `-y_max` and `-y_min`. - -Useful for having ore in sky realms without having to duplicate ore entries. +`puff_cliffs`, `puff_additive_composition`. ### `puff_cliffs` If set, puff ore generation will not taper down large differences in displacement diff --git a/src/mg_ore.cpp b/src/mg_ore.cpp index f959ca9e..73af2e2e 100644 --- a/src/mg_ore.cpp +++ b/src/mg_ore.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., FlagDesc flagdesc_ore[] = { - {"absheight", OREFLAG_ABSHEIGHT}, + {"absheight", OREFLAG_ABSHEIGHT}, // Non-functional {"puff_cliffs", OREFLAG_PUFF_CLIFFS}, {"puff_additive_composition", OREFLAG_PUFF_ADDITIVE}, {NULL, 0} @@ -87,22 +87,11 @@ void Ore::resolveNodeNames() size_t Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { - int in_range = 0; - - in_range |= (nmin.Y <= y_max && nmax.Y >= y_min); - if (flags & OREFLAG_ABSHEIGHT) - in_range |= (nmin.Y >= -y_max && nmax.Y <= -y_min) << 1; - if (!in_range) + if (!(nmin.Y <= y_max && nmax.Y >= y_min)) return 0; - int actual_ymin, actual_ymax; - if (in_range & ORE_RANGE_MIRROR) { - actual_ymin = MYMAX(nmin.Y, -y_max); - actual_ymax = MYMIN(nmax.Y, -y_min); - } else { - actual_ymin = MYMAX(nmin.Y, y_min); - actual_ymax = MYMIN(nmax.Y, y_max); - } + int actual_ymin = MYMAX(nmin.Y, y_min); + int actual_ymax = MYMIN(nmax.Y, y_max); if (clust_size >= actual_ymax - actual_ymin + 1) return 0; diff --git a/src/mg_ore.h b/src/mg_ore.h index 4b052e07..5aeb3631 100644 --- a/src/mg_ore.h +++ b/src/mg_ore.h @@ -32,14 +32,11 @@ class MMVManip; /////////////////// Ore generation flags -#define OREFLAG_ABSHEIGHT 0x01 +#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 ORE_RANGE_ACTUAL 1 -#define ORE_RANGE_MIRROR 2 - enum OreType { ORE_SCATTER, ORE_SHEET, From 1d1d922a7aafc464ec4483a2f8caa8c49ddbbdee Mon Sep 17 00:00:00 2001 From: kilbith Date: Mon, 26 Jun 2017 20:03:48 +0200 Subject: [PATCH 40/53] Add Arm Inertia (#6050) --- builtin/settingtypes.txt | 4 ++ minetest.conf.example | 5 +++ src/camera.cpp | 83 ++++++++++++++++++++++++++++++++++++++-- src/camera.h | 9 +++++ src/defaultsettings.cpp | 1 + 5 files changed, 99 insertions(+), 3 deletions(-) diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index f15fc679..192ce5b6 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -469,6 +469,10 @@ enable_waving_plants (Waving plants) bool false [***Advanced] +# Arm inertia, gives a more realistic movement of +# the arm when the camera moves. +arm_inertia (Arm inertia) bool true + # If FPS would go higher than this, limit it by sleeping # to not waste CPU power for no benefit. fps_max (Maximum FPS) int 60 diff --git a/minetest.conf.example b/minetest.conf.example index d0ed146e..f5f3f5e8 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -534,6 +534,11 @@ #### Advanced +# Arm inertia, gives a more realistic movement of +# the arm when the camera moves. +# type: bool +# arm_inertia = true + # If FPS would go higher than this, limit it by sleeping # to not waste CPU power for no benefit. # type: int diff --git a/src/camera.cpp b/src/camera.cpp index d5e32bf5..f75d6018 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -75,6 +75,7 @@ Camera::Camera(scene::ISceneManager* smgr, MapDrawControl& draw_control, m_cache_view_bobbing_amount = g_settings->getFloat("view_bobbing_amount"); m_cache_fov = g_settings->getFloat("fov"); m_cache_zoom_fov = g_settings->getFloat("zoom_fov"); + m_arm_inertia = g_settings->getBool("arm_inertia"); m_nametags.clear(); } @@ -193,6 +194,82 @@ void Camera::step(f32 dtime) } } +void Camera::add_arm_inertia(f32 player_yaw, f32 frametime) +{ + m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw) / m_timer.X) * 0.01f; + m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / m_timer.Y); + + if (m_cam_vel.X > 1.0f || m_cam_vel.Y > 1.0f) { + /* + the arm moves when the camera moves fast enough. + */ + + if (m_cam_vel.X > 1.0f) { + m_timer.X = 0.0f; + m_timer.X += frametime; + + if (m_cam_vel.X > m_cam_vel_old.X) + m_cam_vel_old.X = m_cam_vel.X; + + if (m_last_cam_pos.X > player_yaw) + // right + m_wieldmesh_offset.X -= (0.1f + frametime) * m_cam_vel.X; + else + // left + m_wieldmesh_offset.X += (0.1f + frametime) * m_cam_vel.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, 48.0f, 62.0f); + } + + if (m_cam_vel.Y > 1.0f) { + m_timer.Y = 0.0f; + m_timer.Y += frametime; + + if (m_cam_vel.Y > m_cam_vel_old.Y) + m_cam_vel_old.Y = m_cam_vel.Y; + + if (m_last_cam_pos.Y > m_camera_direction.Y) + // down + m_wieldmesh_offset.Y += (0.1f + frametime) * m_cam_vel.Y; + else + // up + m_wieldmesh_offset.Y -= (0.1f + frametime) * m_cam_vel.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, -45.0f, -30.0f); + } + } else { + /* + the arm now gets back to its default position when the camera stops. + */ + + if (floor(m_wieldmesh_offset.X) == 55.0f) { + m_cam_vel_old.X = 0.0f; + m_wieldmesh_offset.X = 55.0f; + } + + if (m_wieldmesh_offset.X > 55.0f) + m_wieldmesh_offset.X -= (0.05f + frametime) * m_cam_vel_old.X; + if (m_wieldmesh_offset.X < 55.0f) + m_wieldmesh_offset.X += (0.05f + frametime) * m_cam_vel_old.X; + + if (floor(m_wieldmesh_offset.Y) == -35.0f) { + m_cam_vel_old.Y = 0.0f; + m_wieldmesh_offset.Y = -35.0f; + } + + if (m_wieldmesh_offset.Y > -35.0f) + m_wieldmesh_offset.Y -= (0.05f + frametime) * m_cam_vel_old.Y; + if (m_wieldmesh_offset.Y < -35.0f) + m_wieldmesh_offset.Y += (0.05f + frametime) * m_cam_vel_old.Y; + } +} + void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio, ClientEnvironment &c_env) { @@ -380,12 +457,12 @@ void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, m_cameranode->setAspectRatio(m_aspect); m_cameranode->setFOV(m_fov_y); - float wieldmesh_offset_Y = -35 + player->getPitch() * 0.05; - wieldmesh_offset_Y = rangelim(wieldmesh_offset_Y, -52, -32); + if (m_arm_inertia) + add_arm_inertia(player->getYaw(), frametime); // Position the wielded item //v3f wield_position = v3f(45, -35, 65); - v3f wield_position = v3f(55, wieldmesh_offset_Y, 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); wield_position.Y += fabs(m_wield_change_timer)*320 - 40; diff --git a/src/camera.h b/src/camera.h index 8d213ede..9ed4b727 100644 --- a/src/camera.h +++ b/src/camera.h @@ -166,6 +166,8 @@ public: void drawNametags(); + inline void add_arm_inertia(f32 player_yaw, f32 frametime); + private: // Nodes scene::ISceneNode *m_playernode = nullptr; @@ -188,6 +190,12 @@ private: // Camera offset v3s16 m_camera_offset; + v2f m_wieldmesh_offset = v2f(55.0f, -35.0f); + v2f m_timer; + v2f m_cam_vel; + v2f m_cam_vel_old; + v2f m_last_cam_pos; + // Field of view and aspect ratio stuff f32 m_aspect = 1.0f; f32 m_fov_x = 1.0f; @@ -221,6 +229,7 @@ private: f32 m_cache_view_bobbing_amount; f32 m_cache_fov; f32 m_cache_zoom_fov; + bool m_arm_inertia; std::list m_nametags; }; diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index c10d2cb0..42e369f6 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -171,6 +171,7 @@ void set_default_settings(Settings *settings) settings->setDefault("ambient_occlusion_gamma", "2.2"); settings->setDefault("enable_shaders", "true"); settings->setDefault("enable_particles", "true"); + settings->setDefault("arm_inertia", "true"); settings->setDefault("enable_minimap", "true"); settings->setDefault("minimap_shape_round", "true"); From a8650e785df3f12efa5f8cd3c6a695fb9e22a598 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Mon, 26 Jun 2017 20:10:11 +0200 Subject: [PATCH 41/53] Fix Camera::add_arm_inertia -> addArmInertia --- src/camera.cpp | 4 ++-- src/camera.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/camera.cpp b/src/camera.cpp index f75d6018..dd4e3963 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -194,7 +194,7 @@ void Camera::step(f32 dtime) } } -void Camera::add_arm_inertia(f32 player_yaw, f32 frametime) +void Camera::addArmInertia(f32 player_yaw, f32 frametime) { m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw) / m_timer.X) * 0.01f; m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / m_timer.Y); @@ -458,7 +458,7 @@ void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, m_cameranode->setFOV(m_fov_y); if (m_arm_inertia) - add_arm_inertia(player->getYaw(), frametime); + addArmInertia(player->getYaw(), frametime); // Position the wielded item //v3f wield_position = v3f(45, -35, 65); diff --git a/src/camera.h b/src/camera.h index 9ed4b727..4b2d9d45 100644 --- a/src/camera.h +++ b/src/camera.h @@ -166,7 +166,7 @@ public: void drawNametags(); - inline void add_arm_inertia(f32 player_yaw, f32 frametime); + inline void addArmInertia(f32 player_yaw, f32 frametime); private: // Nodes From b3a36f7378ea0f299cfa36c81de42e00adb7292d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Blot?= Date: Mon, 26 Jun 2017 20:11:17 +0200 Subject: [PATCH 42/53] Isolate irrlicht references and use a singleton (#6041) * Add Device3D class which will contain IrrlichtDevice interface move getSupportedVideoDrivers to Device3D Add Device3D singleton & use it in various places Rename Device3D to Rendering engine & add helper functions to various device pointers More singleton work RenderingEngine owns draw_load_screen move draw functions to RenderingEngine Reduce IrrlichtDevice exposure and guienvironment RenderingEngine: Expose get_timer_time() to remove device from guiEngine Make irrlichtdevice & scene manager less exposed * Code style fixes * Move porting::getVideoDriverName, getVideoDriverFriendlyName, getDisplayDensity, getDisplaySize to RenderingEngine Fix XORG_USED macro -> RenderingEngine + create_engine_device from RenderingEngine constructor directly * enum paralax => enum parallax --- build/android/jni/Android.mk | 2 +- src/CMakeLists.txt | 1 - src/camera.cpp | 6 +- src/client.cpp | 53 +- src/client.h | 5 +- src/client/CMakeLists.txt | 1 + src/client/clientlauncher.cpp | 194 +---- src/client/clientlauncher.h | 5 +- src/client/inputhandler.h | 17 +- src/client/renderingengine.cpp | 1072 ++++++++++++++++++++++++ src/client/renderingengine.h | 185 ++++ src/client/tile.cpp | 65 +- src/client/tile.h | 6 +- src/clientenvironment.cpp | 6 +- src/clientenvironment.h | 4 +- src/clientmap.cpp | 6 +- src/clientmap.h | 2 - src/clouds.cpp | 21 +- src/clouds.h | 4 +- src/content_mapblock.cpp | 4 +- src/content_mapblock.h | 1 - src/drawscene.cpp | 674 --------------- src/drawscene.h | 39 - src/fontengine.cpp | 12 +- src/game.cpp | 100 ++- src/game.h | 3 +- src/guiEngine.cpp | 58 +- src/guiEngine.h | 6 +- src/guiFormSpecMenu.cpp | 20 +- src/guiFormSpecMenu.h | 5 +- src/guiTable.cpp | 4 +- src/guiscalingfilter.cpp | 9 +- src/guiscalingfilter.h | 2 +- src/hud.cpp | 22 +- src/mainmenumanager.h | 11 +- src/mapblock_mesh.cpp | 16 +- src/mapblock_mesh.h | 3 - src/minimap.cpp | 7 +- src/minimap.h | 2 +- src/nodedef.cpp | 7 +- src/particles.cpp | 34 +- src/particles.h | 20 +- src/porting.cpp | 306 ------- src/porting.h | 29 +- src/script/lua_api/l_mainmenu.cpp | 32 +- src/shader.cpp | 38 +- src/shader.h | 4 +- src/sky.cpp | 7 +- src/sky.h | 3 +- util/travis/clang-format-whitelist.txt | 2 - 50 files changed, 1568 insertions(+), 1567 deletions(-) create mode 100644 src/client/renderingengine.cpp create mode 100644 src/client/renderingengine.h delete mode 100644 src/drawscene.cpp delete mode 100644 src/drawscene.h diff --git a/build/android/jni/Android.mk b/build/android/jni/Android.mk index 22ef2090..6155b0d9 100644 --- a/build/android/jni/Android.mk +++ b/build/android/jni/Android.mk @@ -138,7 +138,6 @@ LOCAL_SRC_FILES := \ jni/src/database.cpp \ jni/src/debug.cpp \ jni/src/defaultsettings.cpp \ - jni/src/drawscene.cpp \ jni/src/dungeongen.cpp \ jni/src/emerge.cpp \ jni/src/environment.cpp \ @@ -270,6 +269,7 @@ LOCAL_SRC_FILES := \ jni/src/wieldmesh.cpp \ jni/src/client/clientlauncher.cpp \ jni/src/client/inputhandler.cpp \ + jni/src/client/renderingengine.cpp \ jni/src/client/tile.cpp \ jni/src/client/joystick_controller.cpp \ jni/src/irrlicht_changes/static_text.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9e53b0e2..04f4635d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -500,7 +500,6 @@ set(client_SRCS content_cso.cpp content_mapblock.cpp convert_json.cpp - drawscene.cpp filecache.cpp fontengine.cpp game.cpp diff --git a/src/camera.cpp b/src/camera.cpp index dd4e3963..83239fe7 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "clientmap.h" // MapDrawControl #include "player.h" #include +#include "client/renderingengine.h" #include "settings.h" #include "wieldmesh.h" #include "noise.h" // easeCurve @@ -99,7 +100,7 @@ bool Camera::successfullyCreated(std::string &error_message) } else { error_message.clear(); } - + if (g_settings->getBool("enable_client_modding")) { m_client->getScript()->on_camera_ready(this); } @@ -449,7 +450,8 @@ void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, fov_degrees = rangelim(fov_degrees, 7.0, 160.0); // FOV and aspect ratio - m_aspect = (f32) porting::getWindowSize().X / (f32) porting::getWindowSize().Y; + const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); + m_aspect = (f32) window_size.X / (f32) window_size.Y; m_fov_y = fov_degrees * M_PI / 180.0; // Increase vertical FOV on lower aspect ratios (<16:10) m_fov_y *= MYMAX(1.0, MYMIN(1.4, sqrt(16./10. / m_aspect))); diff --git a/src/client.cpp b/src/client.cpp index ebe1d9c8..5681c3dd 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include "threading/mutex_auto_lock.h" +#include "client/renderingengine.h" #include "util/auth.h" #include "util/directiontables.h" #include "util/pointedthing.h" @@ -41,7 +42,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "clientmap.h" #include "clientmedia.h" #include "version.h" -#include "drawscene.h" #include "database-sqlite3.h" #include "serialization.h" #include "guiscalingfilter.h" @@ -55,7 +55,6 @@ extern gui::IGUIEnvironment* guienv; */ Client::Client( - IrrlichtDevice *device, const char *playername, const std::string &password, const std::string &address_name, @@ -77,16 +76,12 @@ Client::Client( m_event(event), m_mesh_update_thread(this), m_env( - new ClientMap(this, control, - device->getSceneManager()->getRootSceneNode(), - device->getSceneManager(), 666), - device->getSceneManager(), + new ClientMap(this, control, 666), tsrc, this ), m_particle_manager(&m_env), m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this), m_address_name(address_name), - m_device(device), m_server_ser_ver(SER_FMT_VER_INVALID), m_last_chat_message_sent(time(NULL)), m_password(password), @@ -99,7 +94,7 @@ Client::Client( m_env.setLocalPlayer(new LocalPlayer(this, playername)); if (g_settings->getBool("enable_minimap")) { - m_minimap = new Minimap(device, this); + m_minimap = new Minimap(this); } m_cache_save_interval = g_settings->getU16("server_map_save_interval"); @@ -217,12 +212,11 @@ Client::~Client() } // cleanup 3d model meshes on client shutdown - while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) { - scene::IAnimatedMesh *mesh = - m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0); + while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) { + scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0); if (mesh) - m_device->getSceneManager()->getMeshCache()->removeMesh(mesh); + RenderingEngine::get_mesh_cache()->removeMesh(mesh); } delete m_minimap; @@ -614,8 +608,8 @@ bool Client::loadMedia(const std::string &data, const std::string &filename) verbosestream<<"Client: Attempting to load image " <<"file \""<getFileSystem(); - video::IVideoDriver *vdrv = m_device->getVideoDriver(); + io::IFileSystem *irrfs = RenderingEngine::get_filesystem(); + video::IVideoDriver *vdrv = RenderingEngine::get_video_driver(); // Create an irrlicht memory file io::IReadFile *rfile = irrfs->createMemoryReadFile( @@ -1628,7 +1622,6 @@ float Client::mediaReceiveProgress() } typedef struct TextureUpdateArgs { - IrrlichtDevice *device; gui::IGUIEnvironment *guienv; u64 last_time_ms; u16 last_percent; @@ -1655,12 +1648,12 @@ void texture_update_progress(void *args, u32 progress, u32 max_progress) targs->last_time_ms = time_ms; std::basic_stringstream strm; strm << targs->text_base << " " << targs->last_percent << "%..."; - draw_load_screen(strm.str(), targs->device, targs->guienv, targs->tsrc, 0, + RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0, 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true); } } -void Client::afterContentReceived(IrrlichtDevice *device) +void Client::afterContentReceived() { infostream<<"Client::afterContentReceived() started"<getVideoDriver()); + guiScalingCacheClear(); // Rebuild inherited images and recreate textures infostream<<"- Rebuilding images and textures"<rebuildImagesAndTextures(); delete[] text; // Rebuild shaders infostream<<"- Rebuilding shaders"<rebuildShaders(); delete[] text; // Update node aliases infostream<<"- Updating node aliases"<updateAliases(m_itemdef); std::string texture_path = g_settings->get("texture_path"); if (texture_path != "" && fs::IsDir(texture_path)) @@ -1702,7 +1695,6 @@ void Client::afterContentReceived(IrrlichtDevice *device) // Update node textures and assign shaders to each tile infostream<<"- Updating node textures"<getVideoDriver(); + irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver(); irr::video::IImage* const raw_image = driver->createScreenShot(); if (!raw_image) @@ -1857,10 +1849,7 @@ IShaderSource* Client::getShaderSource() { return m_shsrc; } -scene::ISceneManager* Client::getSceneManager() -{ - return m_device->getSceneManager(); -} + u16 Client::allocateUnknownNodeId(const std::string &name) { errorstream << "Client::allocateUnknownNodeId(): " @@ -1892,22 +1881,20 @@ scene::IAnimatedMesh* Client::getMesh(const std::string &filename) return NULL; } const std::string &data = it->second; - scene::ISceneManager *smgr = m_device->getSceneManager(); // 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::IFileSystem *irrfs = m_device->getFileSystem(); - io::IReadFile *rfile = irrfs->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"); - scene::IAnimatedMesh *mesh = smgr->getMesh(rfile); + scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile); rfile->drop(); // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch // of uniquely named instances and re-use them mesh->grab(); - smgr->getMeshCache()->removeMesh(mesh); + RenderingEngine::get_mesh_cache()->removeMesh(mesh); return mesh; } diff --git a/src/client.h b/src/client.h index ab47cfa4..ab9801d6 100644 --- a/src/client.h +++ b/src/client.h @@ -256,7 +256,6 @@ public: */ Client( - IrrlichtDevice *device, const char *playername, const std::string &password, const std::string &address_name, @@ -467,7 +466,7 @@ public: float mediaReceiveProgress(); - void afterContentReceived(IrrlichtDevice *device); + void afterContentReceived(); float getRTT(); float getCurRate(); @@ -486,7 +485,6 @@ public: ITextureSource* getTextureSource(); virtual IShaderSource* getShaderSource(); IShaderSource *shsrc() { return getShaderSource(); } - scene::ISceneManager* getSceneManager(); virtual u16 allocateUnknownNodeId(const std::string &name); virtual ISoundManager* getSoundManager(); virtual MtEventManager* getEventManager(); @@ -593,7 +591,6 @@ private: ParticleManager m_particle_manager; con::Connection m_con; std::string m_address_name; - IrrlichtDevice *m_device; Camera *m_camera = nullptr; Minimap *m_minimap = nullptr; bool m_minimap_disabled_by_server = false; diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index 2d274ae6..4ba8fea5 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -1,4 +1,5 @@ set(client_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/renderingengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/clientlauncher.cpp ${CMAKE_CURRENT_SOURCE_DIR}/inputhandler.cpp ${CMAKE_CURRENT_SOURCE_DIR}/tile.cpp diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index 9856c192..4fc8fb3e 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -18,7 +18,6 @@ with this program; if not, write to the Free Software Foundation, Inc., */ #include "mainmenumanager.h" -#include "debug.h" #include "clouds.h" #include "server.h" #include "filesys.h" @@ -27,14 +26,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "chat.h" #include "gettext.h" #include "profiler.h" -#include "log.h" #include "serverlist.h" #include "guiEngine.h" -#include "player.h" #include "fontengine.h" -#include "joystick_controller.h" #include "clientlauncher.h" #include "version.h" +#include "renderingengine.h" /* mainmenumanager.h */ @@ -58,9 +55,9 @@ ClientLauncher::~ClientLauncher() delete input; delete g_fontengine; + delete g_gamecallback; - if (device) - device->drop(); + delete RenderingEngine::get_instance(); } @@ -70,7 +67,7 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) // List video modes if requested if (list_video_modes) - return print_video_modes(); + return RenderingEngine::print_video_modes(); if (!init_engine()) { errorstream << "Could not initialize game engine." << std::endl; @@ -84,15 +81,14 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) return true; } - video::IVideoDriver *video_driver = device->getVideoDriver(); + video::IVideoDriver *video_driver = RenderingEngine::get_video_driver(); if (video_driver == NULL) { errorstream << "Could not initialize video driver." << std::endl; return false; } - porting::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C); - - porting::setWindowIcon(device); + RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C); + RenderingEngine::get_instance()->setWindowIcon(); /* This changes the minimum allowed number of vertices in a VBO. @@ -101,17 +97,17 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) //driver->setMinHardwareBufferVertexCount(50); // Create game callback for menus - g_gamecallback = new MainGameCallback(device); + g_gamecallback = new MainGameCallback(); - device->setResizable(true); + RenderingEngine::get_instance()->setResizable(true); init_input(); - smgr = device->getSceneManager(); - smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); + RenderingEngine::get_scene_manager()->getParameters()-> + setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); - guienv = device->getGUIEnvironment(); - skin = guienv->getSkin(); + guienv = RenderingEngine::get_gui_env(); + skin = RenderingEngine::get_gui_env()->getSkin(); skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255)); skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0)); skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30)); @@ -130,10 +126,9 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) // Create the menu clouds if (!g_menucloudsmgr) - g_menucloudsmgr = smgr->createNewSceneManager(); + g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager(); if (!g_menuclouds) - g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(), - g_menucloudsmgr, -1, rand(), 100); + g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand(), 100); g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255)); scene::ICameraSceneNode* camera; camera = g_menucloudsmgr->addCameraSceneNode(0, @@ -159,25 +154,27 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) bool retval = true; bool *kill = porting::signal_handler_killstatus(); - while (device->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"); - device->setWindowCaption((utf8_to_wide(PROJECT_NAME_C) + + 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 - guienv->clear(); + RenderingEngine::get_gui_env()->clear(); /* We need some kind of a root node to be able to add custom gui elements directly on the screen. Otherwise they won't be automatically drawn. */ - guiroot = guienv->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, game_params, cmd_args); @@ -199,7 +196,7 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) } // Break out of menu-game loop to shut down cleanly - if (!device->run() || *kill) { + if (!RenderingEngine::get_raw_device()->run() || *kill) { if (g_settings_path != "") g_settings->updateConfigFile(g_settings_path.c_str()); break; @@ -212,7 +209,7 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) continue; } - device->getVideoDriver()->setTextureCreationFlag( + RenderingEngine::get_video_driver()->setTextureCreationFlag( video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map")); #ifdef HAVE_TOUCHSCREENGUI @@ -224,7 +221,6 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) kill, random_input, input, - device, worldspec.path, current_playername, current_password, @@ -236,7 +232,7 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) gamespec, simple_singleplayer_mode ); - smgr->clear(); + RenderingEngine::get_scene_manager()->clear(); #ifdef HAVE_TOUCHSCREENGUI delete g_touchscreengui; @@ -308,8 +304,8 @@ void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args bool ClientLauncher::init_engine() { receiver = new MyEventReceiver(); - create_engine_device(); - return device != NULL; + new RenderingEngine(receiver); + return RenderingEngine::get_raw_device() != nullptr; } void ClientLauncher::init_input() @@ -317,7 +313,7 @@ void ClientLauncher::init_input() if (random_input) input = new RandomInputHandler(); else - input = new RealInputHandler(device, receiver); + input = new RealInputHandler(receiver); if (g_settings->getBool("enable_joysticks")) { irr::core::array infos; @@ -326,7 +322,7 @@ void ClientLauncher::init_input() // Make sure this is called maximum once per // irrlicht device, otherwise it will give you // multiple events for the same joystick. - if (device->activateJoysticks(infos)) { + if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) { infostream << "Joystick support enabled" << std::endl; joystick_infos.reserve(infos.size()); for (u32 i = 0; i < infos.size(); i++) { @@ -487,14 +483,14 @@ bool ClientLauncher::launch_game(std::string &error_message, void ClientLauncher::main_menu(MainMenuData *menudata) { bool *kill = porting::signal_handler_killstatus(); - video::IVideoDriver *driver = device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); infostream << "Waiting for other menus" << std::endl; - while (device->run() && *kill == false) { + while (RenderingEngine::get_raw_device()->run() && *kill == false) { if (!isMenuActive()) break; driver->beginScene(true, true, video::SColor(255, 128, 128, 128)); - guienv->drawAll(); + RenderingEngine::get_gui_env()->drawAll(); driver->endScene(); // On some computers framerate doesn't seem to be automatically limited sleep_ms(25); @@ -503,73 +499,14 @@ void ClientLauncher::main_menu(MainMenuData *menudata) // Cursor can be non-visible when coming from the game #ifndef ANDROID - device->getCursorControl()->setVisible(true); + RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true); #endif /* show main menu */ - GUIEngine mymenu(device, &input->joystick, guiroot, - &g_menumgr, smgr, menudata, *kill); + GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill); - smgr->clear(); /* leave scene manager in a clean state */ -} - -bool ClientLauncher::create_engine_device() -{ - // Resolution selection - bool fullscreen = g_settings->getBool("fullscreen"); - u16 screen_w = g_settings->getU16("screen_w"); - u16 screen_h = g_settings->getU16("screen_h"); - - // bpp, fsaa, vsync - bool vsync = g_settings->getBool("vsync"); - u16 bits = g_settings->getU16("fullscreen_bpp"); - u16 fsaa = g_settings->getU16("fsaa"); - - // stereo buffer required for pageflip stereo - bool stereo_buffer = g_settings->get("3d_mode") == "pageflip"; - - // Determine driver - video::E_DRIVER_TYPE driverType = video::EDT_OPENGL; - const std::string &driverstring = g_settings->get("video_driver"); - std::vector drivers - = porting::getSupportedVideoDrivers(); - u32 i; - for (i = 0; i != drivers.size(); i++) { - if (!strcasecmp(driverstring.c_str(), - porting::getVideoDriverName(drivers[i]))) { - driverType = drivers[i]; - break; - } - } - if (i == drivers.size()) { - errorstream << "Invalid video_driver specified; " - "defaulting to opengl" << std::endl; - } - - SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); - params.DriverType = driverType; - params.WindowSize = core::dimension2d(screen_w, screen_h); - params.Bits = bits; - params.AntiAlias = fsaa; - params.Fullscreen = fullscreen; - params.Stencilbuffer = false; - params.Stereobuffer = stereo_buffer; - params.Vsync = vsync; - params.EventReceiver = receiver; - params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); - params.ZBufferBits = 24; -#ifdef __ANDROID__ - params.PrivateData = porting::app_global; - params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM + - "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str(); -#endif - - device = createDeviceEx(params); - - if (device) - porting::initIrrlicht(device); - - return device != NULL; + /* leave scene manager in a clean state */ + RenderingEngine::get_scene_manager()->clear(); } void ClientLauncher::speed_tests() @@ -584,8 +521,8 @@ void ClientLauncher::speed_tests() tempv3f1 = v3f(); tempv3f2 = v3f(); - tempstring = std::string(); - tempstring2 = std::string(); + tempstring.clear(); + tempstring2.clear(); { infostream << "The following test should take around 20ms." << std::endl; @@ -670,58 +607,3 @@ void ClientLauncher::speed_tests() infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl; } } - -bool ClientLauncher::print_video_modes() -{ - IrrlichtDevice *nulldevice; - - bool vsync = g_settings->getBool("vsync"); - u16 fsaa = g_settings->getU16("fsaa"); - MyEventReceiver* receiver = new MyEventReceiver(); - - SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); - params.DriverType = video::EDT_NULL; - params.WindowSize = core::dimension2d(640, 480); - params.Bits = 24; - params.AntiAlias = fsaa; - params.Fullscreen = false; - params.Stencilbuffer = false; - params.Vsync = vsync; - params.EventReceiver = receiver; - params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); - - nulldevice = createDeviceEx(params); - - if (nulldevice == NULL) { - delete receiver; - return false; - } - - std::cout << _("Available video modes (WxHxD):") << std::endl; - - video::IVideoModeList *videomode_list = nulldevice->getVideoModeList(); - - if (videomode_list != NULL) { - s32 videomode_count = videomode_list->getVideoModeCount(); - core::dimension2d videomode_res; - s32 videomode_depth; - for (s32 i = 0; i < videomode_count; ++i) { - videomode_res = videomode_list->getVideoModeResolution(i); - videomode_depth = videomode_list->getVideoModeDepth(i); - std::cout << videomode_res.Width << "x" << videomode_res.Height - << "x" << videomode_depth << std::endl; - } - - std::cout << _("Active video mode (WxHxD):") << std::endl; - videomode_res = videomode_list->getDesktopResolution(); - videomode_depth = videomode_list->getDesktopDepth(); - std::cout << videomode_res.Width << "x" << videomode_res.Height - << "x" << videomode_depth << std::endl; - - } - - nulldevice->drop(); - delete receiver; - - return videomode_list != NULL; -} diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h index 9e0560b1..8f8a01e2 100644 --- a/src/client/clientlauncher.h +++ b/src/client/clientlauncher.h @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/inputhandler.h" #include "gameparams.h" +class RenderingEngine; class ClientLauncher { @@ -43,10 +44,8 @@ protected: GameParams &game_params, const Settings &cmd_args); void main_menu(MainMenuData *menudata); - bool create_engine_device(); void speed_tests(); - bool print_video_modes(); bool list_video_modes = false; bool skip_main_menu = false; @@ -55,12 +54,10 @@ protected: std::string address = ""; std::string playername = ""; std::string password = ""; - IrrlichtDevice *device = nullptr; InputHandler *input = nullptr; MyEventReceiver *receiver = nullptr; gui::IGUISkin *skin = nullptr; gui::IGUIFont *font = nullptr; - scene::ISceneManager *smgr = nullptr; SubgameSpec gamespec; WorldSpec worldspec; bool simple_singleplayer_mode; diff --git a/src/client/inputhandler.h b/src/client/inputhandler.h index 19733e3e..822e2786 100644 --- a/src/client/inputhandler.h +++ b/src/client/inputhandler.h @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "joystick_controller.h" #include #include "keycode.h" +#include "renderingengine.h" #ifdef HAVE_TOUCHSCREENGUI #include "touchscreengui.h" @@ -219,8 +220,7 @@ public: class RealInputHandler : public InputHandler { public: - RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver) - : m_device(device), m_receiver(receiver) + RealInputHandler(MyEventReceiver *receiver) : m_receiver(receiver) { m_receiver->joystick = &joystick; } @@ -239,16 +239,20 @@ public: virtual void dontListenForKeys() { m_receiver->dontListenForKeys(); } virtual v2s32 getMousePos() { - if (m_device->getCursorControl()) { - return m_device->getCursorControl()->getPosition(); + if (RenderingEngine::get_raw_device()->getCursorControl()) { + return RenderingEngine::get_raw_device() + ->getCursorControl() + ->getPosition(); } else { return m_mousepos; } } virtual void setMousePos(s32 x, s32 y) { - if (m_device->getCursorControl()) { - m_device->getCursorControl()->setPosition(x, y); + if (RenderingEngine::get_raw_device()->getCursorControl()) { + RenderingEngine::get_raw_device() + ->getCursorControl() + ->setPosition(x, y); } else { m_mousepos = v2s32(x, y); } @@ -276,7 +280,6 @@ public: } private: - IrrlichtDevice *m_device = nullptr; MyEventReceiver *m_receiver = nullptr; v2s32 m_mousepos; }; diff --git a/src/client/renderingengine.cpp b/src/client/renderingengine.cpp new file mode 100644 index 00000000..ce8f643b --- /dev/null +++ b/src/client/renderingengine.cpp @@ -0,0 +1,1072 @@ +/* +Minetest +Copyright (C) 2010-2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include +#include +#include "fontengine.h" +#include "clouds.h" +#include "util/numeric.h" +#include "guiscalingfilter.h" +#include "hud.h" +#include "camera.h" +#include "minimap.h" +#include "clientmap.h" +#include "renderingengine.h" +#include "inputhandler.h" +#include "gettext.h" + +#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && !defined(SERVER) +#define XORG_USED +#endif +#ifdef XORG_USED +#include +#include +#endif + +RenderingEngine *RenderingEngine::s_singleton = nullptr; + +RenderingEngine::RenderingEngine(IEventReceiver *receiver) +{ + sanity_check(!s_singleton); + + // Resolution selection + bool fullscreen = g_settings->getBool("fullscreen"); + u16 screen_w = g_settings->getU16("screen_w"); + u16 screen_h = g_settings->getU16("screen_h"); + + // bpp, fsaa, vsync + bool vsync = g_settings->getBool("vsync"); + u16 bits = g_settings->getU16("fullscreen_bpp"); + u16 fsaa = g_settings->getU16("fsaa"); + + // stereo buffer required for pageflip stereo + bool stereo_buffer = g_settings->get("3d_mode") == "pageflip"; + + // Determine driver + video::E_DRIVER_TYPE driverType = video::EDT_OPENGL; + const std::string &driverstring = g_settings->get("video_driver"); + std::vector drivers = + RenderingEngine::getSupportedVideoDrivers(); + u32 i; + for (i = 0; i != drivers.size(); i++) { + if (!strcasecmp(driverstring.c_str(), + RenderingEngine::getVideoDriverName(drivers[i]))) { + driverType = drivers[i]; + break; + } + } + if (i == drivers.size()) { + errorstream << "Invalid video_driver specified; " + "defaulting to opengl" + << std::endl; + } + + SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); + params.DriverType = driverType; + params.WindowSize = core::dimension2d(screen_w, screen_h); + params.Bits = bits; + params.AntiAlias = fsaa; + params.Fullscreen = fullscreen; + params.Stencilbuffer = false; + params.Stereobuffer = stereo_buffer; + params.Vsync = vsync; + params.EventReceiver = receiver; + params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); + params.ZBufferBits = 24; +#ifdef __ANDROID__ + params.PrivateData = porting::app_global; + params.OGLES2ShaderPath = std::string( + porting::path_user + DIR_DELIM + "media" + DIR_DELIM + "Shaders" + + DIR_DELIM).c_str(); +#endif + + m_device = createDeviceEx(params); + s_singleton = this; +} + +RenderingEngine::~RenderingEngine() +{ + m_device->drop(); + s_singleton = nullptr; +} + +v2u32 RenderingEngine::getWindowSize() const +{ + return m_device->getVideoDriver()->getScreenSize(); +} + +void RenderingEngine::setResizable(bool resize) +{ + m_device->setResizable(resize); +} + +video::IVideoDriver *RenderingEngine::getVideoDriver() +{ + return m_device->getVideoDriver(); +} + +bool RenderingEngine::print_video_modes() +{ + IrrlichtDevice *nulldevice; + + bool vsync = g_settings->getBool("vsync"); + u16 fsaa = g_settings->getU16("fsaa"); + MyEventReceiver *receiver = new MyEventReceiver(); + + SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); + params.DriverType = video::EDT_NULL; + params.WindowSize = core::dimension2d(640, 480); + params.Bits = 24; + params.AntiAlias = fsaa; + params.Fullscreen = false; + params.Stencilbuffer = false; + params.Vsync = vsync; + params.EventReceiver = receiver; + params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); + + nulldevice = createDeviceEx(params); + + if (!nulldevice) { + delete receiver; + return false; + } + + std::cout << _("Available video modes (WxHxD):") << std::endl; + + video::IVideoModeList *videomode_list = nulldevice->getVideoModeList(); + + if (videomode_list != NULL) { + s32 videomode_count = videomode_list->getVideoModeCount(); + core::dimension2d videomode_res; + s32 videomode_depth; + for (s32 i = 0; i < videomode_count; ++i) { + videomode_res = videomode_list->getVideoModeResolution(i); + videomode_depth = videomode_list->getVideoModeDepth(i); + std::cout << videomode_res.Width << "x" << videomode_res.Height + << "x" << videomode_depth << std::endl; + } + + std::cout << _("Active video mode (WxHxD):") << std::endl; + videomode_res = videomode_list->getDesktopResolution(); + videomode_depth = videomode_list->getDesktopDepth(); + std::cout << videomode_res.Width << "x" << videomode_res.Height << "x" + << videomode_depth << std::endl; + } + + nulldevice->drop(); + delete receiver; + + return videomode_list != NULL; +} + +void RenderingEngine::setXorgClassHint( + const video::SExposedVideoData &video_data, const std::string &name) +{ +#ifdef XORG_USED + if (video_data.OpenGLLinux.X11Display == NULL) + return; + + XClassHint *classhint = XAllocClassHint(); + classhint->res_name = (char *)name.c_str(); + classhint->res_class = (char *)name.c_str(); + + XSetClassHint((Display *)video_data.OpenGLLinux.X11Display, + video_data.OpenGLLinux.X11Window, classhint); + XFree(classhint); +#endif +} + +bool RenderingEngine::setWindowIcon() +{ +#if defined(XORG_USED) +#if RUN_IN_PLACE + return setXorgWindowIconFromPath( + porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png"); +#else + // We have semi-support for reading in-place data if we are + // compiled with RUN_IN_PLACE. Don't break with this and + // also try the path_share location. + return setXorgWindowIconFromPath( + ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") || + setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME + "-xorg-icon-128.png"); +#endif +#elif defined(_WIN32) + const video::SExposedVideoData exposedData = + m_device->getVideoDriver()->getExposedVideoData(); + HWND hWnd; // Window handle + + switch (m_device->getVideoDriver()->getDriverType()) { + case video::EDT_DIRECT3D8: + hWnd = reinterpret_cast(exposedData.D3D8.HWnd); + break; + case video::EDT_DIRECT3D9: + hWnd = reinterpret_cast(exposedData.D3D9.HWnd); + break; + case video::EDT_OPENGL: + hWnd = reinterpret_cast(exposedData.OpenGLWin32.HWnd); + break; + default: + return false; + } + + // Load the ICON from resource file + const HICON hicon = LoadIcon(GetModuleHandle(NULL), + MAKEINTRESOURCE(130) // The ID of the ICON defined in + // winresource.rc + ); + + if (hicon) { + SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast(hicon)); + SendMessage(hWnd, WM_SETICON, ICON_SMALL, + reinterpret_cast(hicon)); + return true; + } + return false; +#else + return false; +#endif +} + +bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file) +{ +#ifdef XORG_USED + + video::IVideoDriver *v_driver = m_device->getVideoDriver(); + + video::IImageLoader *image_loader = NULL; + u32 cnt = v_driver->getImageLoaderCount(); + for (u32 i = 0; i < cnt; i++) { + if (v_driver->getImageLoader(i)->isALoadableFileExtension( + icon_file.c_str())) { + image_loader = v_driver->getImageLoader(i); + break; + } + } + + if (!image_loader) { + warningstream << "Could not find image loader for file '" << icon_file + << "'" << std::endl; + return false; + } + + io::IReadFile *icon_f = + m_device->getFileSystem()->createAndOpenFile(icon_file.c_str()); + + if (!icon_f) { + warningstream << "Could not load icon file '" << icon_file << "'" + << std::endl; + return false; + } + + video::IImage *img = image_loader->loadImage(icon_f); + + if (!img) { + warningstream << "Could not load icon file '" << icon_file << "'" + << std::endl; + icon_f->drop(); + return false; + } + + u32 height = img->getDimension().Height; + u32 width = img->getDimension().Width; + + size_t icon_buffer_len = 2 + height * width; + long *icon_buffer = new long[icon_buffer_len]; + + icon_buffer[0] = width; + icon_buffer[1] = height; + + for (u32 x = 0; x < width; x++) { + for (u32 y = 0; y < height; y++) { + video::SColor col = img->getPixel(x, y); + long pixel_val = 0; + pixel_val |= (u8)col.getAlpha() << 24; + pixel_val |= (u8)col.getRed() << 16; + pixel_val |= (u8)col.getGreen() << 8; + pixel_val |= (u8)col.getBlue(); + icon_buffer[2 + x + y * width] = pixel_val; + } + } + + img->drop(); + icon_f->drop(); + + const video::SExposedVideoData &video_data = v_driver->getExposedVideoData(); + + Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display; + + if (x11_dpl == NULL) { + warningstream << "Could not find x11 display for setting its icon." + << std::endl; + delete[] icon_buffer; + return false; + } + + Window x11_win = (Window)video_data.OpenGLLinux.X11Window; + + Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False); + Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False); + XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace, + (const unsigned char *)icon_buffer, icon_buffer_len); + + delete[] icon_buffer; + +#endif + return true; +} + +/* + Draws a screen with a single text on it. + Text will be removed when the screen is drawn the next time. + Additionally, a progressbar can be drawn when percent is set between 0 and 100. +*/ +void RenderingEngine::_draw_load_screen(const std::wstring &text, + gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime, + int percent, bool clouds) +{ + v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); + + v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight()); + v2s32 center(screensize.X / 2, screensize.Y / 2); + core::rect textrect(center - textsize / 2, center + textsize / 2); + + gui::IGUIStaticText *guitext = + guienv->addStaticText(text.c_str(), textrect, false, false); + guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + + bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); + if (cloud_menu_background) { + g_menuclouds->step(dtime * 3); + g_menuclouds->render(); + get_video_driver()->beginScene( + true, true, video::SColor(255, 140, 186, 250)); + g_menucloudsmgr->drawAll(); + } else + get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0)); + + // draw progress bar + if ((percent >= 0) && (percent <= 100)) { + video::ITexture *progress_img = tsrc->getTexture("progress_bar.png"); + video::ITexture *progress_img_bg = + tsrc->getTexture("progress_bar_bg.png"); + + if (progress_img && progress_img_bg) { +#ifndef __ANDROID__ + const core::dimension2d &img_size = + progress_img_bg->getSize(); + u32 imgW = rangelim(img_size.Width, 200, 600); + u32 imgH = rangelim(img_size.Height, 24, 72); +#else + const core::dimension2d img_size(256, 48); + float imgRatio = (float)img_size.Height / img_size.Width; + u32 imgW = screensize.X / 2.2f; + u32 imgH = floor(imgW * imgRatio); +#endif + v2s32 img_pos((screensize.X - imgW) / 2, + (screensize.Y - imgH) / 2); + + draw2DImageFilterScaled(get_video_driver(), progress_img_bg, + core::rect(img_pos.X, img_pos.Y, + img_pos.X + imgW, + img_pos.Y + imgH), + core::rect(0, 0, img_size.Width, + img_size.Height), + 0, 0, true); + + draw2DImageFilterScaled(get_video_driver(), progress_img, + core::rect(img_pos.X, img_pos.Y, + img_pos.X + (percent * imgW) / 100, + img_pos.Y + imgH), + core::rect(0, 0, + (percent * img_size.Width) / 100, + img_size.Height), + 0, 0, true); + } + } + + guienv->drawAll(); + get_video_driver()->endScene(); + guitext->remove(); +} + +std::vector> RenderingEngine::getSupportedVideoModes() +{ + IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); + sanity_check(nulldevice); + + std::vector> mlist; + video::IVideoModeList *modelist = nulldevice->getVideoModeList(); + + s32 num_modes = modelist->getVideoModeCount(); + for (s32 i = 0; i != num_modes; i++) { + core::dimension2d mode_res = modelist->getVideoModeResolution(i); + u32 mode_depth = (u32)modelist->getVideoModeDepth(i); + mlist.push_back(core::vector3d( + mode_res.Width, mode_res.Height, mode_depth)); + } + + nulldevice->drop(); + return mlist; +} + +std::vector RenderingEngine::getSupportedVideoDrivers() +{ + std::vector drivers; + + for (int i = 0; i != irr::video::EDT_COUNT; i++) { + if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i)) + drivers.push_back((irr::video::E_DRIVER_TYPE)i); + } + + return drivers; +} + +void RenderingEngine::_draw_scene(Camera *camera, Client *client, LocalPlayer *player, + Hud *hud, Minimap *mapper, gui::IGUIEnvironment *guienv, + const v2u32 &screensize, const video::SColor &skycolor, bool show_hud, + bool show_minimap) +{ + bool draw_wield_tool = + (show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) && + camera->getCameraMode() < CAMERA_MODE_THIRD); + + 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"); + } catch (SettingNotFoundException) { + } +#endif + + const std::string &draw_mode = g_settings->get("3d_mode"); + + if (draw_mode == "anaglyph") { + draw_anaglyph_3d_mode( + camera, show_hud, hud, draw_wield_tool, client, guienv); + draw_crosshair = false; + } else if (draw_mode == "interlaced") { + draw_interlaced_3d_mode(camera, show_hud, hud, screensize, + draw_wield_tool, client, guienv, skycolor); + draw_crosshair = false; + } else if (draw_mode == "sidebyside") { + draw_sidebyside_3d_mode(camera, show_hud, hud, screensize, + draw_wield_tool, client, guienv, skycolor); + show_hud = false; + } else if (draw_mode == "topbottom") { + draw_top_bottom_3d_mode(camera, show_hud, hud, screensize, + draw_wield_tool, client, guienv, skycolor); + show_hud = false; + } else if (draw_mode == "pageflip") { + draw_pageflip_3d_mode(camera, show_hud, hud, screensize, draw_wield_tool, + client, guienv, skycolor); + draw_crosshair = false; + show_hud = false; + } else { + draw_plain(camera, show_hud, hud, screensize, draw_wield_tool, client, + guienv, skycolor); + } + + /* + Post effects + */ + client->getEnv().getClientMap().renderPostFx(camera->getCameraMode()); + + // TODO how to make those 3d too + if (show_hud) { + if (draw_crosshair) + hud->drawCrosshair(); + + hud->drawHotbar(client->getPlayerItem()); + hud->drawLuaElements(camera->getOffset()); + camera->drawNametags(); + + if (mapper && show_minimap) + mapper->drawMinimap(); + } + + guienv->drawAll(); +} + +void RenderingEngine::draw_anaglyph_3d_mode(Camera *camera, bool show_hud, Hud *hud, + bool draw_wield_tool, Client *client, gui::IGUIEnvironment *guienv) +{ + + /* preserve old setup*/ + irr::core::vector3df oldPosition = camera->getCameraNode()->getPosition(); + irr::core::vector3df oldTarget = camera->getCameraNode()->getTarget(); + + irr::core::matrix4 startMatrix = + camera->getCameraNode()->getAbsoluteTransformation(); + irr::core::vector3df focusPoint = + (camera->getCameraNode()->getTarget() - + camera->getCameraNode()->getAbsolutePosition()) + .setLength(1) + + camera->getCameraNode()->getAbsolutePosition(); + + // Left eye... + irr::core::vector3df leftEye; + irr::core::matrix4 leftMove; + leftMove.setTranslation(irr::core::vector3df( + -g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); + leftEye = (startMatrix * leftMove).getTranslation(); + + // clear the depth buffer, and color + getVideoDriver()->beginScene(true, true, irr::video::SColor(0, 200, 200, 255)); + getVideoDriver()->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED; + getVideoDriver()->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK; + getVideoDriver()->getOverrideMaterial().EnablePasses = + irr::scene::ESNRP_SKY_BOX + irr::scene::ESNRP_SOLID + + irr::scene::ESNRP_TRANSPARENT + + irr::scene::ESNRP_TRANSPARENT_EFFECT + irr::scene::ESNRP_SHADOW; + camera->getCameraNode()->setPosition(leftEye); + camera->getCameraNode()->setTarget(focusPoint); + get_scene_manager()->drawAll(); + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) + camera->drawWieldedTool(&leftMove); + } + + guienv->drawAll(); + + // Right eye... + irr::core::vector3df rightEye; + irr::core::matrix4 rightMove; + rightMove.setTranslation(irr::core::vector3df( + g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); + rightEye = (startMatrix * rightMove).getTranslation(); + + // clear the depth buffer + getVideoDriver()->clearZBuffer(); + getVideoDriver()->getOverrideMaterial().Material.ColorMask = + irr::video::ECP_GREEN + irr::video::ECP_BLUE; + getVideoDriver()->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK; + getVideoDriver()->getOverrideMaterial().EnablePasses = + irr::scene::ESNRP_SKY_BOX + irr::scene::ESNRP_SOLID + + irr::scene::ESNRP_TRANSPARENT + + irr::scene::ESNRP_TRANSPARENT_EFFECT + irr::scene::ESNRP_SHADOW; + camera->getCameraNode()->setPosition(rightEye); + camera->getCameraNode()->setTarget(focusPoint); + get_scene_manager()->drawAll(); + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) + camera->drawWieldedTool(&rightMove); + } + + guienv->drawAll(); + + getVideoDriver()->getOverrideMaterial().Material.ColorMask = irr::video::ECP_ALL; + getVideoDriver()->getOverrideMaterial().EnableFlags = 0; + getVideoDriver()->getOverrideMaterial().EnablePasses = 0; + camera->getCameraNode()->setPosition(oldPosition); + camera->getCameraNode()->setTarget(oldTarget); +} + +void RenderingEngine::init_texture( + const v2u32 &screensize, video::ITexture **texture, const char *name) +{ + if (*texture) { + getVideoDriver()->removeTexture(*texture); + } + *texture = getVideoDriver()->addRenderTargetTexture( + core::dimension2d(screensize.X, screensize.Y), name, + irr::video::ECF_A8R8G8B8); +} + +video::ITexture *RenderingEngine::draw_image(const v2u32 &screensize, parallax_sign psign, + const irr::core::matrix4 &startMatrix, + const irr::core::vector3df &focusPoint, bool show_hud, Camera *camera, + Hud *hud, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor) +{ + static video::ITexture *images[2] = {NULL, NULL}; + static v2u32 last_screensize = v2u32(0, 0); + + video::ITexture *image = NULL; + + if (screensize != last_screensize) { + init_texture(screensize, &images[1], "mt_drawimage_img1"); + init_texture(screensize, &images[0], "mt_drawimage_img2"); + last_screensize = screensize; + } + + if (psign == RIGHT) + image = images[1]; + else + image = images[0]; + + getVideoDriver()->setRenderTarget(image, true, true, + irr::video::SColor(255, skycolor.getRed(), skycolor.getGreen(), + skycolor.getBlue())); + + irr::core::vector3df eye_pos; + irr::core::matrix4 movement; + movement.setTranslation(irr::core::vector3df( + (int)psign * g_settings->getFloat("3d_paralax_strength"), 0.0f, + 0.0f)); + eye_pos = (startMatrix * movement).getTranslation(); + + // clear the depth buffer + getVideoDriver()->clearZBuffer(); + camera->getCameraNode()->setPosition(eye_pos); + camera->getCameraNode()->setTarget(focusPoint); + get_scene_manager()->drawAll(); + + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) + camera->drawWieldedTool(&movement); + } + + guienv->drawAll(); + + /* switch back to real renderer */ + getVideoDriver()->setRenderTarget(0, true, true, + irr::video::SColor(0, skycolor.getRed(), skycolor.getGreen(), + skycolor.getBlue())); + + return image; +} + +video::ITexture *RenderingEngine::draw_hud(const v2u32 &screensize, bool show_hud, + Hud *hud, Client *client, bool draw_crosshair, + const video::SColor &skycolor, gui::IGUIEnvironment *guienv, + Camera *camera) +{ + static video::ITexture *image = nullptr; + init_texture(screensize, &image, "mt_drawimage_hud"); + getVideoDriver()->setRenderTarget( + image, true, true, irr::video::SColor(255, 0, 0, 0)); + + if (show_hud) { + if (draw_crosshair) + hud->drawCrosshair(); + hud->drawHotbar(client->getPlayerItem()); + hud->drawLuaElements(camera->getOffset()); + camera->drawNametags(); + guienv->drawAll(); + } + + getVideoDriver()->setRenderTarget(0, true, true, + irr::video::SColor(0, skycolor.getRed(), skycolor.getGreen(), + skycolor.getBlue())); + + return image; +} + +void RenderingEngine::draw_interlaced_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor) +{ + /* save current info */ + irr::core::vector3df oldPosition = camera->getCameraNode()->getPosition(); + irr::core::vector3df oldTarget = camera->getCameraNode()->getTarget(); + irr::core::matrix4 startMatrix = + camera->getCameraNode()->getAbsoluteTransformation(); + irr::core::vector3df focusPoint = + (camera->getCameraNode()->getTarget() - + camera->getCameraNode()->getAbsolutePosition()) + .setLength(1) + + camera->getCameraNode()->getAbsolutePosition(); + + /* create left view */ + video::ITexture *left_image = draw_image(screensize, LEFT, startMatrix, + focusPoint, show_hud, camera, hud, draw_wield_tool, client, + guienv, skycolor); + + // Right eye... + irr::core::vector3df rightEye; + irr::core::matrix4 rightMove; + rightMove.setTranslation(irr::core::vector3df( + g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); + rightEye = (startMatrix * rightMove).getTranslation(); + + // clear the depth buffer + getVideoDriver()->clearZBuffer(); + camera->getCameraNode()->setPosition(rightEye); + camera->getCameraNode()->setTarget(focusPoint); + get_scene_manager()->drawAll(); + + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) + camera->drawWieldedTool(&rightMove); + } + guienv->drawAll(); + + for (unsigned int i = 0; i < screensize.Y; i += 2) { +#if (IRRLICHT_VERSION_MAJOR >= 1) && (IRRLICHT_VERSION_MINOR >= 8) + getVideoDriver()->draw2DImage(left_image, + irr::core::position2d(0, i), +#else + getVideoDriver()->draw2DImage(left_image, + irr::core::position2d(0, screensize.Y - i), +#endif + irr::core::rect(0, i, screensize.X, i + 1), 0, + irr::video::SColor(255, 255, 255, 255), false); + } + + /* cleanup */ + camera->getCameraNode()->setPosition(oldPosition); + camera->getCameraNode()->setTarget(oldTarget); +} + +void RenderingEngine::draw_sidebyside_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor) +{ + /* save current info */ + irr::core::vector3df oldPosition = camera->getCameraNode()->getPosition(); + irr::core::vector3df oldTarget = camera->getCameraNode()->getTarget(); + irr::core::matrix4 startMatrix = + camera->getCameraNode()->getAbsoluteTransformation(); + irr::core::vector3df focusPoint = + (camera->getCameraNode()->getTarget() - + camera->getCameraNode()->getAbsolutePosition()) + .setLength(1) + + camera->getCameraNode()->getAbsolutePosition(); + + /* create left view */ + video::ITexture *left_image = draw_image(screensize, LEFT, startMatrix, + focusPoint, show_hud, camera, hud, draw_wield_tool, client, + guienv, skycolor); + + /* create right view */ + video::ITexture *right_image = draw_image(screensize, RIGHT, startMatrix, + focusPoint, show_hud, camera, hud, draw_wield_tool, client, + guienv, skycolor); + + /* create hud overlay */ + video::ITexture *hudtexture = draw_hud(screensize, show_hud, hud, client, false, + skycolor, guienv, camera); + getVideoDriver()->makeColorKeyTexture( + hudtexture, irr::video::SColor(255, 0, 0, 0)); + // makeColorKeyTexture mirrors texture so we do it twice to get it right again + getVideoDriver()->makeColorKeyTexture( + hudtexture, irr::video::SColor(255, 0, 0, 0)); + + draw2DImageFilterScaled(getVideoDriver(), left_image, + irr::core::rect(0, 0, screensize.X / 2, screensize.Y), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + false); + + draw2DImageFilterScaled(getVideoDriver(), hudtexture, + irr::core::rect(0, 0, screensize.X / 2, screensize.Y), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + true); + + draw2DImageFilterScaled(getVideoDriver(), right_image, + irr::core::rect( + screensize.X / 2, 0, screensize.X, screensize.Y), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + false); + + draw2DImageFilterScaled(getVideoDriver(), hudtexture, + irr::core::rect( + screensize.X / 2, 0, screensize.X, screensize.Y), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + true); + + left_image = nullptr; + right_image = nullptr; + + /* cleanup */ + camera->getCameraNode()->setPosition(oldPosition); + camera->getCameraNode()->setTarget(oldTarget); +} + +void RenderingEngine::draw_top_bottom_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor) +{ + /* save current info */ + irr::core::vector3df oldPosition = camera->getCameraNode()->getPosition(); + irr::core::vector3df oldTarget = camera->getCameraNode()->getTarget(); + irr::core::matrix4 startMatrix = + camera->getCameraNode()->getAbsoluteTransformation(); + irr::core::vector3df focusPoint = + (camera->getCameraNode()->getTarget() - + camera->getCameraNode()->getAbsolutePosition()) + .setLength(1) + + camera->getCameraNode()->getAbsolutePosition(); + + /* create left view */ + video::ITexture *left_image = draw_image(screensize, LEFT, startMatrix, + focusPoint, show_hud, camera, hud, draw_wield_tool, client, + guienv, skycolor); + + /* create right view */ + video::ITexture *right_image = draw_image(screensize, RIGHT, startMatrix, + focusPoint, show_hud, camera, hud, draw_wield_tool, client, + guienv, skycolor); + + /* create hud overlay */ + video::ITexture *hudtexture = draw_hud(screensize, show_hud, hud, client, false, + skycolor, guienv, camera); + getVideoDriver()->makeColorKeyTexture( + hudtexture, irr::video::SColor(255, 0, 0, 0)); + // makeColorKeyTexture mirrors texture so we do it twice to get it right again + getVideoDriver()->makeColorKeyTexture( + hudtexture, irr::video::SColor(255, 0, 0, 0)); + + draw2DImageFilterScaled(getVideoDriver(), left_image, + irr::core::rect(0, 0, screensize.X, screensize.Y / 2), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + false); + + draw2DImageFilterScaled(getVideoDriver(), hudtexture, + irr::core::rect(0, 0, screensize.X, screensize.Y / 2), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + true); + + draw2DImageFilterScaled(getVideoDriver(), right_image, + irr::core::rect( + 0, screensize.Y / 2, screensize.X, screensize.Y), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + false); + + draw2DImageFilterScaled(getVideoDriver(), hudtexture, + irr::core::rect( + 0, screensize.Y / 2, screensize.X, screensize.Y), + irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, + true); + + left_image = NULL; + right_image = NULL; + + /* cleanup */ + camera->getCameraNode()->setPosition(oldPosition); + camera->getCameraNode()->setTarget(oldTarget); +} + +void RenderingEngine::draw_pageflip_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor) +{ +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 + errorstream << "Pageflip 3D mode is not supported" + << " with your Irrlicht version!" << std::endl; +#else + /* preserve old setup*/ + irr::core::vector3df oldPosition = camera->getCameraNode()->getPosition(); + irr::core::vector3df oldTarget = camera->getCameraNode()->getTarget(); + + irr::core::matrix4 startMatrix = + camera->getCameraNode()->getAbsoluteTransformation(); + irr::core::vector3df focusPoint = + (camera->getCameraNode()->getTarget() - + camera->getCameraNode()->getAbsolutePosition()) + .setLength(1) + + camera->getCameraNode()->getAbsolutePosition(); + + // Left eye... + getVideoDriver()->setRenderTarget(irr::video::ERT_STEREO_LEFT_BUFFER); + + irr::core::vector3df leftEye; + irr::core::matrix4 leftMove; + leftMove.setTranslation(irr::core::vector3df( + -g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); + leftEye = (startMatrix * leftMove).getTranslation(); + + // clear the depth buffer, and color + getVideoDriver()->beginScene(true, true, irr::video::SColor(200, 200, 200, 255)); + camera->getCameraNode()->setPosition(leftEye); + camera->getCameraNode()->setTarget(focusPoint); + get_scene_manager()->drawAll(); + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) + camera->drawWieldedTool(&leftMove); + hud->drawHotbar(client->getPlayerItem()); + hud->drawLuaElements(camera->getOffset()); + camera->drawNametags(); + } + + guienv->drawAll(); + + // Right eye... + getVideoDriver()->setRenderTarget(irr::video::ERT_STEREO_RIGHT_BUFFER); + + irr::core::vector3df rightEye; + irr::core::matrix4 rightMove; + rightMove.setTranslation(irr::core::vector3df( + g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); + rightEye = (startMatrix * rightMove).getTranslation(); + + // clear the depth buffer, and color + getVideoDriver()->beginScene(true, true, irr::video::SColor(200, 200, 200, 255)); + camera->getCameraNode()->setPosition(rightEye); + camera->getCameraNode()->setTarget(focusPoint); + get_scene_manager()->drawAll(); + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) + camera->drawWieldedTool(&rightMove); + hud->drawHotbar(client->getPlayerItem()); + hud->drawLuaElements(camera->getOffset()); + camera->drawNametags(); + } + + guienv->drawAll(); + + camera->getCameraNode()->setPosition(oldPosition); + camera->getCameraNode()->setTarget(oldTarget); +#endif +} + +// returns (size / coef), rounded upwards +inline int scaledown(int coef, int size) +{ + return (size + coef - 1) / coef; +} + +void RenderingEngine::draw_plain(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor) +{ + // Undersampling-specific stuff + static video::ITexture *image = NULL; + static v2u32 last_pixelated_size = v2u32(0, 0); + static thread_local int undersampling = g_settings->getU16("undersampling"); + v2u32 pixelated_size; + v2u32 dest_size; + if (undersampling > 0) { + pixelated_size = v2u32(scaledown(undersampling, screensize.X), + scaledown(undersampling, screensize.Y)); + dest_size = v2u32(undersampling * pixelated_size.X, + undersampling * pixelated_size.Y); + if (pixelated_size != last_pixelated_size) { + init_texture(pixelated_size, &image, "mt_drawimage_img1"); + last_pixelated_size = pixelated_size; + } + getVideoDriver()->setRenderTarget(image, true, true, skycolor); + } + + // Render + get_scene_manager()->drawAll(); + getVideoDriver()->setTransform(video::ETS_WORLD, core::IdentityMatrix); + if (show_hud) { + hud->drawSelectionMesh(); + if (draw_wield_tool) { + camera->drawWieldedTool(); + } + } + + // Upscale lowres render + if (undersampling > 0) { + getVideoDriver()->setRenderTarget(0, true, true); + getVideoDriver()->draw2DImage(image, + irr::core::rect(0, 0, dest_size.X, dest_size.Y), + irr::core::rect(0, 0, pixelated_size.X, + pixelated_size.Y)); + } +} + +const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type) +{ + static const char *driver_ids[] = { + "null", "software", "burningsvideo", "direct3d8", "direct3d9", + "opengl", "ogles1", "ogles2", + }; + + return driver_ids[type]; +} + +const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type) +{ + static const char *driver_names[] = { + "NULL Driver", "Software Renderer", "Burning's Video", + "Direct3D 8", "Direct3D 9", "OpenGL", "OpenGL ES1", "OpenGL ES2", + }; + + return driver_names[type]; +} + +#ifndef __ANDROID__ +#ifdef XORG_USED + +static float calcDisplayDensity() +{ + const char *current_display = getenv("DISPLAY"); + + if (current_display != NULL) { + Display *x11display = XOpenDisplay(current_display); + + if (x11display != NULL) { + /* try x direct */ + float dpi_height = floor( + DisplayHeight(x11display, 0) / + (DisplayHeightMM(x11display, 0) * + 0.039370) + + 0.5); + float dpi_width = floor( + DisplayWidth(x11display, 0) / + (DisplayWidthMM(x11display, 0) * + 0.039370) + + 0.5); + + XCloseDisplay(x11display); + + return std::max(dpi_height, dpi_width) / 96.0; + } + } + + /* return manually specified dpi */ + return g_settings->getFloat("screen_dpi") / 96.0; +} + +float RenderingEngine::getDisplayDensity() +{ + static float cached_display_density = calcDisplayDensity(); + return cached_display_density; +} + +#else // XORG_USED +float RenderingEngine::getDisplayDensity() +{ + return g_settings->getFloat("screen_dpi") / 96.0; +} +#endif // XORG_USED + +v2u32 RenderingEngine::getDisplaySize() +{ + IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); + + core::dimension2d deskres = + nulldevice->getVideoModeList()->getDesktopResolution(); + nulldevice->drop(); + + return deskres; +} +#endif // __ANDROID__ diff --git a/src/client/renderingengine.h b/src/client/renderingengine.h new file mode 100644 index 00000000..40fbaa87 --- /dev/null +++ b/src/client/renderingengine.h @@ -0,0 +1,185 @@ +/* +Minetest +Copyright (C) 2010-2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#pragma once + +#include +#include +#include "irrlichttypes_extrabloated.h" +#include "debug.h" + +class ITextureSource; +class Camera; +class Client; +class LocalPlayer; +class Hud; +class Minimap; + +class RenderingEngine +{ +public: + RenderingEngine(IEventReceiver *eventReceiver); + ~RenderingEngine(); + + v2u32 getWindowSize() const; + void setResizable(bool resize); + + video::IVideoDriver *getVideoDriver(); + + static const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type); + static const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type); + static float getDisplayDensity(); + static v2u32 getDisplaySize(); + + static void setXorgClassHint(const video::SExposedVideoData &video_data, + const std::string &name); + bool setWindowIcon(); + bool setXorgWindowIconFromPath(const std::string &icon_file); + static bool print_video_modes(); + + static RenderingEngine *get_instance() { return s_singleton; } + + static io::IFileSystem *get_filesystem() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device->getFileSystem(); + } + + static video::IVideoDriver *get_video_driver() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device->getVideoDriver(); + } + + static scene::IMeshCache *get_mesh_cache() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device->getSceneManager()->getMeshCache(); + } + + static scene::ISceneManager *get_scene_manager() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device->getSceneManager(); + } + + static irr::IrrlichtDevice *get_raw_device() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device; + } + + static u32 get_timer_time() + { + sanity_check(s_singleton && s_singleton->m_device && + s_singleton->m_device->getTimer()); + return s_singleton->m_device->getTimer()->getTime(); + } + + static gui::IGUIEnvironment *get_gui_env() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device->getGUIEnvironment(); + } + + inline static void draw_load_screen(const std::wstring &text, + gui::IGUIEnvironment *guienv, ITextureSource *tsrc, + float dtime = 0, int percent = 0, bool clouds = true) + { + s_singleton->_draw_load_screen( + text, guienv, tsrc, dtime, percent, clouds); + } + + inline static void draw_scene(Camera *camera, Client *client, LocalPlayer *player, + Hud *hud, Minimap *mapper, gui::IGUIEnvironment *guienv, + const v2u32 &screensize, const video::SColor &skycolor, + bool show_hud, bool show_minimap) + { + s_singleton->_draw_scene(camera, client, player, hud, mapper, guienv, + screensize, skycolor, show_hud, show_minimap); + } + + static bool run() + { + sanity_check(s_singleton && s_singleton->m_device); + return s_singleton->m_device->run(); + } + + static std::vector> getSupportedVideoModes(); + static std::vector getSupportedVideoDrivers(); + +private: + enum parallax_sign + { + LEFT = -1, + RIGHT = 1, + EYECOUNT = 2 + }; + + void _draw_load_screen(const std::wstring &text, gui::IGUIEnvironment *guienv, + ITextureSource *tsrc, float dtime = 0, int percent = 0, + bool clouds = true); + + void _draw_scene(Camera *camera, Client *client, LocalPlayer *player, Hud *hud, + Minimap *mapper, gui::IGUIEnvironment *guienv, + const v2u32 &screensize, const video::SColor &skycolor, + bool show_hud, bool show_minimap); + + void draw_anaglyph_3d_mode(Camera *camera, bool show_hud, Hud *hud, + bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv); + + void draw_interlaced_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor); + + void draw_sidebyside_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor); + + void draw_top_bottom_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor); + + void draw_pageflip_3d_mode(Camera *camera, bool show_hud, Hud *hud, + const v2u32 &screensize, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor); + + void draw_plain(Camera *camera, bool show_hud, Hud *hud, const v2u32 &screensize, + bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor); + + void init_texture(const v2u32 &screensize, video::ITexture **texture, + const char *name); + + video::ITexture *draw_image(const v2u32 &screensize, parallax_sign psign, + const irr::core::matrix4 &startMatrix, + const irr::core::vector3df &focusPoint, bool show_hud, + Camera *camera, Hud *hud, bool draw_wield_tool, Client *client, + gui::IGUIEnvironment *guienv, const video::SColor &skycolor); + + video::ITexture *draw_hud(const v2u32 &screensize, bool show_hud, Hud *hud, + Client *client, bool draw_crosshair, + const video::SColor &skycolor, gui::IGUIEnvironment *guienv, + Camera *camera); + + irr::IrrlichtDevice *m_device = nullptr; + static RenderingEngine *s_singleton; +}; diff --git a/src/client/tile.cpp b/src/client/tile.cpp index e47a40ea..1bcbdc6f 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -36,6 +36,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "imagefilters.h" #include "guiscalingfilter.h" #include "nodedef.h" +#include "renderingengine.h" #ifdef __ANDROID__ @@ -198,8 +199,7 @@ public: } m_images.clear(); } - void insert(const std::string &name, video::IImage *img, - bool prefer_local, video::IVideoDriver *driver) + void insert(const std::string &name, video::IImage *img, bool prefer_local) { assert(img); // Pre-condition // Remove old image @@ -217,7 +217,8 @@ public: if (prefer_local){ std::string path = getTexturePath(name); if (path != ""){ - video::IImage *img2 = driver->createImageFromFile(path.c_str()); + video::IImage *img2 = RenderingEngine::get_video_driver()-> + createImageFromFile(path.c_str()); if (img2){ toadd = img2; need_to_grab = false; @@ -238,7 +239,7 @@ public: return NULL; } // Primarily fetches from cache, secondarily tries to read from filesystem - video::IImage* getOrLoad(const std::string &name, IrrlichtDevice *device) + video::IImage *getOrLoad(const std::string &name) { std::map::iterator n; n = m_images.find(name); @@ -246,7 +247,7 @@ public: n->second->grab(); // Grab for caller return n->second; } - video::IVideoDriver* driver = device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); std::string path = getTexturePath(name); if (path == ""){ infostream<<"SourceImageCache::getOrLoad(): No path found for \"" @@ -274,7 +275,7 @@ private: class TextureSource : public IWritableTextureSource { public: - TextureSource(IrrlichtDevice *device); + TextureSource(); virtual ~TextureSource(); /* @@ -343,12 +344,6 @@ public: virtual Palette* getPalette(const std::string &name); - // Returns a pointer to the irrlicht device - virtual IrrlichtDevice* getDevice() - { - return m_device; - } - bool isKnownSourceImage(const std::string &name) { bool is_known = false; @@ -387,8 +382,6 @@ private: // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; - // The irrlicht device - IrrlichtDevice *m_device; // Cache of source images // This should be only accessed from the main thread @@ -435,16 +428,13 @@ private: bool m_setting_anisotropic_filter; }; -IWritableTextureSource* createTextureSource(IrrlichtDevice *device) +IWritableTextureSource *createTextureSource() { - return new TextureSource(device); + return new TextureSource(); } -TextureSource::TextureSource(IrrlichtDevice *device): - m_device(device) +TextureSource::TextureSource() { - assert(m_device); // Pre-condition - m_main_thread = std::this_thread::get_id(); // Add a NULL TextureInfo as the first index, named "" @@ -461,7 +451,7 @@ TextureSource::TextureSource(IrrlichtDevice *device): TextureSource::~TextureSource() { - video::IVideoDriver* driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); unsigned int textures_before = driver->getTextureCount(); @@ -622,7 +612,7 @@ u32 TextureSource::generateTexture(const std::string &name) return 0; } - video::IVideoDriver *driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); video::IImage *img = generateImage(name); @@ -773,7 +763,7 @@ void TextureSource::insertSourceImage(const std::string &name, video::IImage *im sanity_check(std::this_thread::get_id() == m_main_thread); - m_sourcecache.insert(name, img, true, m_device->getVideoDriver()); + m_sourcecache.insert(name, img, true); m_source_image_existence.set(name, true); } @@ -781,7 +771,7 @@ void TextureSource::rebuildImagesAndTextures() { MutexAutoLock lock(m_textureinfo_cache_mutex); - video::IVideoDriver* driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); // Recreate textures @@ -810,7 +800,7 @@ void TextureSource::rebuildImagesAndTextures() video::ITexture* TextureSource::generateTextureFromMesh( const TextureFromMeshParams ¶ms) { - video::IVideoDriver *driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); #ifdef __ANDROID__ @@ -935,8 +925,7 @@ video::ITexture* TextureSource::generateTextureFromMesh( } #endif - if (driver->queryFeature(video::EVDF_RENDER_TO_TARGET) == false) - { + if (!driver->queryFeature(video::EVDF_RENDER_TO_TARGET)) { static bool warned = false; if (!warned) { @@ -967,7 +956,7 @@ video::ITexture* TextureSource::generateTextureFromMesh( } // Get a scene manager - scene::ISceneManager *smgr_main = m_device->getSceneManager(); + scene::ISceneManager *smgr_main = RenderingEngine::get_scene_manager(); assert(smgr_main); scene::ISceneManager *smgr = smgr_main->createNewSceneManager(); assert(smgr); @@ -1065,10 +1054,6 @@ video::IImage* TextureSource::generateImage(const std::string &name) baseimg = generateImage(name.substr(0, last_separator_pos)); } - - video::IVideoDriver* driver = m_device->getVideoDriver(); - sanity_check(driver); - /* Parse out the last part of the name of the image and act according to it @@ -1196,13 +1181,13 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& baseimg) { const char escape = '\\'; // same as in generateImage() - video::IVideoDriver* driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); // Stuff starting with [ are special commands if (part_of_name.size() == 0 || part_of_name[0] != '[') { - video::IImage *image = m_sourcecache.getOrLoad(part_of_name, m_device); + video::IImage *image = m_sourcecache.getOrLoad(part_of_name); #ifdef __ANDROID__ image = Align2Npot2(image, driver); #endif @@ -1275,7 +1260,7 @@ bool TextureSource::generateImagePart(std::string part_of_name, blit_with_alpha(image, baseimg, pos_from, pos_to, dim); } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) { // Upscale overlying image - video::IImage* scaled_image = m_device->getVideoDriver()-> + video::IImage *scaled_image = RenderingEngine::get_video_driver()-> createImage(video::ECF_A8R8G8B8, dim_dst); image->copyToScaling(scaled_image); @@ -1283,7 +1268,7 @@ bool TextureSource::generateImagePart(std::string part_of_name, scaled_image->drop(); } else { // Upscale base image - video::IImage* scaled_base = m_device->getVideoDriver()-> + video::IImage *scaled_base = RenderingEngine::get_video_driver()-> createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(scaled_base); baseimg->drop(); @@ -1333,7 +1318,7 @@ bool TextureSource::generateImagePart(std::string part_of_name, horizontally tiled. */ video::IImage *img_crack = m_sourcecache.getOrLoad( - "crack_anylength.png", m_device); + "crack_anylength.png"); if (img_crack) { draw_crack(img_crack, baseimg, @@ -1855,7 +1840,7 @@ bool TextureSource::generateImagePart(std::string part_of_name, u32 height = stoi(sf.next("")); core::dimension2d dim(width, height); - video::IImage* image = m_device->getVideoDriver()-> + video::IImage *image = RenderingEngine::get_video_driver()-> createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(image); baseimg->drop(); @@ -2356,7 +2341,7 @@ video::ITexture* TextureSource::getNormalTexture(const std::string &name) video::SColor TextureSource::getTextureAverageColor(const std::string &name) { - video::IVideoDriver *driver = m_device->getVideoDriver(); + 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, @@ -2400,7 +2385,7 @@ video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present) if (isKnownSourceImage(tname)) { return getTexture(tname); } else { - video::IVideoDriver *driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IImage *flags_image = driver->createImage( video::ECF_A8R8G8B8, core::dimension2d(1, 1)); sanity_check(flags_image != NULL); diff --git a/src/client/tile.h b/src/client/tile.h index a810aa8e..b4d61542 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -114,7 +114,6 @@ public: * Should be called from the main thread. */ virtual Palette* getPalette(const std::string &name) = 0; - virtual IrrlichtDevice* getDevice()=0; virtual bool isKnownSourceImage(const std::string &name)=0; virtual video::ITexture* generateTextureFromMesh( const TextureFromMeshParams ¶ms)=0; @@ -133,7 +132,6 @@ public: virtual video::ITexture* getTexture(u32 id)=0; virtual video::ITexture* getTexture( const std::string &name, u32 *id = nullptr)=0; - virtual IrrlichtDevice* getDevice()=0; virtual bool isKnownSourceImage(const std::string &name)=0; virtual video::ITexture* generateTextureFromMesh( const TextureFromMeshParams ¶ms)=0; @@ -146,7 +144,7 @@ public: virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0; }; -IWritableTextureSource* createTextureSource(IrrlichtDevice *device); +IWritableTextureSource *createTextureSource(); #ifdef __ANDROID__ video::IImage * Align2Npot2(video::IImage * image, video::IVideoDriver* driver); @@ -302,7 +300,7 @@ struct TileSpec for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) layers[layer] = TileLayer(); } - + /*! * Returns true if this tile can be merged with the other tile. */ diff --git a/src/clientenvironment.cpp b/src/clientenvironment.cpp index e0398a06..28b61b06 100644 --- a/src/clientenvironment.cpp +++ b/src/clientenvironment.cpp @@ -31,16 +31,16 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "voxelalgorithms.h" #include "settings.h" #include +#include "client/renderingengine.h" /* ClientEnvironment */ -ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr, +ClientEnvironment::ClientEnvironment(ClientMap *map, ITextureSource *texturesource, Client *client): Environment(client), m_map(map), - m_smgr(smgr), m_texturesource(texturesource), m_client(client) { @@ -456,7 +456,7 @@ u16 ClientEnvironment::addActiveObject(ClientActiveObject *object) infostream<<"ClientEnvironment::addActiveObject(): " <<"added (id="<getId()<<")"<getId()] = object; - object->addToScene(m_smgr, m_texturesource); + object->addToScene(RenderingEngine::get_scene_manager(), m_texturesource); { // Update lighting immediately u8 light = 0; bool pos_ok; diff --git a/src/clientenvironment.h b/src/clientenvironment.h index 9d893766..05ec1908 100644 --- a/src/clientenvironment.h +++ b/src/clientenvironment.h @@ -67,8 +67,7 @@ typedef std::unordered_map ClientActiveObjectMap; class ClientEnvironment : public Environment { public: - ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr, - ITextureSource *texturesource, Client *client); + ClientEnvironment(ClientMap *map, ITextureSource *texturesource, Client *client); ~ClientEnvironment(); Map & getMap(); @@ -175,7 +174,6 @@ public: private: ClientMap *m_map; LocalPlayer *m_local_player = nullptr; - scene::ISceneManager *m_smgr; ITextureSource *m_texturesource; Client *m_client; ClientScripting *m_script = nullptr; diff --git a/src/clientmap.cpp b/src/clientmap.cpp index 73d600a7..7027d07e 100644 --- a/src/clientmap.cpp +++ b/src/clientmap.cpp @@ -31,16 +31,16 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "camera.h" // CameraModes #include "util/basic_macros.h" #include +#include "client/renderingengine.h" ClientMap::ClientMap( Client *client, MapDrawControl &control, - scene::ISceneNode* parent, - scene::ISceneManager* mgr, s32 id ): Map(dout_client, client), - scene::ISceneNode(parent, mgr, id), + scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), + RenderingEngine::get_scene_manager(), id), m_client(client), m_control(control), m_camera_position(0,0,0), diff --git a/src/clientmap.h b/src/clientmap.h index 8d272077..a0f16e46 100644 --- a/src/clientmap.h +++ b/src/clientmap.h @@ -59,8 +59,6 @@ public: ClientMap( Client *client, MapDrawControl &control, - scene::ISceneNode* parent, - scene::ISceneManager* mgr, s32 id ); diff --git a/src/clouds.cpp b/src/clouds.cpp index dc08d1ac..dd6a2dcb 100644 --- a/src/clouds.cpp +++ b/src/clouds.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 "client/renderingengine.h" #include "clouds.h" #include "noise.h" #include "constants.h" @@ -36,14 +37,12 @@ static void cloud_3d_setting_changed(const std::string &settingname, void *data) ((Clouds *)data)->readSettings(); } -Clouds::Clouds( - scene::ISceneNode* parent, - scene::ISceneManager* mgr, +Clouds::Clouds(scene::ISceneManager* mgr, s32 id, u32 seed, s16 cloudheight ): - scene::ISceneNode(parent, mgr, id), + scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), m_seed(seed) { m_material.setFlag(video::EMF_LIGHTING, false); @@ -101,22 +100,22 @@ void Clouds::render() return; ScopeProfiler sp(g_profiler, "Rendering of clouds, avg", SPT_AVG); - + int num_faces_to_draw = m_enable_3d ? 6 : 1; - + m_material.setFlag(video::EMF_BACK_FACE_CULLING, m_enable_3d); driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); driver->setMaterial(m_material); - + /* Clouds move from Z+ towards Z- */ static const float cloud_size = BS * 64.0f; - + const float cloud_full_radius = cloud_size * m_cloud_radius_i; - + // Position of cloud noise origin from the camera v2f cloud_origin_from_camera_f = m_origin - m_camera_pos; // The center point of drawing in the noise @@ -164,7 +163,7 @@ void Clouds::render() bool fog_rangefog = false; 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); @@ -340,7 +339,7 @@ void Clouds::render() } delete[] grid; - + // Restore fog settings driver->setFog(fog_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog, fog_rangefog); diff --git a/src/clouds.h b/src/clouds.h index 869f7f7f..52ea930f 100644 --- a/src/clouds.h +++ b/src/clouds.h @@ -36,9 +36,7 @@ extern irr::scene::ISceneManager *g_menucloudsmgr; class Clouds : public scene::ISceneNode { public: - Clouds( - scene::ISceneNode* parent, - scene::ISceneManager* mgr, + Clouds(scene::ISceneManager* mgr, s32 id, u32 seed, s16 cloudheight=0 diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index d7ee8fb8..1077c238 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/tile.h" #include "mesh.h" #include +#include "client/renderingengine.h" #include "client.h" #include "log.h" #include "noise.h" @@ -64,8 +65,7 @@ MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector collector = output; nodedef = data->m_client->ndef(); - smgr = data->m_client->getSceneManager(); - meshmanip = smgr->getMeshManipulator(); + 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 diff --git a/src/content_mapblock.h b/src/content_mapblock.h index 2c6a4969..0a0b12a8 100644 --- a/src/content_mapblock.h +++ b/src/content_mapblock.h @@ -39,7 +39,6 @@ public: MeshCollector *collector; INodeDefManager *nodedef; - scene::ISceneManager *smgr; scene::IMeshManipulator *meshmanip; // options diff --git a/src/drawscene.cpp b/src/drawscene.cpp deleted file mode 100644 index 2cf9689a..00000000 --- a/src/drawscene.cpp +++ /dev/null @@ -1,674 +0,0 @@ -/* -Minetest -Copyright (C) 2010-2014 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#include "drawscene.h" -#include "settings.h" -#include "clouds.h" -#include "clientmap.h" -#include "util/timetaker.h" -#include "fontengine.h" -#include "guiscalingfilter.h" -#include "filesys.h" - -typedef enum { - LEFT = -1, - RIGHT = 1, - EYECOUNT = 2 -} paralax_sign; - -void draw_anaglyph_3d_mode(Camera& camera, bool show_hud, Hud& hud, - video::IVideoDriver* driver, scene::ISceneManager* smgr, - bool draw_wield_tool, Client& client, - gui::IGUIEnvironment* guienv ) -{ - - /* preserve old setup*/ - irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); - irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); - - irr::core::matrix4 startMatrix = - camera.getCameraNode()->getAbsoluteTransformation(); - irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - - camera.getCameraNode()->getAbsolutePosition()).setLength(1) - + camera.getCameraNode()->getAbsolutePosition(); - - - //Left eye... - irr::core::vector3df leftEye; - irr::core::matrix4 leftMove; - leftMove.setTranslation( - irr::core::vector3df(-g_settings->getFloat("3d_paralax_strength"), - 0.0f, 0.0f)); - leftEye = (startMatrix * leftMove).getTranslation(); - - //clear the depth buffer, and color - driver->beginScene( true, true, irr::video::SColor(0, 200, 200, 255)); - driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED; - driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK; - driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX - + irr::scene::ESNRP_SOLID + irr::scene::ESNRP_TRANSPARENT - + irr::scene::ESNRP_TRANSPARENT_EFFECT + irr::scene::ESNRP_SHADOW; - camera.getCameraNode()->setPosition(leftEye); - camera.getCameraNode()->setTarget(focusPoint); - smgr->drawAll(); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - if (show_hud) { - hud.drawSelectionMesh(); - if (draw_wield_tool) - camera.drawWieldedTool(&leftMove); - } - - guienv->drawAll(); - - //Right eye... - irr::core::vector3df rightEye; - irr::core::matrix4 rightMove; - rightMove.setTranslation( - irr::core::vector3df(g_settings->getFloat("3d_paralax_strength"), - 0.0f, 0.0f)); - rightEye = (startMatrix * rightMove).getTranslation(); - - //clear the depth buffer - driver->clearZBuffer(); - driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN - + irr::video::ECP_BLUE; - driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK; - driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX - + irr::scene::ESNRP_SOLID + irr::scene::ESNRP_TRANSPARENT - + irr::scene::ESNRP_TRANSPARENT_EFFECT + irr::scene::ESNRP_SHADOW; - camera.getCameraNode()->setPosition(rightEye); - camera.getCameraNode()->setTarget(focusPoint); - smgr->drawAll(); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - if (show_hud) { - hud.drawSelectionMesh(); - if (draw_wield_tool) - camera.drawWieldedTool(&rightMove); - } - - guienv->drawAll(); - - driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_ALL; - driver->getOverrideMaterial().EnableFlags = 0; - driver->getOverrideMaterial().EnablePasses = 0; - camera.getCameraNode()->setPosition(oldPosition); - camera.getCameraNode()->setTarget(oldTarget); -} - -void init_texture(video::IVideoDriver* driver, const v2u32& screensize, - video::ITexture** texture, const char* name) -{ - if (*texture != NULL) - { - driver->removeTexture(*texture); - } - *texture = driver->addRenderTargetTexture( - core::dimension2d(screensize.X, screensize.Y), name, - irr::video::ECF_A8R8G8B8); -} - -video::ITexture* draw_image(const v2u32 &screensize, - paralax_sign psign, const irr::core::matrix4 &startMatrix, - const irr::core::vector3df &focusPoint, bool show_hud, - video::IVideoDriver *driver, Camera &camera, scene::ISceneManager *smgr, - Hud &hud, bool draw_wield_tool, Client &client, - gui::IGUIEnvironment *guienv, const video::SColor &skycolor) -{ - static video::ITexture* images[2] = { NULL, NULL }; - static v2u32 last_screensize = v2u32(0, 0); - - video::ITexture* image = NULL; - - if (screensize != last_screensize) { - init_texture(driver, screensize, &images[1], "mt_drawimage_img1"); - init_texture(driver, screensize, &images[0], "mt_drawimage_img2"); - last_screensize = screensize; - } - - if (psign == RIGHT) - image = images[1]; - else - image = images[0]; - - driver->setRenderTarget(image, true, true, - irr::video::SColor(255, - skycolor.getRed(), skycolor.getGreen(), skycolor.getBlue())); - - irr::core::vector3df eye_pos; - irr::core::matrix4 movement; - movement.setTranslation( - irr::core::vector3df((int) psign * - g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); - eye_pos = (startMatrix * movement).getTranslation(); - - //clear the depth buffer - driver->clearZBuffer(); - camera.getCameraNode()->setPosition(eye_pos); - camera.getCameraNode()->setTarget(focusPoint); - smgr->drawAll(); - - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - - if (show_hud) { - hud.drawSelectionMesh(); - if (draw_wield_tool) - camera.drawWieldedTool(&movement); - } - - guienv->drawAll(); - - /* switch back to real renderer */ - driver->setRenderTarget(0, true, true, - irr::video::SColor(0, - skycolor.getRed(), skycolor.getGreen(), skycolor.getBlue())); - - return image; -} - -video::ITexture* draw_hud(video::IVideoDriver* driver, const v2u32& screensize, - bool show_hud, Hud& hud, Client& client, bool draw_crosshair, - video::SColor skycolor, gui::IGUIEnvironment* guienv, Camera& camera ) -{ - static video::ITexture* image = NULL; - init_texture(driver, screensize, &image, "mt_drawimage_hud"); - driver->setRenderTarget(image, true, true, - irr::video::SColor(255,0,0,0)); - - if (show_hud) - { - if (draw_crosshair) - hud.drawCrosshair(); - hud.drawHotbar(client.getPlayerItem()); - hud.drawLuaElements(camera.getOffset()); - camera.drawNametags(); - guienv->drawAll(); - } - - driver->setRenderTarget(0, true, true, - irr::video::SColor(0, - skycolor.getRed(), skycolor.getGreen(), skycolor.getBlue())); - - return image; -} - -void draw_interlaced_3d_mode(Camera& camera, bool show_hud, - Hud& hud, video::IVideoDriver* driver, - scene::ISceneManager* smgr, const v2u32& screensize, - bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, - video::SColor skycolor ) -{ - /* save current info */ - irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); - irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); - irr::core::matrix4 startMatrix = - camera.getCameraNode()->getAbsoluteTransformation(); - irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - - camera.getCameraNode()->getAbsolutePosition()).setLength(1) - + camera.getCameraNode()->getAbsolutePosition(); - - /* create left view */ - video::ITexture* left_image = draw_image(screensize, LEFT, startMatrix, - focusPoint, show_hud, driver, camera, smgr, hud, - draw_wield_tool, client, guienv, skycolor); - - //Right eye... - irr::core::vector3df rightEye; - irr::core::matrix4 rightMove; - rightMove.setTranslation( - irr::core::vector3df(g_settings->getFloat("3d_paralax_strength"), - 0.0f, 0.0f)); - rightEye = (startMatrix * rightMove).getTranslation(); - - //clear the depth buffer - driver->clearZBuffer(); - camera.getCameraNode()->setPosition(rightEye); - camera.getCameraNode()->setTarget(focusPoint); - smgr->drawAll(); - - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - - if (show_hud) { - hud.drawSelectionMesh(); - if(draw_wield_tool) - camera.drawWieldedTool(&rightMove); - } - guienv->drawAll(); - - for (unsigned int i = 0; i < screensize.Y; i+=2 ) { -#if (IRRLICHT_VERSION_MAJOR >= 1) && (IRRLICHT_VERSION_MINOR >= 8) - driver->draw2DImage(left_image, irr::core::position2d(0, i), -#else - driver->draw2DImage(left_image, irr::core::position2d(0, screensize.Y-i), -#endif - irr::core::rect(0, i,screensize.X, i+1), 0, - irr::video::SColor(255, 255, 255, 255), - false); - } - - /* cleanup */ - camera.getCameraNode()->setPosition(oldPosition); - camera.getCameraNode()->setTarget(oldTarget); -} - -void draw_sidebyside_3d_mode(Camera& camera, bool show_hud, - Hud& hud, video::IVideoDriver* driver, - scene::ISceneManager* smgr, const v2u32& screensize, - bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, - video::SColor skycolor ) -{ - /* save current info */ - irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); - irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); - irr::core::matrix4 startMatrix = - camera.getCameraNode()->getAbsoluteTransformation(); - irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - - camera.getCameraNode()->getAbsolutePosition()).setLength(1) - + camera.getCameraNode()->getAbsolutePosition(); - - /* create left view */ - video::ITexture* left_image = draw_image(screensize, LEFT, startMatrix, - focusPoint, show_hud, driver, camera, smgr, hud, - draw_wield_tool, client, guienv, skycolor); - - /* create right view */ - video::ITexture* right_image = draw_image(screensize, RIGHT, startMatrix, - focusPoint, show_hud, driver, camera, smgr, hud, - draw_wield_tool, client, guienv, skycolor); - - /* create hud overlay */ - video::ITexture* hudtexture = draw_hud(driver, screensize, show_hud, hud, client, - false, skycolor, guienv, camera ); - driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); - //makeColorKeyTexture mirrors texture so we do it twice to get it right again - driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); - - draw2DImageFilterScaled(driver, left_image, - irr::core::rect(0, 0, screensize.X/2, screensize.Y), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); - - draw2DImageFilterScaled(driver, hudtexture, - irr::core::rect(0, 0, screensize.X/2, screensize.Y), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); - - draw2DImageFilterScaled(driver, right_image, - irr::core::rect(screensize.X/2, 0, screensize.X, screensize.Y), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); - - draw2DImageFilterScaled(driver, hudtexture, - irr::core::rect(screensize.X/2, 0, screensize.X, screensize.Y), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); - - left_image = NULL; - right_image = NULL; - - /* cleanup */ - camera.getCameraNode()->setPosition(oldPosition); - camera.getCameraNode()->setTarget(oldTarget); -} - -void draw_top_bottom_3d_mode(Camera& camera, bool show_hud, - Hud& hud, video::IVideoDriver* driver, - scene::ISceneManager* smgr, const v2u32& screensize, - bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, - video::SColor skycolor ) -{ - /* save current info */ - irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); - irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); - irr::core::matrix4 startMatrix = - camera.getCameraNode()->getAbsoluteTransformation(); - irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - - camera.getCameraNode()->getAbsolutePosition()).setLength(1) - + camera.getCameraNode()->getAbsolutePosition(); - - /* create left view */ - video::ITexture* left_image = draw_image(screensize, LEFT, startMatrix, - focusPoint, show_hud, driver, camera, smgr, hud, - draw_wield_tool, client, guienv, skycolor); - - /* create right view */ - video::ITexture* right_image = draw_image(screensize, RIGHT, startMatrix, - focusPoint, show_hud, driver, camera, smgr, hud, - draw_wield_tool, client, guienv, skycolor); - - /* create hud overlay */ - video::ITexture* hudtexture = draw_hud(driver, screensize, show_hud, hud, client, - false, skycolor, guienv, camera ); - driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); - //makeColorKeyTexture mirrors texture so we do it twice to get it right again - driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); - - draw2DImageFilterScaled(driver, left_image, - irr::core::rect(0, 0, screensize.X, screensize.Y/2), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); - - draw2DImageFilterScaled(driver, hudtexture, - irr::core::rect(0, 0, screensize.X, screensize.Y/2), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); - - draw2DImageFilterScaled(driver, right_image, - irr::core::rect(0, screensize.Y/2, screensize.X, screensize.Y), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); - - draw2DImageFilterScaled(driver, hudtexture, - irr::core::rect(0, screensize.Y/2, screensize.X, screensize.Y), - irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); - - left_image = NULL; - right_image = NULL; - - /* cleanup */ - camera.getCameraNode()->setPosition(oldPosition); - camera.getCameraNode()->setTarget(oldTarget); -} - -void draw_pageflip_3d_mode(Camera& camera, bool show_hud, - Hud& hud, video::IVideoDriver* driver, - scene::ISceneManager* smgr, const v2u32& screensize, - bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, - video::SColor skycolor) -{ -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 - errorstream << "Pageflip 3D mode is not supported" - << " with your Irrlicht version!" << std::endl; -#else - /* preserve old setup*/ - irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); - irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); - - irr::core::matrix4 startMatrix = - camera.getCameraNode()->getAbsoluteTransformation(); - irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - - camera.getCameraNode()->getAbsolutePosition()).setLength(1) - + camera.getCameraNode()->getAbsolutePosition(); - - //Left eye... - driver->setRenderTarget(irr::video::ERT_STEREO_LEFT_BUFFER); - - irr::core::vector3df leftEye; - irr::core::matrix4 leftMove; - leftMove.setTranslation( - irr::core::vector3df(-g_settings->getFloat("3d_paralax_strength"), - 0.0f, 0.0f)); - leftEye = (startMatrix * leftMove).getTranslation(); - - //clear the depth buffer, and color - driver->beginScene(true, true, irr::video::SColor(200, 200, 200, 255)); - camera.getCameraNode()->setPosition(leftEye); - camera.getCameraNode()->setTarget(focusPoint); - smgr->drawAll(); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - - if (show_hud) { - hud.drawSelectionMesh(); - if (draw_wield_tool) - camera.drawWieldedTool(&leftMove); - hud.drawHotbar(client.getPlayerItem()); - hud.drawLuaElements(camera.getOffset()); - camera.drawNametags(); - } - - guienv->drawAll(); - - //Right eye... - driver->setRenderTarget(irr::video::ERT_STEREO_RIGHT_BUFFER); - - irr::core::vector3df rightEye; - irr::core::matrix4 rightMove; - rightMove.setTranslation( - irr::core::vector3df(g_settings->getFloat("3d_paralax_strength"), - 0.0f, 0.0f)); - rightEye = (startMatrix * rightMove).getTranslation(); - - //clear the depth buffer, and color - driver->beginScene(true, true, irr::video::SColor(200, 200, 200, 255)); - camera.getCameraNode()->setPosition(rightEye); - camera.getCameraNode()->setTarget(focusPoint); - smgr->drawAll(); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - - if (show_hud) { - hud.drawSelectionMesh(); - if (draw_wield_tool) - camera.drawWieldedTool(&rightMove); - hud.drawHotbar(client.getPlayerItem()); - hud.drawLuaElements(camera.getOffset()); - camera.drawNametags(); - } - - guienv->drawAll(); - - camera.getCameraNode()->setPosition(oldPosition); - camera.getCameraNode()->setTarget(oldTarget); -#endif -} - -// returns (size / coef), rounded upwards -inline int scaledown(int coef, int size) -{ - return (size + coef - 1) / coef; -} - -void draw_plain(Camera &camera, bool show_hud, - Hud &hud, video::IVideoDriver *driver, - scene::ISceneManager *smgr, const v2u32 &screensize, - bool draw_wield_tool, Client &client, gui::IGUIEnvironment *guienv, - video::SColor skycolor) -{ - // Undersampling-specific stuff - static video::ITexture *image = NULL; - static v2u32 last_pixelated_size = v2u32(0, 0); - static thread_local int undersampling = g_settings->getU16("undersampling"); - v2u32 pixelated_size; - v2u32 dest_size; - if (undersampling > 0) { - pixelated_size = v2u32(scaledown(undersampling, screensize.X), - scaledown(undersampling, screensize.Y)); - dest_size = v2u32(undersampling * pixelated_size.X, undersampling * pixelated_size.Y); - if (pixelated_size != last_pixelated_size) { - init_texture(driver, pixelated_size, &image, "mt_drawimage_img1"); - last_pixelated_size = pixelated_size; - } - driver->setRenderTarget(image, true, true, skycolor); - } - - // Render - smgr->drawAll(); - driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); - if (show_hud) { - hud.drawSelectionMesh(); - if (draw_wield_tool) { - camera.drawWieldedTool(); - } - } - - // Upscale lowres render - if (undersampling > 0) { - driver->setRenderTarget(0, true, true); - driver->draw2DImage(image, - irr::core::rect(0, 0, dest_size.X, dest_size.Y), - irr::core::rect(0, 0, pixelated_size.X, pixelated_size.Y)); - } -} - -void draw_scene(video::IVideoDriver *driver, scene::ISceneManager *smgr, - Camera &camera, Client &client, LocalPlayer *player, Hud &hud, - Minimap *mapper, gui::IGUIEnvironment *guienv, - const v2u32 &screensize, const video::SColor &skycolor, - bool show_hud, bool show_minimap) -{ - TimeTaker timer("smgr"); - - bool draw_wield_tool = (show_hud && - (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) && - camera.getCameraMode() < CAMERA_MODE_THIRD ); - - 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"); - } - catch(SettingNotFoundException) {} -#endif - - const std::string &draw_mode = g_settings->get("3d_mode"); - - if (draw_mode == "anaglyph") - { - draw_anaglyph_3d_mode(camera, show_hud, hud, driver, - smgr, draw_wield_tool, client, guienv); - draw_crosshair = false; - } - else if (draw_mode == "interlaced") - { - draw_interlaced_3d_mode(camera, show_hud, hud, driver, - smgr, screensize, draw_wield_tool, client, guienv, skycolor); - draw_crosshair = false; - } - else if (draw_mode == "sidebyside") - { - draw_sidebyside_3d_mode(camera, show_hud, hud, driver, - smgr, screensize, draw_wield_tool, client, guienv, skycolor); - show_hud = false; - } - else if (draw_mode == "topbottom") - { - draw_top_bottom_3d_mode(camera, show_hud, hud, driver, - smgr, screensize, draw_wield_tool, client, guienv, skycolor); - show_hud = false; - } - else if (draw_mode == "pageflip") - { - draw_pageflip_3d_mode(camera, show_hud, hud, driver, - smgr, screensize, draw_wield_tool, client, guienv, skycolor); - draw_crosshair = false; - show_hud = false; - } - else { - draw_plain(camera, show_hud, hud, driver, - smgr, screensize, draw_wield_tool, client, guienv, skycolor); - } - - /* - Post effects - */ - { - client.getEnv().getClientMap().renderPostFx(camera.getCameraMode()); - } - - //TODO how to make those 3d too - if (show_hud) - { - if (draw_crosshair) - hud.drawCrosshair(); - - hud.drawHotbar(client.getPlayerItem()); - hud.drawLuaElements(camera.getOffset()); - camera.drawNametags(); - - if (mapper && show_minimap) - mapper->drawMinimap(); - } - - guienv->drawAll(); - - timer.stop(true); -} - -/* - Draws a screen with a single text on it. - Text will be removed when the screen is drawn the next time. - Additionally, a progressbar can be drawn when percent is set between 0 and 100. -*/ -void draw_load_screen(const std::wstring &text, IrrlichtDevice* device, - gui::IGUIEnvironment* guienv, ITextureSource *tsrc, - float dtime, int percent, bool clouds) -{ - video::IVideoDriver* driver = device->getVideoDriver(); - v2u32 screensize = porting::getWindowSize(); - - v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight()); - v2s32 center(screensize.X / 2, screensize.Y / 2); - core::rect textrect(center - textsize / 2, center + textsize / 2); - - gui::IGUIStaticText *guitext = guienv->addStaticText( - text.c_str(), textrect, false, false); - guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); - - bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); - if (cloud_menu_background) - { - g_menuclouds->step(dtime*3); - g_menuclouds->render(); - driver->beginScene(true, true, video::SColor(255, 140, 186, 250)); - g_menucloudsmgr->drawAll(); - } - else - driver->beginScene(true, true, video::SColor(255, 0, 0, 0)); - - // draw progress bar - if ((percent >= 0) && (percent <= 100)) { - video::ITexture *progress_img = tsrc->getTexture("progress_bar.png"); - video::ITexture *progress_img_bg = tsrc->getTexture("progress_bar_bg.png"); - - if (progress_img && progress_img_bg) { -#ifndef __ANDROID__ - const core::dimension2d &img_size = progress_img_bg->getSize(); - u32 imgW = rangelim(img_size.Width, 200, 600); - u32 imgH = rangelim(img_size.Height, 24, 72); -#else - const core::dimension2d img_size(256, 48); - float imgRatio = (float) img_size.Height / img_size.Width; - u32 imgW = screensize.X / 2.2f; - u32 imgH = floor(imgW * imgRatio); -#endif - v2s32 img_pos((screensize.X - imgW) / 2, (screensize.Y - imgH) / 2); - - draw2DImageFilterScaled( - driver, progress_img_bg, - core::rect(img_pos.X, - img_pos.Y, - img_pos.X + imgW, - img_pos.Y + imgH), - core::rect(0, 0, - img_size.Width, - img_size.Height), - 0, 0, true); - - draw2DImageFilterScaled( - driver, progress_img, - core::rect(img_pos.X, - img_pos.Y, - img_pos.X + (percent * imgW) / 100, - img_pos.Y + imgH), - core::rect(0, 0, - (percent * img_size.Width) / 100, - img_size.Height), - 0, 0, true); - } - } - - guienv->drawAll(); - driver->endScene(); - guitext->remove(); - - //return guitext; -} diff --git a/src/drawscene.h b/src/drawscene.h deleted file mode 100644 index 99ff1a6b..00000000 --- a/src/drawscene.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -Minetest -Copyright (C) 2010-2014 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#ifndef DRAWSCENE_H_ -#define DRAWSCENE_H_ - -#include "camera.h" -#include "hud.h" -#include "minimap.h" -#include "irrlichttypes_extrabloated.h" - - -void draw_load_screen(const std::wstring &text, IrrlichtDevice *device, - gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime = 0, - int percent = 0, bool clouds = true); - -void draw_scene(video::IVideoDriver *driver, scene::ISceneManager *smgr, - Camera &camera, Client &client, LocalPlayer *player, - Hud &hud, Minimap *mapper, gui::IGUIEnvironment *guienv, - const v2u32 &screensize, const video::SColor &skycolor, - bool show_hud, bool show_minimap); - -#endif /* DRAWSCENE_H_ */ diff --git a/src/fontengine.cpp b/src/fontengine.cpp index 536828ed..a4d96e07 100644 --- a/src/fontengine.cpp +++ b/src/fontengine.cpp @@ -16,11 +16,11 @@ You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "fontengine.h" -#include "log.h" +#include "client/renderingengine.h" #include "config.h" #include "porting.h" -#include "constants.h" #include "filesys.h" #if USE_FREETYPE @@ -314,10 +314,8 @@ void FontEngine::initFont(unsigned int basesize, FontMode mode) if (! is_yes(m_settings->get("freetype"))) { return; } - unsigned int size = floor( - porting::getDisplayDensity() * - m_settings->getFloat("gui_scaling") * - basesize); + unsigned int size = floor(RenderingEngine::getDisplayDensity() * + m_settings->getFloat("gui_scaling") * basesize); u32 font_shadow = 0; u32 font_shadow_alpha = 0; @@ -395,7 +393,7 @@ void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode) basesize = DEFAULT_FONT_SIZE; unsigned int size = floor( - porting::getDisplayDensity() * + RenderingEngine::getDisplayDensity() * m_settings->getFloat("gui_scaling") * basesize); diff --git a/src/game.cpp b/src/game.cpp index cd407597..4c903cc7 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "game.h" #include +#include "client/renderingengine.h" #include "camera.h" #include "client.h" #include "client/inputhandler.h" @@ -30,7 +31,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "clouds.h" #include "config.h" #include "content_cao.h" -#include "drawscene.h" #include "event_manager.h" #include "fontengine.h" #include "itemdef.h" @@ -44,6 +44,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiVolumeChange.h" #include "mainmenumanager.h" #include "mapblock.h" +#include "minimap.h" #include "nodedef.h" // Needed for determining pointing to nodes #include "nodemetadata.h" #include "particles.h" @@ -152,6 +153,9 @@ struct LocalFormspecHandler : public TextDest if (fields.find("btn_exit_os") != fields.end()) { g_gamecallback->exitToOS(); +#ifndef __ANDROID__ + RenderingEngine::get_raw_device()->closeDevice(); +#endif return; } @@ -726,7 +730,6 @@ public: minimap_yaw.getAs3Values(minimap_yaw_array); #endif m_minimap_yaw.set(minimap_yaw_array, services); - } SamplerLayer_t base_tex = 0, @@ -924,14 +927,13 @@ bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_de } static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec, - Client *client, IrrlichtDevice *device, JoystickController *joystick, + Client *client, JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest) { if (*cur_formspec == 0) { - *cur_formspec = new GUIFormSpecMenu(device, joystick, - guiroot, -1, &g_menumgr, client, client->getTextureSource(), - fs_src, txt_dest); + *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr, + client, client->getTextureSource(), fs_src, txt_dest); (*cur_formspec)->doPause = false; /* @@ -996,9 +998,10 @@ static void updateChat(Client &client, f32 dtime, bool show_debug, chat_y += 2 * line_height; // first pass to calculate height of text to be set + const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10, - porting::getWindowSize().X - 20); - core::rect rect(10, chat_y, width, chat_y + porting::getWindowSize().Y); + window_size.X - 20); + core::rect rect(10, chat_y, width, chat_y + window_size.Y); guitext_chat->setRelativePosition(rect); //now use real height of text and adjust rect according to this size @@ -1200,7 +1203,6 @@ public: bool startup(bool *kill, bool random_input, InputHandler *input, - IrrlichtDevice *device, const std::string &map_dir, const std::string &playername, const std::string &password, @@ -1584,7 +1586,6 @@ Game::~Game() bool Game::startup(bool *kill, bool random_input, InputHandler *input, - IrrlichtDevice *device, const std::string &map_dir, const std::string &playername, const std::string &password, @@ -1597,7 +1598,7 @@ bool Game::startup(bool *kill, bool simple_singleplayer_mode) { // "cache" - this->device = device; + this->device = RenderingEngine::get_raw_device(); this->kill = kill; this->error_message = &error_message; this->reconnect_requested = reconnect; @@ -1609,10 +1610,11 @@ bool Game::startup(bool *kill, keycache.handler = input; keycache.populate(); - driver = device->getVideoDriver(); - smgr = device->getSceneManager(); + driver = device->getVideoDriver(); + smgr = RenderingEngine::get_scene_manager(); - smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); + RenderingEngine::get_scene_manager()->getParameters()-> + setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); memset(&runData, 0, sizeof(runData)); runData.time_from_last_punch = 10.0; @@ -1649,7 +1651,7 @@ void Game::run() Profiler::GraphValues dummyvalues; g_profiler->graphGet(dummyvalues); - draw_times.last_time = device->getTimer()->getTime(); + draw_times.last_time = RenderingEngine::get_timer_time(); set_light_table(g_settings->getFloat("display_gamma")); @@ -1661,12 +1663,12 @@ void Game::run() irr::core::dimension2d previous_screen_size(g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); - while (device->run() + while (RenderingEngine::run() && !(*kill || g_gamecallback->shutdown_requested || (server && server->getShutdownRequested()))) { const irr::core::dimension2d ¤t_screen_size = - device->getVideoDriver()->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 @@ -1779,11 +1781,11 @@ bool Game::init( u16 port, const SubgameSpec &gamespec) { - texture_src = createTextureSource(device); + texture_src = createTextureSource(); showOverlayMessage("Loading...", 0, 0); - shader_src = createShaderSource(device); + shader_src = createShaderSource(); itemdef_manager = createItemDefManager(); nodedef_manager = createNodeDefManager(); @@ -1908,7 +1910,7 @@ bool Game::createClient(const std::string &playername, shader_src->addShaderConstantSetterFactory(scsf); // Update cached textures, meshes and materials - client->afterContentReceived(device); + client->afterContentReceived(); /* Camera */ @@ -1920,7 +1922,7 @@ bool Game::createClient(const std::string &playername, /* Clouds */ if (m_cache_enable_clouds) { - clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0)); + clouds = new Clouds(smgr, -1, time(0)); if (!clouds) { *error_message = "Memory allocation error (clouds)"; errorstream << *error_message << std::endl; @@ -1930,7 +1932,7 @@ bool Game::createClient(const std::string &playername, /* Skybox */ - sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src); + sky = new Sky(-1, texture_src); scsf->setSky(sky); skybox = NULL; // This is used/set later on in the main run loop @@ -2091,8 +2093,7 @@ bool Game::connectToServer(const std::string &playername, return false; } - client = new Client(device, - playername.c_str(), password, *address, + client = new Client(playername.c_str(), password, *address, *draw_control, texture_src, shader_src, itemdef_manager, nodedef_manager, sound, eventmgr, connect_address.isIPv6(), &flags); @@ -2118,11 +2119,11 @@ bool Game::connectToServer(const std::string &playername, f32 dtime; f32 wait_time = 0; // in seconds - fps_control.last_time = device->getTimer()->getTime(); + fps_control.last_time = RenderingEngine::get_timer_time(); client->initMods(); - while (device->run()) { + while (RenderingEngine::run()) { limitFps(&fps_control, &dtime); @@ -2199,9 +2200,9 @@ bool Game::getServerContent(bool *aborted) FpsControl fps_control = { 0 }; f32 dtime; // in seconds - fps_control.last_time = device->getTimer()->getTime(); + fps_control.last_time = RenderingEngine::get_timer_time(); - while (device->run()) { + while (RenderingEngine::run()) { limitFps(&fps_control, &dtime); @@ -2239,13 +2240,13 @@ bool Game::getServerContent(bool *aborted) if (!client->itemdefReceived()) { const wchar_t *text = wgettext("Item definitions..."); progress = 25; - draw_load_screen(text, device, guienv, texture_src, + 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; - draw_load_screen(text, device, guienv, texture_src, + RenderingEngine::draw_load_screen(text, guienv, texture_src, dtime, progress); delete[] text; } else { @@ -2269,8 +2270,8 @@ bool Game::getServerContent(bool *aborted) } progress = 30 + client->mediaReceiveProgress() * 35 + 0.5; - draw_load_screen(utf8_to_wide(message.str()), device, - guienv, texture_src, dtime, progress); + RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv, + texture_src, dtime, progress); } } @@ -2676,7 +2677,7 @@ void Game::openInventory() PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client); TextDest *txt_dst = new TextDestPlayerInventory(client); - create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst); + create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst); cur_formname = ""; InventoryLocation inventoryloc; @@ -3178,7 +3179,7 @@ void Game::processClientEvents(CameraOrientation *cam) TextDestPlayerInventory *txt_dst = new TextDestPlayerInventory(client, *(event.show_formspec.formname)); - create_formspec_menu(¤t_formspec, client, device, &input->joystick, + create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst); cur_formname = *(event.show_formspec.formname); } @@ -3191,7 +3192,7 @@ void Game::processClientEvents(CameraOrientation *cam) { FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec); LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client); - create_formspec_menu(¤t_formspec, client, device, &input->joystick, + create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst); } delete event.show_formspec.formspec; @@ -3201,8 +3202,7 @@ void Game::processClientEvents(CameraOrientation *cam) case CE_SPAWN_PARTICLE: case CE_ADD_PARTICLESPAWNER: case CE_DELETE_PARTICLESPAWNER: - client->getParticleManager()->handleParticleEvent(&event, client, - smgr, player); + client->getParticleManager()->handleParticleEvent(&event, client, player); break; case CE_HUDADD: @@ -3343,7 +3343,7 @@ void Game::processClientEvents(CameraOrientation *cam) } else if (*event.set_sky.type == "skybox" && event.set_sky.params->size() == 6) { sky->setFallbackBgColor(*event.set_sky.bgcolor); - skybox = smgr->addSkyBoxSceneNode( + skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode( texture_src->getTextureForMesh((*event.set_sky.params)[0]), texture_src->getTextureForMesh((*event.set_sky.params)[1]), texture_src->getTextureForMesh((*event.set_sky.params)[2]), @@ -3810,7 +3810,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed, TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client); create_formspec_menu(¤t_formspec, client, - device, &input->joystick, fs_src, txt_dst); + &input->joystick, fs_src, txt_dst); cur_formname = ""; current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc); @@ -3940,9 +3940,8 @@ 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()->addPunchingParticles(client, smgr, + const ContentFeatures &features = client->getNodeDefManager()->get(n); + client->getParticleManager()->addPunchingParticles(client, player, nodepos, n, features); } } @@ -4019,7 +4018,7 @@ 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, smgr, + client->getParticleManager()->addDiggingParticles(client, player, nodepos, wasnode, features); } @@ -4227,7 +4226,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, TimeTaker tt_draw("mainloop: draw"); driver->beginScene(true, true, skycolor); - draw_scene(driver, smgr, *camera, *client, player, *hud, mapper, + RenderingEngine::draw_scene(camera, client, player, hud, mapper, guienv, screensize, skycolor, flags.show_hud, flags.show_minimap); @@ -4466,11 +4465,10 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime) fps_timings->last_time = time; } -void Game::showOverlayMessage(const char *msg, float dtime, - int percent, bool draw_clouds) +void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds) { const wchar_t *wmsg = wgettext(msg); - draw_load_screen(wmsg, device, guienv, texture_src, dtime, percent, + RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent, draw_clouds); delete[] wmsg; } @@ -4519,7 +4517,7 @@ void Game::extendedResourceCleanup() // Extended resource accounting infostream << "Irrlicht resources after cleanup:" << std::endl; infostream << "\tRemaining meshes : " - << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl; + << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl; infostream << "\tRemaining textures : " << driver->getTextureCount() << std::endl; @@ -4656,7 +4654,7 @@ void Game::showPauseMenu() FormspecFormSource *fs_src = new FormspecFormSource(os.str()); LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU"); - create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst); + create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst); current_formspec->setFocus("btn_continue"); current_formspec->doPause = true; } @@ -4670,8 +4668,6 @@ void Game::showPauseMenu() void the_game(bool *kill, bool random_input, InputHandler *input, - IrrlichtDevice *device, - const std::string &map_dir, const std::string &playername, const std::string &password, @@ -4694,7 +4690,7 @@ void the_game(bool *kill, try { - if (game.startup(kill, random_input, input, device, map_dir, + if (game.startup(kill, random_input, input, map_dir, playername, password, &server_address, port, error_message, reconnect_requested, &chat_backend, gamespec, simple_singleplayer_mode)) { diff --git a/src/game.h b/src/game.h index 4fb198be..de3dd769 100644 --- a/src/game.h +++ b/src/game.h @@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef GAME_HEADER #define GAME_HEADER -#include "irrlichttypes_extrabloated.h" +#include "irrlichttypes.h" #include class InputHandler; @@ -42,7 +42,6 @@ struct GameUIFlags void the_game(bool *kill, bool random_input, InputHandler *input, - IrrlichtDevice *device, const std::string &map_dir, const std::string &playername, const std::string &password, diff --git a/src/guiEngine.cpp b/src/guiEngine.cpp index d4b98c1c..5f5b4bbf 100644 --- a/src/guiEngine.cpp +++ b/src/guiEngine.cpp @@ -19,9 +19,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiEngine.h" -#include #include #include +#include "client/renderingengine.h" #include "scripting_mainmenu.h" #include "util/numeric.h" #include "config.h" @@ -114,17 +114,14 @@ void MenuMusicFetcher::fetchSounds(const std::string &name, /******************************************************************************/ /** GUIEngine */ /******************************************************************************/ -GUIEngine::GUIEngine(irr::IrrlichtDevice *dev, - JoystickController *joystick, +GUIEngine::GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, IMenuManager *menumgr, - scene::ISceneManager *smgr, MainMenuData *data, bool &kill) : - m_device(dev), m_parent(parent), m_menumanager(menumgr), - m_smgr(smgr), + m_smgr(RenderingEngine::get_scene_manager()), m_data(data), m_kill(kill) { @@ -136,7 +133,7 @@ GUIEngine::GUIEngine(irr::IrrlichtDevice *dev, m_buttonhandler = new TextDestGuiEngine(this); //create texture source - m_texture_source = new MenuTextureSource(m_device->getVideoDriver()); + m_texture_source = new MenuTextureSource(RenderingEngine::get_video_driver()); //create soundmanager MenuMusicFetcher soundfetcher; @@ -154,15 +151,14 @@ GUIEngine::GUIEngine(irr::IrrlichtDevice *dev, rect += v2s32(4, 0); m_irr_toplefttext = - addStaticText(m_device->getGUIEnvironment(), m_toplefttext, + addStaticText(RenderingEngine::get_gui_env(), m_toplefttext, rect, false, true, 0, -1); //create formspecsource m_formspecgui = new FormspecFormSource(""); /* Create menu */ - m_menu = new GUIFormSpecMenu(m_device, - joystick, + m_menu = new GUIFormSpecMenu(joystick, m_parent, -1, m_menumanager, @@ -229,7 +225,7 @@ void GUIEngine::run() { // Always create clouds because they may or may not be // needed based on the game selected - video::IVideoDriver* driver = m_device->getVideoDriver(); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); cloudInit(); @@ -238,10 +234,10 @@ void GUIEngine::run() irr::core::dimension2d previous_screen_size(g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); - while (m_device->run() && (!m_startgame) && (!m_kill)) { + while (RenderingEngine::run() && (!m_startgame) && (!m_kill)) { const irr::core::dimension2d ¤t_screen_size = - m_device->getVideoDriver()->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 @@ -272,7 +268,7 @@ void GUIEngine::run() drawHeader(driver); drawFooter(driver); - m_device->getGUIEnvironment()->drawAll(); + RenderingEngine::get_gui_env()->drawAll(); driver->endScene(); @@ -292,10 +288,7 @@ void GUIEngine::run() /******************************************************************************/ GUIEngine::~GUIEngine() { - video::IVideoDriver* driver = m_device->getVideoDriver(); - FATAL_ERROR_IF(driver == 0, "Could not get video driver"); - - if(m_sound_manager != &dummySoundManager){ + if (m_sound_manager != &dummySoundManager){ delete m_sound_manager; m_sound_manager = NULL; } @@ -308,7 +301,7 @@ GUIEngine::~GUIEngine() //clean up texture pointers for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) { if (m_textures[i].texture) - driver->removeTexture(m_textures[i].texture); + RenderingEngine::get_video_driver()->removeTexture(m_textures[i].texture); } delete m_texture_source; @@ -320,21 +313,20 @@ GUIEngine::~GUIEngine() /******************************************************************************/ void GUIEngine::cloudInit() { - m_cloud.clouds = new Clouds(m_smgr->getRootSceneNode(), - m_smgr, -1, rand(), 100); + m_cloud.clouds = new Clouds(m_smgr, -1, rand(), 100); m_cloud.clouds->update(v2f(0, 0), video::SColor(255,200,200,255)); m_cloud.camera = m_smgr->addCameraSceneNode(0, v3f(0,0,0), v3f(0, 60, 100)); m_cloud.camera->setFarValue(10000); - m_cloud.lasttime = m_device->getTimer()->getTime(); + m_cloud.lasttime = RenderingEngine::get_timer_time(); } /******************************************************************************/ void GUIEngine::cloudPreProcess() { - u32 time = m_device->getTimer()->getTime(); + u32 time = RenderingEngine::get_timer_time(); if(time > m_cloud.lasttime) m_cloud.dtime = (time - m_cloud.lasttime) / 1000.0; @@ -356,7 +348,7 @@ void GUIEngine::cloudPostProcess() u32 busytime_u32; // not using getRealTime is necessary for wine - u32 time = m_device->getTimer()->getTime(); + u32 time = RenderingEngine::get_timer_time(); if(time > m_cloud.lasttime) busytime_u32 = time - m_cloud.lasttime; else @@ -365,9 +357,9 @@ void GUIEngine::cloudPostProcess() // FPS limiter u32 frametime_min = 1000./fps_max; - if(busytime_u32 < frametime_min) { + if (busytime_u32 < frametime_min) { u32 sleeptime = frametime_min - busytime_u32; - m_device->sleep(sleeptime); + RenderingEngine::get_raw_device()->sleep(sleeptime); } } @@ -502,17 +494,14 @@ void GUIEngine::drawFooter(video::IVideoDriver *driver) bool GUIEngine::setTexture(texture_layer layer, std::string texturepath, bool tile_image, unsigned int minsize) { - video::IVideoDriver* driver = m_device->getVideoDriver(); - FATAL_ERROR_IF(driver == 0, "Could not get video driver"); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); - if (m_textures[layer].texture != NULL) - { + if (m_textures[layer].texture) { driver->removeTexture(m_textures[layer].texture); m_textures[layer].texture = NULL; } - if ((texturepath == "") || !fs::PathExists(texturepath)) - { + if ((texturepath == "") || !fs::PathExists(texturepath)) { return false; } @@ -520,8 +509,7 @@ bool GUIEngine::setTexture(texture_layer layer, std::string texturepath, m_textures[layer].tile = tile_image; m_textures[layer].minsize = minsize; - if (m_textures[layer].texture == NULL) - { + if (m_textures[layer].texture == NULL) { return false; } @@ -573,7 +561,7 @@ void GUIEngine::updateTopLeftTextSize() m_irr_toplefttext->remove(); m_irr_toplefttext = - addStaticText(m_device->getGUIEnvironment(), m_toplefttext, + addStaticText(RenderingEngine::get_gui_env(), m_toplefttext, rect, false, true, 0, -1); } diff --git a/src/guiEngine.h b/src/guiEngine.h index cf2bade7..9f59051e 100644 --- a/src/guiEngine.h +++ b/src/guiEngine.h @@ -150,11 +150,9 @@ public: * @param smgr scene manager to add scene elements to * @param data struct to transfer data to main game handling */ - GUIEngine(irr::IrrlichtDevice *dev, - JoystickController *joystick, + GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, IMenuManager *menumgr, - scene::ISceneManager *smgr, MainMenuData *data, bool &kill); @@ -192,8 +190,6 @@ private: /** update size of topleftext element */ void updateTopLeftTextSize(); - /** device to draw at */ - irr::IrrlichtDevice *m_device = nullptr; /** parent gui element */ gui::IGUIElement *m_parent = nullptr; /** manager to add menus to */ diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index d721c917..0592f4e1 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -36,6 +36,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include "client/renderingengine.h" #include "log.h" #include "client/tile.h" // ITextureSource #include "hud.h" // drawItemStack @@ -78,14 +79,11 @@ static unsigned int font_line_height(gui::IGUIFont *font) return font->getDimension(L"Ay").Height + font->getKerningHeight(); } -GUIFormSpecMenu::GUIFormSpecMenu(irr::IrrlichtDevice* dev, - JoystickController *joystick, - gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, - Client *client, - ISimpleTextureSource *tsrc, IFormSource* fsrc, TextDest* tdst, +GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick, + gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, + Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst, bool remap_dbl_click) : - GUIModalMenu(dev->getGUIEnvironment(), parent, id, menumgr), - m_device(dev), + GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr), m_invmgr(client), m_tsrc(tsrc), m_client(client), @@ -2054,7 +2052,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) if (mydata.explicit_size) { // compute scaling for specified form size if (m_lock) { - v2u32 current_screensize = m_device->getVideoDriver()->getScreenSize(); + v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize(); v2u32 delta = current_screensize - m_lockscreensize; if (current_screensize.Y > m_lockscreensize.Y) @@ -2075,7 +2073,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) } double gui_scaling = g_settings->getFloat("gui_scaling"); - double screen_dpi = porting::getDisplayDensity() * 96; + double screen_dpi = RenderingEngine::getDisplayDensity() * 96; double use_imgsize; if (m_lock) { @@ -2108,7 +2106,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) ((5.0/4.0) * (0.5 + mydata.invsize.X)); double fity_imgsize = mydata.screensize.Y / ((15.0/13.0) * (0.85 * mydata.invsize.Y)); - double screen_dpi = porting::getDisplayDensity() * 96; + 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))); @@ -2579,7 +2577,7 @@ void GUIFormSpecMenu::drawMenu() /* TODO find way to show tooltips on touchscreen */ #ifndef HAVE_TOUCHSCREENGUI - m_pointer = m_device->getCursorControl()->getPosition(); + m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition(); #endif /* diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 66b9b019..6d015e5c 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -287,8 +287,7 @@ class GUIFormSpecMenu : public GUIModalMenu }; public: - GUIFormSpecMenu(irr::IrrlichtDevice* dev, - JoystickController *joystick, + GUIFormSpecMenu(JoystickController *joystick, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, Client *client, @@ -378,7 +377,6 @@ protected: v2s32 pos_offset; std::stack container_stack; - irr::IrrlichtDevice* m_device; InventoryManager *m_invmgr; ISimpleTextureSource *m_tsrc; Client *m_client; @@ -386,7 +384,6 @@ protected: std::string m_formspec_string; InventoryLocation m_current_inventory_location; - std::vector m_inventorylists; std::vector m_inventory_rings; std::vector m_backgrounds; diff --git a/src/guiTable.cpp b/src/guiTable.cpp index 44da4aa7..9354eef3 100644 --- a/src/guiTable.cpp +++ b/src/guiTable.cpp @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include "client/renderingengine.h" #include "debug.h" #include "log.h" #include "client/tile.h" @@ -79,7 +80,8 @@ GUITable::GUITable(gui::IGUIEnvironment *env, updateAbsolutePosition(); core::rect relative_rect = m_scrollbar->getRelativePosition(); - s32 width = (relative_rect.getWidth()/(2.0/3.0)) * porting::getDisplayDensity() * + s32 width = (relative_rect.getWidth()/(2.0/3.0)) * + RenderingEngine::getDisplayDensity() * g_settings->getFloat("gui_scaling"); m_scrollbar->setRelativePosition(core::rect( relative_rect.LowerRightCorner.X-width,relative_rect.UpperLeftCorner.Y, diff --git a/src/guiscalingfilter.cpp b/src/guiscalingfilter.cpp index 41cc7283..1b0dfac7 100644 --- a/src/guiscalingfilter.cpp +++ b/src/guiscalingfilter.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "util/numeric.h" #include +#include "client/renderingengine.h" /* Maintain a static cache to store the images that correspond to textures * in a format that's manipulable by code. Some platforms exhibit issues @@ -48,18 +49,18 @@ void guiScalingCache(io::path key, video::IVideoDriver *driver, video::IImage *v } // Manually clear the cache, e.g. when switching to different worlds. -void guiScalingCacheClear(video::IVideoDriver *driver) +void guiScalingCacheClear() { for (std::map::iterator it = g_imgCache.begin(); it != g_imgCache.end(); ++it) { - if (it->second != NULL) + if (it->second) it->second->drop(); } g_imgCache.clear(); for (std::map::iterator it = g_txrCache.begin(); it != g_txrCache.end(); ++it) { - if (it->second != NULL) - driver->removeTexture(it->second); + if (it->second) + RenderingEngine::get_video_driver()->removeTexture(it->second); } g_txrCache.clear(); } diff --git a/src/guiscalingfilter.h b/src/guiscalingfilter.h index 768fe8d5..d956e141 100644 --- a/src/guiscalingfilter.h +++ b/src/guiscalingfilter.h @@ -26,7 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., void guiScalingCache(io::path key, video::IVideoDriver *driver, video::IImage *value); // Manually clear the cache, e.g. when switching to different worlds. -void guiScalingCacheClear(video::IVideoDriver *driver); +void guiScalingCacheClear(); /* Get a cached, high-quality pre-scaled texture for display purposes. If the * texture is not already cached, attempt to create it. Returns a pre-scaled texture, diff --git a/src/hud.cpp b/src/hud.cpp index 1b3b2f26..2285fb71 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -34,6 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mesh.h" #include "wieldmesh.h" #include +#include "client/renderingengine.h" #ifdef HAVE_TOUCHSCREENGUI #include "touchscreengui.h" @@ -51,7 +52,8 @@ Hud::Hud(video::IVideoDriver *driver, scene::ISceneManager* smgr, this->inventory = inventory; m_hud_scaling = g_settings->getFloat("hud_scaling"); - m_hotbar_imagesize = floor(HOTBAR_IMAGE_SIZE * porting::getDisplayDensity() + 0.5); + m_hotbar_imagesize = floor(HOTBAR_IMAGE_SIZE * + RenderingEngine::getDisplayDensity() + 0.5f); m_hotbar_imagesize *= m_hud_scaling; m_padding = m_hotbar_imagesize / 12; @@ -213,8 +215,8 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, // Position of upper left corner of bar v2s32 pos = screen_offset; - pos.X *= m_hud_scaling * porting::getDisplayDensity(); - pos.Y *= m_hud_scaling * porting::getDisplayDensity(); + pos.X *= m_hud_scaling * RenderingEngine::getDisplayDensity(); + pos.Y *= m_hud_scaling * RenderingEngine::getDisplayDensity(); pos += upperleftpos; // Store hotbar_image in member variable, used by drawItem() @@ -384,7 +386,7 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, std::string texture, if (size == v2s32()) { dstd = srcd; } else { - float size_factor = m_hud_scaling * porting::getDisplayDensity(); + float size_factor = m_hud_scaling * RenderingEngine::getDisplayDensity(); dstd.Height = size.Y * size_factor; dstd.Width = size.X * size_factor; offset.X *= size_factor; @@ -449,7 +451,8 @@ void Hud::drawHotbar(u16 playeritem) { s32 width = hotbar_itemcount * (m_hotbar_imagesize + m_padding * 2); v2s32 pos = centerlowerpos - v2s32(width / 2, m_hotbar_imagesize + m_padding * 3); - if ( (float) width / (float) porting::getWindowSize().X <= + const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); + 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); @@ -607,11 +610,14 @@ void Hud::updateSelectionMesh(const v3s16 &camera_offset) } void Hud::resizeHotbar() { - if (m_screensize != porting::getWindowSize()) { - m_hotbar_imagesize = floor(HOTBAR_IMAGE_SIZE * porting::getDisplayDensity() + 0.5); + 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 *= m_hud_scaling; m_padding = m_hotbar_imagesize / 12; - m_screensize = porting::getWindowSize(); + m_screensize = window_size; m_displaycenter = v2s32(m_screensize.X/2,m_screensize.Y/2); } } diff --git a/src/mainmenumanager.h b/src/mainmenumanager.h index b9bd3762..adc40f4f 100644 --- a/src/mainmenumanager.h +++ b/src/mainmenumanager.h @@ -124,17 +124,12 @@ extern bool isMenuActive(); class MainGameCallback : public IGameCallback { public: - MainGameCallback(IrrlichtDevice *a_device): - device(a_device) - { - } + MainGameCallback() {} + virtual ~MainGameCallback() {} virtual void exitToOS() { shutdown_requested = true; -#ifndef __ANDROID__ - device->closeDevice(); -#endif } virtual void disconnect() @@ -170,8 +165,6 @@ public: bool shutdown_requested = false; bool keyconfig_changed = false; - - IrrlichtDevice *device; }; extern MainGameCallback *g_gamecallback; diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index 04a22716..d8a7d4d7 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -30,7 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "shader.h" #include "settings.h" #include "util/directiontables.h" -#include +#include "client/renderingengine.h" /* MeshMakeData @@ -1008,15 +1008,11 @@ static void updateAllFastFaceRows(MeshMakeData *data, MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_minimap_mapblock(NULL), - m_client(data->m_client), - m_driver(m_client->tsrc()->getDevice()->getVideoDriver()), - m_tsrc(m_client->getTextureSource()), - m_shdrsrc(m_client->getShaderSource()), + 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_crack_materials(), - m_last_daynight_ratio((u32) -1), - m_daynight_diffs() + m_last_daynight_ratio((u32) -1) { for (int m = 0; m < MAX_TILE_LAYERS; m++) m_mesh[m] = new scene::SMesh(); @@ -1219,7 +1215,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): if (m_use_tangent_vertices) { scene::IMeshManipulator* meshmanip = - m_client->getSceneManager()->getMeshManipulator(); + RenderingEngine::get_scene_manager()->getMeshManipulator(); meshmanip->recalculateTangents(m_mesh[layer], true, false, false); } @@ -1254,7 +1250,7 @@ MapBlockMesh::~MapBlockMesh() if (m_enable_vbo && m_mesh[m]) for (u32 i = 0; i < m_mesh[m]->getMeshBufferCount(); i++) { scene::IMeshBuffer *buf = m_mesh[m]->getMeshBuffer(i); - m_driver->removeHardwareBuffer(buf); + RenderingEngine::get_video_driver()->removeHardwareBuffer(buf); } m_mesh[m]->drop(); m_mesh[m] = NULL; diff --git a/src/mapblock_mesh.h b/src/mapblock_mesh.h index 8aeccff2..e2a66fbb 100644 --- a/src/mapblock_mesh.h +++ b/src/mapblock_mesh.h @@ -42,7 +42,6 @@ struct MeshMakeData v3s16 m_blockpos = v3s16(-1337,-1337,-1337); v3s16 m_crack_pos_relative = v3s16(-1337,-1337,-1337); bool m_smooth_lighting = false; - bool m_show_hud = false; Client *m_client; bool m_use_shaders; @@ -138,8 +137,6 @@ public: private: scene::IMesh *m_mesh[MAX_TILE_LAYERS]; MinimapMapblock *m_minimap_mapblock; - Client *m_client; - video::IVideoDriver *m_driver; ITextureSource *m_tsrc; IShaderSource *m_shdrsrc; diff --git a/src/minimap.cpp b/src/minimap.cpp index 9b17cbc6..8b240b19 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -28,6 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/string.h" #include "mapblock.h" #include +#include "client/renderingengine.h" //// @@ -184,10 +185,10 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height) //// Mapper //// -Minimap::Minimap(IrrlichtDevice *device, Client *client) +Minimap::Minimap(Client *client) { this->client = client; - this->driver = device->getVideoDriver(); + this->driver = RenderingEngine::get_video_driver(); this->m_tsrc = client->getTextureSource(); this->m_shdrsrc = client->getShaderSource(); this->m_ndef = client->getNodeDefManager(); @@ -478,7 +479,7 @@ void Minimap::drawMinimap() return; updateActiveMarkers(); - v2u32 screensize = porting::getWindowSize(); + v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); const u32 size = 0.25 * screensize.Y; core::rect oldViewPort = driver->getViewPort(); diff --git a/src/minimap.h b/src/minimap.h index 04ac27a0..c465abdc 100644 --- a/src/minimap.h +++ b/src/minimap.h @@ -116,7 +116,7 @@ private: class Minimap { public: - Minimap(IrrlichtDevice *device, Client *client); + Minimap(Client *client); ~Minimap(); void addBlock(v3s16 pos, MinimapMapblock *data); diff --git a/src/nodedef.cpp b/src/nodedef.cpp index 1b6c28cf..110393d6 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -21,9 +21,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "itemdef.h" #ifndef SERVER -#include "client/tile.h" #include "mesh.h" #include "client.h" +#include "client/renderingengine.h" +#include "client/tile.h" #include #endif #include "log.h" @@ -1427,8 +1428,8 @@ void CNodeDefManager::updateTextures(IGameDef *gamedef, Client *client = (Client *)gamedef; ITextureSource *tsrc = client->tsrc(); IShaderSource *shdsrc = client->getShaderSource(); - scene::ISceneManager* smgr = client->getSceneManager(); - scene::IMeshManipulator* meshmanip = smgr->getMeshManipulator(); + scene::IMeshManipulator *meshmanip = + RenderingEngine::get_scene_manager()->getMeshManipulator(); TextureSettings tsettings; tsettings.readSettings(); diff --git a/src/particles.cpp b/src/particles.cpp index a02c32f2..10b9811b 100644 --- a/src/particles.cpp +++ b/src/particles.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client.h" #include "collision.h" #include +#include "client/renderingengine.h" #include "util/numeric.h" #include "light.h" #include "environment.h" @@ -42,7 +43,6 @@ v3f random_v3f(v3f min, v3f max) Particle::Particle( IGameDef *gamedef, - scene::ISceneManager* smgr, LocalPlayer *player, ClientEnvironment *env, v3f pos, @@ -60,7 +60,8 @@ Particle::Particle( u8 glow, video::SColor color ): - scene::ISceneNode(smgr->getRootSceneNode(), smgr) + scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), + RenderingEngine::get_scene_manager()) { // Misc m_gamedef = gamedef; @@ -244,7 +245,7 @@ void Particle::updateVertices() ParticleSpawner */ -ParticleSpawner::ParticleSpawner(IGameDef* gamedef, scene::ISceneManager *smgr, LocalPlayer *player, +ParticleSpawner::ParticleSpawner(IGameDef *gamedef, LocalPlayer *player, u16 amount, float time, v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc, float minexptime, float maxexptime, float minsize, float maxsize, @@ -255,7 +256,6 @@ ParticleSpawner::ParticleSpawner(IGameDef* gamedef, scene::ISceneManager *smgr, m_particlemanager(p_manager) { m_gamedef = gamedef; - m_smgr = smgr; m_player = player; m_amount = amount; m_spawntime = time; @@ -344,7 +344,6 @@ void ParticleSpawner::step(float dtime, ClientEnvironment* env) Particle* toadd = new Particle( m_gamedef, - m_smgr, m_player, env, pos, @@ -405,7 +404,6 @@ void ParticleSpawner::step(float dtime, ClientEnvironment* env) Particle* toadd = new Particle( m_gamedef, - m_smgr, m_player, env, pos, @@ -507,7 +505,7 @@ void ParticleManager::clearAll () } void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client, - scene::ISceneManager* smgr, LocalPlayer *player) + LocalPlayer *player) { switch (event->type) { case CE_DELETE_PARTICLESPAWNER: { @@ -533,7 +531,7 @@ void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client, video::ITexture *texture = client->tsrc()->getTextureForMesh(*(event->add_particlespawner.texture)); - ParticleSpawner* toadd = new ParticleSpawner(client, smgr, player, + ParticleSpawner *toadd = new ParticleSpawner(client, player, event->add_particlespawner.amount, event->add_particlespawner.spawntime, *event->add_particlespawner.minpos, @@ -578,7 +576,7 @@ void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client, video::ITexture *texture = client->tsrc()->getTextureForMesh(*(event->spawn_particle.texture)); - Particle* toadd = new Particle(client, smgr, player, m_env, + Particle *toadd = new Particle(client, player, m_env, *event->spawn_particle.pos, *event->spawn_particle.vel, *event->spawn_particle.acc, @@ -607,25 +605,22 @@ void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client, } void ParticleManager::addDiggingParticles(IGameDef* gamedef, - scene::ISceneManager* smgr, LocalPlayer *player, v3s16 pos, - const MapNode &n, const ContentFeatures &f) + LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f) { - for (u16 j = 0; j < 32; j++) // set the amount of particles here - { - addNodeParticle(gamedef, smgr, player, pos, n, f); + // set the amount of particles here + for (u16 j = 0; j < 32; j++) { + addNodeParticle(gamedef, player, pos, n, f); } } void ParticleManager::addPunchingParticles(IGameDef* gamedef, - scene::ISceneManager* smgr, LocalPlayer *player, v3s16 pos, - const MapNode &n, const ContentFeatures &f) + LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f) { - addNodeParticle(gamedef, smgr, player, pos, n, f); + addNodeParticle(gamedef, player, pos, n, f); } void ParticleManager::addNodeParticle(IGameDef* gamedef, - scene::ISceneManager* smgr, LocalPlayer *player, v3s16 pos, - const MapNode &n, const ContentFeatures &f) + LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f) { // Texture u8 texid = myrand_range(0, 5); @@ -667,7 +662,6 @@ void ParticleManager::addNodeParticle(IGameDef* gamedef, Particle* toadd = new Particle( gamedef, - smgr, player, m_env, particlepos, diff --git a/src/particles.h b/src/particles.h index 9b10afe4..13e73e86 100644 --- a/src/particles.h +++ b/src/particles.h @@ -38,7 +38,6 @@ class Particle : public scene::ISceneNode public: Particle( IGameDef* gamedef, - scene::ISceneManager* mgr, LocalPlayer *player, ClientEnvironment *env, v3f pos, @@ -119,7 +118,6 @@ class ParticleSpawner { public: ParticleSpawner(IGameDef* gamedef, - scene::ISceneManager *smgr, LocalPlayer *player, u16 amount, float time, @@ -148,7 +146,6 @@ class ParticleSpawner ParticleManager* m_particlemanager; float m_time; IGameDef *m_gamedef; - scene::ISceneManager *m_smgr; LocalPlayer *m_player; u16 m_amount; float m_spawntime; @@ -185,19 +182,16 @@ public: void step (float dtime); void handleParticleEvent(ClientEvent *event, Client *client, - scene::ISceneManager* smgr, LocalPlayer *player); + LocalPlayer *player); - void addDiggingParticles(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const MapNode &n, - const ContentFeatures &f); + void addDiggingParticles(IGameDef *gamedef, LocalPlayer *player, v3s16 pos, + const MapNode &n, const ContentFeatures &f); - void addPunchingParticles(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const MapNode &n, - const ContentFeatures &f); + void addPunchingParticles(IGameDef *gamedef, LocalPlayer *player, v3s16 pos, + const MapNode &n, const ContentFeatures &f); - void addNodeParticle(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const MapNode &n, - const ContentFeatures &f); + void addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3s16 pos, + const MapNode &n, const ContentFeatures &f); protected: void addParticle(Particle* toadd); diff --git a/src/porting.cpp b/src/porting.cpp index 0cc32393..51b36459 100644 --- a/src/porting.cpp +++ b/src/porting.cpp @@ -41,14 +41,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #define _PSTAT64 #include #endif -#if !defined(_WIN32) && !defined(__APPLE__) && \ - !defined(__ANDROID__) && !defined(SERVER) - #define XORG_USED -#endif -#ifdef XORG_USED - #include - #include -#endif #include "config.h" #include "debug.h" @@ -592,304 +584,6 @@ void initializePaths() #endif // USE_GETTEXT } - - -void setXorgClassHint(const video::SExposedVideoData &video_data, - const std::string &name) -{ -#ifdef XORG_USED - if (video_data.OpenGLLinux.X11Display == NULL) - return; - - XClassHint *classhint = XAllocClassHint(); - classhint->res_name = (char *)name.c_str(); - classhint->res_class = (char *)name.c_str(); - - XSetClassHint((Display *)video_data.OpenGLLinux.X11Display, - video_data.OpenGLLinux.X11Window, classhint); - XFree(classhint); -#endif -} - -bool setWindowIcon(IrrlichtDevice *device) -{ -#if defined(XORG_USED) -# if RUN_IN_PLACE - return setXorgWindowIconFromPath(device, - path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png"); -# else - // We have semi-support for reading in-place data if we are - // compiled with RUN_IN_PLACE. Don't break with this and - // also try the path_share location. - return - setXorgWindowIconFromPath(device, - ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") || - setXorgWindowIconFromPath(device, - path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png"); -# endif -#elif defined(_WIN32) - const video::SExposedVideoData exposedData = device->getVideoDriver()->getExposedVideoData(); - HWND hWnd; // Window handle - - switch (device->getVideoDriver()->getDriverType()) { - case video::EDT_DIRECT3D8: - hWnd = reinterpret_cast(exposedData.D3D8.HWnd); - break; - case video::EDT_DIRECT3D9: - hWnd = reinterpret_cast(exposedData.D3D9.HWnd); - break; - case video::EDT_OPENGL: - hWnd = reinterpret_cast(exposedData.OpenGLWin32.HWnd); - break; - default: - return false; - } - - // Load the ICON from resource file - const HICON hicon = LoadIcon( - GetModuleHandle(NULL), - MAKEINTRESOURCE(130) // The ID of the ICON defined in winresource.rc - ); - - if (hicon) { - SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast(hicon)); - SendMessage(hWnd, WM_SETICON, ICON_SMALL, reinterpret_cast(hicon)); - return true; - } - return false; -#else - return false; -#endif -} - -bool setXorgWindowIconFromPath(IrrlichtDevice *device, - const std::string &icon_file) -{ -#ifdef XORG_USED - - video::IVideoDriver *v_driver = device->getVideoDriver(); - - video::IImageLoader *image_loader = NULL; - u32 cnt = v_driver->getImageLoaderCount(); - for (u32 i = 0; i < cnt; i++) { - if (v_driver->getImageLoader(i)->isALoadableFileExtension(icon_file.c_str())) { - image_loader = v_driver->getImageLoader(i); - break; - } - } - - if (!image_loader) { - warningstream << "Could not find image loader for file '" - << icon_file << "'" << std::endl; - return false; - } - - io::IReadFile *icon_f = device->getFileSystem()->createAndOpenFile(icon_file.c_str()); - - if (!icon_f) { - warningstream << "Could not load icon file '" - << icon_file << "'" << std::endl; - return false; - } - - video::IImage *img = image_loader->loadImage(icon_f); - - if (!img) { - warningstream << "Could not load icon file '" - << icon_file << "'" << std::endl; - icon_f->drop(); - return false; - } - - u32 height = img->getDimension().Height; - u32 width = img->getDimension().Width; - - size_t icon_buffer_len = 2 + height * width; - long *icon_buffer = new long[icon_buffer_len]; - - icon_buffer[0] = width; - icon_buffer[1] = height; - - for (u32 x = 0; x < width; x++) { - for (u32 y = 0; y < height; y++) { - video::SColor col = img->getPixel(x, y); - long pixel_val = 0; - pixel_val |= (u8)col.getAlpha() << 24; - pixel_val |= (u8)col.getRed() << 16; - pixel_val |= (u8)col.getGreen() << 8; - pixel_val |= (u8)col.getBlue(); - icon_buffer[2 + x + y * width] = pixel_val; - } - } - - img->drop(); - icon_f->drop(); - - const video::SExposedVideoData &video_data = v_driver->getExposedVideoData(); - - Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display; - - if (x11_dpl == NULL) { - warningstream << "Could not find x11 display for setting its icon." - << std::endl; - delete [] icon_buffer; - return false; - } - - Window x11_win = (Window)video_data.OpenGLLinux.X11Window; - - Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False); - Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False); - XChangeProperty(x11_dpl, x11_win, - net_wm_icon, cardinal, 32, - PropModeReplace, (const unsigned char *)icon_buffer, - icon_buffer_len); - - delete [] icon_buffer; - -#endif - return true; -} - -//// -//// Video/Display Information (Client-only) -//// - -#ifndef SERVER - -static irr::IrrlichtDevice *device; - -void initIrrlicht(irr::IrrlichtDevice *device_) -{ - device = device_; -} - -v2u32 getWindowSize() -{ - return device->getVideoDriver()->getScreenSize(); -} - - -std::vector > getSupportedVideoModes() -{ - IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); - sanity_check(nulldevice != NULL); - - std::vector > mlist; - video::IVideoModeList *modelist = nulldevice->getVideoModeList(); - - u32 num_modes = modelist->getVideoModeCount(); - for (u32 i = 0; i != num_modes; i++) { - core::dimension2d mode_res = modelist->getVideoModeResolution(i); - s32 mode_depth = modelist->getVideoModeDepth(i); - mlist.push_back(core::vector3d(mode_res.Width, mode_res.Height, mode_depth)); - } - - nulldevice->drop(); - - return mlist; -} - -std::vector getSupportedVideoDrivers() -{ - std::vector drivers; - - for (int i = 0; i != irr::video::EDT_COUNT; i++) { - if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i)) - drivers.push_back((irr::video::E_DRIVER_TYPE)i); - } - - return drivers; -} - -const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type) -{ - static const char *driver_ids[] = { - "null", - "software", - "burningsvideo", - "direct3d8", - "direct3d9", - "opengl", - "ogles1", - "ogles2", - }; - - return driver_ids[type]; -} - - -const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type) -{ - static const char *driver_names[] = { - "NULL Driver", - "Software Renderer", - "Burning's Video", - "Direct3D 8", - "Direct3D 9", - "OpenGL", - "OpenGL ES1", - "OpenGL ES2", - }; - - return driver_names[type]; -} - -# ifndef __ANDROID__ -# ifdef XORG_USED - -static float calcDisplayDensity() -{ - const char *current_display = getenv("DISPLAY"); - - if (current_display != NULL) { - Display *x11display = XOpenDisplay(current_display); - - if (x11display != NULL) { - /* try x direct */ - float dpi_height = floor(DisplayHeight(x11display, 0) / - (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5); - float dpi_width = floor(DisplayWidth(x11display, 0) / - (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5); - - XCloseDisplay(x11display); - - return std::max(dpi_height,dpi_width) / 96.0; - } - } - - /* return manually specified dpi */ - return g_settings->getFloat("screen_dpi")/96.0; -} - - -float getDisplayDensity() -{ - static float cached_display_density = calcDisplayDensity(); - return cached_display_density; -} - - -# else // XORG_USED -float getDisplayDensity() -{ - return g_settings->getFloat("screen_dpi")/96.0; -} -# endif // XORG_USED - -v2u32 getDisplaySize() -{ - IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); - - core::dimension2d deskres = nulldevice->getVideoModeList()->getDesktopResolution(); - nulldevice -> drop(); - - return deskres; -} -# endif // __ANDROID__ -#endif // SERVER - - //// //// OS-specific Secure Random //// diff --git a/src/porting.h b/src/porting.h index 05614543..21655314 100644 --- a/src/porting.h +++ b/src/porting.h @@ -61,7 +61,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Use standard Posix macro for Linux #if (defined(linux) || defined(__linux)) && !defined(__linux__) - #define __linux__ + #define __linux__ #endif #if (defined(__linux__) || defined(__GNU__)) && !defined(_GNU_SOURCE) #define _GNU_SOURCE @@ -178,8 +178,6 @@ void initializePaths(); */ std::string get_sysinfo(); -void initIrrlicht(irr::IrrlichtDevice * ); - // Monotonic counter getters. @@ -281,19 +279,6 @@ inline u64 getDeltaMs(u64 old_time_ms, u64 new_time_ms) } } - -#ifndef SERVER -float getDisplayDensity(); - -v2u32 getDisplaySize(); -v2u32 getWindowSize(); - -std::vector > getSupportedVideoModes(); -std::vector getSupportedVideoDrivers(); -const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type); -const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type); -#endif - inline const char *getPlatformName() { return @@ -338,18 +323,6 @@ inline const char *getPlatformName() ; } -void setXorgClassHint(const video::SExposedVideoData &video_data, - const std::string &name); - -bool setWindowIcon(IrrlichtDevice *device); - -bool setXorgWindowIconFromPath(IrrlichtDevice *device, - const std::string &icon_file); - -// This only needs to be called at the start of execution, since all future -// threads in the process inherit this exception handler -void setWin32ExceptionHandler(); - bool secure_rand_fill_buf(void *buf, size_t len); // This attaches to the parents process console, or creates a new one if it doesnt exist. diff --git a/src/script/lua_api/l_mainmenu.cpp b/src/script/lua_api/l_mainmenu.cpp index 3ed2ba0e..7c86525f 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -33,10 +33,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverlist.h" #include "mapgen.h" #include "settings.h" -#include "EDriverTypes.h" #include #include +#include "client/renderingengine.h" /******************************************************************************/ @@ -628,8 +628,7 @@ int ModApiMainMenu::l_show_keys_menu(lua_State *L) GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - GUIKeyChangeMenu *kmenu - = new GUIKeyChangeMenu( engine->m_device->getGUIEnvironment(), + GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(), engine->m_parent, -1, engine->m_menumanager); @@ -832,9 +831,6 @@ int ModApiMainMenu::l_copy_dir(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_extract_zip(lua_State *L) { - GUIEngine* engine = getGuiEngine(L); - sanity_check(engine); - const char *zipfile = luaL_checkstring(L, 1); const char *destination = luaL_checkstring(L, 2); @@ -843,7 +839,7 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) if (ModApiMainMenu::isMinetestPath(absolute_destination)) { fs::CreateAllDirs(absolute_destination); - io::IFileSystem* fs = engine->m_device->getFileSystem(); + io::IFileSystem *fs = RenderingEngine::get_filesystem(); if (!fs->addFileArchive(zipfile,true,false,io::EFAT_ZIP)) { lua_pushboolean(L,false); @@ -960,7 +956,7 @@ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) bool is_file_select = lua_toboolean(L, 3); GUIFileSelectMenu* fileOpenMenu = - new GUIFileSelectMenu(engine->m_device->getGUIEnvironment(), + new GUIFileSelectMenu(RenderingEngine::get_gui_env(), engine->m_parent, -1, engine->m_menumanager, @@ -997,13 +993,12 @@ int ModApiMainMenu::l_download_file(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_video_drivers(lua_State *L) { - std::vector drivers - = porting::getSupportedVideoDrivers(); + std::vector drivers = RenderingEngine::getSupportedVideoDrivers(); lua_newtable(L); for (u32 i = 0; i != drivers.size(); i++) { - const char *name = porting::getVideoDriverName(drivers[i]); - const char *fname = porting::getVideoDriverFriendlyName(drivers[i]); + const char *name = RenderingEngine::getVideoDriverName(drivers[i]); + const char *fname = RenderingEngine::getVideoDriverFriendlyName(drivers[i]); lua_newtable(L); lua_pushstring(L, name); @@ -1021,7 +1016,7 @@ int ModApiMainMenu::l_get_video_drivers(lua_State *L) int ModApiMainMenu::l_get_video_modes(lua_State *L) { std::vector > videomodes - = porting::getSupportedVideoModes(); + = RenderingEngine::getSupportedVideoModes(); lua_newtable(L); for (u32 i = 0; i != videomodes.size(); i++) { @@ -1054,23 +1049,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,porting::getDisplayDensity()); + lua_pushnumber(L,RenderingEngine::getDisplayDensity()); lua_settable(L, top); lua_pushstring(L,"display_width"); - lua_pushnumber(L,porting::getDisplaySize().X); + lua_pushnumber(L,RenderingEngine::getDisplaySize().X); lua_settable(L, top); lua_pushstring(L,"display_height"); - lua_pushnumber(L,porting::getDisplaySize().Y); + lua_pushnumber(L,RenderingEngine::getDisplaySize().Y); lua_settable(L, top); + const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); lua_pushstring(L,"window_width"); - lua_pushnumber(L,porting::getWindowSize().X); + lua_pushnumber(L, window_size.X); lua_settable(L, top); lua_pushstring(L,"window_height"); - lua_pushnumber(L,porting::getWindowSize().Y); + lua_pushnumber(L, window_size.Y); lua_settable(L, top); return 1; } diff --git a/src/shader.cpp b/src/shader.cpp index 5ff8c910..6e89d75a 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -32,6 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include "client/renderingengine.h" #include "EShaderTypes.h" #include "log.h" #include "gamedef.h" @@ -177,7 +178,7 @@ class ShaderCallback : public video::IShaderConstantSetCallBack std::vector m_setters; public: - ShaderCallback(const std::vector &factories) + ShaderCallback(const std::vector &factories) { for (u32 i = 0; i < factories.size(); ++i) m_setters.push_back(factories[i]->create()); @@ -260,7 +261,7 @@ public: class ShaderSource : public IWritableShaderSource { public: - ShaderSource(IrrlichtDevice *device); + ShaderSource(); ~ShaderSource(); /* @@ -309,8 +310,6 @@ private: // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; - // The irrlicht device - IrrlichtDevice *m_device; // Cache of source shaders // This should be only accessed from the main thread @@ -332,18 +331,17 @@ private: std::vector m_callbacks; }; -IWritableShaderSource* createShaderSource(IrrlichtDevice *device) +IWritableShaderSource *createShaderSource() { - return new ShaderSource(device); + return new ShaderSource(); } /* Generate shader given the shader name. */ ShaderInfo generate_shader(const std::string &name, - u8 material_type, u8 drawtype, - IrrlichtDevice *device, std::vector &callbacks, - const std::vector &setter_factories, + u8 material_type, u8 drawtype, std::vector &callbacks, + const std::vector &setter_factories, SourceShaderCache *sourcecache); /* @@ -354,11 +352,8 @@ void load_shaders(std::string name, SourceShaderCache *sourcecache, std::string &vertex_program, std::string &pixel_program, std::string &geometry_program, bool &is_highlevel); -ShaderSource::ShaderSource(IrrlichtDevice *device): - m_device(device) +ShaderSource::ShaderSource() { - assert(m_device); // Pre-condition - m_main_thread = std::this_thread::get_id(); // Add a dummy ShaderInfo as the first index, named "" @@ -453,7 +448,7 @@ u32 ShaderSource::getShaderIdDirect(const std::string &name, } ShaderInfo info = generate_shader(name, material_type, drawtype, - m_device, m_callbacks, m_setter_factories, &m_sourcecache); + m_callbacks, m_setter_factories, &m_sourcecache); /* Add shader to caches (add dummy shaders too) @@ -518,7 +513,7 @@ void ShaderSource::rebuildShaders() ShaderInfo *info = &m_shaderinfo_cache[i]; if(info->name != ""){ *info = generate_shader(info->name, info->material_type, - info->drawtype, m_device, m_callbacks, + info->drawtype, m_callbacks, m_setter_factories, &m_sourcecache); } } @@ -526,8 +521,8 @@ void ShaderSource::rebuildShaders() ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype, - IrrlichtDevice *device, std::vector &callbacks, - const std::vector &setter_factories, + std::vector &callbacks, + const std::vector &setter_factories, SourceShaderCache *sourcecache) { ShaderInfo shaderinfo; @@ -535,7 +530,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp shaderinfo.material_type = material_type; shaderinfo.drawtype = drawtype; shaderinfo.material = video::EMT_SOLID; - switch(material_type){ + switch (material_type) { case TILE_MATERIAL_BASIC: shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; break; @@ -553,15 +548,16 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp break; case TILE_MATERIAL_WAVING_PLANTS: shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; - break; + break; + default: + break; } bool enable_shaders = g_settings->getBool("enable_shaders"); if (!enable_shaders) return shaderinfo; - video::IVideoDriver* driver = device->getVideoDriver(); - sanity_check(driver); + video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices(); if(!gpu){ diff --git a/src/shader.h b/src/shader.h index 979318c9..1db4cba8 100644 --- a/src/shader.h +++ b/src/shader.h @@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #define SHADER_HEADER #include -#include "irrlichttypes_extrabloated.h" +#include "irrlichttypes_bloated.h" #include class IGameDef; @@ -149,7 +149,7 @@ public: virtual void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) = 0; }; -IWritableShaderSource* createShaderSource(IrrlichtDevice *device); +IWritableShaderSource *createShaderSource(); void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type, const std::string &program); diff --git a/src/sky.cpp b/src/sky.cpp index 3176ea93..46340019 100644 --- a/src/sky.cpp +++ b/src/sky.cpp @@ -8,13 +8,14 @@ #include "profiler.h" #include "util/numeric.h" #include +#include "client/renderingengine.h" #include "settings.h" #include "camera.h" // CameraModes -Sky::Sky(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id, - ITextureSource *tsrc): - scene::ISceneNode(parent, mgr, id) +Sky::Sky(s32 id, ITextureSource *tsrc): + scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), + RenderingEngine::get_scene_manager(), id) { setAutomaticCulling(scene::EAC_OFF); m_box.MaxEdge.set(0, 0, 0); diff --git a/src/sky.h b/src/sky.h index 1fa25bd9..64d2877e 100644 --- a/src/sky.h +++ b/src/sky.h @@ -34,8 +34,7 @@ class Sky : public scene::ISceneNode { public: //! constructor - Sky(scene::ISceneNode *parent, scene::ISceneManager *mgr, s32 id, - ITextureSource *tsrc); + Sky(s32 id, ITextureSource *tsrc); virtual void OnRegisterSceneNode(); diff --git a/util/travis/clang-format-whitelist.txt b/util/travis/clang-format-whitelist.txt index f276af28..23c036cb 100644 --- a/util/travis/clang-format-whitelist.txt +++ b/util/travis/clang-format-whitelist.txt @@ -57,8 +57,6 @@ src/daynightratio.h src/debug.cpp src/debug.h src/defaultsettings.cpp -src/drawscene.cpp -src/drawscene.h src/dungeongen.cpp src/dungeongen.h src/emerge.cpp From 53a6b5439eac140bbbe76441a4d6a02590fadb2f Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Mon, 26 Jun 2017 23:19:47 +0200 Subject: [PATCH 43/53] Fix undefined behaviour in arm movement when dividing by zero --- src/camera.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/camera.cpp b/src/camera.cpp index 83239fe7..855bca3a 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -197,8 +197,15 @@ void Camera::step(f32 dtime) void Camera::addArmInertia(f32 player_yaw, f32 frametime) { - m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw) / m_timer.X) * 0.01f; - m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / m_timer.Y); + if (m_timer.X == 0.0f) + m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw)) * 0.01f; + else + m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw) / m_timer.X) * 0.01f; + + if (m_timer.Y == 0.0f) + m_cam_vel.Y = std::fabs(m_last_cam_pos.Y - m_camera_direction.Y); + else + m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / m_timer.Y); if (m_cam_vel.X > 1.0f || m_cam_vel.Y > 1.0f) { /* @@ -206,8 +213,7 @@ void Camera::addArmInertia(f32 player_yaw, f32 frametime) */ if (m_cam_vel.X > 1.0f) { - m_timer.X = 0.0f; - m_timer.X += frametime; + m_timer.X = frametime; if (m_cam_vel.X > m_cam_vel_old.X) m_cam_vel_old.X = m_cam_vel.X; @@ -226,8 +232,7 @@ void Camera::addArmInertia(f32 player_yaw, f32 frametime) } if (m_cam_vel.Y > 1.0f) { - m_timer.Y = 0.0f; - m_timer.Y += frametime; + m_timer.Y = frametime; if (m_cam_vel.Y > m_cam_vel_old.Y) m_cam_vel_old.Y = m_cam_vel.Y; From 48cd217e3b6f53af32802c1897ddd1914d215078 Mon Sep 17 00:00:00 2001 From: kilbith Date: Tue, 27 Jun 2017 11:26:13 +0200 Subject: [PATCH 44/53] Fix arm inertia limit case --- src/camera.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/camera.cpp b/src/camera.cpp index 855bca3a..2de76da1 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -197,13 +197,17 @@ void Camera::step(f32 dtime) void Camera::addArmInertia(f32 player_yaw, f32 frametime) { - if (m_timer.X == 0.0f) - m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw)) * 0.01f; + if (m_timer.X == 0.0f) { + // In the limit case where timer is 0 set a static velocity (generic case divide by zero) + m_cam_vel.X = 1.0001f; + } else m_cam_vel.X = std::fabs((m_last_cam_pos.X - player_yaw) / m_timer.X) * 0.01f; - if (m_timer.Y == 0.0f) - m_cam_vel.Y = std::fabs(m_last_cam_pos.Y - m_camera_direction.Y); + if (m_timer.Y == 0.0f) { + // In the limit case where timer is 0 set a static velocity (generic case divide by zero) + m_cam_vel.Y = 1.0001f; + } else m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / m_timer.Y); From d7343b6c930d22857f858929ea684acbbeefe482 Mon Sep 17 00:00:00 2001 From: adrido Date: Tue, 27 Jun 2017 11:54:40 +0200 Subject: [PATCH 45/53] Fix msvc annoyances (#5963) * MSVC: Fix '/std:c++11' is not a valid compiler option * MSVC/MINGW: Define 'WIN32_LEAN_AND_MEAN' for the whole project In some obscure cases 'Windows.h" got includet before that definition, which leaded to compilation warnings+errors * MSVC: '/arch:SSE' is only available for x86 * MSVC: Fix float conversation * MSVC/MINGW: use winthreads on Windows * MSVC: 'USE_CMAKE_CONFIG' might be already definied by CMake build system * MSVC: Use all available cpu cores for compiling * Add missing include ctime and use std::time_t --- misc/winresource.rc | 2 ++ src/CMakeLists.txt | 8 ++++++-- src/database-postgresql.cpp | 3 --- src/debug.h | 3 +-- src/mesh_generator_thread.cpp | 2 +- src/mesh_generator_thread.h | 3 ++- src/noise.cpp | 4 ++-- src/socket.cpp | 3 --- src/socket.h | 3 --- src/threading/thread.cpp | 12 ++++++++++-- 10 files changed, 24 insertions(+), 19 deletions(-) diff --git a/misc/winresource.rc b/misc/winresource.rc index 6b82e261..e1e82581 100644 --- a/misc/winresource.rc +++ b/misc/winresource.rc @@ -1,7 +1,9 @@ #include #include #include +#ifndef USE_CMAKE_CONFIG_H #define USE_CMAKE_CONFIG_H +#endif #include "config.h" #undef USE_CMAKE_CONFIG_H diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 04f4635d..e03f3f39 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -703,9 +703,12 @@ include(CheckCXXCompilerFlag) if(MSVC) # Visual Studio - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++11") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D WIN32_LEAN_AND_MEAN /MP") # EHa enables SEH exceptions (used for catching segfaults) - set(CMAKE_CXX_FLAGS_RELEASE "/EHa /Ox /GL /FD /MT /GS- /Zi /arch:SSE /fp:fast /D NDEBUG /D _HAS_ITERATOR_DEBUGGING=0 /TP") + set(CMAKE_CXX_FLAGS_RELEASE "/EHa /Ox /GL /FD /MT /GS- /Zi /fp:fast /D NDEBUG /D _HAS_ITERATOR_DEBUGGING=0 /TP") + if(CMAKE_SIZEOF_VOID_P EQUAL 4) + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /arch:SSE") + endif() #set(CMAKE_EXE_LINKER_FLAGS_RELEASE "/LTCG /NODEFAULTLIB:\"libcmtd.lib\" /NODEFAULTLIB:\"libcmt.lib\"") set(CMAKE_EXE_LINKER_FLAGS_RELEASE "/LTCG /INCREMENTAL:NO /DEBUG /OPT:REF /OPT:ICF") @@ -748,6 +751,7 @@ else() if(MINGW) set(OTHER_FLAGS "${OTHER_FLAGS} -mthreads -fexceptions") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWIN32_LEAN_AND_MEAN") endif() set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG ${RELEASE_WARNING_FLAGS} ${WARNING_FLAGS} ${OTHER_FLAGS} -Wall -pipe -funroll-loops") diff --git a/src/database-postgresql.cpp b/src/database-postgresql.cpp index 3c54f48d..78f59419 100644 --- a/src/database-postgresql.cpp +++ b/src/database-postgresql.cpp @@ -23,9 +23,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database-postgresql.h" #ifdef _WIN32 - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif // Without this some of the network functions are not found on mingw #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 diff --git a/src/debug.h b/src/debug.h index 415797f4..639ba673 100644 --- a/src/debug.h +++ b/src/debug.h @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gettime.h" #include "log.h" -#if (defined(WIN32) || defined(_WIN32_WCE)) - #define WIN32_LEAN_AND_MEAN +#ifdef _WIN32 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif diff --git a/src/mesh_generator_thread.cpp b/src/mesh_generator_thread.cpp index f06bddb5..b69d7f48 100644 --- a/src/mesh_generator_thread.cpp +++ b/src/mesh_generator_thread.cpp @@ -223,7 +223,7 @@ void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q) data->fillBlockDataBegin(q->p); - int t_now = time(0); + std::time_t t_now = std::time(0); // Collect data for 3*3*3 blocks from cache v3s16 dp; diff --git a/src/mesh_generator_thread.h b/src/mesh_generator_thread.h index 77b34a3c..051a0dc8 100644 --- a/src/mesh_generator_thread.h +++ b/src/mesh_generator_thread.h @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef MESH_GENERATOR_THREAD_HEADER #define MESH_GENERATOR_THREAD_HEADER +#include #include #include "mapblock_mesh.h" #include "threading/mutex_auto_lock.h" @@ -30,7 +31,7 @@ struct CachedMapBlockData v3s16 p = v3s16(-1337, -1337, -1337); MapNode *data = nullptr; // A copy of the MapBlock's data member int refcount_from_queue = 0; - int last_used_timestamp = std::time(0); + std::time_t last_used_timestamp = std::time(0); CachedMapBlockData() {} ~CachedMapBlockData(); diff --git a/src/noise.cpp b/src/noise.cpp index e75fb827..f67771b8 100644 --- a/src/noise.cpp +++ b/src/noise.cpp @@ -47,8 +47,8 @@ typedef float (*Interp3dFxn)( float x, float y, float z); float cos_lookup[16] = { - 1.0, 0.9238, 0.7071, 0.3826, 0, -0.3826, -0.7071, -0.9238, - 1.0, -0.9238, -0.7071, -0.3826, 0, 0.3826, 0.7071, 0.9238 + 1.0f, 0.9238f, 0.7071f, 0.3826f, .0f, -0.3826f, -0.7071f, -0.9238f, + 1.0f, -0.9238f, -0.7071f, -0.3826f, .0f, 0.3826f, 0.7071f, 0.9238f }; FlagDesc flagdesc_noiseparams[] = { diff --git a/src/socket.cpp b/src/socket.cpp index d0ab16ca..0bd2702a 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -34,9 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #ifdef _WIN32 - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif // Without this some of the network functions are not found on mingw #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 diff --git a/src/socket.h b/src/socket.h index 77ce3192..b1f1e087 100644 --- a/src/socket.h +++ b/src/socket.h @@ -21,9 +21,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #define SOCKET_HEADER #ifdef _WIN32 - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif diff --git a/src/threading/thread.cpp b/src/threading/thread.cpp index 8f54fb76..09cc7d83 100644 --- a/src/threading/thread.cpp +++ b/src/threading/thread.cpp @@ -261,10 +261,14 @@ bool Thread::bindToProcessor(unsigned int proc_number) return false; -#elif USE_WIN_THREADS +#elif _MSC_VER return SetThreadAffinityMask(getThreadHandle(), 1 << proc_number); +#elif __MINGW32__ + + return SetThreadAffinityMask(pthread_gethandle(getThreadHandle()), 1 << proc_number); + #elif __FreeBSD_version >= 702106 || defined(__linux__) cpu_set_t cpuset; @@ -309,10 +313,14 @@ bool Thread::bindToProcessor(unsigned int proc_number) bool Thread::setPriority(int prio) { -#if USE_WIN_THREADS +#ifdef _MSC_VER return SetThreadPriority(getThreadHandle(), prio); +#elif __MINGW32__ + + return SetThreadPriority(pthread_gethandle(getThreadHandle()), prio); + #else struct sched_param sparam; From 85d7b18d851504e6d9f637c4373cf896b1ce8e4c Mon Sep 17 00:00:00 2001 From: Jesse McDonald Date: Tue, 27 Jun 2017 05:34:11 -0500 Subject: [PATCH 46/53] Fix for empty key/value when reading item string with wear but no metadata (#6058) --- src/itemstackmetadata.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/itemstackmetadata.cpp b/src/itemstackmetadata.cpp index c3d60224..65829fd6 100644 --- a/src/itemstackmetadata.cpp +++ b/src/itemstackmetadata.cpp @@ -28,16 +28,18 @@ void ItemStackMetadata::deSerialize(std::istream &is) m_stringvars.clear(); - if (!in.empty() && in[0] == DESERIALIZE_START) { - Strfnd fnd(in); - 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); - m_stringvars[name] = var; + if (!in.empty()) { + if (in[0] == DESERIALIZE_START) { + Strfnd fnd(in); + 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); + m_stringvars[name] = var; + } + } else { + // BACKWARDS COMPATIBILITY + m_stringvars[""] = in; } - } else { - // BACKWARDS COMPATIBILITY - m_stringvars[""] = in; } } From 6d2833a8879b5dd64936991bf2a3e407f26357a7 Mon Sep 17 00:00:00 2001 From: paramat Date: Wed, 28 Jun 2017 09:35:46 +0100 Subject: [PATCH 47/53] Mgv7: Fix undefined 'float_mount_height' Commit cad10ce3b747b721fd63784915e05f12bc488128 altered the parameter 'float_mount_height' but was missing the necessary line in the constructor to get the altered value from 'params'. Fixes 3D floatland terrain generating everywhere. --- src/mapgen_v7.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index 4b1844a7..e361a8f1 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -68,6 +68,7 @@ MapgenV7::MapgenV7(int mapgenid, MapgenV7Params *params, EmergeManager *emerge) // This is to avoid a divide-by-zero. // Parameter will be saved to map_meta.txt in limited form. params->float_mount_height = MYMAX(params->float_mount_height, 1.0f); + this->float_mount_height = params->float_mount_height; // 2D noise noise_terrain_base = new Noise(¶ms->np_terrain_base, seed, csize.X, csize.Z); From 367d218f2b8c9d5fa754875407bd52c6bff771a7 Mon Sep 17 00:00:00 2001 From: Vincent Glize Date: Thu, 29 Jun 2017 07:53:44 +0200 Subject: [PATCH 48/53] Change the server description after a search (#6074) --- builtin/mainmenu/tab_online.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/builtin/mainmenu/tab_online.lua b/builtin/mainmenu/tab_online.lua index ab23a4b7..90228b11 100644 --- a/builtin/mainmenu/tab_online.lua +++ b/builtin/mainmenu/tab_online.lua @@ -295,6 +295,7 @@ local function main_button_handler(tabview, fields, name, tabdata) local first_server = search_result[1] core.settings:set("address", first_server.address) core.settings:set("remote_port", first_server.port) + gamedata.serverdescription = first_server.description end return true end From 2e53801fc0d9ba13afec6c1ddb5e3999f68b96bd Mon Sep 17 00:00:00 2001 From: Paramat Date: Fri, 30 Jun 2017 14:32:35 +0100 Subject: [PATCH 49/53] Mapgen: Remove unnecessary 'this->' from constructors (#6069) --- src/mapgen_flat.cpp | 18 +++++++++--------- src/mapgen_fractal.cpp | 30 +++++++++++++++--------------- src/mapgen_v5.cpp | 14 +++++++------- src/mapgen_v6.cpp | 12 ++++++------ src/mapgen_v7.cpp | 22 +++++++++++----------- src/mapgen_valleys.cpp | 30 +++++++++++++++--------------- 6 files changed, 63 insertions(+), 63 deletions(-) diff --git a/src/mapgen_flat.cpp b/src/mapgen_flat.cpp index e7f5f4df..95fb3541 100644 --- a/src/mapgen_flat.cpp +++ b/src/mapgen_flat.cpp @@ -51,15 +51,15 @@ FlagDesc flagdesc_mapgen_flat[] = { MapgenFlat::MapgenFlat(int mapgenid, MapgenFlatParams *params, EmergeManager *emerge) : MapgenBasic(mapgenid, params, emerge) { - this->spflags = params->spflags; - this->ground_level = params->ground_level; - this->large_cave_depth = params->large_cave_depth; - this->lava_depth = params->lava_depth; - this->cave_width = params->cave_width; - this->lake_threshold = params->lake_threshold; - this->lake_steepness = params->lake_steepness; - this->hill_threshold = params->hill_threshold; - this->hill_steepness = params->hill_steepness; + spflags = params->spflags; + ground_level = params->ground_level; + large_cave_depth = params->large_cave_depth; + lava_depth = params->lava_depth; + 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; // 2D noise noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); diff --git a/src/mapgen_fractal.cpp b/src/mapgen_fractal.cpp index b43dcd3f..4fe0d836 100644 --- a/src/mapgen_fractal.cpp +++ b/src/mapgen_fractal.cpp @@ -49,19 +49,19 @@ FlagDesc flagdesc_mapgen_fractal[] = { MapgenFractal::MapgenFractal(int mapgenid, MapgenFractalParams *params, EmergeManager *emerge) : MapgenBasic(mapgenid, params, emerge) { - this->spflags = params->spflags; - this->cave_width = params->cave_width; - this->large_cave_depth = params->large_cave_depth; - this->lava_depth = params->lava_depth; - this->fractal = params->fractal; - this->iterations = params->iterations; - this->scale = params->scale; - this->offset = params->offset; - this->slice_w = params->slice_w; - this->julia_x = params->julia_x; - this->julia_y = params->julia_y; - this->julia_z = params->julia_z; - this->julia_w = params->julia_w; + spflags = params->spflags; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; + lava_depth = params->lava_depth; + 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 terrain noise noise_seabed = new Noise(¶ms->np_seabed, seed, csize.X, csize.Z); @@ -70,8 +70,8 @@ MapgenFractal::MapgenFractal(int mapgenid, MapgenFractalParams *params, EmergeMa MapgenBasic::np_cave1 = params->np_cave1; MapgenBasic::np_cave2 = params->np_cave2; - this->formula = fractal / 2 + fractal % 2; - this->julia = fractal % 2 == 0; + formula = fractal / 2 + fractal % 2; + julia = fractal % 2 == 0; } diff --git a/src/mapgen_v5.cpp b/src/mapgen_v5.cpp index 04482670..ffa1f538 100644 --- a/src/mapgen_v5.cpp +++ b/src/mapgen_v5.cpp @@ -48,13 +48,13 @@ FlagDesc flagdesc_mapgen_v5[] = { MapgenV5::MapgenV5(int mapgenid, MapgenV5Params *params, EmergeManager *emerge) : MapgenBasic(mapgenid, params, emerge) { - this->spflags = params->spflags; - this->cave_width = params->cave_width; - this->large_cave_depth = params->large_cave_depth; - this->lava_depth = params->lava_depth; - this->cavern_limit = params->cavern_limit; - this->cavern_taper = params->cavern_taper; - this->cavern_threshold = params->cavern_threshold; + spflags = params->spflags; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; + lava_depth = params->lava_depth; + cavern_limit = params->cavern_limit; + cavern_taper = params->cavern_taper; + cavern_threshold = params->cavern_threshold; // Terrain noise noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); diff --git a/src/mapgen_v6.cpp b/src/mapgen_v6.cpp index f932f45f..ebbd932d 100644 --- a/src/mapgen_v6.cpp +++ b/src/mapgen_v6.cpp @@ -58,14 +58,14 @@ FlagDesc flagdesc_mapgen_v6[] = { MapgenV6::MapgenV6(int mapgenid, MapgenV6Params *params, EmergeManager *emerge) : Mapgen(mapgenid, params, emerge) { - this->m_emerge = emerge; - this->ystride = csize.X; //////fix this + m_emerge = emerge; + ystride = csize.X; //////fix this - this->heightmap = new s16[csize.X * csize.Z]; + heightmap = new s16[csize.X * csize.Z]; - this->spflags = params->spflags; - this->freq_desert = params->freq_desert; - this->freq_beach = params->freq_beach; + spflags = params->spflags; + freq_desert = params->freq_desert; + freq_beach = params->freq_beach; np_cave = ¶ms->np_cave; np_humidity = ¶ms->np_humidity; diff --git a/src/mapgen_v7.cpp b/src/mapgen_v7.cpp index e361a8f1..17f2df83 100644 --- a/src/mapgen_v7.cpp +++ b/src/mapgen_v7.cpp @@ -54,21 +54,21 @@ FlagDesc flagdesc_mapgen_v7[] = { MapgenV7::MapgenV7(int mapgenid, MapgenV7Params *params, EmergeManager *emerge) : MapgenBasic(mapgenid, params, emerge) { - this->spflags = params->spflags; - this->cave_width = params->cave_width; - this->large_cave_depth = params->large_cave_depth; - this->lava_depth = params->lava_depth; - this->float_mount_density = params->float_mount_density; - this->floatland_level = params->floatland_level; - this->shadow_limit = params->shadow_limit; - this->cavern_limit = params->cavern_limit; - this->cavern_taper = params->cavern_taper; - this->cavern_threshold = params->cavern_threshold; + spflags = params->spflags; + cave_width = params->cave_width; + large_cave_depth = params->large_cave_depth; + lava_depth = params->lava_depth; + float_mount_density = params->float_mount_density; + floatland_level = params->floatland_level; + shadow_limit = params->shadow_limit; + cavern_limit = params->cavern_limit; + cavern_taper = params->cavern_taper; + cavern_threshold = params->cavern_threshold; // This is to avoid a divide-by-zero. // Parameter will be saved to map_meta.txt in limited form. params->float_mount_height = MYMAX(params->float_mount_height, 1.0f); - this->float_mount_height = params->float_mount_height; + float_mount_height = params->float_mount_height; // 2D noise noise_terrain_base = new Noise(¶ms->np_terrain_base, seed, csize.X, csize.Z); diff --git a/src/mapgen_valleys.cpp b/src/mapgen_valleys.cpp index cf982206..71c0b001 100644 --- a/src/mapgen_valleys.cpp +++ b/src/mapgen_valleys.cpp @@ -66,19 +66,19 @@ MapgenValleys::MapgenValleys(int mapgenid, MapgenValleysParams *params, EmergeMa : MapgenBasic(mapgenid, params, emerge) { // NOTE: MapgenValleys has a hard dependency on BiomeGenOriginal - this->m_bgen = (BiomeGenOriginal *)biomegen; + m_bgen = (BiomeGenOriginal *)biomegen; BiomeParamsOriginal *bp = (BiomeParamsOriginal *)params->bparams; - this->spflags = params->spflags; - this->altitude_chill = params->altitude_chill; - this->large_cave_depth = params->large_cave_depth; - this->lava_features_lim = rangelim(params->lava_features, 0, 10); - this->massive_cave_depth = params->massive_cave_depth; - this->river_depth_bed = params->river_depth + 1.f; - this->river_size_factor = params->river_size / 100.f; - this->water_features_lim = rangelim(params->water_features, 0, 10); - this->cave_width = params->cave_width; + spflags = params->spflags; + altitude_chill = params->altitude_chill; + large_cave_depth = params->large_cave_depth; + lava_features_lim = rangelim(params->lava_features, 0, 10); + massive_cave_depth = params->massive_cave_depth; + river_depth_bed = params->river_depth + 1.f; + river_size_factor = params->river_size / 100.f; + water_features_lim = rangelim(params->water_features, 0, 10); + cave_width = params->cave_width; //// 2D Terrain noise noise_filler_depth = new Noise(¶ms->np_filler_depth, seed, csize.X, csize.Z); @@ -96,13 +96,13 @@ MapgenValleys::MapgenValleys(int mapgenid, MapgenValleysParams *params, EmergeMa noise_cave2 = new Noise(¶ms->np_cave2, seed, csize.X, csize.Y + 1, csize.Z); noise_massive_caves = new Noise(¶ms->np_massive_caves, seed, csize.X, csize.Y + 1, csize.Z); - this->humid_rivers = (spflags & MGVALLEYS_HUMID_RIVERS); - this->use_altitude_chill = (spflags & MGVALLEYS_ALT_CHILL); - this->humidity_adjust = bp->np_humidity.offset - 50.f; + humid_rivers = (spflags & MGVALLEYS_HUMID_RIVERS); + use_altitude_chill = (spflags & MGVALLEYS_ALT_CHILL); + humidity_adjust = bp->np_humidity.offset - 50.f; // a small chance of overflows if the settings are very high - this->cave_water_max_height = water_level + MYMAX(0, water_features_lim - 4) * 50; - this->lava_max_height = water_level + MYMAX(0, lava_features_lim - 4) * 50; + cave_water_max_height = water_level + MYMAX(0, water_features_lim - 4) * 50; + lava_max_height = water_level + MYMAX(0, lava_features_lim - 4) * 50; tcave_cache = new float[csize.Y + 2]; } From f3ad75691aea30d2d68aab19fbfa9031409c39d7 Mon Sep 17 00:00:00 2001 From: red-001 Date: Fri, 30 Jun 2017 19:14:39 +0100 Subject: [PATCH 50/53] Create a filesystem abstraction layer for CSM and only allow accessing files that are scanned into it. (#5965) * Load client-side mods into memory before executing them. This removes the remaining filesystem access that client-sided mods had and it will hopefully make then more secure. * Lua Virtual filesystem: don't load the files into memory just scan the filenames into memory. * Fix the issues with backtrace * fix most of the issues * fix code style. * add a comment --- builtin/client/init.lua | 2 +- builtin/game/init.lua | 2 +- builtin/init.lua | 2 +- builtin/mainmenu/dlg_settings_advanced.lua | 4 +- builtin/mainmenu/init.lua | 12 +-- builtin/profiler/init.lua | 2 +- clientmods/preview/example.lua | 2 + clientmods/preview/examples/first.lua | 1 + clientmods/preview/init.lua | 1 + src/client.cpp | 67 ++++++++++---- src/client.h | 16 ++++ src/game.cpp | 1 + src/script/common/c_internal.cpp | 34 +------ src/script/common/c_internal.h | 4 +- src/script/cpp_api/s_base.cpp | 35 ++++++- src/script/cpp_api/s_base.h | 13 +++ src/script/cpp_api/s_security.cpp | 103 ++++++++++++++------- src/script/cpp_api/s_security.h | 8 +- src/script/lua_api/l_client.cpp | 9 ++ src/script/lua_api/l_client.h | 3 + src/script/lua_api/l_util.cpp | 4 +- src/script/scripting_client.cpp | 4 + src/script/scripting_mainmenu.cpp | 1 + src/script/scripting_server.cpp | 1 + 24 files changed, 230 insertions(+), 101 deletions(-) create mode 100644 clientmods/preview/example.lua create mode 100644 clientmods/preview/examples/first.lua diff --git a/builtin/client/init.lua b/builtin/client/init.lua index 3ac34d84..22256f6f 100644 --- a/builtin/client/init.lua +++ b/builtin/client/init.lua @@ -1,5 +1,5 @@ -- Minetest: builtin/client/init.lua -local scriptpath = core.get_builtin_path()..DIR_DELIM +local scriptpath = core.get_builtin_path() local clientpath = scriptpath.."client"..DIR_DELIM local commonpath = scriptpath.."common"..DIR_DELIM diff --git a/builtin/game/init.lua b/builtin/game/init.lua index e2635f07..ab1503de 100644 --- a/builtin/game/init.lua +++ b/builtin/game/init.lua @@ -1,5 +1,5 @@ -local scriptpath = core.get_builtin_path()..DIR_DELIM +local scriptpath = core.get_builtin_path() local commonpath = scriptpath.."common"..DIR_DELIM local gamepath = scriptpath.."game"..DIR_DELIM diff --git a/builtin/init.lua b/builtin/init.lua index 356e119f..e94f3213 100644 --- a/builtin/init.lua +++ b/builtin/init.lua @@ -25,7 +25,7 @@ os.setlocale("C", "numeric") minetest = core -- Load other files -local scriptdir = core.get_builtin_path() .. DIR_DELIM +local scriptdir = core.get_builtin_path() local gamepath = scriptdir .. "game" .. DIR_DELIM local clientpath = scriptdir .. "client" .. DIR_DELIM local commonpath = scriptdir .. "common" .. DIR_DELIM diff --git a/builtin/mainmenu/dlg_settings_advanced.lua b/builtin/mainmenu/dlg_settings_advanced.lua index cac9f698..90b8d1e6 100644 --- a/builtin/mainmenu/dlg_settings_advanced.lua +++ b/builtin/mainmenu/dlg_settings_advanced.lua @@ -264,7 +264,7 @@ end -- read_all: whether to ignore certain setting types for GUI or not -- parse_mods: whether to parse settingtypes.txt in mods and games local function parse_config_file(read_all, parse_mods) - local builtin_path = core.get_builtin_path() .. DIR_DELIM .. FILENAME + local builtin_path = core.get_builtin_path() .. FILENAME local file = io.open(builtin_path, "r") local settings = {} if not file then @@ -775,4 +775,4 @@ end -- Generate minetest.conf.example and settings_translation_file.cpp ---assert(loadfile(core.get_builtin_path()..DIR_DELIM.."mainmenu"..DIR_DELIM.."generate_from_settingtypes.lua"))(parse_config_file(true, false)) +--assert(loadfile(core.get_builtin_path().."mainmenu"..DIR_DELIM.."generate_from_settingtypes.lua"))(parse_config_file(true, false)) diff --git a/builtin/mainmenu/init.lua b/builtin/mainmenu/init.lua index 7c6af7d2..da4c3cce 100644 --- a/builtin/mainmenu/init.lua +++ b/builtin/mainmenu/init.lua @@ -27,12 +27,12 @@ local basepath = core.get_builtin_path() defaulttexturedir = core.get_texturepath_share() .. DIR_DELIM .. "base" .. DIR_DELIM .. "pack" .. DIR_DELIM -dofile(basepath .. DIR_DELIM .. "common" .. DIR_DELIM .. "async_event.lua") -dofile(basepath .. DIR_DELIM .. "common" .. DIR_DELIM .. "filterlist.lua") -dofile(basepath .. DIR_DELIM .. "fstk" .. DIR_DELIM .. "buttonbar.lua") -dofile(basepath .. DIR_DELIM .. "fstk" .. DIR_DELIM .. "dialog.lua") -dofile(basepath .. DIR_DELIM .. "fstk" .. DIR_DELIM .. "tabview.lua") -dofile(basepath .. DIR_DELIM .. "fstk" .. DIR_DELIM .. "ui.lua") +dofile(basepath .. "common" .. DIR_DELIM .. "async_event.lua") +dofile(basepath .. "common" .. DIR_DELIM .. "filterlist.lua") +dofile(basepath .. "fstk" .. DIR_DELIM .. "buttonbar.lua") +dofile(basepath .. "fstk" .. DIR_DELIM .. "dialog.lua") +dofile(basepath .. "fstk" .. DIR_DELIM .. "tabview.lua") +dofile(basepath .. "fstk" .. DIR_DELIM .. "ui.lua") dofile(menupath .. DIR_DELIM .. "common.lua") dofile(menupath .. DIR_DELIM .. "gamemgr.lua") dofile(menupath .. DIR_DELIM .. "modmgr.lua") diff --git a/builtin/profiler/init.lua b/builtin/profiler/init.lua index 87495036..a0033d75 100644 --- a/builtin/profiler/init.lua +++ b/builtin/profiler/init.lua @@ -23,7 +23,7 @@ local function get_bool_default(name, default) return val end -local profiler_path = core.get_builtin_path()..DIR_DELIM.."profiler"..DIR_DELIM +local profiler_path = core.get_builtin_path().."profiler"..DIR_DELIM local profiler = {} local sampler = assert(loadfile(profiler_path .. "sampling.lua"))(profiler) local instrumentation = assert(loadfile(profiler_path .. "instrumentation.lua"))(profiler, sampler, get_bool_default) diff --git a/clientmods/preview/example.lua b/clientmods/preview/example.lua new file mode 100644 index 00000000..2f661c07 --- /dev/null +++ b/clientmods/preview/example.lua @@ -0,0 +1,2 @@ +print("Loaded example file!, loading more examples") +dofile("preview:examples/first.lua") diff --git a/clientmods/preview/examples/first.lua b/clientmods/preview/examples/first.lua new file mode 100644 index 00000000..c24f461e --- /dev/null +++ b/clientmods/preview/examples/first.lua @@ -0,0 +1 @@ +print("loaded first.lua example file") diff --git a/clientmods/preview/init.lua b/clientmods/preview/init.lua index 809e4f01..150db181 100644 --- a/clientmods/preview/init.lua +++ b/clientmods/preview/init.lua @@ -1,6 +1,7 @@ local modname = core.get_current_modname() or "??" local modstorage = core.get_mod_storage() +dofile("preview:example.lua") -- This is an example function to ensure it's working properly, should be removed before merge core.register_on_shutdown(function() print("[PREVIEW] shutdown client") diff --git a/src/client.cpp b/src/client.cpp index 5681c3dd..0f689a71 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -104,17 +104,17 @@ Client::Client( m_script->setEnv(&m_env); } -void Client::initMods() +void Client::loadMods() { - m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME); + // Load builtin + scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath()); // If modding is not enabled, don't load mods, just builtin if (!m_modding_enabled) { return; } - ClientModConfiguration modconf(getClientModsLuaPath()); - std::vector mods = modconf.getMods(); + m_mods = modconf.getMods(); std::vector unsatisfied_mods = modconf.getUnsatisfiedMods(); // complain about mods with unsatisfied dependencies if (!modconf.isConsistent()) { @@ -123,28 +123,52 @@ void Client::initMods() // Print mods infostream << "Client Loading mods: "; - for (std::vector::const_iterator i = mods.begin(); - i != mods.end(); ++i) { - infostream << (*i).name << " "; - } - + for (const ModSpec &mod : m_mods) + infostream << mod.name << " "; infostream << std::endl; + // Load and run "mod" scripts - for (std::vector::const_iterator it = mods.begin(); - it != mods.end(); ++it) { - const ModSpec &mod = *it; + 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: " "Only characters [a-z0-9_] are allowed."); } - std::string script_path = mod.path + DIR_DELIM + "init.lua"; - infostream << " [" << padStringRight(mod.name, 12) << "] [\"" - << script_path << "\"]" << std::endl; - m_script->loadMod(script_path, mod.name); + scanModIntoMemory(mod.name, mod.path); } } +void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path, + std::string mod_subpath) +{ + std::string full_path = mod_path + DIR_DELIM + mod_subpath; + std::vector mod = fs::GetDirListing(full_path); + for (unsigned int j=0; j < mod.size(); j++){ + std::string filename = mod[j].name; + if (mod[j].dir) { + scanModSubfolder(mod_name, mod_path, mod_subpath + + filename + DIR_DELIM); + continue; + } + std::replace( mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/'); + m_mod_files[mod_name + ":" + mod_subpath + filename] = full_path + filename; + } +} + +void Client::initMods() +{ + m_script->loadModFromMemory(BUILTIN_MOD_NAME); + + // If modding is not enabled, don't load mods, just builtin + if (!m_modding_enabled) { + return; + } + + // Load and run "mod" scripts + for (const ModSpec &mod : m_mods) + m_script->loadModFromMemory(mod.name); +} + const std::string &Client::getBuiltinLuaPath() { static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin"; @@ -1898,6 +1922,17 @@ scene::IAnimatedMesh* Client::getMesh(const std::string &filename) return mesh; } +const std::string* Client::getModFile(const std::string &filename) +{ + StringMap::const_iterator it = m_mod_files.find(filename); + if (it == m_mod_files.end()) { + errorstream << "Client::getModFile(): File not found: \"" << filename + << "\"" << std::endl; + return NULL; + } + return &it->second; +} + bool Client::registerModStorage(ModMetadata *storage) { if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) { diff --git a/src/client.h b/src/client.h index ab9801d6..0255b280 100644 --- a/src/client.h +++ b/src/client.h @@ -37,6 +37,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapnode.h" #include "tileanimation.h" #include "mesh_generator_thread.h" +#include +#include "filesys.h" #define CLIENT_CHAT_MESSAGE_LIMIT_PER_10S 10.0f @@ -273,6 +275,16 @@ public: ~Client(); DISABLE_CLASS_COPY(Client); + // Load local mods into memory + void loadMods(); + 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) + { + scanModSubfolder(mod_name, mod_path, ""); + } + + // Initizle the mods void initMods(); /* @@ -492,6 +504,7 @@ public: bool checkLocalPrivilege(const std::string &priv) { return checkPrivilege(priv); } virtual scene::IAnimatedMesh* getMesh(const std::string &filename); + const std::string* getModFile(const std::string &filename); virtual std::string getModStoragePath() const; virtual bool registerModStorage(ModMetadata *meta); @@ -672,6 +685,8 @@ private: // Storage for mesh data for creating multiple instances of the same mesh StringMap m_mesh_data; + StringMap m_mod_files; + // own state LocalClientState m_state; @@ -684,6 +699,7 @@ private: bool m_modding_enabled; std::unordered_map m_mod_storages; float m_mod_storage_save_timer = 10.0f; + std::vector m_mods; GameUIFlags *m_game_ui_flags; bool m_shutdown = false; diff --git a/src/game.cpp b/src/game.cpp index 4c903cc7..841b2d7e 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -2121,6 +2121,7 @@ bool Game::connectToServer(const std::string &playername, fps_control.last_time = RenderingEngine::get_timer_time(); + client->loadMods(); client->initMods(); while (RenderingEngine::run()) { diff --git a/src/script/common/c_internal.cpp b/src/script/common/c_internal.cpp index b349f9dd..0b388e38 100644 --- a/src/script/common/c_internal.cpp +++ b/src/script/common/c_internal.cpp @@ -24,37 +24,9 @@ with this program; if not, write to the Free Software Foundation, Inc., std::string script_get_backtrace(lua_State *L) { - std::string s; - lua_getglobal(L, "debug"); - if(lua_istable(L, -1)){ - lua_getfield(L, -1, "traceback"); - if(lua_isfunction(L, -1)) { - lua_call(L, 0, 1); - if(lua_isstring(L, -1)){ - s = lua_tostring(L, -1); - } - } - lua_pop(L, 1); - } - lua_pop(L, 1); - return s; -} - -int script_error_handler(lua_State *L) { - lua_getglobal(L, "debug"); - if (!lua_istable(L, -1)) { - lua_pop(L, 1); - return 1; - } - lua_getfield(L, -1, "traceback"); - if (!lua_isfunction(L, -1)) { - lua_pop(L, 2); - return 1; - } - lua_pushvalue(L, 1); - lua_pushinteger(L, 2); - lua_call(L, 2, 1); - return 1; + lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE); + lua_call(L, 0, 1); + return luaL_checkstring(L, -1); } int script_exception_wrapper(lua_State *L, lua_CFunction f) diff --git a/src/script/common/c_internal.h b/src/script/common/c_internal.h index fc59b0e2..b77f0a7c 100644 --- a/src/script/common/c_internal.h +++ b/src/script/common/c_internal.h @@ -53,11 +53,11 @@ extern "C" { #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_ERROR_HANDLER (CUSTOM_RIDX_BASE + 3) +#define CUSTOM_RIDX_BACKTRACE (CUSTOM_RIDX_BASE + 3) // Pushes the error handler onto the stack and returns its index #define PUSH_ERROR_HANDLER(L) \ - (lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER), lua_gettop((L))) + (lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L))) #define PCALL_RESL(L, RES) do { \ int result_ = (RES); \ diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index aaf26a9c..6bea8230 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -89,8 +89,10 @@ ScriptApiBase::ScriptApiBase() lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); // Add and save an error handler - lua_pushcfunction(m_luastack, script_error_handler); - lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER); + lua_getglobal(m_luastack, "debug"); + lua_getfield(m_luastack, -1, "traceback"); + lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE); + lua_pop(m_luastack, 1); // pop debug // If we are using LuaJIT add a C++ wrapper function to catch // exceptions thrown in Lua -> C++ calls @@ -158,6 +160,35 @@ void ScriptApiBase::loadScript(const std::string &script_path) lua_pop(L, 1); // Pop error handler } +#ifndef SERVER +void ScriptApiBase::loadModFromMemory(const std::string &mod_name) +{ + ModNameStorer mod_name_storer(getStack(), mod_name); + + const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua"); + const std::string display_filename = mod_name + ":init.lua"; + if(init_filename == NULL) + throw ModError("Mod:\"" + mod_name + "\" lacks init.lua"); + + verbosestream << "Loading and running script " << display_filename << std::endl; + + lua_State *L = getStack(); + + int error_handler = PUSH_ERROR_HANDLER(L); + + bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str()); + if (ok) + ok = !lua_pcall(L, 0, 0, error_handler); + if (!ok) { + std::string error_msg = luaL_checkstring(L, -1); + lua_pop(L, 2); // Pop error message and error handler + throw ModError("Failed to load and run mod \"" + + mod_name + "\":\n" + error_msg); + } + lua_pop(L, 1); // Pop error handler +} +#endif + // Push the list of callbacks (a lua table). // Then push nargs arguments. // Then call this function, which diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index 38ee9901..28fefdd3 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -54,6 +54,12 @@ extern "C" { #define setOriginFromTable(index) \ setOriginFromTableRaw(index, __FUNCTION__) +enum class ScriptingType: u8 { + Client, + Server, + MainMenu +}; + class Server; #ifndef SERVER class Client; @@ -73,6 +79,10 @@ public: void loadMod(const std::string &script_path, const std::string &mod_name); void loadScript(const std::string &script_path); +#ifndef SERVER + void loadModFromMemory(const std::string &mod_name); +#endif + void runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn); @@ -82,6 +92,8 @@ public: IGameDef *getGameDef() { return m_gamedef; } Server* getServer(); + void setType(ScriptingType type) { m_type = type; } + ScriptingType getType() { return m_type; } #ifndef SERVER Client* getClient(); #endif @@ -133,6 +145,7 @@ private: IGameDef *m_gamedef = nullptr; Environment *m_environment = nullptr; GUIEngine *m_guiengine = nullptr; + ScriptingType m_type; }; #endif /* S_BASE_H_ */ diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index 5ad7947d..76159770 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "filesys.h" #include "porting.h" #include "server.h" +#include "client.h" #include "settings.h" #include @@ -140,8 +141,18 @@ void ScriptApiSecurity::initializeSecurity() lua_State *L = getStack(); + // Backup globals to the registry + lua_getglobal(L, "_G"); + lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); - int old_globals = backupGlobals(L); + // Replace the global environment with an empty one + int thread = getThread(L); + createEmptyEnv(L); + setLuaEnv(L, thread); + + // Get old globals + lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); + int old_globals = lua_gettop(L); // Copy safe base functions @@ -274,80 +285,83 @@ void ScriptApiSecurity::initializeSecurityClient() m_secure = true; lua_State *L = getStack(); + int thread = getThread(L); - - int old_globals = backupGlobals(L); - + // create an empty environment + createEmptyEnv(L); // Copy safe base functions lua_getglobal(L, "_G"); + lua_getfield(L, -2, "_G"); copy_safe(L, whitelist, sizeof(whitelist)); // And replace unsafe ones SECURE_API(g, dofile); + SECURE_API(g, load); + SECURE_API(g, loadfile); SECURE_API(g, loadstring); SECURE_API(g, require); - lua_pop(L, 1); + lua_pop(L, 2); // Copy safe OS functions - lua_getfield(L, old_globals, "os"); + lua_getglobal(L, "os"); lua_newtable(L); copy_safe(L, os_whitelist, sizeof(os_whitelist)); - lua_setglobal(L, "os"); + lua_setfield(L, -3, "os"); lua_pop(L, 1); // Pop old OS // Copy safe debug functions - lua_getfield(L, old_globals, "debug"); + lua_getglobal(L, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); - lua_setglobal(L, "debug"); + lua_setfield(L, -3, "debug"); lua_pop(L, 1); // Pop old debug #if USE_LUAJIT // Copy safe jit functions, if they exist - lua_getfield(L, -1, "jit"); - if (!lua_isnil(L, -1)) { - lua_newtable(L); - copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); - lua_setglobal(L, "jit"); - } + lua_getglobal(L, "jit"); + lua_newtable(L); + copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); + lua_setfield(L, -3, "jit"); lua_pop(L, 1); // Pop old jit #endif - lua_pop(L, 1); // Pop globals_backup + // Set the environment to the one we created earlier + setLuaEnv(L, thread); } -int ScriptApiSecurity::backupGlobals(lua_State *L) +int ScriptApiSecurity::getThread(lua_State *L) { - // Backup globals to the registry - lua_getglobal(L, "_G"); - lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); - - // Replace the global environment with an empty one #if LUA_VERSION_NUM <= 501 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!"); + return lua_gettop(L); #endif + return 0; +} + +void ScriptApiSecurity::createEmptyEnv(lua_State *L) +{ lua_newtable(L); // Create new environment lua_pushvalue(L, -1); - lua_setfield(L, -2, "_G"); // Set _G of new environment + 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 // Set the global environment lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); #else // Lua <= 5.1 // Set the environment of the main thread - FATAL_ERROR_IF(!lua_setfenv(L, -2), "Security: Unable to set " + FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set " "environment of the main Lua thread!"); lua_pop(L, 1); // Pop thread #endif - - // Get old globals - lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); - return lua_gettop(L); } bool ScriptApiSecurity::isSecure(lua_State *L) @@ -367,11 +381,13 @@ bool ScriptApiSecurity::isSecure(lua_State *L) } -bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path) +bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name) { FILE *fp; char *chunk_name; - if (path == NULL) { + if (!display_name) + display_name = path; + if (!path) { fp = stdin; chunk_name = const_cast("=stdin"); } else { @@ -380,10 +396,10 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path) lua_pushfstring(L, "%s: %s", path, strerror(errno)); return false; } - chunk_name = new char[strlen(path) + 2]; + chunk_name = new char[strlen(display_name) + 2]; chunk_name[0] = '@'; chunk_name[1] = '\0'; - strcat(chunk_name, path); + strcat(chunk_name, display_name); } size_t start = 0; @@ -626,8 +642,29 @@ int ScriptApiSecurity::sl_g_load(lua_State *L) int ScriptApiSecurity::sl_g_loadfile(lua_State *L) { - const char *path = NULL; +#ifndef SERVER + lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); + ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1); + lua_pop(L, 1); + if (script->getType() == ScriptingType::Client) { + std:: string display_path = lua_tostring(L, 1); + const std::string *path = script->getClient()->getModFile(display_path); + if (!path) { + std::string error_msg = "Coudln't find script called:" + display_path; + lua_pushnil(L); + lua_pushstring(L, error_msg.c_str()); + return 2; + } + if (!safeLoadFile(L, path->c_str(), display_path.c_str())) { + lua_pushnil(L); + lua_insert(L, -2); + return 2; + } + return 1; + } +#endif + const char *path = NULL; if (lua_isstring(L, 1)) { path = lua_tostring(L, 1); CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL); diff --git a/src/script/cpp_api/s_security.h b/src/script/cpp_api/s_security.h index f0eef00b..059dccef 100644 --- a/src/script/cpp_api/s_security.h +++ b/src/script/cpp_api/s_security.h @@ -41,14 +41,18 @@ with this program; if not, write to the Free Software Foundation, Inc., class ScriptApiSecurity : virtual public ScriptApiBase { public: - int backupGlobals(lua_State *L); + int getThread(lua_State *L); + // creates an empty Lua environment + void createEmptyEnv(lua_State *L); + // sets the enviroment to the table thats on top of the stack + void setLuaEnv(lua_State *L, int thread); // Sets up security on the ScriptApi's Lua state void initializeSecurity(); void initializeSecurityClient(); // Checks if the Lua state has been secured static bool isSecure(lua_State *L); // Loads a file as Lua code safely (doesn't allow bytecode). - static bool safeLoadFile(lua_State *L, const char *path); + 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); diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index 84eafd3f..1077d5f2 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -341,6 +341,14 @@ int ModApiClient::l_get_privilege_list(lua_State *L) } return 1; } + +// get_builtin_path() +int ModApiClient::l_get_builtin_path(lua_State *L) +{ + lua_pushstring(L, BUILTIN_MOD_NAME ":"); + return 1; +} + void ModApiClient::Initialize(lua_State *L, int top) { API_FCT(get_current_modname); @@ -366,4 +374,5 @@ void ModApiClient::Initialize(lua_State *L, int top) API_FCT(get_node_def); API_FCT(take_screenshot); API_FCT(get_privilege_list); + API_FCT(get_builtin_path); } diff --git a/src/script/lua_api/l_client.h b/src/script/lua_api/l_client.h index 2f0c2e3f..7472915f 100644 --- a/src/script/lua_api/l_client.h +++ b/src/script/lua_api/l_client.h @@ -95,6 +95,9 @@ private: // get_privilege_list() static int l_get_privilege_list(lua_State *L); + // get_builtin_path() + static int l_get_builtin_path(lua_State *L); + public: static void Initialize(lua_State *L, int top); }; diff --git a/src/script/lua_api/l_util.cpp b/src/script/lua_api/l_util.cpp index 3cf19f02..c68f64a6 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -246,7 +246,7 @@ int ModApiUtil::l_get_builtin_path(lua_State *L) { NO_MAP_LOCK_REQUIRED; - std::string path = porting::path_share + DIR_DELIM + "builtin"; + std::string path = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM; lua_pushstring(L, path.c_str()); return 1; @@ -470,8 +470,6 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(is_yes); - API_FCT(get_builtin_path); - API_FCT(compress); API_FCT(decompress); diff --git a/src/script/scripting_client.cpp b/src/script/scripting_client.cpp index da289e56..904f735f 100644 --- a/src/script/scripting_client.cpp +++ b/src/script/scripting_client.cpp @@ -36,6 +36,7 @@ ClientScripting::ClientScripting(Client *client): ScriptApiBase() { setGameDef(client); + setType(ScriptingType::Client); SCRIPTAPI_PRECHECKHEADER @@ -58,6 +59,9 @@ ClientScripting::ClientScripting(Client *client): lua_pushstring(L, "client"); lua_setglobal(L, "INIT"); + lua_pushstring(L, "/"); + lua_setglobal(L, "DIR_DELIM"); + infostream << "SCRIPTAPI: Initialized client game modules" << std::endl; } diff --git a/src/script/scripting_mainmenu.cpp b/src/script/scripting_mainmenu.cpp index 48957b47..e2f73592 100644 --- a/src/script/scripting_mainmenu.cpp +++ b/src/script/scripting_mainmenu.cpp @@ -36,6 +36,7 @@ extern "C" { MainMenuScripting::MainMenuScripting(GUIEngine* guiengine) { setGuiEngine(guiengine); + setType(ScriptingType::MainMenu); SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/scripting_server.cpp b/src/script/scripting_server.cpp index cd01b077..51e13f04 100644 --- a/src/script/scripting_server.cpp +++ b/src/script/scripting_server.cpp @@ -50,6 +50,7 @@ extern "C" { ServerScripting::ServerScripting(Server* server) { setGameDef(server); + setType(ScriptingType::Server); // setEnv(env) is called by ScriptApiEnv::initializeEnvironment() // once the environment has been created From 6e5588c8e1a6cf79005b5e95c75cbfacf7c75589 Mon Sep 17 00:00:00 2001 From: stujones11 Date: Wed, 7 Jun 2017 18:52:38 +0100 Subject: [PATCH 51/53] Tile material: Add 'TILE_MATERIAL_OPAQUE', use for drawtype 'NDT_NORMAL' Prevents normal drawtype nodes having transparency. Avoids clients cheating by using 'x-ray' texture packs with transparent textures. --- src/client/tile.h | 10 ++++++---- src/nodedef.cpp | 16 ++++++++++++++-- src/shader.cpp | 36 +++++++++++++++--------------------- 3 files changed, 35 insertions(+), 27 deletions(-) diff --git a/src/client/tile.h b/src/client/tile.h index b4d61542..fb1c8737 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -156,7 +156,8 @@ enum MaterialType{ TILE_MATERIAL_LIQUID_TRANSPARENT, TILE_MATERIAL_LIQUID_OPAQUE, TILE_MATERIAL_WAVING_LEAVES, - TILE_MATERIAL_WAVING_PLANTS + TILE_MATERIAL_WAVING_PLANTS, + TILE_MATERIAL_OPAQUE }; // Material flags @@ -216,6 +217,10 @@ struct TileLayer void applyMaterialOptions(video::SMaterial &material) const { switch (material_type) { + case TILE_MATERIAL_OPAQUE: + case TILE_MATERIAL_LIQUID_OPAQUE: + material.MaterialType = video::EMT_SOLID; + break; case TILE_MATERIAL_BASIC: case TILE_MATERIAL_WAVING_LEAVES: case TILE_MATERIAL_WAVING_PLANTS: @@ -225,9 +230,6 @@ struct TileLayer case TILE_MATERIAL_LIQUID_TRANSPARENT: material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; - case TILE_MATERIAL_LIQUID_OPAQUE: - material.MaterialType = video::EMT_SOLID; - break; } material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) ? true : false; diff --git a/src/nodedef.cpp b/src/nodedef.cpp index 110393d6..6ccbc155 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -690,6 +690,8 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc switch (drawtype) { default: case NDT_NORMAL: + material_type = (alpha == 255) ? + TILE_MATERIAL_OPAQUE : TILE_MATERIAL_ALPHA; solidness = 2; break; case NDT_AIRLIKE: @@ -786,6 +788,16 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc tile_shader[j] = shdsrc->getShader("nodes_shader", material_type, drawtype); } + u8 overlay_material = material_type; + if (overlay_material == TILE_MATERIAL_OPAQUE) + overlay_material = TILE_MATERIAL_BASIC; + else if (overlay_material == TILE_MATERIAL_LIQUID_OPAQUE) + overlay_material = TILE_MATERIAL_LIQUID_TRANSPARENT; + u32 overlay_shader[6]; + for (u16 j = 0; j < 6; j++) { + overlay_shader[j] = shdsrc->getShader("nodes_shader", + overlay_material, drawtype); + } // Tiles (fill in f->tiles[]) for (u16 j = 0; j < 6; j++) { @@ -794,8 +806,8 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc tdef[j].backface_culling, material_type); if (tdef_overlay[j].name != "") fillTileAttribs(tsrc, &tiles[j].layers[1], &tdef_overlay[j], - tile_shader[j], tsettings.use_normal_texture, - tdef[j].backface_culling, material_type); + overlay_shader[j], tsettings.use_normal_texture, + tdef[j].backface_culling, overlay_material); } // Special tiles (fill in f->special_tiles[]) diff --git a/src/shader.cpp b/src/shader.cpp index 6e89d75a..4f482fdd 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -531,26 +531,19 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp shaderinfo.drawtype = drawtype; shaderinfo.material = video::EMT_SOLID; switch (material_type) { - case TILE_MATERIAL_BASIC: - shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; - break; - case TILE_MATERIAL_ALPHA: - shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL; - break; - case TILE_MATERIAL_LIQUID_TRANSPARENT: - shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL; - break; - case TILE_MATERIAL_LIQUID_OPAQUE: - shaderinfo.base_material = video::EMT_SOLID; - break; - case TILE_MATERIAL_WAVING_LEAVES: - shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; - break; - case TILE_MATERIAL_WAVING_PLANTS: - shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; - break; - default: - break; + case TILE_MATERIAL_OPAQUE: + case TILE_MATERIAL_LIQUID_OPAQUE: + shaderinfo.base_material = video::EMT_SOLID; + break; + case TILE_MATERIAL_ALPHA: + case TILE_MATERIAL_LIQUID_TRANSPARENT: + shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + break; + case TILE_MATERIAL_BASIC: + case TILE_MATERIAL_WAVING_LEAVES: + case TILE_MATERIAL_WAVING_PLANTS: + shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + break; } bool enable_shaders = g_settings->getBool("enable_shaders"); @@ -642,7 +635,8 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp "TILE_MATERIAL_LIQUID_TRANSPARENT", "TILE_MATERIAL_LIQUID_OPAQUE", "TILE_MATERIAL_WAVING_LEAVES", - "TILE_MATERIAL_WAVING_PLANTS" + "TILE_MATERIAL_WAVING_PLANTS", + "TILE_MATERIAL_OPAQUE" }; for (int i = 0; i < 6; i++){ From c772e0e18c90e48f237e37a45230a1dacd945786 Mon Sep 17 00:00:00 2001 From: Vincent Glize Date: Sat, 1 Jul 2017 14:07:40 +0200 Subject: [PATCH 52/53] C++11 cleanup inventorymanager (#6077) * C++11 cleanup inventorymanager --- src/guiFormSpecMenu.cpp | 16 +-- src/inventorymanager.cpp | 190 +++++++++++----------------- src/inventorymanager.h | 65 ++++------ src/network/serverpackethandler.cpp | 8 +- 4 files changed, 111 insertions(+), 168 deletions(-) diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 0592f4e1..a2a336b8 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -3526,7 +3526,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) // Possibly send inventory action to server if (move_amount > 0) { - // Send IACTION_MOVE + // Send IAction::Move assert(m_selected_item && m_selected_item->isValid()); assert(s.isValid()); @@ -3563,7 +3563,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) m_selected_content_guess = ItemStack(); // Clear } - 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; @@ -3599,7 +3599,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) ItemStack stack_from = list_from->getItem(s.i); assert(shift_move_amount <= stack_from.count); if (m_client->getProtoVersion() >= 25) { - 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; @@ -3617,7 +3617,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) && shift_move_amount > 0; slot_to++) { list_to->itemFits(slot_to, stack_from, &leftover); if (leftover.count < 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 = MYMIN(shift_move_amount, (u32) (stack_from.count - leftover.count)); @@ -3637,7 +3637,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) } else if (drop_amount > 0) { m_selected_content_guess = ItemStack(); // Clear - // Send IACTION_DROP + // Send IAction::Drop assert(m_selected_item && m_selected_item->isValid()); assert(inv_selected); @@ -3650,7 +3650,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) assert(drop_amount > 0 && drop_amount <= m_selected_amount); m_selected_amount -= drop_amount; - infostream << "Handing IACTION_DROP to manager" << std::endl; + infostream << "Handing IAction::Drop to manager" << std::endl; IDropAction *a = new IDropAction(); a->count = drop_amount; a->from_inv = m_selected_item->inventoryloc; @@ -3660,12 +3660,12 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event) } else if (craft_amount > 0) { m_selected_content_guess = ItemStack(); // Clear - // Send IACTION_CRAFT + // Send IAction::Craft assert(s.isValid()); assert(inv_s); - 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; diff --git a/src/inventorymanager.cpp b/src/inventorymanager.cpp index c976bd03..fe37bcd8 100644 --- a/src/inventorymanager.cpp +++ b/src/inventorymanager.cpp @@ -43,7 +43,7 @@ std::string InventoryLocation::dump() const void InventoryLocation::serialize(std::ostream &os) const { - switch(type){ + switch (type) { case InventoryLocation::UNDEFINED: os<<"undefined"; break; @@ -68,21 +68,14 @@ void InventoryLocation::deSerialize(std::istream &is) { std::string tname; std::getline(is, tname, ':'); - if(tname == "undefined") - { + if (tname == "undefined") { type = InventoryLocation::UNDEFINED; - } - else if(tname == "current_player") - { + } else if (tname == "current_player") { type = InventoryLocation::CURRENT_PLAYER; - } - else if(tname == "player") - { + } else if (tname == "player") { type = InventoryLocation::PLAYER; std::getline(is, name, '\n'); - } - else if(tname == "nodemeta") - { + } else if (tname == "nodemeta") { type = InventoryLocation::NODEMETA; std::string pos; std::getline(is, pos, '\n'); @@ -90,14 +83,10 @@ void InventoryLocation::deSerialize(std::istream &is) p.X = stoi(fn.next(",")); p.Y = stoi(fn.next(",")); p.Z = stoi(fn.next(",")); - } - else if(tname == "detached") - { + } else if (tname == "detached") { type = InventoryLocation::DETACHED; std::getline(is, name, '\n'); - } - else - { + } else { infostream<<"Unknown InventoryLocation type=\""<getItem(from_i).count; int src_can_take_count = 0xffff; @@ -274,28 +261,23 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame /* Query detached inventories */ // Move occurs in the same detached inventory - if(from_inv.type == InventoryLocation::DETACHED && + if (from_inv.type == InventoryLocation::DETACHED && to_inv.type == InventoryLocation::DETACHED && - from_inv.name == to_inv.name) - { + from_inv.name == to_inv.name) { src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowMove( from_inv.name, from_list, from_i, to_list, to_i, try_take_count, player); dst_can_put_count = src_can_take_count; - } - else - { + } else { // Destination is detached - if(to_inv.type == InventoryLocation::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( to_inv.name, to_list, to_i, src_item, player); } // Source is detached - if(from_inv.type == InventoryLocation::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( @@ -307,28 +289,23 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame // Both endpoints are nodemeta // Move occurs in the same nodemeta inventory - if(from_inv.type == InventoryLocation::NODEMETA && + if (from_inv.type == InventoryLocation::NODEMETA && to_inv.type == InventoryLocation::NODEMETA && - from_inv.p == to_inv.p) - { + from_inv.p == to_inv.p) { src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowMove( from_inv.p, from_list, from_i, to_list, to_i, try_take_count, player); dst_can_put_count = src_can_take_count; - } - else - { + } else { // Destination is nodemeta - if(to_inv.type == InventoryLocation::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( to_inv.p, to_list, to_i, src_item, player); } // Source is nodemeta - if(from_inv.type == InventoryLocation::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( @@ -340,17 +317,16 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame /* Modify count according to collected data */ count = try_take_count; - if(src_can_take_count != -1 && count > src_can_take_count) + if (src_can_take_count != -1 && count > src_can_take_count) count = src_can_take_count; - if(dst_can_put_count != -1 && count > dst_can_put_count) + if (dst_can_put_count != -1 && count > dst_can_put_count) count = dst_can_put_count; /* Limit according to source item count */ - if(count > list_from->getItem(from_i).count) + if (count > list_from->getItem(from_i).count) count = list_from->getItem(from_i).count; /* If no items will be moved, don't go further */ - if(count == 0) - { + if (count == 0) { infostream<<"IMoveAction::apply(): move was completely disallowed:" <<" count="<deleteItem(to_i); list_to->addItem(to_i, to_stack_was); list_from->deleteItem(from_i); @@ -426,19 +402,17 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame // If we are inside the move somewhere loop, we don't need to report // anything if nothing happened (perhaps we don't need to report // anything for caused_by_move_somewhere == true, but this way its safer) - if (caused_by_move_somewhere && move_count == 0) { + if (caused_by_move_somewhere && move_count == 0) return; - } /* Record rollback information */ - if(!ignore_rollback && gamedef->rollback()) - { + if (!ignore_rollback && gamedef->rollback()) { IRollbackManager *rollback = gamedef->rollback(); // If source is not infinite, record item take - if(src_can_take_count != -1){ + if (src_can_take_count != -1) { RollbackAction action; std::string loc; { @@ -451,7 +425,7 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame rollback->reportAction(action); } // If destination is not infinite, record item put - if(dst_can_put_count != -1){ + if (dst_can_put_count != -1) { RollbackAction action; std::string loc; { @@ -472,25 +446,20 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame /* Detached inventories */ // Both endpoints are same detached - if(from_inv.type == InventoryLocation::DETACHED && + if (from_inv.type == InventoryLocation::DETACHED && to_inv.type == InventoryLocation::DETACHED && - from_inv.name == to_inv.name) - { + from_inv.name == to_inv.name) { PLAYER_TO_SA(player)->detached_inventory_OnMove( from_inv.name, from_list, from_i, to_list, to_i, count, player); - } - else - { + } else { // Destination is detached - if(to_inv.type == InventoryLocation::DETACHED) - { + if (to_inv.type == InventoryLocation::DETACHED) { PLAYER_TO_SA(player)->detached_inventory_OnPut( to_inv.name, to_list, to_i, src_item, player); } // Source is detached - if(from_inv.type == InventoryLocation::DETACHED) - { + if (from_inv.type == InventoryLocation::DETACHED) { PLAYER_TO_SA(player)->detached_inventory_OnTake( from_inv.name, from_list, from_i, src_item, player); } @@ -499,31 +468,27 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame /* Node metadata inventories */ // Both endpoints are same nodemeta - if(from_inv.type == InventoryLocation::NODEMETA && + if (from_inv.type == InventoryLocation::NODEMETA && to_inv.type == InventoryLocation::NODEMETA && - from_inv.p == to_inv.p) - { + from_inv.p == to_inv.p) { PLAYER_TO_SA(player)->nodemeta_inventory_OnMove( from_inv.p, from_list, from_i, to_list, to_i, count, player); - } - else{ + } else { // Destination is nodemeta - if(to_inv.type == InventoryLocation::NODEMETA) - { + if (to_inv.type == InventoryLocation::NODEMETA) { PLAYER_TO_SA(player)->nodemeta_inventory_OnPut( to_inv.p, to_list, to_i, src_item, player); } // Source is nodemeta - else if(from_inv.type == InventoryLocation::NODEMETA) - { + else if (from_inv.type == InventoryLocation::NODEMETA) { PLAYER_TO_SA(player)->nodemeta_inventory_OnTake( from_inv.p, from_list, from_i, src_item, player); } } mgr->setInventoryModified(from_inv, false); - if(inv_from != inv_to) + if (inv_from != inv_to) mgr->setInventoryModified(to_inv, false); } @@ -534,18 +499,18 @@ void IMoveAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) Inventory *inv_from = mgr->getInventory(from_inv); Inventory *inv_to = mgr->getInventory(to_inv); - if(!inv_from || !inv_to) + if (!inv_from || !inv_to) return; InventoryLocation current_player; current_player.setCurrentPlayer(); Inventory *inv_player = mgr->getInventory(current_player); - if(inv_from != inv_player || inv_to != inv_player) + if (inv_from != inv_player || inv_to != inv_player) return; InventoryList *list_from = inv_from->getList(from_list); InventoryList *list_to = inv_to->getList(to_list); - if(!list_from || !list_to) + if (!list_from || !list_to) return; if (!move_somewhere) @@ -554,7 +519,7 @@ void IMoveAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) list_from->moveItemSomewhere(from_i, list_to, count); mgr->setInventoryModified(from_inv); - if(inv_from != inv_to) + if (inv_from != inv_to) mgr->setInventoryModified(to_inv); } @@ -582,7 +547,7 @@ void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame { Inventory *inv_from = mgr->getInventory(from_inv); - if(!inv_from){ + if (!inv_from) { infostream<<"IDropAction::apply(): FAIL: source inventory not found: " <<"from_inv=\""<getItem(from_i).empty()) - { + if (list_from->getItem(from_i).empty()) { infostream<<"IDropAction::apply(): FAIL: source item not found: " <<"from_inv=\""<getItem(from_i).count; - if(count != 0 && count < take_count) + if (count != 0 && count < take_count) take_count = count; int src_can_take_count = take_count; // Source is detached - if(from_inv.type == InventoryLocation::DETACHED) - { + if (from_inv.type == InventoryLocation::DETACHED) { ItemStack src_item = list_from->getItem(from_i); src_item.count = take_count; src_can_take_count = PLAYER_TO_SA(player)->detached_inventory_AllowTake( @@ -631,15 +594,14 @@ void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame } // Source is nodemeta - if(from_inv.type == InventoryLocation::NODEMETA) - { + if (from_inv.type == InventoryLocation::NODEMETA) { ItemStack src_item = list_from->getItem(from_i); src_item.count = take_count; src_can_take_count = PLAYER_TO_SA(player)->nodemeta_inventory_AllowTake( from_inv.p, from_list, from_i, src_item, player); } - if(src_can_take_count != -1 && src_can_take_count < take_count) + if (src_can_take_count != -1 && src_can_take_count < take_count) take_count = src_can_take_count; int actually_dropped_count = 0; @@ -649,22 +611,21 @@ void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame // Drop the item ItemStack item1 = list_from->getItem(from_i); item1.count = take_count; - if(PLAYER_TO_SA(player)->item_OnDrop(item1, player, - player->getBasePosition() + v3f(0,1,0))) - { + if (PLAYER_TO_SA(player)->item_OnDrop(item1, player, + player->getBasePosition() + v3f(0,1,0))) { actually_dropped_count = take_count - item1.count; - if(actually_dropped_count == 0){ + if (actually_dropped_count == 0) { infostream<<"Actually dropped no items"<takeItem(from_i, actually_dropped_count); - if(item2.count != actually_dropped_count) + if (item2.count != actually_dropped_count) errorstream<<"Could not take dropped count of items"<setInventoryModified(from_inv, false); @@ -684,15 +645,13 @@ void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame */ // Source is detached - if(from_inv.type == InventoryLocation::DETACHED) - { + if (from_inv.type == InventoryLocation::DETACHED) { PLAYER_TO_SA(player)->detached_inventory_OnTake( from_inv.name, from_list, from_i, src_item, player); } // Source is nodemeta - if(from_inv.type == InventoryLocation::NODEMETA) - { + if (from_inv.type == InventoryLocation::NODEMETA) { PLAYER_TO_SA(player)->nodemeta_inventory_OnTake( from_inv.p, from_list, from_i, src_item, player); } @@ -700,12 +659,11 @@ void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame /* Record rollback information */ - if(!ignore_src_rollback && gamedef->rollback()) - { + if (!ignore_src_rollback && gamedef->rollback()) { IRollbackManager *rollback = gamedef->rollback(); // If source is not infinite, record item take - if(src_can_take_count != -1){ + if (src_can_take_count != -1) { RollbackAction action; std::string loc; { @@ -726,20 +684,20 @@ void IDropAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) // to make lag less apparent. Inventory *inv_from = mgr->getInventory(from_inv); - if(!inv_from) + if (!inv_from) return; InventoryLocation current_player; current_player.setCurrentPlayer(); Inventory *inv_player = mgr->getInventory(current_player); - if(inv_from != inv_player) + if (inv_from != inv_player) return; InventoryList *list_from = inv_from->getList(from_list); - if(!list_from) + if (!list_from) return; - if(count == 0) + if (count == 0) list_from->changeItem(from_i, ItemStack()); else list_from->takeItem(from_i, count); @@ -881,7 +839,7 @@ void ICraftAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) // Crafting helper -bool getCraftingResult(Inventory *inv, ItemStack& result, +bool getCraftingResult(Inventory *inv, ItemStack &result, std::vector &output_replacements, bool decrementInput, IGameDef *gamedef) { @@ -891,28 +849,26 @@ bool getCraftingResult(Inventory *inv, ItemStack& result, // Get the InventoryList in which we will operate InventoryList *clist = inv->getList("craft"); - if(!clist) + if (!clist) return false; // Mangle crafting grid to an another format CraftInput ci; ci.method = CRAFT_METHOD_NORMAL; ci.width = clist->getWidth() ? clist->getWidth() : 3; - for(u16 i=0; igetSize(); 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 CraftOutput co; bool found = gamedef->getCraftDefManager()->getCraftResult( ci, co, output_replacements, decrementInput, gamedef); - if(found) + if (found) result.deSerialize(co.item, gamedef->getItemDefManager()); - if(found && decrementInput) - { + if (found && decrementInput) { // CraftInput has been changed, apply changes in clist - for(u16 i=0; igetSize(); i++) - { + for (u16 i=0; i < clist->getSize(); i++) { clist->changeItem(i, ci.items[i]); } } diff --git a/src/inventorymanager.h b/src/inventorymanager.h index 35fcf4b9..916b3ea3 100644 --- a/src/inventorymanager.h +++ b/src/inventorymanager.h @@ -117,15 +117,17 @@ public: virtual void inventoryAction(InventoryAction *a){} }; -#define IACTION_MOVE 0 -#define IACTION_DROP 1 -#define IACTION_CRAFT 2 +enum class IAction : u16 { + Move, + Drop, + Craft +}; struct InventoryAction { - static InventoryAction * deSerialize(std::istream &is); + static InventoryAction *deSerialize(std::istream &is); - virtual u16 getType() const = 0; + virtual IAction getType() const = 0; virtual void serialize(std::ostream &os) const = 0; virtual void apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) = 0; @@ -136,35 +138,27 @@ struct InventoryAction struct IMoveAction : public InventoryAction { // count=0 means "everything" - u16 count; + u16 count = 0; InventoryLocation from_inv; std::string from_list; - s16 from_i; + s16 from_i = -1; InventoryLocation to_inv; std::string to_list; - s16 to_i; - bool move_somewhere; + s16 to_i = -1; + bool move_somewhere = false; // treat these as private // related to movement to somewhere - bool caused_by_move_somewhere; - u32 move_count; + bool caused_by_move_somewhere = false; + u32 move_count = 0; - IMoveAction() - { - count = 0; - from_i = -1; - to_i = -1; - move_somewhere = false; - caused_by_move_somewhere = false; - move_count = 0; - } + IMoveAction() {} IMoveAction(std::istream &is, bool somewhere); - u16 getType() const + IAction getType() const { - return IACTION_MOVE; + return IAction::Move; } void serialize(std::ostream &os) const @@ -191,22 +185,18 @@ struct IMoveAction : public InventoryAction struct IDropAction : public InventoryAction { // count=0 means "everything" - u16 count; + u16 count = 0; InventoryLocation from_inv; std::string from_list; - s16 from_i; + s16 from_i = -1; - IDropAction() - { - count = 0; - from_i = -1; - } + IDropAction() {} IDropAction(std::istream &is); - u16 getType() const + IAction getType() const { - return IACTION_DROP; + return IAction::Drop; } void serialize(std::ostream &os) const @@ -226,19 +216,16 @@ struct IDropAction : public InventoryAction struct ICraftAction : public InventoryAction { // count=0 means "everything" - u16 count; + u16 count = 0; InventoryLocation craft_inv; - ICraftAction() - { - count = 0; - } + ICraftAction() {} ICraftAction(std::istream &is); - u16 getType() const + IAction getType() const { - return IACTION_CRAFT; + return IAction::Craft; } void serialize(std::ostream &os) const @@ -254,7 +241,7 @@ struct ICraftAction : public InventoryAction }; // Crafting helper -bool getCraftingResult(Inventory *inv, ItemStack& result, +bool getCraftingResult(Inventory *inv, ItemStack &result, std::vector &output_replacements, bool decrementInput, IGameDef *gamedef); diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index da421b36..a2882b2e 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -908,7 +908,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) std::istringstream is(datastring, std::ios_base::binary); // Create an action InventoryAction *a = InventoryAction::deSerialize(is); - if (a == NULL) { + if (!a) { infostream << "TOSERVER_INVENTORY_ACTION: " << "InventoryAction::deSerialize() returned NULL" << std::endl; @@ -927,7 +927,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) /* Handle restrictions and special cases of the move action */ - if (a->getType() == IACTION_MOVE) { + if (a->getType() == IAction::Move) { IMoveAction *ma = (IMoveAction*)a; ma->from_inv.applyCurrentPlayer(player->getName()); @@ -982,7 +982,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) /* Handle restrictions and special cases of the drop action */ - else if (a->getType() == IACTION_DROP) { + else if (a->getType() == IAction::Drop) { IDropAction *da = (IDropAction*)a; da->from_inv.applyCurrentPlayer(player->getName()); @@ -1018,7 +1018,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) /* Handle restrictions and special cases of the craft action */ - else if (a->getType() == IACTION_CRAFT) { + else if (a->getType() == IAction::Craft) { ICraftAction *ca = (ICraftAction*)a; ca->craft_inv.applyCurrentPlayer(player->getName()); From c3580043685671c4f767e1c380ae7c3e237f8b8b Mon Sep 17 00:00:00 2001 From: stujones11 Date: Sat, 1 Jul 2017 17:01:07 +0100 Subject: [PATCH 53/53] Include TILE_MATERIAL_OPAQUE in shaders header (#6086) --- src/shader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shader.cpp b/src/shader.cpp index 4f482fdd..ac0745cb 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -639,7 +639,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp "TILE_MATERIAL_OPAQUE" }; - for (int i = 0; i < 6; i++){ + for (int i = 0; i < 7; i++){ shaders_header += "#define "; shaders_header += materialTypes[i]; shaders_header += " ";