Пример #1
0
static void CleanNetIfNeeded() {
  static int mult_time = 0;
  if (session()->IsCleanNetNeeded() || std::abs(timer1() - mult_time) > 1000L) {
    cleanup_net();
    mult_time = timer1();
  }
}
void Client::addNode(v3s16 p, MapNode n)
{
	//JMutexAutoLock envlock(m_env_mutex); //bulk comment-out

	TimeTaker timer1("Client::addNode()");

	core::map<v3s16, MapBlock*> modified_blocks;

	try
	{
		//TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
		std::string st = std::string("");
		m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, st);
	}
	catch(InvalidPositionException &e)
	{}

	//TimeTaker timer2("Client::addNode(): updateMeshes");

	for(core::map<v3s16, MapBlock * >::Iterator
			i = modified_blocks.getIterator();
			i.atEnd() == false; i++)
	{
		v3s16 p = i.getNode()->getKey();
		//m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
		addUpdateMeshTaskWithEdge(p);
	}
}
Пример #3
0
QString FopLeader::Name() const
{
	QDateTime timer1( QDateTime::currentDateTime() );
	const QString TimestampsMs = QString("%1-%2-space").arg(timer1.toTime_t()).arg(timer1.toString("zzz"));
	QString j_op( QString::number( qrand() % 10000 ) );
	return Imagename(QString("/foleader/%1/%2/%3x%4").arg(TimestampsMs).arg(j_op).arg(area.size().width()).arg(area.size().height()));
}
Пример #4
0
QString Smtp::TimeStampMail()
{
    /* mail rtf Date format! http://www.faqs.org/rfcs/rfc788.html */
    QDateTime timer1( QDateTime::currentDateTime() );


    uint unixtime = timer1.toTime_t();
    QDateTime fromunix;
    fromunix.setTime_t(unixtime);


    QStringList RTFdays = QStringList() << "giorno_NULL" << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
    QStringList RTFmonth = QStringList() << "mese_NULL" << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
    QDate timeroad(dateswap("yyyy",unixtime),dateswap("M",unixtime),dateswap("d",unixtime));

    QStringList rtfd_line;
    rtfd_line.clear();
    rtfd_line.append("Date: ");
    rtfd_line.append(RTFdays.at(timeroad.dayOfWeek()));
    rtfd_line.append(", ");
    rtfd_line.append(QString::number(dateswap("d",unixtime)));
    rtfd_line.append(" ");
    rtfd_line.append(RTFmonth.at(dateswap("M",unixtime)));
    rtfd_line.append(" ");
    rtfd_line.append(QString::number(dateswap("yyyy",unixtime)));
    rtfd_line.append(" ");
    rtfd_line.append(fromunix.toString("hh:mm:ss"));
    rtfd_line.append(" +0100");

    return QString(rtfd_line.join(""));
}
Пример #5
0
int main()
{
    timer1();
    timer2();
    timer3();
    timer4();
    timer5();
    return 0;
}
Пример #6
0
void fixupSelfReferentialMacrosInAST( SgNode* node )
   {
  // DQ (3/11/2006): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup known self-referential macros:");

     FixupSelfReferentialMacrosInAST astFixupTraversal;

  // I think the default should be preorder so that the interfaces would be more uniform
     astFixupTraversal.traverse(node,preorder);
   }
Пример #7
0
void removeConstantFoldedValue( SgNode* node )
   {
  // This is the interface function called by resetConstantFoldedValues(SgNode*).

  // DQ (3/11/2006): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup Constant Folded Values (replace with original expression trees):");

     RemoveConstantFoldedValue astFixupTraversal;

#if 0
     printf ("**************************************************************** \n");
     printf ("Processing the AST (AST traversal for RemoveConstantFoldedValue) \n");
     printf ("**************************************************************** \n");
#endif

  // I think the default should be preorder so that the interfaces would be more uniform
  // astFixupTraversal.traverse(node,postorder);
     astFixupTraversal.traverse(node);

#if 0
     printf ("**************************************** \n");
     printf ("Processing the array types and bitfields \n");
     printf ("**************************************** \n");
#endif
     
     {
     TimingPerformance timer1 ("Fixup Constant Folded Values (catch all expresions via memory pool traversal):");
  // DQ (9/17/2011): Use a traversal over the memory pool so that we can catch all 
  // expressions, even those not in the AST traversal such as those in array types.
     RemoveConstantFoldedValueViaParent astFixupTraversal_2;
     astFixupTraversal_2.traverseMemoryPool();
     }
     
  // DQ (10/12/2012): Turn on the verification that expression trees have been removed...previously commented out.
#if 1
     {
     TimingPerformance timer1 ("Fixup Constant Folded Values (verifyFixup):");
     VerifyOriginalExpressionTreesSetToNull verifyFixup;
     verifyFixup.traverseMemoryPool();
     }
#endif
   }
