Modernize source code: last part (#6285)

* Modernize source code: last par

* Use empty when needed
* Use emplace_back instead of push_back when needed
* For range-based loops
* Initializers fixes
* constructors, destructors default
* c++ C stl includes
This commit is contained in:
Loïc Blot 2017-08-20 13:30:50 +02:00 committed by GitHub
parent 50669cd282
commit 1c1c97cbd1
72 changed files with 446 additions and 584 deletions

@ -35,7 +35,7 @@ struct Nametag {
Nametag(scene::ISceneNode *a_parent_node, Nametag(scene::ISceneNode *a_parent_node,
const std::string &a_nametag_text, const std::string &a_nametag_text,
const video::SColor &a_nametag_color, const video::SColor &a_nametag_color,
const v3f a_nametag_pos): const v3f &a_nametag_pos):
parent_node(a_parent_node), parent_node(a_parent_node),
nametag_text(a_nametag_text), nametag_text(a_nametag_text),
nametag_color(a_nametag_color), nametag_color(a_nametag_color),

@ -365,8 +365,8 @@ s32 ChatBuffer::getBottomScrollPos() const
s32 rows = (s32) m_rows; s32 rows = (s32) m_rows;
if (rows == 0) if (rows == 0)
return 0; return 0;
else
return formatted_count - rows; return formatted_count - rows;
} }

@ -35,7 +35,7 @@ public:
void savePlayer(RemotePlayer *player) {} void savePlayer(RemotePlayer *player) {}
bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) { return true; } bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) { return true; }
bool removePlayer(const std::string &name) { return true; } bool removePlayer(const std::string &name) { return true; }
void listPlayers(std::vector<std::string> &) {} void listPlayers(std::vector<std::string> &res) {}
void beginSave() {} void beginSave() {}
void endSave() {} void endSave() {}

@ -29,10 +29,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define BLOCK_EMERGE_ALLOW_GEN (1 << 0) #define BLOCK_EMERGE_ALLOW_GEN (1 << 0)
#define BLOCK_EMERGE_FORCE_QUEUE (1 << 1) #define BLOCK_EMERGE_FORCE_QUEUE (1 << 1)
#define EMERGE_DBG_OUT(x) do { \ #define EMERGE_DBG_OUT(x) { \
if (enable_mapgen_debug_info) \ if (enable_mapgen_debug_info) \
infostream << "EmergeThread: " x << std::endl; \ infostream << "EmergeThread: " x << std::endl; \
} while (0) }
class EmergeThread; class EmergeThread;
class INodeDefManager; class INodeDefManager;

