AREXPORT void *ArFunctorASyncTask::runThread(void *arg)
{
  threadStarted();
  void *ret = myFunc->invokeR(arg);
  threadFinished();
  return ret;
}
Esempio n. 2
0
 virtual void* runThread(void* arg)
 {
   threadStarted();
   while(Aria::getRunning() && getRunning())
   {
     ArSystemStatus::invalidate();
     ArUtil::sleep(myRefreshFrequency);
   }
   threadFinished();
   return NULL;
 }
Esempio n. 3
0
// The main loop for the threads. It checks to see if its still running.
// If not, it exits. The running variable is managed by ArThread. While its
// running, it waits on the condition variable.
void * Task::runThread(void *arg)
{
  threadStarted();
  while (getRunning())
  {
    printf("Task %d waiting\n", myNum);
    myCond->wait();
    printf("Task %d woke up\n", myNum);
  }

  return(NULL);
}
Esempio n. 4
0
void Server::incomingConnection(int socketDescriptor)
{
    Thread *thread = new Thread(socketDescriptor, this);
    for (int i = 0; i < numberOfPlayers; i++){
        if (!players[i]->isConnected()){
            players[i]->setConnectionThread(thread);
            connect(players[i], SIGNAL(fromPlayer(QString)), this, SLOT(fromClient(QString)));
            break;
        }
    }
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    connect(thread, SIGNAL(started()), thread, SLOT(threadStarted()));
    connect(thread, SIGNAL(threadRead()), this, SLOT(checkPlayers()));
    thread->start();
}
// this is the function called in the new thread
void *Joydrive::runThread(void *arg)
{
  threadStarted();

  int trans, rot;

  // only run while running, ie play nice and pay attention to the thread 
  //being shutdown
  while (myRunning)
  {
    // lock the robot before touching it
    myRobot->lock();
    if (!myRobot->isConnected())
    {
      myRobot->unlock();
      break;
    }
    // print out some information about the robot
    printf("\rx %6.1f  y %6.1f  tth  %6.1f vel %7.1f mpacs %3d   ", 
	   myRobot->getX(), myRobot->getY(), myRobot->getTh(), 
	   myRobot->getVel(), myRobot->getMotorPacCount());
    fflush(stdout);
    // if one of the joystick buttons is pushed, drive the robot
    if (myJoyHandler.haveJoystick() && (myJoyHandler.getButton(1) ||
					myJoyHandler.getButton(2)))
    {
      // get out the values from the joystick
      myJoyHandler.getAdjusted(&rot, &trans);
      // drive the robot
      myRobot->setVel(trans);
      myRobot->setRotVel(-rot);
    }
    // if no buttons are pushed stop the robot
    else
    {
      myRobot->setVel(0);
      myRobot->setRotVel(0);
    }
    // unlock the robot, so everything else can run
    myRobot->unlock();
    // now take a little nap
    ArUtil::sleep(50);
  }
  // return out here, means the thread is done
  return NULL;
}
void QGeoTiledMappingManagerEngine::setTileFetcher(QGeoTileFetcher *fetcher)
{
    Q_D(QGeoTiledMappingManagerEngine);

    d->fetcher_ = fetcher;
    d->fetcher_->init();

    d->thread_ = new QThread;

    qRegisterMetaType<QGeoTileSpec>();

    connect(d->fetcher_,
            SIGNAL(tileFinished(QGeoTileSpec,QByteArray,QString)),
            this,
            SLOT(engineTileFinished(QGeoTileSpec,QByteArray,QString)),
            Qt::QueuedConnection);
    connect(d->fetcher_,
            SIGNAL(tileError(QGeoTileSpec,QString)),
            this,
            SLOT(engineTileError(QGeoTileSpec,QString)),
            Qt::QueuedConnection);

    d->fetcher_->moveToThread(d_ptr->thread_);

    connect(d->thread_,
            SIGNAL(started()),
            d->fetcher_,
            SLOT(threadStarted()));

    connect(d->thread_,
            SIGNAL(finished()),
            d->fetcher_,
            SLOT(threadFinished()));

    connect(d->fetcher_,
            SIGNAL(destroyed()),
            d->thread_,
            SLOT(deleteLater()));

    engineInitialized();

    QTimer::singleShot(0, d->thread_, SLOT(start()));
}
Esempio n. 7
0
SDLEvents::SDLEvents() {
    // Initialize the GameController database with the most recent file
    // from https://github.com/gabomdq/SDL_GameControllerDB
    // TODO: Instead of storing the file as a ressource, have it in some
    // directory so the user can modify it if needed..
    Q_INIT_RESOURCE( assets ); // needed to access resources before app.exec()
    QFile f( ":/assets/gamecontrollerdb.txt" );
    f.open( QIODevice::ReadOnly );
    SDL_SetHint( SDL_HINT_GAMECONTROLLERCONFIG, f.readAll().constData() );

    event_list = new SDL_Event[10]();

    this->moveToThread( &thread );
    polltimer.moveToThread( &thread );
    connect( &thread, SIGNAL( started() ), SLOT( threadStarted() ) );
    connect( &thread, SIGNAL( finished() ), SLOT( threadFinished() ) );
    thread.setObjectName( "phoenix-SDLEvents" );

    thread.start( QThread::HighPriority );
}
AREXPORT void *
ArRecurrentTask::runThread(void *ptr) 
{
  threadStarted();
#ifndef WIN32
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
#endif
  while (myRunning)
    {
      bool doit;

      while (myRunning)
	{
	  lock();
	  doit = go_req;
	  unlock();
	  if (doit)
	    break;
//	  yield();		// don't hog resources
#ifndef WIN32
	  usleep(10000);
#else
	  Sleep(10);
#endif
	}
      if (!myRunning)
	break;
      lock();
      go_req = false;
      running = true;		// we've been requested to go
      unlock();
      task();			// do what we've got to do...
      lock();
      running = false;		// say we're done
      unlock();
    }

  threadFinished();
  return NULL;
}
Esempio n. 9
0
AREXPORT void * ArSignalHandler::runThread(void *arg)
{
  MRPT_UNUSED_PARAM(arg);
  threadStarted();

  // I think the old code was broken in that it didn't block all the
  // signals it wanted to wait for, which sigwait is supposed to
  // do... it also didn't check the return... for some reason system
  // on a debian box (at least a newer one) causes sigwait to return
  // with an error state (return of 4)... the old sigwait from rh 7.x
  // said it never returned an error... I don't entirely understand
  // it, and thats why both blocks of code are here

  // old code
  /*
  int sig;
  
  pthread_sigmask(SIG_SETMASK, &ourBlockSigSet, 0);

  while (myRunning)
  {
    sigwait(&ourHandleSigSet, &sig);
    signalCB(sig);
  }

  return(0);
*/
  // new code
  int sig = 0;
  
  while (myRunning)
  {
    pthread_sigmask(SIG_SETMASK, &ourBlockSigSet, 0);
    pthread_sigmask(SIG_BLOCK, &ourHandleSigSet, 0);

    if (sigwait(&ourHandleSigSet, &sig) == 0)
      signalCB(sig);
  }
  return(0);
}
Esempio n. 10
0
    void Thread::thread_loop() {
        Task *task;

        threadStarted();

        while(_run) {
            try {
                while ((task = getNextTask())) {
                    task->run();
                    task->acquired_thread = 0;
                    if (task->task_finished)
                        delete task;
                }
                
                while ((task = dynamic_cast<Task*>(Task::getNextTask()))) {
                    task->run();
                    task->acquired_thread = 0;
                    if (task->task_finished)
                        delete task;
                }
                
                if (task_queue.length())
                    continue;
                
            } catch (...) {
                LOG(Log::LOGLEVEL_ERROR, "Invalid Task in queue");
            }
            
            if (!pool || threads->length() > max_threads)
                break;
            
            wait();
        }

        threadFinished();
    }
