Modernize code: very last fixes (#6290)

Last modernization fixes
master
Loïc Blot 2017-08-20 19:37:29 +02:00 committed by GitHub
parent c8d3d11339
commit ae9b5e0098
31 changed files with 428 additions and 523 deletions

View File

@ -104,7 +104,9 @@ void CavesNoiseIntersection::generateCaves(MMVManip *vm,
c == biome->c_water) { c == biome->c_water) {
column_is_open = true; column_is_open = true;
continue; continue;
} else if (c == biome->c_river_water) { }
if (c == biome->c_river_water) {
column_is_open = true; column_is_open = true;
is_under_river = true; is_under_river = true;
continue; continue;

View File

@ -280,12 +280,11 @@ void RemoteClient::GetNextBlocks (
// Block is dummy if data doesn't exist. // Block is dummy if data doesn't exist.
// It means it has been not found from disk and not generated // It means it has been not found from disk and not generated
if(block->isDummy()) if (block->isDummy()) {
{
surely_not_found_on_disk = true; surely_not_found_on_disk = true;
} }
if(block->isGenerated() == false) if (!block->isGenerated())
block_is_invalid = true; block_is_invalid = true;
/* /*
@ -295,9 +294,8 @@ void RemoteClient::GetNextBlocks (
Block is near ground level if night-time mesh Block is near ground level if night-time mesh
differs from day-time mesh. differs from day-time mesh.
*/ */
if(d >= d_opt) if (d >= d_opt) {
{ if (!block->getDayNightDiff())
if(block->getDayNightDiff() == false)
continue; continue;
} }
@ -311,8 +309,7 @@ void RemoteClient::GetNextBlocks (
If block has been marked to not exist on disk (dummy) If block has been marked to not exist on disk (dummy)
and generating new ones is not wanted, skip block. and generating new ones is not wanted, skip block.
*/ */
if(generate == false && surely_not_found_on_disk == true) if (!generate && surely_not_found_on_disk) {
{
// get next one. // get next one.
continue; continue;
} }
@ -413,11 +410,8 @@ void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
m_nearest_unsent_d = 0; m_nearest_unsent_d = 0;
m_nothing_to_send_pause_timer = 0; m_nothing_to_send_pause_timer = 0;
for(std::map<v3s16, MapBlock*>::iterator for (auto &block : blocks) {
i = blocks.begin(); v3s16 p = block.first;
i != blocks.end(); ++i)
{
v3s16 p = i->first;
m_blocks_modified.insert(p); m_blocks_modified.insert(p);
if(m_blocks_sending.find(p) != m_blocks_sending.end()) if(m_blocks_sending.find(p) != m_blocks_sending.end())
@ -609,10 +603,9 @@ ClientInterface::~ClientInterface()
{ {
MutexAutoLock clientslock(m_clients_mutex); MutexAutoLock clientslock(m_clients_mutex);
for (RemoteClientMap::iterator i = m_clients.begin(); for (auto &client_it : m_clients) {
i != m_clients.end(); ++i) {
// Delete client // Delete client
delete i->second; delete client_it.second;
} }
} }
} }
@ -660,8 +653,8 @@ void ClientInterface::UpdatePlayerList()
if(!clients.empty()) if(!clients.empty())
infostream<<"Players:"<<std::endl; infostream<<"Players:"<<std::endl;
for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) { for (u16 i : clients) {
RemotePlayer *player = m_env->getPlayer(*i); RemotePlayer *player = m_env->getPlayer(i);
if (player == NULL) if (player == NULL)
continue; continue;
@ -670,12 +663,12 @@ void ClientInterface::UpdatePlayerList()
{ {
MutexAutoLock clientslock(m_clients_mutex); MutexAutoLock clientslock(m_clients_mutex);
RemoteClient* client = lockedGetClientNoEx(*i); RemoteClient* client = lockedGetClientNoEx(i);
if (client) if (client)
client->PrintInfo(infostream); client->PrintInfo(infostream);
} }
m_clients_names.push_back(player->getName()); m_clients_names.emplace_back(player->getName());
} }
} }
} }
@ -689,9 +682,8 @@ void ClientInterface::send(u16 peer_id, u8 channelnum,
void ClientInterface::sendToAll(NetworkPacket *pkt) void ClientInterface::sendToAll(NetworkPacket *pkt)
{ {
MutexAutoLock clientslock(m_clients_mutex); MutexAutoLock clientslock(m_clients_mutex);
for (RemoteClientMap::iterator i = m_clients.begin(); for (auto &client_it : m_clients) {
i != m_clients.end(); ++i) { RemoteClient *client = client_it.second;
RemoteClient *client = i->second;
if (client->net_proto_version != 0) { if (client->net_proto_version != 0) {
m_con->Send(client->peer_id, m_con->Send(client->peer_id,
@ -705,9 +697,8 @@ void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacyp
u16 min_proto_ver) u16 min_proto_ver)
{ {
MutexAutoLock clientslock(m_clients_mutex); MutexAutoLock clientslock(m_clients_mutex);
for (std::unordered_map<u16, RemoteClient*>::iterator i = m_clients.begin(); for (auto &client_it : m_clients) {
i != m_clients.end(); ++i) { RemoteClient *client = client_it.second;
RemoteClient *client = i->second;
NetworkPacket *pkt_to_send = nullptr; NetworkPacket *pkt_to_send = nullptr;
if (client->net_proto_version >= min_proto_ver) { if (client->net_proto_version >= min_proto_ver) {
@ -738,8 +729,8 @@ RemoteClient* ClientInterface::getClientNoEx(u16 peer_id, ClientState state_min)
if (n->second->getState() >= state_min) if (n->second->getState() >= state_min)
return n->second; return n->second;
else
return NULL; return NULL;
} }
RemoteClient* ClientInterface::lockedGetClientNoEx(u16 peer_id, ClientState state_min) RemoteClient* ClientInterface::lockedGetClientNoEx(u16 peer_id, ClientState state_min)
@ -752,8 +743,8 @@ RemoteClient* ClientInterface::lockedGetClientNoEx(u16 peer_id, ClientState stat
if (n->second->getState() >= state_min) if (n->second->getState() >= state_min)
return n->second; return n->second;
else
return NULL; return NULL;
} }
ClientState ClientInterface::getClientState(u16 peer_id) ClientState ClientInterface::getClientState(u16 peer_id)
@ -795,10 +786,8 @@ void ClientInterface::DeleteClient(u16 peer_id)
//TODO this should be done by client destructor!!! //TODO this should be done by client destructor!!!
RemoteClient *client = n->second; RemoteClient *client = n->second;
// Handle objects // Handle objects
for (std::set<u16>::iterator i = client->m_known_objects.begin(); for (u16 id : client->m_known_objects) {
i != client->m_known_objects.end(); ++i) {
// Get object // Get object
u16 id = *i;
ServerActiveObject* obj = m_env->getActiveObject(id); ServerActiveObject* obj = m_env->getActiveObject(id);
if(obj && obj->m_known_by_count > 0) if(obj && obj->m_known_by_count > 0)

View File

@ -274,8 +274,8 @@ struct MeshBufListList
void clear() void clear()
{ {
for (int l = 0; l < MAX_TILE_LAYERS; l++) for (auto &list : lists)
lists[l].clear(); list.clear();
} }
void add(scene::IMeshBuffer *buf, u8 layer) void add(scene::IMeshBuffer *buf, u8 layer)
@ -441,9 +441,7 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
} }
// Render all layers in order // Render all layers in order
for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { for (auto &lists : drawbufs.lists) {
std::vector<MeshBufList> &lists = drawbufs.lists[layer];
int timecheck_counter = 0; int timecheck_counter = 0;
for (MeshBufList &list : lists) { for (MeshBufList &list : lists) {
timecheck_counter++; timecheck_counter++;

View File

@ -237,8 +237,8 @@ void Clouds::render()
switch(i) switch(i)
{ {
case 0: // top case 0: // top
for(int j=0;j<4;j++){ for (video::S3DVertex &vertex : v) {
v[j].Normal.set(0,1,0); vertex.Normal.set(0,1,0);
} }
v[0].Pos.set(-rx, ry,-rz); v[0].Pos.set(-rx, ry,-rz);
v[1].Pos.set(-rx, ry, rz); v[1].Pos.set(-rx, ry, rz);
@ -251,9 +251,9 @@ void Clouds::render()
if(grid[j]) if(grid[j])
continue; continue;
} }
for(int j=0;j<4;j++){ for (video::S3DVertex &vertex : v) {
v[j].Color = c_side_1; vertex.Color = c_side_1;
v[j].Normal.set(0,0,-1); vertex.Normal.set(0,0,-1);
} }
v[0].Pos.set(-rx, ry,-rz); v[0].Pos.set(-rx, ry,-rz);
v[1].Pos.set( rx, ry,-rz); v[1].Pos.set( rx, ry,-rz);
@ -266,9 +266,9 @@ void Clouds::render()
if(grid[j]) if(grid[j])
continue; continue;
} }
for(int j=0;j<4;j++){ for (video::S3DVertex &vertex : v) {
v[j].Color = c_side_2; vertex.Color = c_side_2;
v[j].Normal.set(1,0,0); vertex.Normal.set(1,0,0);
} }
v[0].Pos.set( rx, ry,-rz); v[0].Pos.set( rx, ry,-rz);
v[1].Pos.set( rx, ry, rz); v[1].Pos.set( rx, ry, rz);
@ -281,9 +281,9 @@ void Clouds::render()
if(grid[j]) if(grid[j])
continue; continue;
} }
for(int j=0;j<4;j++){ for (video::S3DVertex &vertex : v) {
v[j].Color = c_side_1; vertex.Color = c_side_1;
v[j].Normal.set(0,0,-1); vertex.Normal.set(0,0,-1);
} }
v[0].Pos.set( rx, ry, rz); v[0].Pos.set( rx, ry, rz);
v[1].Pos.set(-rx, ry, rz); v[1].Pos.set(-rx, ry, rz);
@ -296,9 +296,9 @@ void Clouds::render()
if(grid[j]) if(grid[j])
continue; continue;
} }
for(int j=0;j<4;j++){ for (video::S3DVertex &vertex : v) {
v[j].Color = c_side_2; vertex.Color = c_side_2;
v[j].Normal.set(-1,0,0); vertex.Normal.set(-1,0,0);
} }
v[0].Pos.set(-rx, ry, rz); v[0].Pos.set(-rx, ry, rz);
v[1].Pos.set(-rx, ry,-rz); v[1].Pos.set(-rx, ry,-rz);
@ -306,9 +306,9 @@ void Clouds::render()
v[3].Pos.set(-rx, 0, rz); v[3].Pos.set(-rx, 0, rz);
break; break;
case 5: // bottom case 5: // bottom
for(int j=0;j<4;j++){ for (video::S3DVertex &vertex : v) {
v[j].Color = c_bottom; vertex.Color = c_bottom;
v[j].Normal.set(0,-1,0); vertex.Normal.set(0,-1,0);
} }
v[0].Pos.set( rx, 0, rz); v[0].Pos.set( rx, 0, rz);
v[1].Pos.set(-rx, 0, rz); v[1].Pos.set(-rx, 0, rz);
@ -320,8 +320,8 @@ void Clouds::render()
v3f pos(p0.X, m_params.height * BS, p0.Y); v3f pos(p0.X, m_params.height * BS, p0.Y);
pos -= intToFloat(m_camera_offset, BS); pos -= intToFloat(m_camera_offset, BS);
for(u16 i=0; i<4; i++) for (video::S3DVertex &vertex : v)
v[i].Pos += pos; vertex.Pos += pos;
u16 indices[] = {0,1,2,2,3,0}; u16 indices[] = {0,1,2,2,3,0};
driver->drawVertexPrimitiveList(v, 4, indices, 2, driver->drawVertexPrimitiveList(v, 4, indices, 2,
video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT); video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT);

View File

@ -245,9 +245,8 @@ LuaEntitySAO::~LuaEntitySAO()
m_env->getScriptIface()->luaentity_Remove(m_id); m_env->getScriptIface()->luaentity_Remove(m_id);
} }
for (std::unordered_set<u32>::iterator it = m_attached_particle_spawners.begin(); for (u32 attached_particle_spawner : m_attached_particle_spawners) {
it != m_attached_particle_spawners.end(); ++it) { m_env->deleteParticleSpawner(attached_particle_spawner, false);
m_env->deleteParticleSpawner(*it, false);
} }
} }
@ -267,7 +266,7 @@ void LuaEntitySAO::addedToEnvironment(u32 dtime_s)
m_hp = m_prop.hp_max; m_hp = m_prop.hp_max;
// Activate entity, supplying serialized state // Activate entity, supplying serialized state
m_env->getScriptIface()-> m_env->getScriptIface()->
luaentity_Activate(m_id, m_init_state.c_str(), dtime_s); luaentity_Activate(m_id, m_init_state, dtime_s);
} else { } else {
m_prop.infotext = m_init_name; m_prop.infotext = m_init_name;
} }
@ -281,7 +280,7 @@ ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos,
s16 hp = 1; s16 hp = 1;
v3f velocity; v3f velocity;
float yaw = 0; float yaw = 0;
if(data != ""){ if (!data.empty()) {
std::istringstream is(data, std::ios::binary); std::istringstream is(data, std::ios::binary);
// read version // read version
u8 version = readU8(is); u8 version = readU8(is);
@ -791,10 +790,10 @@ PlayerSAO::PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, u16 peer_id
m_prop.visual = "upright_sprite"; m_prop.visual = "upright_sprite";
m_prop.visual_size = v2f(1, 2); m_prop.visual_size = v2f(1, 2);
m_prop.textures.clear(); m_prop.textures.clear();
m_prop.textures.push_back("player.png"); m_prop.textures.emplace_back("player.png");
m_prop.textures.push_back("player_back.png"); m_prop.textures.emplace_back("player_back.png");
m_prop.colors.clear(); m_prop.colors.clear();
m_prop.colors.push_back(video::SColor(255, 255, 255, 255)); m_prop.colors.emplace_back(255, 255, 255, 255);
m_prop.spritediv = v2s16(1,1); m_prop.spritediv = v2s16(1,1);
// end of default appearance // end of default appearance
m_prop.is_visible = true; m_prop.is_visible = true;
@ -843,9 +842,8 @@ void PlayerSAO::removingFromEnvironment()
ServerActiveObject::removingFromEnvironment(); ServerActiveObject::removingFromEnvironment();
if (m_player->getPlayerSAO() == this) { if (m_player->getPlayerSAO() == this) {
unlinkPlayerSessionAndSave(); unlinkPlayerSessionAndSave();
for (std::unordered_set<u32>::iterator it = m_attached_particle_spawners.begin(); for (u32 attached_particle_spawner : m_attached_particle_spawners) {
it != m_attached_particle_spawners.end(); ++it) { m_env->deleteParticleSpawner(attached_particle_spawner, false);
m_env->deleteParticleSpawner(*it, false);
} }
} }
} }
@ -897,7 +895,7 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version)
return os.str(); return os.str();
} }
void PlayerSAO::getStaticData(std::string *) const void PlayerSAO::getStaticData(std::string * result) const
{ {
FATAL_ERROR("Deprecated function"); FATAL_ERROR("Deprecated function");
} }

