Ejemplo n.º 1
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;
}
Ejemplo n.º 2
0
ButtonStatus
DecafSDL::getButtonStatus(vpad::Channel channel, vpad::Core button)
{
   if (!mVpad0Config) {
      return ButtonStatus::ButtonReleased;
   }

   switch (mVpad0Config->type) {
   case config::input::None:
      break;

   case config::input::Keyboard:
   {
      int numKeys = 0;
      auto scancode = getKeyboardButtonMapping(mVpad0Config, channel, button);
      auto state = SDL_GetKeyboardState(&numKeys);

      if (scancode >= 0 && scancode < numKeys && state[scancode]) {
         return ButtonStatus::ButtonPressed;
      }

      break;
   }

   case config::input::Joystick:
      if (mVpad0Controller && SDL_GameControllerGetAttached(mVpad0Controller)) {
         if (getJoystickButtonState(mVpad0Config, mVpad0Controller, channel, button)) {
            return ButtonStatus::ButtonPressed;
         }
      }
      break;
   }

   return ButtonStatus::ButtonReleased;
}
Ejemplo n.º 3
0
void GameController::closeSDLDevice()
{
    if (controller && SDL_GameControllerGetAttached(controller))
    {
        SDL_GameControllerClose(controller);
        controller = 0;
    }
}
Ejemplo n.º 4
0
bool isControllerButtonPressed(u32 controllerIndex, ControllerButton button)
{
	SDL_GameController* gc = g_controllerHandles[controllerIndex];
	if (gc && SDL_GameControllerGetAttached(gc))
		return SDL_GameControllerGetButton(gc, (SDL_GameControllerButton)button) != 0;

	return false;
}
Ejemplo n.º 5
0
int main(int argc, char* argv[]) {
  init(argc, argv, 800, 600);
  init_controllers_and_audio();
  game = new StateManager();
  glutMainLoop();
  if (SDL_GameControllerGetAttached(controller)) {
    SDL_GameControllerClose(controller);
  }
  delete game;
  return EXIT_SUCCESS;
}
Ejemplo n.º 6
0
int DEV_Joystick::Connected(void)
{
#ifdef WITH_SDL
	if (m_isinit &&
		(SDL_CHECK(SDL_GameControllerGetAttached) &&
		SDL_GameControllerGetAttached(m_private->m_gamecontroller)))
	{
		return 1;
	}
#endif
	return 0;
}
Ejemplo n.º 7
0
void PIN_GameControllerManager::CheckControllers()
{
    for(PIN_ControllerBaseList::iterator it = _controllerList.begin();
            it != _controllerList.end();/*it++*/)
    {
        PIN_GameControllerEntry* ctrl = (PIN_GameControllerEntry*)*it;
        if(SDL_GameControllerGetAttached(ctrl->Controller) == SDL_FALSE)
        {
            RemoveGameController(ctrl->ControllerID);
        }
        else
        {
            ++it;
        }
    }
}
Ejemplo n.º 8
0
float
DecafSDL::getAxisValue(vpad::Channel channel, vpad::CoreAxis axis)
{
   if (!mVpad0Config) {
      return 0.0f;
   }

   switch (mVpad0Config->type) {
   case config::input::None:
      break;

   case config::input::Keyboard:
   {
      auto numKeys = 0;
      auto scancodeMinus = getKeyboardAxisMapping(mVpad0Config, channel, axis, true);
      auto scancodePlus = getKeyboardAxisMapping(mVpad0Config, channel, axis, false);
      auto state = SDL_GetKeyboardState(&numKeys);
      auto result = 0.0f;

      if (scancodeMinus >= 0 && scancodeMinus < numKeys && state[scancodeMinus]) {
         result -= 1.0f;
      }

      if (scancodePlus >= 0 && scancodePlus < numKeys && state[scancodePlus]) {
         result += 1.0f;
      }

      return result;
   }

   case config::input::Joystick:
      if (mVpad0Controller && SDL_GameControllerGetAttached(mVpad0Controller)) {
         auto value = getJoystickAxisState(mVpad0Config, mVpad0Controller, channel, axis);

         if (value < 0) {
            return value / 32768.0f;
         } else {
            return value / 32767.0f;
         }
      }

      break;
   }

   return 0.0f;
}
Ejemplo n.º 9
0
static SDL_GameController* grab_controller(SDL_GameController* controller)
{
	if (!controller || !SDL_GameControllerGetAttached(controller)) {
		int32_t i, joystick_count;

		controller = NULL;

		joystick_count = SDL_NumJoysticks();
		for (i = 0; i < joystick_count; ++i) {
			if (SDL_IsGameController(i)) {
				controller = SDL_GameControllerOpen(i);
				break;
			}
		}

	}
	return (controller);
}
Ejemplo n.º 10
0
f32 getControllerAxis(u32 controllerIndex, ControllerAxis axis)
{
	SDL_GameController* gc = g_controllerHandles[controllerIndex];

	if (gc && SDL_GameControllerGetAttached(gc))
	{
		s16 value = SDL_GameControllerGetAxis(gc, (SDL_GameControllerAxis)axis);
		if (axis == ControllerAxis::LeftY)
			value = -value;

		if (value >= 0)
			return (f32)value / 32767.0f;

		return (f32)value / 32768.0f;
	}

	return 0.0f;
}
Ejemplo n.º 11
0
/*
* IN_SDL_JoyCommands
*
* SDL game controller code called in IN_Commands.
*/
void IN_SDL_JoyCommands( void )
{
	int i, buttons = 0, buttonsDiff;
	static int buttonsOld;
	const int keys[] =
	{
		K_A_BUTTON, K_B_BUTTON, K_X_BUTTON, K_Y_BUTTON, K_ESCAPE, 0, 0,
		K_LSTICK, K_RSTICK, K_LSHOULDER, K_RSHOULDER,
		K_DPAD_UP, K_DPAD_DOWN, K_DPAD_LEFT, K_DPAD_RIGHT,
		K_LTRIGGER, K_RTRIGGER
	};

	if( in_sdl_joyInitialized )
	{
		SDL_GameControllerUpdate();

		if( in_sdl_joyController && !SDL_GameControllerGetAttached( in_sdl_joyController ) )
		{
			SDL_GameControllerClose( in_sdl_joyController );
			in_sdl_joyController = NULL;
		}

		if( !in_sdl_joyController )
		{
			int num = SDL_NumJoysticks();

			for( i = 0; i < num; i++ )
			{
				in_sdl_joyController = SDL_GameControllerOpen( i );
				if( in_sdl_joyController )	
					break;
			}
		}
	}

	if( in_sdl_joyActive )
	{
		SDL_GameController *controller = in_sdl_joyController;
		if( controller )
		{
			for( i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++ )
			{
				if( keys[i] && SDL_GameControllerGetButton( controller, i ) )
					buttons |= 1 << i;
			}

			if( SDL_GameControllerGetButton( controller, SDL_CONTROLLER_BUTTON_START ) )
				buttons |= 1 << SDL_CONTROLLER_BUTTON_BACK;
			if( SDL_GameControllerGetAxis( controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT ) > ( 30 * 128 ) )
				buttons |= 1 << SDL_CONTROLLER_BUTTON_MAX;
			if( SDL_GameControllerGetAxis( controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT ) > ( 30 * 128 ) )
				buttons |= 1 << ( SDL_CONTROLLER_BUTTON_MAX + 1 );
		}
	}

	buttonsDiff = buttons ^ buttonsOld;
	if( buttonsDiff )
	{
		unsigned int time = Sys_Milliseconds();

		for( i = 0; i < ( sizeof( keys ) / sizeof( keys[0] ) ); i++ )
		{
			if( buttonsDiff & ( 1 << i ) )
				Key_Event( keys[i], ( buttons & ( 1 << i ) ) ? true : false, time );
		}

		buttonsOld = buttons;
	}
}
Ejemplo n.º 12
0
internal void process_joysticks(struct sdl_event_context *ctx,
				struct human_input *old_input,
				struct human_input *new_input)
{
	unsigned int i;
	struct game_controller_input *old_controller_input,
	    *new_controller_input;
	int stick_x, stick_y;
	/* DPAD
	   unsigned int up, down, left, right, start, back;
	 */

