/*
Get texture
*/
- if (std::this_thread::get_id() == m_main_thread)
- {
+ if (std::this_thread::get_id() == m_main_thread) {
return generateTexture(name);
}
- else
- {
- infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;
- // We're gonna ask the result to be put into here
- static ResultQueue<std::string, u32, u8, u8> result_queue;
- // Throw a request in
- m_get_texture_queue.add(name, 0, 0, &result_queue);
+ infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;
- /*infostream<<"Waiting for texture from main thread, name=\""
- <<name<<"\""<<std::endl;*/
+ // We're gonna ask the result to be put into here
+ static ResultQueue<std::string, u32, u8, u8> result_queue;
- try
- {
- while(true) {
- // Wait result for a second
- GetResult<std::string, u32, u8, u8>
- result = result_queue.pop_front(1000);
+ // Throw a request in
+ m_get_texture_queue.add(name, 0, 0, &result_queue);
- if (result.key == name) {
- return result.item;
- }
+ try {
+ while(true) {
+ // Wait result for a second
+ GetResult<std::string, u32, u8, u8>
+ result = result_queue.pop_front(1000);
+
+ if (result.key == name) {
+ return result.item;
}
}
- catch(ItemNotFoundException &e)
- {
- errorstream<<"Waiting for texture " << name << " timed out."<<std::endl;
- return 0;
- }
+ } catch(ItemNotFoundException &e) {
+ errorstream << "Waiting for texture " << name << " timed out." << std::endl;
+ return 0;
}
- infostream<<"getTextureId(): Failed"<<std::endl;
+ infostream << "getTextureId(): Failed" << std::endl;
return 0;
}
// Only the main thread may load images
sanity_check(std::this_thread::get_id() == m_main_thread);
- if (name == "")
+ if (name.empty())
return NULL;
auto it = m_palettes.find(name);
case TILE_MATERIAL_LIQUID_TRANSPARENT:
material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
break;
+ default:
+ break;
}
material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0;
if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) {
struct TileSpec
{
TileSpec() {
- for (int layer = 0; layer < MAX_TILE_LAYERS; layer++)
- layers[layer] = TileLayer();
+ for (auto &layer : layers)
+ layer = TileLayer();
}
/*!
if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN ||
denyCode == SERVER_ACCESSDENIED_CRASH) {
*pkt >> m_access_denied_reason;
- if (m_access_denied_reason == "") {
+ if (m_access_denied_reason.empty()) {
m_access_denied_reason = accessDeniedStrings[denyCode];
}
u8 reconnect;
// Until then (which may be never), this is outside
// of the defined protocol.
*pkt >> m_access_denied_reason;
- if (m_access_denied_reason == "") {
+ if (m_access_denied_reason.empty()) {
m_access_denied_reason = "Unknown";
}
}
Strfnd sf(str);
while(!sf.at_end()) {
std::string baseurl = trim(sf.next(","));
- if (baseurl != "")
+ if (!baseurl.empty())
m_media_downloader->addRemoteServer(baseurl);
}
}
}
else if (param == HUD_PARAM_HOTBAR_IMAGE) {
// If value not empty verify image exists in texture source
- if (value != "" && !getTextureSource()->isKnownSourceImage(value)) {
+ if (!value.empty() && !getTextureSource()->isKnownSourceImage(value)) {
errorstream << "Server sent wrong Hud hotbar image (sent value: '"
<< value << "')" << std::endl;
return;
}
else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) {
// If value not empty verify image exists in texture source
- if (value != "" && !getTextureSource()->isKnownSourceImage(value)) {
+ if (!value.empty() && !getTextureSource()->isKnownSourceImage(value)) {
errorstream << "Server sent wrong Hud hotbar selected image (sent value: '"
<< value << "')" << std::endl;
return;
*/
#include <iomanip>
-#include <errno.h>
+#include <cerrno>
#include "connection.h"
#include "serialization.h"
#include "log.h"
}
while(end != data.getSize() - 1);
- for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
- i != chunks.end(); ++i)
- {
+ for (SharedBuffer<u8> &chunk : chunks) {
// Write chunk_count
- writeU16(&((*i)[3]), chunk_count);
+ writeU16(&(chunk[3]), chunk_count);
}
return chunks;
split_seqnum++;
return list;
}
- else
- {
- list.push_back(makeOriginalPacket(data));
- }
+
+ list.push_back(makeOriginalPacket(data));
return list;
}
SharedBuffer<u8> makeReliablePacket(
- SharedBuffer<u8> data,
+ const SharedBuffer<u8> &data,
u16 seqnum)
{
u32 header_size = 3;
MutexAutoLock listlock(m_list_mutex);
LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
unsigned int index = 0;
- for(std::list<BufferedPacket>::iterator i = m_list.begin();
- i != m_list.end();
- ++i)
- {
- u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
+ for (BufferedPacket &bufferedPacket : m_list) {
+ u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
LOG(dout_con<<index<< ":" << s << std::endl);
index++;
}
void ReliablePacketBuffer::incrementTimeouts(float dtime)
{
MutexAutoLock listlock(m_list_mutex);
- for(std::list<BufferedPacket>::iterator i = m_list.begin();
- i != m_list.end(); ++i)
- {
- i->time += dtime;
- i->totaltime += dtime;
+ for (BufferedPacket &bufferedPacket : m_list) {
+ bufferedPacket.time += dtime;
+ bufferedPacket.totaltime += dtime;
}
}
{
MutexAutoLock listlock(m_list_mutex);
std::list<BufferedPacket> timed_outs;
- for(std::list<BufferedPacket>::iterator i = m_list.begin();
- i != m_list.end(); ++i)
- {
- if (i->time >= timeout) {
- timed_outs.push_back(*i);
+ for (BufferedPacket &bufferedPacket : m_list) {
+ if (bufferedPacket.time >= timeout) {
+ timed_outs.push_back(bufferedPacket);
//this packet will be sent right afterwards reset timeout here
- i->time = 0.0;
+ bufferedPacket.time = 0.0f;
if (timed_outs.size() >= max_packets)
break;
}
IncomingSplitBuffer::~IncomingSplitBuffer()
{
MutexAutoLock listlock(m_map_mutex);
- for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
- i != m_buf.end(); ++i)
- {
- delete i->second;
+ for (auto &i : m_buf) {
+ delete i.second;
}
}
/*
sp->chunks[chunk_num] = chunkdata;
// If not all chunks are received, return empty buffer
- if (sp->allReceived() == false)
+ if (!sp->allReceived())
return SharedBuffer<u8>();
// Calculate total size
u32 totalsize = 0;
- for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
- i != sp->chunks.end(); ++i)
- {
- totalsize += i->second.getSize();
+ for (const auto &chunk : sp->chunks) {
+ totalsize += chunk.second.getSize();
}
SharedBuffer<u8> fulldata(totalsize);
std::list<u16> remove_queue;
{
MutexAutoLock listlock(m_map_mutex);
- for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
- i != m_buf.end(); ++i)
- {
- IncomingSplitPacket *p = i->second;
+ for (auto &i : m_buf) {
+ IncomingSplitPacket *p = i.second;
// Reliable ones are not removed by timeout
- if (p->reliable == true)
+ if (p->reliable)
continue;
p->time += dtime;
if (p->time >= timeout)
- remove_queue.push_back(i->first);
+ remove_queue.push_back(i.first);
}
}
- for(std::list<u16>::iterator j = remove_queue.begin();
- j != remove_queue.end(); ++j)
- {
+ for (u16 j : remove_queue) {
MutexAutoLock listlock(m_map_mutex);
LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
- delete m_buf[*j];
- m_buf.erase(*j);
+ delete m_buf[j];
+ m_buf.erase(j);
}
}
m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
jitter * (1/num_samples);
- if (profiler_id != "") {
+ if (!profiler_id.empty()) {
g_profiler->graphAdd(profiler_id + "_rtt", rtt);
g_profiler->graphAdd(profiler_id + "_jitter", jitter);
}
if (c.raw)
{
- originals.push_back(c.data);
+ originals.emplace_back(c.data);
}
else {
originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
std::queue<BufferedPacket> toadd;
volatile u16 initial_sequence_number = 0;
- for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
- i != originals.end(); ++i)
- {
+ for (SharedBuffer<u8> &original : originals) {
u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
/* oops, we don't have enough sequence numbers to send this packet */
have_initial_sequence_number = true;
}
- SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
+ SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
// Add base headers and make a packet
BufferedPacket p = con::makePacket(address, reliable,
if (have_sequence_number) {
volatile u16 pcount = 0;
- while(toadd.size() > 0) {
+ while (!toadd.empty()) {
BufferedPacket p = toadd.front();
toadd.pop();
// LOG(dout_con<<connection->getDesc()
sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
return true;
}
- else {
- volatile u16 packets_available = toadd.size();
- /* we didn't get a single sequence number no need to fill queue */
- if (!have_initial_sequence_number)
- {
- return false;
- }
- while(toadd.size() > 0) {
- /* remove packet */
- toadd.pop();
-
- bool successfully_put_back_sequence_number
- = channels[c.channelnum].putBackSequenceNumber(
- (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
- FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
- }
- LOG(dout_con<<m_connection->getDesc()
- << " Windowsize exceeded on reliable sending "
- << c.data.getSize() << " bytes"
- << std::endl << "\t\tinitial_sequence_number: "
- << initial_sequence_number
- << std::endl << "\t\tgot at most : "
- << packets_available << " packets"
- << std::endl << "\t\tpackets queued : "
- << channels[c.channelnum].outgoing_reliables_sent.size()
- << std::endl);
+ volatile u16 packets_available = toadd.size();
+ /* we didn't get a single sequence number no need to fill queue */
+ if (!have_initial_sequence_number) {
return false;
}
+
+ while (!toadd.empty()) {
+ /* remove packet */
+ toadd.pop();
+
+ bool successfully_put_back_sequence_number
+ = channels[c.channelnum].putBackSequenceNumber(
+ (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
+
+ FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
+ }
+
+ LOG(dout_con<<m_connection->getDesc()
+ << " Windowsize exceeded on reliable sending "
+ << c.data.getSize() << " bytes"
+ << std::endl << "\t\tinitial_sequence_number: "
+ << initial_sequence_number
+ << std::endl << "\t\tgot at most : "
+ << packets_available << " packets"
+ << std::endl << "\t\tpackets queued : "
+ << channels[c.channelnum].outgoing_reliables_sent.size()
+ << std::endl);
+
+ return false;
}
void UDPPeer::RunCommandQueues(
unsigned int maxtransfer)
{
- for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
+ for (Channel &channel : channels) {
unsigned int commands_processed = 0;
- if ((channels[i].queued_commands.size() > 0) &&
- (channels[i].queued_reliables.size() < maxtransfer) &&
+ if ((!channel.queued_commands.empty()) &&
+ (channel.queued_reliables.size() < maxtransfer) &&
(commands_processed < maxcommands)) {
try {
- ConnectionCommand c = channels[i].queued_commands.front();
+ ConnectionCommand c = channel.queued_commands.front();
LOG(dout_con << m_connection->getDesc()
<< " processing queued reliable command " << std::endl);
// Packet is processed, remove it from queue
if (processReliableSendCommand(c,max_packet_size)) {
- channels[i].queued_commands.pop_front();
+ channel.queued_commands.pop_front();
} else {
LOG(dout_con << m_connection->getDesc()
<< " Failed to queue packets for peer_id: " << c.peer_id
if (!m_outgoing_queue.empty() && !peerIds.empty())
return true;
- for(std::list<u16>::iterator j = peerIds.begin();
- j != peerIds.end(); ++j)
- {
- PeerHelper peer = m_connection->getPeerNoEx(*j);
+ for (u16 peerId : peerIds) {
+ PeerHelper peer = m_connection->getPeerNoEx(peerId);
if (!peer)
continue;
if (dynamic_cast<UDPPeer*>(&peer) == 0)
continue;
- for(u16 i=0; i < CHANNEL_COUNT; i++) {
- Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
-
- if (channel->queued_commands.size() > 0) {
+ for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
+ if (channel.queued_commands.size() > 0) {
return true;
}
}
std::list<u16> timeouted_peers;
std::list<u16> peerIds = m_connection->getPeerIDs();
- for(std::list<u16>::iterator j = peerIds.begin();
- j != peerIds.end(); ++j)
- {
- PeerHelper peer = m_connection->getPeerNoEx(*j);
+ for (u16 &peerId : peerIds) {
+ PeerHelper peer = m_connection->getPeerNoEx(peerId);
if (!peer)
continue;
PROFILE(std::stringstream peerIdentifier);
PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
- << ";" << *j << ";RELIABLE]");
+ << ";" << peerId << ";RELIABLE]");
PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
bool retry_count_exceeded = false;
- for(u16 i=0; i<CHANNEL_COUNT; i++)
- {
+ for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
std::list<BufferedPacket> timed_outs;
- Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
- channel->setWindowSize(g_settings->getU16("workaround_window_size"));
+ channel.setWindowSize(g_settings->getU16("workaround_window_size"));
// Remove timed out incomplete unreliable split packets
- channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
+ channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
// Increment reliable packet times
- channel->outgoing_reliables_sent.incrementTimeouts(dtime);
+ channel.outgoing_reliables_sent.incrementTimeouts(dtime);
unsigned int numpeers = m_connection->m_peers.size();
return;
// Re-send timed out outgoing reliables
- timed_outs = channel->
- outgoing_reliables_sent.getTimedOuts(resend_timeout,
- (m_max_data_packets_per_iteration/numpeers));
+ timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
+ (m_max_data_packets_per_iteration/numpeers));
- channel->UpdatePacketLossCounter(timed_outs.size());
+ channel.UpdatePacketLossCounter(timed_outs.size());
g_profiler->graphAdd("packets_lost", timed_outs.size());
m_iteration_packets_avaialble -= timed_outs.size();
u8 channelnum = readChannel(*(k->data));
u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
- channel->UpdateBytesLost(k->data.getSize());
+ channel.UpdateBytesLost(k->data.getSize());
k->resend_count++;
if (k-> resend_count > MAX_RELIABLE_RETRY) {
break; /* no need to check other channels if we already did timeout */
}
- channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
+ channel.UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
}
/* skip to next peer if we did timeout */
}
// Remove timed out peers
- for(std::list<u16>::iterator i = timeouted_peers.begin();
- i != timeouted_peers.end(); ++i)
- {
- LOG(derr_con<<m_connection->getDesc()
- <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
- m_connection->deletePeer(*i, true);
+ for (u16 timeouted_peer : timeouted_peers) {
+ LOG(derr_con << m_connection->getDesc()
+ << "RunTimeouts(): Removing peer "<< timeouted_peer <<std::endl);
+ m_connection->deletePeer(timeouted_peer, true);
}
}
sendAsPacketReliable(p,channel);
return true;
}
- else {
- LOG(dout_con<<m_connection->getDesc()
- <<" INFO: queueing reliable packet for peer_id: " << peer_id
- <<" channel: " << channelnum
- <<" seqnum: " << seqnum << std::endl);
- channel->queued_reliables.push(p);
- return false;
- }
+
+ LOG(dout_con<<m_connection->getDesc()
+ <<" INFO: queueing reliable packet for peer_id: " << peer_id
+ <<" channel: " << channelnum
+ <<" seqnum: " << seqnum << std::endl);
+ channel->queued_reliables.push(p);
+ return false;
}
- else
- {
- Address peer_address;
- if (peer->getAddress(MTP_UDP, peer_address))
- {
- // Add base headers and make a packet
- BufferedPacket p = con::makePacket(peer_address, data,
- m_connection->GetProtocolID(), m_connection->GetPeerID(),
- channelnum);
+ Address peer_address;
+ if (peer->getAddress(MTP_UDP, peer_address)) {
+ // Add base headers and make a packet
+ BufferedPacket p = con::makePacket(peer_address, data,
+ m_connection->GetProtocolID(), m_connection->GetPeerID(),
+ channelnum);
- // Send the packet
- rawSend(p);
- return true;
- }
- else {
- LOG(dout_con<<m_connection->getDesc()
- <<" INFO: dropped unreliable packet for peer_id: " << peer_id
- <<" because of (yet) missing udp address" << std::endl);
- return false;
- }
+ // Send the packet
+ rawSend(p);
+ return true;
}
- //never reached
+ LOG(dout_con << m_connection->getDesc()
+ << " INFO: dropped unreliable packet for peer_id: " << peer_id
+ << " because of (yet) missing udp address" << std::endl);
return false;
}
// Send to all
std::list<u16> peerids = m_connection->getPeerIDs();
- for (std::list<u16>::iterator i = peerids.begin();
- i != peerids.end();
- ++i)
- {
- sendAsPacket(*i, 0,data,false);
+ for (u16 peerid : peerids) {
+ sendAsPacket(peerid, 0,data,false);
}
}
peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
- for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
- i != originals.end(); ++i)
- {
- SharedBuffer<u8> original = *i;
+ for (const SharedBuffer<u8> &original : originals) {
sendAsPacket(peer_id, channelnum, original);
}
}
{
std::list<u16> peerids = m_connection->getPeerIDs();
- for (std::list<u16>::iterator i = peerids.begin();
- i != peerids.end();
- ++i)
- {
- send(*i, channelnum, data);
+ for (u16 peerid : peerids) {
+ send(peerid, channelnum, data);
}
}
{
std::list<u16> peerids = m_connection->getPeerIDs();
- for (std::list<u16>::iterator i = peerids.begin();
- i != peerids.end();
- ++i)
- {
- PeerHelper peer = m_connection->getPeerNoEx(*i);
+ for (u16 peerid : peerids) {
+ PeerHelper peer = m_connection->getPeerNoEx(peerid);
if (!peer)
continue;
std::list<u16> pendingDisconnect;
std::map<u16,bool> pending_unreliable;
- for(std::list<u16>::iterator
- j = peerIds.begin();
- j != peerIds.end(); ++j)
- {
- PeerHelper peer = m_connection->getPeerNoEx(*j);
+ for (u16 peerId : peerIds) {
+ PeerHelper peer = m_connection->getPeerNoEx(peerId);
//peer may have been removed
if (!peer) {
- LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
+ LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << peerId
+ << std::endl);
continue;
}
peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
- if (dynamic_cast<UDPPeer*>(&peer) == 0)
- {
+ UDPPeer *udpPeer = dynamic_cast<UDPPeer*>(&peer);
+
+ if (!udpPeer) {
continue;
}
- if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
- {
- pendingDisconnect.push_back(*j);
+ if (udpPeer->m_pending_disconnect) {
+ pendingDisconnect.push_back(peerId);
}
PROFILE(std::stringstream peerIdentifier);
- PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
+ PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId
+ << ";RELIABLE]");
PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
LOG(dout_con<<m_connection->getDesc()
- << " Handle per peer queues: peer_id=" << *j
- << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
+ << " Handle per peer queues: peer_id=" << peerId
+ << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
+
// first send queued reliable packets for all peers (if possible)
- for (unsigned int i=0; i < CHANNEL_COUNT; i++)
- {
+ for (unsigned int i=0; i < CHANNEL_COUNT; i++) {
+ Channel &channel = udpPeer->channels[i];
u16 next_to_ack = 0;
- dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
+
+ channel.outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
u16 next_to_receive = 0;
- dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
+ channel.incoming_reliables.getFirstSeqnum(next_to_receive);
LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
<< i << ", peer quota:"
<< peer->m_increment_packets_remaining
<< std::endl
<< "\t\t\treliables on wire: "
- << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
+ << channel.outgoing_reliables_sent.size()
<< ", waiting for ack for " << next_to_ack
<< std::endl
<< "\t\t\tincoming_reliables: "
- << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
+ << channel.incoming_reliables.size()
<< ", next reliable packet: "
- << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
+ << channel.readNextIncomingSeqNum()
<< ", next queued: " << next_to_receive
<< std::endl
<< "\t\t\treliables queued : "
- << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
+ << channel.queued_reliables.size()
<< std::endl
<< "\t\t\tqueued commands : "
- << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
+ << channel.queued_commands.size()
<< std::endl);
- while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
- (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
- < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
+ while ((!channel.queued_reliables.empty()) &&
+ (channel.outgoing_reliables_sent.size()
+ < channel.getWindowSize())&&
(peer->m_increment_packets_remaining > 0))
{
- BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
- dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
- Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
+ BufferedPacket p = channel.queued_reliables.front();
+ channel.queued_reliables.pop();
LOG(dout_con<<m_connection->getDesc()
<<" INFO: sending a queued reliable packet "
<<" channel: " << i
<<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
<< std::endl);
- sendAsPacketReliable(p,channel);
+ sendAsPacketReliable(p, &channel);
peer->m_increment_packets_remaining--;
}
}
}
- if (m_outgoing_queue.size())
- {
+ if (!m_outgoing_queue.empty()) {
LOG(dout_con<<m_connection->getDesc()
<< " Handle non reliable queue ("
<< m_outgoing_queue.size() << " pkts)" << std::endl);
<< ", size: " << packet.data.getSize() <<std::endl);
continue;
}
+
/* send acks immediately */
- else if (packet.ack)
- {
+ if (packet.ack) {
rawSendAsPacket(packet.peer_id, packet.channelnum,
packet.data, packet.reliable);
peer->m_increment_packets_remaining =
}
}
- for(std::list<u16>::iterator
- k = pendingDisconnect.begin();
- k != pendingDisconnect.end(); ++k)
- {
- if (!pending_unreliable[*k])
+ for (u16 peerId : pendingDisconnect) {
+ if (!pending_unreliable[peerId])
{
- m_connection->deletePeer(*k,false);
+ m_connection->deletePeer(peerId,false);
}
}
}
{
std::list<u16> peerids = m_connection->getPeerIDs();
- for(std::list<u16>::iterator j = peerids.begin();
- j != peerids.end(); ++j)
- {
- PeerHelper peer = m_connection->getPeerNoEx(*j);
+ for (u16 peerid : peerids) {
+ PeerHelper peer = m_connection->getPeerNoEx(peerid);
if (!peer)
continue;
if (dynamic_cast<UDPPeer*>(&peer) == 0)
continue;
- for(u16 i=0; i<CHANNEL_COUNT; i++)
- {
- Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
-
- if (checkIncomingBuffers(channel, peer_id, dst)) {
+ for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
+ if (checkIncomingBuffers(&channel, peer_id, dst)) {
return true;
}
}
LOG(dout_con<<m_connection->getDesc()
<<"DISCO: Removing peer "<<(peer_id)<<std::endl);
- if (m_connection->deletePeer(peer_id, false) == false)
- {
+ if (!m_connection->deletePeer(peer_id, false)) {
derr_con<<m_connection->getDesc()
<<"DISCO: Peer not found"<<std::endl;
}
m_receiveThread.wait();
// Delete peers
- for(std::map<u16, Peer*>::iterator
- j = m_peers.begin();
- j != m_peers.end(); ++j)
- {
- delete j->second;
+ for (auto &peer : m_peers) {
+ delete peer.second;
}
}
std::list<Peer*> Connection::getPeers()
{
std::list<Peer*> list;
- for(std::map<u16, Peer*>::iterator j = m_peers.begin();
- j != m_peers.end(); ++j)
- {
- Peer *peer = j->second;
+ for (auto &p : m_peers) {
+ Peer *peer = p.second;
list.push_back(peer);
}
return list;
float retval = 0.0;
- for (u16 j=0; j<CHANNEL_COUNT; j++) {
+ for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
switch(type) {
case CUR_DL_RATE:
- retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
+ retval += channel.getCurrentDownloadRateKB();
break;
case AVG_DL_RATE:
- retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
+ retval += channel.getAvgDownloadRateKB();
break;
case CUR_INC_RATE:
- retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
+ retval += channel.getCurrentIncomingRateKB();
break;
case AVG_INC_RATE:
- retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
+ retval += channel.getAvgIncomingRateKB();
break;
case AVG_LOSS_RATE:
- retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
+ retval += channel.getAvgLossRateKB();
break;
case CUR_LOSS_RATE:
- retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
+ retval += channel.getCurrentLossRateKB();
break;
default:
FATAL_ERROR("Connection::getLocalStat Invalid stat type");
{
if ((totest - base) > (SEQNUM_MAX/2))
return false;
- else
- return true;
- }
- else
- {
- if ((base - totest) > (SEQNUM_MAX/2))
- return true;
- else
- return false;
+
+ return true;
}
+
+ if ((base - totest) > (SEQNUM_MAX/2))
+ return true;
+
+ return false;
}
inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
u16 window_start = next;
u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
- if (window_start < window_end)
- {
+ if (window_start < window_end) {
return ((seqnum >= window_start) && (seqnum < window_end));
}
- else
- {
- return ((seqnum < window_end) || (seqnum >= window_start));
- }
+
+
+ return ((seqnum < window_end) || (seqnum >= window_start));
}
struct BufferedPacket
data(a_data, a_size)
{}
BufferedPacket(u32 a_size):
- data(a_size), time(0.0), totaltime(0.0), absolute_send_time(-1),
- resend_count(0)
+ data(a_size)
{}
Buffer<u8> data; // Data of the packet, including headers
float time = 0.0f; // Seconds from buffering the packet or re-sending
// Add the TYPE_RELIABLE header to the data
SharedBuffer<u8> makeReliablePacket(
- SharedBuffer<u8> data,
+ const SharedBuffer<u8> &data,
u16 seqnum);
struct IncomingSplitPacket
{
- IncomingSplitPacket() {}
+ IncomingSplitPacket() = default;
+
// Key is chunk number, value is data without headers
std::map<u16, SharedBuffer<u8> > chunks;
u32 chunk_count;
class ReliablePacketBuffer
{
public:
- ReliablePacketBuffer() {};
+ ReliablePacketBuffer() = default;
bool getFirstSeqnum(u16& result);
bool reliable = false;
bool raw = false;
- ConnectionCommand() {}
+ ConnectionCommand() = default;
void serve(Address address_)
{
IncomingSplitBuffer incoming_splits;
- Channel() {};
- ~Channel() {};
+ Channel() = default;
+ ~Channel() = default;
void UpdatePacketLossCounter(unsigned int count);
void UpdatePacketTooLateCounter();
{
public:
- PeerHandler()
- {
- }
- virtual ~PeerHandler()
- {
- }
+ PeerHandler() = default;
+ virtual ~PeerHandler() = default;
/*
This is called after the Peer has been inserted into the
class PeerHelper
{
public:
- PeerHelper() {};
+ PeerHelper() = default;;
PeerHelper(Peer* peer);
~PeerHelper();
float max_rtt = 0.0f;
float avg_rtt = -1.0f;
- rttstats() {};
+ rttstats() = default;
};
rttstats m_rtt;
friend class Connection;
UDPPeer(u16 a_id, Address a_address, Connection* connection);
- virtual ~UDPPeer() {};
+ virtual ~UDPPeer() = default;
void PutReliableSendCommand(ConnectionCommand &c,
unsigned int max_packet_size);
bool timeout = false;
Address address;
- ConnectionEvent() {}
+ ConnectionEvent() = default;
std::string describe()
{
public:
NetworkPacket(u16 command, u32 datasize, u16 peer_id);
NetworkPacket(u16 command, u32 datasize);
- NetworkPacket() {}
+ NetworkPacket() = default;
+
~NetworkPacket();
void putRawPacket(u8 *data, u32 datasize, u16 peer_id);
return;
}
- if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) {
+ if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
actionstream << "Server: Player with an invalid name "
<< "tried to connect from " << addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
<< "tried to connect from " << addr_s << " "
<< "but it was disallowed for the following reason: "
<< reason << std::endl;
- DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING,
- reason.c_str());
+ DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
return;
}
}
return;
}
- if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) {
+ if (!string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)) {
actionstream << "Server: Player with an invalid name "
<< "tried to connect from " << addr_s << std::endl;
DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters");
<< "tried to connect from " << addr_s << " "
<< "but it was disallowed for the following reason: "
<< reason << std::endl;
- DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason.c_str()));
+ DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason));
return;
}
}
if (!has_auth) {
if (!isSingleplayer() &&
g_settings->getBool("disallow_empty_password") &&
- std::string(given_password) == "") {
+ std::string(given_password).empty()) {
actionstream << "Server: " << playername
<< " supplied empty password" << std::endl;
DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
RemoteClient *client = getClient(pkt->getPeerId());
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
- if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
+ if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
client->SetBlockNotSent(blockpos);
if (blockpos2 != blockpos) {
client->SetBlockNotSent(blockpos2);
if (wantSudo) {
DenySudoAccess(pkt->getPeerId());
return;
- } else {
- DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
- return;
}
+
+ DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
+ return;
}
std::string bytes_A;
if (wantSudo) {
DenySudoAccess(pkt->getPeerId());
return;
- } else {
- DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
- return;
}
+
+ DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
+ return;
}
NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
if (wantSudo) {
DenySudoAccess(pkt->getPeerId());
return;
- } else {
- DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
- return;
}
+
+ DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
+ return;
}
std::string bytes_M;
<< " (SRP) password for authentication." << std::endl;
DenySudoAccess(pkt->getPeerId());
return;
- } else {
- actionstream << "Server: User " << client->getName()
- << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
- << " supplied wrong password (auth mechanism: SRP)."
- << std::endl;
- DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
- return;
}
+
+ actionstream << "Server: User " << client->getName()
+ << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
+ << " supplied wrong password (auth mechanism: SRP)."
+ << std::endl;
+ DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
+ return;
}
if (client->create_player_on_auth_success) {
public:
LuaCamera(Camera *m);
- ~LuaCamera() {}
+ ~LuaCamera() = default;
static void create(lua_State *L, Camera *m);
#include "util/string.h"
#include "nodedef.h"
-extern MainGameCallback *g_gamecallback;
int ModApiClient::l_get_current_modname(lua_State *L)
{
// key at index -2 and value at index -1
if(!lua_isstring(L, -1))
return false;
- recipe.push_back(lua_tostring(L, -1));
+ recipe.emplace_back(lua_tostring(L, -1));
// removes value, keeps key for next iteration
lua_pop(L, 1);
colcount++;
// key at index -2 and value at index -1
if(!lua_isstring(L, -1))
return false;
- recipe.push_back(lua_tostring(L, -1));
+ recipe.emplace_back(lua_tostring(L, -1));
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
return false;
std::string replace_to = lua_tostring(L, -1);
lua_pop(L, 1);
- replacements.pairs.push_back(
- std::make_pair(replace_from, replace_to));
+ replacements.pairs.emplace_back(replace_from, replace_to);
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
*/
if(type == "shaped"){
std::string output = getstringfield_default(L, table, "output", "");
- if(output == "")
+ if (output.empty())
throw LuaError("Crafting definition is missing an output");
int width = 0;
*/
else if(type == "shapeless"){
std::string output = getstringfield_default(L, table, "output", "");
- if(output == "")
+ if (output.empty())
throw LuaError("Crafting definition (shapeless)"
" is missing an output");
*/
else if(type == "cooking"){
std::string output = getstringfield_default(L, table, "output", "");
- if(output == "")
+ if (output.empty())
throw LuaError("Crafting definition (cooking)"
" is missing an output");
std::string recipe = getstringfield_default(L, table, "recipe", "");
- if(recipe == "")
+ if (recipe.empty())
throw LuaError("Crafting definition (cooking)"
" is missing a recipe"
" (output=\"" + output + "\")");
*/
else if(type == "fuel"){
std::string recipe = getstringfield_default(L, table, "recipe", "");
- if(recipe == "")
+ if (recipe.empty())
throw LuaError("Crafting definition (fuel)"
" is missing a recipe");
std::string output = getstringfield_default(L, table, "output", "");
std::string type = getstringfield_default(L, table, "type", "shaped");
CraftOutput c_output(output, 0);
- if (output != "") {
+ if (!output.empty()) {
if (craftdef->clearCraftRecipesByOutput(c_output, getServer(L)))
return 0;
- else
- throw LuaError("No craft recipe known for output"
- " (output=\"" + output + "\")");
+
+ throw LuaError("No craft recipe known for output"
+ " (output=\"" + output + "\")");
}
std::vector<std::string> recipe;
int width = 0;
else if (type == "cooking") {
method = CRAFT_METHOD_COOKING;
std::string rec = getstringfield_default(L, table, "recipe", "");
- if (rec == "")
+ if (rec.empty())
throw LuaError("Crafting definition (cooking)"
" is missing a recipe");
recipe.push_back(rec);
else if (type == "fuel") {
method = CRAFT_METHOD_FUEL;
std::string rec = getstringfield_default(L, table, "recipe", "");
- if (rec == "")
+ if (rec.empty())
throw LuaError("Crafting definition (fuel)"
" is missing a recipe");
recipe.push_back(rec);
for (int d = start_radius; d <= radius; d++) {
std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
- for (std::vector<v3s16>::iterator i = list.begin();
- i != list.end(); ++i) {
- v3s16 p = pos + (*i);
+ for (v3s16 i : list) {
+ v3s16 p = pos + i;
content_t c = env->getMap().getNodeNoEx(p).getContent();
if (filter.count(c) != 0) {
push_v3s16(L, p);
}
}
lua_newtable(L);
- for (std::set<content_t>::const_iterator it = filter.begin();
- it != filter.end(); ++it) {
- lua_pushnumber(L, individual_count[*it]);
- lua_setfield(L, -2, ndef->get(*it).name.c_str());
+ for (content_t it : filter) {
+ lua_pushnumber(L, individual_count[it]);
+ lua_setfield(L, -2, ndef->get(it).name.c_str());
}
return 2;
}
for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
success = success & map.repairBlockLight(blockpos, &modified_blocks);
}
- if (modified_blocks.size() > 0) {
+ if (!modified_blocks.empty()) {
MapEditEvent event;
event.type = MEET_OTHER;
- for (std::map<v3s16, MapBlock *>::iterator it = modified_blocks.begin();
- it != modified_blocks.end(); ++it)
- event.modified_blocks.insert(it->first);
+ for (auto &modified_block : modified_blocks)
+ event.modified_blocks.insert(modified_block.first);
map.dispatchEvent(&event);
}
std::vector<v3s16> path = get_path(env, pos1, pos2,
searchdistance, max_jump, max_drop, algo);
- if (path.size() > 0)
- {
+ if (!path.empty()) {
lua_newtable(L);
int top = lua_gettop(L);
unsigned int index = 1;
- for (std::vector<v3s16>::iterator i = path.begin(); i != path.end(); ++i) {
+ for (v3s16 i : path) {
lua_pushnumber(L,index);
- push_v3s16(L, *i);
+ push_v3s16(L, i);
lua_settable(L, top);
index++;
}
tree_def.leavesnode=ndef->getId(leaves);
tree_def.leaves2_chance=0;
getstringfield(L, 2, "leaves2", leaves);
- if (leaves !="")
- {
+ if (!leaves.empty()) {
tree_def.leaves2node=ndef->getId(leaves);
getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
}
getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
tree_def.fruit_chance=0;
getstringfield(L, 2, "fruit", fruit);
- if (fruit != "")
- {
+ if (!fruit.empty()) {
tree_def.fruitnode=ndef->getId(fruit);
getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
}
while (lua_next(L, 2) != 0)
{
const char *header = luaL_checkstring(L, -1);
- req.extra_headers.push_back(header);
+ req.extra_headers.emplace_back(header);
lua_pop(L, 1);
}
}
{
}
-InvRef::~InvRef()
-{
-}
-
// Creates an InvRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
void InvRef::create(lua_State *L, const InventoryLocation &loc)
public:
InvRef(const InventoryLocation &loc);
- ~InvRef();
+ ~InvRef() = default;
// Creates an InvRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
bool status = true;
item.name = luaL_checkstring(L, 2);
- if (item.name == "" || item.empty()) {
+ if (item.name.empty() || item.empty()) {
item.clear();
status = false;
}
lua_newtable(L);
const StringMap &fields = item.metadata.getStrings();
- for (StringMap::const_iterator it = fields.begin();
- it != fields.end(); ++it) {
- const std::string &name = it->first;
+ for (const auto &field : fields) {
+ const std::string &name = field.first;
if (name.empty())
continue;
- const std::string &value = it->second;
+ const std::string &value = field.second;
lua_pushlstring(L, name.c_str(), name.size());
lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3);
{
}
-LuaItemStack::~LuaItemStack()
-{
-}
-
const ItemStack& LuaItemStack::getItem() const
{
return m_stack;
public:
LuaItemStack(const ItemStack &item);
- ~LuaItemStack();
+ ~LuaItemStack() = default;
const ItemStack& getItem() const;
ItemStack& getItem();
static int gc_object(lua_State *L);
public:
ItemStackMetaRef(ItemStack *istack): istack(istack) {}
- ~ItemStackMetaRef() {}
+ ~ItemStackMetaRef() = default;
// Creates an ItemStackMetaRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
public:
LuaLocalPlayer(LocalPlayer *m);
- ~LuaLocalPlayer() {}
+ ~LuaLocalPlayer() = default;
static void create(lua_State *L, LocalPlayer *m);
public:
LuaMinimap(Minimap *m);
- ~LuaMinimap() {}
+ ~LuaMinimap() = default;
static void create(lua_State *L, Minimap *object);
{
}
-NodeMetaRef::~NodeMetaRef()
-{
-}
-
// Creates an NodeMetaRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env)
NodeMetaRef(v3s16 p, ServerEnvironment *env);
NodeMetaRef(Metadata *meta);
- ~NodeMetaRef();
+ ~NodeMetaRef() = default;
// Creates an NodeMetaRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
{
}
-NodeTimerRef::~NodeTimerRef()
-{
-}
-
// Creates an NodeTimerRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
void NodeTimerRef::create(lua_State *L, v3s16 p, ServerEnvironment *env)
public:
NodeTimerRef(v3s16 p, ServerEnvironment *env);
- ~NodeTimerRef();
+ ~NodeTimerRef() = default;
// Creates an NodeTimerRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
}
-LuaPerlinNoise::~LuaPerlinNoise()
-{
-}
-
-
int LuaPerlinNoise::l_get2d(lua_State *L)
{
NO_MAP_LOCK_REQUIRED;
public:
LuaPerlinNoise(NoiseParams *params);
- ~LuaPerlinNoise();
+ ~LuaPerlinNoise() = default;
// LuaPerlinNoise(seed, octaves, persistence, scale)
// Creates an LuaPerlinNoise and leaves it on top of stack
float frame_speed;
player->getLocalAnimations(frames, &frame_speed);
- for (int i = 0; i < 4; i++) {
- push_v2s32(L, frames[i]);
+ for (v2s32 frame : frames) {
+ push_v2s32(L, frame);
}
lua_pushnumber(L, frame_speed);
ServerActiveObject *co = getobject(ref);
if (co == NULL) return 0;
// Do it
- std::string bone = "";
+ std::string bone;
if (!lua_isnil(L, 2))
bone = lua_tostring(L, 2);
v3f position = v3f(0, 0, 0);
if (co == NULL)
return 0;
// Do it
- std::string bone = "";
+ std::string bone;
if (!lua_isnil(L, 2))
bone = lua_tostring(L, 2);
return 0;
// Do it
int parent_id = 0;
- std::string bone = "";
+ std::string bone;
v3f position = v3f(0, 0, 0);
v3f rotation = v3f(0, 0, 0);
co->getAttachment(&parent_id, &bone, &position, &rotation);
// Do it
int parent_id = 0;
- std::string bone = "";
+ std::string bone;
v3f position = v3f(0, 0, 0);
v3f rotation = v3f(0, 0, 0);
co->getAttachment(&parent_id, &bone, &position, &rotation);
return 0;
int parent_id = 0;
- std::string bone = "";
+ std::string bone;
v3f position;
v3f rotation;
co->getAttachment(&parent_id, &bone, &position, &rotation);
std::string attr = luaL_checkstring(L, 2);
- std::string value = "";
+ std::string value;
if (co->getExtendedAttribute(attr, &value)) {
lua_pushstring(L, value.c_str());
return 1;
while (lua_next(L, 4) != 0) {
// key at index -2 and value at index -1
if (lua_isstring(L, -1))
- params.push_back(lua_tostring(L, -1));
+ params.emplace_back(lua_tostring(L, -1));
else
- params.push_back("");
+ params.emplace_back("");
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
bool clouds;
player->getSky(&bgcolor, &type, ¶ms, &clouds);
- type = type == "" ? "regular" : type;
+ type = type.empty() ? "regular" : type;
push_ARGB8(L, bgcolor);
lua_pushlstring(L, type.c_str(), type.size());
lua_newtable(L);
s16 i = 1;
- for (std::vector<std::string>::iterator it = params.begin();
- it != params.end(); ++it) {
- lua_pushlstring(L, it->c_str(), it->size());
+ for (const std::string ¶m : params) {
+ lua_pushlstring(L, param.c_str(), param.size());
lua_rawseti(L, -2, i);
i++;
}
//infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
}
-ObjectRef::~ObjectRef()
-{
- /*if (m_object)
- infostream<<"ObjectRef destructing for id="
- <<m_object->getId()<<std::endl;
- else
- infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
-}
-
// Creates an ObjectRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
void ObjectRef::create(lua_State *L, ServerActiveObject *object)
public:
ObjectRef(ServerActiveObject *object);
- ~ObjectRef();
+ ~ObjectRef() = default;
// Creates an ObjectRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side.
struct TileAnimationParams animation;
animation.type = TAT_NONE;
- std::string texture = "";
- std::string playername = "";
+ std::string texture;
+ std::string playername;
u8 glow = 0;
struct TileAnimationParams animation;
animation.type = TAT_NONE;
ServerActiveObject *attached = NULL;
- std::string texture = "";
- std::string playername = "";
+ std::string texture;
+ std::string playername;
u8 glow = 0;
if (lua_gettop(L) > 1) //deprecated
// Get parameters
u32 id = luaL_checknumber(L, 1);
- std::string playername = "";
+ std::string playername;
if (lua_gettop(L) == 2) {
playername = luaL_checkstring(L, 2);
}
std::vector<std::string> keys = o->m_settings->getNames();
lua_newtable(L);
- for (unsigned int i=0; i < keys.size(); i++)
- {
- lua_pushstring(L, o->m_settings->get(keys[i]).c_str());
- lua_setfield(L, -2, keys[i].c_str());
+ for (const std::string &key : keys) {
+ lua_pushstring(L, o->m_settings->get(key).c_str());
+ lua_setfield(L, -2, key.c_str());
}
return 1;
public:
StorageRef(ModMetadata *object);
- ~StorageRef() {}
+ ~StorageRef() = default;
static void Register(lua_State *L);
static void create(lua_State *L, ModMetadata *object);
int index = 0;
lua_newtable(L);
- for (size_t i = 0; i < list.size(); i++) {
- if (list_all || list_dirs == list[i].dir) {
- lua_pushstring(L, list[i].name.c_str());
+ for (const fs::DirListNode &dln : list) {
+ if (list_all || list_dirs == dln.dir) {
+ lua_pushstring(L, dln.name.c_str());
lua_rawseti(L, -2, ++index);
}
}
lua_pushstring(L, g_version_string);
lua_setfield(L, table, "string");
- if (strcmp(g_version_string, g_version_hash)) {
+ if (strcmp(g_version_string, g_version_hash) != 0) {
lua_pushstring(L, g_version_hash);
lua_setfield(L, table, "hash");
}
MAP_LOCK_REQUIRED;
LuaVoxelManip *o = checkobject(L, 1);
- bool update_light = lua_isboolean(L, 2) ? lua_toboolean(L, 2) : true;
+ bool update_light = !lua_isboolean(L, 2) || lua_toboolean(L, 2);
GET_ENV_PTR;
ServerMap *map = &(env->getServerMap());
if (o->is_mapgen_vm || !update_light) {
MapEditEvent event;
event.type = MEET_OTHER;
- for (std::map<v3s16, MapBlock *>::iterator it = o->modified_blocks.begin();
- it != o->modified_blocks.end(); ++it)
- event.modified_blocks.insert(it->first);
+ for (const auto &modified_block : o->modified_blocks)
+ event.modified_blocks.insert(modified_block.first);
map->dispatchEvent(&event);
v3s16 fpmax = vm->m_area.MaxEdge;
v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock;
v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock;
- bool propagate_shadow = lua_isboolean(L, 4) ? lua_toboolean(L, 4) : true;
+ bool propagate_shadow = !lua_isboolean(L, 4) || lua_toboolean(L, 4);
sortBoxVerticies(pmin, pmax);
if (!vm->m_area.contains(VoxelArea(pmin, pmax)))
fs::CreateDir(players_path);
for (RemotePlayer *player : m_players) {
- if (player->checkModified() || (player->getPlayerSAO() &&
+ if (player->checkModified() || (player->getPlayerSAO() &&
player->getPlayerSAO()->extendedAttributesModified())) {
try {
m_player_database->savePlayer(player);
Semaphore(int val = 0);
~Semaphore();
+ DISABLE_CLASS_COPY(Semaphore);
+
void post(unsigned int num = 1);
void wait();
bool wait(unsigned int time_ms);
#else
sem_t semaphore;
#endif
-
- DISABLE_CLASS_COPY(Semaphore);
};
};
// Runs a unit test and reports results
-#define TEST(fxn, ...) do { \
+#define TEST(fxn, ...) { \
u64 t1 = porting::getTimeMs(); \
try { \
fxn(__VA_ARGS__); \
num_tests_run++; \
u64 tdiff = porting::getTimeMs() - t1; \
rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \
-} while (0)
+}
// Asserts the specified condition is true, or fails the current unit test
-#define UASSERT(x) do { \
+#define UASSERT(x) \
if (!(x)) { \
rawstream << "Test assertion failed: " #x << std::endl \
<< " at " << fs::GetFilenameFromPath(__FILE__) \
<< ":" << __LINE__ << std::endl; \
throw TestFailedException(); \
- } \
-} while (0)
+ }
// Asserts the specified condition is true, or fails the current unit test
// and prints the format specifier fmt
-#define UTEST(x, fmt, ...) do { \
+#define UTEST(x, fmt, ...) \
if (!(x)) { \
char utest_buf[1024]; \
snprintf(utest_buf, sizeof(utest_buf), fmt, __VA_ARGS__); \
<< " at " << fs::GetFilenameFromPath(__FILE__) \
<< ":" << __LINE__ << std::endl; \
throw TestFailedException(); \
- } \
-} while (0)
+ }
// Asserts the comparison specified by CMP is true, or fails the current unit test
#define UASSERTCMP(T, CMP, actual, expected) do { \
Foobar foobar;
size_t i;
- foobar.m_nodenames.push_back("default:torch");
+ foobar.m_nodenames.emplace_back("default:torch");
- foobar.m_nodenames.push_back("default:dirt_with_grass");
- foobar.m_nodenames.push_back("default:water");
- foobar.m_nodenames.push_back("default:abloobloobloo");
- foobar.m_nodenames.push_back("default:stone");
- foobar.m_nodenames.push_back("default:shmegoldorf");
+ foobar.m_nodenames.emplace_back("default:dirt_with_grass");
+ foobar.m_nodenames.emplace_back("default:water");
+ foobar.m_nodenames.emplace_back("default:abloobloobloo");
+ foobar.m_nodenames.emplace_back("default:stone");
+ foobar.m_nodenames.emplace_back("default:shmegoldorf");
foobar.m_nnlistsizes.push_back(5);
- foobar.m_nodenames.push_back("group:liquids");
+ foobar.m_nodenames.emplace_back("group:liquids");
foobar.m_nnlistsizes.push_back(1);
- foobar.m_nodenames.push_back("default:warf");
- foobar.m_nodenames.push_back("default:stone");
- foobar.m_nodenames.push_back("default:bloop");
+ foobar.m_nodenames.emplace_back("default:warf");
+ foobar.m_nodenames.emplace_back("default:stone");
+ foobar.m_nodenames.emplace_back("default:bloop");
foobar.m_nnlistsizes.push_back(3);
foobar.m_nnlistsizes.push_back(0);
- foobar.m_nodenames.push_back("default:brick");
- foobar.m_nodenames.push_back("default:desert_stone");
- foobar.m_nodenames.push_back("default:shnitzle");
+ foobar.m_nodenames.emplace_back("default:brick");
+ foobar.m_nodenames.emplace_back("default:desert_stone");
+ foobar.m_nodenames.emplace_back("default:shnitzle");
ndef->pendNodeResolve(&foobar);
UASSERT(foobar.m_ndef == ndef);
Foobaz foobaz1;
foobaz1.test_content1 = 1234;
foobaz1.test_content2 = 5678;
- foobaz1.m_nodenames.push_back("default:dirt_with_grass");
- foobaz1.m_nodenames.push_back("default:abloobloobloo");
+ foobaz1.m_nodenames.emplace_back("default:dirt_with_grass");
+ foobaz1.m_nodenames.emplace_back("default:abloobloobloo");
ndef->pendNodeResolve(&foobaz1);
Foobaz foobaz2;
foobaz2.test_content1 = 1234;
foobaz2.test_content2 = 5678;
- foobaz2.m_nodenames.push_back("default:dirt_with_grass");
- foobaz2.m_nodenames.push_back("default:abloobloobloo");
+ foobaz2.m_nodenames.emplace_back("default:dirt_with_grass");
+ foobaz2.m_nodenames.emplace_back("default:abloobloobloo");
ndef->pendNodeResolve(&foobaz2);
ndef->cancelNodeResolveCallback(&foobaz1);
std::ios_base::in | std::ios_base::out);
std::vector<std::string> names;
- names.push_back("foo");
- names.push_back("bar");
- names.push_back("baz");
- names.push_back("qux");
+ names.emplace_back("foo");
+ names.emplace_back("bar");
+ names.emplace_back("baz");
+ names.emplace_back("qux");
Schematic schem, schem2;
schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS;
std::vector<std::string> names;
- names.push_back("air");
- names.push_back("default:lava_source");
- names.push_back("default:glass");
+ names.emplace_back("air");
+ names.emplace_back("default:lava_source");
+ names.emplace_back("default:glass");
std::ostringstream ss(std::ios_base::binary);
static const u8 num_threads = 4;
AtomicTestThread *threads[num_threads];
- for (u8 i = 0; i < num_threads; ++i) {
- threads[i] = new AtomicTestThread(val, trigger);
- UASSERT(threads[i]->start());
+ for (auto &thread : threads) {
+ thread = new AtomicTestThread(val, trigger);
+ UASSERT(thread->start());
}
trigger.post(num_threads);
- for (u8 i = 0; i < num_threads; ++i) {
- threads[i]->wait();
- delete threads[i];
+ for (AtomicTestThread *thread : threads) {
+ thread->wait();
+ delete thread;
}
UASSERT(val == num_threads * 0x10000);
// Correct results
std::vector<VoxelArea> results;
- results.push_back(VoxelArea(v3s16(-2,-2,-3), v3s16(3,2,-3)));
- results.push_back(VoxelArea(v3s16(3,-2,-2), v3s16(3,2,2)));
+ results.emplace_back(v3s16(-2,-2,-3), v3s16(3,2,-3));
+ results.emplace_back(v3s16(3,-2,-2), v3s16(3,2,2));
UASSERT(aa.size() == results.size());
#include "base64.h"
#include "sha1.h"
#include "srp.h"
-#include "string.h"
+#include "util/string.h"
#include "debug.h"
// Get an sha-1 hash of the player's name combined with
bool base64_is_valid(std::string const& s)
{
- for(size_t i=0; i<s.size(); i++)
- if(!is_base64(s[i])) return false;
+ for (char i : s)
+ if (!is_base64(i))
+ return false;
return true;
}
class MutexedMap
{
public:
- MutexedMap() {}
+ MutexedMap() = default;
void set(const Key &name, const Value &value)
{
template<typename Key, typename U, typename Caller, typename CallerData>
friend class RequestQueue;
- MutexedQueue() {}
+ MutexedQueue() = default;
+
bool empty() const
{
MutexAutoLock lock(m_mutex);
T t = m_queue.front();
m_queue.pop_front();
return t;
- } else {
- return T();
}
+
+ return T();
}
T pop_front(u32 wait_time_max_ms)
T t = m_queue.front();
m_queue.pop_front();
return t;
- } else {
- throw ItemNotFoundException("MutexedQueue: queue is empty");
}
+
+ throw ItemNotFoundException("MutexedQueue: queue is empty");
}
T pop_frontNoEx()
T t = m_queue.back();
m_queue.pop_back();
return t;
- } else {
- throw ItemNotFoundException("MutexedQueue: queue is empty");
}
+
+ throw ItemNotFoundException("MutexedQueue: queue is empty");
}
/* this version of pop_back returns a empty element of T on timeout.
T t = m_queue.back();
m_queue.pop_back();
return t;
- } else {
- return T();
}
+
+ return T();
}
T pop_backNoEx()
#include "../constants.h" // BS, MAP_BLOCKSIZE
#include "../noise.h" // PseudoRandom, PcgRandom
#include "../threading/mutex_auto_lock.h"
-#include <string.h>
+#include <cstring>
// myrand
f32 distanceSq = 0;
//! Constructor for POINTEDTHING_NOTHING
- PointedThing() {};
+ PointedThing() = default;
//! Constructor for POINTEDTHING_NODE
PointedThing(const v3s16 &under, const v3s16 &above,
const v3s16 &real_under, const v3f &point, const v3s16 &normal,
writeU16((u8 *)buf, plain.size());
s.append(buf, 2);
- for (u32 i = 0; i < plain.size(); i++) {
- writeU16((u8 *)buf, plain[i]);
+ for (wchar_t i : plain) {
+ writeU16((u8 *)buf, i);
s.append(buf, 2);
}
return s;
std::ostringstream os(std::ios::binary);
os << "\"";
- for (size_t i = 0; i < plain.size(); i++) {
- char c = plain[i];
+ for (char c : plain) {
switch (c) {
case '"':
os << "\\\"";
if (c == '"') {
return os.str();
- } else if (c == '\\') {
+ }
+
+ if (c == '\\') {
c2 = is.get();
if (is.eof())
throw SerializationError("JSON string ended prematurely");
// Found end of word
is.unget();
break;
- } else {
- tmp_os << c;
}
+
+ tmp_os << c;
}
expect_initial_quote = false;
}
if (is_json) {
std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
return deSerializeJsonString(tmp_is);
- } else
- return tmp_os.str();
+ }
+
+ return tmp_os.str();
}
////
#include <endian.h>
#endif
#endif
-#include <string.h> // for memcpy
+#include <cstring> // for memcpy
#include <iostream>
#include <string>
#include <vector>
*/
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <assert.h>
+#include <cstdio>
+#include <cstring>
+#include <cstdlib>
+#include <cassert>
#include "sha1.h"
+(bytes[t*4 + 2] << 8)
+ bytes[t*4 + 3];
for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 );
-
+
/* main loop */
Uint32 temp;
for( t = 0; t < 80; t++ )
num -= toCopy;
data += toCopy;
unprocessedBytes += toCopy;
-
+
// there is a full block
if( unprocessedBytes == 64 ) process();
}
Uint32 totalBitsH = size >> 29;
// add 0x80 to the message
addBytes( "\x80", 1 );
-
+
unsigned char footer[64] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
#include <windows.h>
#include <wincrypt.h>
#else
- #include <time.h>
+ #include <ctime>
+
#endif
// clang-format on
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
+#include <cstdlib>
+#include <cstring>
+#include <cstdio>
#include <config.h>
template<typename Key, typename T, typename Caller, typename CallerData>
class GetRequest {
public:
- GetRequest() {}
- ~GetRequest() {}
+ GetRequest() = default;
+ ~GetRequest() = default;
GetRequest(const Key &a_key): key(a_key)
{
{
public:
UpdateThread(const std::string &name) : Thread(name + "Update") {}
- ~UpdateThread() {}
+ ~UpdateThread() = default;
void deferUpdate() { m_update_sem.post(); }