int PressSensor::readEvents(sensors_event_t* data, int count)
{
	int i;
    if (count < 1)
        return -EINVAL;

    ssize_t n = mInputReader.fill(data_fd);
    if (n < 0)
        return n;

    int numEventReceived = 0;
    input_event const* event;

    while (count && mInputReader.readEvent(&event)) {
        int type = event->type;
        if ((type == EV_ABS) || (type == EV_REL) || (type == EV_KEY)) {
            processEvent(event->code, event->value);
            mInputReader.next();
        } else if (type == EV_SYN) {
            int64_t time = timevalToNano(event->time);
			for(i = 0 ; i< sensors && mPendingMask && count ;i++){
			  	 	if(mPendingMask & (1 << i)){
						mPendingMask &= ~(1 << i);
						mPendingEvent[i].timestamp = time;
						if (mEnabled[i]) {
							*data++ = mPendingEvent[i];
							count--;
							numEventReceived++;
						}
			  	 	}
	       }
		   if (!mPendingMask) {
		       mInputReader.next();
		   }
        } else {
            mInputReader.next();
        }
    }

    return numEventReceived;
}
Esempio n. 2
1
int main(void) {

    PlatformState state;
    SDL_Event e;
    SDL_Window *window;
    SDL_Renderer *renderer;
    SDLInputContext sdlIC;
    SDLSoundRingBuffer srb;
    GameSoundOutput sb;
    GameMemory gameMemory;

    //controller input state
    InputContext inputStates[2]; //contains old and new state
    InputContext* newInputState = &inputStates[0];
    InputContext* oldInputState = &inputStates[1];
    real32_t secsSinceLastFrame = 0;


    sb.volume = 2500;

    gameMemory.permanentStorageSize = MB(64);
    gameMemory.transientStorageSize = MB(64);
    state.gameMemorySize = gameMemory.transientStorageSize + gameMemory.permanentStorageSize;
    state.memoryBlock = mmap(nullptr, state.gameMemorySize, PROT_READ | PROT_WRITE,
            MAP_ANONYMOUS | MAP_PRIVATE ,
            -1,
            0);
    gameMemory.permanentStorage = state.memoryBlock;
    gameMemory.transientStorage = (uint8_t*)(gameMemory.transientStorage) + gameMemory.transientStorageSize;


    initSDL(&window, &renderer, &gOsb, &sdlIC, &srb);

    GameCode gameCode = loadGameCode();

    assert(gameCode.guarf);

    uint64_t startCount = SDL_GetPerformanceCounter();
    real32_t targetFrameSeconds = 1./getRefreshRate(window);

    SDL_PauseAudio(0);
    while(state.running) {

        if(getCreateTimeOfFile(GAME_LIB_PATH) != gameCode.dateLastModified) {
            reloadGameCode(&gameCode);
        }

        //keyboard input
        ControllerInput* newKeyInput = getContoller(newInputState, 0);

        //TODO: figure out why this is special
        ControllerInput* oldKeyInput = getContoller(oldInputState, 0);
        *newKeyInput = {};

        for(size_t i = 0; i < ARRAY_SIZE(oldKeyInput->buttons); i++) {
            newKeyInput->buttons[i] = oldKeyInput->buttons[i];
        }
        while(SDL_PollEvent(&e)) {
            processEvent(&e, newInputState, &state);
        }


        //controller input
        for(int i = 0; i < MAX_SDL_CONTROLLERS; i++) {
            if(sdlIC.controllers[i] != nullptr && SDL_GameControllerGetAttached(sdlIC.controllers[i])) {

                ControllerInput* newCIState = getContoller(newInputState, i+1);
                ControllerInput* oldCIState = getContoller(oldInputState, i+1);


                int16_t xVal = SDL_GameControllerGetAxis(sdlIC.controllers[i], SDL_CONTROLLER_AXIS_LEFTX);
                int16_t yVal = SDL_GameControllerGetAxis(sdlIC.controllers[i], SDL_CONTROLLER_AXIS_LEFTY);

                newCIState->avgX = normalizeStickInput(xVal, LEFT_THUMB_DEADZONE);
                newCIState->avgY = normalizeStickInput(yVal, LEFT_THUMB_DEADZONE);

                if(newCIState->avgX != 0 || newCIState->avgY != 0) {
                    newCIState->isAnalog = true;
                }

                processControllerButtonInput(&newCIState->actionDown, &oldCIState->actionDown, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_A);
                processControllerButtonInput(&newCIState->actionUp, &oldCIState->actionUp, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_Y);
                processControllerButtonInput(&newCIState->actionLeft, &oldCIState->actionLeft, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_X);
                processControllerButtonInput(&newCIState->actionRight, &oldCIState->actionRight, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_B);

                processControllerButtonInput(&newCIState->directionDown, &oldCIState->directionDown, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_DPAD_DOWN);
                processControllerButtonInput(&newCIState->directionUp, &oldCIState->directionUp, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_DPAD_UP);
                processControllerButtonInput(&newCIState->directionLeft, &oldCIState->directionLeft, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_DPAD_LEFT);
                processControllerButtonInput(&newCIState->directionRight, &oldCIState->directionRight, &newCIState->isAnalog, sdlIC.controllers[i], SDL_CONTROLLER_BUTTON_DPAD_RIGHT);

                oldCIState->isAnalog = newCIState->isAnalog;


            }
            else {
                //TODO: Logging
            }
        }


        //TODO: Do this instead of processing input, not after
        //process recording/playback
        assert(!(state.isRecording && state.isPlayingBack));

        if(state.isRecording) {
            recordInput(newInputState, state.inputRecordFile);
        }

        if(state.isPlayingBack) {
            playInput(newInputState, state.inputRecordFile);
        }

        //calculate audio buffers' indicies and sizes
        SDL_LockAudioDevice(1);
        uint32_t startIndex = srb.runningIndex % ARRAY_SIZE(srb.samples);
        uint32_t endIndex = (srb.sampleToPlay + SOUND_LATENCY) % ARRAY_SIZE(srb.samples);
        uint32_t samplesToGetFromGame = (startIndex <= endIndex) ? endIndex - startIndex : (ARRAY_SIZE(srb.samples) - startIndex) + endIndex; 
        sb.numSamples = samplesToGetFromGame;
        SDL_UnlockAudioDevice(1);



        gameCode.guarf(&gameMemory, &gOsb, &sb, newInputState, secsSinceLastFrame);

        updateSDLSoundBuffer(&srb, &sb, startIndex, endIndex);
        updateWindow(window, gTexture);

        InputContext* temp = newInputState;
        newInputState = oldInputState;
        oldInputState = temp;

        //benchmark stuff

        real32_t secsElapsed = secondsForCountRange(startCount, SDL_GetPerformanceCounter());

        //sleep to lock frame rate
        if(secsElapsed < targetFrameSeconds) {


            //NOTE: .5 denotes the amount we will spin manually since
            //      SDL_Delay is not 100% accurate
            real32_t timeToSleep = (targetFrameSeconds - secsElapsed)*1000 - .5;
            SDL_Delay(timeToSleep);
            secsElapsed = secondsForCountRange(startCount, SDL_GetPerformanceCounter());
            
            //This assert will fire if the window is moved
            //assert(secondsForCountRange(startCount, SDL_GetPerformanceCounter()) < targetFrameSeconds); 
            
            while(secondsForCountRange(startCount, SDL_GetPerformanceCounter()) < targetFrameSeconds) {
                //wait
            }
            secsElapsed = secondsForCountRange(startCount, SDL_GetPerformanceCounter());
        }
        uint64_t endCount = SDL_GetPerformanceCounter();
        real32_t fpsCount =  ((1./secsElapsed));
        real32_t mcPerFrame = (real32_t)(endCount-startCount) / (1000 * 1000 );


        printf("TPF: %.2fms FPS: %.2f MCPF: %.2f\n", secsElapsed*1000, fpsCount, mcPerFrame);

        startCount = endCount;
        secsSinceLastFrame = secsElapsed;
    }

    cleanUp(&state, &gameCode);
    return 0;
}
Esempio n. 3
0
int SensorBase::readEvents(sensors_event_t* data, int count)
{
    if (count < 1)
        return -EINVAL;

    ssize_t n = mInputReader.fill(data_fd);
    if (n < 0)
        return n;

    int numEventReceived = 0;
    input_event const* event;

    while (count && mInputReader.readEvent(&event)) {
        int type = event->type;
        if (type == EV_ABS) {
            processEvent(event->code, event->value);
            mInputReader.next();
        } else if (type == EV_SYN) {
            int64_t time = timevalToNano(event->time);

            for (int j=0 ; count && mPendingMask && j<numSensors ; j++) {

                if (mPendingMask & (1<<j)) {
                    mPendingMask &= ~(1<<j);
                    mPendingEvents[j].timestamp = time;
                    if (mEnabled & (1<<j)) {
                        *data++ = mPendingEvents[j];
                        count--;
                        numEventReceived++;
                    }
                }
            }
            if (!mPendingMask) {
                mInputReader.next();
            }
        } else {
            ALOGE("Sensor: unknown event (type=%d, code=%d)",
                    type, event->code);
            mInputReader.next();
        }
    }

    return numEventReceived;
}
void TOOL_MANAGER::RunAction( const TOOL_ACTION& aAction, bool aNow, void* aParam )
{
    TOOL_EVENT event = aAction.MakeEvent();

    // Allow to override the action parameter
    if( aParam )
        event.SetParameter( aParam );

    if( aNow )
    {
        TOOL_STATE* current = m_activeState;
        processEvent( event );
        setActiveState( current );
    }
    else
    {
        PostEvent( event );
    }
}
Esempio n. 5
0
int main(){
  auto reader = podio::ROOTReader();
  auto store = podio::EventStore();
  reader.openFile("example1.root");
  store.setReader(&reader);

  bool verbose = true;

  unsigned nEvents = reader.getEntries();
  for(unsigned i=0; i<nEvents; ++i) {
    if(i%1000==0)
      std::cout<<"reading event "<<i<<std::endl;
    processEvent(store, true, i);
    store.clear();
    reader.endOfEvent();
  }
  reader.closeFile();
  return 0;
}
Esempio n. 6
0
void manageEvents() {
	Common::EventManager *eventMan = g_system->getEventManager();

	uint32 nextFrame = g_system->getMillis() + g_cine->getTimerDelay();
	do {
		Common::Event event;
		while (eventMan->pollEvent(event)) {
			processEvent(event);
		}
		g_system->updateScreen();
		g_system->delayMillis(20);
	} while (g_system->getMillis() < nextFrame);

	g_sound->update();
	mouseData.left = mouseLeft;
	mouseData.right = mouseRight;
	mouseLeft = 0;
	mouseRight = 0;
}
Esempio n. 7
0
void App::run() {

	pRenderer = Renderer::getInstance();

    const double TIME_STEP = 0.01;
  
    register double last_ticks = SDL_GetTicks() * 0.001;
    register double current_ticks( 0.0 );

    while ( !pGame->isDone() ) { 

        //time update
    	current_ticks = SDL_GetTicks() * 0.001;

    	if( current_ticks >= last_ticks ) {
    		last_ticks += 0.001;

         	pGame->update( TIME_STEP );
    		pRenderer->cleanScreen();
    		pGame->draw();
    		pRenderer->flip();

    	}
    	else {
    		int sleep_time = (int) (current_ticks- last_ticks)*1000;
    		SDL_Delay( sleep_time );

    		logger.warring("Sleep");
    	}

    	processEvent();

    	// Zliczanie klatek
		#ifdef DEBUG
        	if( SHOW_FPS ) ++pframeRating; // Licznik wyswietlonych klatek w danej jednostce czasu
		#endif

	SDL_Delay( 0 );

    }//END WHILE

}
Esempio n. 8
0
int GEngine::gameLoop() {

	if (m_errorState == true) {
		setErrorDetails(
				"Cannot enter game loop when the engine is in a error state");
		return -1;
	}

	m_GameActive = true;
	m_physicsActive = true;

	m_clock.initialize();
	float secondsPassed;

	while (m_GameActive) {

		secondsPassed = m_clock.calculateElapsedTime();

		//Alert to the FPS calculator of a new frame
		m_fpsCalculator.frame(secondsPassed);

		//Run through the postbox and trigger events
		while (m_inputPostbox.HasNext()) {

			processEvent(m_inputPostbox.ReadNext());

		}

		doFrameUpdate(secondsPassed);

		//Rendering Step

		GRenderer::getRenderer()->renderScene(m_canvasWidth, m_canvasHeight);

		//End of rendering step

		//Sleep
		f_sleep();
	}

	return 0;
}
Esempio n. 9
0
static LRESULT CALLBACK BSPanelProc(HWND hWnd,
                                    UINT uMsg,
                                    WPARAM wParam,
                                    LPARAM lParam)
{
    if (WM_NCCREATE == uMsg && ::GetWindowLongPtr(hWnd, GWLP_USERDATA) == 0)
    {
        LPCREATESTRUCT lcp = reinterpret_cast<LPCREATESTRUCT>(lParam);
        BSPanel * panel = reinterpret_cast<BSPanel *>(lcp->lpCreateParams);
        panel->attach(hWnd);
        ::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG>(panel));
    }

    LONG user_data = ::GetWindowLongPtr(hWnd, GWLP_USERDATA);
    auto sheet = reinterpret_cast<BSPanel *>(user_data);
    if (sheet)
        return sheet->processEvent(uMsg, wParam, lParam);

    return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Esempio n. 10