@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class MtEvent class MtEvent
{ {
public: public:
virtual ~MtEvent() {}; virtual ~MtEvent() = default;
//virtual MtEvent* clone(){ return new IEvent; } //virtual MtEvent* clone(){ return new IEvent; }
virtual const char* getType() const = 0; virtual const char* getType() const = 0;
@ -49,7 +49,7 @@ public:
class MtEventReceiver class MtEventReceiver
{ {
public: public:
virtual ~MtEventReceiver(){}; virtual ~MtEventReceiver() = default;
virtual void onEvent(MtEvent *e) = 0; virtual void onEvent(MtEvent *e) = 0;
}; };
@ -58,7 +58,7 @@ typedef void (*event_receive_func)(MtEvent *e, void *data);
class MtEventManager class MtEventManager
{ {
public: public:
virtual ~MtEventManager(){}; virtual ~MtEventManager() = default;
virtual void put(MtEvent *e) = 0; virtual void put(MtEvent *e) = 0;
virtual void reg(const char *type, event_receive_func f, void *data) = 0; virtual void reg(const char *type, event_receive_func f, void *data) = 0;
// If data==NULL, every occurence of f is deregistered. // If data==NULL, every occurence of f is deregistered.

@ -43,17 +43,15 @@ class EventManager: public MtEventManager
std::map<std::string, Dest> m_dest; std::map<std::string, Dest> m_dest;
public: public:
~EventManager() ~EventManager() = default;
{
}
void put(MtEvent *e) void put(MtEvent *e)
{ {
std::map<std::string, Dest>::iterator i = m_dest.find(e->getType()); std::map<std::string, Dest>::iterator i = m_dest.find(e->getType());
if(i != m_dest.end()){ if(i != m_dest.end()){
std::list<FuncSpec> &funcs = i->second.funcs; std::list<FuncSpec> &funcs = i->second.funcs;
for(std::list<FuncSpec>::iterator i = funcs.begin(); for (FuncSpec &func : funcs) {
i != funcs.end(); ++i){ (*(func.f))(e, func.d);
(*(i->f))(e, i->d);
} }
} }
delete e; delete e;
@ -62,11 +60,11 @@ public:
{ {
std::map<std::string, Dest>::iterator i = m_dest.find(type); std::map<std::string, Dest>::iterator i = m_dest.find(type);
if(i != m_dest.end()){ if(i != m_dest.end()){
i->second.funcs.push_back(FuncSpec(f, data)); i->second.funcs.emplace_back(f, data);
} else{ } else{
std::list<FuncSpec> funcs; std::list<FuncSpec> funcs;
Dest dest; Dest dest;
dest.funcs.push_back(FuncSpec(f, data)); dest.funcs.emplace_back(f, data);
m_dest[type] = dest; m_dest[type] = dest;
} }
} }
@ -86,9 +84,8 @@ public:
} }
} }
} else{ } else{
for(std::map<std::string, Dest>::iterator for (auto &dest : m_dest) {
i = m_dest.begin(); i != m_dest.end(); ++i){ std::list<FuncSpec> &funcs = dest.second.funcs;
std::list<FuncSpec> &funcs = i->second.funcs;
std::list<FuncSpec>::iterator j = funcs.begin(); std::list<FuncSpec>::iterator j = funcs.begin();
while(j != funcs.end()){ while(j != funcs.end()){
bool remove = (j->f == f && (!data || j->d == data)); bool remove = (j->f == f && (!data || j->d == data));

@ -27,7 +27,8 @@ class BaseException : public std::exception
{ {
public: public:
BaseException(const std::string &s) throw(): m_s(s) {} BaseException(const std::string &s) throw(): m_s(s) {}
~BaseException() throw() {} ~BaseException() throw() = default;
virtual const char * what() const throw() virtual const char * what() const throw()
{ {
return m_s.c_str(); return m_s.c_str();

@ -69,8 +69,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "sound_openal.h" #include "sound_openal.h"
#endif #endif
extern Settings *g_settings;
extern Profiler *g_profiler;
/* /*
Text input system Text input system
@ -248,7 +246,7 @@ void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
setStaticText(guitext_profiler, text.c_str()); setStaticText(guitext_profiler, text.c_str());
guitext_profiler->setVisible(true); guitext_profiler->setVisible(true);
s32 w = fe->getTextWidth(text.c_str()); s32 w = fe->getTextWidth(text);
if (w < 400) if (w < 400)
w = 400; w = 400;
@ -291,11 +289,9 @@ private:
}; };
std::deque<Piece> m_log; std::deque<Piece> m_log;
public: public:
u32 m_log_max_size; u32 m_log_max_size = 200;
ProfilerGraph(): ProfilerGraph() = default;
m_log_max_size(200)
{}
void put(const Profiler::GraphValues &values) void put(const Profiler::GraphValues &values)
{ {
@ -314,14 +310,10 @@ public:
// to be the same for each call to prevent flickering // to be the same for each call to prevent flickering
std::map<std::string, Meta> m_meta; std::map<std::string, Meta> m_meta;
for (std::deque<Piece>::const_iterator k = m_log.begin(); for (const Piece &piece : m_log) {
k != m_log.end(); ++k) { for (const auto &i : piece.values) {
const Piece &piece = *k; const std::string &id = i.first;
const float &value = i.second;
for (Profiler::GraphValues::const_iterator i = piece.values.begin();
i != piece.values.end(); ++i) {
const std::string &id = i->first;
const float &value = i->second;
std::map<std::string, Meta>::iterator j = m_meta.find(id); std::map<std::string, Meta>::iterator j = m_meta.find(id);
if (j == m_meta.end()) { if (j == m_meta.end()) {
@ -349,9 +341,8 @@ public:
sizeof(usable_colors) / sizeof(*usable_colors); sizeof(usable_colors) / sizeof(*usable_colors);
u32 next_color_i = 0; u32 next_color_i = 0;
for (std::map<std::string, Meta>::iterator i = m_meta.begin(); for (auto &i : m_meta) {
i != m_meta.end(); ++i) { Meta &meta = i.second;
Meta &meta = i->second;
video::SColor color(255, 200, 200, 200); video::SColor color(255, 200, 200, 200);
if (next_color_i < usable_colors_count) if (next_color_i < usable_colors_count)
@ -401,9 +392,7 @@ public:
float lastscaledvalue = 0.0; float lastscaledvalue = 0.0;
bool lastscaledvalue_exists = false; bool lastscaledvalue_exists = false;
for (std::deque<Piece>::const_iterator j = m_log.begin(); for (const Piece &piece : m_log) {
j != m_log.end(); ++j) {
const Piece &piece = *j;
float value = 0; float value = 0;
bool value_exists = false; bool value_exists = false;
Profiler::GraphValues::const_iterator k = Profiler::GraphValues::const_iterator k =
@ -763,8 +752,8 @@ public:
void setSky(Sky *sky) { void setSky(Sky *sky) {
m_sky = sky; m_sky = sky;
for (size_t i = 0; i < created_nosky.size(); ++i) { for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
created_nosky[i]->setSky(m_sky); ggscs->setSky(m_sky);
} }
created_nosky.clear(); created_nosky.clear();
} }
@ -793,7 +782,7 @@ bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_de
if (!is_valid_position) if (!is_valid_position)
return false; return false;
if (prediction != "" && !nodedef->get(node).rightclickable) { if (!prediction.empty() && !nodedef->get(node).rightclickable) {
verbosestream << "Node placement prediction for " verbosestream << "Node placement prediction for "
<< playeritem_def.name << " is " << playeritem_def.name << " is "
<< prediction << std::endl; << prediction << std::endl;
@ -978,7 +967,7 @@ static void updateChat(Client &client, f32 dtime, bool show_debug,
} }
// Get new messages from client // Get new messages from client
std::wstring message = L""; std::wstring message;
while (client.getChatMessage(message)) { while (client.getChatMessage(message)) {
chat_backend.addUnparsedMessage(message); chat_backend.addUnparsedMessage(message);
} }
@ -1116,8 +1105,8 @@ void KeyCache::populate()
if (handler) { if (handler) {
// First clear all keys, then re-add the ones we listen for // First clear all keys, then re-add the ones we listen for
handler->dontListenForKeys(); handler->dontListenForKeys();
for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) { for (const KeyPress &k : key) {
handler->listenForKey(key[i]); handler->listenForKey(k);
} }
handler->listenForKey(EscapeKey); handler->listenForKey(EscapeKey);
handler->listenForKey(CancelKey); handler->listenForKey(CancelKey);
@ -1384,7 +1373,7 @@ private:
GameOnDemandSoundFetcher soundfetcher; // useful when testing GameOnDemandSoundFetcher soundfetcher; // useful when testing
ISoundManager *sound; ISoundManager *sound;
bool sound_is_dummy; bool sound_is_dummy = false;
SoundMaker *soundmaker; SoundMaker *soundmaker;
ChatBackend *chat_backend; ChatBackend *chat_backend;
@ -1464,9 +1453,9 @@ private:
f32 m_cache_cam_smoothing; f32 m_cache_cam_smoothing;
f32 m_cache_fog_start; f32 m_cache_fog_start;
bool m_invert_mouse; bool m_invert_mouse = false;
bool m_first_loop_after_window_activation; bool m_first_loop_after_window_activation = false;
bool m_camera_offset_changed; bool m_camera_offset_changed = false;
#ifdef __ANDROID__ #ifdef __ANDROID__
bool m_cache_hold_aux1; bool m_cache_hold_aux1;
@ -1482,7 +1471,6 @@ Game::Game() :
itemdef_manager(NULL), itemdef_manager(NULL),
nodedef_manager(NULL), nodedef_manager(NULL),
sound(NULL), sound(NULL),
sound_is_dummy(false),
soundmaker(NULL), soundmaker(NULL),
chat_backend(NULL), chat_backend(NULL),
current_formspec(NULL), current_formspec(NULL),
@ -1496,10 +1484,7 @@ Game::Game() :
sky(NULL), sky(NULL),
local_inventory(NULL), local_inventory(NULL),
hud(NULL), hud(NULL),
mapper(NULL), mapper(NULL)
m_invert_mouse(false),
m_first_loop_after_window_activation(false),
m_camera_offset_changed(false)
{ {
g_settings->registerChangedCallback("doubletap_jump", g_settings->registerChangedCallback("doubletap_jump",
&settingChangedCallback, this); &settingChangedCallback, this);
@ -1806,7 +1791,7 @@ bool Game::init(
return false; return false;
// Create a server if not connecting to an existing one // Create a server if not connecting to an existing one
if (*address == "") { if (address->empty()) {
if (!createSingleplayerServer(map_dir, gamespec, port, address)) if (!createSingleplayerServer(map_dir, gamespec, port, address))
return false; return false;
} }
@ -2168,7 +2153,7 @@ bool Game::connectToServer(const std::string &playername,
wait_time += dtime; wait_time += dtime;
// Only time out if we aren't waiting for the server we started // Only time out if we aren't waiting for the server we started
if ((*address != "") && (wait_time > 10)) { if ((!address->empty()) && (wait_time > 10)) {
bool sent_old_init = g_settings->getFlag("send_pre_v25_init"); bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
// If no pre v25 init was sent, and no answer was received, // If no pre v25 init was sent, and no answer was received,
// but the low level connection could be established // but the low level connection could be established
@ -3175,8 +3160,9 @@ void Game::processClientEvents(CameraOrientation *cam)
break; break;
case CE_SHOW_FORMSPEC: case CE_SHOW_FORMSPEC:
if (*(event.show_formspec.formspec) == "") { if (event.show_formspec.formspec->empty()) {
if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){ if (current_formspec && (event.show_formspec.formname->empty()
|| *(event.show_formspec.formname) == cur_formname)) {
current_formspec->quitMenu(); current_formspec->quitMenu();
} }
} else { } else {
@ -3713,7 +3699,7 @@ PointedThing Game::updatePointedThing(
} }
// Update selection mesh light level and vertex colors // Update selection mesh light level and vertex colors
if (selectionboxes->size() > 0) { if (!selectionboxes->empty()) {
v3f pf = hud->getSelectionPos(); v3f pf = hud->getSelectionPos();
v3s16 p = floatToInt(pf, BS); v3s16 p = floatToInt(pf, BS);
@ -3722,8 +3708,8 @@ PointedThing Game::updatePointedThing(
u16 node_light = getInteriorLight(n, -1, nodedef); u16 node_light = getInteriorLight(n, -1, nodedef);
u16 light_level = node_light; u16 light_level = node_light;
for (u8 i = 0; i < 6; i++) { for (const v3s16 &dir : g_6dirs) {
n = map.getNodeNoEx(p + g_6dirs[i]); n = map.getNodeNoEx(p + dir);
node_light = getInteriorLight(n, -1, nodedef); node_light = getInteriorLight(n, -1, nodedef);
if (node_light > light_level) if (node_light > light_level)
light_level = node_light; light_level = node_light;
@ -3797,7 +3783,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
runData.repeat_rightclick_timer = 0; runData.repeat_rightclick_timer = 0;
infostream << "Ground right-clicked" << std::endl; infostream << "Ground right-clicked" << std::endl;
if (meta && meta->getString("formspec") != "" && !random_input if (meta && !meta->getString("formspec").empty() && !random_input
&& !isKeyDown(KeyType::SNEAK)) { && !isKeyDown(KeyType::SNEAK)) {
// Report right click to server // Report right click to server
if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) { if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
@ -3842,7 +3828,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
soundmaker->m_player_rightpunch_sound = soundmaker->m_player_rightpunch_sound =
SimpleSoundSpec(); SimpleSoundSpec();
if (playeritem_def.node_placement_prediction == "" || if (playeritem_def.node_placement_prediction.empty() ||
nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) { nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
client->interact(3, pointed); // Report to server client->interact(3, pointed); // Report to server
} else { } else {
@ -3862,7 +3848,7 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &
utf8_to_wide(runData.selected_object->infoText())); utf8_to_wide(runData.selected_object->infoText()));
if (show_debug) { if (show_debug) {
if (infotext != L"") { if (!infotext.empty()) {
infotext += L"\n"; infotext += L"\n";
} }
infotext += unescape_enriched(utf8_to_wide( infotext += unescape_enriched(utf8_to_wide(
@ -3973,7 +3959,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
if (sound_dig.exists() && params.diggable) { if (sound_dig.exists() && params.diggable) {
if (sound_dig.name == "__group") { if (sound_dig.name == "__group") {
if (params.main_group != "") { if (!params.main_group.empty()) {
soundmaker->m_player_leftpunch_sound.gain = 0.5; soundmaker->m_player_leftpunch_sound.gain = 0.5;
soundmaker->m_player_leftpunch_sound.name = soundmaker->m_player_leftpunch_sound.name =
std::string("default_dig_") + std::string("default_dig_") +
@ -4649,7 +4635,7 @@ void Game::showPauseMenu()
static const std::string mode = strgettext("- Mode: "); static const std::string mode = strgettext("- Mode: ");
if (!simple_singleplayer_mode) { if (!simple_singleplayer_mode) {
Address serverAddress = client->getServerAddress(); Address serverAddress = client->getServerAddress();
if (address != "") { if (!address.empty()) {
os << mode << strgettext("Remote server") << "\n" os << mode << strgettext("Remote server") << "\n"
<< strgettext("- Address: ") << address; << strgettext("- Address: ") << address;
} else { } else {
@ -4659,7 +4645,7 @@ void Game::showPauseMenu()
} else { } else {
os << mode << strgettext("Singleplayer") << "\n"; os << mode << strgettext("Singleplayer") << "\n";
} }
if (simple_singleplayer_mode || address == "") { if (simple_singleplayer_mode || address.empty()) {
static const std::string on = strgettext("On"); static const std::string on = strgettext("On");
static const std::string off = strgettext("Off"); static const std::string off = strgettext("Off");
const std::string &damage = g_settings->getBool("enable_damage") ? on : off; const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
@ -4673,7 +4659,7 @@ void Game::showPauseMenu()
<< strgettext("- Public: ") << announced << "\n"; << strgettext("- Public: ") << announced << "\n";
std::string server_name = g_settings->get("server_name"); std::string server_name = g_settings->get("server_name");
str_formspec_escape(server_name); str_formspec_escape(server_name);
if (announced == on && server_name != "") if (announced == on && !server_name.empty())
os << strgettext("- Server Name: ") << server_name; os << strgettext("- Server Name: ") << server_name;
} }

@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#pragma once #pragma once
#include "irrlichttypes.h" #include "irrlichttypes.h"
#include <time.h> #include <ctime>
#include <string> #include <string>
enum TimePrecision enum TimePrecision

@ -100,8 +100,9 @@ private:
class IItemDefManager class IItemDefManager
{ {
public: public:
IItemDefManager(){} IItemDefManager() = default;
virtual ~IItemDefManager(){}
virtual ~IItemDefManager() = default;
// Get item definition // Get item definition
virtual const ItemDefinition& get(const std::string &name) const=0; virtual const ItemDefinition& get(const std::string &name) const=0;
@ -133,8 +134,9 @@ public:
class IWritableItemDefManager : public IItemDefManager class IWritableItemDefManager : public IItemDefManager
{ {
public: public:
IWritableItemDefManager(){} IWritableItemDefManager() = default;
virtual ~IWritableItemDefManager(){}
virtual ~IWritableItemDefManager() = default;
// Get item definition // Get item definition
virtual const ItemDefinition& get(const std::string &name) const=0; virtual const ItemDefinition& get(const std::string &name) const=0;

@ -352,8 +352,8 @@ static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
std::string name = worldspec.name; std::string name = worldspec.name;
std::string path = worldspec.path; std::string path = worldspec.path;
if (name.find(' ') != std::string::npos) if (name.find(' ') != std::string::npos)
name = std::string("'") + name + "'"; name = std::string("'").append(name).append("'");
path = std::string("'") + path + "'"; path = std::string("'").append(path).append("'");
name = padStringRight(name, 14); name = padStringRight(name, 14);
os << " " << name << " " << path << std::endl; os << " " << name << " " << path << std::endl;
} }

@ -48,9 +48,11 @@ class MainMenuManager : public IMenuManager
public: public:
virtual void createdMenu(gui::IGUIElement *menu) virtual void createdMenu(gui::IGUIElement *menu)
{ {
#ifndef NDEBUG
for (gui::IGUIElement *i : m_stack) { for (gui::IGUIElement *i : m_stack) {
assert(i != menu); assert(i != menu);
} }
#endif
if(!m_stack.empty()) if(!m_stack.empty())
m_stack.back()->setVisible(false); m_stack.back()->setVisible(false);

@ -431,12 +431,11 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox,
boxes_size += nodebox.connect_right.size(); boxes_size += nodebox.connect_right.size();
boxes.reserve(boxes_size); boxes.reserve(boxes_size);
#define BOXESPUSHBACK(c) do { \ #define BOXESPUSHBACK(c) \
for (std::vector<aabb3f>::const_iterator \ for (std::vector<aabb3f>::const_iterator \
it = (c).begin(); \ it = (c).begin(); \
it != (c).end(); ++it) \ it != (c).end(); ++it) \
(boxes).push_back(*it); \ (boxes).push_back(*it);
} while (0)
BOXESPUSHBACK(nodebox.fixed); BOXESPUSHBACK(nodebox.fixed);

@ -1281,7 +1281,7 @@ bool ConnectionSendThread::packetsQueued()
continue; continue;
for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) { for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
if (channel.queued_commands.size() > 0) { if (!channel.queued_commands.empty()) {
return true; return true;
} }
} }

@ -604,7 +604,7 @@ public:
class PeerHelper class PeerHelper
{ {
public: public:
PeerHelper() = default;; PeerHelper() = default;
PeerHelper(Peer* peer); PeerHelper(Peer* peer);
~PeerHelper(); ~PeerHelper();

@ -91,7 +91,7 @@ void read_item_definition(lua_State* L, int index,
// If name is "" (hand), ensure there are ToolCapabilities // If name is "" (hand), ensure there are ToolCapabilities
// because it will be looked up there whenever any other item has // because it will be looked up there whenever any other item has
// no ToolCapabilities // no ToolCapabilities
if(def.name == "" && def.tool_capabilities == NULL){ if (def.name.empty() && def.tool_capabilities == NULL){
def.tool_capabilities = new ToolCapabilities(); def.tool_capabilities = new ToolCapabilities();
} }
@ -212,9 +212,9 @@ void read_object_properties(lua_State *L, int index,
while(lua_next(L, table) != 0){ while(lua_next(L, table) != 0){
// key at index -2 and value at index -1 // key at index -2 and value at index -1
if(lua_isstring(L, -1)) if(lua_isstring(L, -1))
prop->textures.push_back(lua_tostring(L, -1)); prop->textures.emplace_back(lua_tostring(L, -1));
else else
prop->textures.push_back(""); prop->textures.emplace_back("");
// removes value, keeps key for next iteration // removes value, keeps key for next iteration
lua_pop(L, 1); lua_pop(L, 1);
} }
@ -303,18 +303,16 @@ void push_object_properties(lua_State *L, ObjectProperties *prop)
lua_newtable(L); lua_newtable(L);
u16 i = 1; u16 i = 1;
for (std::vector<std::string>::iterator it = prop->textures.begin(); for (const std::string &texture : prop->textures) {
it != prop->textures.end(); ++it) { lua_pushlstring(L, texture.c_str(), texture.size());
lua_pushlstring(L, it->c_str(), it->size());
lua_rawseti(L, -2, i); lua_rawseti(L, -2, i);
} }
lua_setfield(L, -2, "textures"); lua_setfield(L, -2, "textures");
lua_newtable(L); lua_newtable(L);
i = 1; i = 1;
for (std::vector<video::SColor>::iterator it = prop->colors.begin(); for (const video::SColor &color : prop->colors) {
it != prop->colors.end(); ++it) { push_ARGB8(L, color);
push_ARGB8(L, *it);
lua_rawseti(L, -2, i); lua_rawseti(L, -2, i);
} }
lua_setfield(L, -2, "colors"); lua_setfield(L, -2, "colors");
@ -564,7 +562,7 @@ ContentFeatures read_content_features(lua_State *L, int index)
f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2", f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
ScriptApiNode::es_ContentParamType2, CPT2_NONE); ScriptApiNode::es_ContentParamType2, CPT2_NONE);
if (f.palette_name != "" && if (!f.palette_name.empty() &&
!(f.param_type_2 == CPT2_COLOR || !(f.param_type_2 == CPT2_COLOR ||
f.param_type_2 == CPT2_COLORED_FACEDIR || f.param_type_2 == CPT2_COLORED_FACEDIR ||
f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) f.param_type_2 == CPT2_COLORED_WALLMOUNTED))
@ -646,7 +644,7 @@ ContentFeatures read_content_features(lua_State *L, int index)
lua_pushnil(L); lua_pushnil(L);
while (lua_next(L, table) != 0) { while (lua_next(L, table) != 0) {
// Value at -1 // Value at -1
f.connects_to.push_back(lua_tostring(L, -1)); f.connects_to.emplace_back(lua_tostring(L, -1));
lua_pop(L, 1); lua_pop(L, 1);
} }
} }
@ -771,9 +769,8 @@ void push_content_features(lua_State *L, const ContentFeatures &c)
lua_newtable(L); lua_newtable(L);
u16 i = 1; u16 i = 1;
for (std::vector<std::string>::const_iterator it = c.connects_to.begin(); for (const std::string &it : c.connects_to) {
it != c.connects_to.end(); ++it) { lua_pushlstring(L, it.c_str(), it.size());
lua_pushlstring(L, it->c_str(), it->size());
lua_rawseti(L, -2, i); lua_rawseti(L, -2, i);
} }
lua_setfield(L, -2, "connects_to"); lua_setfield(L, -2, "connects_to");
@ -893,9 +890,8 @@ void push_box(lua_State *L, const std::vector<aabb3f> &box)
{ {
lua_newtable(L); lua_newtable(L);
u8 i = 1; u8 i = 1;
for (std::vector<aabb3f>::const_iterator it = box.begin(); for (const aabb3f &it : box) {
it != box.end(); ++it) { push_aabb3f(L, it);
push_aabb3f(L, (*it));
lua_rawseti(L, -2, i); lua_rawseti(L, -2, i);
} }
} }
@ -987,21 +983,19 @@ NodeBox read_nodebox(lua_State *L, int index)
nodebox.type = (NodeBoxType)getenumfield(L, index, "type", nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
#define NODEBOXREAD(n, s) \ #define NODEBOXREAD(n, s){ \
do { \
lua_getfield(L, index, (s)); \ lua_getfield(L, index, (s)); \
if (lua_istable(L, -1)) \ if (lua_istable(L, -1)) \
(n) = read_aabb3f(L, -1, BS); \ (n) = read_aabb3f(L, -1, BS); \
lua_pop(L, 1); \ lua_pop(L, 1); \
} while (0) }
#define NODEBOXREADVEC(n, s) \ #define NODEBOXREADVEC(n, s) \
do { \
lua_getfield(L, index, (s)); \ lua_getfield(L, index, (s)); \
if (lua_istable(L, -1)) \ if (lua_istable(L, -1)) \
(n) = read_aabb3f_vector(L, -1, BS); \ (n) = read_aabb3f_vector(L, -1, BS); \
lua_pop(L, 1); \ lua_pop(L, 1);
} while (0)
NODEBOXREADVEC(nodebox.fixed, "fixed"); NODEBOXREADVEC(nodebox.fixed, "fixed");
NODEBOXREAD(nodebox.wall_top, "wall_top"); NODEBOXREAD(nodebox.wall_top, "wall_top");
NODEBOXREAD(nodebox.wall_bottom, "wall_bottom"); NODEBOXREAD(nodebox.wall_bottom, "wall_bottom");
@ -1037,7 +1031,7 @@ MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
param2 = lua_tonumber(L, -1); param2 = lua_tonumber(L, -1);
lua_pop(L, 1); lua_pop(L, 1);
return MapNode(ndef, name, param1, param2); return {ndef, name, param1, param2};
} }
/******************************************************************************/ /******************************************************************************/
@ -1096,18 +1090,17 @@ ItemStack read_item(lua_State* L, int index, IItemDefManager *idef)
if(index < 0) if(index < 0)
index = lua_gettop(L) + 1 + index; index = lua_gettop(L) + 1 + index;
if(lua_isnil(L, index)) if (lua_isnil(L, index)) {
{
return ItemStack(); return ItemStack();
} }
else if(lua_isuserdata(L, index))
{ if (lua_isuserdata(L, index)) {
// Convert from LuaItemStack // Convert from LuaItemStack
LuaItemStack *o = LuaItemStack::checkobject(L, index); LuaItemStack *o = LuaItemStack::checkobject(L, index);
return o->getItem(); return o->getItem();
} }
else if(lua_isstring(L, index))
{ if (lua_isstring(L, index)) {
// Convert from itemstring // Convert from itemstring
std::string itemstring = lua_tostring(L, index); std::string itemstring = lua_tostring(L, index);
try try
@ -1168,18 +1161,16 @@ void push_tool_capabilities(lua_State *L,
// Create groupcaps table // Create groupcaps table
lua_newtable(L); lua_newtable(L);
// For each groupcap // For each groupcap
for (ToolGCMap::const_iterator i = toolcap.groupcaps.begin(); for (const auto &gc_it : toolcap.groupcaps) {
i != toolcap.groupcaps.end(); ++i) {
// Create groupcap table // Create groupcap table
lua_newtable(L); lua_newtable(L);
const std::string &name = i->first; const std::string &name = gc_it.first;
const ToolGroupCap &groupcap = i->second; const ToolGroupCap &groupcap = gc_it.second;
// Create subtable "times" // Create subtable "times"
lua_newtable(L); lua_newtable(L);
for (std::unordered_map<int, float>::const_iterator for (auto time : groupcap.times) {
i = groupcap.times.begin(); i != groupcap.times.end(); ++i) { lua_pushinteger(L, time.first);
lua_pushinteger(L, i->first); lua_pushnumber(L, time.second);
lua_pushnumber(L, i->second);
lua_settable(L, -3); lua_settable(L, -3);
} }
// Set subtable "times" // Set subtable "times"
@ -1195,11 +1186,10 @@ void push_tool_capabilities(lua_State *L,
//Create damage_groups table //Create damage_groups table
lua_newtable(L); lua_newtable(L);
// For each damage group // For each damage group
for (DamageGroup::const_iterator i = toolcap.damageGroups.begin(); for (const auto &damageGroup : toolcap.damageGroups) {
i != toolcap.damageGroups.end(); ++i) {
// Create damage group table // Create damage group table
lua_pushinteger(L, i->second); lua_pushinteger(L, damageGroup.second);
lua_setfield(L, -2, i->first.c_str()); lua_setfield(L, -2, damageGroup.first.c_str());
} }
lua_setfield(L, -2, "damage_groups"); lua_setfield(L, -2, "damage_groups");
} }
@ -1459,9 +1449,9 @@ void read_groups(lua_State *L, int index, ItemGroupList &result)
void push_groups(lua_State *L, const ItemGroupList &groups) void push_groups(lua_State *L, const ItemGroupList &groups)
{ {
lua_newtable(L); lua_newtable(L);
for (ItemGroupList::const_iterator it = groups.begin(); it != groups.end(); ++it) { for (const auto &group : groups) {
lua_pushnumber(L, it->second); lua_pushnumber(L, group.second);
lua_setfield(L, -2, it->first.c_str()); lua_setfield(L, -2, group.first.c_str());
} }
} }
@ -1572,9 +1562,8 @@ static int push_json_value_getdepth(const Json::Value &value)
return 1; return 1;
int maxdepth = 0; int maxdepth = 0;
for (Json::Value::const_iterator it = value.begin(); for (const auto &it : value) {
it != value.end(); ++it) { int elemdepth = push_json_value_getdepth(it);
int elemdepth = push_json_value_getdepth(*it);
if (elemdepth > maxdepth) if (elemdepth > maxdepth)
maxdepth = elemdepth; maxdepth = elemdepth;
} }
@ -1646,8 +1635,8 @@ bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
// of push_json_value_helper is 2, so make sure there a depth * 2 slots // of push_json_value_helper is 2, so make sure there a depth * 2 slots
if (lua_checkstack(L, depth * 2)) if (lua_checkstack(L, depth * 2))
return push_json_value_helper(L, value, nullindex); return push_json_value_helper(L, value, nullindex);
else
return false; return false;
} }
// Converts Lua table --> JSON // Converts Lua table --> JSON

@ -123,7 +123,6 @@ MapNode readnode (lua_State *L, int index,
void pushnode (lua_State *L, const MapNode &n, void pushnode (lua_State *L, const MapNode &n,
INodeDefManager *ndef); INodeDefManager *ndef);
NodeBox read_nodebox (lua_State *L, int index);
void read_groups (lua_State *L, int index, void read_groups (lua_State *L, int index,
ItemGroupList &result); ItemGroupList &result);
@ -159,9 +158,6 @@ std::vector<ItemStack> read_items (lua_State *L,
int index, int index,
Server* srv); Server* srv);
void read_soundspec (lua_State *L,
int index,
SimpleSoundSpec &spec);
void push_soundspec (lua_State *L, void push_soundspec (lua_State *L,
const SimpleSoundSpec &spec); const SimpleSoundSpec &spec);

@ -30,7 +30,7 @@ extern "C" {
#include "constants.h" #include "constants.h"
#define CHECK_TYPE(index, name, type) do { \ #define CHECK_TYPE(index, name, type) { \
int t = lua_type(L, (index)); \ int t = lua_type(L, (index)); \
if (t != (type)) { \ if (t != (type)) { \
std::string traceback = script_get_backtrace(L); \ std::string traceback = script_get_backtrace(L); \
@ -38,7 +38,7 @@ extern "C" {
" (expected " + lua_typename(L, (type)) + \ " (expected " + lua_typename(L, (type)) + \
" got " + lua_typename(L, t) + ").\n" + traceback); \ " got " + lua_typename(L, t) + ").\n" + traceback); \
} \ } \
} while(0) }
#define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER) #define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER)
#define CHECK_FLOAT_RANGE(value, name) \ #define CHECK_FLOAT_RANGE(value, name) \
if (value < F1000_MIN || value > F1000_MAX) { \ if (value < F1000_MIN || value > F1000_MAX) { \

@ -76,8 +76,6 @@ void setfloatfield(lua_State *L, int table,
const char *fieldname, float value); const char *fieldname, float value);
void setboolfield(lua_State *L, int table, void setboolfield(lua_State *L, int table,
const char *fieldname, bool value); const char *fieldname, bool value);
void setstringfield(lua_State *L, int table,
const char *fieldname, const char *value);
v3f checkFloatPos (lua_State *L, int index); v3f checkFloatPos (lua_State *L, int index);
v2f check_v2f (lua_State *L, int index); v2f check_v2f (lua_State *L, int index);

@ -58,12 +58,12 @@ extern "C" {
#define PUSH_ERROR_HANDLER(L) \ #define PUSH_ERROR_HANDLER(L) \
(lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L))) (lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L)))
#define PCALL_RESL(L, RES) do { \ #define PCALL_RESL(L, RES) { \
int result_ = (RES); \ int result_ = (RES); \
if (result_ != 0) { \ if (result_ != 0) { \
script_error((L), result_, NULL, __FUNCTION__); \ script_error((L), result_, NULL, __FUNCTION__); \
} \ } \
} while (0) }
#define script_run_callbacks(L, nargs, mode) \ #define script_run_callbacks(L, nargs, mode) \
script_run_callbacks_f((L), (nargs), (mode), __FUNCTION__) script_run_callbacks_f((L), (nargs), (mode), __FUNCTION__)

@ -17,8 +17,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/ */
#include <stdio.h> #include <cstdio>
#include <stdlib.h> #include <cstdlib>
extern "C" { extern "C" {
#include "lua.h" #include "lua.h"
@ -38,9 +38,8 @@ AsyncEngine::~AsyncEngine()
{ {
// Request all threads to stop // Request all threads to stop
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin(); for (AsyncWorkerThread *workerThread : workerThreads) {
it != workerThreads.end(); ++it) { workerThread->stop();
(*it)->stop();
} }
@ -51,15 +50,13 @@ AsyncEngine::~AsyncEngine()
} }
// Wait for threads to finish // Wait for threads to finish
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin(); for (AsyncWorkerThread *workerThread : workerThreads) {
it != workerThreads.end(); ++it) { workerThread->wait();
(*it)->wait();
} }
// Force kill all threads // Force kill all threads
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin(); for (AsyncWorkerThread *workerThread : workerThreads) {
it != workerThreads.end(); ++it) { delete workerThread;
delete *it;
} }
jobQueueMutex.lock(); jobQueueMutex.lock();
@ -192,9 +189,8 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) {
/******************************************************************************/ /******************************************************************************/
void AsyncEngine::prepareEnvironment(lua_State* L, int top) void AsyncEngine::prepareEnvironment(lua_State* L, int top)
{ {
for (std::vector<StateInitializer>::iterator it = stateInitializers.begin(); for (StateInitializer &stateInitializer : stateInitializers) {
it != stateInitializers.end(); it++) { stateInitializer(L, top);
(*it)(L, top);
} }
} }
@ -202,7 +198,6 @@ void AsyncEngine::prepareEnvironment(lua_State* L, int top)
AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher, AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
const std::string &name) : const std::string &name) :
Thread(name), Thread(name),
ScriptApiBase(),
jobDispatcher(jobDispatcher) jobDispatcher(jobDispatcher)
{ {
lua_State *L = getStack(); lua_State *L = getStack();

@ -68,7 +68,7 @@ class AsyncEngine {
friend class AsyncWorkerThread; friend class AsyncWorkerThread;
typedef void (*StateInitializer)(lua_State *L, int top); typedef void (*StateInitializer)(lua_State *L, int top);
public: public:
AsyncEngine() {}; AsyncEngine() = default;
~AsyncEngine(); ~AsyncEngine();
/** /**

@ -40,7 +40,7 @@ extern "C" {
#endif #endif
} }
#include <stdio.h> #include <cstdio>
#include <cstdarg> #include <cstdarg>
#include "script/common/c_content.h" #include "script/common/c_content.h"
#include <sstream> #include <sstream>

@ -40,12 +40,12 @@ extern "C" {
// use that name to bypass security! // use that name to bypass security!
#define BUILTIN_MOD_NAME "*builtin*" #define BUILTIN_MOD_NAME "*builtin*"
#define PCALL_RES(RES) do { \ #define PCALL_RES(RES) { \
int result_ = (RES); \ int result_ = (RES); \
if (result_ != 0) { \ if (result_ != 0) { \
scriptError(result_, __FUNCTION__); \ scriptError(result_, __FUNCTION__); \
} \ } \
} while (0) }
#define runCallbacks(nargs, mode) \ #define runCallbacks(nargs, mode) \
runCallbacksRaw((nargs), (mode), __FUNCTION__) runCallbacksRaw((nargs), (mode), __FUNCTION__)

@ -218,8 +218,7 @@ bool ScriptApiDetached::getDetachedInventoryCallback(
lua_getfield(L, -1, name.c_str()); lua_getfield(L, -1, name.c_str());
lua_remove(L, -2); lua_remove(L, -2);
// Should be a table // Should be a table
if(lua_type(L, -1) != LUA_TTABLE) if (lua_type(L, -1) != LUA_TTABLE) {
{
errorstream<<"Detached inventory \""<<name<<"\" not defined"<<std::endl; errorstream<<"Detached inventory \""<<name<<"\" not defined"<<std::endl;
lua_pop(L, 1); lua_pop(L, 1);
return false; return false;
@ -230,20 +229,17 @@ bool ScriptApiDetached::getDetachedInventoryCallback(
lua_getfield(L, -1, callbackname); lua_getfield(L, -1, callbackname);
lua_remove(L, -2); lua_remove(L, -2);
// Should be a function or nil // Should be a function or nil
if(lua_type(L, -1) == LUA_TFUNCTION) if (lua_type(L, -1) == LUA_TFUNCTION) {
{
return true; return true;
} }
else if(lua_isnil(L, -1))
{ if (lua_isnil(L, -1)) {
lua_pop(L, 1);
return false;
}
else
{
errorstream<<"Detached inventory \""<<name<<"\" callback \""
<<callbackname<<"\" is not a function"<<std::endl;
lua_pop(L, 1); lua_pop(L, 1);
return false; return false;
} }
errorstream << "Detached inventory \"" << name << "\" callback \""
<< callbackname << "\" is not a function" << std::endl;
lua_pop(L, 1);
return false;
} }

@ -113,12 +113,12 @@ bool ScriptApiItem::item_OnUse(ItemStack &item,
bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, ServerActiveObject *user) bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, ServerActiveObject *user)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L); int error_handler = PUSH_ERROR_HANDLER(L);
if (!getItemCallback(item.name.c_str(), "on_secondary_use")) if (!getItemCallback(item.name.c_str(), "on_secondary_use"))
return false; return false;
LuaItemStack::create(L, item); LuaItemStack::create(L, item);
objectrefGetOrCreate(L, user); objectrefGetOrCreate(L, user);
PointedThing pointed; PointedThing pointed;
@ -237,7 +237,9 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname)
// Should be a function or nil // Should be a function or nil
if (lua_type(L, -1) == LUA_TFUNCTION) { if (lua_type(L, -1) == LUA_TFUNCTION) {
return true; return true;
} else if (!lua_isnil(L, -1)) { }
if (!lua_isnil(L, -1)) {
errorstream << "Item \"" << name << "\" callback \"" errorstream << "Item \"" << name << "\" callback \""
<< callbackname << "\" is not a function" << std::endl; << callbackname << "\" is not a function" << std::endl;
} }

@ -93,12 +93,6 @@ struct EnumString ScriptApiNode::es_NodeBoxType[] =
{0, NULL}, {0, NULL},
}; };
ScriptApiNode::ScriptApiNode() {
}
ScriptApiNode::~ScriptApiNode() {
}
bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed) ServerActiveObject *puncher, PointedThing pointed)
{ {
@ -198,7 +192,7 @@ bool ScriptApiNode::node_on_flood(v3s16 p, MapNode node, MapNode newnode)
pushnode(L, newnode, ndef); pushnode(L, newnode, ndef);
PCALL_RES(lua_pcall(L, 3, 1, error_handler)); PCALL_RES(lua_pcall(L, 3, 1, error_handler));
lua_remove(L, error_handler); lua_remove(L, error_handler);
return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1) == true; return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1);
} }
void ScriptApiNode::node_after_destruct(v3s16 p, MapNode node) void ScriptApiNode::node_after_destruct(v3s16 p, MapNode node)
@ -237,7 +231,7 @@ bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime)
lua_pushnumber(L,dtime); lua_pushnumber(L,dtime);
PCALL_RES(lua_pcall(L, 2, 1, error_handler)); PCALL_RES(lua_pcall(L, 2, 1, error_handler));
lua_remove(L, error_handler); lua_remove(L, error_handler);
return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1) == true; return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1);
} }
void ScriptApiNode::node_on_receive_fields(v3s16 p, void ScriptApiNode::node_on_receive_fields(v3s16 p,

@ -32,8 +32,8 @@ class ScriptApiNode
public ScriptApiNodemeta public ScriptApiNodemeta
{ {
public: public:
ScriptApiNode(); ScriptApiNode() = default;
virtual ~ScriptApiNode(); virtual ~ScriptApiNode() = default;
bool node_on_punch(v3s16 p, MapNode node, bool node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed); ServerActiveObject *puncher, PointedThing pointed);

@ -232,12 +232,3 @@ void ScriptApiNodemeta::nodemeta_inventory_OnTake(v3s16 p,
PCALL_RES(lua_pcall(L, 5, 0, error_handler)); PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler lua_pop(L, 1); // Pop error handler
} }
ScriptApiNodemeta::ScriptApiNodemeta()
{
}
ScriptApiNodemeta::~ScriptApiNodemeta()
{
}

@ -30,8 +30,8 @@ class ScriptApiNodemeta
public ScriptApiItem public ScriptApiItem
{ {
public: public:
ScriptApiNodemeta(); ScriptApiNodemeta() = default;
virtual ~ScriptApiNodemeta(); virtual ~ScriptApiNodemeta() = default;
// Return number of accepted items to be moved // Return number of accepted items to be moved
int nodemeta_inventory_AllowMove(v3s16 p, int nodemeta_inventory_AllowMove(v3s16 p,

@ -192,8 +192,3 @@ void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player,
runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC); runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC);
} }
ScriptApiPlayer::~ScriptApiPlayer()
{
}

@ -28,7 +28,7 @@ struct ToolCapabilities;
class ScriptApiPlayer : virtual public ScriptApiBase class ScriptApiPlayer : virtual public ScriptApiBase
{ {
public: public:
virtual ~ScriptApiPlayer(); virtual ~ScriptApiPlayer() = default;
void on_newplayer(ServerActiveObject *player); void on_newplayer(ServerActiveObject *player);
void on_dieplayer(ServerActiveObject *player); void on_dieplayer(ServerActiveObject *player);

@ -260,7 +260,7 @@ void ScriptApiSecurity::initializeSecurityClient()
static const char *os_whitelist[] = { static const char *os_whitelist[] = {
"clock", "clock",
"date", "date",
"difftime", "difftime",
"time", "time",
"setlocale", "setlocale",
}; };
@ -504,7 +504,7 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
// by the operating system anyways. // by the operating system anyways.
return false; return false;
} }
removed = component + (removed.empty() ? "" : DIR_DELIM + removed); removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
abs_path = fs::AbsolutePath(cur_path); abs_path = fs::AbsolutePath(cur_path);
} }
if (abs_path.empty()) if (abs_path.empty())
@ -550,9 +550,9 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
// Allow read-only access to all mod directories // Allow read-only access to all mod directories
if (!write_required) { if (!write_required) {
const std::vector<ModSpec> mods = gamedef->getMods(); const std::vector<ModSpec> &mods = gamedef->getMods();
for (size_t i = 0; i < mods.size(); ++i) { for (const ModSpec &mod : mods) {
str = fs::AbsolutePath(mods[i].path); str = fs::AbsolutePath(mod.path);
if (!str.empty() && fs::PathStartsWith(abs_path, str)) { if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
return true; return true;
} }
@ -617,7 +617,9 @@ int ScriptApiSecurity::sl_g_load(lua_State *L)
int t = lua_type(L, -1); int t = lua_type(L, -1);
if (t == LUA_TNIL) { if (t == LUA_TNIL) {
break; break;
} else if (t != LUA_TSTRING) { }
if (t != LUA_TSTRING) {
lua_pushnil(L); lua_pushnil(L);
lua_pushliteral(L, "Loader didn't return a string"); lua_pushliteral(L, "Loader didn't return a string");
return 2; return 2;

@ -34,7 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/string.h" #include "util/string.h"
#include "nodedef.h" #include "nodedef.h"
int ModApiClient::l_get_current_modname(lua_State *L) int ModApiClient::l_get_current_modname(lua_State *L)
{ {
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);

@ -743,7 +743,7 @@ int ModApiEnvMod::l_find_node_near(lua_State *L)
for (int d = start_radius; d <= radius; d++) { for (int d = start_radius; d <= radius; d++) {
std::vector<v3s16> list = FacePositionCache::getFacePositions(d); std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
for (v3s16 i : list) { for (const v3s16 &i : list) {
v3s16 p = pos + i; v3s16 p = pos + i;
content_t c = env->getMap().getNodeNoEx(p).getContent(); content_t c = env->getMap().getNodeNoEx(p).getContent();
if (filter.count(c) != 0) { if (filter.count(c) != 0) {
@ -1127,7 +1127,7 @@ int ModApiEnvMod::l_find_path(lua_State *L)
lua_newtable(L); lua_newtable(L);
int top = lua_gettop(L); int top = lua_gettop(L);
unsigned int index = 1; unsigned int index = 1;
for (v3s16 i : path) { for (const v3s16 &i : path) {
lua_pushnumber(L,index); lua_pushnumber(L,index);
push_v3s16(L, i); push_v3s16(L, i);
lua_settable(L, top); lua_settable(L, top);

@ -495,28 +495,29 @@ int ModApiInventory::l_get_inventory(lua_State *L)
v3s16 pos = check_v3s16(L, -1); v3s16 pos = check_v3s16(L, -1);
loc.setNodeMeta(pos); loc.setNodeMeta(pos);
if(getServer(L)->getInventory(loc) != NULL) if (getServer(L)->getInventory(loc) != NULL)
InvRef::create(L, loc); InvRef::create(L, loc);
else else
lua_pushnil(L); lua_pushnil(L);
return 1; return 1;
} else {
NO_MAP_LOCK_REQUIRED;
if(type == "player"){
std::string name = checkstringfield(L, 1, "name");
loc.setPlayer(name);
} else if(type == "detached"){
std::string name = checkstringfield(L, 1, "name");
loc.setDetached(name);
}
if(getServer(L)->getInventory(loc) != NULL)
InvRef::create(L, loc);
else
lua_pushnil(L);
return 1;
// END NO_MAP_LOCK_REQUIRED;
} }
NO_MAP_LOCK_REQUIRED;
if (type == "player") {
std::string name = checkstringfield(L, 1, "name");
loc.setPlayer(name);
} else if (type == "detached") {
std::string name = checkstringfield(L, 1, "name");
loc.setDetached(name);
}
if (getServer(L)->getInventory(loc) != NULL)
InvRef::create(L, loc);
else
lua_pushnil(L);
return 1;
// END NO_MAP_LOCK_REQUIRED;
} }
// create_detached_inventory_raw(name, [player_name]) // create_detached_inventory_raw(name, [player_name])

@ -233,23 +233,22 @@ int ModApiMainMenu::l_get_worlds(lua_State *L)
int top = lua_gettop(L); int top = lua_gettop(L);
unsigned int index = 1; unsigned int index = 1;
for (unsigned int i = 0; i < worlds.size(); i++) for (const WorldSpec &world : worlds) {
{
lua_pushnumber(L,index); lua_pushnumber(L,index);
lua_newtable(L); lua_newtable(L);
int top_lvl2 = lua_gettop(L); int top_lvl2 = lua_gettop(L);
lua_pushstring(L,"path"); lua_pushstring(L,"path");
lua_pushstring(L,worlds[i].path.c_str()); lua_pushstring(L, world.path.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"name"); lua_pushstring(L,"name");
lua_pushstring(L,worlds[i].name.c_str()); lua_pushstring(L, world.name.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"gameid"); lua_pushstring(L,"gameid");
lua_pushstring(L,worlds[i].gameid.c_str()); lua_pushstring(L, world.gameid.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_settable(L, top); lua_settable(L, top);
@ -267,40 +266,38 @@ int ModApiMainMenu::l_get_games(lua_State *L)
int top = lua_gettop(L); int top = lua_gettop(L);
unsigned int index = 1; unsigned int index = 1;
for (unsigned int i = 0; i < games.size(); i++) for (const SubgameSpec &game : games) {
{
lua_pushnumber(L,index); lua_pushnumber(L,index);
lua_newtable(L); lua_newtable(L);
int top_lvl2 = lua_gettop(L); int top_lvl2 = lua_gettop(L);
lua_pushstring(L,"id"); lua_pushstring(L,"id");
lua_pushstring(L,games[i].id.c_str()); lua_pushstring(L, game.id.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"path"); lua_pushstring(L,"path");
lua_pushstring(L,games[i].path.c_str()); lua_pushstring(L, game.path.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"gamemods_path"); lua_pushstring(L,"gamemods_path");
lua_pushstring(L,games[i].gamemods_path.c_str()); lua_pushstring(L, game.gamemods_path.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"name"); lua_pushstring(L,"name");
lua_pushstring(L,games[i].name.c_str()); lua_pushstring(L, game.name.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"menuicon_path"); lua_pushstring(L,"menuicon_path");
lua_pushstring(L,games[i].menuicon_path.c_str()); lua_pushstring(L, game.menuicon_path.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
lua_pushstring(L,"addon_mods_paths"); lua_pushstring(L,"addon_mods_paths");
lua_newtable(L); lua_newtable(L);
int table2 = lua_gettop(L); int table2 = lua_gettop(L);
int internal_index=1; int internal_index=1;
for (std::set<std::string>::iterator iter = games[i].addon_mods_paths.begin(); for (const std::string &addon_mods_path : game.addon_mods_paths) {
iter != games[i].addon_mods_paths.end(); ++iter) {
lua_pushnumber(L,internal_index); lua_pushnumber(L,internal_index);
lua_pushstring(L,(*iter).c_str()); lua_pushstring(L, addon_mods_path.c_str());
lua_settable(L, table2); lua_settable(L, table2);
internal_index++; internal_index++;
} }
@ -331,112 +328,111 @@ int ModApiMainMenu::l_get_favorites(lua_State *L)
int top = lua_gettop(L); int top = lua_gettop(L);
unsigned int index = 1; unsigned int index = 1;
for (unsigned int i = 0; i < servers.size(); i++) for (const Json::Value &server : servers) {
{
lua_pushnumber(L,index); lua_pushnumber(L,index);
lua_newtable(L); lua_newtable(L);
int top_lvl2 = lua_gettop(L); int top_lvl2 = lua_gettop(L);
if (servers[i]["clients"].asString().size()) { if (!server["clients"].asString().empty()) {
std::string clients_raw = servers[i]["clients"].asString(); std::string clients_raw = server["clients"].asString();
char* endptr = 0; char* endptr = 0;
int numbervalue = strtol(clients_raw.c_str(),&endptr,10); int numbervalue = strtol(clients_raw.c_str(),&endptr,10);
if ((clients_raw != "") && (*endptr == 0)) { if ((!clients_raw.empty()) && (*endptr == 0)) {
lua_pushstring(L,"clients"); lua_pushstring(L,"clients");
lua_pushnumber(L,numbervalue); lua_pushnumber(L,numbervalue);
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
} }
if (servers[i]["clients_max"].asString().size()) { if (!server["clients_max"].asString().empty()) {
std::string clients_max_raw = servers[i]["clients_max"].asString(); std::string clients_max_raw = server["clients_max"].asString();
char* endptr = 0; char* endptr = 0;
int numbervalue = strtol(clients_max_raw.c_str(),&endptr,10); int numbervalue = strtol(clients_max_raw.c_str(),&endptr,10);
if ((clients_max_raw != "") && (*endptr == 0)) { if ((!clients_max_raw.empty()) && (*endptr == 0)) {
lua_pushstring(L,"clients_max"); lua_pushstring(L,"clients_max");
lua_pushnumber(L,numbervalue); lua_pushnumber(L,numbervalue);
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
} }
if (servers[i]["version"].asString().size()) { if (!server["version"].asString().empty()) {
lua_pushstring(L,"version"); lua_pushstring(L,"version");
std::string topush = servers[i]["version"].asString(); std::string topush = server["version"].asString();
lua_pushstring(L,topush.c_str()); lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["proto_min"].asString().size()) { if (!server["proto_min"].asString().empty()) {
lua_pushstring(L,"proto_min"); lua_pushstring(L,"proto_min");
lua_pushinteger(L,servers[i]["proto_min"].asInt()); lua_pushinteger(L, server["proto_min"].asInt());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["proto_max"].asString().size()) { if (!server["proto_max"].asString().empty()) {
lua_pushstring(L,"proto_max"); lua_pushstring(L,"proto_max");
lua_pushinteger(L,servers[i]["proto_max"].asInt()); lua_pushinteger(L, server["proto_max"].asInt());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["password"].asString().size()) { if (!server["password"].asString().empty()) {
lua_pushstring(L,"password"); lua_pushstring(L,"password");
lua_pushboolean(L,servers[i]["password"].asBool()); lua_pushboolean(L, server["password"].asBool());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["creative"].asString().size()) { if (!server["creative"].asString().empty()) {
lua_pushstring(L,"creative"); lua_pushstring(L,"creative");
lua_pushboolean(L,servers[i]["creative"].asBool()); lua_pushboolean(L, server["creative"].asBool());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["damage"].asString().size()) { if (!server["damage"].asString().empty()) {
lua_pushstring(L,"damage"); lua_pushstring(L,"damage");
lua_pushboolean(L,servers[i]["damage"].asBool()); lua_pushboolean(L, server["damage"].asBool());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["pvp"].asString().size()) { if (!server["pvp"].asString().empty()) {
lua_pushstring(L,"pvp"); lua_pushstring(L,"pvp");
lua_pushboolean(L,servers[i]["pvp"].asBool()); lua_pushboolean(L, server["pvp"].asBool());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["description"].asString().size()) { if (!server["description"].asString().empty()) {
lua_pushstring(L,"description"); lua_pushstring(L,"description");
std::string topush = servers[i]["description"].asString(); std::string topush = server["description"].asString();
lua_pushstring(L,topush.c_str()); lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["name"].asString().size()) { if (!server["name"].asString().empty()) {
lua_pushstring(L,"name"); lua_pushstring(L,"name");
std::string topush = servers[i]["name"].asString(); std::string topush = server["name"].asString();
lua_pushstring(L,topush.c_str()); lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["address"].asString().size()) { if (!server["address"].asString().empty()) {
lua_pushstring(L,"address"); lua_pushstring(L,"address");
std::string topush = servers[i]["address"].asString(); std::string topush = server["address"].asString();
lua_pushstring(L,topush.c_str()); lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i]["port"].asString().size()) { if (!server["port"].asString().empty()) {
lua_pushstring(L,"port"); lua_pushstring(L,"port");
std::string topush = servers[i]["port"].asString(); std::string topush = server["port"].asString();
lua_pushstring(L,topush.c_str()); lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
} }
if (servers[i].isMember("ping")) { if (server.isMember("ping")) {
float ping = servers[i]["ping"].asFloat(); float ping = server["ping"].asFloat();
lua_pushstring(L, "ping"); lua_pushstring(L, "ping");
lua_pushnumber(L, ping); lua_pushnumber(L, ping);
lua_settable(L, top_lvl2); lua_settable(L, top_lvl2);
@ -558,7 +554,7 @@ int ModApiMainMenu::l_set_topleft_text(lua_State *L)
GUIEngine* engine = getGuiEngine(L); GUIEngine* engine = getGuiEngine(L);
sanity_check(engine != NULL); sanity_check(engine != NULL);
std::string text = ""; std::string text;
if (!lua_isnone(L,1) && !lua_isnil(L,1)) if (!lua_isnone(L,1) && !lua_isnil(L,1))
text = luaL_checkstring(L, 1); text = luaL_checkstring(L, 1);

@ -847,9 +847,8 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L)
lua_newtable(L); lua_newtable(L);
int i = 1; int i = 1;
for (std::set<u32>::iterator it = emerge->gen_notify_on_deco_ids.begin(); for (u32 gen_notify_on_deco_id : emerge->gen_notify_on_deco_ids) {
it != emerge->gen_notify_on_deco_ids.end(); ++it) { lua_pushnumber(L, gen_notify_on_deco_id);
lua_pushnumber(L, *it);
lua_rawseti(L, -2, i); lua_rawseti(L, -2, i);
i++; i++;
} }
@ -1322,7 +1321,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L)
lua_pop(L, 1); lua_pop(L, 1);
u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
prob_list.push_back(std::make_pair(pos, prob)); prob_list.emplace_back(pos, prob);
} }
lua_pop(L, 1); lua_pop(L, 1);
@ -1336,7 +1335,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L)
if (lua_istable(L, -1)) { if (lua_istable(L, -1)) {
s16 ypos = getintfield_default(L, -1, "ypos", 0); s16 ypos = getintfield_default(L, -1, "ypos", 0);
u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
slice_prob_list.push_back(std::make_pair(ypos, prob)); slice_prob_list.emplace_back(ypos, prob);
} }
lua_pop(L, 1); lua_pop(L, 1);

@ -218,10 +218,9 @@ void MetaDataRef::handleToTable(lua_State *L, Metadata *meta)
lua_newtable(L); lua_newtable(L);
{ {
const StringMap &fields = meta->getStrings(); const StringMap &fields = meta->getStrings();
for (StringMap::const_iterator for (const auto &field : fields) {
it = fields.begin(); it != fields.end(); ++it) { const std::string &name = field.first;
const std::string &name = it->first; const std::string &value = field.second;
const std::string &value = it->second;
lua_pushlstring(L, name.c_str(), name.size()); lua_pushlstring(L, name.c_str(), name.size());
lua_pushlstring(L, value.c_str(), value.size()); lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3); lua_settable(L, -3);

@ -31,7 +31,7 @@ class Metadata;
class MetaDataRef : public ModApiBase class MetaDataRef : public ModApiBase
{ {
public: public:
virtual ~MetaDataRef() {} virtual ~MetaDataRef() = default;
protected: protected:
static MetaDataRef *checkobject(lua_State *L, int narg); static MetaDataRef *checkobject(lua_State *L, int narg);

@ -551,7 +551,7 @@ int ObjectRef::l_get_local_animation(lua_State *L)
float frame_speed; float frame_speed;
player->getLocalAnimations(frames, &frame_speed); player->getLocalAnimations(frames, &frame_speed);
for (v2s32 frame : frames) { for (const v2s32 &frame : frames) {
push_v2s32(L, frame); push_v2s32(L, frame);
} }

@ -32,8 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "lua_api/l_localplayer.h" #include "lua_api/l_localplayer.h"
#include "lua_api/l_camera.h" #include "lua_api/l_camera.h"
ClientScripting::ClientScripting(Client *client): ClientScripting::ClientScripting(Client *client)
ScriptApiBase()
{ {
setGameDef(client); setGameDef(client);
setType(ScriptingType::Client); setType(ScriptingType::Client);

@ -460,7 +460,7 @@ void Sky::render()
driver->drawVertexPrimitiveList(vertices, SKY_STAR_COUNT * 4, driver->drawVertexPrimitiveList(vertices, SKY_STAR_COUNT * 4,
indices, SKY_STAR_COUNT, video::EVT_STANDARD, indices, SKY_STAR_COUNT, video::EVT_STANDARD,
scene::EPT_QUADS, video::EIT_16BIT); scene::EPT_QUADS, video::EIT_16BIT);
} while(0); } while(false);
// Draw far cloudy fog thing below east and west horizons // Draw far cloudy fog thing below east and west horizons
for (u32 j = 0; j < 2; j++) { for (u32 j = 0; j < 2; j++) {

@ -39,7 +39,7 @@ struct SimpleSoundSpec
{ {
} }
bool exists() const { return name != ""; } bool exists() const { return !name.empty(); }
std::string name = ""; std::string name = "";
float gain = 1.0f; float gain = 1.0f;
@ -50,7 +50,8 @@ struct SimpleSoundSpec
class ISoundManager class ISoundManager
{ {
public: public:
virtual ~ISoundManager() {} virtual ~ISoundManager() = default;
// Multiple sounds can be loaded per name; when played, the sound // Multiple sounds can be loaded per name; when played, the sound
// should be chosen randomly from alternatives // should be chosen randomly from alternatives
// Return value determines success/failure // Return value determines success/failure
@ -80,7 +81,7 @@ public:
{ {
return playSound(spec.name, loop, spec.gain, spec.fade, spec.pitch); return playSound(spec.name, loop, spec.gain, spec.fade, spec.pitch);
} }
int playSoundAt(const SimpleSoundSpec &spec, bool loop, v3f pos) int playSoundAt(const SimpleSoundSpec &spec, bool loop, const v3f &pos)
{ {
return playSoundAt(spec.name, loop, spec.gain, pos, spec.pitch); return playSoundAt(spec.name, loop, spec.gain, pos, spec.pitch);
} }

@ -275,7 +275,8 @@ private:
std::unordered_map<int, PlayingSound*> m_sounds_playing; std::unordered_map<int, PlayingSound*> m_sounds_playing;
v3f m_listener_pos; v3f m_listener_pos;
struct FadeState { struct FadeState {
FadeState() {} FadeState() = default;
FadeState(float step, float current_gain, float target_gain): FadeState(float step, float current_gain, float target_gain):
step(step), step(step),
current_gain(current_gain), current_gain(current_gain),
@ -351,13 +352,12 @@ public:
alcCloseDevice(m_device); alcCloseDevice(m_device);
m_device = NULL; m_device = NULL;
for (std::unordered_map<std::string, std::vector<SoundBuffer*>>::iterator i = for (auto &buffer : m_buffers) {
m_buffers.begin(); i != m_buffers.end(); ++i) { for (std::vector<SoundBuffer*>::iterator iter = buffer.second.begin();
for (std::vector<SoundBuffer*>::iterator iter = (*i).second.begin(); iter != buffer.second.end(); ++iter) {
iter != (*i).second.end(); ++iter) {
delete *iter; delete *iter;
} }
(*i).second.clear(); buffer.second.clear();
} }
m_buffers.clear(); m_buffers.clear();
infostream<<"Audio: Deinitialized."<<std::endl; infostream<<"Audio: Deinitialized."<<std::endl;
@ -379,7 +379,6 @@ public:
std::vector<SoundBuffer*> bufs; std::vector<SoundBuffer*> bufs;
bufs.push_back(buf); bufs.push_back(buf);
m_buffers[name] = bufs; m_buffers[name] = bufs;
return;
} }
SoundBuffer* getBuffer(const std::string &name) SoundBuffer* getBuffer(const std::string &name)
@ -450,7 +449,8 @@ public:
return id; return id;
} }
int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, v3f pos, float pitch) int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, const v3f &pos,
float pitch)
{ {
assert(buf); assert(buf);
PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos, pitch); PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos, pitch);
@ -485,13 +485,11 @@ public:
std::set<std::string> paths; std::set<std::string> paths;
std::set<std::string> datas; std::set<std::string> datas;
m_fetcher->fetchSounds(name, paths, datas); m_fetcher->fetchSounds(name, paths, datas);
for(std::set<std::string>::iterator i = paths.begin(); for (const std::string &path : paths) {
i != paths.end(); ++i){ loadSoundFile(name, path);
loadSoundFile(name, *i);
} }
for(std::set<std::string>::iterator i = datas.begin(); for (const std::string &data : datas) {
i != datas.end(); ++i){ loadSoundData(name, data);
loadSoundData(name, *i);
} }
return getBuffer(name); return getBuffer(name);
} }
@ -503,10 +501,9 @@ public:
<<m_sounds_playing.size()<<" playing sounds, " <<m_sounds_playing.size()<<" playing sounds, "
<<m_buffers.size()<<" sound names loaded"<<std::endl; <<m_buffers.size()<<" sound names loaded"<<std::endl;
std::set<int> del_list; std::set<int> del_list;
for(std::unordered_map<int, PlayingSound*>::iterator i = m_sounds_playing.begin(); for (auto &sp : m_sounds_playing) {
i != m_sounds_playing.end(); ++i) { int id = sp.first;
int id = i->first; PlayingSound *sound = sp.second;
PlayingSound *sound = i->second;
// If not playing, remove it // If not playing, remove it
{ {
ALint state; ALint state;
@ -519,10 +516,8 @@ public:
if(!del_list.empty()) if(!del_list.empty())
verbosestream<<"OpenALSoundManager::maintain(): deleting " verbosestream<<"OpenALSoundManager::maintain(): deleting "
<<del_list.size()<<" playing sounds"<<std::endl; <<del_list.size()<<" playing sounds"<<std::endl;
for(std::set<int>::iterator i = del_list.begin(); for (int i : del_list) {
i != del_list.end(); ++i) deleteSound(i);
{
deleteSound(*i);
} }
} }
@ -566,7 +561,7 @@ public:
int playSound(const std::string &name, bool loop, float volume, float fade, float pitch) int playSound(const std::string &name, bool loop, float volume, float fade, float pitch)
{ {
maintain(); maintain();
if(name == "") if (name.empty())
return 0; return 0;
SoundBuffer *buf = getFetchBuffer(name); SoundBuffer *buf = getFetchBuffer(name);
if(!buf){ if(!buf){
@ -587,7 +582,7 @@ public:
int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch) int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch)
{ {
maintain(); maintain();
if(name == "") if (name.empty())
return 0; return 0;
SoundBuffer *buf = getFetchBuffer(name); SoundBuffer *buf = getFetchBuffer(name);
if(!buf){ if(!buf){

@ -59,17 +59,12 @@ void StaticObjectList::serialize(std::ostream &os)
} }
writeU16(os, count); writeU16(os, count);
for(std::vector<StaticObject>::iterator for (StaticObject &s_obj : m_stored) {
i = m_stored.begin();
i != m_stored.end(); ++i) {
StaticObject &s_obj = *i;
s_obj.serialize(os); s_obj.serialize(os);
} }
for(std::map<u16, StaticObject>::iterator
i = m_active.begin(); for (auto &i : m_active) {
i != m_active.end(); ++i) StaticObject s_obj = i.second;
{
StaticObject s_obj = i->second;
s_obj.serialize(os); s_obj.serialize(os);
} }
} }

@ -32,8 +32,8 @@ struct StaticObject
v3f pos; v3f pos;
std::string data; std::string data;
StaticObject() {} StaticObject() = default;
StaticObject(u8 type_, v3f pos_, const std::string &data_): StaticObject(u8 type_, const v3f &pos_, const std::string &data_):
type(type_), type(type_),
pos(pos_), pos(pos_),
data(data_) data(data_)
@ -51,7 +51,7 @@ public:
Inserts an object to the container. Inserts an object to the container.
Id must be unique (active) or 0 (stored). Id must be unique (active) or 0 (stored).
*/ */
void insert(u16 id, StaticObject obj) void insert(u16 id, const StaticObject &obj)
{ {
if(id == 0) if(id == 0)
{ {

@ -71,7 +71,7 @@ std::string getSubgamePathEnv()
SubgameSpec findSubgame(const std::string &id) SubgameSpec findSubgame(const std::string &id)
{ {
if(id == "") if (id.empty())
return SubgameSpec(); return SubgameSpec();
std::string share = porting::path_share; std::string share = porting::path_share;
std::string user = porting::path_user; std::string user = porting::path_user;
@ -81,32 +81,27 @@ SubgameSpec findSubgame(const std::string &id)
while (!search_paths.at_end()) { while (!search_paths.at_end()) {
std::string path = search_paths.next(PATH_DELIM); std::string path = search_paths.next(PATH_DELIM);
find_paths.push_back(GameFindPath( find_paths.emplace_back(path + DIR_DELIM + id, false);
path + DIR_DELIM + id, false)); find_paths.emplace_back(path + DIR_DELIM + id + "_game", false);
find_paths.push_back(GameFindPath(
path + DIR_DELIM + id + "_game", false));
} }
find_paths.push_back(GameFindPath( find_paths.emplace_back(user + DIR_DELIM + "games" + DIR_DELIM + id + "_game", true);
user + DIR_DELIM + "games" + DIR_DELIM + id + "_game", true)); find_paths.emplace_back(user + DIR_DELIM + "games" + DIR_DELIM + id, true);
find_paths.push_back(GameFindPath( find_paths.emplace_back(share + DIR_DELIM + "games" + DIR_DELIM + id + "_game",
user + DIR_DELIM + "games" + DIR_DELIM + id, true)); false);
find_paths.push_back(GameFindPath( find_paths.emplace_back(share + DIR_DELIM + "games" + DIR_DELIM + id, false);
share + DIR_DELIM + "games" + DIR_DELIM + id + "_game", false));
find_paths.push_back(GameFindPath(
share + DIR_DELIM + "games" + DIR_DELIM + id, false));
// Find game directory // Find game directory
std::string game_path; std::string game_path;
bool user_game = true; // Game is in user's directory bool user_game = true; // Game is in user's directory
for(u32 i=0; i<find_paths.size(); i++){ for (const GameFindPath &find_path : find_paths) {
const std::string &try_path = find_paths[i].path; const std::string &try_path = find_path.path;
if(fs::PathExists(try_path)){ if (fs::PathExists(try_path)) {
game_path = try_path; game_path = try_path;
user_game = find_paths[i].user_specific; user_game = find_path.user_specific;
break; break;
} }
} }
if(game_path == "") if (game_path.empty())
return SubgameSpec(); return SubgameSpec();
std::string gamemod_path = game_path + DIR_DELIM + "mods"; std::string gamemod_path = game_path + DIR_DELIM + "mods";
// Find mod directories // Find mod directories
@ -116,7 +111,7 @@ SubgameSpec findSubgame(const std::string &id)
if(user != share || user_game) if(user != share || user_game)
mods_paths.insert(user + DIR_DELIM + "mods"); mods_paths.insert(user + DIR_DELIM + "mods");
std::string game_name = getGameName(game_path); std::string game_name = getGameName(game_path);
if(game_name == "") if (game_name.empty())
game_name = id; game_name = id;
std::string menuicon_path; std::string menuicon_path;
#ifndef SERVER #ifndef SERVER
@ -137,7 +132,7 @@ SubgameSpec findWorldSubgame(const std::string &world_path)
gamespec.path = world_gamepath; gamespec.path = world_gamepath;
gamespec.gamemods_path= world_gamepath + DIR_DELIM + "mods"; gamespec.gamemods_path= world_gamepath + DIR_DELIM + "mods";
gamespec.name = getGameName(world_gamepath); gamespec.name = getGameName(world_gamepath);
if(gamespec.name == "") if (gamespec.name.empty())
gamespec.name = "unknown"; gamespec.name = "unknown";
return gamespec; return gamespec;
} }
@ -156,23 +151,22 @@ std::set<std::string> getAvailableGameIds()
while (!search_paths.at_end()) while (!search_paths.at_end())
gamespaths.insert(search_paths.next(PATH_DELIM)); gamespaths.insert(search_paths.next(PATH_DELIM));
for (std::set<std::string>::const_iterator i = gamespaths.begin(); for (const std::string &gamespath : gamespaths) {
i != gamespaths.end(); ++i){ std::vector<fs::DirListNode> dirlist = fs::GetDirListing(gamespath);
std::vector<fs::DirListNode> dirlist = fs::GetDirListing(*i); for (const fs::DirListNode &dln : dirlist) {
for(u32 j=0; j<dirlist.size(); j++){ if(!dln.dir)
if(!dirlist[j].dir)
continue; continue;
// If configuration file is not found or broken, ignore game // If configuration file is not found or broken, ignore game
Settings conf; Settings conf;
if(!getGameConfig(*i + DIR_DELIM + dirlist[j].name, conf)) if(!getGameConfig(gamespath + DIR_DELIM + dln.name, conf))
continue; continue;
// Add it to result // Add it to result
const char *ends[] = {"_game", NULL}; const char *ends[] = {"_game", NULL};
std::string shorter = removeStringEnd(dirlist[j].name, ends); std::string shorter = removeStringEnd(dln.name, ends);
if(shorter != "") if (!shorter.empty())
gameids.insert(shorter); gameids.insert(shorter);
else else
gameids.insert(dirlist[j].name); gameids.insert(dln.name);
} }
} }
return gameids; return gameids;
@ -182,9 +176,8 @@ std::vector<SubgameSpec> getAvailableGames()
{ {
std::vector<SubgameSpec> specs; std::vector<SubgameSpec> specs;
std::set<std::string> gameids = getAvailableGameIds(); std::set<std::string> gameids = getAvailableGameIds();
for(std::set<std::string>::const_iterator i = gameids.begin(); for (const auto &gameid : gameids)
i != gameids.end(); ++i) specs.push_back(findSubgame(gameid));
specs.push_back(findSubgame(*i));
return specs; return specs;
} }
@ -235,15 +228,14 @@ std::vector<WorldSpec> getAvailableWorlds()
worldspaths.insert(porting::path_user + DIR_DELIM + "worlds"); worldspaths.insert(porting::path_user + DIR_DELIM + "worlds");
infostream << "Searching worlds..." << std::endl; infostream << "Searching worlds..." << std::endl;
for (std::set<std::string>::const_iterator i = worldspaths.begin(); for (const std::string &worldspath : worldspaths) {
i != worldspaths.end(); ++i) { infostream << " In " << worldspath << ": " <<std::endl;
infostream << " In " << (*i) << ": " <<std::endl; std::vector<fs::DirListNode> dirvector = fs::GetDirListing(worldspath);
std::vector<fs::DirListNode> dirvector = fs::GetDirListing(*i); for (const fs::DirListNode &dln : dirvector) {
for(u32 j=0; j<dirvector.size(); j++){ if(!dln.dir)
if(!dirvector[j].dir)
continue; continue;
std::string fullpath = *i + DIR_DELIM + dirvector[j].name; std::string fullpath = worldspath + DIR_DELIM + dln.name;
std::string name = dirvector[j].name; std::string name = dln.name;
// Just allow filling in the gameid always for now // Just allow filling in the gameid always for now
bool can_be_legacy = true; bool can_be_legacy = true;
std::string gameid = getWorldGameId(fullpath, can_be_legacy); std::string gameid = getWorldGameId(fullpath, can_be_legacy);
@ -267,7 +259,7 @@ std::vector<WorldSpec> getAvailableWorlds()
WorldSpec spec(fullpath, name, gameid); WorldSpec spec(fullpath, name, gameid);
infostream<<"Old world found."<<std::endl; infostream<<"Old world found."<<std::endl;
worlds.push_back(spec); worlds.push_back(spec);
}while(0); }while(false);
infostream<<worlds.size()<<" found."<<std::endl; infostream<<worlds.size()<<" found."<<std::endl;
return worlds; return worlds;
} }

@ -50,7 +50,7 @@ struct SubgameSpec
bool isValid() const bool isValid() const
{ {
return (id != "" && path != ""); return (!id.empty() && !path.empty());
} }
}; };
@ -89,7 +89,7 @@ struct WorldSpec
bool isValid() const bool isValid() const
{ {
return (name != "" && path != "" && gameid != ""); return (!name.empty() && !path.empty() && !gameid.empty());
} }
}; };

@ -348,7 +348,8 @@ void TerminalChatConsole::step(int ch)
std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first)); std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first));
if (!g_settings->getBool("disable_escape_sequences")) { if (!g_settings->getBool("disable_escape_sequences")) {
error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)"; error_message = std::wstring(L"\x1b(c@red)").append(error_message)
.append(L"\x1b(c@white)");
} }
m_chat_backend.addMessage(error_message, utf8_to_wide(p.second)); m_chat_backend.addMessage(error_message, utf8_to_wide(p.second));
} }
@ -439,8 +440,7 @@ void TerminalChatConsole::draw_text()
const ChatFormattedLine& line = buf.getFormattedLine(row); const ChatFormattedLine& line = buf.getFormattedLine(row);
if (line.fragments.empty()) if (line.fragments.empty())
continue; continue;
for (u32 i = 0; i < line.fragments.size(); ++i) { for (const ChatFormattedFragment &fragment : line.fragments) {
const ChatFormattedFragment& fragment = line.fragments[i];
addstr(wide_to_utf8(fragment.text.getString()).c_str()); addstr(wide_to_utf8(fragment.text.getString()).c_str());
} }
} }

