Exemple #1
0
void
Main::launch_game()
{

  SDLSubsystem sdl_subsystem;
  ConsoleBuffer console_buffer;

  timelog("controller");
  InputManager input_manager(g_config->keyboard_config, g_config->joystick_config);

  timelog("commandline");

  timelog("video");
  std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
  DrawingContext context(*video_system);
  init_video();

  timelog("audio");
  SoundManager sound_manager;
  sound_manager.enable_sound(g_config->sound_enabled);
  sound_manager.enable_music(g_config->music_enabled);

  Console console(console_buffer);

  timelog("scripting");
  scripting::Scripting scripting(g_config->enable_script_debugger);

  timelog("resources");
  TileManager tile_manager;
  SpriteManager sprite_manager;
  Resources resources;

  timelog("addons");
  AddonManager addon_manager("addons", g_config->addons);

  timelog(0);

  const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));

  GameManager game_manager;
  ScreenManager screen_manager;

  if(!g_config->start_level.empty()) {
    // we have a normal path specified at commandline, not a physfs path.
    // So we simply mount that path here...
    std::string dir = FileSystem::dirname(g_config->start_level);
    std::string filename = FileSystem::basename(g_config->start_level);
    std::string fileProtocol = "file://";
    std::string::size_type position = dir.find(fileProtocol);
    if(position != std::string::npos) {
      dir = dir.replace(position, fileProtocol.length(), "");
    }
    log_debug << "Adding dir: " << dir << std::endl;
    PHYSFS_mount(dir.c_str(), NULL, true);

    if(g_config->start_level.size() > 4 &&
       g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
    {
      screen_manager.push_screen(std::unique_ptr<Screen>(
                                              new worldmap::WorldMap(filename, *default_savegame)));
    } else {
      std::unique_ptr<GameSession> session (
        new GameSession(filename, *default_savegame));

      g_config->random_seed = session->get_demo_random_seed(g_config->start_demo);
      g_config->random_seed = gameRandom.srand(g_config->random_seed);
      graphicsRandom.srand(0);

      if (g_config->tux_spawn_pos)
      {
        session->get_current_sector()->player->set_pos(*g_config->tux_spawn_pos);
      }

      if(!g_config->start_demo.empty())
        session->play_demo(g_config->start_demo);

      if(!g_config->record_demo.empty())
        session->record_demo(g_config->record_demo);
      screen_manager.push_screen(std::move(session));
    }
  } else {
    screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));

    if (g_config->edit_level) {
      if (PHYSFS_exists(g_config->edit_level->c_str())) {
        std::unique_ptr<Editor> editor(new Editor());
        editor->set_level(*(g_config->edit_level));
        editor->setup();
        editor->update(0);
        screen_manager.push_screen(std::move(editor));
        MenuManager::instance().clear_menu_stack();
        sound_manager.stop_music(0.5);
      } else {
        log_warning << "Level " << *(g_config->edit_level) << " doesn't exist." << std::endl;
      }
    }
  }

  screen_manager.run(context);
}
Exemple #2
0
int
Main::run(int argc, char** argv)
{
#ifdef WIN32
	//SDL is used instead of PHYSFS because both create the same path in app data
	//However, PHYSFS is not yet initizlized, and this should be run before anything is initialized
	std::string prefpath = SDL_GetPrefPath("SuperTux", "supertux2");
	freopen((prefpath + "/console.out").c_str(), "a", stdout);
	freopen((prefpath + "/console.err").c_str(), "a", stderr);
#endif
 
  int result = 0;

  try
  {
    CommandLineArguments args;

    try
    {
      args.parse_args(argc, argv);
      g_log_level = args.get_log_level();
    }
    catch(const std::exception& err)
    {
      std::cout << "Error: " << err.what() << std::endl;
      return EXIT_FAILURE;
    }

    PhysfsSubsystem physfs_subsystem(argv[0], args.datadir, args.userdir);
    physfs_subsystem.print_search_path();

    timelog("config");
    ConfigSubsystem config_subsystem;
    args.merge_into(*g_config);

    timelog("tinygettext");
    init_tinygettext();

    switch (args.get_action())
    {
      case CommandLineArguments::PRINT_VERSION:
        args.print_version();
        return 0;

      case CommandLineArguments::PRINT_HELP:
        args.print_help(argv[0]);
        return 0;

      case CommandLineArguments::PRINT_DATADIR:
        args.print_datadir();
        return 0;

      default:
        launch_game();
        break;
    }
  }
  catch(const std::exception& e)
  {
    log_fatal << "Unexpected exception: " << e.what() << std::endl;
    result = 1;
  }
  catch(...)
  {
    log_fatal << "Unexpected exception" << std::endl;
    result = 1;
  }

  g_dictionary_manager.reset();

  return result;
}
Exemple #3
0
int
Main::run(int argc, char** argv)
{
#ifdef WIN32
	//SDL is used instead of PHYSFS because both create the same path in app data
	//However, PHYSFS is not yet initizlized, and this should be run before anything is initialized
	std::string prefpath = SDL_GetPrefPath("SuperTux", "supertux2");

	std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

	//All this conversion stuff is necessary to make this work for internationalized usernames
	std::string outpath = prefpath + u8"/console.out";
	std::wstring w_outpath = converter.from_bytes(outpath);
	_wfreopen(w_outpath.c_str(), L"a", stdout);

	std::string errpath = prefpath + u8"/console.err";
	std::wstring w_errpath = converter.from_bytes(errpath);
	_wfreopen(w_errpath.c_str(), L"a", stderr);
#endif

  // Create and install global locale
  std::locale::global(boost::locale::generator().generate(""));
  // Make boost.filesystem use it
  boost::filesystem::path::imbue(std::locale());

  int result = 0;

  try
  {
    CommandLineArguments args;

    try
    {
      args.parse_args(argc, argv);
      g_log_level = args.get_log_level();
    }
    catch(const std::exception& err)
    {
      std::cout << "Error: " << err.what() << std::endl;
      return EXIT_FAILURE;
    }

    PhysfsSubsystem physfs_subsystem(argv[0], args.datadir, args.userdir);
    physfs_subsystem.print_search_path();

    timelog("config");
    ConfigSubsystem config_subsystem;
    args.merge_into(*g_config);

    timelog("tinygettext");
    init_tinygettext();

    switch (args.get_action())
    {
      case CommandLineArguments::PRINT_VERSION:
        args.print_version();
        return 0;

      case CommandLineArguments::PRINT_HELP:
        args.print_help(argv[0]);
        return 0;

      case CommandLineArguments::PRINT_DATADIR:
        args.print_datadir();
        return 0;

      default:
        launch_game();
        break;
    }
  }
  catch(const std::exception& e)
  {
    log_fatal << "Unexpected exception: " << e.what() << std::endl;
    result = 1;
  }
  catch(...)
  {
    log_fatal << "Unexpected exception" << std::endl;
    result = 1;
  }

  g_dictionary_manager.reset();

  return result;
}
Exemple #4
0
int
main (int argc, char **argv)
{
  clock_gettime (CLOCK_REALTIME, &t0);
  char message[256];

  parse_args (argc, argv);

  // PREP - read genotype file into memory
  kjg_geno* X;
  if (B)
    {
      kjg_bedIO *bp = kjg_bedIO_bfile_fopen (GENO_FILENAME, "r");
      if (!bp)
        print_usage ("Unable to open bed/bim/fam");

      uint8_t* SNPmask = 0;
      if (SNP_MASK)
        {
          SNPmask = read_mask (bp->m, SNP_MASK);
          if (!SNPmask)
            print_usage ("Unable to read SNP mask");
        }

      uint8_t* indmask = 0;
      if (IND_MASK)
        {
          indmask = read_mask (bp->m, IND_MASK);
          if (!indmask)
            print_usage ("Unable to read individual mask");
        }

      sprintf (message, "Reading geno (%dx%d)", bp->m, bp->n);
      timelog (message);

      X = kjg_bedIO_fread_geno (bp, SNPmask, indmask);
      kjg_bedIO_fclose (bp);

      if (SNPmask)
        free (SNPmask);
      if (indmask)
        free (indmask);

      sprintf (message, "Finished reading geno (%dx%d)", X->m, X->n);
      timelog (message);
    }
  else
    {
      kjg_genoIO *gp = kjg_genoIO_fopen (GENO_FILENAME, "r");
      if (!gp)
        {
          print_usage ("Unable to open geno");
        }

      sprintf (message, "Reading geno (%dx%d)", gp->m, gp->n);
      timelog (message);

      X = kjg_genoIO_fread_geno (gp);
      kjg_genoIO_fclose (gp);
    }

  // calculate the SNP means
  timelog ("Calculating SNP allele frequencies");
  kjg_geno_set_norm (X, 0);

  // run fast PCA
  gsl_vector* eval = gsl_vector_alloc (K);
  gsl_matrix* evec = gsl_matrix_alloc (X->n, K);

  timelog ("fastPCA started");
  kjg_fpca (X, eval, evec, L, I);
  timelog ("fastPCA completed");

  FILE *fh_evec = kjg_util_fopen_suffix (OUTPUT_PREFIX, "evec", "w");
  kjg_gsl_evec_fprintf (fh_evec, eval, evec, "%g");
  fclose (fh_evec);

  timelog ("Done");
  return (0);
}
Exemple #5
0
void SqlwriteThread::run()
{
    QString databaseseq;
    QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL",databaseseq.setNum(m_index));
    database.setHostName(m_hostname);
    database.setDatabaseName(m_databasename);
    database.setUserName(m_usrname);
    database.setPassword(m_psword);

    if (!database.open())
    {
        database.close();
        qDebug()<<trUtf8("数据库打不开")<<endl;
        return ;
    }
    else
    {
        qDebug()<<trUtf8("线程内数据已经打开")<<endl;
    }

    QString i2c;
    QFile timelog("timelog"+i2c.setNum(m_index)+".txt");
    if (!timelog.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
    {
        qDebug()<<trUtf8("LOG日志没有打开")<<endl;
        return;
    }
    timelog.close();

    QSqlQuery sqlquery(database);
//    QTime timerecord;
//    timerecord.start();
    qDebug()<<"sqltest thread runing...";
    for(int i=0;i <= m_range/SQLLINE ; ++i)		//i要改成大数,同range
    {
        QString sqlstatement = "";
        int statementnum =( (i+1)*SQLLINE > m_range ) ? m_range - i*SQLLINE: SQLLINE;
        sqlstatement="insert into TestInsert("
                "id,"
                "threadnum,"
                "idinthread,"
                "Data) VALUES";
        for(int j=0; j < statementnum; j++)
        {
            QString inttemp;
            sqlstatement += "(null,";                             //id
            sqlstatement += inttemp.setNum(m_index);                //threadnum
            sqlstatement += ","+inttemp.setNum( i*SQLLINE + j + m_index*m_range );		//idinthread
            sqlstatement += ",'dagnoansdongfnalksngnalksndlfkja;ngaldkfalnlkgnaldnfja')"; //framesize
            if( j == statementnum -1) sqlstatement += ";";
            else sqlstatement += ",";
        }
        if( statementnum != 0 )
        {
            if(!sqlquery.exec(sqlstatement))
            {
                qDebug()<<"block--"<<i<<"\t\n"<<sqlquery.lastError().databaseText();
                qDebug()<<trUtf8("发生语句错误")<<sqlstatement;
                return;
            }
        }
        else
        {
            break;
        }
//        qDebug()<<i<<"--Block insert over!";
    }

//    timelog.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append);
//    QTextStream logout(&timelog);
//    logout << "Insert "<<m_range<<" Lines to SQL need time : " << timerecord.elapsed() << "(ms)\n";
//    timelog.close();
    database.close();
    qDebug()<<m_index<<"_thread run over!"<<endl;
}
CChatItem* CChatSelector::StartSession(CUpDownClient* pClient, bool bForceFocus /* true */)
{
	if (pClient == NULL || !g_App.m_pMDlg->IsRunning())
		return NULL;

	EMULE_TRY

	if (GetTabByClient(pClient) != (uint16)-1)
	{
		SetCurSel(GetTabByClient(pClient));
		if (bForceFocus)
			ShowChat();
		return NULL;
	}

	CChatItem	*pChatItem = new CChatItem();
	CRect		rcRect;

	pChatItem->m_pClient = pClient;
	pChatItem->m_pLog = new CHTRichEditCtrl;

	GetClientRect(&rcRect);
	AdjustRect(false, rcRect);
	rcRect.left += 3;
	rcRect.top += 4;
	rcRect.right -= 3;
	rcRect.bottom -= 3;

	if (GetItemCount() == 0)
		rcRect.top += 20;

	pChatItem->m_pLog->Create(WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_HSCROLL | WS_VSCROLL | ES_MULTILINE | ES_READONLY | ES_NOHIDESEL, rcRect, this, (UINT)-1);
	pChatItem->m_pLog->ModifyStyleEx(0, WS_EX_STATICEDGE, SWP_FRAMECHANGED);
	pChatItem->m_pLog->SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELONG(3, 3));
	pChatItem->m_pLog->SetFont(&g_App.m_pMDlg->m_fontDefault);
	pChatItem->m_pLog->m_dwFlags |= HTC_ISWORDWRAP;
	pChatItem->m_pLog->SetTargetDevice(NULL, 0);

	COleDateTime	timelog(COleDateTime::GetCurrentTime());
	CString			strName = pClient->GetUserName(), strCountry, strTemp;

	if (g_App.m_pIP2Country->IsIP2Country())
		strCountry.Format(_T(" (%s)"), pClient->GetCountryName());
	strTemp.Format(_T("*** %s: %s (%s: %s:%u%s) - %s\n"), 
		GetResString(IDS_CHAT_START),
		strName,
		GetResString(IDS_IP), pClient->GetFullIP(), pClient->GetUserPort(), strCountry,
		timelog.Format(_T("%c")));
	pChatItem->m_pLog->AppendText(strTemp, RGB(255, 0, 0));
	pClient->SetChatState(MS_CHATTING);
	if (pClient->IsFriend())
		pClient->m_pFriend->m_dwLastChatted = time(NULL);

	if (strName.GetLength() > 30)
	{
		strName.Truncate(30);
		strName += _T("...");
	}
	else if (strName.IsEmpty())
		strName.Format(_T("[%s]"), GetResString(IDS_UNKNOWN));

	TCITEM	tcitem;

	tcitem.mask = TCIF_PARAM | TCIF_TEXT | TCIF_IMAGE;
	tcitem.lParam = (LPARAM)pChatItem;
	tcitem.pszText = (TCHAR*)strName.GetString();
	tcitem.iImage = 0;
	
	int	iResult = InsertItem(GetItemCount(), &tcitem);

	g_App.m_pMDlg->m_wndChat.m_ctlCloseButton.EnableWindow(true);
	g_App.m_pMDlg->m_wndChat.m_ctlSendButton.EnableWindow(true);

	if (iResult != -1 && IsWindowVisible())
	{
		SetCurSel(iResult);
		pChatItem->m_pLog->SetTitle(pClient->GetUserName());
		if (bForceFocus)
			ShowChat();
	}

	return pChatItem;

	EMULE_CATCH

	return NULL;
}
void CChatSelector::ProcessMessage(CUpDownClient* pSender, const CString &strIncomingMessage)
{
	CString	strMessage = strIncomingMessage;
	int		iCurPos = 0;

	strMessage.MakeLower();

//	Ban spammers
	if ( g_App.m_pPrefs->IsCounterMeasures() &&
		( strMessage.Find(_T("di-emule")) >= 0
		|| strMessage.Find(_T("emule fx")) >= 0
		|| strMessage.Find(_T("zambor")) >= 0
		|| strMessage.Find(_T("fastest emule ever")) >= 0
		|| strMessage.Find(_T("robot from riaa")) >= 0
		|| strMessage.Find(_T("ketamine")) >= 0
		|| strMessage.Find(_T("http://www.chez.com/theworld/")) >= 0
		|| strMessage.Find(_T("http://fullspeed.to/mison")) >= 0 ) )
	{
		AddDebugLogLine(RGB_LOG_DIMMED_TXT _T("Anti-leechermods: Client %s has been banned because of spamming"), pSender->GetClientNameWithSoftware());
		pSender->Ban(BAN_CLIENT_SPAMMING);
		return;
	}

	CString	strResToken, strFilter = g_App.m_pPrefs->GetMessageFilter();

	strFilter.MakeLower();
	for (;;)
	{
		strResToken = strFilter.Tokenize(_T("|"), iCurPos);
		if (strResToken.IsEmpty())
			break;
		if (strMessage.Find(strResToken) >= 0)
		{
			AddDebugLogLine(RGB_LOG_DIMMED_TXT _T("Filtered message '%s' from client %s"), strIncomingMessage, pSender->GetClientNameWithSoftware());
			return;
		}
	}

	CChatItem	*pChatItem = GetItemByClient(pSender);
	bool		bIsNewChatWindow = false;

	if (pChatItem == NULL)
	{
		if (GetItemCount() >= 50)
		{
			AddDebugLogLine(RGB_LOG_WARNING_TXT _T("Instant Messaging: Messages limit reached"));
			return;
		}

		if (g_App.m_pPrefs->GetAcceptMessagesFrom() == 4) //no messages
			return;

		if ((g_App.m_pPrefs->GetAcceptMessagesFrom() == 2) && !pSender->IsFriend()) //only friends
			return;

		if ((g_App.m_pPrefs->GetAcceptMessagesFrom() == 3) && !pSender->IsFriend()) //log non friends
		{
			AddLogLine(false, GetResString(IDS_IM_MSGFROMCHAT) + _T(" %s: %s"), pSender->GetUserName(), strIncomingMessage);
			pSender->SetChatState(MS_NONE);
			return;
		}

		pChatItem = StartSession(pSender);
		if (pChatItem == NULL)
			return;
		bIsNewChatWindow = true;
	}
	COleDateTime	timelog(COleDateTime::GetCurrentTime());

	strMessage.Format(_T("%s (%s): "), pSender->GetUserName(), timelog.Format(_T("%c")));
	pChatItem->m_pLog->AppendText(strMessage, RGB(50, 200, 250));
	pChatItem->m_pLog->AppendText(strIncomingMessage + _T('\n'));

	if (g_App.m_pPrefs->GetAwayState())
	{
		if ((::GetTickCount() - pChatItem->m_pClient->GetAwayMessageResendCount()) > 3000)
		{ //send again only if 3 secs from last away message
			SendAwayMessage(pChatItem);
			pChatItem->m_pClient->SetAwayMessageResendCount(::GetTickCount());
		}
	}

	if ((iCurPos = GetTabByClient(pSender)) != GetCurSel())
		SetItemState(iCurPos, TCIS_HIGHLIGHTED, TCIS_HIGHLIGHTED);
	if (!g_App.m_pPrefs->GetAwayState())
	{
		BOOL	bVisible = ::IsWindowVisible(::GetParent(m_hWnd));

	//	Show statusbar indicator if Messages window isn't active or our application isn't topmost one
		if (!bVisible || (g_App.m_pMDlg->m_hWnd != ::GetForegroundWindow()))
		{
			pChatItem->m_bNotify = true;
		//	Send Notification is required
			if ( ( g_App.m_pPrefs->GetUseChatNotifier() &&
				(bIsNewChatWindow || g_App.m_pPrefs->GetNotifierPopsEveryChatMsg()) ) )
			{
				strMessage.Format(_T("%s %s:'%s'\n"), GetResString(IDS_TBN_NEWCHATMSG), pSender->GetUserName(), strIncomingMessage);
				g_App.m_pMDlg->SendMail(strMessage, true, g_App.m_pPrefs->IsSMTPInfoEnabled());
				g_App.m_pMDlg->ShowNotifier(strMessage, TBN_CHAT, false, true);
			}
		}
	}
}