Example #1
0
void IServer::Reset()
{
    m_users.Nullify();
    while (m_users.GetNumUsers() > 0) {
        try {
            User* u = &m_users.GetUser(0);
            m_users.RemoveUser(u->GetNick());
            delete u;
        } catch (std::runtime_error) {
        }
    }

    while (battles_iter->GetNumBattles() > 0) {
        battles_iter->IteratorBegin();
        IBattle* b = battles_iter->GetBattle();
        if (b != 0) {
            m_battles.RemoveBattle(b->GetBattleId());
            delete b;
        }
    }
    while (m_channels.GetNumChannels() > 0) {
        Channel* c = &m_channels.GetChannel(0);
        m_channels.RemoveChannel(c->GetName());
        delete c;
    }
}
void ServerEvents::OnUserQuit(const std::string& nick)
{
	slLogDebugFunc("");
	try {
		User& user = m_serv.GetUser(nick);
		IBattle* userbattle = user.GetBattle();
		if (userbattle) {
			int battleid = userbattle->GetID();
			try {
				if (&userbattle->GetFounder() == &user) {
					for (int i = 0; i < int(userbattle->GetNumUsers()); i++) {
						User& battleuser = userbattle->GetUser(i);
						OnUserLeftBattle(battleid, battleuser.GetNick());
					}
					OnBattleClosed(battleid);
				} else
					OnUserLeftBattle(battleid, user.GetNick());
			} catch (...) {
			}
		}
		ui().OnUserOffline(user);
		m_serv._RemoveUser(nick);
		if (useractions().DoActionOnUser(UserActions::ActNotifLogin, TowxString(nick)))
			actNotifBox(SL_MAIN_ICON, TowxString(nick) + _(" just went offline"));
	} catch (std::runtime_error& except) {
	}
}
Example #3
0
void BattleListTab::OnHost( wxCommandEvent& /*unused*/ )
{
	if ( !ui().IsConnected() )
	{
		wxLogWarning( _T( "Trying to host while offline" ) );
		customMessageBoxNoModal( SL_MAIN_ICON, _( "You cannot host a game while being offline. Please connect to a lobby server." ), _( "Not Online." ), wxOK );
		ui().ShowConnectWindow();
		return;
	}

	IBattle* battle = ui().mw().GetJoinTab().GetCurrentBattle();
	if ( battle != 0 )
	{
		if ( ui().Ask( _( "Already in a battle" ), _( "You are already in a battle.\n\nDo you want to leave current battle to start a new?" ) ) ) {
			battle->Leave();
			ui().mw().GetJoinTab().LeaveCurrentBattle();
		}
		else
		{
			return;
		}
	}

	SL::RunHostBattleDialog( this );
}
Example #4
0
void BattleListTab::AddBattle(IBattle& battle)
{
	if (battle.GetGUIListActiv() || (m_filter->GetActiv() && !m_filter->FilterBattle(battle))) {
		return;
	}
	m_battle_list->AddBattle(battle);
	battle.SetGUIListActiv(true);
	SetNumDisplayed();
}
void ServerEvents::OnForceJoinBattle(int battleid, const std::string& scriptPW)
{
	IBattle* battle = m_serv.GetCurrentBattle();
	if (battle != NULL) {
		m_serv.LeaveBattle(battle->GetID());
	}
	m_serv.JoinBattle(battleid, scriptPW);
	UiEvents::GetStatusEventSender(UiEvents::addStatusMessage).SendEvent(
	    UiEvents::StatusData(_("Automatically moved to new battle"), 1));
}
Example #6
0
ContentDownloadRequest ContentManager::WhatContentForBattleIsRequired(
		const IBattle& battle) {

	ContentDownloadRequest contentNeeded = ContentDownloadRequest();

	const std::string engineVersion = battle.GetBattleOptions().engineVersion;
	const std::string engineName = battle.GetBattleOptions().engineName;

	/*Engine is needed*/
	if (IsHavingSpringVersion(engineName, engineVersion) == false) {
		contentNeeded.EngineRequired(engineVersion);
	}

	/*Map is needed*/
	if (battle.MapExists() == false) {
		contentNeeded.MapRequired(battle.GetHostMapName(), battle.GetHostMapHash());
	}

	/*Game is needed*/
	if (battle.GameExists() == false) {
		contentNeeded.GameRequired(battle.GetHostGameName(), battle.GetHostGameHash());
	}

	return contentNeeded;
}
void ServerEvents::AutoCheckCommandSpam(IBattle& battle, User& user)
{
	const std::string nick = user.GetNick();
	MessageSpamCheck info = m_spam_check[nick];
	time_t now = time(0);
	if (info.lastmessage == now)
		info.count++;
	else
		info.count = 0;
	info.lastmessage = now;
	m_spam_check[nick] = info;
	if (info.count == 7) {
		battle.DoAction("is autokicking " + nick + " due to command spam.");
		battle.KickPlayer(user);
	}
}
Example #8
0
void MapSelectDialog::LoadPopular()
{
	wxLogDebugFunc( wxEmptyString );

	m_mapgrid->Clear();

	try {
		serverSelector().GetServer().battles_iter->IteratorBegin();
		while ( !serverSelector().GetServer().battles_iter->EOL() ) {
			IBattle* b = serverSelector().GetServer().battles_iter->GetBattle();
			const std::string mapname = b->GetHostMapName();
			assert(!mapname.empty());
			if ( b != NULL ) m_mapgrid->AddMap(TowxString(mapname));
		}
	}
	catch (...) {} // ui().GetServer may throw when disconnected...

	m_mapgrid->Refresh();
}
Example #9
0
void BattleListTab::RemoveBattle(IBattle& battle)
{
	if (&battle == m_sel_battle) {
		SelectBattle(0);
	}

	m_battle_list->RemoveBattle(battle);

	battle.SetGUIListActiv(false);
	SetNumDisplayed();
}
Example #10
0
bool Spring::Run( IBattle& battle )
{
	std::string executable = SlPaths::GetSpringBinary(battle.GetEngineVersion());
	if ( !wxFile::Exists(TowxString(executable)) ) {
		executable = SlPaths::GetSpringBinary(SlPaths::GetCompatibleVersion(battle.GetEngineVersion())); //fallback, no exact version found, try fallback version
		if ( !wxFile::Exists(TowxString(executable)) ) {
			customMessageBoxNoModal( SL_MAIN_ICON, wxFormat(_T("The spring executable version '%s' was not found at the set location '%s', please re-check.")) % battle.GetEngineVersion() % executable, _T("Executable not found") );
			ui().mw().ShowConfigure( MainWindow::OPT_PAGE_SPRING );
			return false;
		}
	}

	wxArrayString params;

	const std::string demopath = battle.GetPlayBackFilePath();
	if (!demopath.empty()){
		params.push_back(TowxString(demopath));
		return LaunchEngine(executable, params);
	}

	const wxString scripttxt = TowxString(SlPaths::GetLobbyWriteDir()) + _T("script.txt");
	try {

		wxFile f( scripttxt, wxFile::write );
		battle.DisableHostStatusInProxyMode( true );
		f.Write( WriteScriptTxt(battle) );
		battle.DisableHostStatusInProxyMode( false );
		f.Close();
	} catch ( std::exception& e ) {
		wxLogError( wxString::Format( _T("Couldn't write %s, exception caught:\n %s"), scripttxt.c_str(), TowxString( e.what() ).c_str() ) );
		return false;
	} catch (...) {
		wxLogError( wxString::Format( _T("Couldn't write %s"), scripttxt.c_str()));
		return false;
	}

	params.push_back(scripttxt);
	return LaunchEngine(executable, params);
}
Example #11
0
void BattleListTab::UpdateBattle( IBattle& battle )
{
	if ( !battle.GetGUIListActiv() ) {
		AddBattle( battle );
		return;
	}
	if ( m_filter->GetActiv() && !m_filter->FilterBattle( battle ) ) {
		RemoveBattle( battle );
		return;
	}
	m_battle_list->UpdateBattle( battle );
	if ( &battle == m_sel_battle )
		SelectBattle( m_sel_battle );
}
Example #12
0
int IconImageList::GetBattleStatusIcon( const IBattle& battle ) const
{
    unsigned idx = battle.GetInGame() << 3 | battle.IsLocked() << 2 | battle.IsFull() << 1 | battle.IsPassworded() << 0;
    static const int icons[16] = {
        /* -                                 */ ICON_OPEN_GAME,
        /* passworded                        */ ICON_OPEN_PW_GAME,
        /* full                              */ ICON_OPEN_FULL_GAME,
        /* full, passworded                  */ ICON_OPEN_FULL_PW_GAME,
        /* locked                            */ ICON_CLOSED_GAME,
        /* locked, passworded                */ ICON_CLOSED_PW_GAME,
        /* locked, full                      */ ICON_CLOSED_FULL_GAME,
        /* locked, full, passworded          */ ICON_CLOSED_FULL_PW_GAME,
        /* in game                           */ ICON_STARTED_GAME,
        /* in game, passworded               */ ICON_STARTED_GAME,
        /* in game, full                     */ ICON_STARTED_GAME,
        /* in game, full, passworded         */ ICON_STARTED_GAME,
        /* in game, locked                   */ ICON_STARTED_GAME_LOCKED,
        /* in game, locked, passworded       */ ICON_STARTED_GAME_LOCKED,
        /* in game, locked, full             */ ICON_STARTED_GAME_LOCKED,
        /* in game, locked, full, passworded */ ICON_STARTED_GAME_LOCKED,
    };
    return icons[idx];
    // return ICON_GAME_UNKNOWN;
}
Example #13
0
wxString IconImageList::GetBattleStatus( const IBattle& battle ) const
{
    unsigned idx = battle.GetInGame() << 3 | battle.IsLocked() << 2 | battle.IsFull() << 1 | battle.IsPassworded() << 0;
    static const wxString states[16] = {
        /* -                                 */ _("Game is open."),
        /* passworded                        */ _("Game is password-protected."),
        /* full                              */ _("Game is full."),
        /* full, passworded                  */ _("Game is full and password-protected."),
        /* locked                            */ _("Game is closed."),
        /* locked, passworded                */ _("Game is closed and password-protected."),
        /* locked, full                      */ _("Game is closed and full."),
        /* locked, full, passworded          */ _("Game is closed, full and password-protected."),
        /* in game                           */ _("Game is in progress."),
        /* in game, passworded               */ _("Game is in progress and password-protected."),
        /* in game, full                     */ _("Game is in progress and full."),
        /* in game, full, passworded         */ _("Game is in progress, full and password-protected."),
        /* in game, locked                   */ _("Game is in progress and closed."),
        /* in game, locked, passworded       */ _("Game is in progress, closed and password-protected."),
        /* in game, locked, full             */ _("Game is in progress, closed and full."),
        /* in game, locked, full, passworded */ _("Game is in progress, closed, full and password-protected."),
    };
    return states[idx];
    // return _T("Game has unknown status");
}
Example #14
0
void BattleListTab::UpdateBattle(IBattle& battle)
{
	if (!battle.GetGUIListActiv()) {
		AddBattle(battle);
	}
	if (m_filter->GetActiv() && !m_filter->FilterBattle(battle)) {
		RemoveBattle(battle);
		if (&battle == m_sel_battle) {
			m_sel_battle = NULL;
			SelectBattle(NULL);
			m_battle_list->SetSelectedIndex(-1);
		}
		return;
	}
	m_battle_list->UpdateBattle(battle);
	if (&battle == m_sel_battle)
		SelectBattle(m_sel_battle);
}
Example #15
0
void BattleListTab::DoJoin(IBattle& battle)
{
	wxString password = wxEmptyString;

	IBattle* curbattle = ui().mw().GetJoinTab().GetCurrentBattle();

	if (curbattle != 0 && curbattle->GetID() == battle.GetID()) {
		ui().mw().ShowTab(MainWindow::PAGE_JOIN);
		return;
	}

	if (curbattle != 0) {
		if (ui().Ask(_("Already in another battle"), _("You are already in a battle.\n\nDo you want to leave your current battle and join this one?"))) {
			curbattle->Leave();
			ui().mw().GetJoinTab().LeaveCurrentBattle();
		} else {
			return;
		}
	}

	if (battle.IsPassworded()) {
		wxPasswordEntryDialog pw(this, _("Battle password"), _("Enter password (spaces will be stripped)"));
		pw.SetFocus();
		if (pw.ShowModal() != wxID_OK) {
			return;
		}
		password = pw.GetValue();
		password.Replace(_T(" "), wxEmptyString);
	}

	if (!ui().DownloadArchives(battle)) {
		return;
	}

	battle.Join(STD_STRING(password));
}
Example #16
0
AddBotDialog::AddBotDialog( wxWindow* parent, IBattle& battle , bool singleplayer)
	: wxDialog( parent, wxID_ANY, _("Add bot"), wxDefaultPosition, wxDefaultSize, wxRESIZE_BORDER | wxDEFAULT_DIALOG_STYLE ),
	WindowAttributesPickle( _T("ADDBOTDIALOG"), this, wxSize(-1, 255) ),
	m_battle( battle ),
	m_sp(singleplayer)
{
  //this->SetSizeHints( wxDefaultSize, wxDefaultSize );
	if(battle.GetNumBots()>=2)
		SetTitle(_("Add bot: high nimber of bots can cause performance problems"));

	m_main_sizer = new wxBoxSizer( wxVERTICAL );

	wxBoxSizer* m_nick_sizer;
	m_nick_sizer = new wxBoxSizer( wxHORIZONTAL );

	m_nick_lbl = new wxStaticText( this, wxID_ANY, _("Nickname:"), wxDefaultPosition, wxDefaultSize, 0 );
	m_nick_sizer->Add( m_nick_lbl, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5 );

	int bot = 1;
	wxString botname = wxString::Format( _T("Bot%d"), bot );
	while ( m_battle.UserExists( botname ) )
	{
		bot++;
		botname = wxString::Format( _T("Bot%d"), bot );
	}

	m_nick = new wxTextCtrl( this, wxID_ANY, botname, wxDefaultPosition, wxDefaultSize, 0 );
	m_nick_sizer->Add( m_nick, 2, wxALL, 5 );

	m_main_sizer->Add( m_nick_sizer, 0, wxEXPAND, 5 );

	wxBoxSizer* m_ai_sizer;
	m_ai_sizer = new wxBoxSizer( wxHORIZONTAL );

	m_ai_lbl = new wxStaticText( this, wxID_ANY, _("AI:"), wxDefaultPosition, wxDefaultSize, 0 );
	m_ai_sizer->Add( m_ai_lbl, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5 );

	m_ai = new wxChoice( this, ADDBOT_AI );
	m_ai->SetToolTip( TE(_("Choose the AI library to use with this bot.") ) );

	m_ai_sizer->Add( m_ai, 2, wxALL, 5 );

	m_main_sizer->Add( m_ai_sizer, 0, wxEXPAND, 5 );

	if ( LSL::usync().VersionSupports( LSL::USYNC_GetSkirmishAI ) )
	{
		m_ai_infos_lst = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxLC_REPORT | wxLC_SINGLE_SEL | wxLC_NO_HEADER );
		wxListItem col;
		col.SetText( _("property") );
		col.SetImage( -1 );
		m_ai_infos_lst->InsertColumn( 0, col );
		wxListItem col2;
		col2.SetText( _("value") );
		col2.SetImage( -1 );
		m_ai_infos_lst->InsertColumn( 1, col2 );

		m_opts_list = new wxListCtrl( this, ADDBOT_OPTIONLIST, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxLC_REPORT | wxLC_SINGLE_SEL | wxLC_NO_HEADER );
		wxListItem col3;
		col3.SetText( _("property") );
		col3.SetImage( -1 );
		m_opts_list->InsertColumn( 0, col3 );
		wxListItem col4;
		col4.SetText( _("value") );
		col4.SetImage( -1 );
		m_opts_list->InsertColumn( 1, col4 );

		m_info_sizer = new wxBoxSizer(wxVERTICAL);
		m_info_sizer->Add( m_ai_infos_lst, 1, wxALL|wxEXPAND );
		m_info_sizer->Add( m_opts_list, 1, wxALL|wxEXPAND );
		m_main_sizer->Add( m_info_sizer, 1, wxALL|wxEXPAND );

	}
	else
	{
		 m_main_sizer->AddStretchSpacer();
	}

	m_buttons_sep = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
	m_main_sizer->Add( m_buttons_sep, 0, wxALL|wxEXPAND );

	wxBoxSizer* m_buttons_sizer;
	m_buttons_sizer = new wxBoxSizer( wxHORIZONTAL );

	m_cancel_btn = new wxButton( this, ADDBOT_CANCEL, _("Cancel"), wxDefaultPosition, wxSize(-1,CONTROL_HEIGHT), 0 );
	m_buttons_sizer->Add( m_cancel_btn, 0, wxALL );

	m_buttons_sizer->Add( 0, 0, 1, wxEXPAND );

	m_add_btn = new wxButton( this, ADDBOT_ADD, _("Add Bot"), wxDefaultPosition, wxSize(-1,CONTROL_HEIGHT), 0 );
	m_buttons_sizer->Add( m_add_btn, 0, wxALL );

	m_main_sizer->Add( m_buttons_sizer, 0, wxEXPAND );

	this->SetSizer( m_main_sizer );
	this->Layout();
	ReloadAIList();
	m_add_btn->SetFocus();
}
Example #17
0
wxString Spring::WriteScriptTxt( IBattle& battle ) const
{
    wxLogMessage(_T("0 WriteScriptTxt called "));

    wxString ret;

    TDFWriter tdf(ret);

    // Start generating the script.
    tdf.EnterSection( _T("GAME") );

		tdf.Append( _T("HostIP"), battle.GetHostIp() );
			if ( battle.IsFounderMe() )
			{
					if ( battle.GetNatType() == NAT_Hole_punching ) tdf.Append( _T("HostPort"), battle.GetMyInternalUdpSourcePort() );
					else tdf.Append(_T("HostPort"), battle.GetHostPort() );
			}
			else
			{
					tdf.Append( _T("HostPort"), battle.GetHostPort() );
					if ( battle.GetNatType() == NAT_Hole_punching )
					{
						tdf.Append( _T("SourcePort"), battle.GetMyInternalUdpSourcePort() );
					}
					else if ( sett().GetClientPort() != 0)
					{
						tdf.Append( _T("SourcePort"), sett().GetClientPort() ); /// this allows to play with broken router by setting SourcePort to some forwarded port.
					}
			}
			tdf.Append( _T("IsHost"), battle.IsFounderMe() );

			tdf.Append(_T("MyPlayerName"), battle.GetMe().GetNick() );

			if ( !battle.IsFounderMe() )
			{
					tdf.LeaveSection();
					return ret;
			}

			/**********************************************************************************
																		Host-only section
			**********************************************************************************/

			tdf.AppendLineBreak();

			tdf.Append(_T("ModHash"), battle.LoadMod().hash );
			tdf.Append(_T("MapHash"), battle.LoadMap().hash );

			tdf.Append( _T("Mapname"), battle.GetHostMapName() );
			tdf.Append( _T("GameType"), battle.GetHostModName() );

			tdf.AppendLineBreak();

			switch ( battle.GetBattleType() )
			{
				case BT_Played: break;
				case BT_Replay:
				{
					wxString path = battle.GetPlayBackFilePath();
					if ( path.Find(_T("/")) != wxNOT_FOUND ) path.BeforeLast(_T('/'));
					tdf.Append( _T("DemoFile"), path );
					tdf.AppendLineBreak();
					break;
				}
				case BT_Savegame:
				{
					wxString path = battle.GetPlayBackFilePath();
					if ( path.Find(_T("/")) != wxNOT_FOUND ) path.BeforeLast(_T('/'));
					tdf.Append( _T("Savefile"), path );
					tdf.AppendLineBreak();
					break;
				}
				default:
                    wxLogDebugFunc( _T("") ); break;
			}

			long startpostype;
			battle.CustomBattleOptions().getSingleValue( _T("startpostype"), OptionsWrapper::EngineOption ).ToLong( &startpostype );

			std::vector<StartPos> remap_positions;
			if ( battle.IsProxy() && ( startpostype != IBattle::ST_Pick ) && ( startpostype != IBattle::ST_Choose ) )
			{
				std::set<int> parsedteams;
				unsigned int NumUsers = battle.GetNumUsers();
				unsigned int NumTeams = 0;
				for ( unsigned int i = 0; i < NumUsers; i++ )
				{
						User& usr = battle.GetUser( i );
						UserBattleStatus& status = usr.BattleStatus();
						if ( status.spectator ) continue;
						if ( parsedteams.find( status.team ) != parsedteams.end() ) continue; // skip duplicates
						parsedteams.insert( status.team );
						NumTeams++;
				}

				MapInfo infos = battle.LoadMap().info;
				unsigned int nummapstartpositions = infos.positions.size();
				unsigned int copysize = std::min( nummapstartpositions, NumTeams );
				remap_positions = std::vector<StartPos> ( infos.positions.begin(), infos.positions.begin() + copysize ); // only add the first x positions

				if ( startpostype == IBattle::ST_Random )
				{
					random_shuffle( remap_positions.begin(), remap_positions.end() ); // shuffle the positions
				}

			}
			if ( battle.IsProxy() )
			{
				if ( ( startpostype == IBattle::ST_Random ) || ( startpostype == IBattle::ST_Fixed ) )
				{
					tdf.Append( _T("startpostype"), IBattle::ST_Pick );
				}
				else tdf.Append( _T("startpostype"), startpostype );
			}
			else tdf.Append( _T("startpostype"), startpostype );

			tdf.EnterSection( _T("mapoptions") );
				OptionsWrapper::wxStringTripleVec optlistMap = battle.CustomBattleOptions().getOptions( OptionsWrapper::MapOption );
				for (OptionsWrapper::wxStringTripleVec::const_iterator it = optlistMap.begin(); it != optlistMap.end(); ++it)
				{
						tdf.Append(it->first,it->second.second);
				}
			tdf.LeaveSection();


			tdf.EnterSection(_T("modoptions"));
				OptionsWrapper::wxStringTripleVec optlistMod = battle.CustomBattleOptions().getOptions( OptionsWrapper::ModOption );
				for (OptionsWrapper::wxStringTripleVec::const_iterator it = optlistMod.begin(); it != optlistMod.end(); ++it)
				{
						tdf.Append(it->first,it->second.second);
				}
			tdf.LeaveSection();

			std::map<wxString,int> units = battle.RestrictedUnits();
			tdf.Append( _T("NumRestrictions"), units.size());
			tdf.EnterSection( _T("RESTRICT") );
				int restrictcount = 0;
				for ( std::map<wxString, int>::iterator itor = units.begin(); itor != units.end(); itor++ )
				{
						tdf.Append(_T("Unit") + TowxString( restrictcount ), itor->first );
						tdf.Append(_T("Limit") + TowxString( restrictcount ), itor->second );
						restrictcount++;
				}
			tdf.LeaveSection();


			tdf.AppendLineBreak();

			if ( battle.IsProxy() )
			{
				tdf.Append( _T("NumPlayers"), battle.GetNumPlayers() -1 );
				tdf.Append( _T("NumUsers"), battle.GetNumUsers() -1 );
			}
			else
			{
				tdf.Append( _T("NumPlayers"), battle.GetNumPlayers() );
				tdf.Append( _T("NumUsers"), battle.GetNumUsers() );
			}

			tdf.AppendLineBreak();

			unsigned int NumUsers = battle.GetNumUsers();

			typedef std::map<int, int> ProgressiveTeamsVec;
			typedef ProgressiveTeamsVec::iterator ProgressiveTeamsVecIter;
			ProgressiveTeamsVec teams_to_sorted_teams; // original team -> progressive team
			int free_team = 0;
			std::map<User*, int> player_to_number; // player -> ordernumber
			srand ( time(NULL) );
			for ( unsigned int i = 0; i < NumUsers; i++ )
			{
					User& user = battle.GetUser( i );
					UserBattleStatus& status = user.BattleStatus();
					if ( !status.spectator )
					{
						ProgressiveTeamsVecIter itor = teams_to_sorted_teams.find ( status.team );
						if ( itor == teams_to_sorted_teams.end() )
						{
							teams_to_sorted_teams[status.team] = free_team;
							free_team++;
						}
					}
				  if ( battle.IsProxy() && ( user.GetNick() == battle.GetFounder().GetNick() ) ) continue;
					if ( status.IsBot() ) continue;
					tdf.EnterSection( _T("PLAYER") + TowxString( i ) );
							tdf.Append( _T("Name"), user.GetNick() );
							tdf.Append( _T("CountryCode"), user.GetCountry().Lower());
							tdf.Append( _T("Spectator"), status.spectator );
							tdf.Append( _T("Rank"), (int)user.GetRank() );
							tdf.Append( _T("IsFromDemo"), int(status.isfromdemo) );
							if ( !status.spectator )
							{
								tdf.Append( _T("Team"), teams_to_sorted_teams[status.team] );
							}
							else
							{
								int speccteam = 0;
								if ( teams_to_sorted_teams.size() != 0 ) speccteam = rand() % teams_to_sorted_teams.size();
								tdf.Append( _T("Team"), speccteam );
							}
					tdf.LeaveSection();
					player_to_number[&user] = i;
			}
			if ( usync().VersionSupports( IUnitSync::USYNC_GetSkirmishAI ) )
			{
				for ( unsigned int i = 0; i < NumUsers; i++ )
				{
						User& user = battle.GetUser( i );
						UserBattleStatus& status = user.BattleStatus();
						if ( !status.IsBot() ) continue;
						tdf.EnterSection( _T("AI") + TowxString( i ) );
								tdf.Append( _T("Name"), user.GetNick() ); // AI's nick;
								tdf.Append( _T("ShortName"), status.aishortname ); // AI libtype
								tdf.Append( _T("Version"), status.aiversion ); // AI libtype version
								tdf.Append( _T("Team"), teams_to_sorted_teams[status.team] );
								tdf.Append( _T("IsFromDemo"), int(status.isfromdemo) );
								tdf.Append( _T("Host"), player_to_number[&battle.GetUser( status.owner )] );
								tdf.EnterSection( _T("Options") );
									int optionmapindex = battle.CustomBattleOptions().GetAIOptionIndex( user.GetNick() );
									if ( optionmapindex > 0 )
									{
										OptionsWrapper::wxStringTripleVec optlistMod_ = battle.CustomBattleOptions().getOptions( (OptionsWrapper::GameOption)optionmapindex );
										for (OptionsWrapper::wxStringTripleVec::const_iterator it = optlistMod_.begin(); it != optlistMod_.end(); ++it)
										{
												tdf.Append(it->first,it->second.second);
										}
									}
								tdf.LeaveSection();
						tdf.LeaveSection();
						player_to_number[&user] = i;
				}
			}

			tdf.AppendLineBreak();

			std::set<int> parsedteams;
			wxArrayString sides = usync().GetSides( battle.GetHostModName() );
			for ( unsigned int i = 0; i < NumUsers; i++ )
			{
					User& usr = battle.GetUser( i );
					UserBattleStatus& status = usr.BattleStatus();
					if ( status.spectator ) continue;
					if ( parsedteams.find( status.team ) != parsedteams.end() ) continue; // skip duplicates
					parsedteams.insert( status.team );

					tdf.EnterSection( _T("TEAM") + TowxString( teams_to_sorted_teams[status.team] ) );
						if ( !usync().VersionSupports( IUnitSync::USYNC_GetSkirmishAI ) && status.IsBot() )
						{
								tdf.Append( _T("AIDLL"), status.aishortname );
								tdf.Append( _T("TeamLeader"), player_to_number[&battle.GetUser( status.owner )] ); // bot owner is the team leader
						}
						else
						{
								if ( status.IsBot() )
								{
										tdf.Append( _T("TeamLeader"), player_to_number[&battle.GetUser( status.owner )] );
								}
								else
								{
										tdf.Append( _T("TeamLeader"), player_to_number[&usr] );
								}
						}
						if ( battle.IsProxy() )
						{
							if ( startpostype == IBattle::ST_Pick )
							{
									tdf.Append(_T("StartPosX"), status.pos.x );
									tdf.Append(_T("StartPosZ"), status.pos.y );
							}
							else if ( ( startpostype == IBattle::ST_Fixed ) || ( startpostype == IBattle::ST_Random ) )
							{
									int teamnumber = teams_to_sorted_teams[status.team];
									if ( teamnumber < int(remap_positions.size()) ) // don't overflow
									{
										StartPos position = remap_positions[teamnumber];
										tdf.Append(_T("StartPosX"), position.x );
										tdf.Append(_T("StartPosZ"), position.y );
									}
							}
						}
						else
						{
							if ( startpostype == IBattle::ST_Pick )
							{
									tdf.Append(_T("StartPosX"), status.pos.x );
									tdf.Append(_T("StartPosZ"), status.pos.y );
							}
						}

						tdf.Append( _T("AllyTeam"),status.ally );

						wxString colourstring =
								TowxString( status.colour.Red()/255.0 ) + _T(' ') +
								TowxString( status.colour.Green()/255.0 ) + _T(' ') +
								TowxString( status.colour.Blue()/255.0 );
						tdf.Append( _T("RGBColor"), colourstring);

						unsigned int side = status.side;
						if ( side < sides.GetCount() ) tdf.Append( _T("Side"), sides[side] );
						tdf.Append( _T("Handicap"), status.handicap );
					tdf.LeaveSection();
			}

			tdf.AppendLineBreak();


			unsigned int maxiter = std::max( NumUsers, battle.GetLastRectIdx() + 1 );
			std::set<int> parsedallys;
			for ( unsigned int i = 0; i < maxiter; i++ )
			{

					User& usr = battle.GetUser( i );
					UserBattleStatus& status = usr.BattleStatus();
					BattleStartRect sr = battle.GetStartRect( i );
					if ( status.spectator && !sr.IsOk() ) continue;
					int ally = status.ally;
					if ( status.spectator ) ally = i;
					if ( parsedallys.find( ally ) != parsedallys.end() ) continue; // skip duplicates
					sr = battle.GetStartRect( ally );
					parsedallys.insert( ally );

					tdf.EnterSection( _T("ALLYTEAM") + TowxString( ally ) );
						tdf.Append( _T("NumAllies"), 0 );
						if ( sr.IsOk() )
						{
								const char* old_locale = std::setlocale(LC_NUMERIC, "C");

								tdf.Append( _T("StartRectLeft"), wxString::Format( _T("%.3f"), sr.left / 200.0 ) );
								tdf.Append( _T("StartRectTop"), wxString::Format( _T("%.3f"), sr.top / 200.0 ) );
								tdf.Append( _T("StartRectRight"), wxString::Format( _T("%.3f"), sr.right / 200.0 ) );
								tdf.Append( _T("StartRectBottom"), wxString::Format( _T("%.3f"), sr.bottom / 200.0 ) );

								std::setlocale(LC_NUMERIC, old_locale);
						}
					tdf.LeaveSection();
			}

    tdf.LeaveSection();

    return ret;

}
Example #18
0
bool BattleListFilter::FilterBattle(IBattle& battle)
{
	if (!m_activ)
		return true;

	if (m_filter_highlighted->IsChecked() |
	    m_filter_status_start->IsChecked() |
	    m_filter_status_locked->IsChecked() |
	    m_filter_status_pass->IsChecked() |
	    m_filter_status_full->IsChecked() |
	    m_filter_status_open->IsChecked()) {
		bool bResult = false;

		if (m_filter_highlighted->IsChecked()) {
			try {
				wxString host = TowxString(battle.GetFounder().GetNick());
				bResult = useractions().DoActionOnUser(UserActions::ActHighlight, host);

				if (!bResult)
					for (unsigned int i = 0; i < battle.GetNumUsers(); ++i) {
						wxString name = TowxString(battle.GetUser(i).GetNick());
						if (useractions().DoActionOnUser(UserActions::ActHighlight, name)) {
							bResult = true;
							break;
						}
					}
			} catch (...) {
			}
		}


		//Battle Status Check
		if (m_filter_status_start->GetValue())
			bResult |= battle.GetInGame();

		if (m_filter_status_locked->GetValue())
			bResult |= battle.IsLocked();

		if (m_filter_status_pass->GetValue())
			bResult |= battle.IsPassworded();

		if (m_filter_status_full->GetValue())
			bResult |= battle.IsFull();

		if (m_filter_status_open->GetValue())
			bResult |= (!battle.IsPassworded() && !battle.IsLocked() && !battle.GetInGame() && !battle.IsFull());

		if (bResult == false)
			return false;
	}

	//Rank Check

	/** @fixme Is `nonsenserank' useful, or can it be removed?  Why is
   * it here in the first place?
   */
	/* `Nonsense', in this context, apparently means that the battle
   * requires rank 100, exactly, AND we're filtering for values less
   * than some number.
   */
	bool nonsenserank = (m_filter_rank_mode == BUTTON_MODE_SMALLER) && (battle.GetRankNeeded() == 100);

	if (m_filter_rank_choice_value != -1 /* don't have "all" selected */
	    && !nonsenserank		     /* Nonsensical `nonsenserank' flag isn't set. */
	    && !_IntCompare(battle.GetRankNeeded(), m_filter_rank_choice_value, m_filter_rank_mode))
		return false;

	//Player Check
	if ((m_filter_player_choice_value != -1) && !_IntCompare(battle.GetNumUsers() - battle.GetSpectators(), m_filter_player_choice_value, m_filter_player_mode))
		return false;

	//MaxPlayer Check
	if ((m_filter_maxplayer_choice_value != -1) && !_IntCompare(battle.GetMaxPlayers(), m_filter_maxplayer_choice_value, m_filter_maxplayer_mode))
		return false;

	//Spectator Check
	if ((m_filter_spectator_choice_value != -1) && !_IntCompare(battle.GetSpectators(), m_filter_spectator_choice_value, m_filter_spectator_mode))
		return false;

	//Only Maps i have Check
	if (m_filter_map_show->GetValue() && !battle.MapExists())
		return false;

	//Only Mods i have Check
	if (m_filter_mod_show->GetValue() && !battle.GameExists())
		return false;

	//Strings Plain Text & RegEx Check (Case insensitiv)

	//Description:
	if (!StringMatches(TowxString(battle.GetDescription()),
			   m_filter_description_edit->GetValue(),
			   m_filter_description_expression))
		return false;

	//Host:
	try { //!TODO
		if (!StringMatches(TowxString(battle.GetFounder().GetNick()),
				   m_filter_host_edit->GetValue(),
				   m_filter_host_expression))
			return false;
	} catch (...) {
	}

	//Map:
	if (!StringMatches(TowxString(battle.GetHostMapName()),
			   m_filter_map_edit->GetValue(),
			   m_filter_map_expression))
		return false;

	//Mod:
	if (!StringMatches(TowxString(battle.GetHostGameName()),
			   m_filter_mod_edit->GetValue(),
			   m_filter_mod_expression))
		return false;

	return true;
}
Example #19
0
wxString Spring::WriteScriptTxt( IBattle& battle ) const
{
	wxLogMessage(_T("0 WriteScriptTxt called "));

	std::stringstream ret;

	LSL::TDF::TDFWriter tdf(ret);

	// Start generating the script.
	tdf.EnterSection("GAME");

	if ( battle.IsFounderMe() ) {
		tdf.Append("HostIP", ""); //Listen on all addresses for connections when hosting
		if ( battle.GetNatType() == NAT_Hole_punching ) tdf.Append("HostPort", battle.GetMyInternalUdpSourcePort() );
		else tdf.Append("HostPort", battle.GetHostPort() );
	} else {
		tdf.Append("HostIP", battle.GetHostIp() );
		tdf.Append("HostPort", battle.GetHostPort() );
		if ( battle.GetNatType() == NAT_Hole_punching ) {
			tdf.Append("SourcePort", battle.GetMyInternalUdpSourcePort() );
		} else if ( sett().GetClientPort() != 0) {
			tdf.Append("SourcePort", sett().GetClientPort() ); /// this allows to play with broken router by setting SourcePort to some forwarded port.
		}
	}
	tdf.Append("IsHost", battle.IsFounderMe() );

	User& me = battle.GetMe();
	tdf.Append("MyPlayerName", me.GetNick());

	if ( !me.BattleStatus().scriptPassword.empty() ) {
		tdf.Append("MyPasswd", me.BattleStatus().scriptPassword);
	}

	if ( !battle.IsFounderMe() ) {
		tdf.LeaveSection();
		return TowxString(ret.str());
	}

	/**********************************************************************************
																Host-only section
	**********************************************************************************/

	tdf.AppendLineBreak();

	tdf.Append("ModHash", battle.LoadMod().hash);
	tdf.Append("MapHash", battle.LoadMap().hash);

	tdf.Append("Mapname", battle.GetHostMapName());
	tdf.Append("GameType", battle.GetHostModName());

	tdf.AppendLineBreak();

	switch ( battle.GetBattleType() ) {
	case BT_Played:
		break;
	case BT_Replay: {
		wxString path = TowxString(battle.GetPlayBackFilePath());
		if ( path.Find(_T("/")) != wxNOT_FOUND ) path.BeforeLast(_T('/'));
		tdf.Append("DemoFile", STD_STRING(path));
		tdf.AppendLineBreak();
		break;
	}
	case BT_Savegame: {
		wxString path = TowxString(battle.GetPlayBackFilePath());
		if ( path.Find(_T("/")) != wxNOT_FOUND ) path.BeforeLast(_T('/'));
		tdf.Append("Savefile", STD_STRING(path));
		tdf.AppendLineBreak();
		break;
	}
	default:
		slLogDebugFunc("");
		break;
	}

	const long startpostype = LSL::Util::FromString<long>(
					  battle.CustomBattleOptions().getSingleValue("startpostype", LSL::Enum::EngineOption ));

	std::vector<LSL::StartPos> remap_positions;
	if ( battle.IsProxy() && ( startpostype != IBattle::ST_Pick ) && ( startpostype != IBattle::ST_Choose ) ) {
		std::set<int> parsedteams;
		unsigned int NumUsers = battle.GetNumUsers();
		unsigned int NumTeams = 0;
		for ( unsigned int i = 0; i < NumUsers; i++ ) {
			User& usr = battle.GetUser( i );
			UserBattleStatus& status = usr.BattleStatus();
			if ( status.spectator ) continue;
			if ( parsedteams.find( status.team ) != parsedteams.end() ) continue; // skip duplicates
			parsedteams.insert( status.team );
			NumTeams++;
		}

		LSL::MapInfo infos = battle.LoadMap().info;
		unsigned int nummapstartpositions = infos.positions.size();
		unsigned int copysize = std::min( nummapstartpositions, NumTeams );
		remap_positions = std::vector<LSL::StartPos> ( infos.positions.begin(), infos.positions.begin() + copysize ); // only add the first x positions

		if ( startpostype == IBattle::ST_Random ) {
			std::random_shuffle( remap_positions.begin(), remap_positions.end() ); // shuffle the positions
		}

	}
	if ( battle.IsProxy() ) {
		if ( ( startpostype == IBattle::ST_Random ) || ( startpostype == IBattle::ST_Fixed ) ) {
			tdf.Append("startpostype", IBattle::ST_Pick );
		} else tdf.Append("startpostype", startpostype );
	} else tdf.Append("startpostype", startpostype );

	tdf.EnterSection("mapoptions");
	for (const auto& it : battle.CustomBattleOptions().getOptions( LSL::Enum::MapOption )) {
		tdf.Append(it.first, it.second.second);
	}
	tdf.LeaveSection();


	tdf.EnterSection("modoptions");
	tdf.Append("relayhoststartpostype", startpostype ); // also save the original wanted setting
	for (const auto& it : battle.CustomBattleOptions().getOptions( LSL::Enum::ModOption )) {
		tdf.Append(it.first, it.second.second);
	}
	tdf.LeaveSection();

	std::map<std::string,int> units = battle.RestrictedUnits();
	tdf.Append("NumRestrictions", units.size());
	tdf.EnterSection("RESTRICT");
	int restrictcount = 0;
	for ( std::map<std::string, int>::const_iterator itor = units.begin(); itor != units.end(); ++itor ) {
		tdf.Append(stdprintf("Unit%d", restrictcount), itor->first );
		tdf.Append(stdprintf("Limit%d", restrictcount), itor->second );
		restrictcount++;
	}
	tdf.LeaveSection();


	tdf.AppendLineBreak();

	if ( battle.IsProxy() ) {
		tdf.Append("NumPlayers", battle.GetNumPlayers() -1 );
		tdf.Append("NumUsers", battle.GetNumUsers() -1 );
	} else {
		tdf.Append("NumPlayers", battle.GetNumPlayers() );
		tdf.Append("NumUsers", battle.GetNumUsers() );
	}

	tdf.AppendLineBreak();

	unsigned int NumUsers = battle.GetNumUsers();

	typedef std::map<int, int> ProgressiveTeamsVec;
	typedef ProgressiveTeamsVec::iterator ProgressiveTeamsVecIter;
	ProgressiveTeamsVec teams_to_sorted_teams; // original team -> progressive team
	int free_team = 0;
	std::map<User*, int> player_to_number; // player -> ordernumber
	srand ( time(NULL) );
	for ( unsigned int i = 0; i < NumUsers; i++ ) {
		User& user = battle.GetUser( i );
		UserBattleStatus& status = user.BattleStatus();
		if ( !status.spectator ) {
			ProgressiveTeamsVecIter itor = teams_to_sorted_teams.find ( status.team );
			if ( itor == teams_to_sorted_teams.end() ) {
				teams_to_sorted_teams[status.team] = free_team;
				free_team++;
			}
		}
		if ( battle.IsProxy() && ( user.GetNick() == battle.GetFounder().GetNick() ) ) continue;
		if ( status.IsBot() ) continue;
		tdf.EnterSection(stdprintf("PLAYER%d", i));
		tdf.Append("Name", user.GetNick() );
		tdf.Append("CountryCode", STD_STRING(TowxString(user.GetCountry()).Lower()));
		tdf.Append("Spectator", status.spectator );
		tdf.Append("Rank", (int)user.GetRank() );
		tdf.Append("IsFromDemo", int(status.isfromdemo) );
		if ( !status.scriptPassword.empty() ) {
			tdf.Append("Password", status.scriptPassword );
		}
		if ( !status.spectator ) {
			tdf.Append("Team", teams_to_sorted_teams[status.team] );
		} else {
			int speccteam = 0;
			if ( !teams_to_sorted_teams.empty() ) speccteam = rand() % teams_to_sorted_teams.size();
			tdf.Append("Team", speccteam );
		}
		tdf.LeaveSection();
		player_to_number[&user] = i;
	}
	for ( unsigned int i = 0; i < NumUsers; i++ ) {
		User& user = battle.GetUser( i );
		UserBattleStatus& status = user.BattleStatus();
		if ( !status.IsBot() ) continue;
		tdf.EnterSection(stdprintf("AI%d", i));
		tdf.Append("Name", user.GetNick()); // AI's nick;
		tdf.Append("ShortName", status.aishortname ); // AI libtype
		tdf.Append("Version", status.aiversion ); // AI libtype version
		tdf.Append("Team", teams_to_sorted_teams[status.team] );
		tdf.Append("IsFromDemo", int(status.isfromdemo) );
		tdf.Append("Host", player_to_number[&battle.GetUser( status.owner )] );
		tdf.EnterSection("Options");
		int optionmapindex = battle.CustomBattleOptions().GetAIOptionIndex(user.GetNick());
		if ( optionmapindex > 0 ) {
			for (const auto& it : battle.CustomBattleOptions().getOptions((LSL::Enum::GameOption)optionmapindex )) {
				tdf.Append(it.first, it.second.second);
			}
		}
		tdf.LeaveSection();
		tdf.LeaveSection();
		player_to_number[&user] = i;
	}

	tdf.AppendLineBreak();

	std::set<int> parsedteams;
	const auto sides = LSL::usync().GetSides(battle.GetHostModName());
	for ( unsigned int i = 0; i < NumUsers; i++ ) {
		User& usr = battle.GetUser( i );
		UserBattleStatus& status = usr.BattleStatus();
		if ( status.spectator ) continue;
		if ( parsedteams.find( status.team ) != parsedteams.end() ) continue; // skip duplicates
		parsedteams.insert( status.team );

		tdf.EnterSection(stdprintf("TEAM%d", teams_to_sorted_teams[status.team]));
		if ( status.IsBot() ) {
			tdf.Append("TeamLeader", player_to_number[&battle.GetUser( status.owner )] );
		} else {
			tdf.Append("TeamLeader", player_to_number[&usr] );
		}
		if ( battle.IsProxy() ) {
			if ( startpostype == IBattle::ST_Pick ) {
				tdf.Append("StartPosX", status.pos.x );
				tdf.Append("StartPosZ", status.pos.y );
			} else if ( ( startpostype == IBattle::ST_Fixed ) || ( startpostype == IBattle::ST_Random ) ) {
				int teamnumber = teams_to_sorted_teams[status.team];
				if ( teamnumber < int(remap_positions.size()) ) { // don't overflow
					LSL::StartPos position = remap_positions[teamnumber];
					tdf.Append("StartPosX", position.x );
					tdf.Append("StartPosZ", position.y );
				}
			}
		} else {
			if ( startpostype == IBattle::ST_Pick ) {
				tdf.Append("StartPosX", status.pos.x );
				tdf.Append("StartPosZ", status.pos.y );
			}
		}

		tdf.Append("AllyTeam",status.ally );

		wxString colourstring =
			TowxString( status.colour.Red()/255.0 ) + _T(' ') +
			TowxString( status.colour.Green()/255.0 ) + _T(' ') +
			TowxString( status.colour.Blue()/255.0 );
		tdf.Append("RGBColor", STD_STRING(colourstring));

		unsigned int side = status.side;
		if ( side < sides.size() ) tdf.Append("Side", sides[side] );
		tdf.Append("Handicap", status.handicap );
		tdf.LeaveSection();
	}

	tdf.AppendLineBreak();

	unsigned int maxiter = std::max( NumUsers, battle.GetLastRectIdx() + 1 );
	std::set<int> parsedallys;
	for ( unsigned int i = 0; i < maxiter; i++ ) {

		User& usr = battle.GetUser( i );
		UserBattleStatus& status = usr.BattleStatus();
		BattleStartRect sr = battle.GetStartRect( i );
		if ( status.spectator && !sr.IsOk() )
			continue;
		int ally = status.ally;
		if ( status.spectator )
			ally = i;
		if ( parsedallys.find( ally ) != parsedallys.end() )
			continue; // skip duplicates
		sr = battle.GetStartRect( ally );
		parsedallys.insert( ally );

		tdf.EnterSection( stdprintf("ALLYTEAM%d", ally));
		tdf.Append("NumAllies", 0 );
		if ( startpostype == IBattle::ST_Choose ) {
			if ( sr.IsOk() ) {
				const char* old_locale = std::setlocale(LC_NUMERIC, "C");

				tdf.Append("StartRectLeft", wxFormat( _T("%.3f") ) % ( sr.left / 200.0 ) );
				tdf.Append("StartRectTop", wxFormat( _T("%.3f") ) % ( sr.top / 200.0 ) );
				tdf.Append("StartRectRight", wxFormat( _T("%.3f") ) % ( sr.right / 200.0 ) );
				tdf.Append("StartRectBottom", wxFormat( _T("%.3f") ) % ( sr.bottom / 200.0 ) );

				std::setlocale(LC_NUMERIC, old_locale);
			}
		}
		tdf.LeaveSection();
	}

	tdf.LeaveSection();
	return TowxString(ret.str());
}