Convert time-related code in network to 64bit to avoid overflow

This commit is contained in:
Benau 2018-08-27 13:49:11 +08:00
parent e5925a53b7
commit 0f39add432
19 changed files with 110 additions and 103 deletions

View File

@ -42,6 +42,7 @@
#include "race/race_manager.hpp" #include "race/race_manager.hpp"
#include "states_screens/state_manager.hpp" #include "states_screens/state_manager.hpp"
#include "utils/profiler.hpp" #include "utils/profiler.hpp"
#include "utils/time.hpp"
#ifndef WIN32 #ifndef WIN32
#include <unistd.h> #include <unistd.h>
@ -111,11 +112,9 @@ float MainLoop::getLimitedDt()
return 1.0f/60.0f; return 1.0f/60.0f;
} }
IrrlichtDevice* device = irr_driver->getDevice();
while( 1 ) while( 1 )
{ {
m_curr_time = device->getTimer()->getRealTime(); m_curr_time = StkTime::getRealTimeMs();
dt = (float)(m_curr_time - m_prev_time); dt = (float)(m_curr_time - m_prev_time);
// On a server (i.e. without graphics) the frame rate can be under // On a server (i.e. without graphics) the frame rate can be under
// 1 ms, i.e. dt = 0. Additionally, the resolution of a sleep // 1 ms, i.e. dt = 0. Additionally, the resolution of a sleep
@ -131,7 +130,7 @@ float MainLoop::getLimitedDt()
while (dt <= 0 && !ProfileWorld::isProfileMode()) while (dt <= 0 && !ProfileWorld::isProfileMode())
{ {
StkTime::sleep(1); StkTime::sleep(1);
m_curr_time = device->getTimer()->getRealTime(); m_curr_time = StkTime::getRealTimeMs();
dt = (float)(m_curr_time - m_prev_time); dt = (float)(m_curr_time - m_prev_time);
} }
@ -279,9 +278,7 @@ void MainLoop::updateRace(int ticks)
*/ */
void MainLoop::run() void MainLoop::run()
{ {
IrrlichtDevice* device = irr_driver->getDevice(); m_curr_time = StkTime::getRealTimeMs();
m_curr_time = device->getTimer()->getRealTime();
// DT keeps track of the leftover time, since the race update // DT keeps track of the leftover time, since the race update
// happens in fixed timesteps // happens in fixed timesteps
float left_over_time = 0; float left_over_time = 0;

View File

@ -39,8 +39,8 @@ private:
Synchronised<int> m_ticks_adjustment; Synchronised<int> m_ticks_adjustment;
uint32_t m_curr_time; uint64_t m_curr_time;
uint32_t m_prev_time; uint64_t m_prev_time;
unsigned m_parent_pid; unsigned m_parent_pid;
float getLimitedDt(); float getLimitedDt();
void updateRace(int ticks); void updateRace(int ticks);

View File

@ -771,6 +771,7 @@ void ClientLobby::startGame(Event* event)
int sleep_time = (int)(start_time - cur_time); int sleep_time = (int)(start_time - cur_time);
Log::info("ClientLobby", "Start game after %dms", sleep_time); Log::info("ClientLobby", "Start game after %dms", sleep_time);
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time)); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));
Log::info("ClientLobby", "Started at %lf", StkTime::getRealTime());
m_state.store(RACING); m_state.store(RACING);
}); });
} // startGame } // startGame

View File