Пример #8
0
QPixmap LoadPS(QString fn , const QString arguments_append)
{
	const QString pdfFile = convertPath(fn);
	QChar letter('A' + (qrand() % 26));
	QDateTime timer1(QDateTime::currentDateTime());
	const QString qttmpFile = _GSCACHE_+QString("%2_%1.png").arg(timer1.toString("yyyy-MM-dd-HH-mm-ss-zzz")).arg(letter);
	QFileInfo fitmp(qttmpFile);
	const int VersionGS = getGSVersion();

	QFile lastaction(fitmp.absoluteFilePath());
	lastaction.remove();

	QPixmap pm;
	int ret = -1;
	QStringList args;

	if (arguments_append.size() > 3)
	{
		args.append(arguments_append);
	}

	if (VersionGS >=8)
	{
		args.append("-sDEVICE=png16m");
		args.append("-dGraphicsAlphaBits=4");
		args.append("-r72");
		args.append("-o");
		args.append(fitmp.fileName());
		args.append(pdfFile);
	}
	else
	{
		args.append("-sDEVICE=pnggray");
		args.append("-r72x72");
		args.append("-sOutputFile="+fitmp.fileName());
		args.append("-q");
		args.append(pdfFile);
	}
	ret = callGS(args);
	//////////qDebug() << "### ret " << ret << " VersionGS->" << VersionGS;
	if (ret == 0)
	{
		QPixmap tmpimage(fitmp.absoluteFilePath());
		lastaction.remove();
		return tmpimage;
	}
	return pm;
}
Пример #9
0
void
fixupAstSymbolTables( SgNode* node )
   {
  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup symbol tables:");

  // DQ (1/31/2006): Modified to build all types in the memory pools
  // DQ (6/26/2005): The global function type symbol table should be rebuilt (since the names of templates 
  // used in qualified names of types have been reset (in post processing).
  // extern SgFunctionTypeTable Sgfunc_type_table;
  // fixupGlobalFunctionSymbolTable(Sgfunc_type_table);
     ROSE_ASSERT(SgNode::get_globalFunctionTypeTable() != NULL);
     fixupGlobalFunctionSymbolTable(SgNode::get_globalFunctionTypeTable());

  // DQ (5/16/2006): Fixup the parent of the globalFunctionTypeTable to be either the SgProject or SgFile
     if (SgNode::get_globalFunctionTypeTable()->get_parent() == NULL)
        {
          SgProject* project = isSgProject(node);
          SgFile*    file    = isSgFile(node);
          if (project != NULL || file != NULL)
               SgNode::get_globalFunctionTypeTable()->set_parent(node);
        }

  // DQ (7/25/2010): Set the parent of the global type table to the SgProject
     if (SgNode::get_globalTypeTable()->get_parent() == NULL)
        {
          SgProject* project = isSgProject(node);
          SgFile*    file    = isSgFile(node);
          if (project != NULL || file != NULL)
               SgNode::get_globalTypeTable()->set_parent(node);
        }

  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer2 ("Fixup local symbol tables:");

  // Now fixup the local symbol tables
  // This simplifies how the traversal is called!
     FixupAstSymbolTables astFixupTraversal;

  // I think the default should be preorder so that the interfaces would be more uniform
     astFixupTraversal.traverse(node,preorder);
   }
Пример #10
0
int main() {
	log() << "-- start" << std::endl;

	boost::asio::io_service io;
	boost::asio::io_service::strand strand(io);

	boost::asio::deadline_timer timer1( io, boost::posix_time::seconds(1) );
	boost::asio::deadline_timer timer2( io, boost::posix_time::seconds(1) );

	timer1.async_wait( strand.wrap( boost::bind( timer_expired, "timer1", boost::asio::placeholders::error)));
	timer2.async_wait( strand.wrap( boost::bind( timer_expired, "timer2", boost::asio::placeholders::error)));

	std::thread butler1( [&]() { io.run(); } );
	std::thread butler2( [&]() { io.run(); } );

	butler1.join();
	butler2.join();

	log() << "-- end" << std::endl;
}
Пример #11
0
void removeOriginalExpressionTrees( SgNode* node )
   {
  // This is the interface function called by resetConstantFoldedValues(SgNode*).

  // DQ (3/11/2006): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup Constant Folded Values (remove the original expression tree, leaving the constant folded values):");

     RemoveOriginalExpressionTrees astFixupTraversal;

  // I think the default should be preorder so that the interfaces would be more uniform
  // astFixupTraversal.traverse(node,preorder);

  // DQ (9/17/2011): Use a traversal over the memory pool so that we can catch all 
  // expressions, even those on in the AST traversal such as those in array types.
     astFixupTraversal.traverseMemoryPool();

#if 0
  // This verifies that we have cleared all original expression trees saved into the 
  // AST by the front-end translation into ROSE.
     VerifyOriginalExpressionTreesSetToNull verifyFixup;
     verifyFixup.traverseMemoryPool();
#endif
   }
Пример #12
0
void verifyOriginalExpressionTreesSetToNull( SgNode* node )
   {
  // This is the interface function called by resetConstantFoldedValues(SgNode*).

  // DQ (3/11/2006): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup Constant Folded Values (remove the original expression tree, leaving the constant folded values):");

  // This is a pass over the AST (but not hidden subtrees in array types and bitfield expressions).
     DetectOriginalExpressionTreeTraversal t1;
     t1.traverse(node,preorder);

  // This is a traversal over the expreesion trees in array types and bitfield expressions.
  // This is a simpler test to pass since it will not visit orphaned expression trees.
     DetectHiddenOriginalExpressionTreeTraversal t2;
     t2.traverseMemoryPool();

#if 0
  // This is a memory pool traversal over all expression and is difficult to pass since there can be ophaned expressions (which will be fixed).
  // This verifies that we have cleared all original expression trees saved into the 
  // AST by the front-end translation into ROSE.
     VerifyOriginalExpressionTreesSetToNull verifyFixup;
     verifyFixup.traverseMemoryPool();
#endif
   }