	for (i = 0; i < MAX_CONTROLLERS; ++i) {
		if (!(ctx->players[i].controller)) {
			continue;
		}
		if (!SDL_GameControllerGetAttached(ctx->players[i].controller)) {
			continue;
		}
		old_controller_input = &old_input->controllers[i];
		new_controller_input = &new_input->controllers[i];

		new_controller_input->is_analog = 1;
		/*
		   up = SDL_GameControllerGetButton(ctx->players[i].controller,
		   SDL_CONTROLLER_BUTTON_DPAD_UP);
		   down = SDL_GameControllerGetButton(ctx->players[i].controller,
		   SDL_CONTROLLER_BUTTON_DPAD_DOWN);
		   left = SDL_GameControllerGetButton(ctx->players[i].controller,
		   SDL_CONTROLLER_BUTTON_DPAD_LEFT);
		   right = SDL_GameControllerGetButton(ctx->players[i].controller,
		   SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
		   start = SDL_GameControllerGetButton(ctx->players[i].controller,
		   SDL_CONTROLLER_BUTTON_START);
		   back = SDL_GameControllerGetButton(ctx->players[i].controller,
		   SDL_CONTROLLER_BUTTON_BACK);
		 */

		process_button(&
			       (old_controller_input->but_u.
				six_buttons.l_shoulder),
			       &(new_controller_input->but_u.
				 six_buttons.l_shoulder),
			       ctx->players[i].controller,
			       SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
		process_button(&
			       (old_controller_input->but_u.
				six_buttons.r_shoulder),
			       &(new_controller_input->but_u.
				 six_buttons.r_shoulder),
			       ctx->players[i].controller,
			       SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
		process_button(&(old_controller_input->but_u.six_buttons.down),
			       &(new_controller_input->but_u.six_buttons.down),
			       ctx->players[i].controller,
			       SDL_CONTROLLER_BUTTON_A);
		process_button(&(old_controller_input->but_u.six_buttons.right),
			       &(new_controller_input->but_u.six_buttons.right),
			       ctx->players[i].controller,
			       SDL_CONTROLLER_BUTTON_B);
		process_button(&(old_controller_input->but_u.six_buttons.left),
			       &(new_controller_input->but_u.six_buttons.left),
			       ctx->players[i].controller,
			       SDL_CONTROLLER_BUTTON_X);
		process_button(&(old_controller_input->but_u.six_buttons.up),
			       &(new_controller_input->but_u.six_buttons.up),
			       ctx->players[i].controller,
			       SDL_CONTROLLER_BUTTON_Y);

		stick_x =
		    SDL_GameControllerGetAxis(ctx->players[i].controller,
					      SDL_CONTROLLER_AXIS_LEFTX);
		stick_y =
		    SDL_GameControllerGetAxis(ctx->players[i].controller,
					      SDL_CONTROLLER_AXIS_LEFTY);

		if (stick_x < 0) {
			new_controller_input->end_x = stick_x / -32768.0f;
		} else {
			new_controller_input->end_x = stick_x / -32767.0f;
		}
		new_controller_input->min_x = new_controller_input->max_x =
		    new_controller_input->end_x;

		if (stick_y < 0) {
			new_controller_input->end_y = stick_y / -32768.0f;
		} else {
			new_controller_input->end_y = stick_y / -32767.0f;
		}
		new_controller_input->min_y = new_controller_input->max_y =
		    new_controller_input->end_y;
	}

}
Ejemplo n.º 13
0
SDL_bool
WatchGameController(SDL_GameController * gamecontroller)
{
    /* This is indexed by SDL_GameControllerButton. */
    static const struct { int x; int y; } button_positions[] = {
        {387, 167},  /* A */
        {431, 132},  /* B */
        {342, 132},  /* X */
        {389, 101},  /* Y */
        {174, 132},  /* BACK */
        {233, 132},  /* GUIDE */
        {289, 132},  /* START */
        {75,  154},  /* LEFTSTICK */
        {305, 230},  /* RIGHTSTICK */
        {77,  40},   /* LEFTSHOULDER */
        {396, 36},   /* RIGHTSHOULDER */
        {154, 188},  /* DPAD_UP */
        {154, 249},  /* DPAD_DOWN */
        {116, 217},  /* DPAD_LEFT */
        {186, 217},  /* DPAD_RIGHT */
    };

    /* This is indexed by SDL_GameControllerAxis. */
    static const struct { int x; int y; double angle; } axis_positions[] = {
        {75,  154, 0.0},  /* LEFTX */
        {75,  154, 90.0},  /* LEFTY */
        {305, 230, 0.0},  /* RIGHTX */
        {305, 230, 90.0},  /* RIGHTY */
        {91, 0, 90.0},     /* TRIGGERLEFT */
        {375, 0, 90.0},    /* TRIGGERRIGHT */
    };

    const char *name = SDL_GameControllerName(gamecontroller);
    const char *basetitle = "Game Controller Test: ";
    const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1;
    char *title = (char *)SDL_malloc(titlelen);
    SDL_Texture *background, *button, *axis;
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE;
    SDL_Event event;
    int i;

    if (title) {
        SDL_snprintf(title, titlelen, "%s%s", basetitle, name);
    }

    /* Create a window to display controller state */
    window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }

    SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(screen);
    SDL_RenderPresent(screen);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);

