Use ServerConfig for setup server

This commit is contained in:
Benau 2018-09-11 14:06:30 +08:00
parent 0d93fe427e
commit dd15947aa1
21 changed files with 732 additions and 597 deletions

View File

@ -63,7 +63,7 @@ UserConfigParam::~UserConfigParam()
* \param stream the xml writer. * \param stream the xml writer.
* \param level determines indentation level. * \param level determines indentation level.
*/ */
void UserConfigParam::writeInner(std::ofstream& stream, int level) const void UserConfigParam::writeInner(std::stringstream& stream, int level) const
{ {
std::string tab(level * 4,' '); std::string tab(level * 4,' ');
stream << " " << tab.c_str() << m_param_name.c_str() << "=\"" stream << " " << tab.c_str() << m_param_name.c_str() << "=\""
@ -90,7 +90,7 @@ GroupUserConfigParam::GroupUserConfigParam(const char* group_name,
} // GroupUserConfigParam } // GroupUserConfigParam
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void GroupUserConfigParam::write(std::ofstream& stream) const void GroupUserConfigParam::write(std::stringstream& stream) const
{ {
const int attr_amount = (int)m_attributes.size(); const int attr_amount = (int)m_attributes.size();
@ -120,7 +120,7 @@ void GroupUserConfigParam::write(std::ofstream& stream) const
} // write } // write
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void GroupUserConfigParam::writeInner(std::ofstream& stream, int level) const void GroupUserConfigParam::writeInner(std::stringstream& stream, int level) const
{ {
std::string tab(level * 4,' '); std::string tab(level * 4,' ');
for(int i = 0; i < level; i++) tab =+ " "; for(int i = 0; i < level; i++) tab =+ " ";
@ -220,7 +220,7 @@ MapUserConfigParam<T, U>::MapUserConfigParam(const char* param_name,
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
template<typename T, typename U> template<typename T, typename U>
void MapUserConfigParam<T, U>::write(std::ofstream& stream) const void MapUserConfigParam<T, U>::write(std::stringstream& stream) const
{ {
// comment // comment
if (m_comment.size() > 0) stream << " <!-- " << m_comment.c_str(); if (m_comment.size() > 0) stream << " <!-- " << m_comment.c_str();
@ -293,7 +293,7 @@ IntUserConfigParam::IntUserConfigParam(int default_value,
} // IntUserConfigParam } // IntUserConfigParam
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void IntUserConfigParam::write(std::ofstream& stream) const void IntUserConfigParam::write(std::stringstream& stream) const
{ {
if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str() if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str()
<< " -->\n"; << " -->\n";
@ -356,11 +356,11 @@ TimeUserConfigParam::TimeUserConfigParam(StkTime::TimeType default_value,
} // TimeUserConfigParam } // TimeUserConfigParam
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void TimeUserConfigParam::write(std::ofstream& stream) const void TimeUserConfigParam::write(std::stringstream& stream) const
{ {
if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str() if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str()
<< " -->\n"; << " -->\n";
std::ostringstream o; std::stringstream o;
o<<m_value; o<<m_value;
stream << " <" << m_param_name.c_str() << " value=\"" stream << " <" << m_param_name.c_str() << " value=\""
<< o.str().c_str() << "\" />\n\n"; << o.str().c_str() << "\" />\n\n";
@ -373,7 +373,7 @@ irr::core::stringc TimeUserConfigParam::toString() const
// we can't use an irrlicht's stringw directly. Since it's only a // we can't use an irrlicht's stringw directly. Since it's only a
// number, we can use std::string, and convert to stringw // number, we can use std::string, and convert to stringw
std::ostringstream o; std::stringstream o;
o<<m_value; o<<m_value;
return o.str().c_str(); return o.str().c_str();
} // toString } // toString
@ -427,7 +427,7 @@ StringUserConfigParam::StringUserConfigParam(const char* default_value,
} // StringUserConfigParam } // StringUserConfigParam
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void StringUserConfigParam::write(std::ofstream& stream) const void StringUserConfigParam::write(std::stringstream& stream) const
{ {
if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str() if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str()
<< " -->\n"; << " -->\n";
@ -479,7 +479,7 @@ BoolUserConfigParam::BoolUserConfigParam(bool default_value,
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void BoolUserConfigParam::write(std::ofstream& stream) const void BoolUserConfigParam::write(std::stringstream& stream) const
{ {
if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str() if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str()
<< " -->\n"; << " -->\n";
@ -564,7 +564,7 @@ FloatUserConfigParam::FloatUserConfigParam(float default_value,
} // FloatUserConfigParam } // FloatUserConfigParam
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void FloatUserConfigParam::write(std::ofstream& stream) const void FloatUserConfigParam::write(std::stringstream& stream) const
{ {
if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str() if(m_comment.size() > 0) stream << " <!-- " << m_comment.c_str()
<< " -->\n"; << " -->\n";
@ -661,8 +661,7 @@ bool UserConfig::loadConfig()
// ---- Read parameters values (all parameter objects must have been created before this point if // ---- Read parameters values (all parameter objects must have been created before this point if
// you want them automatically read from the config file) // you want them automatically read from the config file)
const int paramAmount = all_params.size(); for (unsigned i = 0; i < all_params.size(); i++)
for(int i=0; i<paramAmount; i++)
{ {
all_params[i]->findYourDataInAChildOf(root); all_params[i]->findYourDataInAChildOf(root);
} }
@ -688,29 +687,27 @@ bool UserConfig::loadConfig()
void UserConfig::saveConfig() void UserConfig::saveConfig()
{ {
const std::string filename = file_manager->getUserConfigFile(m_filename); const std::string filename = file_manager->getUserConfigFile(m_filename);
std::stringstream ss;
ss << "<?xml version=\"1.0\"?>\n";
ss << "<stkconfig version=\"" << m_current_config_version
<< "\" >\n\n";
for (unsigned i = 0; i < all_params.size(); i++)
{
all_params[i]->write(ss);
}
ss << "</stkconfig>\n";
try try
{ {
std::ofstream configfile (filename.c_str(), std::ofstream::out); std::string s = ss.str();
std::ofstream configfile(filename.c_str(), std::ofstream::out);
configfile << "<?xml version=\"1.0\"?>\n"; configfile << ss.rdbuf();
configfile << "<stkconfig version=\"" << m_current_config_version
<< "\" >\n\n";
const int paramAmount = all_params.size();
for(int i=0; i<paramAmount; i++)
{
//Log::info("UserConfig", "Saving parameter %d to file", i);
all_params[i]->write(configfile);
}
configfile << "</stkconfig>\n";
configfile.close(); configfile.close();
} }
catch (std::runtime_error& e) catch (std::runtime_error& e)
{ {
Log::error("UserConfig::saveConfig", "Failed to write config to %s, because %s", Log::error("UserConfig::saveConfig", "Failed to write config to %s, "
filename.c_str(), e.what()); "because %s", filename.c_str(), e.what());
} }
} // saveConfig } // saveConfig

View File

@ -41,7 +41,7 @@
#include <string> #include <string>
#include <map> #include <map>
#include <vector> #include <vector>
#include <fstream> #include <sstream>
#include <irrString.h> #include <irrString.h>
using irr::core::stringc; using irr::core::stringc;
@ -69,8 +69,8 @@ protected:
std::string m_comment; std::string m_comment;
public: public:
virtual ~UserConfigParam(); virtual ~UserConfigParam();
virtual void write(std::ofstream & stream) const = 0; virtual void write(std::stringstream & stream) const = 0;
virtual void writeInner(std::ofstream & stream, int level = 0) const; virtual void writeInner(std::stringstream & stream, int level = 0) const;
virtual void findYourDataInAChildOf(const XMLNode* node) = 0; virtual void findYourDataInAChildOf(const XMLNode* node) = 0;
virtual void findYourDataInAnAttributeOf(const XMLNode* node) = 0; virtual void findYourDataInAnAttributeOf(const XMLNode* node) = 0;
virtual irr::core::stringc toString() const = 0; virtual irr::core::stringc toString() const = 0;
@ -86,8 +86,8 @@ public:
GroupUserConfigParam(const char* param_name, GroupUserConfigParam(const char* param_name,
GroupUserConfigParam* group, GroupUserConfigParam* group,
const char* comment = NULL); const char* comment = NULL);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void writeInner(std::ofstream& stream, int level = 0) const; void writeInner(std::stringstream& stream, int level = 0) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);
@ -124,7 +124,7 @@ public:
const char* comment, const char* comment,
std::map<T, U> default_value); std::map<T, U> default_value);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);
@ -186,7 +186,7 @@ public:
GroupUserConfigParam* group, GroupUserConfigParam* group,
const char* comment = NULL); const char* comment = NULL);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);
@ -213,7 +213,7 @@ public:
TimeUserConfigParam(StkTime::TimeType default_value, const char* param_name, TimeUserConfigParam(StkTime::TimeType default_value, const char* param_name,
GroupUserConfigParam* group, const char* comment=NULL); GroupUserConfigParam* group, const char* comment=NULL);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);
@ -242,12 +242,12 @@ protected:
public: public:
StringUserConfigParam(const char* default_value, const char* param_name, StringUserConfigParam(const char* default_value, const char* param_name,
const char* comment = NULL); const char* comment);
StringUserConfigParam(const char* default_value, const char* param_name, StringUserConfigParam(const char* default_value, const char* param_name,
GroupUserConfigParam* group, GroupUserConfigParam* group,
const char* comment = NULL); const char* comment = NULL);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);
@ -285,7 +285,7 @@ public:
BoolUserConfigParam(bool default_value, const char* param_name, BoolUserConfigParam(bool default_value, const char* param_name,
GroupUserConfigParam* group, GroupUserConfigParam* group,
const char* comment = NULL); const char* comment = NULL);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);
@ -318,7 +318,7 @@ public:
GroupUserConfigParam* group, GroupUserConfigParam* group,
const char* comment = NULL); const char* comment = NULL);
void write(std::ofstream& stream) const; void write(std::stringstream& stream) const;
void findYourDataInAChildOf(const XMLNode* node); void findYourDataInAChildOf(const XMLNode* node);
void findYourDataInAnAttributeOf(const XMLNode* node); void findYourDataInAnAttributeOf(const XMLNode* node);

View File

@ -216,7 +216,6 @@
#include "network/protocols/connect_to_server.hpp" #include "network/protocols/connect_to_server.hpp"
#include "network/protocols/client_lobby.hpp" #include "network/protocols/client_lobby.hpp"
#include "network/protocols/server_lobby.hpp" #include "network/protocols/server_lobby.hpp"
#include "network/game_setup.hpp"
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "network/network_string.hpp" #include "network/network_string.hpp"
#include "network/rewind_manager.hpp" #include "network/rewind_manager.hpp"
@ -561,11 +560,11 @@ void cmdLineHelp()
" --ai=a,b,... Use the karts a, b, ... for the AI, and additional player kart.\n" " --ai=a,b,... Use the karts a, b, ... for the AI, and additional player kart.\n"
" --aiNP=a,b,... Use the karts a, b, ... for the AI, no additional player kart.\n" " --aiNP=a,b,... Use the karts a, b, ... for the AI, no additional player kart.\n"
" --laps=N Define number of laps to N.\n" " --laps=N Define number of laps to N.\n"
" --mode=N N=1 Beginner, N=2 Intermediate, N=3 Expert, N=4 SuperTux.\n" " --mode=N N=0 Normal, N=1 Time trial, N=2 Battle, N=3 Soccer,\n"
" --type=N N=0 Normal, N=1 Time trial, N=2 Battle, N=3 Soccer,\n"
" N=4 Follow The Leader. In configure server use --battle-mode=n\n" " N=4 Follow The Leader. In configure server use --battle-mode=n\n"
" for battle server and --soccer-timed / goals for soccer server\n" " for battle server and --soccer-timed / goals for soccer server\n"
" to control verbosely, see below:\n" " to control verbosely, see below:\n"
" --difficulty=N N=0 Beginner, N=1 Intermediate, N=2 Expert, N=3 SuperTux.\n"
" --battle-mode=n Specify battle mode in netowrk, 0 is Free-For-All and\n" " --battle-mode=n Specify battle mode in netowrk, 0 is Free-For-All and\n"
" 1 is Capture The Flag.\n" " 1 is Capture The Flag.\n"
" --soccer-timed Use time limit mode in network soccer game.\n" " --soccer-timed Use time limit mode in network soccer game.\n"
@ -598,6 +597,8 @@ void cmdLineHelp()
// " // "
// " --disable-item-collection Disable item collection. Useful for\n" // " --disable-item-collection Disable item collection. Useful for\n"
// " debugging client/server item management.\n" // " debugging client/server item management.\n"
" --server-config=file Specify the server_config.xml for server hosting, it will create\n"
" one if not found.\n"
" --network-console Enable network console.\n" " --network-console Enable network console.\n"
" --wan-server=name Start a Wan server (not a playing client).\n" " --wan-server=name Start a Wan server (not a playing client).\n"
" --public-server Allow direct connection to the server (without stk server)\n" " --public-server Allow direct connection to the server (without stk server)\n"
@ -613,14 +614,13 @@ void cmdLineHelp()
" --port=n Port number to use.\n" " --port=n Port number to use.\n"
" --auto-connect Automatically connect to fist server and start race\n" " --auto-connect Automatically connect to fist server and start race\n"
" --max-players=n Maximum number of clients (server only).\n" " --max-players=n Maximum number of clients (server only).\n"
" --min-players=n Minimum number of clients (server only).\n" " --min-players=n Minimum number of clients for owner less server(server only).\n"
" --motd Message showing in all lobby of clients, can specify a .txt file.\n" " --motd Message showing in all lobby of clients, can specify a .txt file.\n"
" --auto-end Automatically end network game after 1st player finished\n" " --auto-end Automatically end network game after 1st player finished\n"
" for some time (currently his finished time * 0.25 + 15.0). \n" " for some time (currently his finished time * 0.25 + 15.0). \n"
" --team-choosing Allow choosing team in lobby, implicitly allowed in lan or\n" " --no-team-choosing Disable choosing team in lobby for team game.\n"
" password protected server. This function cannot be used in\n"
" owner-less server.\n"
" --network-gp=n Specify number of tracks used in network grand prix.\n" " --network-gp=n Specify number of tracks used in network grand prix.\n"
" --graphical-server Enable graphical view in server.\n"
" --no-validation Allow non validated and unencrypted connection in wan.\n" " --no-validation Allow non validated and unencrypted connection in wan.\n"
" --ranked Server will submit ranking to stk addons server.\n" " --ranked Server will submit ranking to stk addons server.\n"
" You require permission for that.\n" " You require permission for that.\n"
@ -923,7 +923,7 @@ int handleCmdLinePreliminary()
/** Handles command line options. /** Handles command line options.
* \param argc Number of command line options * \param argc Number of command line options
*/ */
int handleCmdLine() int handleCmdLine(bool has_server_config)
{ {
// Some generic variables used in scanning: // Some generic variables used in scanning:
int n; int n;
@ -1021,36 +1021,6 @@ int handleCmdLine()
UserConfigParams::m_check_debug=true; UserConfigParams::m_check_debug=true;
} }
if (CommandLine::has( "--difficulty", &s))
{
int n = atoi(s.c_str());
if(n<0 || n>RaceManager::DIFFICULTY_LAST)
Log::warn("main", "Invalid difficulty '%s' - ignored.\n",
s.c_str());
else
race_manager->setDifficulty(RaceManager::Difficulty(n));
} // --mode
if (CommandLine::has("--type", &n))
{
switch (n)
{
// The order here makes server creation screen easier
case 0: race_manager->setMinorMode(RaceManager::MINOR_MODE_NORMAL_RACE);
break;
case 1: race_manager->setMinorMode(RaceManager::MINOR_MODE_TIME_TRIAL);
break;
case 2: race_manager->setMinorMode(RaceManager::MINOR_MODE_BATTLE);
break;
case 3: race_manager->setMinorMode(RaceManager::MINOR_MODE_SOCCER);
break;
case 4: race_manager->setMinorMode(RaceManager::MINOR_MODE_FOLLOW_LEADER);
break;
default:
Log::warn("main", "Invalid race type '%d' - ignored.", n);
}
} // --type
bool init_user = CommandLine::has("--init-user"); bool init_user = CommandLine::has("--init-user");
if (init_user) if (init_user)
{ {
@ -1093,9 +1063,117 @@ int handleCmdLine()
can_wan = true; can_wan = true;
} }
// Networking command lines if (CommandLine::has( "--difficulty", &s))
if(CommandLine::has("--network-console")) {
int n = atoi(s.c_str());
if (n < 0 || n > RaceManager::DIFFICULTY_LAST)
{
Log::warn("main", "Invalid difficulty '%s', use easy.\n",
s.c_str());
race_manager->setDifficulty(RaceManager::Difficulty(0));
ServerConfig::m_server_difficulty = 0;
}
else
{
race_manager->setDifficulty(RaceManager::Difficulty(n));
ServerConfig::m_server_difficulty = n;
}
} // --difficulty
if (CommandLine::has("--mode", &n))
{
switch (n)
{
// The order here makes server creation screen easier
case 0:
{
ServerConfig::m_server_mode = 3;
race_manager->setMinorMode(RaceManager::MINOR_MODE_NORMAL_RACE);
break;
}
case 1:
{
ServerConfig::m_server_mode = 4;
race_manager->setMinorMode(RaceManager::MINOR_MODE_TIME_TRIAL);
break;
}
case 2:
{
ServerConfig::m_server_mode = 7;
race_manager->setMinorMode(RaceManager::MINOR_MODE_BATTLE);
break;
}
case 3:
{
ServerConfig::m_server_mode = 6;
race_manager->setMinorMode(RaceManager::MINOR_MODE_SOCCER);
break;
}
case 4:
{
race_manager->setMinorMode(RaceManager::MINOR_MODE_FOLLOW_LEADER);
break;
}
default:
Log::warn("main", "Invalid race mode '%d' - ignored.", n);
}
} // --mode
const bool is_soccer =
race_manager->getMinorMode() == RaceManager::MINOR_MODE_SOCCER;
const bool is_battle =
race_manager->getMinorMode() == RaceManager::MINOR_MODE_BATTLE;
if (!has_server_config)
{
if (CommandLine::has("--soccer-timed") && is_soccer)
ServerConfig::m_soccer_goal_target = false;
else if (CommandLine::has("--soccer-goals") && is_soccer)
ServerConfig::m_soccer_goal_target = true;
else if (CommandLine::has("--network-gp", &n))
{
ServerConfig::m_gp_track_count = n;
if (ServerConfig::m_server_mode == 3)
ServerConfig::m_server_mode = 0;
else
ServerConfig::m_server_mode = 1;
}
else if (CommandLine::has("--battle-mode", &n) && is_battle)
{
switch (n)
{
case 0:
ServerConfig::m_server_mode = 7;
break;
case 1:
ServerConfig::m_server_mode = 8;
break;
default:
break;
}
}
else if (is_battle)
{
Log::warn("main", "Set to ffa for battle server");
ServerConfig::m_server_mode = 7;
}
else if (is_soccer)
{
Log::warn("main", "Set to goal target for soccer server");
ServerConfig::m_soccer_goal_target = true;
}
}
if (CommandLine::has("--network-console"))
{
ServerConfig::m_enable_console = true;
STKHost::m_enable_console = true; STKHost::m_enable_console = true;
}
else if (ServerConfig::m_enable_console &&
NetworkConfig::get()->isServer())
{
STKHost::m_enable_console = true;
}
if (CommandLine::has("--disable-item-collection")) if (CommandLine::has("--disable-item-collection"))
ItemManager::disableItemCollection(); ItemManager::disableItemCollection();
@ -1103,45 +1181,27 @@ int handleCmdLine()
std::string server_password; std::string server_password;
if (CommandLine::has("--server-password", &s)) if (CommandLine::has("--server-password", &s))
{ {
ServerConfig::m_private_server_password = s;
server_password = s; server_password = s;
NetworkConfig::get()->setPassword(server_password);
NetworkConfig::get()->setTeamChoosing(true);
} }
if (CommandLine::has("--motd", &s)) if (CommandLine::has("--motd", &s))
{ ServerConfig::m_motd = s;
core::stringw motd;
if (s.find(".txt") != std::string::npos) if (CommandLine::has("--no-team-choosing"))
{ ServerConfig::m_team_choosing = false;
std::ifstream message(s);
if (message.is_open())
{
for (std::string line; std::getline(message, line); )
{
motd += StringUtils::utf8ToWide(line).trim() + L"\n";
}
// Remove last newline
motd.erase(motd.size() - 1);
}
}
else
motd = StringUtils::xmlDecode(s);
NetworkConfig::get()->setMOTD(motd);
}
if (CommandLine::has("--ranked")) if (CommandLine::has("--ranked"))
{ {
NetworkConfig::get()->setValidatedPlayers(true); ServerConfig::m_ranked = true;
NetworkConfig::get()->setRankedServer(true);
NetworkConfig::get()->setOwnerLess(true);
NetworkConfig::get()->setAutoEnd(true);
} }
if (CommandLine::has("--auto-end")) if (CommandLine::has("--auto-end"))
{ {
NetworkConfig::get()->setAutoEnd(true); ServerConfig::m_auto_end = true;
} }
if (CommandLine::has("--owner-less")) if (CommandLine::has("--owner-less"))
{ {
NetworkConfig::get()->setOwnerLess(true); ServerConfig::m_owner_less = true;
} }
if (CommandLine::has("--connection-debug")) if (CommandLine::has("--connection-debug"))
{ {
@ -1160,12 +1220,10 @@ int handleCmdLine()
{ {
ServerConfig::m_server_max_players = n; ServerConfig::m_server_max_players = n;
} }
if (ServerConfig::m_server_max_players < 1) if (ServerConfig::m_server_max_players < 1)
{ {
ServerConfig::m_server_max_players = 1; ServerConfig::m_server_max_players = 1;
} }
NetworkConfig::get()->setMaxPlayers(ServerConfig::m_server_max_players);
if (CommandLine::has("--min-players", &n)) if (CommandLine::has("--min-players", &n))
{ {
@ -1179,17 +1237,12 @@ int handleCmdLine()
// We don't know if this instance is going to be a client // We don't know if this instance is going to be a client
// or server, so just set both ports, only one will be used anyway // or server, so just set both ports, only one will be used anyway
NetworkConfig::get()->setClientPort(n); NetworkConfig::get()->setClientPort(n);
NetworkConfig::get()->setServerPort(n); ServerConfig::m_server_port = n;
} }
if (CommandLine::has("--public-server")) if (CommandLine::has("--public-server"))
{ {
NetworkConfig::get()->setIsPublicServer(); NetworkConfig::get()->setIsPublicServer();
} }
if (CommandLine::has("--team-choosing"))
{
if (!NetworkConfig::get()->isOwnerLess())
NetworkConfig::get()->setTeamChoosing(true);
}
if (CommandLine::has("--connect-now", &s)) if (CommandLine::has("--connect-now", &s))
{ {
TransportAddress server_addr(s); TransportAddress server_addr(s);
@ -1220,15 +1273,18 @@ int handleCmdLine()
} }
} }
std::shared_ptr<LobbyProtocol> server_lobby; if (NetworkConfig::get()->isServer())
if (CommandLine::has("--wan-server", &s)) {
const std::string& server_name = ServerConfig::m_server_name;
if (ServerConfig::m_wan_server)
{ {
// Try to use saved user token if exists
PlayerProfile* player = PlayerManager::getCurrentPlayer(); PlayerProfile* player = PlayerManager::getCurrentPlayer();
// Try to use saved user token if exists
if (!can_wan && player && player->wasOnlineLastTime() && if (!can_wan && player && player->wasOnlineLastTime() &&
player->wasOnlineLastTime() && player->hasSavedSession()) player->wasOnlineLastTime() && player->hasSavedSession())
{ {
while (PlayerManager::getCurrentOnlineState() != PlayerProfile::OS_SIGNED_IN) while (PlayerManager::getCurrentOnlineState() !=
PlayerProfile::OS_SIGNED_IN)
{ {
Online::RequestManager::get()->update(0.0f); Online::RequestManager::get()->update(0.0f);
StkTime::sleep(1); StkTime::sleep(1);
@ -1237,127 +1293,32 @@ int handleCmdLine()
} }
else if (!can_wan) else if (!can_wan)
{ {
Log::warn("main", "No saved online player session to create a wan server"); Log::warn("main",
"No saved online player session to create a wan server");
} }
if (can_wan) if (can_wan)
{ {
NetworkConfig::get()->setServerName(StringUtils::xmlDecode(s));
NetworkConfig::get()->setIsServer(true);
NetworkConfig::get()->setIsWAN(); NetworkConfig::get()->setIsWAN();
NetworkConfig::get()->setIsPublicServer(); NetworkConfig::get()->setIsPublicServer();
if (CommandLine::has("--no-validation")) ServerConfig::loadServerLobbyFromConfig();
{ Log::info("main", "Creating a WAN server '%s'.",
NetworkConfig::get()->setValidatedPlayers(false); server_name.c_str());
}
} }
else else
{ {
NetworkConfig::get()->setValidatedPlayers(true);
}
server_lobby = STKHost::create();
Log::info("main", "Creating a WAN server '%s'.", s.c_str());
}
}
else if (CommandLine::has("--lan-server", &s))
{
NetworkConfig::get()->setServerName(StringUtils::xmlDecode(s));
NetworkConfig::get()->setIsServer(true);
NetworkConfig::get()->setIsLAN(); NetworkConfig::get()->setIsLAN();
NetworkConfig::get()->setTeamChoosing(true); ServerConfig::loadServerLobbyFromConfig();
NetworkConfig::get()->setValidatedPlayers(false); Log::info("main", "Creating a LAN server '%s'.",
server_lobby = STKHost::create(); server_name.c_str());
Log::info("main", "Creating a LAN server '%s'.", s.c_str());
} }
}
if (CommandLine::has("--auto-connect")) if (CommandLine::has("--auto-connect"))
{ {
NetworkConfig::get()->setAutoConnect(true); NetworkConfig::get()->setAutoConnect(true);
} }
const bool is_soccer =
race_manager->getMinorMode() == RaceManager::MINOR_MODE_SOCCER;
const bool is_battle =
race_manager->getMinorMode() == RaceManager::MINOR_MODE_BATTLE;
if (CommandLine::has("--soccer-timed") && is_soccer)
{
LobbyProtocol::get<LobbyProtocol>()->getGameSetup()
->setSoccerGoalTarget(false);
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_SINGLE);
}
else if (CommandLine::has("--soccer-goals") && is_soccer)
{
LobbyProtocol::get<LobbyProtocol>()->getGameSetup()
->setSoccerGoalTarget(true);
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_SINGLE);
}
else if (CommandLine::has("--network-gp", &n))
{
LobbyProtocol::get<LobbyProtocol>()->getGameSetup()
->setGrandPrixTrack(n);
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_GRAND_PRIX);
}
else if (CommandLine::has("--battle-mode", &n) && is_battle)
{
switch (n)
{
case 0:
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_FREE_FOR_ALL);
race_manager->setMajorMode(RaceManager::MAJOR_MODE_FREE_FOR_ALL);
break;
case 1:
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_CAPTURE_THE_FLAG);
race_manager->setMajorMode(RaceManager::MAJOR_MODE_CAPTURE_THE_FLAG);
break;
default:
break;
}
}
else if (is_battle)
{
Log::warn("main", "Set to ffa for battle server");
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_FREE_FOR_ALL);
race_manager->setMajorMode(RaceManager::MAJOR_MODE_FREE_FOR_ALL);
}
else if (is_soccer)
{
Log::warn("main", "Set to goal target for soccer server");
LobbyProtocol::get<LobbyProtocol>()->getGameSetup()
->setSoccerGoalTarget(true);
NetworkConfig::get()->setServerMode(race_manager->getMinorMode(),
RaceManager::MAJOR_MODE_SINGLE);
}
else
{
NetworkConfig::get()->setServerMode(
race_manager->getMinorMode(), RaceManager::MAJOR_MODE_SINGLE);
}
if (is_battle)
{
if (ServerConfig::m_hit_limit_threshold < 0.0f &&
ServerConfig::m_time_limit_threshold_ffa < 0.0f)
{
Log::warn("main", "Reset invalid hit and time limit settings");
ServerConfig::m_hit_limit_threshold.revertToDefaults();
ServerConfig::m_time_limit_threshold_ffa.revertToDefaults();
}
if (ServerConfig::m_capture_limit_threshold < 0.0f &&
ServerConfig::m_time_limit_threshold_ctf < 0.0f)
{
Log::warn("main", "Reset invalid Capture and time limit settings");
ServerConfig::m_capture_limit_threshold.revertToDefaults();
ServerConfig::m_time_limit_threshold_ctf.revertToDefaults();
}
}
// The extra server info has to be set before server lobby started
if (server_lobby)
server_lobby->requestStart();
// Race parameters // Race parameters
if(CommandLine::has("--kartsize-debug")) if(CommandLine::has("--kartsize-debug"))
{ {
@ -1417,16 +1378,6 @@ int handleCmdLine()
race_manager->setNumKarts((int)l.size()); race_manager->setNumKarts((int)l.size());
} // --aiNP } // --aiNP
if(CommandLine::has( "--mode", &s) || CommandLine::has( "--difficulty", &s))
{
int n = atoi(s.c_str());
if(n<0 || n>RaceManager::DIFFICULTY_LAST)
Log::warn("main", "Invalid difficulty '%s' - ignored.\n",
s.c_str());
else
race_manager->setDifficulty(RaceManager::Difficulty(n));
} // --mode
if(CommandLine::has("--track", &s) || CommandLine::has("-t", &s)) if(CommandLine::has("--track", &s) || CommandLine::has("-t", &s))
{ {
race_manager->setTrack(s); race_manager->setTrack(s);
@ -1868,6 +1819,49 @@ int main(int argc, char *argv[] )
handleCmdLinePreliminary(); handleCmdLinePreliminary();
bool has_server_config = false;
bool no_graphics = !CommandLine::has("--graphical-server");
// Load current server config first, if any option is specified than
// override it later
// Disable sound if found server-config or wan/lan server name
if (CommandLine::has("--server-config", &s))
{
if (no_graphics)
{
ProfileWorld::disableGraphics();
UserConfigParams::m_enable_sound = false;
}
has_server_config = true;
ServerConfig::loadServerConfig(s);
NetworkConfig::get()->setIsServer(true);
}
else
ServerConfig::loadServerConfig();
if (CommandLine::has("--wan-server", &s))
{
if (no_graphics)
{
ProfileWorld::disableGraphics();
UserConfigParams::m_enable_sound = false;
}
NetworkConfig::get()->setIsServer(true);
ServerConfig::m_server_name = s;
ServerConfig::m_wan_server = true;
if (CommandLine::has("--no-validation"))
ServerConfig::m_validating_player = false;
else
ServerConfig::m_validating_player = true;
}
else if (CommandLine::has("--lan-server", &s))
{
ProfileWorld::disableGraphics();
UserConfigParams::m_enable_sound = false;
NetworkConfig::get()->setIsServer(true);
ServerConfig::m_server_name = s;
ServerConfig::m_wan_server = false;
ServerConfig::m_validating_player = false;
}
initRest(); initRest();
input_manager = new InputManager (); input_manager = new InputManager ();
@ -1938,7 +1932,7 @@ int main(int argc, char *argv[] )
"banana.png") ); "banana.png") );
//handleCmdLine() needs InitTuxkart() so it can't be called first //handleCmdLine() needs InitTuxkart() so it can't be called first
if(!handleCmdLine()) exit(0); if(!handleCmdLine(has_server_config)) exit(0);
#ifndef SERVER_ONLY #ifndef SERVER_ONLY
addons_manager->checkInstalledAddons(); addons_manager->checkInstalledAddons();

View File

@ -31,6 +31,7 @@
#include "guiengine/modaldialog.hpp" #include "guiengine/modaldialog.hpp"
#include "physics/physics.hpp" #include "physics/physics.hpp"
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "network/server_config.hpp"
#include "race/history.hpp" #include "race/history.hpp"
#include "states_screens/race_gui_base.hpp" #include "states_screens/race_gui_base.hpp"
#include "tracks/drive_graph.hpp" #include "tracks/drive_graph.hpp"
@ -459,7 +460,7 @@ void LinearWorld::newLap(unsigned int kart_index)
float finish_time = prev_time*finish_proportion + getTime()*(1.0f-finish_proportion); float finish_time = prev_time*finish_proportion + getTime()*(1.0f-finish_proportion);
if (NetworkConfig::get()->isServer() && if (NetworkConfig::get()->isServer() &&
NetworkConfig::get()->isAutoEnd() && ServerConfig::m_auto_end &&
m_finish_timeout == std::numeric_limits<float>::max()) m_finish_timeout == std::numeric_limits<float>::max())
{ {
m_finish_timeout = finish_time * 0.25f + 15.0f; m_finish_timeout = finish_time * 0.25f + 15.0f;

View File

@ -31,8 +31,40 @@
#include "utils/log.hpp" #include "utils/log.hpp"
#include <algorithm> #include <algorithm>
#include <fstream>
#include <random> #include <random>
//-----------------------------------------------------------------------------
GameSetup::GameSetup()
{
const std::string& motd = ServerConfig::m_motd;
if (motd.find(".txt") != std::string::npos)
{
const std::string& path = ServerConfig::getConfigDirectory() + "/" +
motd;
std::ifstream message(path);
if (message.is_open())
{
for (std::string line; std::getline(message, line); )
{
m_message_of_today += StringUtils::utf8ToWide(line).trim() +
L"\n";
}
// Remove last newline
m_message_of_today.erase(m_message_of_today.size() - 1);
}
}
else if (!motd.empty())
m_message_of_today = StringUtils::xmlDecode(motd);
const std::string& server_name = ServerConfig::m_server_name;
m_server_name_utf8 = StringUtils::wideToUtf8
(StringUtils::xmlDecode(server_name));
m_connected_players_count.store(0);
m_extra_server_info = -1;
reset();
} // GameSetup
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** Update and see if any player disconnects. /** Update and see if any player disconnects.
* \param remove_disconnected_players remove the disconnected players, * \param remove_disconnected_players remove the disconnected players,
@ -149,7 +181,7 @@ void GameSetup::loadWorld()
bool GameSetup::isGrandPrix() const bool GameSetup::isGrandPrix() const
{ {
return m_extra_server_info != -1 && return m_extra_server_info != -1 &&
NetworkConfig::get()->getLocalGameMode().second == ServerConfig::getLocalGameMode().second ==
RaceManager::MAJOR_MODE_GRAND_PRIX; RaceManager::MAJOR_MODE_GRAND_PRIX;
} // isGrandPrix } // isGrandPrix
@ -157,10 +189,10 @@ bool GameSetup::isGrandPrix() const
void GameSetup::addServerInfo(NetworkString* ns) void GameSetup::addServerInfo(NetworkString* ns)
{ {
assert(NetworkConfig::get()->isServer()); assert(NetworkConfig::get()->isServer());
ns->encodeString(NetworkConfig::get()->getServerName()); ns->encodeString(m_server_name_utf8);
ns->addUInt8(race_manager->getDifficulty()) ns->addUInt8((uint8_t)ServerConfig::m_server_difficulty)
.addUInt8((uint8_t)NetworkConfig::get()->getMaxPlayers()) .addUInt8((uint8_t)ServerConfig::m_server_max_players)
.addUInt8((uint8_t)NetworkConfig::get()->getServerMode()); .addUInt8((uint8_t)ServerConfig::m_server_mode);
if (hasExtraSeverInfo()) if (hasExtraSeverInfo())
{ {
if (isGrandPrix()) if (isGrandPrix())
@ -182,16 +214,16 @@ void GameSetup::addServerInfo(NetworkString* ns)
// No extra server info // No extra server info
ns->addUInt8((uint8_t)0); ns->addUInt8((uint8_t)0);
} }
if (NetworkConfig::get()->isOwnerLess()) if (ServerConfig::m_owner_less)
{ {
ns->addFloat(ServerConfig::m_start_game_threshold) ns->addFloat(ServerConfig::m_start_game_threshold)
.addFloat(ServerConfig::m_start_game_counter); .addFloat(ServerConfig::m_start_game_counter);
} }
else else
ns->addFloat(0.0f).addFloat(0.0f); ns->addFloat(0.0f).addFloat(0.0f);
ns->addUInt8(NetworkConfig::get()->getMaxPlayers()); ns->addUInt8(ServerConfig::m_server_max_players);
ns->encodeString16(NetworkConfig::get()->getMOTD()); ns->encodeString16(m_message_of_today);
} // addServerInfo } // addServerInfo
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -232,7 +264,7 @@ void GameSetup::sortPlayersForGrandPrix()
void GameSetup::sortPlayersForTeamGame() void GameSetup::sortPlayersForTeamGame()
{ {
if (!race_manager->teamEnabled() || if (!race_manager->teamEnabled() ||
NetworkConfig::get()->hasTeamChoosing()) ServerConfig::m_team_choosing)
return; return;
std::lock_guard<std::mutex> lock(m_players_mutex); std::lock_guard<std::mutex> lock(m_players_mutex);
for (unsigned i = 0; i < m_players.size(); i++) for (unsigned i = 0; i < m_players.size(); i++)

View File

@ -62,14 +62,14 @@ private:
std::atomic<uint32_t> m_connected_players_count; std::atomic<uint32_t> m_connected_players_count;
irr::core::stringw m_message_of_today;
/** Utf8 server name (with xml decoded) */
std::string m_server_name_utf8;
public: public:
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
GameSetup() GameSetup();
{
m_connected_players_count.store(0);
m_extra_server_info = -1;
reset();
}
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
~GameSetup() {} ~GameSetup() {}
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -174,6 +174,8 @@ public:
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
std::pair<int, int> getPlayerTeamInfo() const; std::pair<int, int> getPlayerTeamInfo() const;
// ------------------------------------------------------------------------
const std::string& getServerNameUtf8() const { return m_server_name_utf8; }
}; };
#endif // GAME_SETUP_HPP #endif // GAME_SETUP_HPP

View File

@ -19,6 +19,7 @@
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "config/stk_config.hpp" #include "config/stk_config.hpp"
#include "config/user_config.hpp" #include "config/user_config.hpp"
#include "network/server_config.hpp"
#include "network/transport_address.hpp" #include "network/transport_address.hpp"
#include "online/xml_request.hpp" #include "online/xml_request.hpp"
#include "states_screens/main_menu_screen.hpp" #include "states_screens/main_menu_screen.hpp"
@ -28,7 +29,6 @@
#include "states_screens/online_screen.hpp" #include "states_screens/online_screen.hpp"
NetworkConfig *NetworkConfig::m_network_config = NULL; NetworkConfig *NetworkConfig::m_network_config = NULL;
const uint32_t NetworkConfig::m_server_version = 1;
/** \class NetworkConfig /** \class NetworkConfig
* This class is the interface between STK and the online code, particularly * This class is the interface between STK and the online code, particularly
@ -48,108 +48,22 @@ NetworkConfig::NetworkConfig()
m_auto_connect = false; m_auto_connect = false;
m_is_server = false; m_is_server = false;
m_is_public_server = false; m_is_public_server = false;
m_is_ranked_server = false;
m_validated_players = false;
m_auto_end = false;
m_owner_less = false;
m_done_adding_network_players = false; m_done_adding_network_players = false;
m_max_players = 4;
m_cur_user_id = 0; m_cur_user_id = 0;
m_cur_user_token = ""; m_cur_user_token = "";
m_server_name = "";
m_password = "";
m_server_discovery_port = stk_config->m_server_discovery_port;
m_client_port = UserConfigParams::m_random_client_port ? m_client_port = UserConfigParams::m_random_client_port ?
0 : stk_config->m_client_port; 0 : stk_config->m_client_port;
m_server_port = UserConfigParams::m_random_server_port ?
0 : stk_config->m_server_port;
m_team_choosing = false;
m_joined_server_version = 0; m_joined_server_version = 0;
} // NetworkConfig } // NetworkConfig
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/** Sets if this instance is a server or client. It also assigns the /** Set that this is not a networked game.
* private port depending if this is a server or client.
*/ */
void NetworkConfig::setIsServer(bool b) void NetworkConfig::unsetNetworking()
{ {
m_is_server = b; m_network_type = NETWORK_NONE;
} // setIsServer ServerConfig::m_private_server_password = "";
} // unsetNetworking
// ----------------------------------------------------------------------------
void NetworkConfig::setServerMode(RaceManager::MinorRaceModeType minor,
RaceManager::MajorRaceModeType major)
{
if (major == RaceManager::MAJOR_MODE_GRAND_PRIX)
{
if (minor == RaceManager::MINOR_MODE_NORMAL_RACE)
m_server_mode = 0;
else if (minor == RaceManager::MINOR_MODE_TIME_TRIAL)
m_server_mode = 1;
else if (minor == RaceManager::MINOR_MODE_FOLLOW_LEADER)
m_server_mode = 2;
}
else if (major == RaceManager::MAJOR_MODE_SINGLE)
{
if (minor == RaceManager::MINOR_MODE_NORMAL_RACE)
m_server_mode = 3;
else if (minor == RaceManager::MINOR_MODE_TIME_TRIAL)
m_server_mode = 4;
else if (minor == RaceManager::MINOR_MODE_FOLLOW_LEADER)
m_server_mode = 5;
else if (minor == RaceManager::MINOR_MODE_SOCCER)
m_server_mode = 6;
}
else if (major == RaceManager::MAJOR_MODE_FREE_FOR_ALL)
{
m_server_mode = 7;
}
else
{
m_server_mode = 8;
}
} // setServerMode
// ----------------------------------------------------------------------------
std::pair<RaceManager::MinorRaceModeType, RaceManager::MajorRaceModeType>
NetworkConfig::getLocalGameMode()
{
switch (m_server_mode)
{
case 0:
return { RaceManager::MINOR_MODE_NORMAL_RACE,
RaceManager::MAJOR_MODE_GRAND_PRIX };
case 1:
return { RaceManager::MINOR_MODE_TIME_TRIAL,
RaceManager::MAJOR_MODE_GRAND_PRIX };
case 2:
return { RaceManager::MINOR_MODE_FOLLOW_LEADER,
RaceManager::MAJOR_MODE_GRAND_PRIX };
case 3:
return { RaceManager::MINOR_MODE_NORMAL_RACE,
RaceManager::MAJOR_MODE_SINGLE };
case 4:
return { RaceManager::MINOR_MODE_TIME_TRIAL,
RaceManager::MAJOR_MODE_SINGLE };
case 5:
return { RaceManager::MINOR_MODE_FOLLOW_LEADER,
RaceManager::MAJOR_MODE_SINGLE };
case 6:
return { RaceManager::MINOR_MODE_SOCCER,
RaceManager::MAJOR_MODE_SINGLE };
case 7:
return { RaceManager::MINOR_MODE_BATTLE,
RaceManager::MAJOR_MODE_FREE_FOR_ALL };
case 8:
return { RaceManager::MINOR_MODE_BATTLE,
RaceManager::MAJOR_MODE_CAPTURE_THE_FLAG };
default:
break;
}
return { RaceManager::MINOR_MODE_NORMAL_RACE,
RaceManager::MAJOR_MODE_SINGLE };
} // getLocalGameMode
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void NetworkConfig::setUserDetails(Online::XMLRequest* r, void NetworkConfig::setUserDetails(Online::XMLRequest* r,
@ -171,32 +85,6 @@ void NetworkConfig::setServerDetails(Online::XMLRequest* r,
r->addParameter("token", m_cur_user_token); r->addParameter("token", m_cur_user_token);
} // setServerDetails } // setServerDetails
// ----------------------------------------------------------------------------
core::stringw NetworkConfig::getModeName(unsigned id)
{
switch(id)
{
case 0:
return _("Normal Race (Grand Prix)");
case 1:
return _("Time Trial (Grand Prix)");
case 3:
return _("Normal Race");
case 4:
return _("Time Trial");
case 6:
return _("Soccer");
case 7:
// I18n: Free for all means a deathmatch game with battle mode in
// networking
return _("Free-For-All");
case 8:
return _("Capture The Flag");
default:
return L"";
}
} // getModeName
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::vector<GUIEngine::Screen*> std::vector<GUIEngine::Screen*>
NetworkConfig::getResetScreens(bool lobby) const NetworkConfig::getResetScreens(bool lobby) const

View File

@ -16,8 +16,8 @@
// along with this program; if not, write to the Free Software // along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
/*! \file stk_host.hpp /*! \file network_config.hpp
* \brief Defines an interface to use network low-level functions easily. * \brief Defines network configuration for server and client.
*/ */
#ifndef HEADER_NETWORK_CONFIG #ifndef HEADER_NETWORK_CONFIG
#define HEADER_NETWORK_CONFIG #define HEADER_NETWORK_CONFIG
@ -59,54 +59,20 @@ private:
/** If set it allows clients to connect directly to this server without /** If set it allows clients to connect directly to this server without
* using the stk server in between. It requires obviously that this * using the stk server in between. It requires obviously that this
* server is accessible (through the firewall) from the outside, * server is accessible (through the firewall) from the outside. */
* then you can use the \ref m_server_discovery_port and ip address for
* direct connection. */
bool m_is_public_server; bool m_is_public_server;
/** True if this host is a server, false otherwise. */ /** True if this host is a server, false otherwise. */
bool m_is_server; bool m_is_server;
/** True if this is a ranked server */
bool m_is_ranked_server;
/* True if automatically end after 1st player finished for some time. */
bool m_auto_end;
/** The password for a server (or to authenticate to a server). */
std::string m_password;
/** The port number to which the server listens to detect direct socket
* requests. */
uint16_t m_server_discovery_port;
/** The port on which the server listens for connection requests from LAN. */
uint16_t m_server_port;
/** The LAN port on which a client is waiting for a server connection. */ /** The LAN port on which a client is waiting for a server connection. */
uint16_t m_client_port; uint16_t m_client_port;
/** Maximum number of players on the server. */
unsigned m_max_players;
/** True if a client should connect to the first server it finds and /** True if a client should connect to the first server it finds and
* immediately start a race. */ * immediately start a race. */
bool m_auto_connect; bool m_auto_connect;
/** True if only validated players are allowed to join. */
bool m_validated_players;
bool m_owner_less;
bool m_done_adding_network_players; bool m_done_adding_network_players;
bool m_team_choosing;
/** If this is a server, the server name. */
irr::core::stringw m_server_name;
unsigned m_server_mode;
/** Used by wan server. */ /** Used by wan server. */
uint32_t m_cur_user_id; uint32_t m_cur_user_id;
std::string m_cur_user_token; std::string m_cur_user_token;
@ -117,16 +83,11 @@ private:
std::vector<std::tuple<InputDevice*, PlayerProfile*, std::vector<std::tuple<InputDevice*, PlayerProfile*,
PerPlayerDifficulty> > m_network_players; PerPlayerDifficulty> > m_network_players;
core::stringw m_motd;
NetworkConfig(); NetworkConfig();
uint32_t m_joined_server_version; uint32_t m_joined_server_version;
public: public:
/** Server version, will be advanced if there are protocol changes. */
static const uint32_t m_server_version;
/** Singleton get, which creates this object if necessary. */ /** Singleton get, which creates this object if necessary. */
static NetworkConfig *get() static NetworkConfig *get()
{ {
@ -143,35 +104,18 @@ public:
} // destroy } // destroy
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setIsServer(bool b); /** Sets if this instance is a server or client. */
// ------------------------------------------------------------------------ void setIsServer(bool b)
/** Sets the port for server discovery. */
void setServerDiscoveryPort(uint16_t port)
{ {
m_server_discovery_port = port; m_is_server = b;
} // setServerDiscoveryPort } // setIsServer
// ------------------------------------------------------------------------
/** Sets the port on which this server listens. */
void setServerPort(uint16_t port) { m_server_port = port; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Sets the port on which a client listens for server connection. */ /** Sets the port on which a client listens for server connection. */
void setClientPort(uint16_t port) { m_client_port = port; } void setClientPort(uint16_t port) { m_client_port = port; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Returns the port on which this server listenes. */
uint16_t getServerPort() const { return m_server_port; }
// ------------------------------------------------------------------------
/** Returns the port for LAN server discovery. */
uint16_t getServerDiscoveryPort() const { return m_server_discovery_port; }
// ------------------------------------------------------------------------
/** Returns the port on which a client listens for server connections. */ /** Returns the port on which a client listens for server connections. */
uint16_t getClientPort() const { return m_client_port; } uint16_t getClientPort() const { return m_client_port; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Sets the password for a server. */
void setPassword(const std::string &password) { m_password = password; }
// ------------------------------------------------------------------------
/** Returns the password. */
const std::string& getPassword() const { return m_password; }
// ------------------------------------------------------------------------
/** Sets that this server can be contacted directly. */ /** Sets that this server can be contacted directly. */
void setIsPublicServer() { m_is_public_server = true; } void setIsPublicServer() { m_is_public_server = true; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -194,12 +138,7 @@ public:
/** Set that this is a WAN networked game. */ /** Set that this is a WAN networked game. */
void setIsWAN() { m_network_type = NETWORK_WAN; } void setIsWAN() { m_network_type = NETWORK_WAN; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Set that this is not a networked game. */ void unsetNetworking();
void unsetNetworking()
{
m_network_type = NETWORK_NONE;
m_password = "";
}
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
const std::vector<std::tuple<InputDevice*, PlayerProfile*, const std::vector<std::tuple<InputDevice*, PlayerProfile*,
PerPlayerDifficulty> >& PerPlayerDifficulty> >&
@ -240,47 +179,18 @@ public:
m_done_adding_network_players = false; m_done_adding_network_players = false;
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Sets the maximum number of players for this server. */
void setMaxPlayers(unsigned n) { m_max_players = n; }
// ------------------------------------------------------------------------
/** Returns the maximum number of players for this server. */
unsigned getMaxPlayers() const { return m_max_players; }
// ------------------------------------------------------------------------
/** Returns if this instance is a server. */ /** Returns if this instance is a server. */
bool isServer() const { return m_is_server; } bool isServer() const { return m_is_server; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Returns if this instance is a client. */ /** Returns if this instance is a client. */
bool isClient() const { return !m_is_server; } bool isClient() const { return !m_is_server; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Sets the name of this server. */
void setServerName(const irr::core::stringw &name)
{
m_server_name = name;
} // setServerName
// ------------------------------------------------------------------------
/** Returns the server name. */
const irr::core::stringw& getServerName() const
{
assert(isServer());
return m_server_name;
} // getServerName
// ------------------------------------------------------------------------
/** Sets if a client should immediately connect to the first server. */ /** Sets if a client should immediately connect to the first server. */
void setAutoConnect(bool b) { m_auto_connect = b; } void setAutoConnect(bool b) { m_auto_connect = b; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
/** Returns if an immediate connection to the first server was /** Returns if an immediate connection to the first server was
* requested. */ * requested. */
bool isAutoConnect() const { return m_auto_connect; } bool isAutoConnect() const { return m_auto_connect; }
// ------------------------------------------------------------------------
/** Returns if the server use multi-session rankings. */
bool isRankedServer() const { return m_is_ranked_server; }
// ------------------------------------------------------------------------
void setRankedServer(bool val) { m_is_ranked_server = val; }
// ------------------------------------------------------------------------
/** Returns the minor and majar game mode from server database id. */
std::pair<RaceManager::MinorRaceModeType, RaceManager::MajorRaceModeType>
getLocalGameMode();
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setCurrentUserId(uint32_t id) { m_cur_user_id = id ; } void setCurrentUserId(uint32_t id) { m_cur_user_id = id ; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -298,37 +208,8 @@ public:
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
const std::string& getServerIdFile() const { return m_server_id_file; } const std::string& getServerIdFile() const { return m_server_id_file; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setMOTD(const core::stringw& motd) { m_motd = motd; }
// ------------------------------------------------------------------------
const core::stringw& getMOTD() const { return m_motd; }
// ------------------------------------------------------------------------
void setServerMode(RaceManager::MinorRaceModeType mode,
RaceManager::MajorRaceModeType);
// ------------------------------------------------------------------------
void setServerMode(unsigned mode) { m_server_mode = mode; }
// ------------------------------------------------------------------------
unsigned getServerMode() const { return m_server_mode; }
// ------------------------------------------------------------------------
core::stringw getModeName(unsigned id);
// ------------------------------------------------------------------------
std::vector<GUIEngine::Screen*> getResetScreens(bool lobby = false) const; std::vector<GUIEngine::Screen*> getResetScreens(bool lobby = false) const;
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setValidatedPlayers(bool val) { m_validated_players = val; }
// ------------------------------------------------------------------------
bool onlyValidatedPlayers() const { return m_validated_players; }
// ------------------------------------------------------------------------
void setOwnerLess(bool val) { m_owner_less = val; }
// ------------------------------------------------------------------------
bool isOwnerLess() const { return m_owner_less; }
// ------------------------------------------------------------------------
void setAutoEnd(bool val) { m_auto_end = val; }
// ------------------------------------------------------------------------
bool isAutoEnd() const { return m_auto_end; }
// ------------------------------------------------------------------------
void setTeamChoosing(bool val) { m_team_choosing = val; }
// ------------------------------------------------------------------------
bool hasTeamChoosing() const { return m_team_choosing; }
// ------------------------------------------------------------------------
void setJoinedServerVersion(uint32_t v) { m_joined_server_version = v; } void setJoinedServerVersion(uint32_t v) { m_joined_server_version = v; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
uint32_t getJoinedServerVersion() const { return m_joined_server_version; } uint32_t getJoinedServerVersion() const { return m_joined_server_version; }

View File

@ -306,7 +306,7 @@ void ClientLobby::update(int ticks)
{ {
NetworkString* ns = getNetworkString(); NetworkString* ns = getNetworkString();
ns->addUInt8(LE_CONNECTION_REQUESTED) ns->addUInt8(LE_CONNECTION_REQUESTED)
.addUInt32(NetworkConfig::m_server_version); .addUInt32(ServerConfig::m_server_version);
auto all_k = kart_properties_manager->getAllAvailableKarts(); auto all_k = kart_properties_manager->getAllAvailableKarts();
auto all_t = track_manager->getAllTrackIdentifiers(); auto all_t = track_manager->getAllTrackIdentifiers();
@ -344,7 +344,7 @@ void ClientLobby::update(int ticks)
ns->encodeString(PlayerManager::getCurrentOnlineUserName()); ns->encodeString(PlayerManager::getCurrentOnlineUserName());
} }
rest->encodeString(NetworkConfig::get()->getPassword()) rest->encodeString(ServerConfig::m_private_server_password)
.addUInt8(player_count); .addUInt8(player_count);
for (auto& p : NetworkConfig::get()->getNetworkPlayers()) for (auto& p : NetworkConfig::get()->getNetworkPlayers())
{ {
@ -579,8 +579,8 @@ void ClientLobby::handleServerInfo(Event* event)
NetworkingLobby::getInstance()->addMoreServerInfo(each_line); NetworkingLobby::getInstance()->addMoreServerInfo(each_line);
u_data = data.getUInt8(); u_data = data.getUInt8();
NetworkConfig::get()->setServerMode(u_data); ServerConfig::m_server_mode = u_data;
auto game_mode = NetworkConfig::get()->getLocalGameMode(); auto game_mode = ServerConfig::getLocalGameMode();
race_manager->setMinorMode(game_mode.first); race_manager->setMinorMode(game_mode.first);
if (game_mode.first == RaceManager::MINOR_MODE_BATTLE) if (game_mode.first == RaceManager::MINOR_MODE_BATTLE)
race_manager->setMajorMode(game_mode.second); race_manager->setMajorMode(game_mode.second);
@ -591,7 +591,7 @@ void ClientLobby::handleServerInfo(Event* event)
} }
//I18N: In the networking lobby //I18N: In the networking lobby
core::stringw mode_name = NetworkConfig::get()->getModeName(u_data); core::stringw mode_name = ServerConfig::getModeName(u_data);
each_line = _("Game mode: %s", mode_name); each_line = _("Game mode: %s", mode_name);
NetworkingLobby::getInstance()->addMoreServerInfo(each_line); NetworkingLobby::getInstance()->addMoreServerInfo(each_line);

View File

@ -343,7 +343,7 @@ bool ConnectToServer::tryConnect(int timeout, int retry, bool another_port)
Log::info("ConnectToServer", "Detect port for server address."); Log::info("ConnectToServer", "Detect port for server address.");
BareNetworkString s(std::string("stk-server-port")); BareNetworkString s(std::string("stk-server-port"));
TransportAddress address(m_server_address.getIP(), TransportAddress address(m_server_address.getIP(),
NetworkConfig::get()->getServerDiscoveryPort()); stk_config->m_server_discovery_port);
nw->sendRawPacket(s, address); nw->sendRawPacket(s, address);
TransportAddress sender; TransportAddress sender;
const int LEN = 2048; const int LEN = 2048;
@ -352,6 +352,8 @@ bool ConnectToServer::tryConnect(int timeout, int retry, bool another_port)
if (len != 2) if (len != 2)
{ {
Log::error("ConnectToServer", "Invalid port number"); Log::error("ConnectToServer", "Invalid port number");
if (another_port)
delete nw;
return false; return false;
} }
BareNetworkString server_port(buffer, len); BareNetworkString server_port(buffer, len);

View File

@ -98,7 +98,7 @@ ServerLobby::ServerLobby() : LobbyProtocol(NULL)
setHandleDisconnections(true); setHandleDisconnections(true);
m_state = SET_PUBLIC_ADDRESS; m_state = SET_PUBLIC_ADDRESS;
updateBanList(); updateBanList();
if (NetworkConfig::get()->isRankedServer()) if (ServerConfig::m_ranked)
{ {
Log::info("ServerLobby", "This server will submit ranking scores to " Log::info("ServerLobby", "This server will submit ranking scores to "
"STK addons server, don't bother host one if you don't have the " "STK addons server, don't bother host one if you don't have the "
@ -144,7 +144,8 @@ void ServerLobby::setup()
all_t.resize(65535); all_t.resize(65535);
m_available_kts.first = { all_k.begin(), all_k.end() }; m_available_kts.first = { all_k.begin(), all_k.end() };
m_available_kts.second = { all_t.begin(), all_t.end() }; m_available_kts.second = { all_t.begin(), all_t.end() };
switch (NetworkConfig::get()->getLocalGameMode().first) RaceManager::MinorRaceModeType m = ServerConfig::getLocalGameMode().first;
switch (m)
{ {
case RaceManager::MINOR_MODE_NORMAL_RACE: case RaceManager::MINOR_MODE_NORMAL_RACE:
case RaceManager::MINOR_MODE_TIME_TRIAL: case RaceManager::MINOR_MODE_TIME_TRIAL:
@ -278,7 +279,7 @@ void ServerLobby::handleChat(Event* event)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void ServerLobby::changeTeam(Event* event) void ServerLobby::changeTeam(Event* event)
{ {
if (!NetworkConfig::get()->hasTeamChoosing() || if (!ServerConfig::m_team_choosing ||
!race_manager->teamEnabled()) !race_manager->teamEnabled())
return; return;
if (!checkDataSize(event, 1)) return; if (!checkDataSize(event, 1)) return;
@ -422,11 +423,11 @@ void ServerLobby::asynchronousUpdate()
} }
case WAITING_FOR_START_GAME: case WAITING_FOR_START_GAME:
{ {
if (NetworkConfig::get()->isOwnerLess()) if (ServerConfig::m_owner_less)
{ {
float player_size = (float)m_game_setup->getPlayerCount(); float player_size = (float)m_game_setup->getPlayerCount();
if ((player_size >= if ((player_size >=
(float)NetworkConfig::get()->getMaxPlayers() * (float)ServerConfig::m_server_max_players *
ServerConfig::m_start_game_threshold || ServerConfig::m_start_game_threshold ||
m_game_setup->isGrandPrixStarted()) && m_game_setup->isGrandPrixStarted()) &&
m_timeout.load() == std::numeric_limits<int64_t>::max()) m_timeout.load() == std::numeric_limits<int64_t>::max())
@ -436,7 +437,7 @@ void ServerLobby::asynchronousUpdate()
(ServerConfig::m_start_game_counter * 1000.0f)); (ServerConfig::m_start_game_counter * 1000.0f));
} }
else if (player_size < else if (player_size <
(float)NetworkConfig::get()->getMaxPlayers() * (float)ServerConfig::m_server_max_players*
ServerConfig::m_start_game_threshold && ServerConfig::m_start_game_threshold &&
!m_game_setup->isGrandPrixStarted()) !m_game_setup->isGrandPrixStarted())
{ {
@ -585,7 +586,7 @@ void ServerLobby::update(int ticks)
} }
// Reset for ranked server if in kart / track selection has only 1 player // Reset for ranked server if in kart / track selection has only 1 player
if (NetworkConfig::get()->isRankedServer() && if (ServerConfig::m_ranked &&
m_state.load() == SELECTING && m_state.load() == SELECTING &&
m_game_setup->getPlayerCount() == 1) m_game_setup->getPlayerCount() == 1)
{ {
@ -688,15 +689,16 @@ bool ServerLobby::registerServer()
request->addParameter("port", m_server_address.getPort() ); request->addParameter("port", m_server_address.getPort() );
request->addParameter("private_port", request->addParameter("private_port",
STKHost::get()->getPrivatePort() ); STKHost::get()->getPrivatePort() );
request->addParameter("name", NetworkConfig::get()->getServerName() ); // The ServerConfig::m_server_name has xml encoded name so we send this
request->addParameter("max_players", // insteaf of from game_setup
NetworkConfig::get()->getMaxPlayers()); const std::string& server_name = ServerConfig::m_server_name;
request->addParameter("difficulty", race_manager->getDifficulty()); request->addParameter("name", server_name);
request->addParameter("game_mode", NetworkConfig::get()->getServerMode()); request->addParameter("max_players", ServerConfig::m_server_max_players);
request->addParameter("password", request->addParameter("difficulty", ServerConfig::m_server_difficulty);
(unsigned)(!NetworkConfig::get()->getPassword().empty())); request->addParameter("game_mode", ServerConfig::m_server_mode);
request->addParameter("version", const std::string& pw = ServerConfig::m_private_server_password;
(unsigned)NetworkConfig::m_server_version); request->addParameter("password", (unsigned)(!pw.empty()));
request->addParameter("version", (unsigned)ServerConfig::m_server_version);
Log::info("ServerLobby", "Public server address %s", Log::info("ServerLobby", "Public server address %s",
m_server_address.toString().c_str()); m_server_address.toString().c_str());
@ -778,7 +780,7 @@ void ServerLobby::startSelection(const Event *event)
} }
} }
if (NetworkConfig::get()->hasTeamChoosing() && race_manager->teamEnabled()) if (ServerConfig::m_team_choosing && race_manager->teamEnabled())
{ {
auto red_blue = m_game_setup->getPlayerTeamInfo(); auto red_blue = m_game_setup->getPlayerTeamInfo();
if ((red_blue.first == 0 || red_blue.second == 0) && if ((red_blue.first == 0 || red_blue.second == 0) &&
@ -1047,7 +1049,7 @@ void ServerLobby::checkRaceFinished()
static_cast<LinearWorld*>(World::getWorld())->getFastestLapTicks(); static_cast<LinearWorld*>(World::getWorld())->getFastestLapTicks();
m_result_ns->addUInt32(fastest_lap); m_result_ns->addUInt32(fastest_lap);
} }
if (NetworkConfig::get()->isRankedServer()) if (ServerConfig::m_ranked)
{ {
computeNewRankings(); computeNewRankings();
submitRankingsToAddons(); submitRankingsToAddons();
@ -1435,7 +1437,7 @@ void ServerLobby::connectionRequested(Event* event)
if (m_game_setup->getPlayerCount() + player_count + if (m_game_setup->getPlayerCount() + player_count +
m_waiting_players_counts.load() > m_waiting_players_counts.load() >
NetworkConfig::get()->getMaxPlayers()) (unsigned)ServerConfig::m_server_max_players)
{ {
NetworkString *message = getNetworkString(2); NetworkString *message = getNetworkString(2);
message->setSynchronous(true); message->setSynchronous(true);
@ -1454,10 +1456,9 @@ void ServerLobby::connectionRequested(Event* event)
!(peer->getAddress().isPublicAddressLocalhost() || !(peer->getAddress().isPublicAddressLocalhost() ||
peer->getAddress().isLAN()) && peer->getAddress().isLAN()) &&
NetworkConfig::get()->isWAN() && NetworkConfig::get()->isWAN() &&
NetworkConfig::get()->onlyValidatedPlayers()) || ServerConfig::m_validating_player) ||
((player_count != 1 || online_id == 0 || ((player_count != 1 || online_id == 0 ||
m_scores.find(online_id) != m_scores.end()) && m_scores.find(online_id) != m_scores.end()) && ServerConfig::m_ranked))
NetworkConfig::get()->isRankedServer()))
{ {
NetworkString* message = getNetworkString(2); NetworkString* message = getNetworkString(2);
message->setSynchronous(true); message->setSynchronous(true);
@ -1493,7 +1494,8 @@ void ServerLobby::handleUnencryptedConnection(std::shared_ptr<STKPeer> peer,
// Check for password // Check for password
std::string password; std::string password;
data.decodeString(&password); data.decodeString(&password);
if (password != NetworkConfig::get()->getPassword()) const std::string& server_pw = ServerConfig::m_private_server_password;
if (password != server_pw)
{ {
NetworkString *message = getNetworkString(2); NetworkString *message = getNetworkString(2);
message->setSynchronous(true); message->setSynchronous(true);
@ -1508,7 +1510,7 @@ void ServerLobby::handleUnencryptedConnection(std::shared_ptr<STKPeer> peer,
// Check again for duplicated online id in ranked server // Check again for duplicated online id in ranked server
if (m_scores.find(online_id) != m_scores.end() && if (m_scores.find(online_id) != m_scores.end() &&
NetworkConfig::get()->isRankedServer()) ServerConfig::m_ranked)
{ {
NetworkString* message = getNetworkString(2); NetworkString* message = getNetworkString(2);
message->setSynchronous(true); message->setSynchronous(true);
@ -1533,7 +1535,7 @@ void ServerLobby::handleUnencryptedConnection(std::shared_ptr<STKPeer> peer,
(peer, i == 0 && !online_name.empty() ? online_name : name, (peer, i == 0 && !online_name.empty() ? online_name : name,
peer->getHostId(), default_kart_color, i == 0 ? online_id : 0, peer->getHostId(), default_kart_color, i == 0 ? online_id : 0,
per_player_difficulty, (uint8_t)i, KART_TEAM_NONE); per_player_difficulty, (uint8_t)i, KART_TEAM_NONE);
if (NetworkConfig::get()->hasTeamChoosing() && if (ServerConfig::m_team_choosing &&
race_manager->teamEnabled()) race_manager->teamEnabled())
{ {
KartTeam cur_team = KART_TEAM_NONE; KartTeam cur_team = KART_TEAM_NONE;
@ -1575,7 +1577,7 @@ void ServerLobby::handleUnencryptedConnection(std::shared_ptr<STKPeer> peer,
(m_timeout.load() - (int64_t)StkTime::getRealTimeMs()) / 1000.0f; (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).addFloat(auto_start_timer); .addUInt32(ServerConfig::m_server_version).addFloat(auto_start_timer);
if (game_started) if (game_started)
{ {
@ -1603,7 +1605,7 @@ void ServerLobby::handleUnencryptedConnection(std::shared_ptr<STKPeer> peer,
peer->sendPacket(message_ack); peer->sendPacket(message_ack);
delete message_ack; delete message_ack;
if (NetworkConfig::get()->isRankedServer()) if (ServerConfig::m_ranked)
{ {
getRankingForPlayer(peer->getPlayerProfiles()[0]); getRankingForPlayer(peer->getPlayerProfiles()[0]);
} }
@ -1645,7 +1647,7 @@ void ServerLobby::updatePlayerList(bool update_when_reset_server)
server_owner = 1; server_owner = 1;
pl->addUInt8(server_owner); pl->addUInt8(server_owner);
pl->addUInt8(profile->getPerPlayerDifficulty()); pl->addUInt8(profile->getPerPlayerDifficulty());
if (NetworkConfig::get()->hasTeamChoosing() && if (ServerConfig::m_team_choosing &&
race_manager->teamEnabled()) race_manager->teamEnabled())
pl->addUInt8(profile->getTeam()); pl->addUInt8(profile->getTeam());
else else
@ -1670,7 +1672,7 @@ void ServerLobby::updateServerOwner()
{ {
if (m_state.load() < WAITING_FOR_START_GAME || if (m_state.load() < WAITING_FOR_START_GAME ||
m_state.load() > RESULT_DISPLAY || m_state.load() > RESULT_DISPLAY ||
NetworkConfig::get()->isOwnerLess()) ServerConfig::m_owner_less)
return; return;
if (!m_server_owner.expired()) if (!m_server_owner.expired())
return; return;
@ -2306,7 +2308,7 @@ void ServerLobby::addWaitingPlayersToGame()
auto peer = npp->getPeer(); auto peer = npp->getPeer();
assert(peer); assert(peer);
uint32_t online_id = npp->getOnlineId(); uint32_t online_id = npp->getOnlineId();
if (NetworkConfig::get()->isRankedServer()) if (ServerConfig::m_ranked)
{ {
if (m_scores.find(online_id) != m_scores.end()) if (m_scores.find(online_id) != m_scores.end())
{ {
@ -2329,7 +2331,7 @@ void ServerLobby::addWaitingPlayersToGame()
StringUtils::wideToUtf8(npp->getName()).c_str(), StringUtils::wideToUtf8(npp->getName()).c_str(),
npp->getOnlineId(), peer->getAddress().toString().c_str()); npp->getOnlineId(), peer->getAddress().toString().c_str());
if (NetworkConfig::get()->isRankedServer()) if (ServerConfig::m_ranked)
{ {
getRankingForPlayer(peer->getPlayerProfiles()[0]); getRankingForPlayer(peer->getPlayerProfiles()[0]);
} }

View File

@ -31,7 +31,15 @@ static std::vector<UserConfigParam*> g_server_params;
#define SERVER_CFG_DEFAULT(X) = X #define SERVER_CFG_DEFAULT(X) = X
#include "network/server_config.hpp" #include "network/server_config.hpp"
#include "config/stk_config.hpp"
#include "io/file_manager.hpp" #include "io/file_manager.hpp"
#include "network/game_setup.hpp"
#include "network/protocols/lobby_protocol.hpp"
#include "network/stk_host.hpp"
#include "race/race_manager.hpp"
#include "utils/string_utils.hpp"
#include <fstream>
namespace ServerConfig namespace ServerConfig
{ {
@ -70,6 +78,17 @@ BoolServerConfigParam::BoolServerConfigParam(bool default_value,
g_server_params.push_back(this); g_server_params.push_back(this);
} // BoolServerConfigParam } // BoolServerConfigParam
// ============================================================================
StringServerConfigParam::StringServerConfigParam(std::string default_value,
const char* param_name,
const char* comment)
: StringUserConfigParam(param_name, comment)
{
m_value = default_value;
m_default_value = default_value;
g_server_params.push_back(this);
} // StringServerConfigParam
// ============================================================================ // ============================================================================
template<typename T, typename U> template<typename T, typename U>
MapServerConfigParam<T, U>::MapServerConfigParam(const char* param_name, MapServerConfigParam<T, U>::MapServerConfigParam(const char* param_name,
@ -91,15 +110,219 @@ void loadServerConfig(const std::string& path)
} }
else else
{ {
g_server_config_path = path; g_server_config_path = file_manager->getFileSystem()
->getAbsolutePath(path.c_str()).c_str();
} }
const XMLNode* root = file_manager->createXMLTree(g_server_config_path);
loadServerConfigXML(root);
} // loadServerConfig } // loadServerConfig
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void writeServerConfig() void loadServerConfigXML(const XMLNode* root)
{ {
} // writeServerConfig if (!root || root->getName() != "server-config")
{
Log::info("ServerConfig",
"Could not read server config file '%s'. "
"A new file will be created.", g_server_config_path.c_str());
if (root)
delete root;
writeServerConfigToDisk();
return;
}
int config_file_version = -1;
if (root->get("version", &config_file_version) < 1 ||
config_file_version < stk_config->m_min_server_version ||
config_file_version > stk_config->m_max_server_version)
{
Log::info("ServerConfig", "Your config file was not compatible, "
"so it was deleted and a new one will be created.");
delete root;
writeServerConfigToDisk();
return;
}
for (unsigned i = 0; i < g_server_params.size(); i++)
g_server_params[i]->findYourDataInAChildOf(root);
delete root;
} // loadServerConfigXML
// ----------------------------------------------------------------------------
std::string getServerConfigXML()
{
std::stringstream ss;
ss << "<?xml version=\"1.0\"?>\n";
ss << "<server-config version=\"" << m_server_version << "\" >\n\n";
for (unsigned i = 0; i < g_server_params.size(); i++)
g_server_params[i]->write(ss);
ss << "</server-config>\n";
return ss.str();
} // getServerConfigXML
// ----------------------------------------------------------------------------
void writeServerConfigToDisk()
{
const std::string& config_xml = getServerConfigXML();
try
{
std::ofstream configfile(g_server_config_path.c_str(),
std::ofstream::out);
configfile << config_xml;
configfile.close();
}
catch (std::runtime_error& e)
{
Log::error("ServerConfig", "Failed to write server config to %s, "
"because %s", g_server_config_path.c_str(), e.what());
}
} // writeServerConfigToDisk
// ----------------------------------------------------------------------------
/** Returns the minor and majar game mode from server database id. */
std::pair<RaceManager::MinorRaceModeType, RaceManager::MajorRaceModeType>
getLocalGameMode()
{
switch (m_server_mode)
{
case 0:
return { RaceManager::MINOR_MODE_NORMAL_RACE,
RaceManager::MAJOR_MODE_GRAND_PRIX };
case 1:
return { RaceManager::MINOR_MODE_TIME_TRIAL,
RaceManager::MAJOR_MODE_GRAND_PRIX };
case 2:
return { RaceManager::MINOR_MODE_FOLLOW_LEADER,
RaceManager::MAJOR_MODE_GRAND_PRIX };
case 3:
return { RaceManager::MINOR_MODE_NORMAL_RACE,
RaceManager::MAJOR_MODE_SINGLE };
case 4:
return { RaceManager::MINOR_MODE_TIME_TRIAL,
RaceManager::MAJOR_MODE_SINGLE };
case 5:
return { RaceManager::MINOR_MODE_FOLLOW_LEADER,
RaceManager::MAJOR_MODE_SINGLE };
case 6:
return { RaceManager::MINOR_MODE_SOCCER,
RaceManager::MAJOR_MODE_SINGLE };
case 7:
return { RaceManager::MINOR_MODE_BATTLE,
RaceManager::MAJOR_MODE_FREE_FOR_ALL };
case 8:
return { RaceManager::MINOR_MODE_BATTLE,
RaceManager::MAJOR_MODE_CAPTURE_THE_FLAG };
default:
break;
}
return { RaceManager::MINOR_MODE_NORMAL_RACE,
RaceManager::MAJOR_MODE_SINGLE };
} // getLocalGameMode
// ----------------------------------------------------------------------------
core::stringw getModeName(unsigned id)
{
switch(id)
{
case 0:
return _("Normal Race (Grand Prix)");
case 1:
return _("Time Trial (Grand Prix)");
case 3:
return _("Normal Race");
case 4:
return _("Time Trial");
case 6:
return _("Soccer");
case 7:
// I18n: Free for all means a deathmatch game with battle mode in
// networking
return _("Free-For-All");
case 8:
return _("Capture The Flag");
default:
return L"";
}
} // getModeName
// ----------------------------------------------------------------------------
void loadServerLobbyFromConfig()
{
if (unsupportedGameMode())
Log::fatal("ServerConfig", "Unsupported game mode");
if (m_server_difficulty > (unsigned)RaceManager::DIFFICULTY_LAST)
m_server_difficulty = (unsigned)RaceManager::DIFFICULTY_LAST;
if (m_server_mode > 8)
m_server_mode = 3;
auto modes = getLocalGameMode();
race_manager->setMinorMode(modes.first);
race_manager->setMajorMode(modes.second);
unsigned difficulty = m_server_difficulty;
race_manager->setDifficulty(RaceManager::Difficulty(difficulty));
if (m_ranked)
{
m_validating_player = true;
m_auto_end = true;
m_owner_less = true;
}
if (m_owner_less)
m_team_choosing = false;
const bool is_soccer =
race_manager->getMinorMode() == RaceManager::MINOR_MODE_SOCCER;
const bool is_gp =
race_manager->getMajorMode() == RaceManager::MAJOR_MODE_GRAND_PRIX;
const bool is_battle =
race_manager->getMinorMode() == RaceManager::MINOR_MODE_BATTLE;
std::shared_ptr<LobbyProtocol> server_lobby;
server_lobby = STKHost::create();
if (is_soccer)
{
server_lobby->getGameSetup()
->setSoccerGoalTarget(m_soccer_goal_target);
}
else if (is_gp)
{
server_lobby->getGameSetup()->setGrandPrixTrack(m_gp_track_count);
}
else if (is_battle)
{
if (m_hit_limit_threshold < 0.0f &&
m_time_limit_threshold_ffa < 0.0f)
{
Log::warn("main", "Reset invalid hit and time limit settings");
m_hit_limit_threshold.revertToDefaults();
m_time_limit_threshold_ffa.revertToDefaults();
}
if (m_capture_limit_threshold < 0.0f &&
m_time_limit_threshold_ctf < 0.0f)
{
Log::warn("main", "Reset invalid Capture and time limit settings");
m_capture_limit_threshold.revertToDefaults();
m_time_limit_threshold_ctf.revertToDefaults();
}
}
// The extra server info has to be set before server lobby started
if (server_lobby)
server_lobby->requestStart();
} // loadServerLobbyFromConfig
// ----------------------------------------------------------------------------
std::string getConfigDirectory()
{
return StringUtils::getPath(g_server_config_path);
} // getConfigDirectory
} }

View File

@ -20,6 +20,7 @@
#define HEADER_SERVER_CONFIG #define HEADER_SERVER_CONFIG
#include "config/user_config.hpp" #include "config/user_config.hpp"
#include "race/race_manager.hpp"
#ifndef SERVER_CFG_PREFIX #ifndef SERVER_CFG_PREFIX
#define SERVER_CFG_PREFIX extern #define SERVER_CFG_PREFIX extern
@ -32,6 +33,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
class XMLNode;
namespace ServerConfig namespace ServerConfig
{ {
// ======================================================================== // ========================================================================
@ -59,6 +62,14 @@ namespace ServerConfig
using BoolUserConfigParam::operator=; using BoolUserConfigParam::operator=;
}; };
// ======================================================================== // ========================================================================
class StringServerConfigParam : public StringUserConfigParam
{
public:
StringServerConfigParam(std::string default_value,
const char* param_name, const char* comment);
using StringUserConfigParam::operator=;
};
// ========================================================================
template<typename T, typename U> template<typename T, typename U>
class MapServerConfigParam : public MapUserConfigParam<T, U> class MapServerConfigParam : public MapUserConfigParam<T, U>
{ {
@ -74,8 +85,62 @@ namespace ServerConfig
typedef MapServerConfigParam<std::string, uint32_t> typedef MapServerConfigParam<std::string, uint32_t>
StringToUIntServerConfigParam; StringToUIntServerConfigParam;
// ======================================================================== // ========================================================================
void loadServerConfig(const std::string& path = ""); SERVER_CFG_PREFIX StringServerConfigParam m_server_name
void writeServerConfig(); SERVER_CFG_DEFAULT(StringServerConfigParam("stk server", "server-name",
"Name of server, encode in XML if you want to use unicode "
"characters."));
SERVER_CFG_PREFIX IntServerConfigParam m_server_port
SERVER_CFG_DEFAULT(IntServerConfigParam(0, "server-port",
"Port used in server, if you specify 0, it will use the server port "
"specified in stk_config.xml or if random-server-port is enabled "
"in user config, than any port. STK will auto change to random "
"port if the port you specify failed to be bound."));
SERVER_CFG_PREFIX IntServerConfigParam m_server_mode
SERVER_CFG_DEFAULT(IntServerConfigParam(3, "server-mode",
"Game mode in server, 0 is normal race (grand prix), "
"1 is time trial (grand prix), 3 is normal race, "
"4 time trial, 6 is soccer, 7 is free-for-all and "
"8 is capture the flag. Notice: grand prix server doesn't "
"allow for players to join and wait for ongoing game."));
SERVER_CFG_PREFIX IntServerConfigParam m_server_difficulty
SERVER_CFG_DEFAULT(IntServerConfigParam(0, "server-difficulty",
"Difficulty in server, 0 is beginner, 1 is intermediate, 2 is expert "
"and 3 is supertux (the most difficult)."));
SERVER_CFG_PREFIX IntServerConfigParam m_gp_track_count
SERVER_CFG_DEFAULT(IntServerConfigParam(3, "gp-track-count",
"Number of grand prix tracks per game (If grand prix enabled)."));
SERVER_CFG_PREFIX BoolServerConfigParam m_soccer_goal_target
SERVER_CFG_DEFAULT(BoolServerConfigParam(false, "soccer-goal-target",
"Use goal torget in soccer."));
SERVER_CFG_PREFIX BoolServerConfigParam m_wan_server
SERVER_CFG_DEFAULT(BoolServerConfigParam(true, "wan-server",
"Enable wan server, which requires you to have an stk-addons account "
"with a saved session. Check init-user command for details."));
SERVER_CFG_PREFIX BoolServerConfigParam m_enable_console
SERVER_CFG_DEFAULT(BoolServerConfigParam(false, "enable-console",
"Enable network console, which can do for example kickban."));
SERVER_CFG_PREFIX IntServerConfigParam m_server_max_players
SERVER_CFG_DEFAULT(IntServerConfigParam(8, "server-max-players",
"Maximum number of players on the server, setting it more than "
"8 will have performance degradation."));
SERVER_CFG_PREFIX StringServerConfigParam m_private_server_password
SERVER_CFG_DEFAULT(StringServerConfigParam("",
"private-server-password", "Password for private server, "
"empty for a public server."));
SERVER_CFG_PREFIX StringServerConfigParam m_motd
SERVER_CFG_DEFAULT(StringServerConfigParam("",
"motd", "Message of today shown in lobby, you can enter encoded XML "
"words here or a file.txt and let STK load it."));
SERVER_CFG_PREFIX FloatServerConfigParam m_voting_timeout SERVER_CFG_PREFIX FloatServerConfigParam m_voting_timeout
SERVER_CFG_DEFAULT(FloatServerConfigParam(20.0f, "voting-timeout", SERVER_CFG_DEFAULT(FloatServerConfigParam(20.0f, "voting-timeout",
@ -83,12 +148,14 @@ namespace ServerConfig
SERVER_CFG_PREFIX FloatServerConfigParam m_validation_timeout SERVER_CFG_PREFIX FloatServerConfigParam m_validation_timeout
SERVER_CFG_DEFAULT(FloatServerConfigParam(20.0f, "validation-timeout", SERVER_CFG_DEFAULT(FloatServerConfigParam(20.0f, "validation-timeout",
"Timeout in seconds for validation of clients.")); "Timeout in seconds for validation of clients in wan, currently "
"stk will use the stk-addons server to share AES key between client "
"and server."));
SERVER_CFG_PREFIX IntServerConfigParam m_server_max_players SERVER_CFG_PREFIX BoolServerConfigParam m_validating_player
SERVER_CFG_DEFAULT(IntServerConfigParam(8, "server-max-players", SERVER_CFG_DEFAULT(BoolServerConfigParam(true, "validating-player",
"Maximum number of players on the server, setting it more than " "By default WAN server will always validate player and LAN will not, "
"8 will have performance degradation.")); "disable it to allow non-validated player in WAN."));
SERVER_CFG_PREFIX BoolServerConfigParam m_firewalled_server SERVER_CFG_PREFIX BoolServerConfigParam m_firewalled_server
SERVER_CFG_DEFAULT(BoolServerConfigParam(true, "firewalled-server", SERVER_CFG_DEFAULT(BoolServerConfigParam(true, "firewalled-server",
@ -96,6 +163,11 @@ namespace ServerConfig
"it allows saving server resource if your server is not " "it allows saving server resource if your server is not "
"behind a firewall.")); "behind a firewall."));
SERVER_CFG_PREFIX BoolServerConfigParam m_owner_less
SERVER_CFG_DEFAULT(BoolServerConfigParam(false, "owner-less",
"No server owner in lobby which can control the starting of game or "
"kick any players."));
SERVER_CFG_PREFIX FloatServerConfigParam m_start_game_counter SERVER_CFG_PREFIX FloatServerConfigParam m_start_game_counter
SERVER_CFG_DEFAULT(FloatServerConfigParam(30.0f, "start-game-counter", SERVER_CFG_DEFAULT(FloatServerConfigParam(30.0f, "start-game-counter",
"Time to wait before entering kart selection screen " "Time to wait before entering kart selection screen "
@ -108,6 +180,22 @@ namespace ServerConfig
"connected player is larger than max player * this value, for " "connected player is larger than max player * this value, for "
"owner less or ranked server, after start-game-counter.")); "owner less or ranked server, after start-game-counter."));
SERVER_CFG_PREFIX BoolServerConfigParam m_auto_end
SERVER_CFG_DEFAULT(BoolServerConfigParam(false, "auto-end",
"Automatically end linear race game after 1st player finished "
"for some time (currently his finished time * 0.25 + 15.0)."));
SERVER_CFG_PREFIX BoolServerConfigParam m_team_choosing
SERVER_CFG_DEFAULT(BoolServerConfigParam(true, "team-choosing",
"Enable team choosing in lobby in team game (soccer and CTF). "
"If owner-less is enabled, than this option is always disabled."));
SERVER_CFG_PREFIX BoolServerConfigParam m_ranked
SERVER_CFG_DEFAULT(BoolServerConfigParam(false, "ranked",
"Server will submit ranking to stk addons server "
"for linear race games, you require permission for that. "
"validating-player, auto-end and owner-less will be turned on."));
SERVER_CFG_PREFIX FloatServerConfigParam m_flag_return_timemout SERVER_CFG_PREFIX FloatServerConfigParam m_flag_return_timemout
SERVER_CFG_DEFAULT(FloatServerConfigParam(20.0f, "flag-return-timemout", SERVER_CFG_DEFAULT(FloatServerConfigParam(20.0f, "flag-return-timemout",
"Time in seconds when a flag is dropped a by player in CTF " "Time in seconds when a flag is dropped a by player in CTF "
@ -175,6 +263,30 @@ namespace ServerConfig
"if -1 (uint32_t max) than a permanent ban.", "if -1 (uint32_t max) than a permanent ban.",
{ { 0u, 0u } })); { { 0u, 0u } }));
// ========================================================================
/** Server version, will be advanced if there are protocol changes. */
static const uint32_t m_server_version = 1;
// ========================================================================
void loadServerConfig(const std::string& path = "");
// ------------------------------------------------------------------------
void loadServerConfigXML(const XMLNode* root);
// ------------------------------------------------------------------------
std::string getServerConfigXML();
// ------------------------------------------------------------------------
void writeServerConfigToDisk();
// ------------------------------------------------------------------------
std::pair<RaceManager::MinorRaceModeType, RaceManager::MajorRaceModeType>
getLocalGameMode();
// ------------------------------------------------------------------------
core::stringw getModeName(unsigned id);
// ------------------------------------------------------------------------
inline bool unsupportedGameMode()
{ return m_server_mode == 2 || m_server_mode == 5; }
// ------------------------------------------------------------------------
void loadServerLobbyFromConfig();
// ------------------------------------------------------------------------
std::string getConfigDirectory();
}; // namespace ServerConfig }; // namespace ServerConfig
#endif // HEADER_SERVER_CONFIG #endif // HEADER_SERVER_CONFIG

View File

@ -321,7 +321,7 @@ void ServersManager::setDefaultBroadcastAddresses()
m_broadcast_address.emplace_back(std::string("127.0.0.255") ); m_broadcast_address.emplace_back(std::string("127.0.0.255") );
m_broadcast_address.emplace_back(std::string("127.0.0.1") ); m_broadcast_address.emplace_back(std::string("127.0.0.1") );
for (auto& addr : m_broadcast_address) for (auto& addr : m_broadcast_address)
addr.setPort(NetworkConfig::get()->getServerDiscoveryPort()); addr.setPort(stk_config->m_server_discovery_port);
} // setDefaultBroadcastAddresses } // setDefaultBroadcastAddresses
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@ -345,7 +345,7 @@ void ServersManager::addAllBroadcastAddresses(const TransportAddress &a, int len
{ {
unsigned int mask = (1 << len) - 1; unsigned int mask = (1 << len) - 1;
TransportAddress bcast(a.getIP() | mask, TransportAddress bcast(a.getIP() | mask,
NetworkConfig::get()->getServerDiscoveryPort()); stk_config->m_server_discovery_port);
Log::info("Broadcast", "address %s length %d mask %x --> %s", Log::info("Broadcast", "address %s length %d mask %x --> %s",
a.toString().c_str(), a.toString().c_str(),
len, mask, len, mask,

View File

@ -271,9 +271,11 @@ STKHost::STKHost(bool server)
if (server) if (server)
{ {
addr.port = NetworkConfig::get()->getServerPort(); addr.port = ServerConfig::m_server_port;
if (addr.port == 0 && !UserConfigParams::m_random_server_port)
addr.port = stk_config->m_server_port;
// Reserve 1 peer to deliver full server message // Reserve 1 peer to deliver full server message
m_network = new Network(NetworkConfig::get()->getMaxPlayers() + 1, m_network = new Network(ServerConfig::m_server_max_players + 1,
/*channel_limit*/EVENT_CHANNEL_COUNT, /*max_in_bandwidth*/0, /*channel_limit*/EVENT_CHANNEL_COUNT, /*max_in_bandwidth*/0,
/*max_out_bandwidth*/ 0, &addr, true/*change_port_if_bound*/); /*max_out_bandwidth*/ 0, &addr, true/*change_port_if_bound*/);
} }
@ -703,8 +705,7 @@ void STKHost::mainLoop()
if ((NetworkConfig::get()->isLAN() && is_server) || if ((NetworkConfig::get()->isLAN() && is_server) ||
NetworkConfig::get()->isPublicServer()) NetworkConfig::get()->isPublicServer())
{ {
TransportAddress address(0, TransportAddress address(0, stk_config->m_server_discovery_port);
NetworkConfig::get()->getServerDiscoveryPort());
ENetAddress eaddr = address.toEnetAddress(); ENetAddress eaddr = address.toEnetAddress();
direct_socket = new Network(1, 1, 0, 0, &eaddr); direct_socket = new Network(1, 1, 0, 0, &eaddr);
if (direct_socket->getENetHost() == NULL) if (direct_socket->getENetHost() == NULL)
@ -1022,24 +1023,20 @@ void STKHost::handleDirectSocketRequest(Network* direct_socket,
if (command == "stk-server") if (command == "stk-server")
{ {
Log::verbose("STKHost", "Received LAN server query"); Log::verbose("STKHost", "Received LAN server query");
std::string name = const std::string& name = sl->getGameSetup()->getServerNameUtf8();
StringUtils::wideToUtf8(NetworkConfig::get()->getServerName());
// Avoid buffer overflows
if (name.size() > 255)
name = name.substr(0, 255);
// Send the answer, consisting of server name, max players, // Send the answer, consisting of server name, max players,
// current players // current players
const std::string& pw = ServerConfig::m_private_server_password;
BareNetworkString s((int)name.size()+1+11); BareNetworkString s((int)name.size()+1+11);
s.addUInt32(NetworkConfig::m_server_version); s.addUInt32(ServerConfig::m_server_version);
s.encodeString(name); s.encodeString(name);
s.addUInt8(NetworkConfig::get()->getMaxPlayers()); s.addUInt8((uint8_t)ServerConfig::m_server_max_players);
s.addUInt8((uint8_t)(sl->getGameSetup()->getPlayerCount() + s.addUInt8((uint8_t)(sl->getGameSetup()->getPlayerCount() +
sl->getWaitingPlayersCount())); sl->getWaitingPlayersCount()));
s.addUInt16(m_private_port); s.addUInt16(m_private_port);
s.addUInt8((uint8_t)race_manager->getDifficulty()); s.addUInt8((uint8_t)ServerConfig::m_server_difficulty);
s.addUInt8((uint8_t)NetworkConfig::get()->getServerMode()); s.addUInt8((uint8_t)ServerConfig::m_server_mode);
s.addUInt8(!NetworkConfig::get()->getPassword().empty()); s.addUInt8(!pw.empty());
s.addUInt8((uint8_t) s.addUInt8((uint8_t)
(sl->getCurrentState() == ServerLobby::WAITING_FOR_START_GAME ? (sl->getCurrentState() == ServerLobby::WAITING_FOR_START_GAME ?
0 : 1)); 0 : 1));

View File

@ -22,6 +22,7 @@
#include "config/user_config.hpp" #include "config/user_config.hpp"
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "network/server.hpp" #include "network/server.hpp"
#include "network/server_config.hpp"
#include "network/stk_host.hpp" #include "network/stk_host.hpp"
#include "states_screens/state_manager.hpp" #include "states_screens/state_manager.hpp"
#include "states_screens/networking_lobby.hpp" #include "states_screens/networking_lobby.hpp"
@ -257,12 +258,12 @@ void CreateServerScreen::createServer()
return; return;
} }
NetworkConfig::get()->setPassword(password); ServerConfig::m_private_server_password = password;
if (!password.empty()) if (!password.empty())
password = std::string(" --server-password=") + password; password = std::string(" --server-password=") + password;
TransportAddress server_address(0x7f000001, TransportAddress server_address(0x7f000001,
NetworkConfig::get()->getServerDiscoveryPort()); stk_config->m_server_discovery_port);
auto server = std::make_shared<Server>(0/*server_id*/, name, auto server = std::make_shared<Server>(0/*server_id*/, name,
max_players, /*current_player*/0, (RaceManager::Difficulty) max_players, /*current_player*/0, (RaceManager::Difficulty)
@ -275,8 +276,8 @@ void CreateServerScreen::createServer()
// In case of a WAN game, we register this server with the // In case of a WAN game, we register this server with the
// stk server, and will get the server's id when this // stk server, and will get the server's id when this
// request is finished. // request is finished.
NetworkConfig::get()->setMaxPlayers(max_players); ServerConfig::m_server_max_players = max_players;
NetworkConfig::get()->setServerName(name); ServerConfig::m_server_name = StringUtils::xmlEncode(name);
// FIXME: Add the following fields to the create server screen // FIXME: Add the following fields to the create server screen
// FIXME: Long term we might add a 'vote' option (e.g. GP vs single race, // FIXME: Long term we might add a 'vote' option (e.g. GP vs single race,
@ -331,7 +332,7 @@ void CreateServerScreen::createServer()
NetworkConfig::get()->setServerIdFile( NetworkConfig::get()->setServerIdFile(
file_manager->getUserConfigFile(server_id_file)); file_manager->getUserConfigFile(server_id_file));
server_cfg << " --no-graphics --no-sound --stdout=server.log --type=" << server_cfg << " --stdout=server.log --mode=" <<
gamemode_widget->getSelection(PLAYER_ID_GAME_MASTER) << gamemode_widget->getSelection(PLAYER_ID_GAME_MASTER) <<
" --difficulty=" << " --difficulty=" <<
difficulty_widget->getSelection(PLAYER_ID_GAME_MASTER) << difficulty_widget->getSelection(PLAYER_ID_GAME_MASTER) <<

View File

@ -24,8 +24,8 @@
#include "guiengine/widgets/ribbon_widget.hpp" #include "guiengine/widgets/ribbon_widget.hpp"
#include "guiengine/widgets/text_box_widget.hpp" #include "guiengine/widgets/text_box_widget.hpp"
#include "network/server.hpp" #include "network/server.hpp"
#include "network/server_config.hpp"
#include "network/stk_host.hpp" #include "network/stk_host.hpp"
#include "network/network_config.hpp"
#include "states_screens/networking_lobby.hpp" #include "states_screens/networking_lobby.hpp"
#include "states_screens/state_manager.hpp" #include "states_screens/state_manager.hpp"
#include "utils/string_utils.hpp" #include "utils/string_utils.hpp"
@ -85,8 +85,7 @@ ServerInfoDialog::ServerInfoDialog(std::shared_ptr<Server> server)
server_info += L"\n"; server_info += L"\n";
//I18N: In server info dialog //I18N: In server info dialog
core::stringw mode = core::stringw mode = ServerConfig::getModeName(server->getServerMode());
NetworkConfig::get()->getModeName(server->getServerMode());
each_line = _("Game mode: %s", mode); each_line = _("Game mode: %s", mode);
server_info += each_line; server_info += each_line;
server_info += L"\n"; server_info += L"\n";
@ -148,12 +147,12 @@ void ServerInfoDialog::requestJoin()
assert(m_password != NULL); assert(m_password != NULL);
if (m_password->getText().empty()) if (m_password->getText().empty())
return; return;
NetworkConfig::get()->setPassword( ServerConfig::m_private_server_password =
StringUtils::wideToUtf8(m_password->getText())); StringUtils::wideToUtf8(m_password->getText());
} }
else else
{ {
NetworkConfig::get()->setPassword(""); ServerConfig::m_private_server_password = "";
} }
STKHost::create(); STKHost::create();
NetworkingLobby::getInstance()->setJoinedServer(m_server); NetworkingLobby::getInstance()->setJoinedServer(m_server);

View File

@ -24,6 +24,7 @@
#include "guiengine/widget.hpp" #include "guiengine/widget.hpp"
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "network/stk_host.hpp" #include "network/stk_host.hpp"
#include "network/server_config.hpp"
#include "network/servers_manager.hpp" #include "network/servers_manager.hpp"
#include "states_screens/state_manager.hpp" #include "states_screens/state_manager.hpp"
#include "states_screens/create_server_screen.hpp" #include "states_screens/create_server_screen.hpp"
@ -112,7 +113,7 @@ void OnlineProfileServers::eventCallback(Widget* widget, const std::string& name
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void OnlineProfileServers::doQuickPlay() void OnlineProfileServers::doQuickPlay()
{ {
NetworkConfig::get()->setPassword(""); ServerConfig::m_private_server_password = "";
STKHost::create(); STKHost::create();
NetworkingLobby::getInstance()->setJoinedServer(nullptr); NetworkingLobby::getInstance()->setJoinedServer(nullptr);
NetworkingLobby::getInstance()->push(); NetworkingLobby::getInstance()->push();

View File

@ -31,6 +31,7 @@
#include "network/protocols/client_lobby.hpp" #include "network/protocols/client_lobby.hpp"
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "network/server.hpp" #include "network/server.hpp"
#include "network/server_config.hpp"
#include "network/stk_host.hpp" #include "network/stk_host.hpp"
#include "network/stk_peer.hpp" #include "network/stk_peer.hpp"
#include "online/request_manager.hpp" #include "online/request_manager.hpp"
@ -259,7 +260,7 @@ void OnlineScreen::eventCallback(Widget* widget, const std::string& name,
} }
NetworkConfig::get()->setIsWAN(); NetworkConfig::get()->setIsWAN();
NetworkConfig::get()->setIsServer(false); NetworkConfig::get()->setIsServer(false);
NetworkConfig::get()->setPassword(""); ServerConfig::m_private_server_password = "";
auto server = std::make_shared<Server>(0, L"", 0, 0, 0, 0, auto server = std::make_shared<Server>(0, L"", 0, 0, 0, 0,
server_addr, false, false); server_addr, false, false);
STKHost::create(); STKHost::create();

View File

@ -27,6 +27,7 @@
#include "io/file_manager.hpp" #include "io/file_manager.hpp"
#include "network/network_config.hpp" #include "network/network_config.hpp"
#include "network/server.hpp" #include "network/server.hpp"
#include "network/server_config.hpp"
#include "network/servers_manager.hpp" #include "network/servers_manager.hpp"
#include "states_screens/dialogs/message_dialog.hpp" #include "states_screens/dialogs/message_dialog.hpp"
#include "states_screens/dialogs/server_info_dialog.hpp" #include "states_screens/dialogs/server_info_dialog.hpp"
@ -202,7 +203,7 @@ void ServerSelection::loadList()
true)); true));
core::stringw mode = core::stringw mode =
NetworkConfig::get()->getModeName(server->getServerMode()); ServerConfig::getModeName(server->getServerMode());
row.push_back(GUIEngine::ListWidget::ListCell(mode, -1, 2, true)); row.push_back(GUIEngine::ListWidget::ListCell(mode, -1, 2, true));
if (NetworkConfig::get()->isWAN()) if (NetworkConfig::get()->isWAN())

View File

@ -33,6 +33,7 @@
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <cwchar> #include <cwchar>
#include <fstream>
#include <iostream> #include <iostream>
#include <vector> #include <vector>