0
int execute() {
    if(init() == false) {
        return -1;
    }

    SDL_Event Event;

    while(Running) {
        while(SDL_PollEvent(&Event)) {
            processEvent(&Event);
        }

        update();
        draw();
    }

    cleanup();

    return 0;
}
Esempio n. 11
0
void PmInput::run() {
	QFile device(devicename);

	if(!device.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {
		qDebug() << "Error opening device " << device.fileName()
			<< ": " << device.error();
		return;
	}

	struct input_event iev;
	while(1) {
		int r = device.read((char*)&iev, sizeof(struct input_event));
		if(r==0) break;
		if(r!=sizeof(struct input_event)) {
			qDebug() << "read only " << r << "bytes, expected " << sizeof(struct input_event);
		} else {
			processEvent(iev);
		}
	}
}
bool TOOL_MANAGER::processEvent( const TOOL_EVENT& aEvent )
{
    // Early dispatch of events destined for the TOOL_MANAGER
    if( !dispatchStandardEvents( aEvent ) )
        return true;

    dispatchInternal( aEvent );
    dispatchActivation( aEvent );
    dispatchContextMenu( aEvent );

    // Dispatch queue
    while( !m_eventQueue.empty() )
    {
        TOOL_EVENT event = m_eventQueue.front();
        m_eventQueue.pop_front();
        processEvent( event );
    }

    return false;
}
bool TOOL_MANAGER::ProcessEvent( const TOOL_EVENT& aEvent )
{
    bool hotkey_handled = processEvent( aEvent );

    if( TOOL_STATE* active = GetCurrentToolState() )
        setActiveState( active );

    if( m_view->IsDirty() )
    {
        auto f = dynamic_cast<EDA_DRAW_FRAME*>( GetEditFrame() );

        if( f )
            f->GetGalCanvas()->Refresh(); // fixme: ugly hack, provide a method in TOOL_DISPATCHER.

#if defined( __WXMAC__ ) || defined( __WINDOWS__ )
        wxTheApp->ProcessPendingEvents(); // required for updating brightening behind a popup menu
#endif
    }

    return hotkey_handled;
}
Esempio n. 14
0
/*
 * Animate to the rpgcode screen (for RPGCode functions).
 */
void CAnimation::animate(const int x, const int y)
{
	extern CCanvas *g_cnvRpgCode;
	extern void processEvent();

	// Copy the screen.
	const CCanvas cnvScr = *g_cnvRpgCode;

	std::vector<CCanvas *>::iterator i = m_canvases.begin(), start = i;
	for (; i != m_canvases.end(); ++i)
	{
		if (!*i)
		{
			*i = new CCanvas();
			(*i)->CreateBlank(NULL, m_data.pxWidth, m_data.pxHeight, TRUE);
			if (!(this->*renderFrame)(*i, i - start)) continue;
		}

		// Place on g_cnvRpgCode.
		(*i)->BltTransparent(g_cnvRpgCode, x, y, TRANSP_COLOR);

		// Refresh the screen.
		processEvent();
		renderRpgCodeScreen();

		// Play the frame's sound.
		playFrameSound(i - start);

		Sleep(DWORD(m_data.delay * MILLISECONDS));

		// Replace g_cnvRpgCode with the original.
		cnvScr.BltPart(
			g_cnvRpgCode, 
			x, y, 
			x, y, 
			m_data.pxWidth, m_data.pxHeight,
			SRCCOPY
		);
	}
}
Esempio n. 15
0
/**
 * Displays window and updates camera, processes events until
 * window is closed
 */
void FlyerWindow::run()
{
    App.SetActive();
    while(App.IsOpened())
    {
        // Move camera forward
        float const elapsedTime = App.GetFrameTime();
        cam.moveForward(speed * elapsedTime);

        // Handle any events that have occured
        sf::Event Event;
        while(App.GetEvent(Event))
        {
            processEvent(Event);
        }

        // Update screen
        cam.look();
        paint();
        App.Display();
    }
}
Esempio n. 16
0
bool BaseAppInput::runFrame(void)
{
	//ideally, we would be using events. However, that tended to result in either segfaults or a hang when I tried it. *sigh*
	//so, we'll fake events on our own
	if (! handleKeyboard(NULL) || ! handleMouse())
	{
		return false;
	}
	
	SDL_Event evt;
	while (SDL_PollEvent(&evt)) //need to make sure it's not null
	{
		if (!processEvent(&evt))
		{
			return false;
		}
	}
	
	frameDone();
	
	return true;
}
Esempio n. 17
0
/**
 * Actually run the game:
 * process events, advance through generations and draw the cells
 *
 * @see{
 *  Game::setCell
 *  Game::setCells
 *  Game::processEvent
 * }
 */
void Game::run(){
    SDL_Event event;

    while(running){
        while(SDL_PollEvent(&event)){
            processEvent(&event);
        }

        std::pair<positions_t, positions_t> positions = life->evolve();

        std::vector<SDL_Rect> cell_rects(setCells(positions.first, alive_color));
        std::vector<SDL_Rect> dead_cell_rects(
            setCells(positions.second, dead_color));

        cell_rects.insert(cell_rects.end(), dead_cell_rects.begin(),
            dead_cell_rects.end());

        SDL_UpdateRects(screen, cell_rects.size(), cell_rects.data());

        SDL_Delay(interval);
    }
}
Esempio n. 18
0
PSMResult PSM_PollNextMessage(PSMMessage *message, size_t message_size)
{
    PSMResult result= PSMResult_Error;

    // Poll events queued up by the call to ClientPSMoveAPI::update()
    ClientPSMoveAPI::Message message_internal;
    if (ClientPSMoveAPI::poll_next_message(&message_internal, sizeof(message_internal)))
    {
        assert(sizeof(PSMMessage) == message_size);
        assert(message != nullptr);

        switch (message_internal.payload_type)
        {
        case ClientPSMoveAPI::_messagePayloadType_Response:
            {
                message->payload_type= PSMMessage::_messagePayloadType_Response;
                extractResponseMessage(&message_internal.response_data, &message->response_data);
            } break;
        case ClientPSMoveAPI::_messagePayloadType_Event:
            {
                // Update event flags before handling off the event
                processEvent(&message_internal.event_data);

                // Package up the event
                message->payload_type= PSMMessage::_messagePayloadType_Event;
                message->event_data.event_type= static_cast<PSMEventMessage::eEventType>(message_internal.event_data.event_type);
                message->event_data.event_data_handle= static_cast<PSMEventDataHandle>(message_internal.event_data.event_data_handle);

            } break;
        default:
            assert(0 && "unreachable");
        }

        result= PSMResult_Success;
    }

    return result;
}
Esempio n. 19
0
void UserInfo::saveInfo()
{
    if (m_nUin){
        ICQUser *u = pClient->getUser(m_nUin);
        if (u){
            inSave = true;
            emit saveInfo(u);
            inSave = false;
            ICQEvent e(EVENT_INFO_CHANGED, m_nUin);
            processEvent(&e);
            if (u->bIsTemp)
                pClient->getUser(m_nUin, true);
        }
    }else{
        ICQGroup *g = NULL;
        if (m_nGrpId)
            g = pClient->getGroup(m_nGrpId);
        inSave = true;
        emit saveInfo(g);
        inSave = false;
    }
    close();
}
Esempio n. 20
0
/*
	Main Function

*/
void Game::run()
{
	init();
	
	///			GAME LOOP		///
	while (event_.type != SDL_QUIT)
	{
		processEvent();
		
		// No delay when life is not activated
		if (!worldManager_.getLifeStatus())
		{
			update();
			draw();
		}
		else
		{
			// Delay
			fpsManager_.begin();
			
			static int extraDelay = 0;
			if (extraDelay < FpsConst::EXTRADELAY) extraDelay++;
			else
			{
				update();
				draw();
				extraDelay = 0;
			}
				
			fpsManager_.end();
			
			fpsS_ << "FPS: " << fpsManager_.getFps();
			fpsMessage_ = fpsS_.str();
			fpsS_.str("");
		}
	}
}
Esempio n. 21
0
int main() {
    window = new sf::RenderWindow(sf::VideoMode(RES_X, RES_Y), "I love this Game");

    sf::Clock clock;
    float frameTime = 1/60.0f;
    float dTime = 0;

    initialiseGame();

    while (window->isOpen()) {
        dTime += clock.getElapsedTime().asSeconds();
        clock.restart();

        // Event handling
        sf::Event event;
        while(window->pollEvent(event)) {
            processEvent(event);
        }

        // Safeguard (slowdown) to prevent game from lagging to death
        if (dTime > 5*frameTime) dTime = 5*frameTime;

        // Update game
        while (dTime > frameTime) {
            dTime -= frameTime;
            updateGame();
        }

        // Draw frame
        window->clear();
        drawGameFrame();
        window->display();
    }

    delete window;
    return 0;
}
int Accelerometer::readEvents(sensors_event_t* data, int count) {
	if (count < 1)
		return -EINVAL;

	ssize_t n = mInputReader.fill(data_fd);
	if (n < 0)
		return n;

	int numEventReceived = 0;
	input_event const* event;

	while (count && mInputReader.readEvent(&event)) {
		int type = event->type;
		if (type == EV_ABS) {
			processEvent(event->code, event->value);
		} else if (type == EV_SYN) {
			int64_t time = timevalToNano(event->time);
			mPendingEvent.timestamp = time;
			if (mEnabled) {
				*data++ = mPendingEvent;
				count--;
				numEventReceived++;
				/* FOR DEBUG
				LOGE("Accelerometer: x = %f, y = %f, z = %f",
						mPendingEvent.acceleration.x,
						mPendingEvent.acceleration.y,
						mPendingEvent.acceleration.z);
				*/
			}
		} else {
			LOGE("Accelerometer: unknown event (type=%d, code=%d)", type,
					event->code);
		}
		mInputReader.next();
	}
	return numEventReceived;
}
Esempio n. 23
0
  void AbstractDevice::eventThread() {
    ADR_GUARD("AbstractDevice::eventThread");
    m_thread_exists = true;
    while (!m_thread_should_die) {
      m_event_mutex.lock();
      while (m_events.empty()) {
        m_events_available.wait(m_event_mutex, 1);
        if (m_thread_should_die) {
          break;
        }
      }
      if (m_thread_should_die) {
        m_event_mutex.unlock();
        break;
      }

      // Make a local copy of the events so they can be processed without
      // leaving the mutex locked.
      EventQueue events = m_events;

      // Queues don't support clear().  o_o
      while (!m_events.empty()) {
        m_events.pop();
      }

      m_event_mutex.unlock();

      // Process the events.
      while (!events.empty()) {
        EventPtr event = events.front();
        events.pop();
        processEvent(event.get());
      }
    }
    m_thread_exists = false;
  }
Esempio n. 24
0
///////////////////////////////////////////////////////////////////////////////
/// \brief static thread function passed to pthread. opens the device and 
///  attempts to process inputs from it.
///
void* InputHandler :: thread_func ( void* in_ptr )
{
  if ( in_ptr == NULL )
  {
    rt_printf ( "InputHandler :: thread_func: received invalide pointer" ) ;
    return NULL ;
  }

  std :: string *filename = ( std :: string* ) in_ptr ;
  int fd = -1 ;

  if ( ( fd = open ( filename -> c_str () , O_RDONLY ) ) < 0 ) {
    perror("evdev open");
    return NULL ; //exit(1);
  }

  mqd_t output = mq_open ( BBT_EVENT_QUEUE_NAME
                      , O_WRONLY ) ;

  if ( output < 0 )
  {
    rt_printf ( "InputHandler: failed to open queue" ) ;
  }

  struct input_event ev;
  while ( 1 )
  {
    size_t rb = read ( fd , &ev , sizeof ( struct input_event ) ) ;
    if ( rb > 0 )
      processEvent ( ev , output ) ;
  }

  mq_close ( output ) ;
  close ( fd ) ;
  return NULL ;
}
Esempio n. 25
0
void *UserListBase::processEvent(Event *e)
{
    if (e->type() == EventRepaintView)
        viewport()->repaint();
    if (m_bInit){
        switch (e->type()){
        case EventGroupCreated:{
                Group *g = (Group*)(e->param());
                addGroupForUpdate(g->id());
                break;
            }
        case EventGroupChanged:{
                Group *g = (Group*)(e->param());
                addGroupForUpdate(g->id());
                break;
            }
        case EventGroupDeleted:{
                Group *g = (Group*)(e->param());
                for (list<unsigned long>::iterator it = updGroups.begin(); it != updGroups.end(); ++it){
                    if (*it == g->id()){
                        updGroups.erase(it);
                        break;
                    }
                }
                QListViewItem *item = findGroupItem(g->id());
                deleteItem(item);
                break;
            }
        case EventContactCreated:{
                Contact *c = (Contact*)(e->param());
                if (!c->getIgnore() && (c->getTemporary() == 0))
                    addContactForUpdate(c->id());
                break;
            }
        case EventContactStatus:
        case EventContactChanged:{
                Contact *c = (Contact*)(e->param());
                if (!c->getIgnore() && (c->getTemporary() == 0)){
                    addContactForUpdate(c->id());
                }else{
                    Event e(EventContactDeleted, c);
                    processEvent(&e);
                }
                break;
            }
        case EventMessageReceived:{
                Message *msg = (Message*)(e->param());
                if (msg->type() == MessageStatus){
                    Contact *contact = getContacts()->contact(msg->contact());
                    if (contact)
                        addContactForUpdate(contact->id());
                }
                break;
            }
        case EventContactDeleted:{
                Contact *g = (Contact*)(e->param());
                for (list<unsigned long>::iterator it = updContacts.begin(); it != updContacts.end(); ++it){
                    if (*it == g->id()){
                        updContacts.erase(it);
                        break;
                    }
                }
                ContactItem *item = findContactItem(g->id());
                if (item){
                    if (m_groupMode){
                        GroupItem *grpItem = static_cast<GroupItem*>(item->parent());
                        grpItem->m_nContacts--;
                        if (item->m_bOnline)
                            grpItem->m_nContactsOnline--;
                        addGroupForUpdate(grpItem->id());
                        deleteItem(item);
                        if ((m_groupMode == 2) &&
                                (grpItem->firstChild() == NULL) &&
                                m_bShowOnline){
                            DivItem *div = static_cast<DivItem*>(grpItem->parent());
                            if (div->state() == DIV_OFFLINE){
                                deleteItem(grpItem);
                                if (div->firstChild() == NULL)
                                    deleteItem(div);
                            }
                        }
                    }else{
                        QListViewItem *p = item->parent();
                        deleteItem(item);
                        if (p->firstChild() == NULL)
                            deleteItem(p);
                    }
                }
                break;
            }
        }
    }
    return ListView::processEvent(e);
}
Esempio n. 26
0
 bool Frame::processEvent(const sf::Event& event)
 {
     return processEvent(event,sf::Vector2f(0,0));
 }
Esempio n. 27
0
int main(int argc, char **argv)
{
    swss::Logger::getInstance().setMinPrio(swss::Logger::SWSS_DEBUG);

    SWSS_LOG_ENTER();

    auto options = handleCmdLine(argc, argv);

    handleProfileMap(options.profileMapFile);

    swss::DBConnector *db = new swss::DBConnector(ASIC_DB, "localhost", 6379, 0);
    swss::DBConnector *dbNtf = new swss::DBConnector(ASIC_DB, "localhost", 6379, 0);

    g_redisClient = new swss::RedisClient(db);

    updateLogLevel();

    swss::ConsumerTable *asicState = new swss::ConsumerTable(db, "ASIC_STATE");
    swss::NotificationConsumer *notifySyncdQuery = new swss::NotificationConsumer(db, "NOTIFYSYNCDREQUERY");
    swss::NotificationConsumer *restartQuery = new swss::NotificationConsumer(db, "RESTARTQUERY");

    // at the end we cant use producer consumer concept since
    // if one proces will restart there may be something in the queue
    // also "remove" from response queue will also trigger another "response"
    getRequest = new swss::ConsumerTable(db, "GETREQUEST");
    getResponse  = new swss::ProducerTable(db, "GETRESPONSE");
    notifications = new swss::NotificationProducer(dbNtf, "NOTIFICATIONS");
    notifySyncdResponse = new swss::NotificationProducer(db, "NOTIFYSYNCDRESPONSE");

#ifdef MLNXSAI
    /* This file is included in Mellanox SAI package. */
    std::string mlnx_config_file = "/usr/share/sai_2700.xml";
    gProfileMap[SAI_KEY_INIT_CONFIG_FILE] = mlnx_config_file;
#endif /* MLNX_SAI */

    g_veryFirstRun = isVeryFirstRun();

    if (options.warmStart)
    {
        const char *warmBootReadFile = profile_get_value(0, SAI_KEY_WARM_BOOT_READ_FILE);

        SWSS_LOG_NOTICE("using warmBootReadFile: '%s'", warmBootReadFile);

        if (warmBootReadFile == NULL || access(warmBootReadFile, F_OK) == -1)
        {
            SWSS_LOG_WARN("user requested warmStart but warmBootReadFile is not specified or not accesible, forcing cold start");

            options.warmStart = false;
        }
    }

    if (options.warmStart && g_veryFirstRun)
    {
        SWSS_LOG_WARN("warm start requested, but this is very first syncd start, forcing cold start");

        // we force cold start since if it's first run then redis db is not complete
        // so redis asic view will not reflect warm boot asic state, if this happen
        // then orch agent needs to be restarted as well to repopulate asic view
        options.warmStart = false;
    }

//    gProfileMap[SAI_KEY_WARM_BOOT] = options.warmStart ? "1" : "0";

    sai_api_initialize(0, (service_method_table_t*)&test_services);

    populate_sai_apis();

    initialize_common_api_pointers();

    sai_status_t status = sai_switch_api->initialize_switch(0, "0xb850", "", &switch_notifications);

    if (status != SAI_STATUS_SUCCESS)
    {
        SWSS_LOG_ERROR("fail to sai_initialize_switch: %d", status);
        exit(EXIT_FAILURE);
    }

#ifdef BRCMSAI

    if (options.diagShell)
    {
        SWSS_LOG_NOTICE("starting bcm diag shell thread");

        std::thread bcm_diag_shell_thread = std::thread(sai_diag_shell);
        bcm_diag_shell_thread.detach();
    }

#endif /* BRCMSAI */

    SWSS_LOG_NOTICE("syncd started");

    bool warmRestartHint = false;

    try
    {
        onSyncdStart(options.warmStart);

        if (options.disableCountersThread == false)
        {
            SWSS_LOG_NOTICE("starting counters thread");

            startCountersThread(options.countersThreadIntervalInSeconds);
        }

        SWSS_LOG_NOTICE("syncd listening for events");

        swss::Select s;

        s.addSelectable(getRequest);
        s.addSelectable(asicState);
        s.addSelectable(notifySyncdQuery);
        s.addSelectable(restartQuery);

        while(true)
        {
            swss::Selectable *sel;

            int fd;

            int result = s.select(&sel, &fd);

            if (sel == restartQuery)
            {
                warmRestartHint = handleRestartQuery(*restartQuery);
                break;
            }

            if (sel == notifySyncdQuery)
            {
                notifySyncd(*notifySyncdQuery);
                continue;
            }

            if (result == swss::Select::OBJECT)
            {
                processEvent(*(swss::ConsumerTable*)sel);
            }
        }
    }
    catch(const std::exception &e)
    {
        SWSS_LOG_ERROR("Runtime error: %s", e.what());

        exit(EXIT_FAILURE);
    }

    endCountersThread();

    if (warmRestartHint)
    {
        const char *warmBootWriteFile = profile_get_value(0, SAI_KEY_WARM_BOOT_WRITE_FILE);

        SWSS_LOG_NOTICE("using warmBootWriteFile: '%s'", warmBootWriteFile);

        if (warmBootWriteFile == NULL)
        {
            SWSS_LOG_WARN("user requested warm shutdown but warmBootWriteFile is not specified, forcing cold shutdown");

            warmRestartHint = false;
        }
    }

    sai_switch_api->shutdown_switch(warmRestartHint);

    SWSS_LOG_NOTICE("calling api uninitialize");

    sai_api_uninitialize();

    SWSS_LOG_NOTICE("uninitialize finished");

    return EXIT_SUCCESS;
}
Esempio n. 28
0
 void processKeys(void) {
     XEvent event;
     while (XCheckWindowEvent(display, window, StructureNotifyMask | KeyPressMask, &event)) {
         processEvent(event);
     }
 }
Esempio n. 29
0
/// @brief Issues an event without attached data to the widget of choice
/// @param type Type of event to issue
/// @param pContext [in-out] User-defined context parameter
/// @note Tested
void UserInterface::IssueBasicEvent (WidgetEventType type, void * pContext)
{
	void (*processEvent)(Uint32, WidgetEventType, void *) = Widget::Get(mChoice).mProcessEvent;

	if (processEvent != 0) processEvent(mChoice, type, pContext);
}
Esempio n. 30
0
File: event.c Progetto: Zoxc/gltron
void Game_Idle(void) {
  List *l;
  List *p;
  int i;
  int dt;
  int t;

	switch(game2->mode) {
	case GAME_SINGLE:
#ifdef RECORD
	case GAME_SINGLE_RECORD:
#endif
		/* check for fast finish */
    
		if (gSettingsCache.fast_finish == 1) {
			int factors[4] = { 4, 6, 12, 25 };
			int threshold[4] = { 0, 300, 600, 800 };
			int factor = 1;
			for(i = 0; i < 4; i++) {
				if(game2->rules.grid_size > threshold[i])
					factor = factors[i];
			}
			for (i = 0; i < game->players; i++) {
				if (game->player[i].ai->active != AI_COMPUTER &&
						gPlayerVisuals[i].exp_radius < EXP_RADIUS_MAX) {
					factor = 1;
				}
			}
			dt = game2->time.dt * factor;
		} else { 
			dt = game2->time.dt;
		}

		while(dt > 0) {
			if(dt > PHYSICS_RATE) t = PHYSICS_RATE;
			else t = dt;

			/* run AI */
			for(i = 0; i < game->players; i++)
				if(game->player[i].ai != NULL)
					if(game->player[i].ai->active == AI_COMPUTER &&
						 PLAYER_IS_ACTIVE(&game->player[i])) {
						doComputer(i, 0);
					}

			/* process any outstanding events (turns, etc) */
			for(p = &(game2->events); p->next != NULL; p = p->next) {
				if(processEvent((GameEvent*) p->data)) return;
			}

			/* free events */
			p = game2->events.next;
			while(p != NULL) {
				l = p;
				p = p->next;
				free(l);
			}
			game2->events.next = NULL;

			l = doMovement(1, t); /* this can generate new events */
			if(l != NULL) {
				for(p = l; p->next != NULL; p = p->next) {
					if(processEvent((GameEvent*) p->data));
				}

			}
			/* free list  */
			p = l;
			while(p != NULL) {
				l = p;
				p = p->next;
				free(l);
			}
			dt -= PHYSICS_RATE;
		}
		break;
#ifdef RECORD
	case GAME_PLAY_NETWORK:
		/* fall through to GAME_PLAY */
	case GAME_PLAY:
		getEvents(); 
		l = doMovement(0, game2->time.dt); /* this won't generate new events */
		if(l != NULL) {
			fprintf(stderr, "something is seriously wrong - ignoring events\n");
		}
		break;
#endif /* RECORD */
	}
    
	doCameraMovement();
	doRecognizerMovement();
}