    if (!background || !button || !axis) {
        SDL_DestroyRenderer(screen);
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    SDL_SetTextureColorMod(button, 10, 255, 21);
    SDL_SetTextureColorMod(axis, 10, 255, 21);

    /* !!! FIXME: */
    /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/

    /* Print info about the controller we are watching */
    SDL_Log("Watching controller %s\n",  name ? name : "Unknown Controller");

    /* Loop, getting controller events! */
    while (!done) {
        /* blank screen, set up for drawing this frame. */
        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(screen);
        SDL_RenderCopy(screen, background, NULL, NULL);

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                if (event.key.keysym.sym != SDLK_ESCAPE) {
                    break;
                }
                /* Fall through to signal quit */
            case SDL_QUIT:
                done = SDL_TRUE;
                break;
            default:
                break;
            }
        }

        /* Update visual controller state */
        for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) {
            if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
                const SDL_Rect dst = { button_positions[i].x, button_positions[i].y, 50, 50 };
                SDL_RenderCopyEx(screen, button, NULL, &dst, 0, NULL, 0);
            }
        }

        for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) {
            const Sint16 deadzone = 8000;  /* !!! FIXME: real deadzone */
            const Sint16 value = SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i));
            if (value < -deadzone) {
                const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 };
                const double angle = axis_positions[i].angle;
                SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0);
            } else if (value > deadzone) {
                const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 };
                const double angle = axis_positions[i].angle + 180.0;
                SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0);
            }
        }

        SDL_RenderPresent(screen);

        if (!SDL_GameControllerGetAttached(gamecontroller)) {
            done = SDL_TRUE;
            retval = SDL_TRUE;  /* keep going, wait for reattach. */
        }
    }

    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}