Пример #13
0
int main()
{
    //window properties
    sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "GameName", sf::Style::Fullscreen);
    pong.setMouseCursorVisible(false);
    pong.setFramerateLimit(60);

    //music
    sf::Music bgm;
    bgm.openFromFile("multimedia/audio/musica.wav");
    bgm.setPitch(1);
    bgm.setLoop(true);
    bgm.play();

    //sound
    sf::SoundBuffer buffer1;
    buffer1.loadFromFile("multimedia/audio/bounce.wav");
    sf::Sound bounce;
    bounce.setBuffer(buffer1);
    sf::SoundBuffer buffer2;
    buffer2.loadFromFile("multimedia/audio/point.wav");
    sf::Sound point;
    point.setBuffer(buffer2);

    //ncp properties
    sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6));
    ncp.setFillColor(sf::Color(50, 50, 50));
    ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 );

    //player 1 properties
    int p1Len = 100;
    sf::RectangleShape player1(sf::Vector2f(10, p1Len));
    player1.setFillColor(sf::Color(0, 0, 255));
    player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
    int player1Score = 0;

    //player 2 properties
    int p2Len = 100;
    sf::RectangleShape player2(sf::Vector2f(10, p2Len));
    player2.setFillColor(sf::Color(255, 0, 0));
    player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
    int player2Score = 0;

    //ball properties
    sf::CircleShape ball(10, 25);
    ball.setFillColor(sf::Color(255, 255, 255));
    ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
    float BALLSPEED = 2;
    float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
    float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
    float ballDiameter = ball.getRadius() * 2;

    //score-timer text
    sf::Font font;
    font.loadFromFile("fonts/LiberationSerif-Regular.ttf");
    sf::Text score1("0", font, 80);
    score1.setPosition(RENDERWIDTH / 4, 0);
    sf::Text score2("0", font, 80);
    score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
    sf::Text timer1("", font, 80);
    timer1.setPosition(0 , 5 * RENDERHEIGHT / 6);
    sf::Text timer2("", font, 80);
    timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6);
    int time1 = 0;
    int time2 = 0;

    //gameover
    sf::Text gameover("GAME OVER", font, 120);
    gameover.setColor(sf::Color::Red);
    gameover.setPosition(0, RENDERHEIGHT / 3);


    //game loop
    while(player1Score + player2Score != 3)
    {
        sf::Event event;
        while(pong.pollEvent(event))
        {
            if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
                pong.close();
        }


        //score for player one winning
        if(player1Score == player2Score + 1)
        {
            timer1.setString(convertInt(time1 += 2));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 2)
        {
            timer1.setString(convertInt(time1 += 4));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 3)
        {
            timer1.setString(convertInt(time1 += 8));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 4)
        {
            timer1.setString(convertInt(time1 += 16));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 5)
        {
            timer1.setString(convertInt(time1 += 32));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 6)
        {
            timer1.setString(convertInt(time1 += 64));
            timer2.setString(convertInt(time2 += 1));
        }

        //score on equals
        if(player1Score == player2Score)
        {
            timer1.setString(convertInt(time1 += 1));
            timer2.setString(convertInt(time2 += 1));
        }

        //score for player two winning
        if(player2Score == player1Score + 1)
        {
            timer2.setString(convertInt(time2 += 2));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 2)
        {
            timer2.setString(convertInt(time2 += 4));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 3)
        {
            timer2.setString(convertInt(time2 += 8));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 4)
        {
            timer2.setString(convertInt(time2 += 16));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 5)
        {
            timer2.setString(convertInt(time2 += 32));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 6)
        {
            timer2.setString(convertInt(time2 += 64));
            timer1.setString(convertInt(time1 += 1));
        }

        //player 1 movement
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
            player1.move(0, -10);
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
            player1.move(0, 10);

        //player 2 movement
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
            player2.move(0, -10);
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
            player2.move(0, 10);

        //player 1 and wall collision
        if(player1.getPosition().y <= 0)
            player1.setPosition(0, 0);
        if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)
            player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

        //player 2 and wall collision
        if(player2.getPosition().y <= 0)
            player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);
        if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)
            player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

        //ball and wall collision
        if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter)
        {
            ballVelY *= -1;
            bounce.play();
        }

        //ball and player 1 collision
        if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x)
        {
            if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y
                    && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y)
                    || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y
                    && ball.getPosition().y >= player1.getPosition().y)
            {
                ballVelX = (ballVelX - 1) * -1;
                bounce.play();
            }
            else
            {
                point.play();
                player2Score += 1;
                ballX = RENDERWIDTH / 2 - ball.getRadius();
                if (BALLSPEED < 8)
                    BALLSPEED += 0.5;
                ballVelX = BALLSPEED;
                score2.setString(convertInt(player2Score));
                score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
                if (p2Len > 30)
                    p2Len -= 10;
                player2.setSize(sf::Vector2f(10, p2Len));
                if (p1Len < 80)
                    p1Len += 10;
                player1.setSize(sf::Vector2f(10, p1Len));
            }
        }

        //ball and player 2 collision
        if (ball.getPosition().x + ballDiameter >= player2.getPosition().x)
        {
            if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y
                    && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y)
                    || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y
                    && ball.getPosition().y >= player2.getPosition().y)
            {
                ballVelX = (ballVelX + 1) * -1;
                bounce.play();
            }
            else
            {
                point.play();
                player1Score += 1;
                ballX = RENDERWIDTH / 2 - ball.getRadius();
                if (BALLSPEED < 8)
                    BALLSPEED += 0.5;
                ballVelX = -BALLSPEED;
                score1.setString(convertInt(player1Score));
                if (p1Len > 30)
                    p1Len -= 10;
                player1.setSize(sf::Vector2f(10, p1Len));
                if (p2Len < 80)
                    p2Len += 10;
                player2.setSize(sf::Vector2f(10, p2Len));
            }
        }

        //ball position update
        ballX += ballVelX;
        ballY += ballVelY;
        ball.setPosition(ballX, ballY);

        //render updates
        pong.clear();
        pong.draw(score1);
        pong.draw(timer1);
        pong.draw(timer2);
        pong.draw(score2);
        pong.draw(player1);
        pong.draw(player2);
        pong.draw(ball);
        pong.draw(ncp);
        pong.display();

        while(player1Score + player2Score == 3)
        {
            if(player1Score > player2Score)
                timer1.setString(convertInt(time1 += 10000));
            if(player1Score < player2Score)
                timer2.setString(convertInt(time2 += 10000));

            pong.clear(sf::Color::Black);
            pong.draw(score1);
            pong.draw(timer1);
            pong.draw(timer2);
            pong.draw(score2);
            pong.draw(gameover);
            pong.display();

            counter(3);
            break;
        }

    }

    std::stringstream ss;
    ss.str (timer1.getString());
    std::string scorePlayer1 = ss.str();
    ss.str (timer2.getString());
    std::string scorePlayer2 = ss.str();
    std::cout << "Final Score:" << '\n';
    std::cout << "Player1: " + scorePlayer1 << '\n';
    std::cout << "Player2: " + scorePlayer2 << '\n';


    std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app);
    if (myfile.is_open())
    {
        myfile << scorePlayer1 << std::endl;
        myfile << scorePlayer2 << std::endl;
        myfile.close();
    }
    else std::cout << "Unable to open file";

    return 0;
}
Пример #14
0
int main(){
  
////////////////////GAME PROPERTIES///////////////////////////////////

	//window properties
	sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "Tungu");
	pong.setMouseCursorVisible(false);
	pong.setFramerateLimit(60);

	//music
	sf::Music bgm;
	bgm.openFromFile("multimedia/audio/background.wav");
	bgm.setPitch(1.5);
	bgm.setLoop(true);
	bgm.play();

	//sound
	sf::SoundBuffer buffer1;
	buffer1.loadFromFile("multimedia/audio/bounce.wav");
	sf::Sound bounce;
	bounce.setBuffer(buffer1);
	sf::SoundBuffer buffer2;
	buffer2.loadFromFile("multimedia/audio/point.wav");
	sf::Sound point;
	point.setBuffer(buffer2);
	
	//ncp properties
	sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6));
	ncp.setFillColor(sf::Color(50, 50, 50));
	ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 );

	//player 1 properties
	int p1Len = 100;
	sf::RectangleShape player1(sf::Vector2f(15, p1Len));
	player1.setFillColor(sf::Color(0, 0, 255));
	player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
	int player1Score = 0;

	//player 2 properties
	int p2Len = 100;
	sf::RectangleShape player2(sf::Vector2f(15, p2Len));
	player2.setFillColor(sf::Color(0, 255, 0));
	player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
	int player2Score = 0;

	//ball properties
	sf::CircleShape ball(10, 25);
	ball.setFillColor(sf::Color(255, 255, 255));
	ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
	float BALLSPEED = 15;
	float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
	float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
	float ballDiameter = ball.getRadius() * 2;
	
	//score-timer text
	sf::Font font;
	font.loadFromFile("fonts/LiberationSerif-Regular.ttf");
	sf::Text score1("0", font, 80);
	score1.setPosition(RENDERWIDTH / 4, 0);
	sf::Text score2("0", font, 80);
	score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
	sf::Text timer1("", font, 50);
	timer1.setPosition(0 , 5 * RENDERHEIGHT / 6);
	sf::Text timer2("", font, 50);
	timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6);
	int time1 = 0;
	int time2 = 0;
	
	//gameover
	sf::Text gameover("GAME OVER", font, 120);
	gameover.setColor(sf::Color::Red);
	gameover.setPosition(0, RENDERHEIGHT / 3);
	
		
	///////////////CAMERA FUNTIONS//////////////////////

      CvCapture* capture =0;   
    
      capture = cvCaptureFromCAM(0);


     	 if(!capture){

		printf("Capture failure\n");

		return -1;
      }
      
      IplImage* frame=0;

      frame = cvQueryFrame(capture);  
         
      if(!frame) return -1;
  
     //create a blank image and assigned to 'imgTracking' which has the same size of original video

     imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);

     cvZero(imgTracking); //covert the image, 'imgTracking' to black

     //cvNamedWindow("Player1"); 
    
     ///cvNamedWindow("Player2");

      //iterate through each frames of the video
     
      while(player1Score + player2Score != 7){

		frame = cvQueryFrame(capture); 
          
		if(!frame) break;

		frame=cvCloneImage(frame); 
            
		cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

			/////////////////// Player 1 ////////////////////

			IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 

			cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV

			IplImage* imgThresh = GetThresholdedImage(imgHSV, 85, 143, 40, 116, 256, 159); //guante cyan
	 
			cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
	    
			player100 =  trackObject(imgThresh, 255, 0, 0, 1);

			/////////////////// Player 2 ////////////////////

			IplImage* imgHSV2 = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
	    
			cvCvtColor(frame, imgHSV2, CV_BGR2HSV);//Change the color format from BGR to HSV

			IplImage* imgThresh2 = GetThresholdedImage(imgHSV2, 26, 145, 31, 73, 256, 111); //guante verde

 			cvSmooth(imgThresh2, imgThresh2, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

			player200 = trackObject(imgThresh2, 0, 255, 0, 2);

            	// Add the tracking image and the frame

		cvAdd(frame, imgTracking, frame);

		//cvShowImage("Player1", imgThresh);
 
		//cvShowImage("Player2", imgThresh2); 
		
		cvMoveWindow("Video", 1800, 0);

		cvResizeWindow("Video", 100, 240);
           
		cvShowImage("Video", frame);
           
           //Clean up used images

           cvReleaseImage(&imgHSV);

	   cvReleaseImage(&imgHSV2);

           cvReleaseImage(&imgThresh);

	   cvReleaseImage(&imgThresh2);   
          
           cvReleaseImage(&frame);

            //Wait 10mS
            int c = cvWaitKey(10);

            //If 'ESC' is pressed, break the loop
            if((char)c==27 ) break;  


/////////////////////////////Scores///////////////////////////////////

		//score for player one winning
		if(player1Score == player2Score + 1)
		{
		    timer1.setString(convertInt(time1 += 2));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 2)
		{
		    timer1.setString(convertInt(time1 += 4));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 3)
		{
		    timer1.setString(convertInt(time1 += 8));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 4)
		{
		    timer1.setString(convertInt(time1 += 16));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 5)
		{
		    timer1.setString(convertInt(time1 += 32));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 6)
		{
		    timer1.setString(convertInt(time1 += 64));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		//score on equals
		if(player1Score == player2Score)
		{
		    timer1.setString(convertInt(time1 += 1));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		//score for player two winning
		if(player2Score == player1Score + 1)
		{
		    timer2.setString(convertInt(time2 += 2));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 2)
		{
		    timer2.setString(convertInt(time2 += 4));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 3)
		{
		    timer2.setString(convertInt(time2 += 8));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 4)
		{
		    timer2.setString(convertInt(time2 += 16));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 5)
		{
		    timer2.setString(convertInt(time2 += 32));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 6)
		{
		    timer2.setString(convertInt(time2 += 64));
		    timer1.setString(convertInt(time1 += 1));
		}

//////////////////////////////Game////////////////////////////////////

		//player 1 movement muy lento
		
		if(player100==6)
			
			player1.move(0, -(vel-3));

		else if(player100==-6)

			player1.move(0, vel-3);

		//player 1 movement LENTO	
		
		if(player100==1)
			
			player1.move(0, -vel);

		else if(player100==-1)

			player1.move(0, vel);


		//player 1 movement MEDIO
		
		if(player100==2)
			
			player1.move(0, -(vel+10));

		else if(player100==-2)

			player1.move(0, vel+10);

		//player 1 movement RAPIDO
		
		if(player100==3)
			
			player1.move(0, -(vel+20));

		else if(player100==-3)

			player1.move(0, vel+20);

		//player 1 movement muy rapido
		
		if(player100==4)
			
			player1.move(0, -(vel+25));

		else if(player100==-4)

			player1.move(0, vel+25);

		//player 1 movement Extreme
		
		if(player100==5)
			
			player1.move(0, -(vel+30));

		else if(player100==-5)

			player1.move(0, vel+30);

		
		//MOVIMIENTO GOLPE PLAYER1

		if(player100==0)

			player1.move(0,0);
			
		
	
		if (player1.getPosition().x <= 10){

		if(player100==22)
			
			player1.move(10, 0);
			
			
		}


		//player 2 movement muy LENTO

		if(player200==6)

			player2.move(0, -(vel-3));

		else if(player200==-6)

			player2.move(0, vel-3);

		//player 2 movement LENTO

		if(player200==1)

			player2.move(0, -vel);

		else if(player200==-1)

			player2.move(0, vel);

		//player 2 movement MEDIO

		if(player200==2)

			player2.move(0, -(vel+10));

		else if(player200==-2)

			player2.move(0, vel+10);

		//player 2 movement RAPIDO

		if(player200==3)

			player2.move(0, -(vel+20));

		else if(player200==-3)

			player2.move(0, vel+20);

		//player 2 movement muy rapido

		if(player200==4)

			player2.move(0, -(vel+25));

		else if(player200==-4)

			player2.move(0, vel+25);

		//player 2 movement Extreme

		if(player200==5)
			player2.move(0, -(vel+30));

		else if(player200==-5)

			player2.move(0, vel+30);

		
		if(player200==0) 

			player2.move(0,0);

		//MOVIMIENTO GOLPE PLAYER2
		
		if (player2.getPosition().x >= RENDERWIDTH-player2.getSize().x-10){
			  
		if(player200==-22)
			
			player2.move(-10, 0);
			
			
		}

		//player 1 and wall collision

		if(player1.getPosition().y <= 0)

			player1.setPosition(0, 0);

		if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)

			player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

		//PLAYER1 AND WALL BACK COLLISION

		if(player1.getPosition().x != 0)

			player1.move(-1,0);
		
		//PLAYER2 AND WALL BACK COLLISION

		if(player2.getPosition().x != RENDERWIDTH-player2.getSize().x)

			player2.move(1,0);
		
		//player 2 and wall collision

		if(player2.getPosition().y <= 0)

			player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);

		if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)

			player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

		//ball and wall collision

		if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter){


			ballVelY *= -1;

			bounce.play();

		}

		//ball and player 1 collision

		if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x){


			if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y){


	if (player1.getPosition().x > 14){

				ballVelX = (ballVelX - 5) * -1;

				ball.setFillColor(sf::Color(255,0,0));

				
			}

	else if (player1.getPosition().x <= 14){

				ballVelX = (ballVelX - 3) * -1;

				ball.setFillColor(sf::Color(0,0,255));

				bounce.play();
}
			

			}

			else{
				ball.setFillColor(sf::Color(255,255,255));

				point.play();

				player2Score += 1;  

				ballX = RENDERWIDTH / 2 - ball.getRadius();

				if (BALLSPEED < 8)

					BALLSPEED += 0.2;

				ballVelX = BALLSPEED;

				score2.setString(convertInt(player2Score));

				score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);

				if (p2Len > 40)

					p2Len -= 10;

				player2.setSize(sf::Vector2f(15, p2Len));

				if (p1Len < 100)

					p1Len += 10;

				player1.setSize(sf::Vector2f(15, p1Len));
				
			}
		}

		//ball and player 2 collision

		if (ball.getPosition().x + ballDiameter >= player2.getPosition().x){

		
			if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y){
			


				if (player2.getPosition().x < (RENDERWIDTH-9-player2.getSize().x)){

					ballVelX = (ballVelX + 5) * -1;

					ball.setFillColor(sf::Color(255,0,0));

					
				
				}

				else if (player2.getPosition().x >= (RENDERWIDTH-9-player2.getSize().x)){

					ballVelX = (ballVelX + 3) * -1;

					ball.setFillColor(sf::Color(0,255,0));

					bounce.play();
			}
		}
				
			
				else{
			
					ball.setFillColor(sf::Color(255,255,255));

					point.play();

					player1Score += 1;

					ballX = RENDERWIDTH / 2 - ball.getRadius();

					if (BALLSPEED < 8)

						BALLSPEED += 0.5;

					ballVelX = -BALLSPEED;

					score1.setString(convertInt(player1Score));

					if (p1Len > 40)
						p1Len -= 10;

					player1.setSize(sf::Vector2f(15, p1Len));

					if (p2Len < 100)

						p2Len += 10;

					player2.setSize(sf::Vector2f(15, p2Len));
			}
		}

		//ball position update
		ballX += ballVelX;
		ballY += ballVelY;
		ball.setPosition(ballX, ballY);

		//render updates
		
		pong.clear();
		pong.draw(score1);
		pong.draw(timer1);
		pong.draw(timer2);
		pong.draw(score2);
		pong.draw(player1);
		pong.draw(player2);
		pong.draw(ball);
		pong.draw(ncp);
		pong.display();


		while(player1Score + player2Score == 7){

			if(player1Score > player2Score)
				timer1.setString(convertInt(time1 += 500));
			if(player1Score < player2Score)
				timer2.setString(convertInt(time2 += 500));
		
			pong.clear(sf::Color::Black);
			pong.draw(score1);
			pong.draw(timer1);
			pong.draw(timer2);
			pong.draw(score2);
			pong.draw(gameover);
			pong.display();

			counter(3);
			break;
		}