@ -55,9 +55,9 @@ void ConnectToPeer::asynchronousUpdate()
break; break;
} }
// Each 2 second for a ping or broadcast // Each 2 second for a ping or broadcast
if (StkTime::getRealTime() > m_timer + 2.0) if (StkTime::getRealTimeMs() > m_timer + 2000)
{ {
m_timer = StkTime::getRealTime(); m_timer = StkTime::getRealTimeMs();
// Send a broadcast packet with the string aloha_stk inside, // Send a broadcast packet with the string aloha_stk inside,
// the client will know our ip address and will connect // the client will know our ip address and will connect
// The wan remote should already start its ping message to us now // The wan remote should already start its ping message to us now

View File

@ -33,7 +33,7 @@ protected:
TransportAddress m_peer_address; TransportAddress m_peer_address;
/** Timer use for tracking broadcast. */ /** Timer use for tracking broadcast. */
double m_timer = 0.0; uint64_t m_timer = 0;
/** If greater than a certain value, terminate this protocol. */ /** If greater than a certain value, terminate this protocol. */
unsigned m_tried_connection = 0; unsigned m_tried_connection = 0;

View File

@ -141,7 +141,7 @@ void ConnectToServer::asynchronousUpdate()
request_connection->requestStart(); request_connection->requestStart();
m_current_protocol = request_connection; m_current_protocol = request_connection;
// Reset timer for next usage // Reset timer for next usage
m_timer = 0.0; m_timer = 0;
break; break;
} }
case REQUESTING_CONNECTION: case REQUESTING_CONNECTION:
@ -169,7 +169,7 @@ void ConnectToServer::asynchronousUpdate()
" aloha, trying to connect anyway."); " aloha, trying to connect anyway.");
m_state = CONNECTING; m_state = CONNECTING;
// Reset timer for next usage // Reset timer for next usage
m_timer = 0.0; m_timer = 0;
m_tried_connection = 0; m_tried_connection = 0;
} }
else else
@ -190,9 +190,9 @@ void ConnectToServer::asynchronousUpdate()
{ {
// Send a 1-byte datagram, the remote host can simply ignore // Send a 1-byte datagram, the remote host can simply ignore
// this datagram, to keep the port open (2 second each) // this datagram, to keep the port open (2 second each)
if (StkTime::getRealTime() > m_timer + 2.0) if (StkTime::getRealTimeMs() > m_timer + 2000)
{ {
m_timer = StkTime::getRealTime(); m_timer = StkTime::getRealTimeMs();
BareNetworkString data; BareNetworkString data;
data.addUInt8(0); data.addUInt8(0);
STKHost::get()->sendRawPacket(data, m_server_address); STKHost::get()->sendRawPacket(data, m_server_address);
@ -204,9 +204,9 @@ void ConnectToServer::asynchronousUpdate()
case CONNECTING: // waiting the server to answer our connection case CONNECTING: // waiting the server to answer our connection
{ {
// Every 5 seconds // Every 5 seconds
if (StkTime::getRealTime() > m_timer + 5.0) if (StkTime::getRealTimeMs() > m_timer + 5000)
{ {
m_timer = StkTime::getRealTime(); m_timer = StkTime::getRealTimeMs();
STKHost::get()->stopListening(); STKHost::get()->stopListening();
STKHost::get()->connect(m_server_address); STKHost::get()->connect(m_server_address);
STKHost::get()->startListening(); STKHost::get()->startListening();
@ -420,7 +420,7 @@ void ConnectToServer::waitingAloha(bool is_wan)
m_server_address = sender; m_server_address = sender;
m_state = CONNECTING; m_state = CONNECTING;
// Reset timer for next usage // Reset timer for next usage
m_timer = 0.0; m_timer = 0;
m_tried_connection = 0; m_tried_connection = 0;
} }
} // waitingAloha } // waitingAloha

View File

@ -31,7 +31,7 @@ class Server;
class ConnectToServer : public Protocol class ConnectToServer : public Protocol
{ {
private: private:
double m_timer = 0.0; uint64_t m_timer = 0;
TransportAddress m_server_address; TransportAddress m_server_address;
std::shared_ptr<Server> m_server; std::shared_ptr<Server> m_server;
unsigned m_tried_connection = 0; unsigned m_tried_connection = 0;

View File

@ -77,8 +77,8 @@ void RequestConnection::asynchronousUpdate()
{ {
// Allow up to 10 seconds for the separate process to // Allow up to 10 seconds for the separate process to
// fully start-up // fully start-up
double timeout = StkTime::getRealTime() + 10.; uint64_t timeout = StkTime::getRealTimeMs() + 10000;
while (StkTime::getRealTime() < timeout) while (StkTime::getRealTimeMs() < timeout)
{ {
const std::string& sid = NetworkConfig::get() const std::string& sid = NetworkConfig::get()
->getServerIdFile(); ->getServerIdFile();

View File

@ -212,7 +212,7 @@ void ServerLobby::setup()
// the server are ready: // the server are ready:
resetPeersReady(); resetPeersReady();
m_peers_votes.clear(); m_peers_votes.clear();
m_timeout.store(std::numeric_limits<float>::max()); m_timeout.store(std::numeric_limits<int64_t>::max());
m_waiting_for_reset = false; m_waiting_for_reset = false;
Log::info("ServerLobby", "Reset server to initial state."); Log::info("ServerLobby", "Reset server to initial state.");
@ -397,19 +397,20 @@ void ServerLobby::asynchronousUpdate()
(float)NetworkConfig::get()->getMaxPlayers() * (float)NetworkConfig::get()->getMaxPlayers() *
UserConfigParams::m_start_game_threshold || UserConfigParams::m_start_game_threshold ||
m_game_setup->isGrandPrixStarted()) && m_game_setup->isGrandPrixStarted()) &&
m_timeout.load() == std::numeric_limits<float>::max()) m_timeout.load() == std::numeric_limits<int64_t>::max())
{ {
m_timeout.store((float)StkTime::getRealTime() + m_timeout.store((int64_t)StkTime::getRealTimeMs() +
UserConfigParams::m_start_game_counter); (int64_t)
(UserConfigParams::m_start_game_counter * 1000.0f));
} }
else if ((float)players.size() < else if ((float)players.size() <
(float)NetworkConfig::get()->getMaxPlayers() * (float)NetworkConfig::get()->getMaxPlayers() *
UserConfigParams::m_start_game_threshold && UserConfigParams::m_start_game_threshold &&
!m_game_setup->isGrandPrixStarted()) !m_game_setup->isGrandPrixStarted())
{ {
m_timeout.store(std::numeric_limits<float>::max()); m_timeout.store(std::numeric_limits<int64_t>::max());
} }
if (m_timeout.load() < (float)StkTime::getRealTime()) if (m_timeout.load() < (int64_t)StkTime::getRealTimeMs())
{ {
startSelection(); startSelection();
return; return;
@ -444,10 +445,11 @@ void ServerLobby::asynchronousUpdate()
case SELECTING: case SELECTING:
{ {
auto result = handleVote(); auto result = handleVote();
if (m_timeout.load() < (float)StkTime::getRealTime() || if (m_timeout.load() < (int64_t)StkTime::getRealTimeMs() ||
(std::get<3>(result) && (std::get<3>(result) &&
m_timeout.load() - (UserConfigParams::m_voting_timeout / 2.0f) < m_timeout.load() -
(float)StkTime::getRealTime())) (int64_t)(UserConfigParams::m_voting_timeout / 2.0f * 1000.0f) <
(int64_t)StkTime::getRealTimeMs()))
{ {
m_game_setup->setRace(std::get<0>(result), std::get<1>(result), m_game_setup->setRace(std::get<0>(result), std::get<1>(result),
std::get<2>(result)); std::get<2>(result));
@ -509,9 +511,8 @@ void ServerLobby::asynchronousUpdate()
void ServerLobby::sendBadConnectionMessageToPeer(std::shared_ptr<STKPeer> p) void ServerLobby::sendBadConnectionMessageToPeer(std::shared_ptr<STKPeer> p)
{ {
const unsigned max_ping = UserConfigParams::m_max_ping; const unsigned max_ping = UserConfigParams::m_max_ping;
Log::warn("ServerLobby", "Peer %s cannot catch up with max ping %d, it" Log::warn("ServerLobby", "Peer %s cannot catch up with max ping %d.",
" started at %lf.", p->getAddress().toString().c_str(), max_ping, p->getAddress().toString().c_str(), max_ping);
StkTime::getRealTime());
NetworkString* msg = getNetworkString(); NetworkString* msg = getNetworkString();
msg->setSynchronous(true); msg->setSynchronous(true);
msg->addUInt8(LE_BAD_CONNECTION); msg->addUInt8(LE_BAD_CONNECTION);
@ -627,14 +628,14 @@ void ServerLobby::update(int ticks)
resetPeersReady(); resetPeersReady();
// Set the delay before the server forces all clients to exit the race // Set the delay before the server forces all clients to exit the race
// result screen and go back to the lobby // result screen and go back to the lobby
m_timeout.store((float)StkTime::getRealTime() + 15.0f); m_timeout.store((int64_t)StkTime::getRealTimeMs() + 15000);
m_state = RESULT_DISPLAY; m_state = RESULT_DISPLAY;
sendMessageToPeers(m_result_ns, /*reliable*/ true); sendMessageToPeers(m_result_ns, /*reliable*/ true);
Log::info("ServerLobby", "End of game message sent"); Log::info("ServerLobby", "End of game message sent");
break; break;
case RESULT_DISPLAY: case RESULT_DISPLAY:
if (checkPeersReady() || if (checkPeersReady() ||
StkTime::getRealTime() > m_timeout.load()) (int64_t)StkTime::getRealTimeMs() > m_timeout.load())
{ {
// Send a notification to all clients to exit // Send a notification to all clients to exit
// the race result screen // the race result screen
@ -866,7 +867,7 @@ void ServerLobby::startSelection(const Event *event)
ul.unlock(); ul.unlock();
// Will be changed after the first vote received // Will be changed after the first vote received
m_timeout.store(std::numeric_limits<float>::max()); m_timeout.store(std::numeric_limits<int64_t>::max());
} // startSelection } // startSelection
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -876,9 +877,9 @@ void ServerLobby::startSelection(const Event *event)
void ServerLobby::checkIncomingConnectionRequests() void ServerLobby::checkIncomingConnectionRequests()
{ {
// First poll every 5 seconds. Return if no polling needs to be done. // First poll every 5 seconds. Return if no polling needs to be done.
const float POLL_INTERVAL = 5.0f; const uint64_t POLL_INTERVAL = 5000;
static double last_poll_time = 0; static uint64_t last_poll_time = 0;
if (StkTime::getRealTime() < last_poll_time + POLL_INTERVAL) if (StkTime::getRealTimeMs() < last_poll_time + POLL_INTERVAL)
return; return;
// Keep the port open, it can be sent to anywhere as we will send to the // Keep the port open, it can be sent to anywhere as we will send to the
@ -891,7 +892,7 @@ void ServerLobby::checkIncomingConnectionRequests()
} }
// Now poll the stk server // Now poll the stk server
last_poll_time = StkTime::getRealTime(); last_poll_time = StkTime::getRealTimeMs();
// ======================================================================== // ========================================================================
class PollServerRequest : public Online::XMLRequest class PollServerRequest : public Online::XMLRequest
@ -1509,15 +1510,20 @@ void ServerLobby::handleUnencryptedConnection(std::shared_ptr<STKPeer> peer,
NetworkString* message_ack = getNetworkString(4); NetworkString* message_ack = getNetworkString(4);
message_ack->setSynchronous(true); message_ack->setSynchronous(true);
// connection success -- return the host id of peer // connection success -- return the host id of peer
float auto_start_timer = m_timeout.load(); float auto_start_timer = 0.0f;
if (m_timeout.load() == std::numeric_limits<int64_t>::max())
auto_start_timer = std::numeric_limits<float>::max();
else
{
auto_start_timer =
(m_timeout.load() - (int64_t)StkTime::getRealTimeMs()) / 1000.0f;
}
message_ack->addUInt8(LE_CONNECTION_ACCEPTED).addUInt32(peer->getHostId()) message_ack->addUInt8(LE_CONNECTION_ACCEPTED).addUInt32(peer->getHostId())
.addUInt32(NetworkConfig::m_server_version) .addUInt32(NetworkConfig::m_server_version).addFloat(auto_start_timer);
.addFloat(auto_start_timer == std::numeric_limits<float>::max() ?
auto_start_timer : auto_start_timer - (float)StkTime::getRealTime());
peer->sendPacket(message_ack); peer->sendPacket(message_ack);
delete message_ack; delete message_ack;
m_peers_ready[peer] = std::make_pair(false, 0.0); m_peers_ready[peer] = false;
for (std::shared_ptr<NetworkPlayerProfile> npp : peer->getPlayerProfiles()) for (std::shared_ptr<NetworkPlayerProfile> npp : peer->getPlayerProfiles())
{ {
m_game_setup->addPlayer(npp); m_game_setup->addPlayer(npp);
@ -1658,13 +1664,14 @@ void ServerLobby::playerVote(Event* event)
return; return;
// Check if first vote, if so start counter // Check if first vote, if so start counter
if (m_timeout.load() == std::numeric_limits<float>::max()) if (m_timeout.load() == std::numeric_limits<int64_t>::max())
{ {
m_timeout.store((float)StkTime::getRealTime() + m_timeout.store((int64_t)StkTime::getRealTimeMs() +
UserConfigParams::m_voting_timeout); (int64_t)(UserConfigParams::m_voting_timeout * 1000.0f));
} }
float remaining_time = m_timeout.load() - (float)StkTime::getRealTime(); int64_t remaining_time =
if (remaining_time < 0.0f) m_timeout.load() - (int64_t)StkTime::getRealTimeMs();
if (remaining_time < 0)
{ {
return; return;
} }
@ -1847,7 +1854,7 @@ void ServerLobby::finishedLoadingWorld()
void ServerLobby::finishedLoadingWorldClient(Event *event) void ServerLobby::finishedLoadingWorldClient(Event *event)
{ {
std::shared_ptr<STKPeer> peer = event->getPeerSP(); std::shared_ptr<STKPeer> peer = event->getPeerSP();
m_peers_ready.at(peer) = std::make_pair(true, StkTime::getRealTime()); m_peers_ready.at(peer) = true;
Log::info("ServerLobby", "Peer %d has finished loading world at %lf", Log::info("ServerLobby", "Peer %d has finished loading world at %lf",
peer->getHostId(), StkTime::getRealTime()); peer->getHostId(), StkTime::getRealTime());
} // finishedLoadingWorldClient } // finishedLoadingWorldClient
@ -1861,7 +1868,7 @@ void ServerLobby::playerFinishedResult(Event *event)
if (m_state.load() != RESULT_DISPLAY) if (m_state.load() != RESULT_DISPLAY)
return; return;
std::shared_ptr<STKPeer> peer = event->getPeerSP(); std::shared_ptr<STKPeer> peer = event->getPeerSP();
m_peers_ready.at(peer) = std::make_pair(true, StkTime::getRealTime()); m_peers_ready.at(peer) = true;
} // playerFinishedResult } // playerFinishedResult
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -2083,6 +2090,7 @@ void ServerLobby::configPeersStartTime()
int sleep_time = (int)(start_time - cur_time); int sleep_time = (int)(start_time - cur_time);
Log::info("ServerLobby", "Start game after %dms", sleep_time); Log::info("ServerLobby", "Start game after %dms", sleep_time);
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time)); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));
Log::info("ServerLobby", "Started at %lf", StkTime::getRealTime());
m_state.store(RACING); m_state.store(RACING);
}); });
} // configPeersStartTime } // configPeersStartTime

View File

@ -82,7 +82,7 @@ private:
std::atomic_bool m_server_has_loaded_world; std::atomic_bool m_server_has_loaded_world;
/** Counts how many peers have finished loading the world. */ /** Counts how many peers have finished loading the world. */
std::map<std::weak_ptr<STKPeer>, std::pair<bool, double>, std::map<std::weak_ptr<STKPeer>, bool,
std::owner_less<std::weak_ptr<STKPeer> > > m_peers_ready; std::owner_less<std::weak_ptr<STKPeer> > > m_peers_ready;
/** Vote from each peer. */ /** Vote from each peer. */
@ -95,7 +95,7 @@ private:
std::weak_ptr<bool> m_server_unregistered; std::weak_ptr<bool> m_server_unregistered;
/** Timeout counter for various state. */ /** Timeout counter for various state. */
std::atomic<float> m_timeout; std::atomic<int64_t> m_timeout;
/** Lock this mutex whenever a client is connect / disconnect or /** Lock this mutex whenever a client is connect / disconnect or
* starting race. */ * starting race. */
@ -160,7 +160,7 @@ private:
{ {
if (p.first.expired()) if (p.first.expired())
continue; continue;
all_ready = all_ready && p.second.first; all_ready = all_ready && p.second;
if (!all_ready) if (!all_ready)
return false; return false;
} }
@ -176,8 +176,7 @@ private:
} }
else else
{ {
it->second.first = false; it->second = false;
it->second.second = 0.0;
it++; it++;
} }
} }

View File

@ -41,7 +41,7 @@
# include <ifaddrs.h> # include <ifaddrs.h>
#endif #endif
#define SERVER_REFRESH_INTERVAL 5.0f const uint64_t SERVER_REFRESH_INTERVAL = 5000;
static ServersManager* g_manager_singleton(NULL); static ServersManager* g_manager_singleton(NULL);
@ -64,7 +64,7 @@ void ServersManager::deallocate()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
ServersManager::ServersManager() ServersManager::ServersManager()
{ {
m_last_load_time.store(0.0f); m_last_load_time.store(0);
m_list_updated = false; m_list_updated = false;
} // ServersManager } // ServersManager
@ -158,8 +158,8 @@ Online::XMLRequest* ServersManager::getLANRefreshRequest() const
char buffer[LEN]; char buffer[LEN];
// Wait for up to 0.5 seconds to receive an answer from // Wait for up to 0.5 seconds to receive an answer from
// any local servers. // any local servers.
double start_time = StkTime::getRealTime(); uint64_t start_time = StkTime::getRealTimeMs();
const double DURATION = 1.0; const uint64_t DURATION = 1000;
const auto& servers = ServersManager::get()->getServers(); const auto& servers = ServersManager::get()->getServers();
int cur_server_id = (int)servers.size(); int cur_server_id = (int)servers.size();
assert(cur_server_id == 0); assert(cur_server_id == 0);
@ -169,7 +169,7 @@ Online::XMLRequest* ServersManager::getLANRefreshRequest() const
// because e.g. a local client would answer as 127.0.0.1 and // because e.g. a local client would answer as 127.0.0.1 and
// 192.168.**. // 192.168.**.
std::map<irr::core::stringw, std::shared_ptr<Server> > servers_now; std::map<irr::core::stringw, std::shared_ptr<Server> > servers_now;
while (StkTime::getRealTime() - start_time < DURATION) while (StkTime::getRealTimeMs() - start_time < DURATION)
{ {
TransportAddress sender; TransportAddress sender;
int len = broadcast->receiveRawPacket(buffer, LEN, &sender, 1); int len = broadcast->receiveRawPacket(buffer, LEN, &sender, 1);
@ -236,7 +236,7 @@ void ServersManager::setLanServers(const std::map<irr::core::stringw,
*/ */
bool ServersManager::refresh(bool full_refresh) bool ServersManager::refresh(bool full_refresh)
{ {
if (StkTime::getRealTime() - m_last_load_time.load() if (StkTime::getRealTimeMs() - m_last_load_time.load()
< SERVER_REFRESH_INTERVAL) < SERVER_REFRESH_INTERVAL)
{ {
// Avoid too frequent refreshing // Avoid too frequent refreshing
@ -292,7 +292,7 @@ void ServersManager::setWanServers(bool success, const XMLNode* input)
m_servers.emplace_back( m_servers.emplace_back(
std::make_shared<Server>(*servers_xml->getNode(i))); std::make_shared<Server>(*servers_xml->getNode(i)));
} }
m_last_load_time.store((float)StkTime::getRealTime()); m_last_load_time.store(StkTime::getRealTimeMs());
m_list_updated = true; m_list_updated = true;
} // refresh } // refresh

View File

@ -45,7 +45,7 @@ private:
/** List of broadcast addresses to use. */ /** List of broadcast addresses to use. */
std::vector<TransportAddress> m_broadcast_address; std::vector<TransportAddress> m_broadcast_address;
std::atomic<float> m_last_load_time; std::atomic<uint64_t> m_last_load_time;
std::atomic_bool m_list_updated; std::atomic_bool m_list_updated;
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------

View File

@ -307,7 +307,7 @@ void STKHost::init()
m_shutdown = false; m_shutdown = false;
m_authorised = false; m_authorised = false;
m_network = NULL; m_network = NULL;
m_exit_timeout.store(std::numeric_limits<double>::max()); m_exit_timeout.store(std::numeric_limits<uint64_t>::max());
m_client_ping.store(0); m_client_ping.store(0);
// Start with initialising ENet // Start with initialising ENet
@ -440,7 +440,7 @@ void STKHost::setPublicAddress()
} }
m_network->sendRawPacket(s, m_stun_address); m_network->sendRawPacket(s, m_stun_address);
double ping = StkTime::getRealTime(); uint64_t ping = StkTime::getRealTimeMs();
freeaddrinfo(res); freeaddrinfo(res);
// Recieve now // Recieve now
@ -448,7 +448,7 @@ void STKHost::setPublicAddress()
const int LEN = 2048; const int LEN = 2048;
char buffer[LEN]; char buffer[LEN];
int len = m_network->receiveRawPacket(buffer, LEN, &sender, 2000); int len = m_network->receiveRawPacket(buffer, LEN, &sender, 2000);
ping = StkTime::getRealTime() - ping; ping = StkTime::getRealTimeMs() - ping;
if (sender.getIP() != m_stun_address.getIP()) if (sender.getIP() != m_stun_address.getIP())
{ {
@ -587,8 +587,7 @@ void STKHost::setPublicAddress()
m_public_address = non_xor_addr; m_public_address = non_xor_addr;
} }
// Succeed, save ping // Succeed, save ping
UserConfigParams::m_stun_list[server_name] = UserConfigParams::m_stun_list[server_name] = (uint32_t)(ping);
(uint32_t)(ping * 1000.0);
untried_server.clear(); untried_server.clear();
} }
} }
@ -620,7 +619,7 @@ void STKHost::disconnectAllPeers(bool timeout_waiting)
for (auto peer : m_peers) for (auto peer : m_peers)
peer.second->disconnect(); peer.second->disconnect();
// Wait for at most 2 seconds for disconnect event to be generated // Wait for at most 2 seconds for disconnect event to be generated
m_exit_timeout.store(StkTime::getRealTime() + 2.0); m_exit_timeout.store(StkTime::getRealTimeMs() + 2000);
} }
m_peers.clear(); m_peers.clear();
} // disconnectAllPeers } // disconnectAllPeers
@ -667,7 +666,7 @@ bool STKHost::connect(const TransportAddress& address)
*/ */
void STKHost::startListening() void STKHost::startListening()
{ {
m_exit_timeout.store(std::numeric_limits<double>::max()); m_exit_timeout.store(std::numeric_limits<uint64_t>::max());
m_listening_thread = std::thread(std::bind(&STKHost::mainLoop, this)); m_listening_thread = std::thread(std::bind(&STKHost::mainLoop, this));
} // startListening } // startListening
@ -677,7 +676,7 @@ void STKHost::startListening()
*/ */
void STKHost::stopListening() void STKHost::stopListening()
{ {
if (m_exit_timeout.load() == std::numeric_limits<double>::max()) if (m_exit_timeout.load() == std::numeric_limits<uint64_t>::max())
m_exit_timeout.store(0.0); m_exit_timeout.store(0.0);
if (m_listening_thread.joinable()) if (m_listening_thread.joinable())
m_listening_thread.join(); m_listening_thread.join();
@ -716,9 +715,9 @@ void STKHost::mainLoop()
} }
} }
double last_ping_time = StkTime::getRealTime(); uint64_t last_ping_time = StkTime::getRealTimeMs();
double last_ping_time_update_for_client = StkTime::getRealTime(); uint64_t last_ping_time_update_for_client = StkTime::getRealTimeMs();
while (m_exit_timeout.load() > StkTime::getRealTime()) while (m_exit_timeout.load() > StkTime::getRealTimeMs())
{ {
auto sl = LobbyProtocol::get<ServerLobby>(); auto sl = LobbyProtocol::get<ServerLobby>();
if (direct_socket && sl && sl->waitingForPlayers()) if (direct_socket && sl && sl->waitingForPlayers())
@ -740,12 +739,13 @@ void STKHost::mainLoop()
const float timeout = UserConfigParams::m_validation_timeout; const float timeout = UserConfigParams::m_validation_timeout;
bool need_ping = false; bool need_ping = false;
if (sl && !sl->isRacing() && if (sl && !sl->isRacing() &&
last_ping_time < StkTime::getRealTime()) last_ping_time < StkTime::getRealTimeMs())
{ {
// If not racing, send an reliable packet at the same rate with // If not racing, send an reliable packet at the same rate with
// state exchange to keep enet ping accurate // state exchange to keep enet ping accurate
last_ping_time = StkTime::getRealTime() + last_ping_time = StkTime::getRealTimeMs() +
1.0 / double(stk_config->m_network_state_frequeny); (uint64_t)((1.0f /
(float)(stk_config->m_network_state_frequeny)) * 1000.0f);
need_ping = true; need_ping = true;
} }
@ -793,8 +793,7 @@ void STKHost::mainLoop()
// Remove peer which has not been validated after a specific time // Remove peer which has not been validated after a specific time
// It is validated when the first connection request has finished // It is validated when the first connection request has finished
if (!it->second->isValidated() && if (!it->second->isValidated() &&
(float)StkTime::getRealTime() > it->second->getConnectedTime() > timeout)
it->second->getConnectedTime() + timeout)
{ {
Log::info("STKHost", "%s has not been validated for more" Log::info("STKHost", "%s has not been validated for more"
" than %f seconds, disconnect it by force.", " than %f seconds, disconnect it by force.",
@ -843,10 +842,10 @@ void STKHost::mainLoop()
while (enet_host_service(host, &event, 10) != 0) while (enet_host_service(host, &event, 10) != 0)
{ {
if (!is_server && if (!is_server &&
last_ping_time_update_for_client < StkTime::getRealTime()) last_ping_time_update_for_client < StkTime::getRealTimeMs())
{ {
last_ping_time_update_for_client = last_ping_time_update_for_client =
StkTime::getRealTime() + 2.0; StkTime::getRealTimeMs() + 2000;
auto lp = LobbyProtocol::get<LobbyProtocol>(); auto lp = LobbyProtocol::get<LobbyProtocol>();
if (lp && lp->isRacing()) if (lp && lp->isRacing())
{ {
@ -886,9 +885,9 @@ void STKHost::mainLoop()
// If used a timeout waiting disconnect, exit now // If used a timeout waiting disconnect, exit now
if (m_exit_timeout.load() != if (m_exit_timeout.load() !=
std::numeric_limits<double>::max()) std::numeric_limits<uint64_t>::max())
{ {
m_exit_timeout.store(0.0); m_exit_timeout.store(0);
break; break;
} }
// Use the previous stk peer so protocol can see the network // Use the previous stk peer so protocol can see the network
@ -981,7 +980,7 @@ void STKHost::mainLoop()
else else
delete stk_event; delete stk_event;
} // while enet_host_service } // while enet_host_service
} // while m_exit_timeout.load() > StkTime::getRealTime() } // while m_exit_timeout.load() > StkTime::getRealTimeMs()
delete direct_socket; delete direct_socket;
Log::info("STKHost", "Listening has been stopped."); Log::info("STKHost", "Listening has been stopped.");
} // mainLoop } // mainLoop

View File

@ -120,7 +120,7 @@ private:
std::atomic_bool m_authorised; std::atomic_bool m_authorised;
/** Use as a timeout to waiting a disconnect event when exiting. */ /** Use as a timeout to waiting a disconnect event when exiting. */
std::atomic<double> m_exit_timeout; std::atomic<uint64_t> m_exit_timeout;
/** An error message, which is set by a protocol to be displayed /** An error message, which is set by a protocol to be displayed
* in the GUI. */ * in the GUI. */

View File

@ -37,7 +37,7 @@ STKPeer::STKPeer(ENetPeer *enet_peer, STKHost* host, uint32_t host_id)
{ {
m_enet_peer = enet_peer; m_enet_peer = enet_peer;
m_host_id = host_id; m_host_id = host_id;
m_connected_time = (float)StkTime::getRealTime(); m_connected_time = StkTime::getRealTimeMs();
m_validated.store(false); m_validated.store(false);
m_average_ping.store(0); m_average_ping.store(0);
} // STKPeer } // STKPeer
@ -114,7 +114,7 @@ void STKPeer::sendPacket(NetworkString *data, bool reliable, bool encrypted)
{ {
if (Network::m_connection_debug) if (Network::m_connection_debug)
{ {
Log::verbose("STKPeer", "sending packet of size %d to %s at %f", Log::verbose("STKPeer", "sending packet of size %d to %s at %lf",
packet->dataLength, a.toString().c_str(), packet->dataLength, a.toString().c_str(),
StkTime::getRealTime()); StkTime::getRealTime());
} }
@ -155,7 +155,7 @@ bool STKPeer::isSamePeer(const ENetPeer* peer) const
*/ */
uint32_t STKPeer::getPing() uint32_t STKPeer::getPing()
{ {
if ((float)StkTime::getRealTime() - m_connected_time < 3.0f) if (getConnectedTime() < 3.0f)
return 0; return 0;
if (NetworkConfig::get()->isServer()) if (NetworkConfig::get()->isServer())
{ {

View File

@ -25,6 +25,7 @@
#include "network/transport_address.hpp" #include "network/transport_address.hpp"
#include "utils/no_copy.hpp" #include "utils/no_copy.hpp"
#include "utils/time.hpp"
#include "utils/types.hpp" #include "utils/types.hpp"
#include <enet/enet.h> #include <enet/enet.h>
@ -72,7 +73,7 @@ protected:
std::vector<std::shared_ptr<NetworkPlayerProfile> > m_players; std::vector<std::shared_ptr<NetworkPlayerProfile> > m_players;
float m_connected_time; uint64_t m_connected_time;
/** Available karts and tracks from this peer */ /** Available karts and tracks from this peer */
std::pair<std::set<std::string>, std::set<std::string> > m_available_kts; std::pair<std::set<std::string>, std::set<std::string> > m_available_kts;
@ -120,7 +121,8 @@ public:
/** Returns the host id of this peer. */ /** Returns the host id of this peer. */
uint32_t getHostId() const { return m_host_id; } uint32_t getHostId() const { return m_host_id; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
float getConnectedTime() const { return m_connected_time; } float getConnectedTime() const
{ return float(StkTime::getRealTimeMs() - m_connected_time) / 1000.0f; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setAvailableKartsTracks(std::set<std::string>& k, void setAvailableKartsTracks(std::set<std::string>& k,
std::set<std::string>& t) std::set<std::string>& t)

View File

@ -165,12 +165,12 @@ GUIEngine::EventPropagation
} }
else if (selection == m_refresh_widget->m_properties[PROP_ID]) else if (selection == m_refresh_widget->m_properties[PROP_ID])
{ {
static double timer = StkTime::getRealTime(); static uint64_t timer = StkTime::getRealTimeMs();
// 1 minute per refresh // 1 minute per refresh
if (StkTime::getRealTime() < timer + 60.0) if (StkTime::getRealTimeMs() < timer + 60000)
return GUIEngine::EVENT_BLOCK; return GUIEngine::EVENT_BLOCK;
timer = StkTime::getRealTime(); timer = StkTime::getRealTimeMs();
*m_fetched_ranking = false; *m_fetched_ranking = false;
updatePlayerRanking(m_name, m_online_id, m_ranking_info, updatePlayerRanking(m_name, m_online_id, m_ranking_info,
m_fetched_ranking); m_fetched_ranking);

View File

@ -135,7 +135,7 @@ bool TracksScreen::onEscapePressed()
void TracksScreen::tearDown() void TracksScreen::tearDown()
{ {
m_network_tracks = false; m_network_tracks = false;
m_vote_timeout = -1.0f; m_vote_timeout = std::numeric_limits<uint64_t>::max();
m_selected_track = NULL; m_selected_track = NULL;
} // tearDown } // tearDown
@ -418,9 +418,9 @@ void TracksScreen::setFocusOnTrack(const std::string& trackName)
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TracksScreen::setVoteTimeout(float timeout) void TracksScreen::setVoteTimeout(float timeout)
{ {
if (m_vote_timeout != -1.0f) if (m_vote_timeout != std::numeric_limits<uint64_t>::max())
return; return;
m_vote_timeout = (float)StkTime::getRealTime() + timeout; m_vote_timeout = StkTime::getRealTimeMs() + (uint64_t)(timeout * 1000.0f);
} // setVoteTimeout } // setVoteTimeout
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -451,14 +451,14 @@ void TracksScreen::voteForPlayer()
void TracksScreen::onUpdate(float dt) void TracksScreen::onUpdate(float dt)
{ {
assert(m_votes); assert(m_votes);
if (m_vote_timeout == -1.0f) if (m_vote_timeout == std::numeric_limits<uint64_t>::max())
{ {
m_votes->setText(L"", false); m_votes->setText(L"", false);
return; return;
} }
m_votes->setVisible(true); m_votes->setVisible(true);
int remaining_time = (int)(m_vote_timeout - StkTime::getRealTime()); int remaining_time = (m_vote_timeout - StkTime::getRealTimeMs()) / 1000;
if (remaining_time < 0) if (remaining_time < 0)
remaining_time = 0; remaining_time = 0;
//I18N: In tracks screen, about voting of tracks in network //I18N: In tracks screen, about voting of tracks in network

View File

@ -21,6 +21,7 @@
#include "guiengine/screen.hpp" #include "guiengine/screen.hpp"
#include "utils/synchronised.hpp" #include "utils/synchronised.hpp"
#include <deque> #include <deque>
#include <limits>
#include <map> #include <map>
#include <string> #include <string>
@ -58,7 +59,7 @@ private:
int m_bottom_box_height = -1; int m_bottom_box_height = -1;
float m_vote_timeout = -1.0f; uint64_t m_vote_timeout = std::numeric_limits<uint64_t>::max();
std::map<std::string, core::stringw> m_vote_messages; std::map<std::string, core::stringw> m_vote_messages;
@ -101,7 +102,7 @@ public:
void resetVote() void resetVote()
{ {
m_vote_messages.clear(); m_vote_messages.clear();
m_vote_timeout = -1.0f; m_vote_timeout = std::numeric_limits<uint64_t>::max();
} }
void setVoteTimeout(float timeout); void setVoteTimeout(float timeout);