void loop(void *arg) {
  SDL_Event event;
  int i;
  SDL_GameController *gamecontroller = (SDL_GameController *)arg;

  /* blank screen, set up for drawing this frame. */
  SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
  SDL_RenderClear(screen);
  SDL_RenderCopy(screen, background, NULL, NULL);

  while (SDL_PollEvent(&event)) {
    switch (event.type) {
    case SDL_KEYDOWN:
      if (event.key.keysym.sym != SDLK_ESCAPE) {
        break;
      }
    /* Fall through to signal quit */
    case SDL_QUIT:
      done = SDL_TRUE;
      break;
    default:
      break;
    }
  }

  /* Update visual controller state */
  for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) {
    if (SDL_GameControllerGetButton(
            gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
      const SDL_Rect dst = {button_positions[i].x, button_positions[i].y, 50,
                            50};
      SDL_RenderCopyEx(screen, button, NULL, &dst, 0, NULL, 0);
    }
  }

  for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) {
    const Sint16 deadzone = 8000; /* !!! FIXME: real deadzone */
    const Sint16 value =
        SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i));
    if (value < -deadzone) {
      const SDL_Rect dst = {axis_positions[i].x, axis_positions[i].y, 50, 50};
      const double angle = axis_positions[i].angle;
      SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0);
    } else if (value > deadzone) {
      const SDL_Rect dst = {axis_positions[i].x, axis_positions[i].y, 50, 50};
      const double angle = axis_positions[i].angle + 180.0;
      SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0);
    }
  }

  SDL_RenderPresent(screen);

  if (!SDL_GameControllerGetAttached(gamecontroller)) {
    done = SDL_TRUE;
    retval = SDL_TRUE; /* keep going, wait for reattach. */
  }