Esempio n. 11
0
/// This should be its own thread here
void *ArCentralManager::runThread(void *arg)
{
  std::list<ArSocket *>::iterator sIt;
  std::list<std::string>::iterator nIt;
  std::list<ArCentralForwarder *>::iterator fIt;
  ArSocket *socket;
  std::string robotName;
  ArCentralForwarder *forwarder;

  ArNetPacket *packet;
  std::list<ArNetPacket *> addPackets;
  std::list<ArNetPacket *> remPackets;


  threadStarted();
  while (getRunning())
  {
    int numForwarders = 0;
    int numClients = 0;
    
    myDataMutex.lock();
    // this is where the original code to add forwarders was before we
    // changed the unique behavior to drop old ones...


    std::list<ArCentralForwarder *> connectedRemoveList;
    std::list<ArCentralForwarder *> unconnectedRemoveList;
    for (fIt = myForwarders.begin(); fIt != myForwarders.end(); fIt++)
    {
      forwarder = (*fIt);

      numForwarders++;
      if (forwarder->getServer() != NULL)
	numClients += forwarder->getServer()->getNumClients();
      bool connected = forwarder->isConnected();
      bool removed = false;
      if (!forwarder->callOnce(myHeartbeatTimeout, myUdpHeartbeatTimeout,
			       myRobotBackupTimeout, myClientBackupTimeout))
      {
	if (connected)
	{
	  ArLog::log(ArLog::Normal, "Will remove forwarder from %s", 
		     forwarder->getRobotName());
	  connectedRemoveList.push_back(forwarder);
	  removed = true;
	}
	else
	{
	  ArLog::log(ArLog::Normal, "Failed to connect to forwarder from %s", 
		     forwarder->getRobotName());
	  unconnectedRemoveList.push_back(forwarder);
	  removed = true;
	}
      }
      if (!connected && !removed && forwarder->isConnected())
      {
	ArLog::log(ArLog::Normal, "Adding forwarder %s", 
		   forwarder->getRobotName());
	ArTime *newTime = new ArTime;
	newTime->setSec(0);
	myUsedPorts[forwarder->getPort()] = newTime;
	
	std::multimap<int, ArFunctor1<ArCentralForwarder *> *>::iterator it;
	for (it = myForwarderAddedCBList.begin();
	     it != myForwarderAddedCBList.end();
	     it++)
	{
	  if ((*it).second->getName() == NULL || 
	      (*it).second->getName()[0] == '\0')
	    ArLog::log(ArLog::Normal, "Calling unnamed add functor at %d",
		       -(*it).first);
	  else
	    ArLog::log(ArLog::Normal, "Calling %s add functor at %d",
		       (*it).second->getName(), -(*it).first);
	  (*it).second->invoke(forwarder);
	}
	ArLog::log(ArLog::Normal, "Added forwarder %s", 
		   forwarder->getRobotName());      
	ArNetPacket *sendPacket = new ArNetPacket;
	sendPacket->strToBuf("");
	sendPacket->uByte2ToBuf(forwarder->getPort());
	sendPacket->strToBuf(forwarder->getRobotName());
	sendPacket->strToBuf("");
	sendPacket->strToBuf(
		forwarder->getClient()->getTcpSocket()->getIPString());
	addPackets.push_back(sendPacket);
	// MPL added this at the same time as the changes for the deadlock that happened down below
	//myClientServer->broadcastPacketTcp(&sendPacket, "clientAdded");
      }
    }

    while ((fIt = connectedRemoveList.begin()) != connectedRemoveList.end())
    {
      forwarder = (*fIt);

      ArLog::log(ArLog::Normal, "Removing forwarder %s", 
		 forwarder->getRobotName());
      std::multimap<int, ArFunctor1<ArCentralForwarder *> *>::iterator it;
      for (it = myForwarderRemovedCBList.begin();
	   it != myForwarderRemovedCBList.end();
	   it++)
      {
	if ((*it).second->getName() == NULL || 
	    (*it).second->getName()[0] == '\0')
	  ArLog::log(ArLog::Normal, "Calling unnamed remove functor at %d",
		     -(*it).first);
	else
	  ArLog::log(ArLog::Normal, "Calling %s remove functor at %d",
		     (*it).second->getName(), -(*it).first);
	(*it).second->invoke(forwarder);
      }

      ArLog::log(ArLog::Normal, "Called forwarder removed for %s", 
		 forwarder->getRobotName());
      ArNetPacket *sendPacket = new ArNetPacket;
      sendPacket->strToBuf("");
      sendPacket->uByte2ToBuf(forwarder->getPort());
      sendPacket->strToBuf(forwarder->getRobotName());
      sendPacket->strToBuf("");
      sendPacket->strToBuf(
	      forwarder->getClient()->getTcpSocket()->getIPString());
      // MPL making this just push packets into a list to broadcast at the end since this was deadlocking
      //myClientServer->broadcastPacketTcp(&sendPacket, "clientRemoved");
      remPackets.push_back(sendPacket);

      if (myUsedPorts.find(forwarder->getPort()) != myUsedPorts.end() && 
	  myUsedPorts[forwarder->getPort()] != NULL)
	myUsedPorts[forwarder->getPort()]->setToNow();

      myForwarders.remove(forwarder);
      delete forwarder;
      connectedRemoveList.pop_front();
      ArLog::log(ArLog::Normal, "Removed forwarder");

    }

    while ((fIt = unconnectedRemoveList.begin()) != 
	   unconnectedRemoveList.end())
    {
      forwarder = (*fIt);
      ArLog::log(ArLog::Normal, "Removing unconnected forwarder %s", 
		 forwarder->getRobotName());

      if (myUsedPorts.find(forwarder->getPort()) != myUsedPorts.end() && 
	  myUsedPorts[forwarder->getPort()] != NULL)
	myUsedPorts[forwarder->getPort()]->setToNow();      

      myForwarders.remove(forwarder);
      delete forwarder;
      unconnectedRemoveList.pop_front();
      ArLog::log(ArLog::Normal, "Removed unconnected forwarder");
    }


    // this code was up above just after the lock before we changed
    // the behavior for unique names
    while ((sIt = myClientSockets.begin()) != myClientSockets.end() && 
	   (nIt = myClientNames.begin()) != myClientNames.end())
    {
      socket = (*sIt);
      robotName = (*nIt);

      myClientSockets.pop_front();
      myClientNames.pop_front();

      ArLog::log(ArLog::Normal, 
		 "New forwarder for socket from %s with name %s", 
		 socket->getIPString(), robotName.c_str());

      forwarder = new ArCentralForwarder(myClientServer, socket, 
					 robotName.c_str(), 
					 myClientServer->getTcpPort() + 1, 
					 &myUsedPorts, 
					 &myForwarderServerClientRemovedCB,
					 myEnforceProtocolVersion.c_str(),
					 myEnforceType);
      myForwarders.push_back(forwarder);
    }

    numClients += myRobotServer->getNumClients();
    if (myRobotServer != myClientServer)
      numClients += myClientServer->getNumClients();
    // end of code moved for change in unique behavior
    if (numClients > myMostClients)
    {
      ArLog::log(ArLog::Normal, "CentralManager: New most clients: %d", 
		 numClients);
      myMostClients = numClients;
    }

    if (numForwarders > myMostForwarders)
      myMostForwarders = numForwarders;

    if (numClients > myMostClients)
    {
      ArLog::log(ArLog::Normal, "CentralManager: New most forwarders: %d", 
		 numForwarders);
      myMostForwarders = numForwarders;
    }

    myRobotServer->internalSetNumClients(numForwarders + 
					 myClientSockets.size());

    myDataMutex.unlock();

    while (addPackets.begin() != addPackets.end())
    {
      packet = addPackets.front();
      myClientServer->broadcastPacketTcp(packet, "clientAdded");
      addPackets.pop_front();
      delete packet;
    }

    while (remPackets.begin() != remPackets.end())
    {
      packet = remPackets.front();
      myClientServer->broadcastPacketTcp(packet, "clientRemoved");
      remPackets.pop_front();
      delete packet;
    }

    ArUtil::sleep(1); 

    //make this a REALLY long sleep to test the duplicate pending
    //connection code
    //ArUtil::sleep(20000);
  }

  threadFinished();
  return NULL;
}
Esempio n. 12
0
AREXPORT void * ArSyncLoop::runThread(void *arg)
{
  threadStarted();

  long timeToSleep;
  ArTime loopEndTime;
  std::list<ArFunctor *> *runList;
  std::list<ArFunctor *>::iterator iter;
  ArTime lastLoop;
  bool firstLoop = true;
  bool warned = false;

  if (!myRobot)
  {
    ArLog::log(ArLog::Terse, "ArSyncLoop::runThread: Trying to run the synchronous loop without a robot.");
    return(0);
  }

  if (!myRobot->getSyncTaskRoot())
  {
    ArLog::log(ArLog::Terse, "ArSyncLoop::runThread: Can not run the synchronous loop without a task tree");
    return(0);
  }

  while (myRunning)
  {

    myRobot->lock();
    if (!firstLoop && !warned && !myRobot->getNoTimeWarningThisCycle() && 
	myRobot->getCycleWarningTime() != 0 && 
	myRobot->getCycleWarningTime() > 0 && 
	lastLoop.mSecSince() > (signed int) myRobot->getCycleWarningTime())
    {
      ArLog::log(ArLog::Normal, 
 "Warning: ArRobot cycle took too long because the loop was waiting for lock.");
      ArLog::log(ArLog::Normal,
		 "\tThe cycle took %u ms, (%u ms normal %u ms warning)", 
		 lastLoop.mSecSince(), myRobot->getCycleTime(), 
		 myRobot->getCycleWarningTime());
    }
    myRobot->setNoTimeWarningThisCycle(false);
    firstLoop = false;
    warned = false;
    lastLoop.setToNow();

    loopEndTime.setToNow();
    loopEndTime.addMSec(myRobot->getCycleTime());
    myRobot->incCounter();
    myRobot->unlock();

    // note that all the stuff beyond here should maybe have a lock
    // but it should be okay because its just getting data
    myInRun = true;
    myRobot->getSyncTaskRoot()->run();
    myInRun = false;
    if (myStopRunIfNotConnected && !myRobot->isConnected())
    {
      if (myRunning)
	ArLog::log(ArLog::Normal, "Exiting robot run because of lost connection.");
      break;
    }
    timeToSleep = loopEndTime.mSecTo();
    // if the cycles chained and we're connected the packet handler will be 
    // doing the timing for us
    if (myRobot->isCycleChained() && myRobot->isConnected())
      timeToSleep = 0;

    if (!myRobot->getNoTimeWarningThisCycle() && 
	myRobot->getCycleWarningTime() != 0 && 
	myRobot->getCycleWarningTime() > 0 && 
	lastLoop.mSecSince() > (signed int) myRobot->getCycleWarningTime())
    {
      ArLog::log(ArLog::Normal, 
	"Warning: ArRobot sync tasks too long at %u ms, (%u ms normal %u ms warning)", 
		 lastLoop.mSecSince(), myRobot->getCycleTime(), 
		 myRobot->getCycleWarningTime());
      warned = true;
    }
    

    if (timeToSleep > 0)
      ArUtil::sleep(timeToSleep);
  }   
  myRobot->lock();
  myRobot->wakeAllRunExitWaitingThreads();
  myRobot->unlock();

  myRobot->lock();
  runList=myRobot->getRunExitListCopy();
  myRobot->unlock();
  for (iter=runList->begin();
       iter != runList->end(); ++iter)
    (*iter)->invoke();
  delete runList;

  threadFinished();
  return(0);
}
Esempio n. 13
0
// Physics thread that controls the motion of all the spheres.
void physicsThread(int threadNum)
{
	int localFrame = 0;

	// Define the normals for each of the walls.
	static const Vector3 bottom(0, 1, 0);
	static const Vector3 left(1, 0, 0);
	static const Vector3 right(-1, 0, 0);
	static const Vector3 front(0, 0, -1);
	static const Vector3 back(0, 0, 1);

	// Initialize the starting values for the wall and sphere, spring and damping values.
	float wallSpringConst = UPPER_WALL_SPRING_CONST;
	float sphereSpringConst = UPPER_SPHERE_SPRING_CONST;

	float wallDampFactor = UPPER_WALL_DAMP_FACTOR;
	float sphereDampFactor = UPPER_SPHERE_DAMP_FACTOR;

	// The physics thread itself deals with reseting its frame counter. 
	// It will do this once a second.
	float secondCheck = 0.0f;

#if _USE_MT
	// If the physics function is being called as a thread, then we don't want it 
	// to finish after one pass.
	int threadRunning = 0;
	while(programRunning)
	{
		// If the simulation needs to be paused but the thread is running,
		// stop.
		if(pauseSimulation && threadRunning)
		{
			threadRunning = 0;
			threadStopped();
		}
		// If the simulation needs to be running but the thread is stopped,
		// start.
		else if(!pauseSimulation && !threadRunning)
		{
			threadRunning = 1;
			threadStarted();
		}

		// If the thread isn't running at this time we can't go any further and 
		// we'll just wait and check if the thread has started up next time the
		// thread is executing.
		if(!threadRunning)
		{
			boost::this_thread::yield();
			continue;
		}
#endif

		localFrame++;

		LARGE_INTEGER time;
		QueryPerformanceCounter(&time);

		// Get the time since this thread last executed and convert into
		// seconds (from milliseconds).
		float dt = (float)(((double)time.QuadPart - (double)updateTimes[threadNum].QuadPart) / freq);
		dt *= 0.001;

		// Adjust the spring and dampening values based on dt.
		// This helps when going to lower frame rates and the overlap between
		// the walls and spheres when using high frame rate values will cause
		// the spheres to gain energy.
		wallSpringConst = WALL_SPRING_GRAD * dt + WALL_SPRING_CONST;
		sphereSpringConst = SPHERE_SPRING_GRAD * dt + SPHERE_SPRING_CONST;

		wallDampFactor = WALL_DAMP_GRAD * dt + WALL_DAMP_CONST;
		sphereDampFactor = SPHERE_DAMP_GRAD * dt + SPHERE_DAMP_CONST;

		// As the gradients for the spring and dampening factors are negative,
		// we want to clamp the lower bounds of the values. Otherwise at low
		// framerates the values will be negative.
		if (wallSpringConst < LOWER_WALL_SPRING_CONST)
			wallSpringConst = LOWER_WALL_SPRING_CONST;

		if (sphereSpringConst < LOWER_SPHERE_SPRING_CONST)
			sphereSpringConst = LOWER_SPHERE_SPRING_CONST;

		if (wallDampFactor < LOWER_WALL_DAMP_FACTOR)
			wallDampFactor = LOWER_WALL_DAMP_FACTOR;

		if (sphereDampFactor < LOWER_SPHERE_DAMP_FACTOR)
			sphereDampFactor = LOWER_SPHERE_DAMP_FACTOR;

		// If this is the 1st thread, then we will deal with the user controlled
		// sphere here.
		int startSphere = threadNum;
		if(threadNum == 0)
		{
			// Skip calcuating the user sphere like a typical sphere.
			startSphere += numPhysicsThreads;

			// As the user controlled sphere only has a position and velocity
			// that is either zero or constant, we can easily calculate its new
			// position.
			if(numSpheres > 0)
			{
				spherePositions[0] += sphereData[0].m_velocity * dt;
			}
		}

		for(int i = startSphere; i < numSpheres; i += numPhysicsThreads)
		{
			// Calculate the radius of the sphere based on array index.
			float radius = (float)((i % 3) + 1) * 0.5f;
			float roomSize = ROOM_SIZE - radius;
			
			Vector3 forces(0);

			Vector3 &spherePosition = spherePositions[i];
			SphereData &sphere = sphereData[i];

			// Calculate the interim velocity.
			Vector3 halfVelo = sphere.m_velocity + (0.5f * sphere.m_acc * dt);
			spherePosition += halfVelo * dt;

			Vector3 tempVelocity = sphere.m_velocity + (sphere.m_acc * dt);

			float overlap;

			// As the % operator is fairly slow we can take advantage here
			// that we always know what the next value in the array is going
			// to be and manually determine the mod.
			int indexCounter = 0;
			
			for(int j = 0; j < numSpheres; j++)
			{
				// And since we don't want the actual mod value but mod + 1
				// we don't worry about resetting to 0.
				indexCounter++;
				if(indexCounter > 3)
					indexCounter = 1;

				// We don't want a sphere to check if it's collided with itself.
				if(i == j)
					continue;

				SphereData &otherSphere = sphereData[j];
				Vector3 toCentre = spherePosition - spherePositions[j];
				// An unfortunately slow way of checking if the radius of the
				// other sphere should be the other spheres actual radius or
				// the user controlled spheres radius.
				float otherRadius; 
				if(j == 0)
				{
					otherRadius = userSphereSize;
				}
				else
				{
					otherRadius = (float)(indexCounter) * 0.5f;
				}

				float combinedRadius = radius + otherRadius;
				float lengthSqrd = lengthSquared(toCentre);
				float combinedRadiusSqrd = combinedRadius * combinedRadius;
				
				// A check to see if the spheres have overlapped at all.
				float overlapSqrd = lengthSqrd - combinedRadiusSqrd;
				if(overlapSqrd < 0)
				{
#if _SSE
					overlap = sqrt(lengthSqrd) - combinedRadius;
					// We want to let the vector normalize itself in SSE
					// because we can take advantage of the rsqrt instruction
					// which will be quicker than loading in a float value
					// and multiplying by the reciprocal.
					Vector3 tangent = normalize(toCentre);
#else
					// Here we can take advantage that we've already calculated
					// the actual length value so that we have the overlap and
					// can use that value again to normalize the tangent.
					float len = sqrt(lengthSqrd);
					overlap = len - combinedRadius;
					Vector3 tangent = toCentre / len;
#endif
					calcForce(forces, sphereSpringConst, sphereDampFactor, overlap, tangent, tempVelocity);
				}
			}
			
			// Calculate the overlap with the walls using the normal of the wall
			// and the walls distance from the origin. Should work best for SSE
			// as it should not require any checking of individual elements of
			// the vector.
			overlap = dot3(spherePosition, bottom) + roomSize;
			if(overlap < 0)
			{
				calcForce(forces, wallSpringConst, wallDampFactor, overlap, bottom, tempVelocity);
			}

			overlap = dot3(spherePosition, left) + roomSize;
			if(overlap < 0)
			{
				calcForce(forces, wallSpringConst, wallDampFactor, overlap, left, tempVelocity);
			}
			overlap = dot3(spherePosition, right) + roomSize;
			if(overlap < 0)
			{
				calcForce(forces, wallSpringConst, wallDampFactor, overlap, right, tempVelocity);
			}

			overlap = dot3(spherePosition, front) + roomSize;
			if(overlap < 0)
			{
				calcForce(forces, wallSpringConst, wallDampFactor, overlap, front, tempVelocity);
			}
			overlap = dot3(spherePosition, back) + roomSize;
			if(overlap < 0)
			{
				calcForce(forces, wallSpringConst, wallDampFactor, overlap, back, tempVelocity);
			}

			// Apply the accumulated forces to the acceleration.
			sphere.m_acc = forces / (radius * 2.0f);
			sphere.m_acc += GRAVITY;

			// Calculate the final velocity value from the interim velocity
			// and final acceleration.
			sphere.m_velocity = halfVelo + (0.5f * sphere.m_acc * dt);
		}

		// Determin if we need to reset out physics frame counter.
		secondCheck += dt;
		if(secondCheck > 1.0f)
		{
			physicsFrames[threadNum] = 1;
			secondCheck -= 1.0f;
		}
		else
		{
			physicsFrames[threadNum]++;
		}

		updateTimes[threadNum] = time;

		// If we're running the physics function as a thread function then we
		// need to keep it running, so this is the end of the while(programRunning) loop.
#if _USE_MT
	}
#endif
}
Esempio n. 14
0
void TrainingThread::mainThreadFunction(){

    //Flag that the core is running
    {
        boost::mutex::scoped_lock lock( mutex );
        threadRunning = true;
        stopMainThread = false;
        trainingInProcess = false;
        startTraining = false;
    }

    //Flag that the core is now running
    emit threadStarted();

    bool keepRunning = true;

    while( keepRunning ){

        //Check to see if we should start a new training batch
        bool runTraining = false;

        {
            boost::mutex::scoped_lock lock( mutex );
            runTraining = startTraining;
            if( startTraining ){
                startTraining = false;
                trainingInProcess = true;
            }
        }

        if( runTraining ){
            emit pipelineTrainingStarted();

            //Start the training, the thread will pause here until the training has finished
            bool result = trainer.train();

            //Flag that the training has stopped
            {
                boost::mutex::scoped_lock lock( mutex );
                trainingInProcess = false;
            }

            //Emit the results
            if( result ){
                emit newInfoMessage( "Pipeline trained" );
            }else{
                emit newHelpMessage( trainer.getLastErrorMessage() );
            }

            GRT::GestureRecognitionPipeline tempPipeline;
            {
                boost::mutex::scoped_lock lock( mutex );
                tempPipeline = trainer.getPipeline();
            }
            emit pipelineUpdated( tempPipeline );
            emit pipelineTrainingFinished( result );
        }

        //Let the thread sleep so we don't kill the CPU
        boost::this_thread::sleep( boost::posix_time::milliseconds( DEFAULT_TRAINING_THREAD_SLEEP_TIME ) );

        //Check to see if we should stop the thread
        {
            boost::mutex::scoped_lock lock( mutex );
            if( stopMainThread ){
                keepRunning = false;
            }
        }
    }

    //Flag that the core has stopped
    {
        boost::mutex::scoped_lock lock( mutex );
        threadRunning = false;
        stopMainThread = false;
        trainingInProcess = false;
        startTraining = false;
    }

    //Signal that the core has stopped
    emit threadStopped();
}
AREXPORT void * ArSignalHandler::runThread(void *arg)
{
  threadStarted();
  threadFinished(); // ??
  return(0);
}
Esempio n. 16
0
AREXPORT void * ArSignalHandler::runThread(void *arg)
{
  threadStarted();
  return(0);
}
Esempio n. 17
0
void display(void)
{
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	if(displayError)
	{
		orthographicView();

		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		txtInstructions.render((screenWidth - txtInstructions.getTextureWidth()) / 2.0f, (screenHeight - txtInstructions.getTextureHeight()) / 2.0f);

		glFlush();
		return;
	}

	glPushMatrix();

	// Setup the navigation
	glTranslated(0, 0, -zoom);
	glRotatef(camRotateX, 1, 0, 0);
	glRotatef(camRotateY, 0, 1, 0);
	glTranslated(0, ROOM_SIZE, 0);

	// Setup drawing for the scene.
	perspectiveView();
	
#if _USE_MT
	// If the render thread needs to wait for new spheres to be added.
	while(pauseSimulation)
	{
		boost::this_thread::yield();
	}

	threadStarted();
#endif

	renderFrame++;
	renderFrameCounter++;

	glEnable(GL_DEPTH_TEST);

	glColor3f(1.0f, 1.0f, 1.0f);
	
	glUseProgram(g_program);
	glUniform3fv(g_programCameraPositionLocation, 1, g_cameraPosition);
	glUniform3fv(g_programLightDirectionLocation, 1, g_lightDirection);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereMesh.indexBufferId);

	// We are using instanced rendering, however we cannot draw all the spheres at once.
	// So we have a maximum number of objects that can be rendered at once and we'll just
	// render that many at a time until we have less spheres than MAX_OBJECTS_PER_RENDER 
	// left to render.
	for(int objectIndex = 0; objectIndex < numSpheres; objectIndex += MAX_OBJECTS_PER_RENDER)
	{
		int numObjects = MAX_OBJECTS_PER_RENDER;
		// Are we going to be rendering more spheres than we should?
		if (numObjects + objectIndex > numSpheres)
		{
			numObjects = numSpheres - objectIndex;
		}
		Vector3 *positionIndex = spherePositions + objectIndex;
		glUniform4fv(g_programObjectPositionLocation, numObjects, (float *)positionIndex);
		// Tell the shader the size of the user sphere.
		// Due to the way the shader renders multiple instances, it only knows the id
		// of the current instance it is rendering, which does not reflect the sphere's actual
		// id.
		// So we will set that the size of the userSphere only on the first instanced render
		// and all later renders it will be zero.
		glUniform1f(g_programUserSphereLocation, (objectIndex == 0) * userSphereSize);

		glDrawElementsInstancedEXT(GL_TRIANGLES, sphereMesh.numIndicies, GL_UNSIGNED_INT, 0, numObjects);
	}

	glUseProgram(0);
	