@ -31,26 +31,24 @@ void ToolCapabilities::serialize(std::ostream &os, u16 protocol_version) const
writeF1000(os, full_punch_interval); writeF1000(os, full_punch_interval);
writeS16(os, max_drop_level); writeS16(os, max_drop_level);
writeU32(os, groupcaps.size()); writeU32(os, groupcaps.size());
for (ToolGCMap::const_iterator i = groupcaps.begin(); i != groupcaps.end(); ++i) { for (const auto &groupcap : groupcaps) {
const std::string *name = &i->first; const std::string *name = &groupcap.first;
const ToolGroupCap *cap = &i->second; const ToolGroupCap *cap = &groupcap.second;
os << serializeString(*name); os << serializeString(*name);
writeS16(os, cap->uses); writeS16(os, cap->uses);
writeS16(os, cap->maxlevel); writeS16(os, cap->maxlevel);
writeU32(os, cap->times.size()); writeU32(os, cap->times.size());
for (std::unordered_map<int, float>::const_iterator for (const auto &time : cap->times) {
j = cap->times.begin(); j != cap->times.end(); ++j) { writeS16(os, time.first);
writeS16(os, j->first); writeF1000(os, time.second);
writeF1000(os, j->second);
} }
} }
writeU32(os, damageGroups.size()); writeU32(os, damageGroups.size());
for (DamageGroup::const_iterator i = damageGroups.begin(); for (const auto &damageGroup : damageGroups) {
i != damageGroups.end(); ++i) { os << serializeString(damageGroup.first);
os << serializeString(i->first); writeS16(os, damageGroup.second);
writeS16(os, i->second);
} }
} }
@ -107,15 +105,14 @@ DigParams getDigParams(const ItemGroupList &groups,
bool result_diggable = false; bool result_diggable = false;
float result_time = 0.0; float result_time = 0.0;
float result_wear = 0.0; float result_wear = 0.0;
std::string result_main_group = ""; std::string result_main_group;
int level = itemgroup_get(groups, "level"); int level = itemgroup_get(groups, "level");
//infostream<<"level="<<level<<std::endl; //infostream<<"level="<<level<<std::endl;
for (ToolGCMap::const_iterator i = tp->groupcaps.begin(); for (const auto &groupcap : tp->groupcaps) {
i != tp->groupcaps.end(); ++i) { const std::string &name = groupcap.first;
const std::string &name = i->first;
//infostream<<"group="<<name<<std::endl; //infostream<<"group="<<name<<std::endl;
const ToolGroupCap &cap = i->second; const ToolGroupCap &cap = groupcap.second;
int rating = itemgroup_get(groups, name); int rating = itemgroup_get(groups, name);
float time = 0; float time = 0;
bool time_exists = cap.getTime(rating, &time); bool time_exists = cap.getTime(rating, &time);
@ -159,14 +156,14 @@ HitParams getHitParams(const ItemGroupList &armor_groups,
s16 damage = 0; s16 damage = 0;
float full_punch_interval = tp->full_punch_interval; float full_punch_interval = tp->full_punch_interval;
for (DamageGroup::const_iterator i = tp->damageGroups.begin(); for (const auto &damageGroup : tp->damageGroups) {
i != tp->damageGroups.end(); ++i) { s16 armor = itemgroup_get(armor_groups, damageGroup.first);
s16 armor = itemgroup_get(armor_groups, i->first); damage += damageGroup.second
damage += i->second * rangelim(time_from_last_punch / full_punch_interval, 0.0, 1.0) * rangelim(time_from_last_punch / full_punch_interval, 0.0, 1.0)
* armor / 100.0; * armor / 100.0;
} }
return HitParams(damage, 0); return {damage, 0};
} }
HitParams getHitParams(const ItemGroupList &armor_groups, HitParams getHitParams(const ItemGroupList &armor_groups,
@ -183,12 +180,13 @@ PunchDamageResult getPunchDamage(
){ ){
bool do_hit = true; bool do_hit = true;
{ {
if(do_hit && punchitem){ if (do_hit && punchitem) {
if(itemgroup_get(armor_groups, "punch_operable") && if (itemgroup_get(armor_groups, "punch_operable") &&
(toolcap == NULL || punchitem->name == "")) (toolcap == NULL || punchitem->name.empty()))
do_hit = false; do_hit = false;
} }
if(do_hit){
if (do_hit) {
if(itemgroup_get(armor_groups, "immortal")) if(itemgroup_get(armor_groups, "immortal"))
do_hit = false; do_hit = false;
} }

@ -30,7 +30,7 @@ struct ToolGroupCap
int maxlevel = 1; int maxlevel = 1;
int uses = 20; int uses = 20;
ToolGroupCap() {} ToolGroupCap() = default;
bool getTime(int rating, float *time) const bool getTime(int rating, float *time) const
{ {
@ -118,7 +118,7 @@ struct PunchDamageResult
int damage = 0; int damage = 0;
int wear = 0; int wear = 0;
PunchDamageResult() {} PunchDamageResult() = default;
}; };
struct ItemStack; struct ItemStack;

@ -37,8 +37,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
using namespace irr::core; using namespace irr::core;
extern Settings *g_settings;
const char** touchgui_button_imagenames = (const char*[]) { const char** touchgui_button_imagenames = (const char*[]) {
"up_arrow.png", "up_arrow.png",
"down_arrow.png", "down_arrow.png",
@ -356,7 +354,7 @@ void AutoHideButtonBar::step(float dtime)
void AutoHideButtonBar::deactivate() void AutoHideButtonBar::deactivate()
{ {
if (m_visible == true) { if (m_visible) {
m_starter.guibutton->setVisible(true); m_starter.guibutton->setVisible(true);
m_starter.guibutton->setEnabled(true); m_starter.guibutton->setEnabled(true);
} }

@ -93,7 +93,7 @@ void make_tree(MMVManip &vmanip, v3s16 p0,
u32 vi = vmanip.m_area.index(pmin + p1); u32 vi = vmanip.m_area.index(pmin + p1);
for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) {
v3s16 p(x, y, z); v3s16 p(x, y, z);
if (vmanip.m_area.contains(p + p1) == true && if (vmanip.m_area.contains(p + p1) &&
(vmanip.m_data[vi].getContent() == CONTENT_AIR || (vmanip.m_data[vi].getContent() == CONTENT_AIR ||
vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) { vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) {
if (leaves_d[i] == 1) { if (leaves_d[i] == 1) {
@ -131,10 +131,8 @@ treegen::error spawn_ltree(ServerEnvironment *env, v3s16 p0,
// Send a MEET_OTHER event // Send a MEET_OTHER event
MapEditEvent event; MapEditEvent event;
event.type = MEET_OTHER; event.type = MEET_OTHER;
for (std::map<v3s16, MapBlock*>::iterator for (auto &modified_block : modified_blocks)
i = modified_blocks.begin(); event.modified_blocks.insert(modified_block.first);
i != modified_blocks.end(); ++i)
event.modified_blocks.insert(i->first);
map->dispatchEvent(&event); map->dispatchEvent(&event);
return SUCCESS; return SUCCESS;
} }
@ -182,7 +180,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0,
//generate axiom //generate axiom
std::string axiom = tree_definition.initial_axiom; std::string axiom = tree_definition.initial_axiom;
for (s16 i = 0; i < iterations; i++) { for (s16 i = 0; i < iterations; i++) {
std::string temp = ""; std::string temp;
for (s16 j = 0; j < (s16)axiom.size(); j++) { for (s16 j = 0; j < (s16)axiom.size(); j++) {
char axiom_char = axiom.at(j); char axiom_char = axiom.at(j);
switch (axiom_char) { switch (axiom_char) {
@ -403,7 +401,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0,
v3f(position.X, position.Y, position.Z - 1), v3f(position.X, position.Y, position.Z - 1),
tree_definition tree_definition
); );
} if (stack_orientation.empty() == false) { } if (!stack_orientation.empty()) {
s16 size = 1; s16 size = 1;
for (x = -size; x <= size; x++) for (x = -size; x <= size; x++)
for (y = -size; y <= size; y++) for (y = -size; y <= size; y++)
@ -527,7 +525,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0,
void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node) void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node)
{ {
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false) if (!vmanip.m_area.contains(p1))
return; return;
u32 vi = vmanip.m_area.index(p1); u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -540,7 +538,7 @@ void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node)
void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition)
{ {
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false) if (!vmanip.m_area.contains(p1))
return; return;
u32 vi = vmanip.m_area.index(p1); u32 vi = vmanip.m_area.index(p1);
content_t current_node = vmanip.m_data[vi].getContent(); content_t current_node = vmanip.m_data[vi].getContent();
@ -560,7 +558,7 @@ void tree_leaves_placement(MMVManip &vmanip, v3f p0,
if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance) if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance)
leavesnode = tree_definition.leaves2node; leavesnode = tree_definition.leaves2node;
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false) if (!vmanip.m_area.contains(p1))
return; return;
u32 vi = vmanip.m_area.index(p1); u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -584,7 +582,7 @@ void tree_single_leaves_placement(MMVManip &vmanip, v3f p0,
if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance) if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance)
leavesnode = tree_definition.leaves2node; leavesnode = tree_definition.leaves2node;
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false) if (!vmanip.m_area.contains(p1))
return; return;
u32 vi = vmanip.m_area.index(p1); u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -597,7 +595,7 @@ void tree_single_leaves_placement(MMVManip &vmanip, v3f p0,
void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition) void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition)
{ {
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z)); v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false) if (!vmanip.m_area.contains(p1))
return; return;
u32 vi = vmanip.m_area.index(p1); u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -734,7 +732,7 @@ void make_jungletree(MMVManip &vmanip, v3s16 p0, INodeDefManager *ndef, s32 seed
u32 vi = vmanip.m_area.index(pmin + p1); u32 vi = vmanip.m_area.index(pmin + p1);
for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) {
v3s16 p(x, y, z); v3s16 p(x, y, z);
if (vmanip.m_area.contains(p + p1) == true && if (vmanip.m_area.contains(p + p1) &&
(vmanip.m_data[vi].getContent() == CONTENT_AIR || (vmanip.m_data[vi].getContent() == CONTENT_AIR ||
vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) { vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) {
if (leaves_d[i] == 1) if (leaves_d[i] == 1)
@ -856,7 +854,7 @@ void make_pine_tree(MMVManip &vmanip, v3s16 p0, INodeDefManager *ndef, s32 seed)
u32 vi = vmanip.m_area.index(pmin + p1); u32 vi = vmanip.m_area.index(pmin + p1);
for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) { for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) {
v3s16 p(x, y, z); v3s16 p(x, y, z);
if (vmanip.m_area.contains(p + p1) == true && if (vmanip.m_area.contains(p + p1) &&
(vmanip.m_data[vi].getContent() == CONTENT_AIR || (vmanip.m_data[vi].getContent() == CONTENT_AIR ||
vmanip.m_data[vi].getContent() == CONTENT_IGNORE || vmanip.m_data[vi].getContent() == CONTENT_IGNORE ||
vmanip.m_data[vi] == snownode)) { vmanip.m_data[vi] == snownode)) {

@ -120,8 +120,8 @@ void TestGameDef::defineSomeNodes()
"{default_stone.png"; "{default_stone.png";
f = ContentFeatures(); f = ContentFeatures();
f.name = itemdef.name; f.name = itemdef.name;
for(int i = 0; i < 6; i++) for (TileDef &tiledef : f.tiledef)
f.tiledef[i].name = "default_stone.png"; tiledef.name = "default_stone.png";
f.is_ground_content = true; f.is_ground_content = true;
idef->registerItem(itemdef); idef->registerItem(itemdef);
t_CONTENT_STONE = ndef->set(f.name, f); t_CONTENT_STONE = ndef->set(f.name, f);
@ -175,8 +175,8 @@ void TestGameDef::defineSomeNodes()
f.liquid_viscosity = 4; f.liquid_viscosity = 4;
f.is_ground_content = true; f.is_ground_content = true;
f.groups["liquids"] = 3; f.groups["liquids"] = 3;
for(int i = 0; i < 6; i++) for (TileDef &tiledef : f.tiledef)
f.tiledef[i].name = "default_water.png"; tiledef.name = "default_water.png";
idef->registerItem(itemdef); idef->registerItem(itemdef);
t_CONTENT_WATER = ndef->set(f.name, f); t_CONTENT_WATER = ndef->set(f.name, f);
@ -197,8 +197,8 @@ void TestGameDef::defineSomeNodes()
f.light_source = LIGHT_MAX-1; f.light_source = LIGHT_MAX-1;
f.is_ground_content = true; f.is_ground_content = true;
f.groups["liquids"] = 3; f.groups["liquids"] = 3;
for(int i = 0; i < 6; i++) for (TileDef &tiledef : f.tiledef)
f.tiledef[i].name = "default_lava.png"; tiledef.name = "default_lava.png";
idef->registerItem(itemdef); idef->registerItem(itemdef);
t_CONTENT_LAVA = ndef->set(f.name, f); t_CONTENT_LAVA = ndef->set(f.name, f);
@ -215,8 +215,8 @@ void TestGameDef::defineSomeNodes()
"{default_brick.png"; "{default_brick.png";
f = ContentFeatures(); f = ContentFeatures();
f.name = itemdef.name; f.name = itemdef.name;
for(int i = 0; i < 6; i++) for (TileDef &tiledef : f.tiledef)
f.tiledef[i].name = "default_brick.png"; tiledef.name = "default_brick.png";
f.is_ground_content = true; f.is_ground_content = true;
idef->registerItem(itemdef); idef->registerItem(itemdef);
t_CONTENT_BRICK = ndef->set(f.name, f); t_CONTENT_BRICK = ndef->set(f.name, f);

@ -71,7 +71,7 @@ class TestFailedException : public std::exception {
} }
// Asserts the comparison specified by CMP is true, or fails the current unit test // Asserts the comparison specified by CMP is true, or fails the current unit test
#define UASSERTCMP(T, CMP, actual, expected) do { \ #define UASSERTCMP(T, CMP, actual, expected) { \
T a = (actual); \ T a = (actual); \
T e = (expected); \ T e = (expected); \
if (!(a CMP e)) { \ if (!(a CMP e)) { \
@ -84,12 +84,12 @@ class TestFailedException : public std::exception {
<< e << std::endl; \ << e << std::endl; \
throw TestFailedException(); \ throw TestFailedException(); \
} \ } \
} while (0) }
#define UASSERTEQ(T, actual, expected) UASSERTCMP(T, ==, actual, expected) #define UASSERTEQ(T, actual, expected) UASSERTCMP(T, ==, actual, expected)
// UASSERTs that the specified exception occurs // UASSERTs that the specified exception occurs
#define EXCEPTION_CHECK(EType, code) do { \ #define EXCEPTION_CHECK(EType, code) { \
bool exception_thrown = false; \ bool exception_thrown = false; \
try { \ try { \
code; \ code; \
@ -97,7 +97,7 @@ class TestFailedException : public std::exception {
exception_thrown = true; \ exception_thrown = true; \
} \ } \
UASSERT(exception_thrown); \ UASSERT(exception_thrown); \
} while (0) }
class IGameDef; class IGameDef;

@ -65,8 +65,8 @@ void TestCompression::testRLECompression()
infostream << "str_out.size()="<<str_out.size()<<std::endl; infostream << "str_out.size()="<<str_out.size()<<std::endl;
infostream << "TestCompress: 1,5,5,1 -> "; infostream << "TestCompress: 1,5,5,1 -> ";
for (u32 i = 0; i < str_out.size(); i++) for (char i : str_out)
infostream << (u32)str_out[i] << ","; infostream << (u32) i << ",";
infostream << std::endl; infostream << std::endl;
UASSERT(str_out.size() == 10); UASSERT(str_out.size() == 10);
@ -89,8 +89,8 @@ void TestCompression::testRLECompression()
std::string str_out2 = os2.str(); std::string str_out2 = os2.str();
infostream << "decompress: "; infostream << "decompress: ";
for (u32 i = 0; i < str_out2.size(); i++) for (char i : str_out2)
infostream << (u32)str_out2[i] << ","; infostream << (u32) i << ",";
infostream << std::endl; infostream << std::endl;
UASSERTEQ(size_t, str_out2.size(), fromdata.getSize()); UASSERTEQ(size_t, str_out2.size(), fromdata.getSize());
@ -114,8 +114,8 @@ void TestCompression::testZlibCompression()
infostream << "str_out.size()=" << str_out.size() <<std::endl; infostream << "str_out.size()=" << str_out.size() <<std::endl;
infostream << "TestCompress: 1,5,5,1 -> "; infostream << "TestCompress: 1,5,5,1 -> ";
for (u32 i = 0; i < str_out.size(); i++) for (char i : str_out)
infostream << (u32)str_out[i] << ","; infostream << (u32) i << ",";
infostream << std::endl; infostream << std::endl;
std::istringstream is(str_out, std::ios_base::binary); std::istringstream is(str_out, std::ios_base::binary);
@ -125,8 +125,8 @@ void TestCompression::testZlibCompression()
std::string str_out2 = os2.str(); std::string str_out2 = os2.str();
infostream << "decompress: "; infostream << "decompress: ";
for (u32 i = 0; i < str_out2.size(); i++) for (char i : str_out2)
infostream << (u32)str_out2[i] << ","; infostream << (u32) i << ",";
infostream << std::endl; infostream << std::endl;
UASSERTEQ(size_t, str_out2.size(), fromdata.getSize()); UASSERTEQ(size_t, str_out2.size(), fromdata.getSize());

@ -50,8 +50,8 @@ void TestNodeDef::testContentFeaturesSerialization()
ContentFeatures f; ContentFeatures f;
f.name = "default:stone"; f.name = "default:stone";
for (int i = 0; i < 6; i++) for (TileDef &tiledef : f.tiledef)
f.tiledef[i].name = "default_stone.png"; tiledef.name = "default_stone.png";
f.is_ground_content = true; f.is_ground_content = true;
std::ostringstream os(std::ios::binary); std::ostringstream os(std::ios::binary);

@ -113,7 +113,7 @@ void TestNoise::testNoiseInvalidParams()
NoiseParams np_highmem(4, 70, v3f(1, 1, 1), 5, 60, 0.7, 10.0); NoiseParams np_highmem(4, 70, v3f(1, 1, 1), 5, 60, 0.7, 10.0);
Noise noise_highmem_3d(&np_highmem, 1337, 200, 200, 200); Noise noise_highmem_3d(&np_highmem, 1337, 200, 200, 200);
noise_highmem_3d.perlinMap3D(0, 0, 0, NULL); noise_highmem_3d.perlinMap3D(0, 0, 0, NULL);
} catch (InvalidNoiseParamsException) { } catch (InvalidNoiseParamsException &) {
exception_thrown = true; exception_thrown = true;
} }

@ -215,11 +215,11 @@ void TestVoxelAlgorithms::testVoxelLineIterator(INodeDefManager *ndef)
for (f32 x = -9.1; x < 9; x += 3.124) { for (f32 x = -9.1; x < 9; x += 3.124) {
for (f32 y = -9.2; y < 9; y += 3.123) { for (f32 y = -9.2; y < 9; y += 3.123) {
for (f32 z = -9.3; z < 9; z += 3.122) { for (f32 z = -9.3; z < 9; z += 3.122) {
lines.push_back(core::line3d<f32>(-x, -y, -z, x, y, z)); lines.emplace_back(-x, -y, -z, x, y, z);
} }
} }
} }
lines.push_back(core::line3d<f32>(0, 0, 0, 0, 0, 0)); lines.emplace_back(0, 0, 0, 0, 0, 0);
// Test every line // Test every line
std::vector<core::line3d<f32> >::iterator it = lines.begin(); std::vector<core::line3d<f32> >::iterator it = lines.begin();
for (; it < lines.end(); it++) { for (; it < lines.end(); it++) {

@ -68,9 +68,8 @@ void AreaStore::serialize(std::ostream &os) const
// TODO: Compression? // TODO: Compression?
writeU16(os, areas_map.size()); writeU16(os, areas_map.size());
for (AreaMap::const_iterator it = areas_map.begin(); for (const auto &it : areas_map) {
it != areas_map.end(); ++it) { const Area &a = it.second;
const Area &a = it->second;
writeV3S16(os, a.minedge); writeV3S16(os, a.minedge);
writeV3S16(os, a.maxedge); writeV3S16(os, a.maxedge);
writeU16(os, a.data.size()); writeU16(os, a.data.size());
@ -193,10 +192,9 @@ bool VectorAreaStore::removeArea(u32 id)
void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos) void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos)
{ {
for (size_t i = 0; i < m_areas.size(); ++i) { for (Area *area : m_areas) {
Area *b = m_areas[i]; if (AST_CONTAINS_PT(area, pos)) {
if (AST_CONTAINS_PT(b, pos)) { result->push_back(area);
result->push_back(b);
} }
} }
} }
@ -204,11 +202,10 @@ void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos)
void VectorAreaStore::getAreasInArea(std::vector<Area *> *result, void VectorAreaStore::getAreasInArea(std::vector<Area *> *result,
v3s16 minedge, v3s16 maxedge, bool accept_overlap) v3s16 minedge, v3s16 maxedge, bool accept_overlap)
{ {
for (size_t i = 0; i < m_areas.size(); ++i) { for (Area *area : m_areas) {
Area *b = m_areas[i]; if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, area) :
if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, b) : AST_CONTAINS_AREA(minedge, maxedge, area)) {
AST_CONTAINS_AREA(minedge, maxedge, b)) { result->push_back(area);
result->push_back(b);
} }
} }
} }

@ -37,7 +37,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
struct Area { struct Area {
Area() {} Area() = default;
Area(const v3s16 &mine, const v3s16 &maxe) : Area(const v3s16 &mine, const v3s16 &maxe) :
minedge(mine), maxedge(maxe) minedge(mine), maxedge(maxe)
{ {
@ -56,7 +57,7 @@ public:
m_res_cache(1000, &cacheMiss, this) m_res_cache(1000, &cacheMiss, this)
{} {}
virtual ~AreaStore() {} virtual ~AreaStore() = default;
static AreaStore *getOptimalImplementation(); static AreaStore *getOptimalImplementation();

@ -97,7 +97,6 @@ void EnrichedString::addAtEnd(const std::wstring &s, const SColor &initial_color
parseColorString(wide_to_utf8(parts[1]), m_background, true); parseColorString(wide_to_utf8(parts[1]), m_background, true);
m_has_background = true; m_has_background = true;
} }
continue;
} }
} }
@ -111,7 +110,7 @@ void EnrichedString::addCharNoColor(wchar_t c)
{ {
m_string += c; m_string += c;
if (m_colors.empty()) { if (m_colors.empty()) {
m_colors.push_back(SColor(255, 255, 255, 255)); m_colors.emplace_back(255, 255, 255, 255);
} else { } else {
m_colors.push_back(m_colors[m_colors.size() - 1]); m_colors.push_back(m_colors[m_colors.size() - 1]);
} }
@ -138,15 +137,16 @@ EnrichedString EnrichedString::substr(size_t pos, size_t len) const
} }
if (len == std::string::npos || pos + len > m_string.length()) { if (len == std::string::npos || pos + len > m_string.length()) {
return EnrichedString( return EnrichedString(
m_string.substr(pos, std::string::npos), m_string.substr(pos, std::string::npos),
std::vector<SColor>(m_colors.begin() + pos, m_colors.end()) std::vector<SColor>(m_colors.begin() + pos, m_colors.end())
); );
} else {
return EnrichedString(
m_string.substr(pos, len),
std::vector<SColor>(m_colors.begin() + pos, m_colors.begin() + pos + len)
);
} }
return EnrichedString(
m_string.substr(pos, len),
std::vector<SColor>(m_colors.begin() + pos, m_colors.begin() + pos + len)
);
} }
const wchar_t *EnrichedString::c_str() const const wchar_t *EnrichedString::c_str() const

@ -281,7 +281,8 @@ inline aabb3f getNodeBox(v3s16 p, float d)
class IntervalLimiter class IntervalLimiter
{ {
public: public:
IntervalLimiter() {} IntervalLimiter() = default;
/* /*
dtime: time from last call to this method dtime: time from last call to this method
wanted_interval: interval wanted wanted_interval: interval wanted

@ -697,7 +697,7 @@ struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg,
goto cleanup_and_exit; goto cleanup_and_exit;
} }
memcpy((char *)ver->username, username, ulen); memcpy(ver->username, username, ulen);
ver->authenticated = 0; ver->authenticated = 0;

@ -167,7 +167,7 @@ std::string wide_to_utf8(const std::wstring &input)
wchar_t *utf8_to_wide_c(const char *str) wchar_t *utf8_to_wide_c(const char *str)
{ {
std::wstring ret = utf8_to_wide(std::string(str)).c_str(); std::wstring ret = utf8_to_wide(std::string(str));
size_t len = ret.length(); size_t len = ret.length();
wchar_t *ret_c = new wchar_t[len + 1]; wchar_t *ret_c = new wchar_t[len + 1];
memset(ret_c, 0, (len + 1) * sizeof(wchar_t)); memset(ret_c, 0, (len + 1) * sizeof(wchar_t));
@ -308,8 +308,8 @@ std::string wide_to_narrow(const std::wstring &wcs)
size_t len = wcstombs(*mbs, wcs.c_str(), mbl); size_t len = wcstombs(*mbs, wcs.c_str(), mbl);
if (len == (size_t)(-1)) if (len == (size_t)(-1))
return "Character conversion failed!"; return "Character conversion failed!";
else
mbs[len] = 0; mbs[len] = 0;
return *mbs; return *mbs;
} }
@ -321,8 +321,7 @@ std::string urlencode(const std::string &str)
// followed by two hex digits. See RFC 3986, section 2.3. // followed by two hex digits. See RFC 3986, section 2.3.
static const char url_hex_chars[] = "0123456789ABCDEF"; static const char url_hex_chars[] = "0123456789ABCDEF";
std::ostringstream oss(std::ios::binary); std::ostringstream oss(std::ios::binary);
for (u32 i = 0; i < str.size(); i++) { for (unsigned char c : str) {
unsigned char c = str[i];
if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') { if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
oss << c; oss << c;
} else { } else {

@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#pragma once #pragma once
#include "irrlichttypes_bloated.h" #include "irrlichttypes_bloated.h"
#include <stdlib.h> #include <cstdlib>
#include <string> #include <string>
#include <cstring> #include <cstring>
#include <vector> #include <vector>
@ -231,12 +231,12 @@ inline std::vector<std::basic_string<T> > str_split(
*/ */
inline std::string lowercase(const std::string &str) inline std::string lowercase(const std::string &str)
{ {
std::string s2 = ""; std::string s2;
s2.reserve(str.size()); s2.reserve(str.size());
for (size_t i = 0; i < str.size(); i++) for (char i : str)
s2 += tolower(str[i]); s2 += tolower(i);
return s2; return s2;
} }
@ -607,8 +607,8 @@ std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
*/ */
inline bool is_number(const std::string &to_check) inline bool is_number(const std::string &to_check)
{ {
for (size_t i = 0; i < to_check.size(); i++) for (char i : to_check)
if (!std::isdigit(to_check[i])) if (!std::isdigit(i))
return false; return false;
return !to_check.empty(); return !to_check.empty();

@ -21,8 +21,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "map.h" #include "map.h"
#include "gettime.h" #include "gettime.h"
#include "nodedef.h" #include "nodedef.h"
#include "util/directiontables.h"
#include "util/timetaker.h" #include "util/timetaker.h"
#include <string.h> // memcpy, memset #include <cstring> // memcpy, memset
/* /*
Debug stuff Debug stuff
@ -32,11 +33,6 @@ u64 emerge_time = 0;
u64 emerge_load_time = 0; u64 emerge_load_time = 0;
u64 clearflag_time = 0; u64 clearflag_time = 0;
VoxelManipulator::VoxelManipulator()
{
}
VoxelManipulator::~VoxelManipulator() VoxelManipulator::~VoxelManipulator()
{ {
clear(); clear();
@ -110,7 +106,7 @@ void VoxelManipulator::print(std::ostream &o, INodeDefManager *ndef,
{ {
if(ndef->get(m).light_source != 0) if(ndef->get(m).light_source != 0)
c = 'S'; c = 'S';
else if(ndef->get(m).light_propagates == false) else if(!ndef->get(m).light_propagates)
c = 'X'; c = 'X';
else else
{ {
@ -322,23 +318,13 @@ void VoxelManipulator::clearFlag(u8 flags)
void VoxelManipulator::unspreadLight(enum LightBank bank, v3s16 p, u8 oldlight, void VoxelManipulator::unspreadLight(enum LightBank bank, v3s16 p, u8 oldlight,
std::set<v3s16> & light_sources, INodeDefManager *nodemgr) std::set<v3s16> & light_sources, INodeDefManager *nodemgr)
{ {
v3s16 dirs[6] = {
v3s16(0,0,1), // back
v3s16(0,1,0), // top
v3s16(1,0,0), // right
v3s16(0,0,-1), // front
v3s16(0,-1,0), // bottom
v3s16(-1,0,0), // left
};
VoxelArea voxel_area(p - v3s16(1,1,1), p + v3s16(1,1,1)); VoxelArea voxel_area(p - v3s16(1,1,1), p + v3s16(1,1,1));
addArea(voxel_area); addArea(voxel_area);
// Loop through 6 neighbors // Loop through 6 neighbors
for(u16 i=0; i<6; i++) for (const v3s16 &dir : g_6dirs) {
{
// Get the position of the neighbor node // Get the position of the neighbor node
v3s16 n2pos = p + dirs[i]; v3s16 n2pos = p + dir;
u32 n2i = m_area.index(n2pos); u32 n2i = m_area.index(n2pos);
@ -387,15 +373,6 @@ void VoxelManipulator::unspreadLight(enum LightBank bank, v3s16 p, u8 oldlight,
void VoxelManipulator::spreadLight(enum LightBank bank, v3s16 p, void VoxelManipulator::spreadLight(enum LightBank bank, v3s16 p,
INodeDefManager *nodemgr) INodeDefManager *nodemgr)
{ {
const v3s16 dirs[6] = {
v3s16(0,0,1), // back
v3s16(0,1,0), // top
v3s16(1,0,0), // right
v3s16(0,0,-1), // front
v3s16(0,-1,0), // bottom
v3s16(-1,0,0), // left
};
VoxelArea voxel_area(p - v3s16(1,1,1), p + v3s16(1,1,1)); VoxelArea voxel_area(p - v3s16(1,1,1), p + v3s16(1,1,1));
addArea(voxel_area); addArea(voxel_area);
@ -410,10 +387,9 @@ void VoxelManipulator::spreadLight(enum LightBank bank, v3s16 p,
u8 newlight = diminish_light(oldlight); u8 newlight = diminish_light(oldlight);
// Loop through 6 neighbors // Loop through 6 neighbors
for(u16 i=0; i<6; i++) for (const auto &dir : g_6dirs) {
{
// Get the position of the neighbor node // Get the position of the neighbor node
v3s16 n2pos = p + dirs[i]; v3s16 n2pos = p + dir;
u32 n2i = m_area.index(n2pos); u32 n2i = m_area.index(n2pos);
@ -457,25 +433,12 @@ const MapNode VoxelManipulator::ContentIgnoreNode = MapNode(CONTENT_IGNORE);
void VoxelManipulator::spreadLight(enum LightBank bank, void VoxelManipulator::spreadLight(enum LightBank bank,
std::set<v3s16> & from_nodes, INodeDefManager *nodemgr) std::set<v3s16> & from_nodes, INodeDefManager *nodemgr)
{ {
const v3s16 dirs[6] = {
v3s16(0,0,1), // back
v3s16(0,1,0), // top
v3s16(1,0,0), // right
v3s16(0,0,-1), // front
v3s16(0,-1,0), // bottom
v3s16(-1,0,0), // left
};
if(from_nodes.empty()) if(from_nodes.empty())
return; return;
std::set<v3s16> lighted_nodes; std::set<v3s16> lighted_nodes;
for(std::set<v3s16>::iterator j = from_nodes.begin(); for (const v3s16 &pos : from_nodes) {
j != from_nodes.end(); ++j)
{
v3s16 pos = *j;
VoxelArea voxel_area(pos - v3s16(1,1,1), pos + v3s16(1,1,1)); VoxelArea voxel_area(pos - v3s16(1,1,1), pos + v3s16(1,1,1));
addArea(voxel_area); addArea(voxel_area);
@ -490,10 +453,9 @@ void VoxelManipulator::spreadLight(enum LightBank bank,
u8 newlight = diminish_light(oldlight); u8 newlight = diminish_light(oldlight);
// Loop through 6 neighbors // Loop through 6 neighbors
for(u16 i=0; i<6; i++) for (const v3s16 &dir : g_6dirs) {
{
// Get the position of the neighbor node // Get the position of the neighbor node
v3s16 n2pos = pos + dirs[i]; v3s16 n2pos = pos + dir;
try try
{ {

@ -59,7 +59,7 @@ class VoxelArea
{ {
public: public:
// Starts as zero sized // Starts as zero sized
VoxelArea() {} VoxelArea() = default;
VoxelArea(const v3s16 &min_edge, const v3s16 &max_edge): VoxelArea(const v3s16 &min_edge, const v3s16 &max_edge):
MinEdge(min_edge), MinEdge(min_edge),
@ -175,12 +175,12 @@ public:
VoxelArea operator+(const v3s16 &off) const VoxelArea operator+(const v3s16 &off) const
{ {
return VoxelArea(MinEdge+off, MaxEdge+off); return {MinEdge+off, MaxEdge+off};
} }
VoxelArea operator-(const v3s16 &off) const VoxelArea operator-(const v3s16 &off) const
{ {
return VoxelArea(MinEdge-off, MaxEdge-off); return {MinEdge-off, MaxEdge-off};
} }
/* /*
@ -344,7 +344,7 @@ enum VoxelPrintMode
class VoxelManipulator class VoxelManipulator
{ {
public: public:
VoxelManipulator(); VoxelManipulator() = default;
virtual ~VoxelManipulator(); virtual ~VoxelManipulator();
/* /*
@ -374,7 +374,7 @@ public:
addArea(voxel_area); addArea(voxel_area);
if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) { if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) {
return MapNode(CONTENT_IGNORE); return {CONTENT_IGNORE};
} }
return m_data[m_area.index(p)]; return m_data[m_area.index(p)];
@ -382,9 +382,9 @@ public:
MapNode getNodeNoExNoEmerge(const v3s16 &p) MapNode getNodeNoExNoEmerge(const v3s16 &p)
{ {
if (!m_area.contains(p)) if (!m_area.contains(p))
return MapNode(CONTENT_IGNORE); return {CONTENT_IGNORE};
if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA)
return MapNode(CONTENT_IGNORE); return {CONTENT_IGNORE};
return m_data[m_area.index(p)]; return m_data[m_area.index(p)];
} }
// Stuff explodes if non-emerged area is touched with this. // Stuff explodes if non-emerged area is touched with this.

@ -118,7 +118,7 @@ SunlightPropagateResult propagateSunlight(VoxelManipulator &v, VoxelArea a,
} else if(incoming_light == LIGHT_SUN && } else if(incoming_light == LIGHT_SUN &&
ndef->get(n).sunlight_propagates){ ndef->get(n).sunlight_propagates){
// Do nothing // Do nothing
} else if(ndef->get(n).sunlight_propagates == false){ } else if(!ndef->get(n).sunlight_propagates){
incoming_light = 0; incoming_light = 0;
} else { } else {
incoming_light = diminish_light(incoming_light); incoming_light = diminish_light(incoming_light);
@ -152,7 +152,7 @@ SunlightPropagateResult propagateSunlight(VoxelManipulator &v, VoxelArea a,
} }
} }
return SunlightPropagateResult(bottom_sunlight_valid); return {bottom_sunlight_valid};
} }
/*! /*!
@ -186,21 +186,16 @@ struct ChangingLight {
//! Position of the node's block. //! Position of the node's block.
mapblock_v3 block_position; mapblock_v3 block_position;
//! Pointer to the node's block. //! Pointer to the node's block.
MapBlock *block; MapBlock *block = NULL;
/*! /*!
* Direction from the node that caused this node's changing * Direction from the node that caused this node's changing
* to this node. * to this node.
*/ */
direction source_direction; direction source_direction = 6;
ChangingLight() : ChangingLight() = default;
rel_position(),
block_position(),
block(NULL),
source_direction(6)
{}
ChangingLight(relative_v3 rel_pos, mapblock_v3 block_pos, ChangingLight(const relative_v3 &rel_pos, const mapblock_v3 &block_pos,
MapBlock *b, direction source_dir) : MapBlock *b, direction source_dir) :
rel_position(rel_pos), rel_position(rel_pos),
block_position(block_pos), block_position(block_pos),
@ -265,8 +260,7 @@ struct LightQueue {
direction source_dir) direction source_dir)
{ {
assert(light <= LIGHT_SUN); assert(light <= LIGHT_SUN);
lights[light].push_back( lights[light].emplace_back(rel_pos, block_pos, block, source_dir);
ChangingLight(rel_pos, block_pos, block, source_dir));
} }
}; };
@ -611,8 +605,7 @@ void update_lighting_nodes(Map *map,
bool is_valid_position; bool is_valid_position;
// Process each light bank separately // Process each light bank separately
for (s32 i = 0; i < 2; i++) { for (LightBank bank : banks) {
LightBank bank = banks[i];
UnlightQueue disappearing_lights(256); UnlightQueue disappearing_lights(256);
ReLightQueue light_sources(256); ReLightQueue light_sources(256);
// Nodes that are brighter than the brightest modified node was // Nodes that are brighter than the brightest modified node was
@ -663,8 +656,8 @@ void update_lighting_nodes(Map *map,
new_light = LIGHT_SUN; new_light = LIGHT_SUN;
} else { } else {
new_light = ndef->get(n).light_source; new_light = ndef->get(n).light_source;
for (int i = 0; i < 6; i++) { for (const v3s16 &neighbor_dir : neighbor_dirs) {
v3s16 p2 = p + neighbor_dirs[i]; v3s16 p2 = p + neighbor_dir;
bool is_valid; bool is_valid;
MapNode n2 = map->getNodeNoEx(p2, &is_valid); MapNode n2 = map->getNodeNoEx(p2, &is_valid);
if (is_valid) { if (is_valid) {
@ -813,8 +806,8 @@ bool is_light_locally_correct(Map *map, INodeDefManager *ndef, LightBank bank,
u8 light = n.getLightNoChecks(bank, &f); u8 light = n.getLightNoChecks(bank, &f);
assert(f.light_source <= LIGHT_MAX); assert(f.light_source <= LIGHT_MAX);
u8 brightest_neighbor = f.light_source + 1; u8 brightest_neighbor = f.light_source + 1;
for (direction d = 0; d < 6; ++d) { for (const v3s16 &neighbor_dir : neighbor_dirs) {
MapNode n2 = map->getNodeNoEx(pos + neighbor_dirs[d], MapNode n2 = map->getNodeNoEx(pos + neighbor_dir,
&is_valid_position); &is_valid_position);
u8 light2 = n2.getLight(bank, ndef); u8 light2 = n2.getLight(bank, ndef);
if (brightest_neighbor < light2) { if (brightest_neighbor < light2) {
@ -830,8 +823,7 @@ void update_block_border_lighting(Map *map, MapBlock *block,
{ {
INodeDefManager *ndef = map->getNodeDefManager(); INodeDefManager *ndef = map->getNodeDefManager();
bool is_valid_position; bool is_valid_position;
for (s32 i = 0; i < 2; i++) { for (LightBank bank : banks) {
LightBank bank = banks[i];
// Since invalid light is not common, do not allocate // Since invalid light is not common, do not allocate
// memory if not needed. // memory if not needed.
UnlightQueue disappearing_lights(0); UnlightQueue disappearing_lights(0);
@ -1213,8 +1205,7 @@ void blit_back_with_light(ServerMap *map, MMVManip *vm,
data.target_block = v3s16(x, minblock.Y - 1, z); data.target_block = v3s16(x, minblock.Y - 1, z);
for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
for (s16 x = 0; x < MAP_BLOCKSIZE; x++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
data.data.push_back( data.data.emplace_back(v2s16(x, z), lights[z][x]);
SunlightPropagationUnit(v2s16(x, z), lights[z][x]));
// Propagate sunlight and shadow below the voxel manipulator. // Propagate sunlight and shadow below the voxel manipulator.
while (!data.data.empty()) { while (!data.data.empty()) {
if (propagate_block_sunlight(map, ndef, &data, &unlight[0], if (propagate_block_sunlight(map, ndef, &data, &unlight[0],
@ -1241,8 +1232,7 @@ void blit_back_with_light(ServerMap *map, MMVManip *vm,
continue; continue;
v3s16 offset = block->getPosRelative(); v3s16 offset = block->getPosRelative();
// For each border of the block: // For each border of the block:
for (direction d = 0; d < 6; d++) { for (const VoxelArea &a : block_pad) {
VoxelArea a = block_pad[d];
// For each node of the border: // For each node of the border:
for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++) for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++)
for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++)
@ -1353,8 +1343,7 @@ void repair_block_light(ServerMap *map, MapBlock *block,
data.target_block = v3s16(blockpos.X, blockpos.Y - 1, blockpos.Z); data.target_block = v3s16(blockpos.X, blockpos.Y - 1, blockpos.Z);
for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { for (s16 x = 0; x < MAP_BLOCKSIZE; x++) {
data.data.push_back( data.data.emplace_back(v2s16(x, z), lights[z][x]);
SunlightPropagationUnit(v2s16(x, z), lights[z][x]));
} }
// Propagate sunlight and shadow below the voxel manipulator. // Propagate sunlight and shadow below the voxel manipulator.
while (!data.data.empty()) { while (!data.data.empty()) {
@ -1369,8 +1358,7 @@ void repair_block_light(ServerMap *map, MapBlock *block,
// --- STEP 2: Get nodes from borders to unlight // --- STEP 2: Get nodes from borders to unlight
// For each border of the block: // For each border of the block:
for (direction d = 0; d < 6; d++) { for (const VoxelArea &a : block_pad) {
VoxelArea a = block_pad[d];
// For each node of the border: // For each node of the border:
for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++) for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++)
for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++)

@ -146,10 +146,8 @@ public:
// Destructor // Destructor
virtual ~ExtrusionMeshCache() virtual ~ExtrusionMeshCache()
{ {
for (std::map<int, scene::IMesh*>::iterator for (auto &extrusion_meshe : m_extrusion_meshes) {
it = m_extrusion_meshes.begin(); extrusion_meshe.second->drop();
it != m_extrusion_meshes.end(); ++it) {
it->second->drop();
} }
m_cube->drop(); m_cube->drop();
} }
@ -309,14 +307,15 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client)
m_base_color = idef->getItemstackColor(item, client); m_base_color = idef->getItemstackColor(item, client);
// If wield_image is defined, it overrides everything else // If wield_image is defined, it overrides everything else
if (def.wield_image != "") { if (!def.wield_image.empty()) {
setExtruded(def.wield_image, def.wield_scale, tsrc, 1); setExtruded(def.wield_image, def.wield_scale, tsrc, 1);
m_colors.push_back(ItemPartColor()); m_colors.emplace_back();
return; return;
} }
// Handle nodes // Handle nodes
// See also CItemDefManager::createClientCached() // See also CItemDefManager::createClientCached()
else if (def.type == ITEM_NODE) { if (def.type == ITEM_NODE) {
if (f.mesh_ptr[0]) { if (f.mesh_ptr[0]) {
// e.g. mesh nodes and nodeboxes // e.g. mesh nodes and nodeboxes
scene::SMesh *mesh = cloneMesh(f.mesh_ptr[0]); scene::SMesh *mesh = cloneMesh(f.mesh_ptr[0]);
@ -377,9 +376,9 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client)
} }
return; return;
} }
else if (def.inventory_image != "") { else if (!def.inventory_image.empty()) {
setExtruded(def.inventory_image, def.wield_scale, tsrc, 1); setExtruded(def.inventory_image, def.wield_scale, tsrc, 1);
m_colors.push_back(ItemPartColor()); m_colors.emplace_back();
return; return;
} }
@ -455,9 +454,9 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result)
result->needs_shading = true; result->needs_shading = true;
// If inventory_image is defined, it overrides everything else // If inventory_image is defined, it overrides everything else
if (def.inventory_image != "") { if (!def.inventory_image.empty()) {
mesh = getExtrudedMesh(tsrc, def.inventory_image); mesh = getExtrudedMesh(tsrc, def.inventory_image);
result->buffer_colors.push_back(ItemPartColor()); result->buffer_colors.emplace_back();
// Items with inventory images do not need shading // Items with inventory images do not need shading
result->needs_shading = false; result->needs_shading = false;
} else if (def.type == ITEM_NODE) { } else if (def.type == ITEM_NODE) {
@ -560,7 +559,7 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
} }
void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f,
bool use_shaders, bool set_material, video::E_MATERIAL_TYPE *mattype, bool use_shaders, bool set_material, const video::E_MATERIAL_TYPE *mattype,
std::vector<ItemPartColor> *colors) std::vector<ItemPartColor> *colors)
{ {
u32 mc = mesh->getMeshBufferCount(); u32 mc = mesh->getMeshBufferCount();

@ -44,7 +44,7 @@ struct ItemPartColor
*/ */
video::SColor color = 0; video::SColor color = 0;
ItemPartColor() {} ItemPartColor() = default;
ItemPartColor(bool override, video::SColor color) ItemPartColor(bool override, video::SColor color)
: override_base(override), color(color) : override_base(override), color(color)
@ -65,7 +65,7 @@ struct ItemMesh
*/ */
bool needs_shading = true; bool needs_shading = true;
ItemMesh() {} ItemMesh() = default;
}; };
/* /*
@ -135,5 +135,5 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
* \param colors returns the colors of the mesh buffers in the mesh. * \param colors returns the colors of the mesh buffers in the mesh.
*/ */
void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders, void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders,
bool set_material, video::E_MATERIAL_TYPE *mattype, bool set_material, const video::E_MATERIAL_TYPE *mattype,
std::vector<ItemPartColor> *colors); std::vector<ItemPartColor> *colors);