#ifdef __EMSCRIPTEN__
  if (done) {
    emscripten_cancel_main_loop();
  }
#endif
}
Ejemplo n.º 15
0
void
WatchGameController(SDL_GameController * gamecontroller)
{
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    const char *name = NULL;
    int done = 0;
    SDL_Event event;
    int i;

    /* Create a window to display controller axis position */
    window = SDL_CreateWindow("Game Controller Test", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (window == NULL) {
        fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError());
        return;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        fprintf(stderr, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return;
    }

    SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(screen);
    SDL_RenderPresent(screen);
	SDL_RaiseWindow(window);

    /* Print info about the controller we are watching */
    name = SDL_GameControllerName(gamecontroller);
    printf("Watching controller %s\n",  name ? name : "Unknown Controller");
    
    /* Loop, getting controller events! */
    while (!done) {
        /* blank screen, set up for drawing this frame. */
        SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(screen);

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_CONTROLLERAXISMOTION:
                printf("Controller %d axis %d value: %d\n",
                       event.caxis.which,
                       event.caxis.axis, event.caxis.value);
                break;
            case SDL_CONTROLLERBUTTONDOWN:
                printf("Controller %d button %d down\n",
                       event.cbutton.which, event.cbutton.button);
                break;
            case SDL_CONTROLLERBUTTONUP:
                printf("Controller %d button %d up\n",
                       event.cbutton.which, event.cbutton.button);
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym != SDLK_ESCAPE) {
                    break;
                }
                /* Fall through to signal quit */
            case SDL_QUIT:
                done = 1;
				s_ForceQuit = SDL_TRUE;
                break;
            default:
                break;
            }
        }
        /* Update visual controller state */
        SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE);
        for (i = 0; i <SDL_CONTROLLER_BUTTON_MAX; ++i) {
            if (SDL_GameControllerGetButton(gamecontroller, i) == SDL_PRESSED) {
                DrawRect(screen, i * 34, SCREEN_HEIGHT - 34, 32, 32);
            }
        }

        SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE);
        for (i = 0; i < SDL_CONTROLLER_AXIS_MAX / 2; ++i) {
            /* Draw the X/Y axis */
            int x, y;
            x = (((int) SDL_GameControllerGetAxis(gamecontroller, i * 2 + 0)) + 32768);
            x *= SCREEN_WIDTH;
            x /= 65535;
            if (x < 0) {
                x = 0;
            } else if (x > (SCREEN_WIDTH - 16)) {
                x = SCREEN_WIDTH - 16;
            }
            y = (((int) SDL_GameControllerGetAxis(gamecontroller, i * 2 + 1)) + 32768);
            y *= SCREEN_HEIGHT;
            y /= 65535;
            if (y < 0) {
                y = 0;
            } else if (y > (SCREEN_HEIGHT - 16)) {
                y = SCREEN_HEIGHT - 16;
            }

            DrawRect(screen, x, y, 16, 16);
        }

        SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0xFF, SDL_ALPHA_OPAQUE);

        SDL_RenderPresent(screen);
		
		if ( !done )
			done = SDL_GameControllerGetAttached( gamecontroller ) == 0;
    }

    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
}
Ejemplo n.º 16
0
	int GameController::isAttached(State & state, SDL_GameController * gamecontroller) {
		Stack * stack = state.stack;
		stack->push<bool>(SDL_GameControllerGetAttached(gamecontroller) == SDL_TRUE);
		return 1;
	}
