예제 #1
0
void frts::MainLoop::start(const SharedManagerImplPtr& shared) const
{
    assert(shared != nullptr);

    Frame::time runTime = fromMilliseconds(0);
    Frame::time currentTime = highResTime();
    Frame::time accumulator = fromMilliseconds(0);
    Frame::ticks tick = 0;

    Frame::time deltaTimeDebug = deltaTime + fromMilliseconds(1);

    std::string maxFrameTimeWarnMsg = R"(Frame %3% exceeded frame time of %1%ms with max frame time of %2%ms.)";
    std::string frameTimeWarnMsg = R"(Frame %3% exceeded frame time of %1%ms with delta frame time of %2%ms.)";

    auto frame = makeFrame(deltaTime, tick, runTime);
    shared->setFrame(frame);

    while (!shared->isQuitApplication())
    {
        Frame::time newTime = highResTime();

        // Limit frame time to a maximum to avoid spiral of death.
        Frame::time frameTime = newTime - currentTime;
        if (frameTime > maxFrameTime)
        {
            auto msg = boost::format(maxFrameTimeWarnMsg)
                    % std::chrono::duration_cast<std::chrono::milliseconds>(frameTime).count()
                    % std::chrono::duration_cast<std::chrono::milliseconds>(maxFrameTime).count()
                    % frame->getNumber();
            shared->getLog()->info(logModule, msg.str());

            frameTime = maxFrameTime;
        }
        // For debugging.
        else if (frameTime > deltaTimeDebug)
        {
            auto msg = boost::format(frameTimeWarnMsg)
                    % std::chrono::duration_cast<std::chrono::milliseconds>(frameTime).count()
                    % std::chrono::duration_cast<std::chrono::milliseconds>(deltaTime).count()
                    % frame->getNumber();
            shared->getLog()->debug(logModule, msg.str());
        }

        currentTime = newTime;
        accumulator += frameTime;

        while (accumulator >= deltaTime)
        {
            frame = makeFrame(deltaTime, tick, runTime);
            shared->setFrame(frame);
            update(shared);
            accumulator -= deltaTime;
            runTime += deltaTime;
            tick += 1;
        }

        render(shared);
    }
}
//*****
void DtmfDataLinkLayer::passDataUpwards(int listLength)
{
#ifdef DEBUG
	DEBUG_OUT << "Pushing to datagram buffer:";
#endif

	//iterate through list and push to datagram buffer
	for(int i=0;i<listLength;i++)
	{
#ifdef DEBUG
		for(int k=7;k>=0;k--)
			DEBUG_OUT << (bool)(frameRecList[i].dataByte&(1<<k));
		DEBUG_OUT << " ";
#endif
		datagramUp->push_back(frameRecList[i].dataByte);
	}
	std::cout << std::endl;

#ifdef DEBUG
	DEBUG_OUT << std::endl << "Gerating OK reply to sender" << std::endl;
#endif

	//generate ok for sender
	makeFrame((MY_ADDRESS<<ADDRESS)|(1<<EOT),~0);
	replyGenerated = 1;

	//clear list
	clearFrameReceiveList();
}
void randomSamplePointsOnHemisphere( const vec3& normal, float angle, size_t n, vec3* out, random& seed )
{
	assert( angle > 0.f && angle <= radians(90.f) );
	assert( n > 0 );
	assert( check(normal) );

    const float c = cosf( angle );

	vec3 v1, v2;
	makeFrame( normal, v1, v2 );
    makeStratifiedPairs( n, out, seed );

    for ( size_t i = 0 ; i < n ; ++i )
    {
		const float x1 = out[i].x;
		const float x2 = out[i].y;
		const float costheta2 = c * c + x1 * (1.f - c * c);
		const float costheta = sqrtf( costheta2 );
		const float sintheta = sqrtf( 1.0f - costheta2 );
		const float angle = 6.283185307179586476925286766559f * x2;
		const vec3 p0( sintheta*cosf(angle), sintheta*sinf(angle), costheta );

		out[i] = vec3( p0.x * v1 + p0.y * v2 + p0.z * normal );
    }
}
예제 #4
0
//------------------------------------------//
// Problem 2: There is a requirement that 
// at least 400 DOMs launch.  I want to look 
// at the average, and maybe also the average 
// for given event range.
//------------------------------------------//
void checkNDOM(TTree* tree)
{

  // Plot the number of DOM's per event
  TString var = "DetectorResponseEvent_.totalNumberOfDom_";

  // Make canvas
  TCanvas* c  = makeCanvas("c");

  // Make a vector of TCuts
  vector<TString> cuts;
  cuts.push_back("1");   // 1%
  cuts.push_back("3");   // 3%
  cuts.push_back("10");  // 10%
  cuts.push_back("30");  // 30%
  cuts.push_back("51");  // 51%
  cuts.push_back("100"); // 100%

  // Create histogram holders
  TH1F* hists[6];
  int nbins = 100;
  int min   = 0;
  int max   = 2000;
  TString xtitle = "nDOMs";
  TString ytitle = "Entries";
  
  // Make legend
  TLegend* leg = makeLegend(0.7,0.8,0.6,0.9);
  leg->SetHeader("Luminosity");

  // Loop and draw
  float maximum = -999;
  for(unsigned int i=0; i<cuts.size(); ++i){
    // get cut value
    TString cutval = cuts.at(i); 
    // create histogram
    hists[i] = makeFrame("hist_"+cutval,nbins,min,max,
			 xtitle,ytitle);

    // cut the TCut object from value
    TCut cut = lumiCut(cutval);

    // Draw and set att
    tree->Draw((var+">>hist_"+cutval).Data(),cut,"hist");
    setAtt(hists[i],xtitle,ytitle,m_colors[i],m_markers[i]);
    setMax(hists[i],maximum);

    // Add to legend
    leg->AddEntry(hists[i],(cutval+"%").Data(),"l");
  }

  // Now draw the figures
  hists[0]->SetMaximum(maximum*1.1);
  hists[0]->Draw("hist");
  for(unsigned int i=1; i<cuts.size(); ++i)
    hists[i]->Draw("samehist");
  leg->Draw("same");

  c->SaveAs((savedir+"nDoms_perLumi.png").Data());
}
예제 #5
0
void slotServer(obj cbus, int opc, byte* frame) {
  iOCBUSData data = Data(cbus);
  int offset = (frame[1] == 'S') ? 0:4;
  byte cmd[32];

  switch(opc) {
  case OPC_RLOC:
    {
      int addrh = HEXA2Byte(frame + OFFSET_D1 + offset) & 0x3F;
      int addrl = HEXA2Byte(frame + OFFSET_D2 + offset);
      byte* frame = allocMem(32);

      cmd[0] = OPC_PLOC;
      cmd[1] = 1;   // session
      cmd[2] = addrh;
      cmd[3] = addrl;
      cmd[4] = 0;   // speed
      cmd[5] = 0;   // f0
      cmd[6] = 0;   // f1
      cmd[7] = 0;   // f2

      makeFrame(frame, PRIORITY_NORMAL, cmd, 7, data->cid, False );
      TraceOp.trc( "slotserv", TRCLEVEL_MONITOR, __LINE__, 9999, "OPC_PLOC response" );
      ThreadOp.post(data->writer, (obj)frame);
    }
    break;

  }
}
예제 #6
0
// Evaluates a let* expression and makes a new frame that will point to the frame that is given to it
// as a parameter
Value evalLetStar(Value tree, Frame *env){
    if(tree.type != consType){
        return evaluationError("improper use of \'let*\'");
    }
    if(!tree.consValue){
        return evaluationError("no arguments given to \'let*\'");
    }
    
    // Get the bindings and the body
    Value bindings = getNth(tree.consValue,0); 
    Value body = getNth(tree.consValue,1);
    if( (body.type == openType) || (bindings.type == openType) ){
        return evaluationError("not enough arguments given to a \'let*\'");
    }

    // Make a new frame from the bindings list
    Frame *newEnv = makeFrame(env);
    insertVectorItem(envGarbage, envGarbage->size, (void *)newEnv);
    
    if(!addBindingsStar(newEnv, bindings)){
        return evaluationError("poorly formed \'let*\'");
    }

    return eval(body, newEnv);
}
예제 #7
0
//------------------------------------------//
// Plot nDOM with out any other reqs.
//------------------------------------------//
void plotNDOM(TTree* tree)
{

  // Plot the number of DOM's per event
  TString var = "DetectorResponseEvent_.totalNumberOfDom_";

  // Make canvas
  TCanvas* c  = makeCanvas("c");

  // Create histogram holders
  int nbins = 100;
  int min   = 0;
  int max   = 2000;
  TString xtitle = "nDOMs";
  TString ytitle = "Entries";
  TH1F* hist = makeFrame("hist",nbins,min,max,
			 xtitle,ytitle);

  // Make legend
  TLegend* leg = makeLegend(0.7,0.8,0.8,0.9);
  leg->SetHeader("Luminosity");

  // Draw
  tree->Draw((var+">>hist").Data(),"","hist");

  // Add to legend
  leg->AddEntry(hist, "All", "l");

  // Now draw the figures
  hist->Draw("hist");
  leg->Draw("same");

  c->SaveAs((savedir+"nDoms_total.png").Data());
}
//*****
void DtmfDataLinkLayer::offerToken()
{
	//increase token receiver
	nextStation++;

	//flip over if higher than number of addresses
	if(nextStation>3)
		nextStation = 0;

	//if next receiver has been increased four times
	if(nextStation==MY_ADDRESS)
	{
#ifdef DEBUG
		DEBUG_OUT << "Offering token to self" << std::endl;
#endif
		//offer token to self
		tokenOffered();
		tokenAlreadyOffered = 0;
		noReply = 1;
	}
	else
	{
#ifdef DEBUG
		DEBUG_OUT << "Offering token to " << nextStation << std::endl;
#endif
		tokenAlreadyOffered = 1;
		time( &timestampTokenOffered );
		//generate frame to offer token to next station
		makeFrame((1<<TYPE)|(nextStation<<ADDRESS),0);
	}
}
예제 #9
0
void tst_Q3DockWindow::parents()
{
    // create 5 dock windows, one for each dock area
    // and one for the mainwindow, in the end they should
    // all except the one with the mainwindow as parent should
    // have the same dock() and parent() pointer.
    Q3MainWindow mw;
    QFrame *central = makeFrame( "Central", &mw );
    mw.setCentralWidget( central );

    Q3DockWindow *topDock = makeDock( "Top", mw.topDock() );
    QVERIFY( topDock->area() == topDock->parent() );

    Q3DockWindow *leftDock = makeDock( "Left", mw.leftDock() );
    QVERIFY( leftDock->area() == leftDock->parent() );

    Q3DockWindow *rightDock= makeDock( "Right", mw.rightDock() );
    QVERIFY( rightDock->area() == rightDock->parent() );

    Q3DockWindow *bottomDock = makeDock( "Bottom", mw.bottomDock() );
    QVERIFY( bottomDock->area() == mw.bottomDock() );

    Q3DockWindow *mainDock = makeDock( "MainWindow as parent", &mw );
    QVERIFY( mainDock->parent() == mw.topDock() );
}
예제 #10
0
void Manager::update() {
  clock.update();
  kungfuback.update();
  kungfu.update();
  Uint32 ticks = clock.getTicksSinceLastFrame();

  std::list<ExplodingSprite*>::iterator itr = explodingSprite.begin();
  while( itr != explodingSprite.end()){
    (*itr)->update(ticks);
    if((*itr)->done()){
      delete *itr;
      itr = explodingSprite.erase(itr);
    }
    else ++itr;
  }

  for (unsigned int i = 1; i < sprites.size(); ++i) {
    sprites[i]->update(ticks);
  }



  std::vector<Drawable*>::iterator ptr = sprites.begin() + 1;
  while(ptr != sprites.end() && healthLeft){
    if(static_cast<Player*>(sprites[0])->collidWith(*ptr) ){
      explodingSprite.push_back(new ExplodingSprite(*(static_cast<ScaledSprite*>(*ptr))));
      ScaledSprite* player = static_cast<ScaledSprite*>( sprites[0] );
      ScaledSprite* sprite = static_cast<ScaledSprite*>( *ptr );      
      *ptr = new SmartSprite(sprite->getName(), sprite->getPosition() + Vector2f(100,100), *player); 
      delete sprite;
      ptr++;      
      ++score;                                                 
    }
    else ++ptr;
  }

  std::vector<Drawable*>::iterator pos = sprites.begin() + 1;
  while(pos != sprites.end()){
    (*pos)->update(ticks);
    if(static_cast<Player*>(sprites[0])->playerCollidWith(*pos) && healthLeft){
      explodingSprite.push_back(new ExplodingSprite(*(static_cast<ScaledSprite*>(*pos))));
      ScaledSprite* player = static_cast<ScaledSprite*>(sprites[0]);
      ScaledSprite* sprite = static_cast<ScaledSprite*>(*pos);      
      *pos = new SmartSprite(sprite->getName(), sprite->getPosition() + Vector2f(100,100), *player); 
      delete sprite;
      pos++;
      ++score;
    }
    else ++pos;
  }
  
  if (makeVideo && frameCount < frameMax) makeFrame();
  if(godmode) healthLine.reset();
  healthLine.update(ticks,godmode);
  if(healthLine.getCurrentHealth() == 0) healthLeft = false;  
  if(healthLeft) sprites[0]->update(ticks);
  viewport.update();
}
예제 #11
0
double Compound::computeWidth() const
{
//    double distance=1000;
//    int edgenum=poly.at(0)->getEdgeNum();
//    for (int n=0;n<edgenum;n++)
//    {
//        for (int m=0;m<edgenum;m++)
//        {
//            for (int i=0;i<polyNum;i++)
//            {
//                for (int j=i+1;j<polyNum;j++)
//                {
//                    double checkDist=segmentSegmentDist(poly.at(i)->getEdgeLine(n), poly.at(j)->getEdgeLine(m));
//                    /*if (i==0 && j==2 && n==0 && m==0)
//                    {
//                        std::cout << checkDist << "\n";
//                    }*/
//                    if (checkDist<distance)
//                    {
//                        distance=checkDist;
//                    }
//                    //distance=fmin(distance,checkDist);
//                }
//            }
//        }
//    }
    
    int polyNum=getNumberOfPolyhedra();
    std::vector<Frame> frames;
    for (int i=0;i<polyNum;i++)
    {
        frames.push_back(makeFrame(i));
    }
    
    int edgeNum=frames.at(0).getEdgeNum();
    double distance=100000.0;
    for (int i=0;i<polyNum;i++)
    {
        for (int j=i+1;j<polyNum;j++)
        {
            for (int k=0;k<edgeNum;k++)
            {
                for (int m=0;m<edgeNum;m++)
                {
                    double edgeDist=segmentSegmentDist(frames.at(i).getFrameEdges()->at(k).getLine(),frames.at(j).getFrameEdges()->at(m).getLine());
                    //edgeDistances.push_back(edgeDist);
                    if (edgeDist<distance)
                    {
                        distance=edgeDist;
                    }
                }
            }
        }
    }
    return distance/2;
}
예제 #12
0
Q3DockWindow* makeDock( const char* text, QWidget* parent )
{
    Q3DockWindow* dock = new Q3DockWindow(Q3DockWindow::InDock, parent, text);
    dock->setResizeEnabled(true);
    dock->setCloseMode(Q3DockWindow::Always);
    dock->setCaption(text);
    dock->setWidget(makeFrame(text, dock));
    dock->show();

    return dock;
}
//*****
void DtmfDataLinkLayer::requestResend(int request)
{
#ifdef DEBUG
	for(int j=0;j<8;j++)
		if(!(bool)(request&(1<<j)))
			DEBUG_OUT << "Requesting resend frame " << j << std::endl;
#endif

	//make type 0 frame with data byte holding ones for received an zeroes for resend
	makeFrame((MY_ADDRESS<<ADDRESS)|(1<<EOT),request);
	replyGenerated = 1;
}
예제 #14
0
/*
	UPDATES THE GAME CLOCK, KEEPS TRACK OF TIME, VIEWPORT LOCATION
*/
void Manager::update() {
  ++clock;
  Uint32 ticks = clock.getElapsedTicks();
  checkForCollisions(ticks);
  for(unsigned int i = 0; i < sprites.size(); ++i)
		sprites[i]->update(ticks);
  if ( makeVideo && frameCount < frameMax ) {
		makeFrame();
  }

  world.update();
  viewport.update();
  //player->updateVelocity();
}
예제 #15
0
DWORD L_DATA_indication(long source, long destination)
{   
      
    if(mode == 1){printf("\nL_DATA_indication\n");}
    
   if(side == 0)//nos llega un dato correcto en el emisor, por tanto, lo obtenemos
   {
      catchData(fI);
   }
   else//nos llega un dato correcto en el receptor y por tanto tenemos que mandar ACK y obtenerlo
   {
      makeFrame(ackFrame,NULL);      
      catchData(fD);
   }
      
   return 0;
}
//*****
void DtmfDataLinkLayer::resendData(unsigned int request)
{
	//iterate through databyte
	for(int i=0;i<8;i++)
	{
		//resend requested frames
		if((bool)(request & (1<<i)) == 0)
		{
			makeFrame(
					(3<<TYPE)| //type 3
					(currentReceiver<<ADDRESS)| //receiver address
					(i<<SEQUENCE), //sequence number
					frameSendList[i].dataByte); //data
		}
	}
	//set EOT bit in last frame
	endTransmission();
}
//*****
void DtmfDataLinkLayer::processDatagram(unsigned int incoming)
{
	dataInSendList = 1;

	//generate frame
	makeFrame(
			(3<<TYPE)| //type 3
			(currentReceiver<<ADDRESS)| //receiver address
			(nextInSendSequence<<SEQUENCE), //sequence number
			incoming); //data

	//put data in list
	frameSendList[nextInSendSequence].dataByte = incoming; //save data in list
	frameSendList[nextInSendSequence].flag = 1; //set flag

	//update sequence number
	nextInSendSequence++;
}
void DtmfDataLinkLayer::tokenOffered()
{
	//set time
	time ( &timestampToken );

	//acquire token
	hasToken = 1;

	//set next station to me (increased when offered)
	nextStation = MY_ADDRESS;

#ifdef DEBUG
	DEBUG_OUT << "Token offered" << std::endl;
	std::cout << "Token received " << ctime (&timestampToken) << std::endl;
#endif

	//make type 2 frame for station before me
	makeFrame((2<<TYPE)|(MY_ADDRESS<<ADDRESS),~0);
}
예제 #19
0
파일: manager.cpp 프로젝트: renmaoting/616
void Manager::update() {
  ++clock;
  Uint32 ticks = clock.getElapsedTicks();

  static unsigned int lastSeconds = clock.getSeconds();
  if ( clock.getSeconds() - lastSeconds == 5 ) {
    lastSeconds = clock.getSeconds();
    //switchSprite();
  }

  for (unsigned int i = 0; i < sprites.size(); ++i) {
    sprites[i]->update(ticks);
  }
  if ( makeVideo && frameCount < frameMax ) {
    makeFrame();
  }
  world.update();
  world2.update();
  viewport.update(); // always update viewport last
}
예제 #20
0
DWORD L_CONNECT_request(long source, long destination, int priority)//envia ENQ
{      
      struct Frame *f;
      int trys = 0;
      trysStadistics = 0;
      received=0;
      
      f = (struct Frame*) malloc(sizeof(Frame));
      
      if(mode == 1){printf("\nL_CONNECT_request\n");}

      while(trys != maxTrys)
      {
         //actualizamos la variable  maximo de trys intentados
         if(trysStadistics<trys) {trysStadistics=trys;}
         
         //creamos y enviamos la trama ENQ
        makeFrame(enqFrame, NULL);
         
         //esperamos hasta que haya algo para leer(quizas sea ACK o quizas no)       
         WaitForSingleObject(side_I_data_ready,timeout);
         
         //actualizamos las recibidas
         received++;
         
         switch(fI->type)
         {
            case ackFrame:
                  //actualizamos las correctas
                  correct++;       
                  return 0;
               break;
               
            default:               
                  trys++;              
               break;          
         }
      }
      //si finalmente se han agotado los intentos es que no hemos conseguido contactar cn el receptor
      return 1;     
}
예제 #21
0
DWORD L_CONNECT_response(long source, long destination, int priority)//envia ACK
{
      int ret;
      HANDLE c;
      
      if(mode == 1){printf("\nL_CONNECT_response\n");}
      
      //abrimos el semaforo que indicara que la conexion se ha realizado
      c = OpenSemaphore(SEMAPHORE_ALL_ACCESS,TRUE,"semaphoreConexion");
      
      //creamos y enviamos la trama ACK
      makeFrame(ackFrame,NULL);
      
      //esperamos hasta que nos confirmen la conexion
      ret = WaitForSingleObject(c,timeout);
      
      //si no se ha complido el timeout significa que hemos conseguido conectarnos
      if(ret != WAIT_TIMEOUT){conexionOK = 1;}
             
      return 0;
}
예제 #22
0
DWORD L_DISCONNECT_request(long source, long destination)
{    
      int ret;
      
      if(mode == 1){printf("\nL_DISCONNECT_request\n");}
      
      ret = makeFrame(eotFrame, NULL);
      
      //estadisticas
      printStadistics();
      
      //para que no se cierre la tuberia antes de enviar
      Sleep(2000);
       
      //cerramos todos los ipcs
      liberateDll();
      CloseHandle(side_I_data_ready);
      CloseHandle(conexion);
      CloseHandle(waitingI);
       
      printf("\nDisconnect\n");
           
      return 0;          
}
예제 #23
0
// Allows us to apply userdefined functions
Value apply(Value function, Vector args) {
    if (function.type == primitiveType) {
        void *pointerToAVal = NULL;
        for(int i = 0; i < args.size; i++){
            getVectorItem(&args, i, &pointerToAVal);
            insertVectorItem(valGarbage, valGarbage->size, pointerToAVal);
        }
        return function.primitiveValue(args);
    }
    if (function.type == closureType) {
        Frame *newEnv = makeFrame(function.closureValue->env);
        Value formals = function.closureValue->formals;
        
        //check length
        Value shouldBeLast = getNth(formals.consValue, args.size-1); //should work
        if(args.size == 0) shouldBeLast.type = closeType;
        Value shouldNotExist = getNth(formals.consValue, args.size); //should fail
        if( (shouldBeLast.type == openType) || (shouldNotExist.type != openType) ){
            return evaluationError("expected different number of args than recieved");
        }

        // bind formals to actuals
        for(int i = 0; i < args.size; i++){
            Value sym = getNth(formals.consValue, i);
            void *storedVal = NULL;
            getVectorItem(&args, i, &storedVal); 
            insertVectorItem(&(newEnv->names), 0, (void *)strdup(sym.symbolValue));
            insertVectorItem(&(newEnv->values), 0, (void *)storedVal);
        }
        insertVectorItem(envGarbage, envGarbage->size, (void *)newEnv);
        
        return eval(function.closureValue->body, newEnv);
    }
    // Else, error
    return evaluationError("apply called on non-function");
}
예제 #24
0
파일: vm2tac.c 프로젝트: tctsigemura/C--
// 割り込み関数の入口
void vmEntryI(int depth) {
  for (int gr = 0; gr < AccSIZ; gr = gr + 1)    // アキュムレータを全て
    printf("\tPUSH\t%s\n", regs[gr]);           //   保存する
  makeFrame(depth);                             // スタックフレームを作る
}
예제 #25
0
파일: vm2tac.c 프로젝트: tctsigemura/C--
// カーネル関数の入口
void vmEntryK(int depth) {
  makeFrame(depth);                             // スタックフレームを作る
}
예제 #26
0
파일: vm2tac.c 프로젝트: tctsigemura/C--
// 関数の入口
void vmEntry(int depth) {
  makeFrame(depth);                             // スタックフレームを作る
  printf("\tCALL\t__stkChk\n");                 // スタックオーバーフローを
}                                               //   チェックする
예제 #27
0
파일: frame.cpp 프로젝트: silversthem/2f
Frame::Frame(float const &width,float const &height,std::string const &title)
{
	makeFrame(width,height,title);
}
예제 #28
0
DWORD L_DATA_request(long source, long destination, char* data)//envia los datos
{
      int ret;
      int trys = 0;
      trysStadistics = 0;
      
      if(mode == 1){printf("\nL_DATA_request\n");}
      
      if(side == 0)//si es el lado izquierdo seran datos normales (EMISOR)
      {        
         makeFrame(dataFrame,data);
           
         while(trys != maxTrys && conexionOK == 1)
         {
            //actualizamos los trys
            if(trysStadistics<trys){trysStadistics=trys;}
            
            //esperamos a que haya datos listos
            ret = WaitForSingleObject(side_I_data_ready,timeout);
                      
            if(ret == WAIT_TIMEOUT)//se ha cumplido el timeout, tenemos que reenviar la trama
            {
               trys++;
               makeFrame(dataFrame,data);
            }
            else//ha llegado un dato al buffer, vemos que es
            {
               //actualizamos recibidos
              received++;
              
              switch(fI->type)
              {
                  case ackFrame:
                        //actualizamos correctas
                        correct++;
                        //nos ha llegado confirmacion de que ha llegado el dato, cmbiamos la trama esperada
                        if(nSecuenceNext == 0)
                        {
                           nSecuenceNext = 1;
                        }
                        else
                        {
                           nSecuenceNext = 0;
                        }
                  break;
                     
                  case dataFrame:
                        //actualizamos correctas
                        correct++;
                        
                        //cmbiamos el T-siguiente y salimos para llamar a indication                       
                        if(nSecuenceNext == 0)
                        {
                           nSecuenceNext = 1;
                        }
                        else
                        {
                           nSecuenceNext = 0;
                        }
                       
                        return 0;
                  break;         
               }    
            }
         }
         return 1;
      }
      else//si es el lado derecho tiene que traducirlos a morse(RECEPTOR)
      {
          
         if(data == NULL)//en esta llamada no tiene datos que enviar, solo espera por ellos
         {   
            //esperamos por los datos   
            ret = WaitForSingleObject(side_D_data_ready,timeout);
            
            //antes de hacer cualquier cosa comprobamos si seguimos conectados
            if(conexionOK == 0){return 1;}
            
            //se ha cumplido el timeout, no ha llegado nada
            if(ret == WAIT_TIMEOUT){return 3;}
            
            //actualizamos los recibidos
            received++;
            
            switch(fD->type)
            {
               case dataFrame:                
                     //actualizamos correctas
                     correct++;
                     
                     //el numero de secuencia de la trama es el mismo que el esperado, por tanto lo cambiamos
                     if(fD->nSecuence == nSecuenceWait)
                     {
                        if(nSecuenceWait == 0)
                        {
                           nSecuenceWait = 1;
                        }
                        else
                        {
                           nSecuenceWait = 0;
                        }
                        
                        return 0;                     
                     }
                     else
                     {
                        //no es el mismo, por tanto tenemos que reenviar el dato anterior
                        return 0;                 
                     }
                     
                  break;
                
                  case eotFrame:
                     //actualizamos correctas
                     correct++;
                     return 1;                     
                  break;
                     
                  default://no ha llegado nada correcto
                        return 3;
                  break;              
               }
         }
         else
         {     
                     
            if(conexionOK == 0){return 1;}//si por cualquier casual se corta la conexion
            
            //tenemos que enviar el dato en morse
            makeFrame(morseFrame,data);
            
            return 2;
         }
      }    
}
예제 #29
0
void Manager::update() {
  ++clock;
  
  world_back.update();
  world_front.update();
  
    
  Uint32 ticks = clock.getElapsedTicks();
  

  sprites[0]->update(ticks);//update our hero Rayman

  for (unsigned int i = 1; i < sprites.size(); ++i)// update pinkGear start @ 1 position
  {
    //Begin to update the relationship between fist and Rayman
    //if fist exist and it is now update fist
    if(fistStartPos != 0 && i >= fistStartPos){  
      sprites[i]->update(ticks, sprites[0]);
      if(abs(sprites[i]->X() - sprites[0]->X()) > sprites[i]->getFistRange() ){
          fistReadyToTurn = true;
      }
      if(spriteConflict(sprites[i],sprites[0]) && fistReadyToTurn){// the fist gets back to Rayman
        sprites.erase(sprites.begin() + i);
        fistStartPos = 0;
        fistReadyToTurn = false;
        singlePostion--;
        onceTouch = false;//so the fist can hit the bird again
      }
    }
    else{// if the fist hit the sprite
      sprites[i]->update(ticks);
      if (spriteConflict(sprites[i], sprites[fistStartPos]) 
          && !static_cast<pinkGear*>(sprites[i])-> getAlreadyHit()
          && fistStartPos != 0
          && !onceTouch){

        //give a sound to the sprite
        sound[0];
        onceTouch = true;
        int chealth;
        //the health bar get shorter
        if(!unlimitedMode){
          chealth = static_cast<pinkGear*>(sprites[i])->getCurrentHealth();
          static_cast<pinkGear*>(sprites[i])->setCurrentHealth(--chealth);
          bar.update(chealth);
        }

        //if the health bar equal to zero
        if(chealth == 0){

          pinkGear *tmp = static_cast<pinkGear*>(sprites[i]);   
          sprites[i] = new ExplodingSprite( *tmp );
          static_cast<pinkGear*>(sprites[i])-> setAlreadyHit(true);
          delete tmp;
          
          /*
            std::cout<<"hello"<<std::endl;
            sprites[i] = freeVector[i];
          */
          }

      }
    }
  }

  if ( makeVideo && frameCount < frameMax ) {
    makeFrame();
  }

  viewport.update(); 
}