View File

@ -49,17 +49,17 @@ static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &gr
case CRAFT_HASH_TYPE_ITEM_NAMES: { case CRAFT_HASH_TYPE_ITEM_NAMES: {
std::ostringstream os; std::ostringstream os;
bool is_first = true; bool is_first = true;
for (size_t i = 0; i < grid_names.size(); i++) { for (const std::string &grid_name : grid_names) {
if (!grid_names[i].empty()) { if (!grid_name.empty()) {
os << (is_first ? "" : "\n") << grid_names[i]; os << (is_first ? "" : "\n") << grid_name;
is_first = false; is_first = false;
} }
} }
return getHashForString(os.str()); return getHashForString(os.str());
} case CRAFT_HASH_TYPE_COUNT: { } case CRAFT_HASH_TYPE_COUNT: {
u64 cnt = 0; u64 cnt = 0;
for (size_t i = 0; i < grid_names.size(); i++) for (const std::string &grid_name : grid_names)
if (!grid_names[i].empty()) if (!grid_name.empty())
cnt++; cnt++;
return cnt; return cnt;
} case CRAFT_HASH_TYPE_UNHASHED: } case CRAFT_HASH_TYPE_UNHASHED:
@ -150,10 +150,9 @@ static bool craftGetBounds(const std::vector<std::string> &items, unsigned int w
bool success = false; bool success = false;
unsigned int x = 0; unsigned int x = 0;
unsigned int y = 0; unsigned int y = 0;
for (std::vector<std::string>::size_type i = 0; for (const std::string &item : items) {
i < items.size(); i++) {
// Is this an actual item? // Is this an actual item?
if (!items[i].empty()) { if (!item.empty()) {
if (!success) { if (!success) {
// This is the first nonempty item // This is the first nonempty item
min_x = max_x = x; min_x = max_x = x;
@ -726,13 +725,14 @@ u64 CraftDefinitionCooking::getHash(CraftHashType type) const
if (type == CRAFT_HASH_TYPE_ITEM_NAMES) { if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
return getHashForString(recipe_name); return getHashForString(recipe_name);
} }
if (type == CRAFT_HASH_TYPE_COUNT) { if (type == CRAFT_HASH_TYPE_COUNT) {
return 1; return 1;
} else {
//illegal hash type for this CraftDefinition (pre-condition)
assert(false);
return 0;
} }
// illegal hash type for this CraftDefinition (pre-condition)
assert(false);
return 0;
} }
void CraftDefinitionCooking::initHash(IGameDef *gamedef) void CraftDefinitionCooking::initHash(IGameDef *gamedef)
@ -821,11 +821,11 @@ u64 CraftDefinitionFuel::getHash(CraftHashType type) const
if (type == CRAFT_HASH_TYPE_COUNT) { if (type == CRAFT_HASH_TYPE_COUNT) {
return 1; return 1;
} else {
//illegal hash type for this CraftDefinition (pre-condition)
assert(false);
return 0;
} }
// illegal hash type for this CraftDefinition (pre-condition)
assert(false);
return 0;
} }
void CraftDefinitionFuel::initHash(IGameDef *gamedef) void CraftDefinitionFuel::initHash(IGameDef *gamedef)
@ -1059,9 +1059,8 @@ public:
{ {
for (int type = 0; type <= craft_hash_type_max; ++type) { for (int type = 0; type <= craft_hash_type_max; ++type) {
for (auto &it : m_craft_defs[type]) { for (auto &it : m_craft_defs[type]) {
for (auto iit = it.second.begin(); for (auto &iit : it.second) {
iit != it.second.end(); ++iit) { delete iit;
delete *iit;
} }
it.second.clear(); it.second.clear();
} }

View File

@ -39,10 +39,6 @@ Environment::Environment(IGameDef *gamedef):
m_cache_nodetimer_interval = g_settings->getFloat("nodetimer_interval"); m_cache_nodetimer_interval = g_settings->getFloat("nodetimer_interval");
} }
Environment::~Environment()
{
}
u32 Environment::getDayNightRatio() u32 Environment::getDayNightRatio()
{ {
MutexAutoLock lock(this->m_time_lock); MutexAutoLock lock(this->m_time_lock);
@ -103,9 +99,8 @@ void Environment::continueRaycast(RaycastState *state, PointedThing *result)
if (state->m_objects_pointable) { if (state->m_objects_pointable) {
std::vector<PointedThing> found; std::vector<PointedThing> found;
getSelectedActiveObjects(state->m_shootline, found); getSelectedActiveObjects(state->m_shootline, found);
for (std::vector<PointedThing>::iterator pointed = found.begin(); for (const PointedThing &pointed : found) {
pointed != found.end(); ++pointed) { state->m_found.push(pointed);
state->m_found.push(*pointed);
} }
} }
// Set search range // Set search range

View File

@ -48,7 +48,7 @@ class Environment
public: public:
// Environment will delete the map passed to the constructor // Environment will delete the map passed to the constructor
Environment(IGameDef *gamedef); Environment(IGameDef *gamedef);
virtual ~Environment(); virtual ~Environment() = default;
DISABLE_CLASS_COPY(Environment); DISABLE_CLASS_COPY(Environment);
/* /*

View File

@ -46,8 +46,8 @@ FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) :
m_env(env) m_env(env)
{ {
for (unsigned int i = 0; i < FM_MaxMode; i++) { for (u32 &i : m_default_size) {
m_default_size[i] = (FontMode) FONT_SIZE_UNSPECIFIED; i = (FontMode) FONT_SIZE_UNSPECIFIED;
} }
assert(m_settings != NULL); // pre-condition assert(m_settings != NULL); // pre-condition
@ -113,15 +113,13 @@ FontEngine::~FontEngine()
/******************************************************************************/ /******************************************************************************/
void FontEngine::cleanCache() void FontEngine::cleanCache()
{ {
for ( unsigned int i = 0; i < FM_MaxMode; i++) { for (auto &font_cache_it : m_font_cache) {
for (std::map<unsigned int, irr::gui::IGUIFont*>::iterator iter for (auto &font_it : font_cache_it) {
= m_font_cache[i].begin(); font_it.second->drop();
iter != m_font_cache[i].end(); ++iter) { font_it.second = NULL;
iter->second->drop();
iter->second = NULL;
} }
m_font_cache[i].clear(); font_cache_it.clear();
} }
} }
@ -370,7 +368,7 @@ void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode)
{ {
assert(mode == FM_Simple || mode == FM_SimpleMono); // pre-condition assert(mode == FM_Simple || mode == FM_SimpleMono); // pre-condition
std::string font_path = ""; std::string font_path;
if (mode == FM_Simple) { if (mode == FM_Simple) {
font_path = m_settings->get("font_path"); font_path = m_settings->get("font_path");
} else { } else {

View File

@ -317,9 +317,7 @@ void GUIChatConsole::drawText()
if (y + line_height < 0) if (y + line_height < 0)
continue; continue;
for (u32 i = 0; i < line.fragments.size(); ++i) for (const ChatFormattedFragment &fragment : line.fragments) {
{
const ChatFormattedFragment& fragment = line.fragments[i];
s32 x = (fragment.column + 1) * m_fontsize.X; s32 x = (fragment.column + 1) * m_fontsize.X;
core::rect<s32> destrect( core::rect<s32> destrect(
x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y);
@ -327,7 +325,7 @@ void GUIChatConsole::drawText()
#if USE_FREETYPE #if USE_FREETYPE
// Draw colored text if FreeType is enabled // Draw colored text if FreeType is enabled
irr::gui::CGUITTFont *tmp = static_cast<irr::gui::CGUITTFont*>(m_font); irr::gui::CGUITTFont *tmp = dynamic_cast<irr::gui::CGUITTFont *>(m_font);
tmp->draw( tmp->draw(
fragment.text, fragment.text,
destrect, destrect,
@ -411,8 +409,7 @@ bool GUIChatConsole::OnEvent(const SEvent& event)
if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown)
{ {
// Key input // Key input
if(KeyPress(event.KeyInput) == getKeySetting("keymap_console")) if (KeyPress(event.KeyInput) == getKeySetting("keymap_console")) {
{
closeConsole(); closeConsole();
// inhibit open so the_game doesn't reopen immediately // inhibit open so the_game doesn't reopen immediately
@ -420,8 +417,8 @@ bool GUIChatConsole::OnEvent(const SEvent& event)
m_close_on_enter = false; m_close_on_enter = false;
return true; return true;
} }
else if(event.KeyInput.Key == KEY_ESCAPE)
{ if (event.KeyInput.Key == KEY_ESCAPE) {
closeConsoleAtOnce(); closeConsoleAtOnce();
m_close_on_enter = false; m_close_on_enter = false;
// inhibit open so the_game doesn't reopen immediately // inhibit open so the_game doesn't reopen immediately

View File

@ -60,9 +60,8 @@ void TextDestGuiEngine::gotText(const std::wstring &text)
/******************************************************************************/ /******************************************************************************/
MenuTextureSource::~MenuTextureSource() MenuTextureSource::~MenuTextureSource()
{ {
for (std::set<std::string>::iterator it = m_to_delete.begin(); for (const std::string &texture_to_delete : m_to_delete) {
it != m_to_delete.end(); ++it) { const char *tname = texture_to_delete.c_str();
const char *tname = (*it).c_str();
video::ITexture *texture = m_driver->getTexture(tname); video::ITexture *texture = m_driver->getTexture(tname);
m_driver->removeTexture(texture); m_driver->removeTexture(texture);
} }
@ -126,8 +125,8 @@ GUIEngine::GUIEngine(JoystickController *joystick,
m_kill(kill) m_kill(kill)
{ {
//initialize texture pointers //initialize texture pointers
for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) { for (image_definition &texture : m_textures) {
m_textures[i].texture = NULL; texture.texture = NULL;
} }
// is deleted by guiformspec! // is deleted by guiformspec!
m_buttonhandler = new TextDestGuiEngine(this); m_buttonhandler = new TextDestGuiEngine(this);
@ -299,9 +298,9 @@ GUIEngine::~GUIEngine()
m_irr_toplefttext->setText(L""); m_irr_toplefttext->setText(L"");
//clean up texture pointers //clean up texture pointers
for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) { for (image_definition &texture : m_textures) {
if (m_textures[i].texture) if (texture.texture)
RenderingEngine::get_video_driver()->removeTexture(m_textures[i].texture); RenderingEngine::get_video_driver()->removeTexture(texture.texture);
} }
delete m_texture_source; delete m_texture_source;
@ -502,7 +501,7 @@ bool GUIEngine::setTexture(texture_layer layer, std::string texturepath,
m_textures[layer].texture = NULL; m_textures[layer].texture = NULL;
} }
if ((texturepath == "") || !fs::PathExists(texturepath)) { if (texturepath.empty() || !fs::PathExists(texturepath)) {
return false; return false;
} }
@ -510,7 +509,7 @@ bool GUIEngine::setTexture(texture_layer layer, std::string texturepath,
m_textures[layer].tile = tile_image; m_textures[layer].tile = tile_image;
m_textures[layer].minsize = minsize; m_textures[layer].minsize = minsize;
if (m_textures[layer].texture == NULL) { if (!m_textures[layer].texture) {
return false; return false;
} }

View File

@ -113,9 +113,8 @@ GUIFormSpecMenu::~GUIFormSpecMenu()
{ {
removeChildren(); removeChildren();
for (u32 i = 0; i < m_tables.size(); ++i) { for (auto &table_it : m_tables) {
GUITable *table = m_tables[i].second; table_it.second->drop();
table->drop();
} }
delete m_selected_item; delete m_selected_item;
@ -161,29 +160,26 @@ void GUIFormSpecMenu::setInitialFocus()
} }
// 1. first empty editbox // 1. first empty editbox
for (core::list<gui::IGUIElement*>::Iterator it = children.begin(); for (gui::IGUIElement *it : children) {
it != children.end(); ++it) { if (it->getType() == gui::EGUIET_EDIT_BOX
if ((*it)->getType() == gui::EGUIET_EDIT_BOX && it->getText()[0] == 0) {
&& (*it)->getText()[0] == 0) { Environment->setFocus(it);
Environment->setFocus(*it);
return; return;
} }
} }
// 2. first editbox // 2. first editbox
for (core::list<gui::IGUIElement*>::Iterator it = children.begin(); for (gui::IGUIElement *it : children) {
it != children.end(); ++it) { if (it->getType() == gui::EGUIET_EDIT_BOX) {
if ((*it)->getType() == gui::EGUIET_EDIT_BOX) { Environment->setFocus(it);
Environment->setFocus(*it);
return; return;
} }
} }
// 3. first table // 3. first table
for (core::list<gui::IGUIElement*>::Iterator it = children.begin(); for (gui::IGUIElement *it : children) {
it != children.end(); ++it) { if (it->getTypeName() == std::string("GUITable")) {
if ((*it)->getTypeName() == std::string("GUITable")) { Environment->setFocus(it);
Environment->setFocus(*it);
return; return;
} }
} }
@ -198,11 +194,10 @@ void GUIFormSpecMenu::setInitialFocus()
} }
// 5. first focusable (not statictext, not tabheader) // 5. first focusable (not statictext, not tabheader)
for (core::list<gui::IGUIElement*>::Iterator it = children.begin(); for (gui::IGUIElement *it : children) {
it != children.end(); ++it) { if (it->getType() != gui::EGUIET_STATIC_TEXT &&
if ((*it)->getType() != gui::EGUIET_STATIC_TEXT && it->getType() != gui::EGUIET_TAB_CONTROL) {
(*it)->getType() != gui::EGUIET_TAB_CONTROL) { Environment->setFocus(it);
Environment->setFocus(*it);
return; return;
} }
} }
@ -216,18 +211,18 @@ void GUIFormSpecMenu::setInitialFocus()
GUITable* GUIFormSpecMenu::getTable(const std::string &tablename) GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
{ {
for (u32 i = 0; i < m_tables.size(); ++i) { for (auto &table : m_tables) {
if (tablename == m_tables[i].first.fname) if (tablename == table.first.fname)
return m_tables[i].second; return table.second;
} }
return 0; return 0;
} }
std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name) std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
{ {
for (u32 i = 0; i < m_dropdowns.size(); ++i) { for (auto &dropdown : m_dropdowns) {
if (name == m_dropdowns[i].first.fname) if (name == dropdown.first.fname)
return &m_dropdowns[i].second; return &dropdown.second;
} }
return NULL; return NULL;
} }
@ -300,7 +295,7 @@ void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
std::string listname = parts[1]; std::string listname = parts[1];
std::vector<std::string> v_pos = split(parts[2],','); std::vector<std::string> v_pos = split(parts[2],',');
std::vector<std::string> v_geom = split(parts[3],','); std::vector<std::string> v_geom = split(parts[3],',');
std::string startindex = ""; std::string startindex;
if (parts.size() == 5) if (parts.size() == 5)
startindex = parts[4]; startindex = parts[4];
@ -323,7 +318,7 @@ void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
geom.Y = stoi(v_geom[1]); geom.Y = stoi(v_geom[1]);
s32 start_i = 0; s32 start_i = 0;
if(startindex != "") if (!startindex.empty())
start_i = stoi(startindex); start_i = stoi(startindex);
if (geom.X < 0 || geom.Y < 0 || start_i < 0) { if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
@ -333,7 +328,7 @@ void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
if(!data->explicit_size) if(!data->explicit_size)
warningstream<<"invalid use of list without a size[] element"<<std::endl; warningstream<<"invalid use of list without a size[] element"<<std::endl;
m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i)); m_inventorylists.emplace_back(loc, listname, pos, geom, start_i);
return; return;
} }
errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl; errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'" << std::endl;
@ -359,17 +354,20 @@ void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element
else else
loc.deSerialize(location); loc.deSerialize(location);
m_inventory_rings.push_back(ListRingSpec(loc, listname)); m_inventory_rings.emplace_back(loc, listname);
return; return;
} else if ((element == "") && (m_inventorylists.size() > 1)) { }
if (element.empty() && m_inventorylists.size() > 1) {
size_t siz = m_inventorylists.size(); size_t siz = m_inventorylists.size();
// insert the last two inv list elements into the list ring // insert the last two inv list elements into the list ring
const ListDrawSpec &spa = m_inventorylists[siz - 2]; const ListDrawSpec &spa = m_inventorylists[siz - 2];
const ListDrawSpec &spb = m_inventorylists[siz - 1]; const ListDrawSpec &spb = m_inventorylists[siz - 1];
m_inventory_rings.push_back(ListRingSpec(spa.inventoryloc, spa.listname)); m_inventory_rings.emplace_back(spa.inventoryloc, spa.listname);
m_inventory_rings.push_back(ListRingSpec(spb.inventoryloc, spb.listname)); m_inventory_rings.emplace_back(spb.inventoryloc, spb.listname);
return; return;
} }
errorstream<< "Invalid list ring element(" << parts.size() << ", " errorstream<< "Invalid list ring element(" << parts.size() << ", "
<< m_inventorylists.size() << "): '" << element << "'" << std::endl; << m_inventorylists.size() << "): '" << element << "'" << std::endl;
} }
@ -384,7 +382,7 @@ void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element
std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_pos = split(parts[0],',');
std::string name = parts[1]; std::string name = parts[1];
std::string label = parts[2]; std::string label = parts[2];
std::string selected = ""; std::string selected;
if (parts.size() >= 4) if (parts.size() >= 4)
selected = parts[3]; selected = parts[3];
@ -423,7 +421,7 @@ void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element
Environment->setFocus(e); Environment->setFocus(e);
} }
m_checkboxes.push_back(std::pair<FieldSpec,gui::IGUICheckBox*>(spec,e)); m_checkboxes.emplace_back(spec,e);
m_fields.push_back(spec); m_fields.push_back(spec);
return; return;
} }
@ -482,7 +480,7 @@ void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &elemen
e->setSmallStep(10); e->setSmallStep(10);
e->setLargeStep(100); e->setLargeStep(100);
m_scrollbars.push_back(std::pair<FieldSpec,gui::IGUIScrollBar*>(spec,e)); m_scrollbars.emplace_back(spec,e);
m_fields.push_back(spec); m_fields.push_back(spec);
return; return;
} }
@ -513,9 +511,11 @@ void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
if (!data->explicit_size) if (!data->explicit_size)
warningstream<<"invalid use of image without a size[] element"<<std::endl; warningstream<<"invalid use of image without a size[] element"<<std::endl;
m_images.push_back(ImageDrawSpec(name, pos, geom)); m_images.emplace_back(name, pos, geom);
return; return;
} else if (parts.size() == 2) { }
if (parts.size() == 2) {
std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_pos = split(parts[0],',');
std::string name = unescape_string(parts[1]); std::string name = unescape_string(parts[1]);
@ -527,7 +527,7 @@ void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
if (!data->explicit_size) if (!data->explicit_size)
warningstream<<"invalid use of image without a size[] element"<<std::endl; warningstream<<"invalid use of image without a size[] element"<<std::endl;
m_images.push_back(ImageDrawSpec(name, pos)); m_images.emplace_back(name, pos);
return; return;
} }
errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl; errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl;
@ -557,7 +557,7 @@ void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &elemen
if(!data->explicit_size) if(!data->explicit_size)
warningstream<<"invalid use of item_image without a size[] element"<<std::endl; warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
m_itemimages.push_back(ImageDrawSpec("", name, pos, geom)); m_itemimages.emplace_back("", name, pos, geom);
return; return;
} }
errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl; errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl;
@ -649,7 +649,7 @@ void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &eleme
pos.Y = stoi(v_pos[1]); //acts as offset pos.Y = stoi(v_pos[1]); //acts as offset
clip = true; clip = true;
} }
m_backgrounds.push_back(ImageDrawSpec(name, pos, geom, clip)); m_backgrounds.emplace_back(name, pos, geom, clip);
return; return;
} }
@ -661,9 +661,9 @@ void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &ele
std::vector<std::string> parts = split(element,';'); std::vector<std::string> parts = split(element,';');
data->table_options.clear(); data->table_options.clear();
for (size_t i = 0; i < parts.size(); ++i) { for (const std::string &part : parts) {
// Parse table option // Parse table option
std::string opt = unescape_string(parts[i]); std::string opt = unescape_string(part);
data->table_options.push_back(GUITable::splitOption(opt)); data->table_options.push_back(GUITable::splitOption(opt));
} }
} }
@ -673,8 +673,8 @@ void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &ele
std::vector<std::string> parts = split(element,';'); std::vector<std::string> parts = split(element,';');
data->table_columns.clear(); data->table_columns.clear();
for (size_t i = 0; i < parts.size(); ++i) { for (const std::string &part : parts) {
std::vector<std::string> col_parts = split(parts[i],','); std::vector<std::string> col_parts = split(part,',');
GUITable::TableColumn column; GUITable::TableColumn column;
// Parse column type // Parse column type
if (!col_parts.empty()) if (!col_parts.empty())
@ -699,7 +699,7 @@ void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
std::vector<std::string> v_geom = split(parts[1],','); std::vector<std::string> v_geom = split(parts[1],',');
std::string name = parts[2]; std::string name = parts[2];
std::vector<std::string> items = split(parts[3],','); std::vector<std::string> items = split(parts[3],',');
std::string str_initial_selection = ""; std::string str_initial_selection;
std::string str_transparent = "false"; std::string str_transparent = "false";
if (parts.size() >= 5) if (parts.size() >= 5)
@ -727,8 +727,8 @@ void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
spec.ftype = f_Table; spec.ftype = f_Table;
for (unsigned int i = 0; i < items.size(); ++i) { for (std::string &item : items) {
items[i] = unescape_enriched(unescape_string(items[i])); item = unescape_enriched(unescape_string(item));
} }
//now really show table //now really show table
@ -745,11 +745,10 @@ void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
e->setDynamicData(data->table_dyndata[name]); e->setDynamicData(data->table_dyndata[name]);
} }
if ((str_initial_selection != "") && if (!str_initial_selection.empty() && str_initial_selection != "0")
(str_initial_selection != "0")) e->setSelected(stoi(str_initial_selection));
e->setSelected(stoi(str_initial_selection.c_str()));
m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e)); m_tables.emplace_back(spec, e);
m_fields.push_back(spec); m_fields.push_back(spec);
return; return;
} }
@ -767,7 +766,7 @@ void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element
std::vector<std::string> v_geom = split(parts[1],','); std::vector<std::string> v_geom = split(parts[1],',');
std::string name = parts[2]; std::string name = parts[2];
std::vector<std::string> items = split(parts[3],','); std::vector<std::string> items = split(parts[3],',');
std::string str_initial_selection = ""; std::string str_initial_selection;
std::string str_transparent = "false"; std::string str_transparent = "false";
if (parts.size() >= 5) if (parts.size() >= 5)
@ -799,8 +798,8 @@ void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element
spec.ftype = f_Table; spec.ftype = f_Table;
for (unsigned int i = 0; i < items.size(); ++i) { for (std::string &item : items) {
items[i] = unescape_enriched(unescape_string(items[i])); item = unescape_enriched(unescape_string(item));
} }
//now really show list //now really show list
@ -817,11 +816,10 @@ void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element
e->setDynamicData(data->table_dyndata[name]); e->setDynamicData(data->table_dyndata[name]);
} }
if ((str_initial_selection != "") && if (!str_initial_selection.empty() && str_initial_selection != "0")
(str_initial_selection != "0")) e->setSelected(stoi(str_initial_selection));
e->setSelected(stoi(str_initial_selection.c_str()));
m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e)); m_tables.emplace_back(spec, e);
m_fields.push_back(spec); m_fields.push_back(spec);
return; return;
} }
@ -839,7 +837,7 @@ void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element
std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_pos = split(parts[0],',');
std::string name = parts[2]; std::string name = parts[2];
std::vector<std::string> items = split(parts[3],','); std::vector<std::string> items = split(parts[3],',');
std::string str_initial_selection = ""; std::string str_initial_selection;
str_initial_selection = parts[4]; str_initial_selection = parts[4];
MY_CHECKPOS("dropdown",0); MY_CHECKPOS("dropdown",0);
@ -870,21 +868,20 @@ void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element
Environment->setFocus(e); Environment->setFocus(e);
} }
for (unsigned int i=0; i < items.size(); i++) { for (const std::string &item : items) {
e->addItem(unescape_enriched(unescape_string( e->addItem(unescape_enriched(unescape_string(
utf8_to_wide(items[i]))).c_str()); utf8_to_wide(item))).c_str());
} }
if (str_initial_selection != "") if (!str_initial_selection.empty())
e->setSelected(stoi(str_initial_selection.c_str())-1); e->setSelected(stoi(str_initial_selection)-1);
m_fields.push_back(spec); m_fields.push_back(spec);
m_dropdowns.push_back(std::pair<FieldSpec, m_dropdowns.emplace_back(spec, std::vector<std::string>());
std::vector<std::string> >(spec, std::vector<std::string>()));
std::vector<std::string> &values = m_dropdowns.back().second; std::vector<std::string> &values = m_dropdowns.back().second;
for (unsigned int i = 0; i < items.size(); i++) { for (const std::string &item : items) {
values.push_back(unescape_string(items[i])); values.push_back(unescape_string(item));
} }
return; return;
@ -960,8 +957,8 @@ void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element
evt.EventType = EET_KEY_INPUT_EVENT; evt.EventType = EET_KEY_INPUT_EVENT;
evt.KeyInput.Key = KEY_END; evt.KeyInput.Key = KEY_END;
evt.KeyInput.Char = 0; evt.KeyInput.Char = 0;
evt.KeyInput.Control = 0; evt.KeyInput.Control = false;
evt.KeyInput.Shift = 0; evt.KeyInput.Shift = false;
evt.KeyInput.PressedDown = true; evt.KeyInput.PressedDown = true;
e->OnEvent(evt); e->OnEvent(evt);
@ -1011,13 +1008,10 @@ void GUIFormSpecMenu::parseSimpleField(parserData* data,
258+m_fields.size() 258+m_fields.size()
); );
if (name == "") if (name.empty()) {
{
// spec field id to 0, this stops submit searching for a value that isn't there // spec field id to 0, this stops submit searching for a value that isn't there
addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid); addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid);
} } else {
else
{
spec.send = true; spec.send = true;
gui::IGUIElement *e; gui::IGUIElement *e;
#if USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9 #if USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9
@ -1114,13 +1108,10 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>&
258+m_fields.size() 258+m_fields.size()
); );
if (name == "") if (name.empty()) {
{
// spec field id to 0, this stops submit searching for a value that isn't there // spec field id to 0, this stops submit searching for a value that isn't there
addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid); addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid);
} } else {
else
{
spec.send = true; spec.send = true;
gui::IGUIEditBox *e; gui::IGUIEditBox *e;
@ -1278,10 +1269,10 @@ void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &elemen
if(!data->explicit_size) if(!data->explicit_size)
warningstream<<"invalid use of label without a size[] element"<<std::endl; warningstream<<"invalid use of label without a size[] element"<<std::endl;
std::wstring label = L""; std::wstring label;
for (unsigned int i=0; i < text.length(); i++) { for (wchar_t i : text) {
label += text[i]; label += i;
label += L"\n"; label += L"\n";
} }
@ -1326,7 +1317,7 @@ void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &elem
bool noclip = false; bool noclip = false;
bool drawborder = true; bool drawborder = true;
std::string pressed_image_name = ""; std::string pressed_image_name;
if (parts.size() >= 7) { if (parts.size() >= 7) {
if (parts[5] == "true") if (parts[5] == "true")
@ -1362,7 +1353,7 @@ void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &elem
video::ITexture *texture = 0; video::ITexture *texture = 0;
video::ITexture *pressed_texture = 0; video::ITexture *pressed_texture = 0;
texture = m_tsrc->getTexture(image_name); texture = m_tsrc->getTexture(image_name);
if (pressed_image_name != "") if (!pressed_image_name.empty())
pressed_texture = m_tsrc->getTexture(pressed_image_name); pressed_texture = m_tsrc->getTexture(pressed_image_name);
else else
pressed_texture = texture; pressed_texture = texture;
@ -1444,9 +1435,9 @@ void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &elemen
e->setNotClipped(true); e->setNotClipped(true);
for (unsigned int i = 0; i < buttons.size(); i++) { for (const std::string &button : buttons) {
e->addTab(unescape_enriched(unescape_string( e->addTab(unescape_enriched(unescape_string(
utf8_to_wide(buttons[i]))).c_str(), -1); utf8_to_wide(button))).c_str(), -1);
} }
if ((tab_index >= 0) && if ((tab_index >= 0) &&
@ -1528,8 +1519,8 @@ void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &
pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing; pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
pos.X += stof(v_pos[0]) * (float) spacing.X; pos.X += stof(v_pos[0]) * (float) spacing.X;
pos.Y += stof(v_pos[1]) * (float) spacing.Y; pos.Y += stof(v_pos[1]) * (float) spacing.Y;
m_itemimages.push_back(ImageDrawSpec("", item_name, e, pos, geom)); m_itemimages.emplace_back("", item_name, e, pos, geom);
m_static_texts.push_back(StaticTextSpec(utf8_to_wide(label), rect, e)); m_static_texts.emplace_back(utf8_to_wide(label), rect, e);
return; return;
} }
errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl;
@ -1625,7 +1616,9 @@ void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
m_tooltips[name] = TooltipSpec(unescape_string(parts[1]), m_tooltips[name] = TooltipSpec(unescape_string(parts[1]),
m_default_tooltip_bgcolor, m_default_tooltip_color); m_default_tooltip_bgcolor, m_default_tooltip_color);
return; return;
} else if (parts.size() == 4) { }
if (parts.size() == 4) {
std::string name = parts[0]; std::string name = parts[0];
video::SColor tmp_color1, tmp_color2; video::SColor tmp_color1, tmp_color2;
if ( parseColorString(parts[2], tmp_color1, false) && parseColorString(parts[3], tmp_color2, false) ) { if ( parseColorString(parts[2], tmp_color1, false) && parseColorString(parts[3], tmp_color2, false) ) {
@ -1640,7 +1633,7 @@ void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
bool GUIFormSpecMenu::parseVersionDirect(const std::string &data) bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
{ {
//some prechecks //some prechecks
if (data == "") if (data.empty())
return false; return false;
std::vector<std::string> parts = split(data,'['); std::vector<std::string> parts = split(data,'[');
@ -1663,7 +1656,7 @@ bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element) bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
{ {
if (element == "") if (element.empty())
return false; return false;
std::vector<std::string> parts = split(element,'['); std::vector<std::string> parts = split(element,'[');
@ -1757,7 +1750,7 @@ void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element) void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
{ {
//some prechecks //some prechecks
if (element == "") if (element.empty())
return; return;
std::vector<std::string> parts = split(element,'['); std::vector<std::string> parts = split(element,'[');
@ -1930,9 +1923,9 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
parserData mydata; parserData mydata;
//preserve tables //preserve tables
for (u32 i = 0; i < m_tables.size(); ++i) { for (auto &m_table : m_tables) {
std::string tablename = m_tables[i].first.fname; std::string tablename = m_table.first.fname;
GUITable *table = m_tables[i].second; GUITable *table = m_table.second;
mydata.table_dyndata[tablename] = table->getDynamicData(); mydata.table_dyndata[tablename] = table->getDynamicData();
} }
@ -1945,10 +1938,9 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
if (focused_element && focused_element->getParent() == this) { if (focused_element && focused_element->getParent() == this) {
s32 focused_id = focused_element->getID(); s32 focused_id = focused_element->getID();
if (focused_id > 257) { if (focused_id > 257) {
for (u32 i=0; i<m_fields.size(); i++) { for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
if (m_fields[i].fid == focused_id) { if (field.fid == focused_id) {
mydata.focused_fieldname = mydata.focused_fieldname = field.fname;
m_fields[i].fname;
break; break;
} }
} }
@ -1958,9 +1950,8 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
// Remove children // Remove children
removeChildren(); removeChildren();
for (u32 i = 0; i < m_tables.size(); ++i) { for (auto &table_it : m_tables) {
GUITable *table = m_tables[i].second; table_it.second->drop();
table->drop();
} }
mydata.size= v2s32(100,100); mydata.size= v2s32(100,100);
@ -2020,7 +2011,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
unsigned int i = 0; unsigned int i = 0;
/* try to read version from first element only */ /* try to read version from first element only */
if (elements.size() >= 1) { if (!elements.empty()) {
if ( parseVersionDirect(elements[0]) ) { if ( parseVersionDirect(elements[0]) ) {
i++; i++;
} }
@ -2171,7 +2162,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
// If there are fields without explicit size[], add a "Proceed" // If there are fields without explicit size[], add a "Proceed"
// button and adjust size to fit all the fields. // button and adjust size to fit all the fields.
if (m_fields.size() && !mydata.explicit_size) { if (!m_fields.empty() && !mydata.explicit_size) {
mydata.rect = core::rect<s32>( mydata.rect = core::rect<s32>(
mydata.screensize.X/2 - 580/2, mydata.screensize.X/2 - 580/2,
mydata.screensize.Y/2 - 300/2, mydata.screensize.Y/2 - 300/2,
@ -2257,10 +2248,7 @@ GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
{ {
core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
for(u32 i=0; i<m_inventorylists.size(); i++) for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
{
const ListDrawSpec &s = m_inventorylists[i];
for(s32 i=0; i<s.geom.X*s.geom.Y; i++) { for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
s32 item_i = i + s.start_item_i; s32 item_i = i + s.start_item_i;
s32 x = (i%s.geom.X) * spacing.X; s32 x = (i%s.geom.X) * spacing.X;
@ -2367,7 +2355,7 @@ void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase,
} }
// Draw tooltip // Draw tooltip
std::wstring tooltip_text = L""; std::wstring tooltip_text;
if (hovering && !m_selected_item) { if (hovering && !m_selected_item) {
const std::string &desc = item.metadata.getString("description"); const std::string &desc = item.metadata.getString("description");
if (desc.empty()) if (desc.empty())
@ -2442,9 +2430,7 @@ void GUIFormSpecMenu::drawMenu()
/* /*
Draw backgrounds Draw backgrounds
*/ */
for(u32 i=0; i<m_backgrounds.size(); i++) for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_backgrounds) {
{
const ImageDrawSpec &spec = m_backgrounds[i];
video::ITexture *texture = m_tsrc->getTexture(spec.name); video::ITexture *texture = m_tsrc->getTexture(spec.name);
if (texture != 0) { if (texture != 0) {
@ -2476,10 +2462,7 @@ void GUIFormSpecMenu::drawMenu()
/* /*
Draw Boxes Draw Boxes
*/ */
for(u32 i=0; i<m_boxes.size(); i++) for (const GUIFormSpecMenu::BoxDrawSpec &spec : m_boxes) {
{
const BoxDrawSpec &spec = m_boxes[i];
irr::video::SColor todraw = spec.color; irr::video::SColor todraw = spec.color;
todraw.setAlpha(140); todraw.setAlpha(140);
@ -2498,9 +2481,7 @@ void GUIFormSpecMenu::drawMenu()
/* /*
Draw images Draw images
*/ */
for(u32 i=0; i<m_images.size(); i++) for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_images) {
{
const ImageDrawSpec &spec = m_images[i];
video::ITexture *texture = m_tsrc->getTexture(spec.name); video::ITexture *texture = m_tsrc->getTexture(spec.name);
if (texture != 0) { if (texture != 0) {
@ -2531,12 +2512,10 @@ void GUIFormSpecMenu::drawMenu()
/* /*
Draw item images Draw item images
*/ */
for(u32 i=0; i<m_itemimages.size(); i++) for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_itemimages) {
{
if (m_client == 0) if (m_client == 0)
break; break;
const ImageDrawSpec &spec = m_itemimages[i];
IItemDefManager *idef = m_client->idef(); IItemDefManager *idef = m_client->idef();
ItemStack item; ItemStack item;
item.deSerialize(spec.item_name, idef); item.deSerialize(spec.item_name, idef);
@ -2565,8 +2544,8 @@ void GUIFormSpecMenu::drawMenu()
bool item_hovered = false; bool item_hovered = false;
int start_phase = 0; int start_phase = 0;
for (int phase = start_phase; phase <= 1; phase++) { for (int phase = start_phase; phase <= 1; phase++) {
for (u32 i = 0; i < m_inventorylists.size(); i++) { for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
drawList(m_inventorylists[i], phase, item_hovered); drawList(spec, phase, item_hovered);
} }
} }
if (!item_hovered) { if (!item_hovered) {
@ -2583,8 +2562,7 @@ void GUIFormSpecMenu::drawMenu()
/* /*
Draw static text elements Draw static text elements
*/ */
for (u32 i = 0; i < m_static_texts.size(); i++) { for (const GUIFormSpecMenu::StaticTextSpec &spec : m_static_texts) {
const StaticTextSpec &spec = m_static_texts[i];
core::rect<s32> rect = spec.rect; core::rect<s32> rect = spec.rect;
if (spec.parent_button && spec.parent_button->isPressed()) { if (spec.parent_button && spec.parent_button->isPressed()) {
#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
@ -2625,16 +2603,15 @@ void GUIFormSpecMenu::drawMenu()
// Find and update the current tooltip // Find and update the current tooltip
if (id != -1 && delta >= m_tooltip_show_delay) { if (id != -1 && delta >= m_tooltip_show_delay) {
for (std::vector<FieldSpec>::iterator iter = m_fields.begin(); for (const FieldSpec &field : m_fields) {
iter != m_fields.end(); ++iter) {
if (iter->fid != id) if (field.fid != id)
continue; continue;
const std::wstring &text = m_tooltips[iter->fname].tooltip; const std::wstring &text = m_tooltips[field.fname].tooltip;
if (!text.empty()) if (!text.empty())
showTooltip(text, m_tooltips[iter->fname].color, showTooltip(text, m_tooltips[field.fname].color,
m_tooltips[iter->fname].bgcolor); m_tooltips[field.fname].bgcolor);
break; break;
} }
@ -2707,12 +2684,11 @@ void GUIFormSpecMenu::updateSelectedItem()
// WARNING: BLACK MAGIC // WARNING: BLACK MAGIC
// See if there is a stack suited for our current guess. // See if there is a stack suited for our current guess.
// If such stack does not exist, clear the guess. // If such stack does not exist, clear the guess.
if(m_selected_content_guess.name != "" && if (!m_selected_content_guess.name.empty() &&
selected.name == m_selected_content_guess.name && selected.name == m_selected_content_guess.name &&
selected.count == m_selected_content_guess.count){ selected.count == m_selected_content_guess.count){
// Selected item fits the guess. Skip the black magic. // Selected item fits the guess. Skip the black magic.
} } else if (!m_selected_content_guess.name.empty()) {
else if(m_selected_content_guess.name != ""){
bool found = false; bool found = false;
for(u32 i=0; i<m_inventorylists.size() && !found; i++){ for(u32 i=0; i<m_inventorylists.size() && !found; i++){
const ListDrawSpec &s = m_inventorylists[i]; const ListDrawSpec &s = m_inventorylists[i];
@ -2749,9 +2725,7 @@ void GUIFormSpecMenu::updateSelectedItem()
// If craftresult is nonempty and nothing else is selected, select it now. // If craftresult is nonempty and nothing else is selected, select it now.
if(!m_selected_item) if(!m_selected_item)
{ {
for(u32 i=0; i<m_inventorylists.size(); i++) for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
{
const ListDrawSpec &s = m_inventorylists[i];
if(s.listname == "craftpreview") if(s.listname == "craftpreview")
{ {
Inventory *inv = m_invmgr->getInventory(s.inventoryloc); Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
@ -2853,8 +2827,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
current_keys_pending.key_escape = false; current_keys_pending.key_escape = false;
} }
for(unsigned int i=0; i<m_fields.size(); i++) { for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
const FieldSpec &s = m_fields[i];
if(s.send) { if(s.send) {
std::string name = s.fname; std::string name = s.fname;
if (s.ftype == f_Button) { if (s.ftype == f_Button) {
@ -2871,7 +2844,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
IGUIElement * element = getElementFromId(s.fid); IGUIElement * element = getElementFromId(s.fid);
gui::IGUIComboBox *e = NULL; gui::IGUIComboBox *e = NULL;
if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) { if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
e = static_cast<gui::IGUIComboBox*>(element); e = dynamic_cast<gui::IGUIComboBox*>(element);
} }
s32 selected = e->getSelected(); s32 selected = e->getSelected();
if (selected >= 0) { if (selected >= 0) {
@ -2888,7 +2861,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
IGUIElement * element = getElementFromId(s.fid); IGUIElement * element = getElementFromId(s.fid);
gui::IGUITabControl *e = NULL; gui::IGUITabControl *e = NULL;
if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) { if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
e = static_cast<gui::IGUITabControl*>(element); e = dynamic_cast<gui::IGUITabControl*>(element);
} }
if (e != 0) { if (e != 0) {
@ -2903,7 +2876,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
IGUIElement * element = getElementFromId(s.fid); IGUIElement * element = getElementFromId(s.fid);
gui::IGUICheckBox *e = NULL; gui::IGUICheckBox *e = NULL;
if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) { if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
e = static_cast<gui::IGUICheckBox*>(element); e = dynamic_cast<gui::IGUICheckBox*>(element);
} }
if (e != 0) { if (e != 0) {
@ -2919,7 +2892,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
IGUIElement * element = getElementFromId(s.fid); IGUIElement * element = getElementFromId(s.fid);
gui::IGUIScrollBar *e = NULL; gui::IGUIScrollBar *e = NULL;
if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) { if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
e = static_cast<gui::IGUIScrollBar*>(element); e = dynamic_cast<gui::IGUIScrollBar*>(element);
} }
if (e != 0) { if (e != 0) {
@ -3278,7 +3251,9 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) { ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
tryClose(); tryClose();
return true; return true;
} else if (m_client != NULL && event.KeyInput.PressedDown && }
if (m_client != NULL && event.KeyInput.PressedDown &&
(kp == getKeySetting("keymap_screenshot"))) { (kp == getKeySetting("keymap_screenshot"))) {
m_client->makeScreenshot(); m_client->makeScreenshot();
} }
@ -3687,8 +3662,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
&& isVisible()) { && isVisible()) {
// find the element that was clicked // find the element that was clicked
for (unsigned int i=0; i<m_fields.size(); i++) { for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
FieldSpec &s = m_fields[i];
if ((s.ftype == f_TabHeader) && if ((s.ftype == f_TabHeader) &&
(s.fid == event.GUIEvent.Caller->getID())) { (s.fid == event.GUIEvent.Caller->getID())) {
s.send = true; s.send = true;
@ -3726,12 +3700,11 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
} }
// find the element that was clicked // find the element that was clicked
for (u32 i = 0; i < m_fields.size(); i++) { for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
FieldSpec &s = m_fields[i];
// if its a button, set the send field so // if its a button, set the send field so
// lua knows which button was pressed // lua knows which button was pressed
if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) && if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
(s.fid == event.GUIEvent.Caller->getID())) { s.fid == event.GUIEvent.Caller->getID()) {
s.send = true; s.send = true;
if (s.is_exit) { if (s.is_exit) {
if (m_allowclose) { if (m_allowclose) {
@ -3741,16 +3714,16 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
m_text_dst->gotText(L"ExitButton"); m_text_dst->gotText(L"ExitButton");
} }
return true; return true;
} else {
acceptInput(quit_mode_no);
s.send = false;
return true;
} }
acceptInput(quit_mode_no);
s.send = false;
return true;
} else if ((s.ftype == f_DropDown) && } else if ((s.ftype == f_DropDown) &&
(s.fid == event.GUIEvent.Caller->getID())) { (s.fid == event.GUIEvent.Caller->getID())) {
// only send the changed dropdown // only send the changed dropdown
for (u32 i = 0; i < m_fields.size(); i++) { for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
FieldSpec &s2 = m_fields[i];
if (s2.ftype == f_DropDown) { if (s2.ftype == f_DropDown) {
s2.send = false; s2.send = false;
} }
@ -3760,8 +3733,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
// revert configuration to make sure dropdowns are sent on // revert configuration to make sure dropdowns are sent on
// regular button click // regular button click
for (u32 i = 0; i < m_fields.size(); i++) { for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
FieldSpec &s2 = m_fields[i];
if (s2.ftype == f_DropDown) { if (s2.ftype == f_DropDown) {
s2.send = true; s2.send = true;
} }
@ -3779,8 +3751,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) { if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
if (event.GUIEvent.Caller->getID() > 257) { if (event.GUIEvent.Caller->getID() > 257) {
bool close_on_enter = true; bool close_on_enter = true;
for (u32 i = 0; i < m_fields.size(); i++) { for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
FieldSpec &s = m_fields[i];
if (s.ftype == f_Unknown && if (s.ftype == f_Unknown &&
s.fid == event.GUIEvent.Caller->getID()) { s.fid == event.GUIEvent.Caller->getID()) {
current_field_enter_pending = s.fname; current_field_enter_pending = s.fname;
@ -3810,8 +3781,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
int current_id = event.GUIEvent.Caller->getID(); int current_id = event.GUIEvent.Caller->getID();
if (current_id > 257) { if (current_id > 257) {
// find the element that was clicked // find the element that was clicked
for (u32 i = 0; i < m_fields.size(); i++) { for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
FieldSpec &s = m_fields[i];
// if it's a table, set the send field // if it's a table, set the send field
// so lua knows which table was changed // so lua knows which table was changed
if ((s.ftype == f_Table) && (s.fid == current_id)) { if ((s.ftype == f_Table) && (s.fid == current_id)) {
@ -3835,10 +3805,9 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
*/ */
std::string GUIFormSpecMenu::getNameByID(s32 id) std::string GUIFormSpecMenu::getNameByID(s32 id)
{ {
for(std::vector<FieldSpec>::iterator iter = m_fields.begin(); for (FieldSpec &spec : m_fields) {
iter != m_fields.end(); ++iter) { if (spec.fid == id) {
if (iter->fid == id) { return spec.fname;
return iter->fname;
} }
} }
return ""; return "";
@ -3851,10 +3820,9 @@ std::string GUIFormSpecMenu::getNameByID(s32 id)
*/ */
std::wstring GUIFormSpecMenu::getLabelByID(s32 id) std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
{ {
for(std::vector<FieldSpec>::iterator iter = m_fields.begin(); for (FieldSpec &spec : m_fields) {
iter != m_fields.end(); ++iter) { if (spec.fid == id) {
if (iter->fid == id) { return spec.flabel;
return iter->flabel;
} }
} }
return L""; return L"";

View File

@ -53,7 +53,8 @@ typedef enum {
struct TextDest struct TextDest
{ {
virtual ~TextDest() {} virtual ~TextDest() = default;
// This is deprecated I guess? -celeron55 // This is deprecated I guess? -celeron55
virtual void gotText(const std::wstring &text) {} virtual void gotText(const std::wstring &text) {}
virtual void gotText(const StringMap &fields) = 0; virtual void gotText(const StringMap &fields) = 0;
@ -64,7 +65,7 @@ struct TextDest
class IFormSource class IFormSource
{ {
public: public:
virtual ~IFormSource(){} virtual ~IFormSource() = default;
virtual std::string getForm() = 0; virtual std::string getForm() = 0;
// Fill in variables in field text // Fill in variables in field text
virtual std::string resolveText(const std::string &str) { return str; } virtual std::string resolveText(const std::string &str) { return str; }
@ -74,10 +75,7 @@ class GUIFormSpecMenu : public GUIModalMenu
{ {
struct ItemSpec struct ItemSpec
{ {
ItemSpec() : ItemSpec() = default;
i(-1)
{
}
ItemSpec(const InventoryLocation &a_inventoryloc, ItemSpec(const InventoryLocation &a_inventoryloc,
const std::string &a_listname, const std::string &a_listname,
@ -92,14 +90,13 @@ class GUIFormSpecMenu : public GUIModalMenu
InventoryLocation inventoryloc; InventoryLocation inventoryloc;
std::string listname; std::string listname;
s32 i; s32 i = -1;
}; };
struct ListDrawSpec struct ListDrawSpec
{ {
ListDrawSpec() ListDrawSpec() = default;
{
}
ListDrawSpec(const InventoryLocation &a_inventoryloc, ListDrawSpec(const InventoryLocation &a_inventoryloc,
const std::string &a_listname, const std::string &a_listname,
v2s32 a_pos, v2s32 a_geom, s32 a_start_item_i): v2s32 a_pos, v2s32 a_geom, s32 a_start_item_i):
@ -120,9 +117,8 @@ class GUIFormSpecMenu : public GUIModalMenu
struct ListRingSpec struct ListRingSpec
{ {
ListRingSpec() ListRingSpec() = default;
{
}
ListRingSpec(const InventoryLocation &a_inventoryloc, ListRingSpec(const InventoryLocation &a_inventoryloc,
const std::string &a_listname): const std::string &a_listname):
inventoryloc(a_inventoryloc), inventoryloc(a_inventoryloc),
@ -201,9 +197,8 @@ class GUIFormSpecMenu : public GUIModalMenu
struct FieldSpec struct FieldSpec
{ {
FieldSpec() FieldSpec() = default;
{
}
FieldSpec(const std::string &name, const std::wstring &label, FieldSpec(const std::string &name, const std::wstring &label,
const std::wstring &default_text, int id) : const std::wstring &default_text, int id) :
fname(name), fname(name),
@ -241,7 +236,8 @@ class GUIFormSpecMenu : public GUIModalMenu
struct TooltipSpec struct TooltipSpec
{ {
TooltipSpec() {} TooltipSpec() = default;
TooltipSpec(const std::string &a_tooltip, irr::video::SColor a_bgcolor, TooltipSpec(const std::string &a_tooltip, irr::video::SColor a_bgcolor,
irr::video::SColor a_color): irr::video::SColor a_color):
tooltip(utf8_to_wide(a_tooltip)), tooltip(utf8_to_wide(a_tooltip)),
@ -552,9 +548,7 @@ public:
{ {
} }
~FormspecFormSource() ~FormspecFormSource() = default;
{
}
void setForm(const std::string &formspec) void setForm(const std::string &formspec)
{ {

View File

@ -85,18 +85,17 @@ GUIKeyChangeMenu::GUIKeyChangeMenu(gui::IGUIEnvironment* env,
GUIModalMenu(env, parent, id, menumgr) GUIModalMenu(env, parent, id, menumgr)
{ {
init_keys(); init_keys();
for (size_t i = 0; i < key_settings.size(); i++) for (key_setting *ks : key_settings)
key_used.push_back(key_settings.at(i)->key); key_used.push_back(ks->key);
} }
GUIKeyChangeMenu::~GUIKeyChangeMenu() GUIKeyChangeMenu::~GUIKeyChangeMenu()
{ {
removeChildren(); removeChildren();
for (std::vector<key_setting*>::iterator iter = key_settings.begin(); for (key_setting *ks : key_settings) {
iter != key_settings.end(); ++iter) { delete[] ks->button_name;
delete[] (*iter)->button_name; delete ks;
delete (*iter);
} }
key_settings.clear(); key_settings.clear();
} }
@ -105,15 +104,12 @@ void GUIKeyChangeMenu::removeChildren()
{ {
const core::list<gui::IGUIElement*> &children = getChildren(); const core::list<gui::IGUIElement*> &children = getChildren();
core::list<gui::IGUIElement*> children_copy; core::list<gui::IGUIElement*> children_copy;
for (core::list<gui::IGUIElement*>::ConstIterator i = children.begin(); i for (gui::IGUIElement*i : children) {
!= children.end(); i++) children_copy.push_back(i);
{
children_copy.push_back(*i);
} }
for (core::list<gui::IGUIElement*>::Iterator i = children_copy.begin(); i
!= children_copy.end(); i++) for (gui::IGUIElement *i : children_copy) {
{ i->remove();
(*i)->remove();
} }
} }
@ -238,11 +234,10 @@ void GUIKeyChangeMenu::drawMenu()
bool GUIKeyChangeMenu::acceptInput() bool GUIKeyChangeMenu::acceptInput()
{ {
for(size_t i = 0; i < key_settings.size(); i++) for (key_setting *k : key_settings) {
{
key_setting *k = key_settings.at(i);
g_settings->set(k->setting_name, k->key.sym()); g_settings->set(k->setting_name, k->key.sym());
} }
{ {
gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUX1_DESCENDS); gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUX1_DESCENDS);
if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX)
@ -265,11 +260,8 @@ bool GUIKeyChangeMenu::resetMenu()
{ {
if (activeKey >= 0) if (activeKey >= 0)
{ {
for(size_t i = 0; i < key_settings.size(); i++) for (key_setting *k : key_settings) {
{ if (k->id == activeKey) {
key_setting *k = key_settings.at(i);
if(k->id == activeKey)
{
const wchar_t *text = wgettext(k->key.name()); const wchar_t *text = wgettext(k->key.name());
k->button->setText(text); k->button->setText(text);
delete[] text; delete[] text;
@ -317,11 +309,9 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
// But go on // But go on
{ {
key_setting *k = NULL; key_setting *k = NULL;
for(size_t i = 0; i < key_settings.size(); i++) for (key_setting *ks : key_settings) {
{ if (ks->id == activeKey) {
if(key_settings.at(i)->id == activeKey) k = ks;
{
k = key_settings.at(i);
break; break;
} }
} }
@ -337,10 +327,10 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
if(shift_went_down){ if(shift_went_down){
shift_down = true; shift_down = true;
return false; return false;
}else{
activeKey = -1;
return true;
} }
activeKey = -1;
return true;
} }
} else if (event.EventType == EET_KEY_INPUT_EVENT && activeKey < 0 } else if (event.EventType == EET_KEY_INPUT_EVENT && activeKey < 0
&& event.KeyInput.PressedDown && event.KeyInput.PressedDown
@ -372,11 +362,10 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
return true; return true;
default: default:
key_setting *k = NULL; key_setting *k = NULL;
for(size_t i = 0; i < key_settings.size(); i++)
{ for (key_setting *ks : key_settings) {
if(key_settings.at(i)->id == event.GUIEvent.Caller->getID()) if (ks->id == event.GUIEvent.Caller->getID()) {
{ k = ks;
k = key_settings.at(i);
break; break;
} }
} }

View File

@ -52,13 +52,12 @@ void GUIPasswordChange::removeChildren()
{ {
const core::list<gui::IGUIElement *> &children = getChildren(); const core::list<gui::IGUIElement *> &children = getChildren();
core::list<gui::IGUIElement *> children_copy; core::list<gui::IGUIElement *> children_copy;
for (core::list<gui::IGUIElement *>::ConstIterator i = children.begin(); for (gui::IGUIElement *i : children) {
i != children.end(); i++) { children_copy.push_back(i);
children_copy.push_back(*i);
} }
for (core::list<gui::IGUIElement *>::Iterator i = children_copy.begin();
i != children_copy.end(); i++) { for (gui::IGUIElement *i : children_copy) {
(*i)->remove(); i->remove();
} }
} }
void GUIPasswordChange::regenerateGui(v2u32 screensize) void GUIPasswordChange::regenerateGui(v2u32 screensize)

View File

@ -91,8 +91,8 @@ GUITable::GUITable(gui::IGUIEnvironment *env,
GUITable::~GUITable() GUITable::~GUITable()
{ {
for (size_t i = 0; i < m_rows.size(); ++i) for (GUITable::Row &row : m_rows)
delete[] m_rows[i].cells; delete[] row.cells;
if (m_font) if (m_font)
m_font->drop(); m_font->drop();
@ -105,9 +105,9 @@ GUITable::Option GUITable::splitOption(const std::string &str)
size_t equal_pos = str.find('='); size_t equal_pos = str.find('=');
if (equal_pos == std::string::npos) if (equal_pos == std::string::npos)
return GUITable::Option(str, ""); return GUITable::Option(str, "");
else
return GUITable::Option(str.substr(0, equal_pos), return GUITable::Option(str.substr(0, equal_pos),
str.substr(equal_pos + 1)); str.substr(equal_pos + 1));
} }
void GUITable::setTextList(const std::vector<std::string> &content, void GUITable::setTextList(const std::vector<std::string> &content,
@ -194,9 +194,9 @@ void GUITable::setTable(const TableOptions &options,
// Handle table options // Handle table options
video::SColor default_color(255, 255, 255, 255); video::SColor default_color(255, 255, 255, 255);
s32 opendepth = 0; s32 opendepth = 0;
for (size_t k = 0; k < options.size(); ++k) { for (const Option &option : options) {
const std::string &name = options[k].name; const std::string &name = option.name;
const std::string &value = options[k].value; const std::string &value = option.value;
if (name == "color") if (name == "color")
parseColorString(value, m_color, false); parseColorString(value, m_color, false);
else if (name == "background") else if (name == "background")
@ -224,7 +224,7 @@ void GUITable::setTable(const TableOptions &options,
// Append empty strings to content if there is an incomplete row // Append empty strings to content if there is an incomplete row
s32 cellcount = rowcount * colcount; s32 cellcount = rowcount * colcount;
while (content.size() < (u32) cellcount) while (content.size() < (u32) cellcount)
content.push_back(""); content.emplace_back("");
// Create temporary rows (for processing columns) // Create temporary rows (for processing columns)
struct TempRow { struct TempRow {
@ -289,9 +289,9 @@ void GUITable::setTable(const TableOptions &options,
width = myround(em * 1.5); // default indent width width = myround(em * 1.5); // default indent width
} }
for (size_t k = 0; k < columns[j].options.size(); ++k) { for (const Option &option : columns[j].options) {
const std::string &name = columns[j].options[k].name; const std::string &name = option.name;
const std::string &value = columns[j].options[k].value; const std::string &value = option.value;
if (name == "padding") if (name == "padding")
padding = myround(stof(value) * em); padding = myround(stof(value) * em);
else if (name == "tooltip") else if (name == "tooltip")
@ -404,7 +404,7 @@ void GUITable::setTable(const TableOptions &options,
for (s32 i = 0; i < rowcount; ++i) { for (s32 i = 0; i < rowcount; ++i) {
video::SColor cellcolor(255, 255, 255, 255); video::SColor cellcolor(255, 255, 255, 255);
if (parseColorString(content[i * colcount + j], cellcolor, true)) if (parseColorString(content[i * colcount + j], cellcolor, true))
rows[i].colors.push_back(std::make_pair(cellcolor, j+span)); rows[i].colors.emplace_back(cellcolor, j+span);
} }
} }
else if (columntype == COLUMN_TYPE_INDENT || else if (columntype == COLUMN_TYPE_INDENT ||
@ -481,8 +481,8 @@ void GUITable::setTable(const TableOptions &options,
void GUITable::clear() void GUITable::clear()
{ {
// Clean up cells and rows // Clean up cells and rows
for (size_t i = 0; i < m_rows.size(); ++i) for (GUITable::Row &row : m_rows)
delete[] m_rows[i].cells; delete[] row.cells;
m_rows.clear(); m_rows.clear();
m_visible_rows.clear(); m_visible_rows.clear();
@ -554,7 +554,9 @@ void GUITable::setSelected(s32 index)
s32 rowcount = m_rows.size(); s32 rowcount = m_rows.size();
if (rowcount == 0 || index < 0) { if (rowcount == 0 || index < 0) {
return; return;
} else if (index >= rowcount) { }
if (index >= rowcount) {
index = rowcount - 1; index = rowcount - 1;
} }
@ -793,7 +795,8 @@ bool GUITable::OnEvent(const SEvent &event)
return true; return true;
} }
else if (event.KeyInput.PressedDown && (
if (event.KeyInput.PressedDown && (
event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_LEFT ||
event.KeyInput.Key == KEY_RIGHT)) { event.KeyInput.Key == KEY_RIGHT)) {
// Open/close subtree via keyboard // Open/close subtree via keyboard
@ -942,13 +945,12 @@ s32 GUITable::allocString(const std::string &text)
if (it == m_alloc_strings.end()) { if (it == m_alloc_strings.end()) {
s32 id = m_strings.size(); s32 id = m_strings.size();
std::wstring wtext = utf8_to_wide(text); std::wstring wtext = utf8_to_wide(text);
m_strings.push_back(core::stringw(wtext.c_str())); m_strings.emplace_back(wtext.c_str());
m_alloc_strings.insert(std::make_pair(text, id)); m_alloc_strings.insert(std::make_pair(text, id));
return id; return id;
} }
else {
return it->second; return it->second;
}
} }
s32 GUITable::allocImage(const std::string &imagename) s32 GUITable::allocImage(const std::string &imagename)
@ -960,9 +962,8 @@ s32 GUITable::allocImage(const std::string &imagename)
m_alloc_images.insert(std::make_pair(imagename, id)); m_alloc_images.insert(std::make_pair(imagename, id));
return id; return id;
} }
else {
return it->second; return it->second;
}
} }
void GUITable::allocationComplete() void GUITable::allocationComplete()
@ -977,8 +978,8 @@ const GUITable::Row* GUITable::getRow(s32 i) const
{ {
if (i >= 0 && i < (s32) m_visible_rows.size()) if (i >= 0 && i < (s32) m_visible_rows.size())
return &m_rows[m_visible_rows[i]]; return &m_rows[m_visible_rows[i]];
else
return NULL; return NULL;
} }
bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const
@ -1014,11 +1015,10 @@ s32 GUITable::getRowAt(s32 y, bool &really_hovering) const
really_hovering = true; really_hovering = true;
return i; return i;
} }
else if (i < 0) if (i < 0)
return 0; return 0;
else
return rowcount - 1;
return rowcount - 1;
} }
s32 GUITable::getCellAt(s32 x, s32 row_i) const s32 GUITable::getCellAt(s32 x, s32 row_i) const
@ -1038,7 +1038,8 @@ s32 GUITable::getCellAt(s32 x, s32 row_i) const
if (rel_x >= cell->xmin && rel_x <= cell->xmax) if (rel_x >= cell->xmin && rel_x <= cell->xmax)
return pivot; return pivot;
else if (rel_x < cell->xmin)
if (rel_x < cell->xmin)
jmax = pivot - 1; jmax = pivot - 1;
else else
jmin = pivot + 1; jmin = pivot + 1;
@ -1048,8 +1049,8 @@ s32 GUITable::getCellAt(s32 x, s32 row_i) const
rel_x >= row->cells[jmin].xmin && rel_x >= row->cells[jmin].xmin &&
rel_x <= row->cells[jmin].xmax) rel_x <= row->cells[jmin].xmax)
return jmin; return jmin;
else
return -1; return -1;
} }
void GUITable::autoScroll() void GUITable::autoScroll()

View File

@ -24,7 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <sstream> #include <sstream>
#include <list> #include <list>
#include <map> #include <map>
#include <errno.h> #include <cerrno>
#include <mutex> #include <mutex>
#include "threading/event.h" #include "threading/event.h"
#include "config.h" #include "config.h"
@ -170,7 +170,8 @@ class CurlHandlePool
std::list<CURL*> handles; std::list<CURL*> handles;
public: public:
CurlHandlePool() {} CurlHandlePool() = default;
~CurlHandlePool() ~CurlHandlePool()
{ {
for (std::list<CURL*>::iterator it = handles.begin(); for (std::list<CURL*>::iterator it = handles.begin();
@ -272,7 +273,7 @@ HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
request.connect_timeout); request.connect_timeout);
if (request.useragent != "") if (!request.useragent.empty())
curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str()); curl_easy_setopt(curl, CURLOPT_USERAGENT, request.useragent.c_str());
// Set up a write callback that writes to the // Set up a write callback that writes to the
@ -308,13 +309,12 @@ HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
} else if (request.post_data.empty()) { } else if (request.post_data.empty()) {
curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POST, 1);
std::string str; std::string str;
for (StringMap::iterator it = request.post_fields.begin(); for (auto &post_field : request.post_fields) {
it != request.post_fields.end(); ++it) { if (!str.empty())
if (str != "")
str += "&"; str += "&";
str += urlencode(it->first); str += urlencode(post_field.first);
str += "="; str += "=";
str += urlencode(it->second); str += urlencode(post_field.second);
} }
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
str.size()); str.size());
@ -330,9 +330,8 @@ HTTPFetchOngoing::HTTPFetchOngoing(const HTTPFetchRequest &request_,
// modified until CURLOPT_POSTFIELDS is cleared // modified until CURLOPT_POSTFIELDS is cleared
} }
// Set additional HTTP headers // Set additional HTTP headers
for (std::vector<std::string>::iterator it = request.extra_headers.begin(); for (const std::string &extra_header : request.extra_headers) {
it != request.extra_headers.end(); ++it) { http_header = curl_slist_append(http_header, extra_header.c_str());
http_header = curl_slist_append(http_header, it->c_str());
} }
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);
@ -708,8 +707,8 @@ protected:
} }
// Call curl_multi_remove_handle and cleanup easy handles // Call curl_multi_remove_handle and cleanup easy handles
for (size_t i = 0; i < m_all_ongoing.size(); ++i) { for (HTTPFetchOngoing *i : m_all_ongoing) {
delete m_all_ongoing[i]; delete i;
} }
m_all_ongoing.clear(); m_all_ongoing.clear();

View File

@ -32,11 +32,12 @@ struct ToolCapabilities;
struct ItemStack struct ItemStack
{ {
ItemStack() {} ItemStack() = default;
ItemStack(const std::string &name_, u16 count_, ItemStack(const std::string &name_, u16 count_,
u16 wear, IItemDefManager *itemdef); u16 wear, IItemDefManager *itemdef);
~ItemStack() {} ~ItemStack() = default;
// Serialization // Serialization
void serialize(std::ostream &os) const; void serialize(std::ostream &os) const;
@ -132,10 +133,8 @@ struct ItemStack
wear += amount; wear += amount;
return true; return true;
} }
else
{ return false;
return false;
}
} }
// If possible, adds newitem to this item. // If possible, adds newitem to this item.

View File

@ -135,7 +135,7 @@ void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
writeS16(os, stack_max); writeS16(os, stack_max);
writeU8(os, usable); writeU8(os, usable);
writeU8(os, liquids_pointable); writeU8(os, liquids_pointable);
std::string tool_capabilities_s = ""; std::string tool_capabilities_s;
if(tool_capabilities){ if(tool_capabilities){
std::ostringstream tmp_os(std::ios::binary); std::ostringstream tmp_os(std::ios::binary);
tool_capabilities->serialize(tmp_os, protocol_version); tool_capabilities->serialize(tmp_os, protocol_version);
@ -143,10 +143,9 @@ void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
} }
os << serializeString(tool_capabilities_s); os << serializeString(tool_capabilities_s);
writeU16(os, groups.size()); writeU16(os, groups.size());
for (ItemGroupList::const_iterator for (const auto &group : groups) {
i = groups.begin(); i != groups.end(); ++i){ os << serializeString(group.first);
os << serializeString(i->first); writeS16(os, group.second);
writeS16(os, i->second);
} }
os << serializeString(node_placement_prediction); os << serializeString(node_placement_prediction);
os << serializeString(sound_place.name); os << serializeString(sound_place.name);
@ -244,7 +243,6 @@ class CItemDefManager: public IWritableItemDefManager
ClientCached(): ClientCached():
inventory_texture(NULL), inventory_texture(NULL),
wield_mesh(),
palette(NULL) palette(NULL)
{} {}
}; };
@ -263,20 +261,15 @@ public:
{ {
#ifndef SERVER #ifndef SERVER
const std::vector<ClientCached*> &values = m_clientcached.getValues(); const std::vector<ClientCached*> &values = m_clientcached.getValues();
for(std::vector<ClientCached*>::const_iterator for (ClientCached *cc : values) {
i = values.begin(); i != values.end(); ++i)
{
ClientCached *cc = *i;
if (cc->wield_mesh.mesh) if (cc->wield_mesh.mesh)
cc->wield_mesh.mesh->drop(); cc->wield_mesh.mesh->drop();
delete cc; delete cc;
} }
#endif #endif
for (std::map<std::string, ItemDefinition*>::iterator iter = for (auto &item_definition : m_item_definitions) {
m_item_definitions.begin(); iter != m_item_definitions.end(); delete item_definition.second;
++iter) {
delete iter->second;
} }
m_item_definitions.clear(); m_item_definitions.clear();
} }
@ -302,15 +295,12 @@ public:
virtual void getAll(std::set<std::string> &result) const virtual void getAll(std::set<std::string> &result) const
{ {
result.clear(); result.clear();
for(std::map<std::string, ItemDefinition *>::const_iterator for (const auto &item_definition : m_item_definitions) {
it = m_item_definitions.begin(); result.insert(item_definition.first);
it != m_item_definitions.end(); ++it) {
result.insert(it->first);
} }
for (StringMap::const_iterator
it = m_aliases.begin(); for (const auto &alias : m_aliases) {
it != m_aliases.end(); ++it) { result.insert(alias.first);
result.insert(it->first);
} }
} }
virtual bool isKnown(const std::string &name_) const virtual bool isKnown(const std::string &name_) const
@ -346,7 +336,7 @@ public:
// Create an inventory texture // Create an inventory texture
cc->inventory_texture = NULL; cc->inventory_texture = NULL;
if(def.inventory_image != "") if (!def.inventory_image.empty())
cc->inventory_texture = tsrc->getTexture(def.inventory_image); cc->inventory_texture = tsrc->getTexture(def.inventory_image);
ItemStack item = ItemStack(); ItemStack item = ItemStack();
@ -371,28 +361,27 @@ public:
if (std::this_thread::get_id() == m_main_thread) { if (std::this_thread::get_id() == m_main_thread) {
return createClientCachedDirect(name, client); return createClientCachedDirect(name, client);
} else { }
// We're gonna ask the result to be put into here
static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
// Throw a request in // We're gonna ask the result to be put into here
m_get_clientcached_queue.add(name, 0, 0, &result_queue); static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
try{
while(true) {
// Wait result for a second
GetResult<std::string, ClientCached*, u8, u8>
result = result_queue.pop_front(1000);
if (result.key == name) { // Throw a request in
return result.item; m_get_clientcached_queue.add(name, 0, 0, &result_queue);
} try {
while(true) {
// Wait result for a second
GetResult<std::string, ClientCached*, u8, u8>
result = result_queue.pop_front(1000);
if (result.key == name) {
return result.item;
} }
} }
catch(ItemNotFoundException &e) } catch(ItemNotFoundException &e) {
{ errorstream << "Waiting for clientcached " << name
errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl; << " timed out." << std::endl;
return &m_dummy_clientcached; return &m_dummy_clientcached;
}
} }
} }
// Get item inventory texture // Get item inventory texture
@ -430,13 +419,12 @@ public:
// Look for direct color definition // Look for direct color definition
const std::string &colorstring = stack.metadata.getString("color", 0); const std::string &colorstring = stack.metadata.getString("color", 0);
video::SColor directcolor; video::SColor directcolor;
if ((colorstring != "") if (!colorstring.empty() && parseColorString(colorstring, directcolor, true))
&& parseColorString(colorstring, directcolor, true))
return directcolor; return directcolor;
// See if there is a palette // See if there is a palette
Palette *palette = getPalette(stack.name, client); Palette *palette = getPalette(stack.name, client);
const std::string &index = stack.metadata.getString("palette_index", 0); const std::string &index = stack.metadata.getString("palette_index", 0);
if ((palette != NULL) && (index != "")) if (palette && !index.empty())
return (*palette)[mystoi(index, 0, 255)]; return (*palette)[mystoi(index, 0, 255)];
// Fallback color // Fallback color
return get(stack.name).color; return get(stack.name).color;
@ -485,7 +473,7 @@ public:
{ {
verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl; verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
// Ensure that the "" item (the hand) always has ToolCapabilities // Ensure that the "" item (the hand) always has ToolCapabilities
if(def.name == "") if (def.name.empty())
FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities"); FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities");
if(m_item_definitions.count(def.name) == 0) if(m_item_definitions.count(def.name) == 0)

View File

@ -1109,7 +1109,6 @@ bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) {
// of a mapblock, because we must consider all view angles. // of a mapblock, because we must consider all view angles.
// sqrt(1^2 + 1^2 + 1^2) = 1.732 // sqrt(1^2 + 1^2 + 1^2) = 1.732
float endoff = -BS * MAP_BLOCKSIZE * 1.732050807569; float endoff = -BS * MAP_BLOCKSIZE * 1.732050807569;
v3s16 spn = cam_pos_nodes;
s16 bs2 = MAP_BLOCKSIZE / 2 + 1; s16 bs2 = MAP_BLOCKSIZE / 2 + 1;
// to reduce the likelihood of falsely occluded blocks // to reduce the likelihood of falsely occluded blocks
// require at least two solid blocks // require at least two solid blocks
@ -1118,23 +1117,23 @@ bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) {
return ( return (
// For the central point of the mapblock 'endoff' can be halved // For the central point of the mapblock 'endoff' can be halved
isOccluded(spn, cpn, isOccluded(cam_pos_nodes, cpn,
step, stepfac, startoff, endoff / 2.0f, needed_count) && step, stepfac, startoff, endoff / 2.0f, needed_count) &&
isOccluded(spn, cpn + v3s16(bs2,bs2,bs2), isOccluded(cam_pos_nodes, cpn + v3s16(bs2,bs2,bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(bs2,bs2,-bs2), isOccluded(cam_pos_nodes, cpn + v3s16(bs2,bs2,-bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(bs2,-bs2,bs2), isOccluded(cam_pos_nodes, cpn + v3s16(bs2,-bs2,bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(bs2,-bs2,-bs2), isOccluded(cam_pos_nodes, cpn + v3s16(bs2,-bs2,-bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(-bs2,bs2,bs2), isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,bs2,bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(-bs2,bs2,-bs2), isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,bs2,-bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(-bs2,-bs2,bs2), isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,-bs2,bs2),
step, stepfac, startoff, endoff, needed_count) && step, stepfac, startoff, endoff, needed_count) &&
isOccluded(spn, cpn + v3s16(-bs2,-bs2,-bs2), isOccluded(cam_pos_nodes, cpn + v3s16(-bs2,-bs2,-bs2),
step, stepfac, startoff, endoff, needed_count)); step, stepfac, startoff, endoff, needed_count));
} }

View File

@ -1325,11 +1325,8 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat
scene::IMeshBuffer *buf = m_mesh[daynight_diff.first.first]-> scene::IMeshBuffer *buf = m_mesh[daynight_diff.first.first]->
getMeshBuffer(daynight_diff.first.second); getMeshBuffer(daynight_diff.first.second);
video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices();
for (auto j = daynight_diff.second.begin(); for (const auto &j : daynight_diff.second) {
j != daynight_diff.second.end(); ++j) final_color_blend(&(vertices[j.first].Color), j.second, day_color);
{
final_color_blend(&(vertices[j->first].Color),
j->second, day_color);
} }
} }
m_last_daynight_ratio = daynight_ratio; m_last_daynight_ratio = daynight_ratio;

View File

@ -286,7 +286,7 @@ void DecoSimple::resolveNodeNames()
size_t DecoSimple::generate(MMVManip *vm, PcgRandom *pr, v3s16 p) size_t DecoSimple::generate(MMVManip *vm, PcgRandom *pr, v3s16 p)
{ {
// Don't bother if there aren't any decorations to place // Don't bother if there aren't any decorations to place
if (c_decos.size() == 0) if (c_decos.empty())
return 0; return 0;
if (!canPlaceDecoration(vm, p)) if (!canPlaceDecoration(vm, p))

View File

@ -159,13 +159,13 @@ void NodeBox::deSerialize(std::istream &is)
} }
else if (type == NODEBOX_CONNECTED) else if (type == NODEBOX_CONNECTED)
{ {
#define READBOXES(box) do { \ #define READBOXES(box) { \
count = readU16(is); \ count = readU16(is); \
(box).reserve(count); \ (box).reserve(count); \
while (count--) { \ while (count--) { \
v3f min = readV3F1000(is); \ v3f min = readV3F1000(is); \
v3f max = readV3F1000(is); \ v3f max = readV3F1000(is); \
(box).emplace_back(min, max); }; } while (0) (box).emplace_back(min, max); }; }
u16 count; u16 count;
@ -1958,7 +1958,7 @@ bool NodeResolver::getIdFromNrBacklog(content_t *result_out,
std::string name = m_nodenames[m_nodenames_idx++]; std::string name = m_nodenames[m_nodenames_idx++];
bool success = m_ndef->getId(name, c); bool success = m_ndef->getId(name, c);
if (!success && node_alt != "") { if (!success && !node_alt.empty()) {
name = node_alt; name = node_alt;
success = m_ndef->getId(name, c); success = m_ndef->getId(name, c);
} }

View File

@ -106,10 +106,6 @@ Particle::Particle(
updateVertices(); updateVertices();
} }
Particle::~Particle()
{
}
void Particle::OnRegisterSceneNode() void Particle::OnRegisterSceneNode()
{ {
if (IsVisible) if (IsVisible)
@ -227,17 +223,16 @@ void Particle::updateVertices()
0, 0, 0, 0, m_color, tx0, ty0); 0, 0, 0, 0, m_color, tx0, ty0);
v3s16 camera_offset = m_env->getCameraOffset(); v3s16 camera_offset = m_env->getCameraOffset();
for(u16 i=0; i<4; i++) for (video::S3DVertex &vertex : m_vertices) {
{
if (m_vertical) { if (m_vertical) {
v3f ppos = m_player->getPosition()/BS; v3f ppos = m_player->getPosition()/BS;
m_vertices[i].Pos.rotateXZBy(atan2(ppos.Z-m_pos.Z, ppos.X-m_pos.X)/core::DEGTORAD+90); vertex.Pos.rotateXZBy(atan2(ppos.Z-m_pos.Z, ppos.X-m_pos.X)/core::DEGTORAD+90);
} else { } else {
m_vertices[i].Pos.rotateYZBy(m_player->getPitch()); vertex.Pos.rotateYZBy(m_player->getPitch());
m_vertices[i].Pos.rotateXZBy(m_player->getYaw()); vertex.Pos.rotateXZBy(m_player->getYaw());
} }
m_box.addInternalPoint(m_vertices[i].Pos); m_box.addInternalPoint(vertex.Pos);
m_vertices[i].Pos += m_pos*BS - intToFloat(camera_offset, BS); vertex.Pos += m_pos*BS - intToFloat(camera_offset, BS);
} }
} }
@ -285,8 +280,6 @@ ParticleSpawner::ParticleSpawner(IGameDef *gamedef, LocalPlayer *player,
} }
} }
ParticleSpawner::~ParticleSpawner() {}
void ParticleSpawner::step(float dtime, ClientEnvironment* env) void ParticleSpawner::step(float dtime, ClientEnvironment* env)
{ {
m_time += dtime; m_time += dtime;

View File

@ -53,7 +53,7 @@ class Particle : public scene::ISceneNode
u8 glow, u8 glow,
video::SColor color = video::SColor(0xFFFFFFFF) video::SColor color = video::SColor(0xFFFFFFFF)
); );
~Particle(); ~Particle() = default;
virtual const aabb3f &getBoundingBox() const virtual const aabb3f &getBoundingBox() const
{ {
@ -133,7 +133,7 @@ class ParticleSpawner
const struct TileAnimationParams &anim, u8 glow, const struct TileAnimationParams &anim, u8 glow,
ParticleManager* p_manager); ParticleManager* p_manager);
~ParticleSpawner(); ~ParticleSpawner() = default;
void step(float dtime, ClientEnvironment *env); void step(float dtime, ClientEnvironment *env);

View File

@ -127,10 +127,10 @@ namespace porting
Signal handler (grabs Ctrl-C on POSIX systems) Signal handler (grabs Ctrl-C on POSIX systems)
*/ */
void signal_handler_init(void); void signal_handler_init();
// Returns a pointer to a bool. // Returns a pointer to a bool.
// When the bool is true, program should quit. // When the bool is true, program should quit.
bool * signal_handler_killstatus(void); bool * signal_handler_killstatus();
/* /*
Path of static data directory. Path of static data directory.
@ -326,7 +326,7 @@ inline const char *getPlatformName()
bool secure_rand_fill_buf(void *buf, size_t len); bool secure_rand_fill_buf(void *buf, size_t len);
// This attaches to the parents process console, or creates a new one if it doesnt exist. // This attaches to the parents process console, or creates a new one if it doesnt exist.
void attachOrCreateConsole(void); void attachOrCreateConsole();
} // namespace porting } // namespace porting
#ifdef __ANDROID__ #ifdef __ANDROID__

View File

@ -731,7 +731,7 @@ int ModApiMapgen::l_set_mapgen_setting(lua_State *L)
const char *name = luaL_checkstring(L, 1); const char *name = luaL_checkstring(L, 1);
const char *value = luaL_checkstring(L, 2); const char *value = luaL_checkstring(L, 2);
bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false; bool override_meta = lua_isboolean(L, 3) && lua_toboolean(L, 3);
if (!settingsmgr->setMapSetting(name, value, override_meta)) { if (!settingsmgr->setMapSetting(name, value, override_meta)) {
errorstream << "set_mapgen_setting: cannot set '" errorstream << "set_mapgen_setting: cannot set '"
@ -760,7 +760,7 @@ int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L)
return 0; return 0;
} }
bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false; bool override_meta = lua_isboolean(L, 3) && lua_toboolean(L, 3);
if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) {
errorstream << "set_mapgen_setting_noiseparams: cannot set '" errorstream << "set_mapgen_setting_noiseparams: cannot set '"
@ -786,7 +786,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L)
return 0; return 0;
} }
bool set_default = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : true; bool set_default = !lua_isboolean(L, 3) || lua_toboolean(L, 3);
g_settings->setNoiseParams(name, np, set_default); g_settings->setNoiseParams(name, np, set_default);

View File

@ -345,7 +345,7 @@ ShaderInfo generate_shader(const std::string &name,
/* /*
Load shader programs Load shader programs
*/ */
void load_shaders(std::string name, SourceShaderCache *sourcecache, void load_shaders(const std::string &name, SourceShaderCache *sourcecache,
video::E_DRIVER_TYPE drivertype, bool enable_shaders, video::E_DRIVER_TYPE drivertype, bool enable_shaders,
std::string &vertex_program, std::string &pixel_program, std::string &vertex_program, std::string &pixel_program,
std::string &geometry_program, bool &is_highlevel); std::string &geometry_program, bool &is_highlevel);
@ -821,7 +821,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
return shaderinfo; return shaderinfo;
} }
void load_shaders(std::string name, SourceShaderCache *sourcecache, void load_shaders(const std::string &name, SourceShaderCache *sourcecache,
video::E_DRIVER_TYPE drivertype, bool enable_shaders, video::E_DRIVER_TYPE drivertype, bool enable_shaders,
std::string &vertex_program, std::string &pixel_program, std::string &vertex_program, std::string &pixel_program,
std::string &geometry_program, bool &is_highlevel) std::string &geometry_program, bool &is_highlevel)

View File

@ -19,11 +19,11 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "socket.h" #include "socket.h"
#include <stdio.h> #include <cstdio>
#include <iostream> #include <iostream>
#include <stdlib.h> #include <cstdlib>
#include <string.h> #include <cstring>
#include <errno.h> #include <cerrno>
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
#include "util/string.h" #include "util/string.h"
@ -114,20 +114,20 @@ Address::Address(const IPv6AddressBytes *ipv6_bytes, u16 port)
// Equality (address family, address and port must be equal) // Equality (address family, address and port must be equal)
bool Address::operator==(const Address &address) bool Address::operator==(const Address &address)
{ {
if(address.m_addr_family != m_addr_family || address.m_port != m_port) if (address.m_addr_family != m_addr_family || address.m_port != m_port)
return false; return false;
else if(m_addr_family == AF_INET)
{ if (m_addr_family == AF_INET) {
return m_address.ipv4.sin_addr.s_addr == return m_address.ipv4.sin_addr.s_addr ==
address.m_address.ipv4.sin_addr.s_addr; address.m_address.ipv4.sin_addr.s_addr;
} }
else if(m_addr_family == AF_INET6)
{ if (m_addr_family == AF_INET6) {
return memcmp(m_address.ipv6.sin6_addr.s6_addr, return memcmp(m_address.ipv6.sin6_addr.s6_addr,
address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0; address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
} }
else
return false; return false;
} }
bool Address::operator!=(const Address &address) bool Address::operator!=(const Address &address)
@ -259,7 +259,9 @@ bool Address::isZero() const
{ {
if (m_addr_family == AF_INET) { if (m_addr_family == AF_INET) {
return m_address.ipv4.sin_addr.s_addr == 0; return m_address.ipv4.sin_addr.s_addr == 0;
} else if (m_addr_family == AF_INET6) { }
if (m_addr_family == AF_INET6) {
static const char zero[16] = {0}; static const char zero[16] = {0};
return memcmp(m_address.ipv6.sin6_addr.s6_addr, return memcmp(m_address.ipv6.sin6_addr.s6_addr,
zero, 16) == 0; zero, 16) == 0;
@ -316,7 +318,7 @@ UDPSocket::UDPSocket(bool ipv6)
bool UDPSocket::init(bool ipv6, bool noExceptions) bool UDPSocket::init(bool ipv6, bool noExceptions)
{ {
if (g_sockets_initialized == false) { if (!g_sockets_initialized) {
dstream << "Sockets not initialized" << std::endl; dstream << "Sockets not initialized" << std::endl;
return false; return false;
} }
@ -335,10 +337,10 @@ bool UDPSocket::init(bool ipv6, bool noExceptions)
if (m_handle <= 0) { if (m_handle <= 0) {
if (noExceptions) { if (noExceptions) {
return false; return false;
} else {
throw SocketException(std::string("Failed to create socket: error ")
+ itos(LAST_SOCKET_ERR()));
} }
throw SocketException(std::string("Failed to create socket: error ")
+ itos(LAST_SOCKET_ERR()));
} }
setTimeoutMs(0); setTimeoutMs(0);
@ -467,7 +469,7 @@ void UDPSocket::Send(const Address & destination, const void * data, int size)
int UDPSocket::Receive(Address & sender, void *data, int size) int UDPSocket::Receive(Address & sender, void *data, int size)
{ {
// Return on timeout // Return on timeout
if(WaitData(m_timeout_ms) == false) if (!WaitData(m_timeout_ms))
return -1; return -1;
int received; int received;
@ -556,14 +558,16 @@ bool UDPSocket::WaitData(int timeout_ms)
if (result == 0) if (result == 0)
return false; return false;
else if (result < 0 && (errno == EINTR || errno == EBADF)) {
if (result < 0 && (errno == EINTR || errno == EBADF)) {
// N.B. select() fails when sockets are destroyed on Connection's dtor // N.B. select() fails when sockets are destroyed on Connection's dtor
// with EBADF. Instead of doing tricky synchronization, allow this // with EBADF. Instead of doing tricky synchronization, allow this
// thread to exit but don't throw an exception. // thread to exit but don't throw an exception.
return false; return false;
} else if (result < 0) { }
dstream << (int) m_handle << ": Select failed: "
<< strerror(errno) << std::endl; if (result < 0) {
dstream << m_handle << ": Select failed: " << strerror(errno) << std::endl;
#ifdef _WIN32 #ifdef _WIN32
int e = WSAGetLastError(); int e = WSAGetLastError();
@ -576,7 +580,7 @@ bool UDPSocket::WaitData(int timeout_ms)
#endif #endif
throw SocketException("Select failed"); throw SocketException("Select failed");
} else if(FD_ISSET(m_handle, &readset) == false) { } else if (!FD_ISSET(m_handle, &readset)) {
// No data // No data
return false; return false;
} }

View File

@ -353,9 +353,8 @@ public:
m_device = NULL; m_device = NULL;
for (auto &buffer : m_buffers) { for (auto &buffer : m_buffers) {
for (std::vector<SoundBuffer*>::iterator iter = buffer.second.begin(); for (SoundBuffer *sb : buffer.second) {
iter != buffer.second.end(); ++iter) { delete sb;
delete *iter;
} }
buffer.second.clear(); buffer.second.clear();
} }

View File

@ -376,7 +376,8 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client)
} }
return; return;
} }
else if (!def.inventory_image.empty()) {
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.emplace_back(); m_colors.emplace_back();
return; return;