/////////////////////Finish Game/////////////////////////////////


    
      }

	std::stringstream ss;
	ss.str (timer1.getString());
	std::string scorePlayer1 = ss.str();
	ss.str (timer2.getString());
	std::string scorePlayer2 = ss.str();
	std::cout << "Final Score:" << '\n';
	std::cout << "Player1: " + scorePlayer1 << '\n';
	std::cout << "Player2: " + scorePlayer2 << '\n';

	
	std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app);
  	if (myfile.is_open())
  	{
  		myfile << scorePlayer1 << std::endl;
    		myfile << scorePlayer2 << std::endl;
    		myfile.close();
  	}

  	else std::cout << "Unable to open file";

      cvDestroyAllWindows() ;
      cvReleaseImage(&imgTracking);
      cvReleaseCapture(&capture);     

      return 0;
}
Пример #15
0
void fixupEdgBugDuplicateVariablesInAST()
   {
  // DQ (3/11/2006): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup known EDG bug where some variable declarations are dropped from the source sequence lists:");

     std::set<SgVariableDeclaration*> declarations_to_remove;

  // Loop over all variables added using the convert_field_use() function.
     std::set<SgVariableDeclaration*>::iterator i = nodesAddedWithinFieldUseSet.begin();
     while (i != nodesAddedWithinFieldUseSet.end())
        {
          SgVariableDeclaration* var_decl = *i;
          SgName name = var_decl->get_variables()[0]->get_name();

          SgClassDefinition* classDefinition = isSgClassDefinition(var_decl->get_parent());
          ROSE_ASSERT(classDefinition != NULL);

          std::vector<SgDeclarationStatement*> & members = classDefinition->get_members();

       // Loop over all data members in the class.
          std::vector<SgDeclarationStatement*>::iterator j = members.begin();
          while (j != members.end())
             {
               SgVariableDeclaration* possible_matching_variable_declaration = isSgVariableDeclaration(*j);
               if (possible_matching_variable_declaration != NULL && possible_matching_variable_declaration != var_decl)
                  {
                    if (possible_matching_variable_declaration->get_variables()[0]->get_name() == name)
                       {
#if 0
                         printf ("matching variable declaration found for name = %s \n",name.str());
#endif
                         declarations_to_remove.insert(var_decl);
                       }
                  }
 
               j++;
             }

          i++;
        }

  // Now remove all of the variable declarations that we detected to be duplicates.
     std::set<SgVariableDeclaration*>::iterator k = declarations_to_remove.begin();
     while (k != declarations_to_remove.end())
        {
          SgDeclarationStatement* var_decl = *k;

          SgClassDefinition* classDefinition = isSgClassDefinition(var_decl->get_parent());
          ROSE_ASSERT(classDefinition != NULL);

          std::vector<SgDeclarationStatement*> myvector;
          myvector.push_back(*k);

          std::vector<SgDeclarationStatement*> & members = classDefinition->get_members();

       // members.erase(*k);
       // members.erase(myvector.begin(),myvector.end());

       // This is the remove/erase idiom.
          members.erase(remove(members.begin(), members.end(), *k), members.end());

          k++;
        }

   }