Ejemplo n.º 17
0
bool C4GamePadOpener::IsAttached()
{
	return !!SDL_GameControllerGetAttached(controller);
}
Ejemplo n.º 18
0
 bool is_attached() const noexcept {
     return SDL_GameControllerGetAttached(ptr.get());
 }
Ejemplo n.º 19
0
 void operator()(SDL_GameController* controller) const noexcept {
     if(SDL_GameControllerGetAttached(controller) == SDL_TRUE) {
         SDL_GameControllerClose(controller);
     }
 }
Ejemplo n.º 20
0
bool isControllerPresent(u32 controllerIndex)
{
	SDL_GameController* gc = g_controllerHandles[controllerIndex];

	return (gc && SDL_GameControllerGetAttached(gc));
}
Ejemplo n.º 21
0
SDL_bool
WatchGameController(SDL_GameController * gamecontroller)
{
    const char *name = SDL_GameControllerName(gamecontroller);
    const char *basetitle = "Game Controller Test: ";
    const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1;
    char *title = (char *)SDL_malloc(titlelen);
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE;
    SDL_Event event;
    int i;

    if (title) {
        SDL_snprintf(title, titlelen, "%s%s", basetitle, name);
    }

    /* Create a window to display controller axis position */
    window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }

    SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(screen);
    SDL_RenderPresent(screen);
    SDL_RaiseWindow(window);

    /* Print info about the controller we are watching */
    SDL_Log("Watching controller %s\n",  name ? name : "Unknown Controller");

    /* Loop, getting controller events! */
    while (!done) {
        /* blank screen, set up for drawing this frame. */
        SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(screen);

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_CONTROLLERAXISMOTION:
                SDL_Log("Controller %d axis %d ('%s') value: %d\n",
                       event.caxis.which,
                       event.caxis.axis,
                       ControllerAxisName((SDL_GameControllerAxis)event.caxis.axis),
                       event.caxis.value);
                break;
            case SDL_CONTROLLERBUTTONDOWN:
                SDL_Log("Controller %d button %d ('%s') down\n",
                       event.cbutton.which, event.cbutton.button,
                       ControllerButtonName((SDL_GameControllerButton)event.cbutton.button));
                break;
            case SDL_CONTROLLERBUTTONUP:
                SDL_Log("Controller %d button %d ('%s') up\n",
                       event.cbutton.which, event.cbutton.button,
                       ControllerButtonName((SDL_GameControllerButton)event.cbutton.button));
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym != SDLK_ESCAPE) {
                    break;
                }
                /* Fall through to signal quit */
            case SDL_QUIT:
                done = SDL_TRUE;
                break;
            default:
                break;
            }
        }
        /* Update visual controller state */
        SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE);
        for (i = 0; i <SDL_CONTROLLER_BUTTON_MAX; ++i) {
            if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
                DrawRect(screen, i * 34, SCREEN_HEIGHT - 34, 32, 32);
            }
        }

        SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE);
        for (i = 0; i < SDL_CONTROLLER_AXIS_MAX / 2; ++i) {
            /* Draw the X/Y axis */
            int x, y;
            x = (((int) SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i * 2 + 0))) + 32768);
            x *= SCREEN_WIDTH;
            x /= 65535;
            if (x < 0) {
                x = 0;
            } else if (x > (SCREEN_WIDTH - 16)) {
                x = SCREEN_WIDTH - 16;
            }
            y = (((int) SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i * 2 + 1))) + 32768);
            y *= SCREEN_HEIGHT;
            y /= 65535;
            if (y < 0) {
                y = 0;
            } else if (y > (SCREEN_HEIGHT - 16)) {
                y = SCREEN_HEIGHT - 16;
            }

            DrawRect(screen, x, y, 16, 16);
        }

        SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0xFF, SDL_ALPHA_OPAQUE);

        SDL_RenderPresent(screen);

        if (!SDL_GameControllerGetAttached(gamecontroller)) {
            done = SDL_TRUE;
            retval = SDL_TRUE;  /* keep going, wait for reattach. */
        }
    }

    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}