#if _USE_MT
	threadStopped();
#endif

	glPopMatrix();

	// Setup drawing for the interface.
	orthographicView();

	char buff[64];

	sprintf(buff, "FPS: %d", framesPerSecond);
	txtRenderFrames.setText(buff);

	sprintf(buff, "PPS: %.1f", physicsPerSecond);
	txtPhysicsFrames.setText(buff);

	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	float yPos = -2.0f;
	
	txtInstructions.render(10, yPos += 12.0f);
	txtInstructions2.render(10, yPos += 12.0f);
	txtNumThreads.render(10, yPos += 12.0f);
	txtNumSpheres.render(10, yPos += 12.0f);
	txtRenderFrames.render(10, yPos += 12.0f);
	txtPhysicsFrames.render(10, yPos += 12.0f);
	
	glDisable(GL_BLEND);

	glFlush();
}
Esempio n. 18
0
void DirCleaner::run()
{         
    emit threadStarted( "Cleaning up...", mDirs.size() );
    
    for ( int i = 0; i < mDirs.size(); ++i ) 
    {
        qDebug() << "[DIRCLEANER] Deleting directory" << mDirs.at( i );
        
        QDir dir( mDirs.at( i ) );
        
    #ifndef IS_WIN32
        QProcess p;
        QStringList args;
        
        args.append( "-R" );
        args.append( "777" );
        args.append( dir.path() );
        
        p.start( "chmod", args );
        
        if (  !p.waitForFinished ( -1 ) )
        {
            return;
        }
    #endif

        if ( dir.exists() )
        {
            QDirIterator fileWalker( dir.path(), QDir::Files | QDir::Hidden | QDir::System, QDirIterator::Subdirectories );

            while( fileWalker.hasNext() )
            {
                fileWalker.next();
                QFile::remove( fileWalker.filePath() );
            }

            QDirIterator dirWalker( dir.path(), QDir::Dirs | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot, QDirIterator::Subdirectories );

            while( dirWalker.hasNext() )
            {
                dirWalker.next();
                dir.rmpath( dirWalker.filePath() );
            }

            dir.rmdir( dir.path() );
            emit threadProgress( i, QString::Null() );
        }
    }
    
    QStringList failedList;
    
    for ( int i = 0; i < mDirs.size(); ++i ) 
    {
        QDir d( mDirs.at( i ) );
        
        if ( d.exists() )
        {
            failedList.append( mDirs.at( i ) );
        }
    }
    
    if ( failedList.size() > 0 )
    {
        emit dirsFailed( failedList );
    }
        
    emit threadFinished( this );
}
Esempio n. 19
0
AREXPORT void *ArFunctorASyncTask::runThread(void *arg)
{
  threadStarted();
  return myFunc->invokeR(arg);
}
MessageDefinitionLoader::MessageDefinitionLoader(QObject* parent) :
  QObject(parent),
  impl_(this) {
  connect(&impl_, SIGNAL(started()), this, SLOT(threadStarted()));
  connect(&impl_, SIGNAL(finished()), this, SLOT(threadFinished()));
}