Пример #16
0
int runtime()
{
	justevaled=false;
	if(peakCount>9 && running)
	{
		running = false;
		FinishUp();
		return 1;
	}

	if(timer1(T1)<sampleTime) return false;
	clearTimer(T1);
	double refVal = input;
	justevaled=true;
	if(!running)
	{ //initialize working variables the first time around
		peakType = 0;
		peakCount=0;
		justchanged=false;
		absMax=refVal;
		absMin=refVal;
		setpoint = refVal;
		running = true;
		outputStart = output;
		output = outputStart+oStep;
	}
	else
	{
		if(refVal>absMax)absMax=refVal;
		if(refVal<absMin)absMin=refVal;
	}

	//oscillate the output base on the input's relation to the setpoint

	if(refVal>setpoint+noiseBand) *output = outputStart-oStep;
	else if (refVal<setpoint-noiseBand) *output = outputStart+oStep;


  //bool isMax=true, isMin=true;
  isMax=true;isMin=true;
  //id peaks
  for(int i=nLookBack-1;i>=0;i--)
  {
    double val = lastInputs[i];
    if(isMax) isMax = refVal>val;
    if(isMin) isMin = refVal<val;
    lastInputs[i+1] = lastInputs[i];
  }
  lastInputs[0] = refVal;
  if(nLookBack<9)
  {  //we don't want to trust the maxes or mins until the inputs array has been filled
	return 0;
	}

  if(isMax)
  {
    if(peakType==0)peakType=1;
    if(peakType==-1)
    {
      peakType = 1;
      justchanged=true;
      peak2 = peak1;
    }
    peak1 = now;
    peaks[peakCount] = refVal;

  }
  else if(isMin)
  {
    if(peakType==0)peakType=-1;
    if(peakType==1)
    {
      peakType=-1;
      peakCount++;
      justchanged=true;
    }

    if(peakCount<10)peaks[peakCount] = refVal;
  }

  if(justchanged && peakCount>2)
  { //we've transitioned.  check if we can autotune based on the last peaks
    double avgSeparation = (abs(peaks[peakCount-1]-peaks[peakCount-2])+abs(peaks[peakCount-2]-peaks[peakCount-3]))/2;
    if( avgSeparation < 0.05*(absMax-absMin))
    {
		FinishUp();
      running = false;
	  return 1;

    }
  }
   justchanged=false;
	return 0;
}
Пример #17
0
static void sockevent1(uint64_t id, int fd, int revents, void *ud) {
  struct tasklet *self = (struct tasklet *)ud;

  //TRACE("[%s] sockevent1() id=%lx fd=%d revents=%x\n", self->task_path, id, fd, revents);

  self->stat.sockevent1_evct++;

  int recvct = 0;

  if (revents & POLLIN) {

    int nnsk = -1;
    if (fd == self->nn.sub_efd) {
      nnsk = self->nn.sub;
    } else if (fd == self->nn.bsub_efd) {
      nnsk = self->nn.bsub;
      self->stat.sockevent1_evct_bsub++;
    }

    if (nnsk >= 0) {
      int r;
#if USE_NN_MSG
      char *nnmsg = NULL;
      r = nn_recv(nnsk, &nnmsg, NN_MSG, NN_DONTWAIT);
#else
      char nnmsg[2048];
      r = nn_recv(nnsk, &nnmsg, sizeof(nnmsg), NN_DONTWAIT);
#endif
      if (r < 0) {
	switch (errno) {
	case EAGAIN:
	case EINTR:
	  self->stat.msg_recv_again++;
#if USE_NN_MSG
	  RW_ASSERT(!nnmsg);
#endif
	  break;
	default:
	  self->stat.msg_recv_err++;
	  self->stat.msg_recv_err_lasterrno = errno;
	  printf("[%s] + nn_recv(sk=%d) err %d %s\n", self->task_path, nnsk, errno, strerror(errno));
	}
      } else {
	recvct++;
	self->stat.msg_recv++;
	int i=0;
	while (i < r && nnmsg[i++]) { }
	if ((i + (int)sizeof(rwmsg_header_t)) <= r) {
	  rwmsg_header_t *hdr = (rwmsg_header_t *)&nnmsg[i];
	  char *payload = &nnmsg[i+sizeof(rwmsg_header_t)];
	  int paylen = r - (i + sizeof(rwmsg_header_t));
	  paylen=paylen;
	  payload=payload;
	  int toss = (self->wantblockmsg && hdr->rwmsg_type == RSP && hdr->rwmsg_ser != self->wantblockmsg);
	  TRACE ("[%s] + %s nn_recv(sk=%d/%s) to '%s' ser %u typ %s ret '%s' pay len %d '%s' \n",
		  self->task_path,
		  toss ? "TOSS" : "",
		  nnsk,
		  (nnsk == self->nn.bsub ? "bsub" : nnsk == self->nn.sub ? "sub" : "???"),
		  nnmsg,
		  hdr->rwmsg_ser,
		  hdr->rwmsg_type == REQ ? "REQ" : hdr->rwmsg_type == RSP ? "RSP" : "XXX",
		  hdr->rwmsg_ret,
		  paylen,
		  payload);

	  if (!toss) {
	    switch (hdr->rwmsg_type) {
	    case RSP:
	      self->stat.rsp_recv++;
	      if (nnsk == self->nn.bsub) {
		if (hdr->rwmsg_ser == self->wantblockmsg) {
		  self->stat.rsp_recv_blocking++;
		  self->wantblockmsg = 0;
		  /* CAUTION need to return right away */
		} else {
		  self->stat.rsp_recv_blocking_unk++;
		}
	      } else {
		/* Call timer1 to put some more messages outstanding.  Do not block. */
		int saveblocker = self->blocker;
		self->blocker = 0;
		timer1(0, self);
		self->blocker = saveblocker;
	      }
	    default:
	      break;
	    case REQ:
	      {
		int blocking =  (hdr->rwmsg_ret[3] == 'B');
		self->stat.req_recv++;
		if (blocking) {
		  self->stat.req_recv_blocking++;
		}
		if (0 && blocking) {
		  /* don't answer, to try timeout */
		  goto meh;
		}
		hdr->rwmsg_type = RSP;
		struct nn_iovec iov[3] = {
		  { .iov_base = hdr->rwmsg_ret, .iov_len = strlen(hdr->rwmsg_ret)+1 },
		  { .iov_base = hdr, .iov_len = sizeof(*hdr) },
		  { .iov_base = "This is a response payload.", .iov_len = 28 }
		};
		struct nn_msghdr msghdr = {
		  .msg_iov = iov,
		  .msg_iovlen = 3
		};
		
		TRACE("[%s] + nn_sendmsg sent %s rsp ser %u to %s\n", 
		       self->task_path, 
		       blocking ? "blocking" : "nonblocking",
		       hdr->rwmsg_ser,
		       hdr->rwmsg_ret);

		int r = nn_sendmsg(self->nn.pub, &msghdr, NN_DONTWAIT);
		if (r < 0) {
		  switch (errno) {
		  case EAGAIN:
		  case EINTR:
		    self->stat.rsp_sent_again++;
		    // TBD
		    break;
		  default:
		    self->stat.rsp_sent_err++;
		    self->stat.rsp_sent_err_lasterrno = errno;
		    printf("[%s] + nn_sendmsg errno=%u %s\n", self->task_path, errno, strerror(errno));
		    break;
		  }
		} else {
		  self->stat.rsp_sent++;
		  if (blocking) {
		    self->stat.rsp_sent_blocking++;
		  }
		}
	      }
	      break;
	    }
	  } else {
Пример #18
0
int main (int argc, char** argv)
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " <num-iter>" << std::endl;
        return EXIT_FAILURE;
    }

    const unsigned NUM_ITER = atoi(argv[1]);

    // open first face in the font
    FT_Library ft_library = 0;
    FT_Error error = FT_Init_FreeType(&ft_library);
    if (error) throw std::runtime_error("Failed to initialize FreeType2 library");

    FT_Face ft_face[NUM_EXAMPLES];
    FT_New_Face(ft_library, "fonts/DejaVuSerif.ttf", 0, &ft_face[ENGLISH]);
    FT_New_Face(ft_library, "fonts/amiri-0.104/amiri-regular.ttf", 0, &ft_face[ARABIC]);
    FT_New_Face(ft_library, "fonts/fireflysung-1.3.0/fireflysung.ttf", 0, &ft_face[CHINESE]);

    // Get our harfbuzz font structs
    hb_font_t *hb_ft_font[NUM_EXAMPLES];
    hb_ft_font[ENGLISH] = hb_ft_font_create(ft_face[ENGLISH], NULL);
    hb_ft_font[ARABIC]  = hb_ft_font_create(ft_face[ARABIC] , NULL);
    hb_ft_font[CHINESE] = hb_ft_font_create(ft_face[CHINESE], NULL);

    {
        std::cerr << "Starting ICU shaping:" << std::endl;
        progress_timer timer1(std::clog,"ICU shaping done");
        UErrorCode err = U_ZERO_ERROR;
        for (unsigned i = 0; i < NUM_ITER; ++i)
        {
            for (unsigned j = 0; j < NUM_EXAMPLES; ++j)
            {
                UnicodeString text = UnicodeString::fromUTF8(texts[j]);
                int32_t length = text.length();
                UnicodeString reordered;
                UnicodeString shaped;
                UBiDi *bidi = ubidi_openSized(length, 0, &err);
                ubidi_setPara(bidi, text.getBuffer(), length, UBIDI_DEFAULT_LTR, 0, &err);
                ubidi_writeReordered(bidi, reordered.getBuffer(length),
                                     length, UBIDI_DO_MIRRORING, &err);
                ubidi_close(bidi);
                reordered.releaseBuffer(length);
                u_shapeArabic(reordered.getBuffer(), length,
                              shaped.getBuffer(length), length,
                              U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR |
                              U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err);
                shaped.releaseBuffer(length);
                if (U_SUCCESS(err))
                {
                    U_NAMESPACE_QUALIFIER StringCharacterIterator iter(shaped);
                    for (iter.setToStart(); iter.hasNext();)
                    {
                        UChar ch = iter.nextPostInc();
                        int32_t glyph_index = FT_Get_Char_Index(ft_face[j], ch);
                        if (i == 0)
                        {
                            std::cerr << glyph_index <<  ":";
                        }
                    }
                    if (i == 0) std::cerr << std::endl;
                }
            }
        }
    }

    {
        const char **shaper_list = hb_shape_list_shapers();
        for ( ;*shaper_list; shaper_list++)
        {
            std::cerr << *shaper_list << std::endl;
        }

        std::cerr << "Starting Harfbuzz shaping" << std::endl;
        progress_timer timer2(std::clog,"Harfbuzz shaping done");
        const char* const shapers[]  = { /*"ot",*/"fallback" };
        hb_buffer_t *buffer(hb_buffer_create());

        for (unsigned i = 0; i < NUM_ITER; ++i)
        {
            for (unsigned j = 0; j < NUM_EXAMPLES; ++j)
            {
                UnicodeString text = UnicodeString::fromUTF8(texts[j]);
                int32_t length = text.length();
                hb_buffer_clear_contents(buffer);
                //hb_buffer_set_unicode_funcs(buffer.get(), hb_icu_get_unicode_funcs());
                hb_buffer_pre_allocate(buffer, length);
                hb_buffer_add_utf16(buffer, text.getBuffer(), text.length(), 0, length);
                hb_buffer_set_direction(buffer, text_directions[j]);
                hb_buffer_set_script(buffer, scripts[j]);
                hb_buffer_set_language(buffer,hb_language_from_string(languages[j], std::strlen(languages[j])));
                //hb_shape(hb_ft_font[j], buffer.get(), 0, 0);
                hb_shape_full(hb_ft_font[j], buffer, 0, 0, shapers);
                unsigned num_glyphs = hb_buffer_get_length(buffer);
                hb_glyph_info_t *glyphs = hb_buffer_get_glyph_infos(buffer, NULL);
                //hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer.get(), NULL);
                for (unsigned k=0; k<num_glyphs; ++k)
                {
                    int32_t glyph_index = glyphs[k].codepoint;
                    if (i == 0)
                    {
                        std::cerr  <<  glyph_index << ":";
                    }
                }
                if (i == 0) std::cerr << std::endl;
            }
        }
        hb_buffer_destroy(buffer);
    }

    // cleanup
    for (int j=0; j < NUM_EXAMPLES; ++j)
    {
        hb_font_destroy(hb_ft_font[j]);
    }
    FT_Done_FreeType(ft_library);

    return EXIT_SUCCESS;
}
Пример #19
0
void MapgenV6::flowMud(s16 &mudflow_minpos, s16 &mudflow_maxpos) {
	// 340ms @cs=8
	TimeTaker timer1("flow mud");

	// Iterate a few times
	for(s16 k = 0; k < 3; k++) {
		for (s16 z = mudflow_minpos; z <= mudflow_maxpos; z++)
		for (s16 x = mudflow_minpos; x <= mudflow_maxpos; x++) {
			// Invert coordinates every 2nd iteration
			if (k % 2 == 0) {
				x = mudflow_maxpos - (x - mudflow_minpos);
				z = mudflow_maxpos - (z - mudflow_minpos);
			}

			// Node position in 2d
			v2s16 p2d = v2s16(node_min.X, node_min.Z) + v2s16(x, z);

			v3s16 em = vm->m_area.getExtent();
			u32 i = vm->m_area.index(p2d.X, node_max.Y, p2d.Y);
			s16 y = node_max.Y;

			while(y >= node_min.Y)
			{

			for(;; y--)
			{
				MapNode *n = NULL;
				// Find mud
				for(; y >= node_min.Y; y--) {
					n = &vm->m_data[i];
					if (n->getContent() == c_dirt ||
						n->getContent() == c_dirt_with_grass ||
						n->getContent() == c_gravel)
						break;

					vm->m_area.add_y(em, i, -1);
				}

				// Stop if out of area
				//if(vmanip.m_area.contains(i) == false)
				if (y < node_min.Y)
					break;

				if (n->getContent() == c_dirt ||
					n->getContent() == c_dirt_with_grass)
				{
					// Make it exactly mud
					n->setContent(c_dirt);

					// Don't flow it if the stuff under it is not mud
					{
						u32 i2 = i;
						vm->m_area.add_y(em, i2, -1);
						// Cancel if out of area
						if(vm->m_area.contains(i2) == false)
							continue;
						MapNode *n2 = &vm->m_data[i2];
						if (n2->getContent() != c_dirt &&
							n2->getContent() != c_dirt_with_grass)
							continue;
					}
				}

				v3s16 dirs4[4] = {
					v3s16(0,0,1), // back
					v3s16(1,0,0), // right
					v3s16(0,0,-1), // front
					v3s16(-1,0,0), // left
				};

				// Check that upper is air or doesn't exist.
				// Cancel dropping if upper keeps it in place
				u32 i3 = i;
				vm->m_area.add_y(em, i3, 1);
				if (vm->m_area.contains(i3) == true &&
					ndef->get(vm->m_data[i3]).walkable)
					continue;

				// Drop mud on side
				for(u32 di=0; di<4; di++) {
					v3s16 dirp = dirs4[di];
					u32 i2 = i;
					// Move to side
					vm->m_area.add_p(em, i2, dirp);
					// Fail if out of area
					if (vm->m_area.contains(i2) == false)
						continue;
					// Check that side is air
					MapNode *n2 = &vm->m_data[i2];
					if (ndef->get(*n2).walkable)
						continue;
					// Check that under side is air
					vm->m_area.add_y(em, i2, -1);
					if (vm->m_area.contains(i2) == false)
						continue;
					n2 = &vm->m_data[i2];
					if (ndef->get(*n2).walkable)
						continue;
					// Loop further down until not air
					bool dropped_to_unknown = false;
					do {
						vm->m_area.add_y(em, i2, -1);
						n2 = &vm->m_data[i2];
						// if out of known area
						if(vm->m_area.contains(i2) == false ||
							n2->getContent() == CONTENT_IGNORE) {
							dropped_to_unknown = true;
							break;
						}
					} while (ndef->get(*n2).walkable == false);
					// Loop one up so that we're in air
					vm->m_area.add_y(em, i2, 1);
					n2 = &vm->m_data[i2];

					bool old_is_water = (n->getContent() == c_water_source);
					// Move mud to new place
					if (!dropped_to_unknown) {
						*n2 = *n;
						// Set old place to be air (or water)
						if(old_is_water)
							*n = MapNode(c_water_source);
						else
							*n = MapNode(CONTENT_AIR);
					}

					// Done
					break;
				}
			}
			}
		}
	}
}