Exemplo n.º 1
0
Arquivo: event.c Projeto: mewbak/arcan
void platform_event_rescan_idev(arcan_evctx* ctx)
{
	if (iodev.sticks_init)
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);

	SDL_Init(SDL_INIT_JOYSTICK);
	SDL_JoystickEventState(SDL_ENABLE);

	int n_joys = SDL_NumJoysticks();
	iodev.sticks_init = true;

	if (n_joys == 0){
		drop_joytbl(ctx);
		return;
	}

/*
 * (Re) scan/open all joysticks,
 * look for matching / already present devices
 * and copy their settings.
 */
	size_t jsz = sizeof(struct arcan_stick) * n_joys;
	struct arcan_stick* joys = malloc(jsz);
	memset(joys, '\0', jsz);

	for (int i = 0; i < n_joys; i++) {
		struct arcan_stick* dj = &joys[i];
		struct arcan_stick* sj = NULL;
		unsigned long hashid = djb_hash(SDL_JoystickName(i));

/* find existing */
		if (iodev.joys){
			for (int j = 0; j < iodev.n_joy; j++){
				if (iodev.joys[j].hashid == hashid){
					sj = &iodev.joys[j];
					break;
				}
			}

/* if found, copy to new table */
			if (sj){
				memcpy(dj, sj, sizeof(struct arcan_stick));
				if (dj->hats){
					dj->hattbls = malloc(dj->hats * sizeof(unsigned));
					memcpy(dj->hattbls, sj->hattbls, sizeof(unsigned) * sj->hats);
				}

				if (dj->axis){
					dj->adata = malloc(dj->axis * sizeof(struct axis_opts));
					memcpy(dj->adata, sj->adata, sizeof(struct axis_opts) * sj->axis);
				}

				dj->handle = SDL_JoystickOpen(i);
				continue;
			}
		}

/* otherwise add as new entry */
		strncpy(dj->label, SDL_JoystickName(i), 255);
		dj->hashid = djb_hash(SDL_JoystickName(i));
		dj->handle = SDL_JoystickOpen(i);
		dj->devnum = gen_devid(dj->hashid);

		dj->axis    = SDL_JoystickNumAxes(joys[i].handle);
		dj->buttons = SDL_JoystickNumButtons(joys[i].handle);
		dj->balls   = SDL_JoystickNumBalls(joys[i].handle);
		dj->hats    = SDL_JoystickNumHats(joys[i].handle);

		if (dj->hats > 0){
			size_t dst_sz = joys[i].hats * sizeof(unsigned);
			dj->hattbls = malloc(dst_sz);
			memset(joys[i].hattbls, 0, dst_sz);
		}

		if (dj->axis > 0){
			size_t ad_sz = sizeof(struct axis_opts) * dj->axis;
			dj->adata = malloc(ad_sz);
			memset(dj->adata, '\0', ad_sz);
			for (int i = 0; i < dj->axis; i++){
				dj->adata[i].mode = ARCAN_ANALOGFILTER_AVG;
/* these values are sortof set
 * based on the SixAxis (common enough, and noisy enough) */
				dj->adata[i].lower    = -32765;
				dj->adata[i].deadzone = 5000;
				dj->adata[i].upper    = 32768;
				dj->adata[i].kernel_sz = 1;
			}
		}

/* notify the rest of the system about the added device */
		struct arcan_event addev = {
			.category = EVENT_IO,
			.io.kind = EVENT_IO_STATUS,
			.io.devkind = EVENT_IDEVKIND_STATUS,
			.io.devid = dj->devnum,
			.io.input.status.devkind = EVENT_IDEVKIND_GAMEDEV,
			.io.input.status.action = EVENT_IDEV_ADDED
		};
		snprintf((char*) &addev.io.label, sizeof(addev.io.label) /
			sizeof(addev.io.label[0]), "%s", dj->label);
		arcan_event_enqueue(ctx, &addev);
	}

	iodev.n_joy = n_joys;
	iodev.joys = joys;
}

void platform_event_keyrepeat(arcan_evctx* ctx, int* rate, int* delay)
{
/* sdl repeat start disabled */
	static int cur_rep, cur_del;
	bool upd = false;

	if (*rate < 0){
		*rate = cur_rep;
	}
	else{
		int tmp = *rate;
		*rate = cur_rep;
		cur_rep = tmp;
		upd = true;
	}

	if (*delay < 0){
		*delay = cur_del;
	}
	else{
		int tmp = *delay;
		*delay = cur_del;
		cur_del = tmp;
		upd = true;
	}

	if (upd)
		SDL_EnableKeyRepeat(cur_del, cur_rep);
}

void platform_event_deinit(arcan_evctx* ctx)
{
	if (iodev.sticks_init){
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		iodev.sticks_init = false;
	}
}

void platform_event_reset(arcan_evctx* ctx)
{
	platform_event_deinit(ctx);
}
Exemplo n.º 2
0
void SDLManagerPrivate::closeJoystick()
{
    if ( SDL_NumJoysticks() > 0 && SDL_JoystickOpened(0) )
        SDL_JoystickClose( joystick );
}
Exemplo n.º 3
0
/*
 * Open a controller for use - the index passed as an argument refers to
 * the N'th controller on the system.  This index is the value which will
 * identify this controller in future controller events.
 *
 * This function returns a controller identifier, or NULL if an error occurred.
 */
SDL_GameController *
SDL_GameControllerOpen(int device_index)
{
    SDL_GameController *gamecontroller;
    SDL_GameController *gamecontrollerlist;
    ControllerMapping_t *pSupportedController = NULL;

    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
        return (NULL);
    }

    gamecontrollerlist = SDL_gamecontrollers;
    /* If the controller is already open, return it */
    while (gamecontrollerlist) {
        if (SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == gamecontrollerlist->joystick->instance_id) {
                gamecontroller = gamecontrollerlist;
                ++gamecontroller->ref_count;
                return (gamecontroller);
        }
        gamecontrollerlist = gamecontrollerlist->next;
    }

    /* Find a controller mapping */
    pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
    if (!pSupportedController) {
        SDL_SetError("Couldn't find mapping for device (%d)", device_index);
        return (NULL);
    }

    /* Create and initialize the joystick */
    gamecontroller = (SDL_GameController *) SDL_malloc((sizeof *gamecontroller));
    if (gamecontroller == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    SDL_memset(gamecontroller, 0, (sizeof *gamecontroller));
    gamecontroller->joystick = SDL_JoystickOpen(device_index);
    if (!gamecontroller->joystick) {
        SDL_free(gamecontroller);
        return NULL;
    }

    SDL_PrivateLoadButtonMapping(&gamecontroller->mapping, pSupportedController->guid, pSupportedController->name, pSupportedController->mapping);

    /* The triggers are mapped from -32768 to 32767, where -32768 is the 'unpressed' value */
    {
        int leftTriggerMapping = gamecontroller->mapping.axes[SDL_CONTROLLER_AXIS_TRIGGERLEFT];
        int rightTriggerMapping = gamecontroller->mapping.axes[SDL_CONTROLLER_AXIS_TRIGGERRIGHT];
        if (leftTriggerMapping >= 0) {
            gamecontroller->joystick->axes[leftTriggerMapping] =
            gamecontroller->joystick->axes_zero[leftTriggerMapping] = (Sint16)-32768;
        }
        if (rightTriggerMapping >= 0) {
            gamecontroller->joystick->axes[rightTriggerMapping] =
            gamecontroller->joystick->axes_zero[rightTriggerMapping] = (Sint16)-32768;
        }
    }

    /* Add joystick to list */
    ++gamecontroller->ref_count;
    /* Link the joystick in the list */
    gamecontroller->next = SDL_gamecontrollers;
    SDL_gamecontrollers = gamecontroller;

    SDL_SYS_JoystickUpdate(gamecontroller->joystick);

    return (gamecontroller);
}
Exemplo n.º 4
0
void BomberConfig::set_controller(int _controller)
{
    controller = _controller % (6 + SDL_NumJoysticks());
}
Exemplo n.º 5
0
int joy_init()
{
	int i,j,n;

	if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
		con_printf(CON_VERBOSE, "sdl-joystick: initialisation failed: %s.",SDL_GetError());
		return 0;
	}

	memset(&Joystick,0,sizeof(Joystick));

	n = SDL_NumJoysticks();

	con_printf(CON_VERBOSE, "sdl-joystick: found %d joysticks\n", n);
	for (i = 0; i < n; i++) {
		con_printf(CON_VERBOSE, "sdl-joystick %d: %s\n", i, SDL_JoystickName(i));
		SDL_Joysticks[num_joysticks].handle = SDL_JoystickOpen(i);
		if (SDL_Joysticks[num_joysticks].handle) {
			joy_present = 1;

			SDL_Joysticks[num_joysticks].n_axes
				= SDL_JoystickNumAxes(SDL_Joysticks[num_joysticks].handle);
			if(SDL_Joysticks[num_joysticks].n_axes > MAX_AXES_PER_JOYSTICK)
			{
				Warning("sdl-joystick: found %d axes, only %d supported.  Game may be unstable.\n", SDL_Joysticks[num_joysticks].n_axes, MAX_AXES_PER_JOYSTICK);
				SDL_Joysticks[num_joysticks].n_axes = MAX_AXES_PER_JOYSTICK;
			}

			SDL_Joysticks[num_joysticks].n_buttons
				= SDL_JoystickNumButtons(SDL_Joysticks[num_joysticks].handle);
			if(SDL_Joysticks[num_joysticks].n_buttons > MAX_BUTTONS_PER_JOYSTICK)
			{
				Warning("sdl-joystick: found %d buttons, only %d supported.  Game may be unstable.\n", SDL_Joysticks[num_joysticks].n_buttons, MAX_BUTTONS_PER_JOYSTICK);
				SDL_Joysticks[num_joysticks].n_buttons = MAX_BUTTONS_PER_JOYSTICK;
			}

			SDL_Joysticks[num_joysticks].n_hats
				= SDL_JoystickNumHats(SDL_Joysticks[num_joysticks].handle);
			if(SDL_Joysticks[num_joysticks].n_hats > MAX_HATS_PER_JOYSTICK)
			{
				Warning("sdl-joystick: found %d hats, only %d supported.  Game may be unstable.\n", SDL_Joysticks[num_joysticks].n_hats, MAX_HATS_PER_JOYSTICK);
				SDL_Joysticks[num_joysticks].n_hats = MAX_HATS_PER_JOYSTICK;
			}

			con_printf(CON_VERBOSE, "sdl-joystick: %d axes\n", SDL_Joysticks[num_joysticks].n_axes);
			con_printf(CON_VERBOSE, "sdl-joystick: %d buttons\n", SDL_Joysticks[num_joysticks].n_buttons);
			con_printf(CON_VERBOSE, "sdl-joystick: %d hats\n", SDL_Joysticks[num_joysticks].n_hats);

			for (j=0; j < SDL_Joysticks[num_joysticks].n_axes; j++)
				SDL_Joysticks[num_joysticks].axis_map[j] = Joystick.n_axes++;
			for (j=0; j < SDL_Joysticks[num_joysticks].n_buttons; j++)
				SDL_Joysticks[num_joysticks].button_map[j] = Joystick.n_buttons++;
			for (j=0; j < SDL_Joysticks[num_joysticks].n_hats; j++)
			{
				SDL_Joysticks[num_joysticks].hat_map[j] = Joystick.n_buttons;
				//a hat counts as four buttons
				joybutton_text[Joystick.n_buttons++] = j?TNUM_HAT2_U:TNUM_HAT_U;
				joybutton_text[Joystick.n_buttons++] = j?TNUM_HAT2_R:TNUM_HAT_R;
				joybutton_text[Joystick.n_buttons++] = j?TNUM_HAT2_D:TNUM_HAT_D;
				joybutton_text[Joystick.n_buttons++] = j?TNUM_HAT2_L:TNUM_HAT_L;
			}

			num_joysticks++;
		}
		else
			con_printf(CON_VERBOSE, "sdl-joystick: initialization failed!\n");

		con_printf(CON_VERBOSE, "sdl-joystick: %d axes (total)\n", Joystick.n_axes);
		con_printf(CON_VERBOSE, "sdl-joystick: %d buttons (total)\n", Joystick.n_buttons);
	}

	return joy_present;
}
Exemplo n.º 6
0
Arquivo: joy.cpp Projeto: paud/d2x-xl
int JoyInit()
{
	int				i, j, n;
	tSdlJoystick	*joyP = sdlJoysticks;

	if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
#if TRACE
		console.printf(CON_VERBOSE, "sdl-joystick: initialisation failed: %s.",SDL_GetError());
#endif
		return 0;
	}
	memset (&joyInfo, 0, sizeof (joyInfo));
	n = SDL_NumJoysticks();

#if TRACE
	console.printf(CON_VERBOSE, "sdl-joystick: found %d joysticks\n", n);
#endif
	for (i = 0; (i < n) && (gameStates.input.nJoysticks < MAX_JOYSTICKS); i++) {
#if TRACE
		console.printf(CON_VERBOSE, "sdl-joystick %d: %s\n", i, SDL_JoystickName (i));
#endif
		joyP->handle = SDL_JoystickOpen (i);
		if (joyP->handle) {
			bJoyPresent = 1;
			if((joyP->nAxes = SDL_JoystickNumAxes (joyP->handle)) > MAX_AXES_PER_JOYSTICK) {
				Warning (TXT_JOY_AXESNO, joyP->nAxes, MAX_AXES_PER_JOYSTICK);
				joyP->nAxes = MAX_AXES_PER_JOYSTICK;
				}

			if((joyP->nButtons = SDL_JoystickNumButtons (joyP->handle)) > MAX_BUTTONS_PER_JOYSTICK) {
				Warning (TXT_JOY_BUTTONNO, joyP->nButtons, MAX_BUTTONS_PER_JOYSTICK);
				joyP->nButtons = MAX_BUTTONS_PER_JOYSTICK;
				}
			if((joyP->nHats = SDL_JoystickNumHats (joyP->handle)) > MAX_HATS_PER_JOYSTICK) {
				Warning (TXT_JOY_HATNO, joyP->nHats, MAX_HATS_PER_JOYSTICK);
				joyP->nHats = MAX_HATS_PER_JOYSTICK;
				}
#if TRACE
			console.printf(CON_VERBOSE, "sdl-joystick: %d axes\n", joyP->nAxes);
			console.printf(CON_VERBOSE, "sdl-joystick: %d buttons\n", joyP->nButtons);
			console.printf(CON_VERBOSE, "sdl-joystick: %d hats\n", joyP->nHats);
#endif
			memset (&joyInfo, 0, sizeof (joyInfo));
			for (j = 0; j < joyP->nAxes; j++)
				joyP->axisMap [j] = joyInfo.nAxes++;
			for (j = 0; j < joyP->nButtons; j++)
				joyP->buttonMap [j] = joyInfo.nButtons++;
			for (j = 0; j < joyP->nHats; j++) {
				joyP->hatMap [j] = joyInfo.nButtons;
				//a hat counts as four buttons
				joybutton_text [joyInfo.nButtons++] = i ? TNUM_HAT2_U : TNUM_HAT_U;
				joybutton_text [joyInfo.nButtons++] = i ? TNUM_HAT2_R : TNUM_HAT_R;
				joybutton_text [joyInfo.nButtons++] = i ? TNUM_HAT2_D : TNUM_HAT_D;
				joybutton_text [joyInfo.nButtons++] = i ? TNUM_HAT2_L : TNUM_HAT_L;
				}
			joyP++;
			gameStates.input.nJoysticks++;
			}
		else {
#if TRACE
			console.printf(CON_VERBOSE, "sdl-joystick: initialization failed!\n");
#endif		
		}
#if TRACE
		console.printf(CON_VERBOSE, "sdl-joystick: %d axes (total)\n", joyInfo.nAxes);
		console.printf(CON_VERBOSE, "sdl-joystick: %d buttons (total)\n", joyInfo.nButtons);
#endif
	}
return bJoyPresent;
}
Exemplo n.º 7
0
//
// I_GetJoystickCount
//
int I_GetJoystickCount()
{
	return SDL_NumJoysticks();
}
Exemplo n.º 8
0
int main(int argc, char *argv[]) {
  int opt;
  struct sockaddr_can addr;
  struct canfd_frame frame;
  int running = 1;
  int enable_canfd = 1;
  int play_traffic = 1;
  struct stat st;
  SDL_Event event;

  while ((opt = getopt(argc, argv, "Xdl:s:t:h?")) != -1) {
    switch(opt) {
	case 'l':
		difficulty = atoi(optarg);
		break;
	case 's':
		seed = atoi(optarg);
		break;
	case 't':
		traffic_log = optarg;
		break;
	case 'd':
		debug = 1;
		break;
	case 'X':
		play_traffic = 0;
		break;
	case 'h':
	case '?':
	default:
		usage(NULL);
		break;
    }
  }

  if (optind >= argc) usage("You must specify at least one can device");

  if(stat(traffic_log, &st) == -1) {
	char msg[256];
	snprintf(msg, 255, "CAN Traffic file not found: %s\n", traffic_log);
	usage(msg);
  }

  /* open socket */
  if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
       perror("socket");
       return 1;
  }

  addr.can_family = AF_CAN;

  strcpy(ifr.ifr_name, argv[optind]);
  if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
       perror("SIOCGIFINDEX");
       return 1;
  }
  addr.can_ifindex = ifr.ifr_ifindex;

  if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES,
                 &enable_canfd, sizeof(enable_canfd))){
       printf("error when enabling CAN FD support\n");
       return 1;
  }

  if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
       perror("bind");
       return 1;
  }

  door_id = DEFAULT_DOOR_ID;
  signal_id = DEFAULT_SIGNAL_ID;
  speed_id = DEFAULT_SPEED_ID;

  if (seed) {
	srand(seed);
        door_id = (rand() % 2046) + 1;
        signal_id = (rand() % 2046) + 1;
        speed_id = (rand() % 2046) + 1;
        door_pos = rand() % 9;
        signal_pos = rand() % 9;
        speed_pos = rand() % 8;
        printf("Seed: %d\n", seed);
	door_len = door_pos + 1;
	signal_len = signal_pos + 1;
	speed_len = speed_len + 2;
  }

  if(difficulty > 0) {
	if (door_len < 8) {
		door_len += rand() % (8 - door_len);
	} else {
		door_len = 0;
	}
	if (signal_len < 8) {
		signal_len += rand() % (8 - signal_len);
	} else {
		signal_len = 0;
	}
	if (speed_len < 8) {
		speed_len += rand() % (8 - speed_len);
	} else {
		speed_len = 0;
	}
  }

  if(play_traffic) {
	play_id = fork();
	if((int)play_id == -1) {
		printf("Error: Couldn't fork bg player\n");
		exit(-1);
	} else if (play_id == 0) {
		play_can_traffic();
		// Shouldn't return
		exit(0);
	}
	atexit(kill_child);
  }

  // GUI Setup
  SDL_Window *window = NULL;
  SDL_Surface *screenSurface = NULL;
  if(SDL_Init ( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ) {
        printf("SDL Could not initializes\n");
        exit(40);
  }
  if( SDL_NumJoysticks() < 1) {
	printf(" Warning: No joysticks connected\n");
  } else {
	if(SDL_IsGameController(0)) {
	  gGameController = SDL_GameControllerOpen(0);
	  if(gGameController == NULL) {
		printf(" Warning: Unable to open game controller. %s\n", SDL_GetError() );
	  } else {
		gJoystick = SDL_GameControllerGetJoystick(gGameController);
		gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
		print_joy_info();
	  }
        } else {
		gJoystick = SDL_JoystickOpen(0);
		if(gJoystick == NULL) {
			printf(" Warning: Could not open joystick\n");
		} else {
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			if (gHaptic == NULL) printf("No Haptic support\n");
			print_joy_info();
		}
	}
  }
  window = SDL_CreateWindow("CANBus Control Panel", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if(window == NULL) {
        printf("Window could not be shown\n");
  }
  renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_Surface *image = IMG_Load(get_data("joypad.png"));
  base_texture = SDL_CreateTextureFromSurface(renderer, image);
  SDL_RenderCopy(renderer, base_texture, NULL, NULL);
  SDL_RenderPresent(renderer);
  int button, axis; // Used for checking dynamic joystick mappings

  while(running) {
    while( SDL_PollEvent(&event) != 0 ) {
        switch(event.type) {
            case SDL_QUIT:
                running = 0;
                break;
	    case SDL_WINDOWEVENT:
		switch(event.window.event) {
		case SDL_WINDOWEVENT_ENTER:
		case SDL_WINDOWEVENT_RESIZED:
			redraw_screen();
			break;
		}
	    case SDL_KEYDOWN:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = 1;
			break;
		    case SDLK_LEFT:
			turning = -1;
			break;
		    case SDLK_RIGHT:
			turning = 1;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_a:
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			break;
		    case SDLK_b:
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			break;
		    case SDLK_x:
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			break;
		    case SDLK_y:
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			break;
		}
		kk_check(event.key.keysym.sym);
	   	break;
	    case SDL_KEYUP:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = -1;
			break;
		    case SDLK_LEFT:
		    case SDLK_RIGHT:
			turning = 0;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 0;
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 0;
			break;
		}
		break;
	    case SDL_JOYAXISMOTION:
		axis = event.jaxis.axis;
		if(axis == gAxisLeftH) {
			ud(event.jaxis.value);
		} else if(axis == gAxisLeftV) {
			turn(event.jaxis.value);
		} else if(axis == gAxisR2) {
			accelerate(event.jaxis.value);
		} else if(axis == gAxisRightH ||
			  axis == gAxisRightV ||
			  axis == gAxisL2 ||
			  axis == gJoyX ||
			  axis == gJoyY ||
			  axis == gJoyZ) {
			// Do nothing, the axis is known just not connected
		} else {
			if (debug) printf("Unkown axis: %d\n", event.jaxis.axis);
		}
		break;
	    case SDL_JOYBUTTONDOWN:
                button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonUnlock) {
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonA) {
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			kk_check(SDLK_a);
		} else if (button == gButtonB) {
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			kk_check(SDLK_b);
		} else if (button == gButtonX) {
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			kk_check(SDLK_x);
		} else if (button == gButtonY) {
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			kk_check(SDLK_y);
		} else if (button == gButtonStart) {
			kk_check(SDLK_RETURN);
		} else {
			if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYBUTTONUP:
		button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 0;
		} else if(button == gButtonUnlock) {
			unlock_enabled = 0;
		} else {
			//if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYDEVICEADDED:
		// Only use the first controller
		if(event.cdevice.which == 0) {
			gJoystick = SDL_JoystickOpen(0);
			if(gJoystick) {
				gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
				print_joy_info();
			}
		}
		break;
	    case SDL_JOYDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_JoystickClose(gJoystick);
			gJoystick = NULL;
		}
		break;
	    case SDL_CONTROLLERDEVICEADDED:
		// Only use the first controller
		if(gGameController == NULL) {
			gGameController = SDL_GameControllerOpen(0);
			gJoystick = SDL_GameControllerGetJoystick(gGameController);
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			print_joy_info();
		}
		break;
	    case SDL_CONTROLLERDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_GameControllerClose(gGameController);
			gGameController = NULL;
		}
		break;
        }
    }
    currentTime = SDL_GetTicks();
    checkAccel();
    checkTurn();
    SDL_Delay(5);
  }

  close(s);
  SDL_DestroyTexture(base_texture);
  SDL_FreeSurface(image);
  SDL_GameControllerClose(gGameController);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

}
Exemplo n.º 9
0
void Jugador::manejarEntrada() {
    if(!bMuerto) {
        // manejar teclas
        if(ManejadorDeEntrada::Instancia()->isKeyDown(SDL_SCANCODE_UP)
            && posicion.getY() > 0)
        {
            velocidad.setY(-velocidadMovimiento);
            velocidad.setX(0);
        }
        else if(ManejadorDeEntrada::Instancia()->isKeyDown(SDL_SCANCODE_DOWN)
            && (posicion.getY() + altura) < ElJuego::Instancia()->getAlturaJuego() - 10)
        {
            velocidad.setY(velocidadMovimiento);
            velocidad.setX(0);
        }

        if(ManejadorDeEntrada::Instancia()->isKeyDown(SDL_SCANCODE_LEFT) && posicion.getX() > 0)
        {
            velocidad.setX(-velocidadMovimiento);
            velocidad.setY(0);
        }
        else if(ManejadorDeEntrada::Instancia()->isKeyDown(SDL_SCANCODE_RIGHT)
        && (posicion.getX() + ancho) < ElJuego::Instancia()->getAnchoJuego())
        {
            velocidad.setX(velocidadMovimiento);
            velocidad.setY(0);
        }

//
//        if(ManejadorDeEntrada::Instancia()->isKeyDown(SDL_SCANCODE_SPACE)) {
//            if(m_bulletCounter == m_bulletFiringSpeed) {
//                TheSoundManager::Instance()->playSound("shoot", 0);
//                TheBulletHandler::Instance()->addPlayerBullet(
//                m_position.getX() + 90, m_position.getY() + 12, 11, 11, "bullet1", 1, Vector2D(10,0));
//                m_bulletCounter = 0;
//            }
//
//            m_bulletCounter++;
//        } else { m_bulletCounter = m_bulletFiringSpeed; }
        // */

        /* manejando joysticks */
        //comprobarJoysticks
        if( SDL_NumJoysticks() < 1 ) {
            //printf( "Peligro: No hay Joysticks conectados!\n" );
        } else {
            if(ManejadorDeEntrada::Instancia()->joysticksInicializados()) {
//                if(ManejadorDeEntrada::Instancia()->getButtonState(0, 2)) {
//                    if(m_bulletCounter == m_bulletFiringSpeed)
//                    {
//                        TheSoundManager::Instance()->playSound("shoot", 0);
//                        TheBulletHandler::Instance()->addPlayerBullet(
//                                m_position.getX() + 90, m_position.getY() + 12, 11, 11, "bullet1", 1, Vector2D(10,0));
//                        m_bulletCounter = 0;
//                    }
//
//                    m_bulletCounter++;
//                } else { m_bulletCounter = m_bulletFiringSpeed; }

                if((ManejadorDeEntrada::Instancia()->getAxisX(0, 1) > 0
                    && (posicion.getX() + ancho) < ElJuego::Instancia()->getAnchoJuego())
                    || (ManejadorDeEntrada::Instancia()->getAxisX(0, 1) < 0 && posicion.getX() > 0)) {
                    velocidad.setX(velocidadMovimiento * ManejadorDeEntrada::Instancia()->getAxisX(0, 1));
                }

                if((ManejadorDeEntrada::Instancia()->getAxisY(0, 1) > 0
                    && (posicion.getY() + altura) < ElJuego::Instancia()->getAlturaJuego() - 10 )
                    || (ManejadorDeEntrada::Instancia()->getAxisY(0, 1) < 0 && posicion.getY() > 0)) {
                    velocidad.setY(velocidadMovimiento * ManejadorDeEntrada::Instancia()->getAxisY(0, 1));
                }
            }
        }
    }
}
Exemplo n.º 10
0
int init_SDL(void)
{
	joys[0]=0;
	joys[1]=0;
	joys[2]=0;
	joys[3]=0;
    
    if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        return(0);
    }
    sdlscreen = SDL_SetVideoMode(0,0, 16, SDL_SWSURFACE);
    
	//We handle up to four joysticks
	if(SDL_NumJoysticks())
	{
		int joystickIndex;
                int configuratedJoysticks[4] = {-1,-1,-1,-1};
                SDL_JoystickEventState(SDL_ENABLE);
                
                // Try to configure joysticks from config indexes
                for(int player = 0; player< 4; player++){
                    joystickIndex = joy_indexes[player];
                    if(joystickIndex >= 0){
                        if(SDL_NumJoysticks() > joystickIndex){
                            SDL_Joystick* joystick  = SDL_JoystickOpen(joystickIndex);
                            //Check for valid joystick, some keyboards
                            //aren't SDL compatible
                            if(joystick)
                            {
                                    if (SDL_JoystickNumAxes(myjoy[joystickIndex]) > 6)
                                    {
                                            SDL_JoystickClose(myjoy[joystickIndex]);
                                            joystick=0;
                                            logoutput("Error detected invalid joystick/keyboard\n");
                                            break;
                                    }
                            }
                            configuratedJoysticks[player] = joystickIndex;
                            joys[player] = joystick;
                            logoutput("Configured joystick %s at %d for player %d\n", SDL_JoystickName(joystickIndex), SDL_JoystickIndex(joystick), player+1);
                            joyCount++;
                        }
                    }
                }
       
                // Finish configuration
                for(joystickIndex=0;joystickIndex<SDL_NumJoysticks();joystickIndex++) {
                    // If already configured skip
                    bool alreadyConfig = false;
                    for(int player = 0; player< 4; player++){ 
                        logoutput("Checking if joystick at %d is configured for player %d : %d\n", joystickIndex,player ,configuratedJoysticks[player]);

                        if(configuratedJoysticks[player] == joystickIndex){
                            alreadyConfig = true;
                            break;
                        }
                    }
                    if(alreadyConfig) continue;
                    SDL_Joystick* joystick  = SDL_JoystickOpen(joystickIndex);
			//Check for valid joystick, some keyboards
			//aren't SDL compatible
			if(joystick)
			{
                            if (SDL_JoystickNumAxes(myjoy[joystickIndex]) > 6)
                            {
                                    SDL_JoystickClose(myjoy[joystickIndex]);
                                    joystick=0;
                                    logoutput("Error detected invalid joystick/keyboard\n");
                                    break;
                            }
                            // Set the first free joystick
                            for(int player = 0; player< 4; player++){ 
                                if(configuratedJoysticks[player] == -1){
                                    joy_indexes[player] = joystickIndex;
                                    joys[player] = joystick;
                                    configuratedJoysticks[player] = joystickIndex;
                                    logoutput("Default Configured joystick at %d for player %d\n", joystickIndex ,player+1);
                                    joyCount++;
                                    break;
                                }
                            }
			}
                        
                    }
		
		if(joys[0])
			logoutput("Found %d joysticks\n",joyCount);
	}
	else
		joyCount=1;

	//sq frig number of players for keyboard
	//joyCount=2;

	SDL_EventState(SDL_ACTIVEEVENT,SDL_IGNORE);
	SDL_EventState(SDL_SYSWMEVENT,SDL_IGNORE);
	SDL_EventState(SDL_VIDEORESIZE,SDL_IGNORE);
	SDL_EventState(SDL_USEREVENT,SDL_IGNORE);
	SDL_ShowCursor(SDL_DISABLE);
    
    //Initialise dispmanx
    bcm_host_init();
    
    //Clean exits, hopefully!
    atexit(exitfunc);
    
    return(1);
}
Exemplo n.º 11
0
int main(int argc, char** argv)
{
  if (argc == 1)
  {
    print_help(argv[0]);
    exit(1);
  }
  
//     printf("argv: %s %s %s %s %s %i\n", argv[0], argv[1], argv[2], argv[3], argv[4], argc );


  // FIXME: We don't need video, but without it SDL will fail to work in SDL_WaitEvent()
  if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0)
  {
    fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    exit(1);
  }
  else
  {
    atexit(SDL_Quit);

    if (argc == 2 && (strcmp(argv[1], "--help") == 0 ||
                      strcmp(argv[1], "-h") == 0))
    {
      print_help(argv[0]);
    }
    if (argc == 2 && (strcmp(argv[1], "--version") == 0))
    {
      printf("sdl2osc 0.1.0\n");
      exit(EXIT_SUCCESS);
    }
    else if (argc == 2 && (strcmp(argv[1], "--list") == 0 ||
                           (strcmp(argv[1], "-l") == 0)))
    {
      int num_joysticks = SDL_NumJoysticks();
      if (num_joysticks == 0)
      {
        printf("No joysticks were found\n");
      }
      else
      {
	int joy_idx;
        printf("Found %d joystick(s)\n\n", num_joysticks);
        for(joy_idx = 0; joy_idx < num_joysticks; ++joy_idx)
        {
          SDL_Joystick* joy = SDL_JoystickOpen(joy_idx);
          if (!joy)
          {
            fprintf(stderr, "Unable to open joystick %d\n", joy_idx);
          }
          else
          {
            print_joystick_info(joy_idx, joy);
            SDL_JoystickClose(joy);
          }
        }
      }
    }
    else if (argc == 3 && (strcmp(argv[1], "--event") == 0 ||
                           strcmp(argv[1], "-e") == 0))
    {
      int joy_idx;
      if (!str2int(argv[2], &joy_idx))
      {
        fprintf(stderr, "Error: JOYSTICKNUM argument must be a number, but was '%s'\n", argv[2]);
        exit(1);
      }

      SDL_Joystick* joy = SDL_JoystickOpen(joy_idx);
      if (!joy)
      {
        fprintf(stderr, "Unable to open joystick %d\n", joy_idx);
      }
      else
      {
        print_joystick_info(joy_idx, joy);

        printf("Entering joystick test loop, press Ctrl-c to exit\n");
        int quit = 0;
        SDL_Event event;

        while(!quit && SDL_WaitEvent(&event))
        {
          switch(event.type)
          {
            case SDL_JOYAXISMOTION:
              printf("SDL_JOYAXISMOTION: joystick: %d axis: %d value: %d\n",
                     event.jaxis.which, event.jaxis.axis, event.jaxis.value);
              break;

            case SDL_JOYBUTTONDOWN:
              printf("SDL_JOYBUTTONUP: joystick: %d button: %d state: %d\n",
                     event.jbutton.which, event.jbutton.button, event.jbutton.state);
              break;
            case SDL_JOYBUTTONUP:
              printf("SDL_JOYBUTTONDOWN: joystick: %d button: %d state: %d\n",
                     event.jbutton.which, event.jbutton.button, event.jbutton.state);
              break;

            case SDL_JOYHATMOTION:
              printf("SDL_JOYHATMOTION: joystick: %d hat: %d value: %d\n",
                     event.jhat.which, event.jhat.hat, event.jhat.value);
              break;

            case SDL_JOYBALLMOTION:
              printf("SDL_JOYBALLMOTION: joystick: %d ball: %d x: %d y: %d\n",
                     event.jball.which, event.jball.ball, event.jball.xrel, event.jball.yrel);
              break;

            case SDL_QUIT:
              quit = 1;
              printf("Recieved interrupt, exiting\n");
              break;

            default:
              fprintf(stderr, "Error: Unhandled event type: %d\n", event.type);
          }
        }
        SDL_JoystickClose(joy);

      }
      fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    }
    else if (argc == 2 && (strcmp(argv[1], "--osc") == 0 ||
                           strcmp(argv[1], "-o") == 0))
    {
      int joy_idx;
//       if (!str2int(argv[2], &joy_idx))
//       {
//         fprintf(stderr, "Error: JOYSTICKNUM argument must be a number, but was '%s'\n", argv[2]);
//         exit(1);
//       }
      
      char *port = "57151";
      char *outport = "57120";
      char *ip = "127.0.0.1";

      
      if ( argc == 5 )
	{
	ip = argv[4];
	port = argv[3];
	outport = argv[2];
	}
      else if ( argc == 4 )
	{
	port = argv[3];
	outport = argv[2];
	}
      else if ( argc == 3 )
	{
	outport = argv[2];
	}
  
      init_osc( ip, outport, port );

//       SDL_Joystick* joy = SDL_JoystickOpen(joy_idx);
//       if (!joy)
//       {
//         fprintf(stderr, "Unable to open joystick %d\n", joy_idx);
//       }
//       else
//       {
//         print_joystick_info(joy_idx, joy);

        printf("Entering joystick test loop, press Ctrl-c to exit\n");
//         int quit = 0;
        SDL_Event event;
        lo_timetag lo_now = LO_TT_IMMEDIATE;
        
        while(!done && SDL_WaitEvent(&event))
        {
          switch(event.type)
          {
            case SDL_JOYAXISMOTION:
	      lo_send_from( t, s, lo_now, "/joystick/axis", "iii", event.jaxis.which, event.jaxis.axis, event.jaxis.value );
//               printf("SDL_JOYAXISMOTION: joystick: %d axis: %d value: %d\n",
//                      event.jaxis.which, event.jaxis.axis, event.jaxis.value);
              break;
            case SDL_JOYBUTTONDOWN:
	      lo_send_from( t, s, lo_now, "/joystick/button", "iii", event.jbutton.which, event.jbutton.button, event.jbutton.state );
//               printf("SDL_JOYBUTTONUP: joystick: %d button: %d state: %d\n",
//                      event.jbutton.which, event.jbutton.button, event.jbutton.state);
              break;
            case SDL_JOYBUTTONUP:
	      lo_send_from( t, s, lo_now, "/joystick/button", "iii", event.jbutton.which, event.jbutton.button, event.jbutton.state );
//               printf("SDL_JOYBUTTONDOWN: joystick: %d button: %d state: %d\n",
//                      event.jbutton.which, event.jbutton.button, event.jbutton.state);
              break;

            case SDL_JOYHATMOTION:
	      lo_send_from( t, s, lo_now, "/joystick/hat", "iii", event.jhat.which, event.jhat.hat, event.jhat.value );
//               printf("SDL_JOYHATMOTION: joystick: %d hat: %d value: %d\n",
//                      event.jhat.which, event.jhat.hat, event.jhat.value);
              break;

            case SDL_JOYBALLMOTION:
	      lo_send_from( t, s, lo_now, "/joystick/ball", "iii", event.jball.which, event.jball.ball, event.jball.xrel, event.jball.yrel );
//               printf("SDL_JOYBALLMOTION: joystick: %d ball: %d x: %d y: %d\n",
//                      event.jball.which, event.jball.ball, event.jball.xrel, event.jball.yrel);
              break;

            case SDL_QUIT:
              done = 1;
              printf("Received interrupt, exiting\n");
              break;

            default:
              fprintf(stderr, "Error: Unhandled event type: %d\n", event.type);
          }
	}
//         SDL_JoystickClose(joy);
	  close_all_joysticks();
	  
	  lo_send_from( t, s, lo_now, "/sdl2osc/quit", "s", "nothing more to do, quitting" );
	  lo_server_thread_free( st );
	  lo_address_free( t );

//        }
//       fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    }
    else
    {
      fprintf(stderr, "%s: unknown arguments\n", argv[0]);
      fprintf(stderr, "Try '%s --help' for more informations\n", argv[0]);
    }
  }
}
Exemplo n.º 12
0
//------------------------------------------------------------
void ofxSDLAppWindow::runAppViaInfiniteLoop(ofBaseApp* appPtr) {
	static ofEventArgs voidEventArgs;
  
  // ------------------------------------------------------------
  // enable keyboarding
  
  SDL_EnableUNICODE(1);
  
  // ------------------------------------------------------------
  // connect controllers
  
  SDL_InitSubSystem(SDL_INIT_JOYSTICK);

  numJoys = SDL_NumJoysticks();
  for (int j = 0; j < numJoys; j++) {
    joys[j] = SDL_JoystickOpen(j);
  }
  
  
  // ------------------------------------------------------------
  // setup application
  
	ofAppPtr = (ofxSDLApp*) appPtr;
  
	if (ofAppPtr) {
		ofAppPtr->setup();
		ofAppPtr->update();
	}

#ifdef OF_USING_POCO
  ofNotifyEvent(ofEvents.setup, voidEventArgs);
  ofNotifyEvent(ofEvents.update, voidEventArgs);
#endif
  
  
  // ------------------------------------------------------------
  // loop forever and ever and ever and ever (and ever)
  
  while (true) {
    
    // ------------------------------------------------------------
    // check for events
    
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
        case SDL_JOYAXISMOTION:
          this->joyMovedHandler(&event);
          break;
        case SDL_JOYBUTTONDOWN:
          this->joyDownHandler(&event);
          break;
        case SDL_JOYBUTTONUP:
          this->joyUpHandler(&event);
          break;
				case SDL_MOUSEMOTION:
          // TODO
					break;
				case SDL_MOUSEBUTTONDOWN:
          this->mouseDownHandler(&event);
					break;
        case SDL_MOUSEBUTTONUP:
          this->mouseUpHandler(&event);
					break;
				case SDL_KEYDOWN:
          this->keyDownHandler(&event);
          break;
        case SDL_KEYUP:
          this->keyUpHandler(&event);
          break;
				case SDL_QUIT:
					this->exitApp();
					break;
				default:
					break;
			}
		}
    
    
    // ------------------------------------------------------------
    // set viewport, clear the screen
    
    int width, height;
    width  = ofGetWidth();
    height = ofGetHeight();
    height = height > 0 ? height : 1;
    glViewport(0, 0, width, height);

    float* bgPtr = ofBgColorPtr();
    bool bClearAuto = ofbClearBg();
    
#ifdef TARGET_WIN32
    // TODO: unsure if this is required for SDL, copied from GLUT.
    // to do non auto clear on PC for now - we do something like "single" buffering --
    // it's not that pretty but it work for the most part
    if (bClearAuto == false) {
      glDrawBuffer(GL_FRONT);
    }
#endif
    
    if (bClearAuto == true || nFrameCount < 3) {
      glClearColor(bgPtr[0], bgPtr[1], bgPtr[2], bgPtr[3]);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }
    
    
    // ------------------------------------------------------------
    // do frame drawing
    
    if (bEnableSetupScreen) {
      ofSetupScreen();
    }
    
    if (ofAppPtr) {
      ofAppPtr->draw();
    }
    
#ifdef OF_USING_POCO
		ofNotifyEvent(ofEvents.draw, voidEventArgs);
#endif


    // ------------------------------------------------------------
    // finish viewport
    
#ifdef TARGET_WIN32
    if (bClearAuto == false) {
      // on a PC resizing a window with this method of accumulation (essentially single buffering)
      // is BAD, so we clear on resize events.
      if (nFramesSinceWindowResized < 3) {
        glClearColor(bgPtr[0], bgPtr[1], bgPtr[2], bgPtr[3]);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      } else {
        if (nFrameCount < 3 || nFramesSinceWindowResized < 3) {
          SDL_GL_SwapBuffers();
        } else {
          glFlush();
        }
      }
    } else {
      SDL_GL_SwapBuffers();
    }
#else
		if (bClearAuto == false) {
			// in accum mode resizing a window is BAD, so we clear on resize events.
			if (nFramesSinceWindowResized < 3) {
				glClearColor(bgPtr[0], bgPtr[1], bgPtr[2], bgPtr[3]);
				glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			}
		}
    SDL_GL_SwapBuffers();
#endif
        
    
    // ------------------------------------------------------------
    // wait a moment plz! keep our framerate sane

    timeNow = ofGetElapsedTimef();
    lastFrameTime = timeNow - timeThen;
    if (lastFrameTime > 0.00001) {
      fps        = 1.0 / lastFrameTime;
      frameRate *= 0.9f;
      frameRate += 0.1f * fps;
    }
    timeThen = timeNow;
    
    // --------------
     
    if (nFrameCount != 0 && bFrameRateSet == true) {
      diffMillis = SDL_GetTicks() - prevMillis;
      if (diffMillis > millisForFrame) {
        ; // we do nothing, we are already slower than target frame
      } else {
        waitMillis = millisForFrame - diffMillis;
        SDL_Delay(waitMillis);
      }
    }
    prevMillis = SDL_GetTicks(); // you have to measure here
    
    
    // ------------------------------------------------------------
    // increment the world
    
    nFrameCount++;
    nFramesSinceWindowResized++; // TODO: do we actually use this?
    
    
    // ------------------------------------------------------------
    // update the application
    
    if (ofAppPtr) {
      ofAppPtr->update();
    }
    
#ifdef OF_USING_POCO
		ofNotifyEvent(ofEvents.update, voidEventArgs);
#endif
    
	}
}
Exemplo n.º 13
0
int main(int argc, char *argv[]) {
    // Get path
    char *ip = NULL;
    unsigned short connect_port = 0;
    unsigned short listen_port = 0;
    int net_mode = NET_MODE_NONE;
    int ret = 0;

    // Path manager
    if(pm_init() != 0) {
        err_msgbox(pm_get_errormsg());
        return 1;
    }

    // Check arguments
    if(argc >= 2) {
        if(strcmp(argv[1], "-v") == 0) {
            printf("OpenOMF v%d.%d.%d\n", V_MAJOR, V_MINOR, V_PATCH);
            printf("Source available at https://github.com/omf2097/ under MIT License\n");
            printf("(C) 2097 Tuomas Virtanen, Andrew Thompson, Hunter and others\n");
            goto exit_0;
        } else if(strcmp(argv[1], "-h") == 0) {
            printf("Arguments:\n");
            printf("-h              Prints this help\n");
            printf("-c [ip] [port]  Connect to server\n");
            printf("-l [port]       Start server\n");
            goto exit_0;
        } else if(strcmp(argv[1], "-c") == 0) {
            if(argc >= 3) {
                ip = strcpy(malloc(strlen(argv[2])+1), argv[2]);
            }
            if(argc >= 4) {
                connect_port = atoi(argv[3]);
            }
            net_mode = NET_MODE_CLIENT;
        } else if(strcmp(argv[1], "-l") == 0) {
            if(argc >= 3) {
                listen_port = atoi(argv[2]);
            }
            net_mode = NET_MODE_SERVER;
        }
    }

    // Init log
#if defined(DEBUGMODE) || defined(STANDALONE_SERVER)
    if(log_init(0)) {
        err_msgbox("Error while initializing log!");
        goto exit_0;
    }
#else
    if(log_init(pm_get_local_path(LOG_PATH))) {
        err_msgbox("Error while initializing log '%s'!", pm_get_local_path(LOG_PATH));
        goto exit_0;
    }
#endif

    // Simple header
    INFO("Starting OpenOMF v%d.%d.%d", V_MAJOR, V_MINOR, V_PATCH);

    // Dump pathmanager log
    pm_log();

    // Random seed
    rand_seed(time(NULL));

    // Init stringparser
    sd_stringparser_lib_init();

    // Init config
    if(settings_init(pm_get_local_path(CONFIG_PATH))) {
        err_msgbox("Failed to initialize settings file");
        goto exit_1;
    }
    settings_load();

    // Find plugins and make sure they are valid
    plugins_init();

    // Network game override stuff
    if(ip) {
        DEBUG("Connect IP overridden to %s", ip);
        settings_get()->net.net_connect_ip = ip;
    }
    if(connect_port > 0 && connect_port < 0xFFFF) {
        DEBUG("Connect Port overridden to %u", connect_port&0xFFFF);
        settings_get()->net.net_connect_port = connect_port;
    }
    if(listen_port > 0 && listen_port < 0xFFFF) {
        DEBUG("Listen Port overridden to %u", listen_port&0xFFFF);
        settings_get()->net.net_listen_port = listen_port;
    }

    // Init SDL2
    unsigned int sdl_flags = SDL_INIT_TIMER;
#ifndef STANDALONE_SERVER
    sdl_flags |= SDL_INIT_VIDEO;
#endif
    if(SDL_Init(sdl_flags)) {
        err_msgbox("SDL2 Initialization failed: %s", SDL_GetError());
        goto exit_2;
    }
    SDL_version sdl_linked;
    SDL_GetVersion(&sdl_linked);
    INFO("Found SDL v%d.%d.%d", sdl_linked.major, sdl_linked.minor, sdl_linked.patch);
    INFO("Running on platform: %s", SDL_GetPlatform());

#ifndef STANDALONE_SERVER
    if(SDL_InitSubSystem(SDL_INIT_JOYSTICK|SDL_INIT_GAMECONTROLLER|SDL_INIT_HAPTIC)) {
        err_msgbox("SDL2 Initialization failed: %s", SDL_GetError());
        goto exit_2;
    }

    // Attempt to find gamecontrollerdb.txt, either from resources or from
    // built-in header
    SDL_RWops *rw = SDL_RWFromConstMem(gamecontrollerdb, strlen(gamecontrollerdb));
    SDL_GameControllerAddMappingsFromRW(rw, 1);
    char *gamecontrollerdbpath = malloc(128);
    snprintf(gamecontrollerdbpath, 128, "%s/gamecontrollerdb.txt", pm_get_local_path(RESOURCE_PATH));
    int mappings_loaded = SDL_GameControllerAddMappingsFromFile(gamecontrollerdbpath);
    if (mappings_loaded > 0) {
        DEBUG("loaded %d mappings from %s", mappings_loaded, gamecontrollerdbpath);
    }
    free(gamecontrollerdbpath);

    // Load up joysticks
    INFO("Found %d joysticks attached", SDL_NumJoysticks());
    SDL_Joystick *joy;
    char guidstr[33];
    for (int i = 0; i < SDL_NumJoysticks(); i++) {
        joy = SDL_JoystickOpen(i);
        if (joy) {
            SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy);
            SDL_JoystickGetGUIDString(guid, guidstr, 33);
            INFO("Opened Joystick %d", i);
            INFO(" * Name:              %s", SDL_JoystickNameForIndex(i));
            INFO(" * Number of Axes:    %d", SDL_JoystickNumAxes(joy));
            INFO(" * Number of Buttons: %d", SDL_JoystickNumButtons(joy));
            INFO(" * Number of Balls:   %d", SDL_JoystickNumBalls(joy));
            INFO(" * Number of Hats:    %d", SDL_JoystickNumHats(joy));
            INFO(" * GUID          :    %s", guidstr);
        } else {
            INFO("Joystick %d is unsupported", i);
        }

        if (SDL_JoystickGetAttached(joy)) {
            SDL_JoystickClose(joy);
        }
    }

    // Init libDumb
    dumb_register_stdfiles();
#endif

    // Init enet
    if(enet_initialize() != 0) {
        err_msgbox("Failed to initialize enet");
        goto exit_3;
    }

    // Initialize engine
    if(engine_init()) {
        err_msgbox("Failed to initialize game engine.");
        goto exit_4;
    }

    // Run
    engine_run(net_mode);

    // Close everything
    engine_close();
exit_4:
    enet_deinitialize();
exit_3:
    SDL_Quit();
exit_2:
    dumb_exit();
    settings_save();
    settings_free();
exit_1:
    sd_stringparser_lib_deinit();
    INFO("Exit.");
    log_close();
exit_0:
    if (ip) {
        free(ip);
    }
    plugins_close();
    pm_free();
    return ret;
}
int
main(int argc, char *argv[])
{
    SDL_Joystick *joystick = NULL;
    SDL_Haptic *haptic = NULL;
    SDL_JoystickID instance = -1;
    SDL_bool keepGoing = SDL_TRUE;
    int i;
    SDL_bool enable_haptic = SDL_TRUE;
    Uint32 init_subsystems = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
    
    for (i = 1; i < argc; ++i) {
        if (SDL_strcasecmp(argv[i], "--nohaptic") == 0) {
            enable_haptic = SDL_FALSE;
        }
    }

    if(enable_haptic) {
        init_subsystems |= SDL_INIT_HAPTIC;
    }
    
    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);	

    SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(init_subsystems) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    //SDL_CreateWindow("Dummy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 128, 128, 0);

    SDL_Log("There are %d joysticks at startup\n", SDL_NumJoysticks());
    if (enable_haptic)
        SDL_Log("There are %d haptic devices at startup\n", SDL_NumHaptics());

    while(keepGoing)
    {
        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT:
                    keepGoing = SDL_FALSE;
                    break;
                case SDL_JOYDEVICEADDED:
                    if (joystick != NULL)
                    {
                        SDL_Log("Only one joystick supported by this test\n");
                    }
                    else
                    {
                        joystick = SDL_JoystickOpen(event.jdevice.which);
                        instance = SDL_JoystickInstanceID(joystick);
                        SDL_Log("Joy Added  : %d : %s\n", event.jdevice.which, SDL_JoystickName(joystick));
                        if (enable_haptic)
                        {
                            if (SDL_JoystickIsHaptic(joystick))
                            {
                                haptic = SDL_HapticOpenFromJoystick(joystick);
                                if (haptic)
                                {
                                    SDL_Log("Joy Haptic Opened\n");
                                    if (SDL_HapticRumbleInit( haptic ) != 0)
                                    {
                                        SDL_Log("Could not init Rumble!: %s\n", SDL_GetError());
                                        SDL_HapticClose(haptic);
                                        haptic = NULL;
                                    }
                                } else {
                                    SDL_Log("Joy haptic open FAILED!: %s\n", SDL_GetError());
                                }
                            }
                            else
                            {
                                SDL_Log("No haptic found\n");
                            }
                        }
                    }
                    break;
                case SDL_JOYDEVICEREMOVED:
                    if (instance == event.jdevice.which)
                    {
                        SDL_Log("Joy Removed: %d\n", event.jdevice.which);
                        instance = -1;
                        if(enable_haptic && haptic)
                        {
                            SDL_HapticClose(haptic);
                            haptic = NULL;
                        }
                        SDL_JoystickClose(joystick);
                        joystick = NULL;
                    } else {
                        SDL_Log("Unknown joystick diconnected\n");
                    }
                    break;
                case SDL_JOYAXISMOTION:
//                    SDL_Log("Axis Move: %d\n", event.jaxis.axis);
                    if (enable_haptic)
                        SDL_HapticRumblePlay(haptic, 0.25, 250);
                    break;
                case SDL_JOYBUTTONDOWN:
                    SDL_Log("Button Press: %d\n", event.jbutton.button);
                    if(enable_haptic && haptic)
                    {
                        SDL_HapticRumblePlay(haptic, 0.25, 250);
                    }
					if (event.jbutton.button == 0) {
						SDL_Log("Exiting due to button press of button 0\n");
						keepGoing = SDL_FALSE;
					}
                    break;
                case SDL_JOYBUTTONUP:
                    SDL_Log("Button Release: %d\n", event.jbutton.button);
                    break;
            }
        }
    }

    SDL_Quit();

    return 0;
}
Exemplo n.º 15
0
void GameStateConfigDesktop::logicInput() {
	if (mouse_move_cb->checkClick()) {
		if (mouse_move_cb->isChecked()) {
			MOUSE_MOVE=true;
			no_mouse_cb->unCheck();
			NO_MOUSE=false;
		}
		else MOUSE_MOVE=false;
	}
	else if (mouse_aim_cb->checkClick()) {
		if (mouse_aim_cb->isChecked()) {
			MOUSE_AIM=true;
			no_mouse_cb->unCheck();
			NO_MOUSE=false;
		}
		else MOUSE_AIM=false;
	}
	else if (no_mouse_cb->checkClick()) {
		if (no_mouse_cb->isChecked()) {
			NO_MOUSE=true;
			mouse_aim_cb->unCheck();
			MOUSE_AIM=false;
			mouse_move_cb->unCheck();
			MOUSE_MOVE=false;
		}
		else NO_MOUSE=false;
	}
	else if (enable_joystick_cb->checkClick()) {
		if (enable_joystick_cb->isChecked()) {
			ENABLE_JOYSTICK=true;
			if (SDL_NumJoysticks() > 0) {
				JOYSTICK_DEVICE = 0;
				SDL_JoystickClose(joy);
				joy = SDL_JoystickOpen(JOYSTICK_DEVICE);
				joystick_device_lstb->selected[JOYSTICK_DEVICE] = true;
			}
		}
		else {
			ENABLE_JOYSTICK=false;
			for (int i=0; i<joystick_device_lstb->getSize(); i++)
				joystick_device_lstb->selected[i] = false;
		}
		if (SDL_NumJoysticks() > 0) joystick_device_lstb->refresh();
	}
	else if (joystick_deadzone_sl->checkClick()) {
		JOY_DEADZONE = joystick_deadzone_sl->getValue();
	}
	else if (joystick_device_lstb->checkClick()) {
		JOYSTICK_DEVICE = joystick_device_lstb->getSelected();
		if (JOYSTICK_DEVICE != -1) {
			enable_joystick_cb->Check();
			ENABLE_JOYSTICK=true;
			if (SDL_NumJoysticks() > 0) {
				SDL_JoystickClose(joy);
				joy = SDL_JoystickOpen(JOYSTICK_DEVICE);
			}
		}
		else {
			enable_joystick_cb->unCheck();
			ENABLE_JOYSTICK = false;
		}
	}
}
Exemplo n.º 16
0
  JoystickInput::JoystickInput(bool sdlInitFlag)
    : eventCnt(0),
      eventIndex(0),
      axisCnt(0),
      buttonCnt(0),
      hatCnt(0),
      updateTimer(),
      pwmTimer(),
      autoFireTimer(),
      mutex_(),
      haveJoystick(false),
      lockFlag(false),
      sdlInitialized(false),
      config()
  {
    sdlDevices[0] = (void *) 0;
    sdlDevices[1] = (void *) 0;
#ifdef HAVE_SDL_H
    if (sdlInitFlag) {
      if (SDL_Init(SDL_INIT_JOYSTICK) != 0)
        return;
      sdlInitialized = true;
    }
    int   nDevices = SDL_NumJoysticks();
    int   j = 0;
    int   prvDevNum = -1;
    for (int i = 0; i < nDevices && j < 2; i++) {
      SDL_Joystick  *joy_ = SDL_JoystickOpen(i);
      if (!joy_)
        continue;
      int   axisCnt_ = SDL_JoystickNumAxes(joy_);
      int   buttonCnt_ = SDL_JoystickNumButtons(joy_);
      int   hatCnt_ = SDL_JoystickNumHats(joy_);
      if (!(axisCnt_ >= 4 && buttonCnt_ >= 4 && hatCnt_ >= 1)) {
        SDL_JoystickClose(joy_);
        continue;
      }
      sdlDevices[j++] = joy_;
      prvDevNum = i;
    }
    for (int i = 0; i < nDevices && j < 2; i++) {
      if (i == prvDevNum)
        continue;
      SDL_Joystick  *joy_ = SDL_JoystickOpen(i);
      if (!joy_)
        continue;
      int   axisCnt_ = SDL_JoystickNumAxes(joy_);
      int   buttonCnt_ = SDL_JoystickNumButtons(joy_);
      int   hatCnt_ = SDL_JoystickNumHats(joy_);
      if (!(axisCnt_ >= 2 && buttonCnt_ >= 1 && hatCnt_ >= 1)) {
        SDL_JoystickClose(joy_);
        continue;
      }
      sdlDevices[j++] = joy_;
      prvDevNum = i;
    }
    for (int i = 0; i < nDevices && j < 2; i++) {
      if (i == prvDevNum)
        continue;
      SDL_Joystick  *joy_ = SDL_JoystickOpen(i);
      if (!joy_)
        continue;
      sdlDevices[j++] = joy_;
    }
    if (!j)
      return;
    nDevices = j;
    for (j = 0; j < nDevices; j++) {
      SDL_Joystick  *joy_ = reinterpret_cast<SDL_Joystick *>(sdlDevices[j]);
      int   axisCnt_ = SDL_JoystickNumAxes(joy_);
      int   buttonCnt_ = SDL_JoystickNumButtons(joy_);
      int   hatCnt_ = SDL_JoystickNumHats(joy_);
      if (j == 0 && nDevices > 1) {
        axisCnt_ = (axisCnt_ < 4 ? axisCnt_ : 4);
        buttonCnt_ = (buttonCnt_ < 8 ? buttonCnt_ : 8);
        hatCnt_ = (hatCnt_ < 1 ? hatCnt_ : 1);
      }
      for (int i = 0; i < axisCnt_ && axisCnt < 8; i++) {
        axes[axisCnt].devNum = j;
        axes[axisCnt].axisNum = i;
        axes[axisCnt].prvInputState = 0;
        axes[axisCnt].prvOutputState = 0;
        axisCnt++;
      }
      for (int i = 0; i < buttonCnt_ && buttonCnt < 16; i++) {
        buttons[buttonCnt].devNum = j;
        buttons[buttonCnt].buttonNum = i;
        buttons[buttonCnt].prvInputState = false;
        buttons[buttonCnt].prvOutputState = false;
        buttonCnt++;
      }
      for (int i = 0; i < hatCnt_ && hatCnt < 2; i++) {
        povHats[hatCnt].devNum = j;
        povHats[hatCnt].hatNum = i;
        povHats[hatCnt].prvState = SDL_HAT_CENTERED;
        hatCnt++;
      }
    }
    haveJoystick = (axisCnt > 0 || buttonCnt > 0 || hatCnt > 0);
#else
    (void) sdlInitFlag;
#endif  // HAVE_SDL_H
  }
Exemplo n.º 17
0
/*
 * Open a joystick for use - the index passed as an argument refers to
 * the N'th joystick on the system.  This index is the value which will
 * identify this joystick in future joystick events.
 *
 * This function returns a joystick identifier, or NULL if an error occurred.
 */
SDL_Joystick *
SDL_JoystickOpen(int device_index)
{
    SDL_Joystick *joystick;
    SDL_Joystick *joysticklist;
    const char *joystickname = NULL;

    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
        return (NULL);
    }

    joysticklist = SDL_joysticks;
    /* If the joystick is already open, return it
    * it is important that we have a single joystick * for each instance id
    */
    while (joysticklist) {
        if (SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == joysticklist->instance_id) {
                joystick = joysticklist;
                ++joystick->ref_count;
                return (joystick);
        }
        joysticklist = joysticklist->next;
    }

    /* Create and initialize the joystick */
    joystick = (SDL_Joystick *) SDL_malloc((sizeof *joystick));
    if (joystick == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    SDL_memset(joystick, 0, (sizeof *joystick));
    if (SDL_SYS_JoystickOpen(joystick, device_index) < 0) {
        SDL_free(joystick);
        return NULL;
    }

    joystickname = SDL_SYS_JoystickNameForDeviceIndex(device_index);
    if (joystickname)
        joystick->name = SDL_strdup(joystickname);
    else
        joystick->name = NULL;

    if (joystick->naxes > 0) {
        joystick->axes = (Sint16 *) SDL_malloc
            (joystick->naxes * sizeof(Sint16));
    }
    if (joystick->nhats > 0) {
        joystick->hats = (Uint8 *) SDL_malloc
            (joystick->nhats * sizeof(Uint8));
    }
    if (joystick->nballs > 0) {
        joystick->balls = (struct balldelta *) SDL_malloc
            (joystick->nballs * sizeof(*joystick->balls));
    }
    if (joystick->nbuttons > 0) {
        joystick->buttons = (Uint8 *) SDL_malloc
            (joystick->nbuttons * sizeof(Uint8));
    }
    if (((joystick->naxes > 0) && !joystick->axes)
        || ((joystick->nhats > 0) && !joystick->hats)
        || ((joystick->nballs > 0) && !joystick->balls)
        || ((joystick->nbuttons > 0) && !joystick->buttons)) {
        SDL_OutOfMemory();
        SDL_JoystickClose(joystick);
        return NULL;
    }
    if (joystick->axes) {
        SDL_memset(joystick->axes, 0, joystick->naxes * sizeof(Sint16));
    }
    if (joystick->hats) {
        SDL_memset(joystick->hats, 0, joystick->nhats * sizeof(Uint8));
    }
    if (joystick->balls) {
        SDL_memset(joystick->balls, 0,
            joystick->nballs * sizeof(*joystick->balls));
    }
    if (joystick->buttons) {
        SDL_memset(joystick->buttons, 0, joystick->nbuttons * sizeof(Uint8));
    }

    /* Add joystick to list */
    ++joystick->ref_count;
    /* Link the joystick in the list */
    joystick->next = SDL_joysticks;
    SDL_joysticks = joystick;

    SDL_SYS_JoystickUpdate(joystick);

    return (joystick);
}
Exemplo n.º 18
0
/*
===============
IN_InitJoystick
===============
*/
static void IN_InitJoystick( void )
{
	int i = 0;
	int total = 0;

	if ( stick != NULL )
	{
		SDL_JoystickClose( stick );
	}

	stick = NULL;
	memset( &stick_state, '\0', sizeof( stick_state ) );

	if ( !in_joystick->integer && !in_xbox360Controller->integer )
	{
		Com_DPrintf( "Joystick is not active.\n" );

		if ( !in_xbox360Controller->integer )
		{
			Com_DPrintf( "Gamepad is not active.\n" );
			Cvar_Set( "in_xbox360ControllerAvailable", "0" );
		}

		return;
	}

	if ( !SDL_WasInit( SDL_INIT_JOYSTICK ) )
	{
		Com_DPrintf( "Calling SDL_Init(SDL_INIT_JOYSTICK)...\n" );

		if ( SDL_Init( SDL_INIT_JOYSTICK ) == -1 )
		{
			Com_DPrintf( "SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError() );
			return;
		}

		Com_DPrintf( "SDL_Init(SDL_INIT_JOYSTICK) passed.\n" );
	}

	total = SDL_NumJoysticks();
	Com_DPrintf( "%d possible joysticks\n", total );

	for ( i = 0; i < total; i++ )
	{
		Com_DPrintf( "[%d] %s\n", i, SDL_JoystickName( i ) );
	}

	in_joystickNo = Cvar_Get( "in_joystickNo", "0", CVAR_ARCHIVE );

	if ( in_joystickNo->integer < 0 || in_joystickNo->integer >= total )
	{
		Cvar_Set( "in_joystickNo", "0" );
	}

	in_joystickUseAnalog = Cvar_Get( "in_joystickUseAnalog", "0", CVAR_ARCHIVE );

	stick = SDL_JoystickOpen( in_joystickNo->integer );

	if ( stick == NULL )
	{
		Com_DPrintf( "No joystick opened.\n" );
		return;
	}

	Com_DPrintf( "Joystick %d opened\n", in_joystickNo->integer );
	Com_DPrintf( "Name:    %s\n", SDL_JoystickName( in_joystickNo->integer ) );
	Com_DPrintf( "Axes:    %d\n", SDL_JoystickNumAxes( stick ) );
	Com_DPrintf( "Hats:    %d\n", SDL_JoystickNumHats( stick ) );
	Com_DPrintf( "Buttons: %d\n", SDL_JoystickNumButtons( stick ) );
	Com_DPrintf( "Balls: %d\n", SDL_JoystickNumBalls( stick ) );
	Com_DPrintf( "Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No" );

	SDL_JoystickEventState( SDL_QUERY );

	// XBox 360 controller support
	if ( !Q_stricmp( SDL_JoystickName( in_joystickNo->integer ), "Microsoft X-Box 360 pad" ) )
	{
		Cvar_Set( "in_xbox360ControllerAvailable", "1" );
	}
	else
	{
		Cvar_Set( "in_xbox360ControllerAvailable", "0" );
	}
}
Exemplo n.º 19
0
/*
===============
IN_InitJoystick
===============
*/
static void IN_InitJoystick( void )
{
	int i = 0;
	int total = 0;
	char buf[16384] = "";

	if (stick != NULL)
		SDL_JoystickClose(stick);

	stick = NULL;
	memset(&stick_state, '\0', sizeof (stick_state));

	if (!SDL_WasInit(SDL_INIT_JOYSTICK))
	{
		Com_DPrintf("Calling SDL_Init(SDL_INIT_JOYSTICK)...\n");
		if (SDL_Init(SDL_INIT_JOYSTICK) == -1)
		{
			Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError());
			return;
		}
		Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) passed.\n");
	}

	total = SDL_NumJoysticks();
	Com_DPrintf("%d possible joysticks\n", total);

	// Print list and build cvar to allow ui to select joystick.
	for (i = 0; i < total; i++)
	{
		Q_strcat(buf, sizeof(buf), SDL_JoystickNameForIndex(i));
		Q_strcat(buf, sizeof(buf), "\n");
	}

	Cvar_Get( "in_availableJoysticks", buf, CVAR_ROM );

	if( !in_joystick->integer ) {
		Com_DPrintf( "Joystick is not active.\n" );
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return;
	}

	in_joystickNo = Cvar_Get( "in_joystickNo", "0", CVAR_ARCHIVE );
	if( in_joystickNo->integer < 0 || in_joystickNo->integer >= total )
		Cvar_Set( "in_joystickNo", "0" );

	in_joystickUseAnalog = Cvar_Get( "in_joystickUseAnalog", "0", CVAR_ARCHIVE );

	in_joystickThreshold = Cvar_Get( "joy_threshold", "0.15", CVAR_ARCHIVE );

	stick = SDL_JoystickOpen( in_joystickNo->integer );

	if (stick == NULL) {
		Com_DPrintf( "No joystick opened.\n" );
		return;
	}

	Com_DPrintf( "Joystick %d opened\n", in_joystickNo->integer );
	Com_DPrintf( "Name:       %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer) );
	Com_DPrintf( "Axes:       %d\n", SDL_JoystickNumAxes(stick) );
	Com_DPrintf( "Hats:       %d\n", SDL_JoystickNumHats(stick) );
	Com_DPrintf( "Buttons:    %d\n", SDL_JoystickNumButtons(stick) );
	Com_DPrintf( "Balls:      %d\n", SDL_JoystickNumBalls(stick) );
	Com_DPrintf( "Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No" );
	Com_DPrintf( "Threshold: %f\n", in_joystickThreshold->value );

	SDL_JoystickEventState(SDL_QUERY);
}
Exemplo n.º 20
0
int JoyStick::numJoysticks()
{
	return SDL_NumJoysticks();
}
Exemplo n.º 21
0
XInputController::XInputController(uint Port /*= 0*/)
    : m_Port(Port)
#if BUILD_SDL
      ,
      m_Controller(nullptr)
#endif
      ,
      m_LeftThumbDeadZone(0.0f),
      m_RightThumbDeadZone(0.0f),
      m_LeftThumbSaturationPoint(0.0f),
      m_RightThumbSaturationPoint(0.0f),
      m_TriggerDeadZone(0.0f),
      m_TriggerSaturationPoint(0.0f),
      m_LeftThumbBoolThreshold(0.0f),
      m_RightThumbBoolThreshold(0.0f),
      m_LeftTriggerBoolThreshold(0.0f),
      m_RightTriggerBoolThreshold(0.0f),
      m_ReceivedInputThisTick(false) {
  memset(&m_CurrentState, 0, sizeof(SXInputState));
  memset(&m_LastState, 0, sizeof(SXInputState));

  STATICHASH(LeftThumbDeadZone);
  STATICHASH(RightThumbDeadZone);
  STATICHASH(LeftThumbSaturationPoint);
  STATICHASH(RightThumbSaturationPoint);
  STATICHASH(TriggerDeadZone);
  STATICHASH(TriggerSaturationPoint);
  STATICHASH(LeftThumbBoolThreshold);
  STATICHASH(RightThumbBoolThreshold);
  STATICHASH(LeftTriggerBoolThreshold);
  STATICHASH(RightTriggerBoolThreshold);

  ConfigManager::Bind(&m_LeftThumbDeadZone, sLeftThumbDeadZone, 0.2f);
  ConfigManager::Bind(&m_RightThumbDeadZone, sRightThumbDeadZone, 0.2f);
  ConfigManager::Bind(&m_LeftThumbSaturationPoint, sLeftThumbSaturationPoint,
                      0.9f);
  ConfigManager::Bind(&m_RightThumbSaturationPoint, sRightThumbSaturationPoint,
                      0.9f);
  ConfigManager::Bind(&m_TriggerDeadZone, sTriggerDeadZone, 0.1f);
  ConfigManager::Bind(&m_TriggerSaturationPoint, sTriggerSaturationPoint, 0.9f);

  ConfigManager::Bind(&m_LeftThumbBoolThreshold, sLeftThumbSaturationPoint,
                      1.0f);
  ConfigManager::Bind(&m_RightThumbBoolThreshold, sRightThumbSaturationPoint,
                      1.0f);
  ConfigManager::Bind(&m_LeftTriggerBoolThreshold, sTriggerDeadZone, 1.0f);
  ConfigManager::Bind(&m_RightTriggerBoolThreshold, sTriggerSaturationPoint,
                      1.0f);

#if BUILD_SDL
  const uint NumJoysticks = SDL_NumJoysticks();
  uint PortIndex = 0;
  for (uint JoystickIndex = 0; JoystickIndex < NumJoysticks; ++JoystickIndex) {
    if (SDL_IsGameController(JoystickIndex)) {
      if (PortIndex == m_Port) {
        m_Controller = SDL_GameControllerOpen(JoystickIndex);
        ASSERT(m_Controller);
        break;
      } else {
        ++PortIndex;
      }
    }
  }
#endif
}
Exemplo n.º 22
0
void joy_init()
{
	int i,j,n;
	char temp[10];

	if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
		con_printf(CON_NORMAL, "sdl-joystick: initialisation failed: %s.",SDL_GetError());
		return;
	}

	memset(&Joystick,0,sizeof(Joystick));
	memset(joyaxis_text, 0, JOY_MAX_AXES * sizeof(char *));
	memset(joybutton_text, 0, JOY_MAX_BUTTONS * sizeof(char *));

	n = SDL_NumJoysticks();

	con_printf(CON_NORMAL, "sdl-joystick: found %d joysticks\n", n);
	for (i = 0; i < n; i++) {
		con_printf(CON_NORMAL, "sdl-joystick %d: %s\n", i, SDL_JoystickName(i));
		SDL_Joysticks[num_joysticks].handle = SDL_JoystickOpen(i);
		if (SDL_Joysticks[num_joysticks].handle) {

			SDL_Joysticks[num_joysticks].n_axes
				= SDL_JoystickNumAxes(SDL_Joysticks[num_joysticks].handle);
			if(SDL_Joysticks[num_joysticks].n_axes > MAX_AXES_PER_JOYSTICK)
			{
				Warning("sdl-joystick: found %d axes, only %d supported.\n", SDL_Joysticks[num_joysticks].n_axes, MAX_AXES_PER_JOYSTICK);
				Warning("sdl-joystick: found %d axes, only %d supported.\n", SDL_Joysticks[num_joysticks].n_axes, MAX_AXES_PER_JOYSTICK);
				SDL_Joysticks[num_joysticks].n_axes = MAX_AXES_PER_JOYSTICK;
			}

			SDL_Joysticks[num_joysticks].n_buttons
				= SDL_JoystickNumButtons(SDL_Joysticks[num_joysticks].handle);
			if(SDL_Joysticks[num_joysticks].n_buttons > MAX_BUTTONS_PER_JOYSTICK)
			{
				Warning("sdl-joystick: found %d buttons, only %d supported.\n", SDL_Joysticks[num_joysticks].n_buttons, MAX_BUTTONS_PER_JOYSTICK);
				SDL_Joysticks[num_joysticks].n_buttons = MAX_BUTTONS_PER_JOYSTICK;
			}

			SDL_Joysticks[num_joysticks].n_hats
				= SDL_JoystickNumHats(SDL_Joysticks[num_joysticks].handle);
			if(SDL_Joysticks[num_joysticks].n_hats > MAX_HATS_PER_JOYSTICK)
			{
				Warning("sdl-joystick: found %d hats, only %d supported.\n", SDL_Joysticks[num_joysticks].n_hats, MAX_HATS_PER_JOYSTICK);
				SDL_Joysticks[num_joysticks].n_hats = MAX_HATS_PER_JOYSTICK;
			}

			con_printf(CON_NORMAL, "sdl-joystick: %d axes\n", SDL_Joysticks[num_joysticks].n_axes);
			con_printf(CON_NORMAL, "sdl-joystick: %d buttons\n", SDL_Joysticks[num_joysticks].n_buttons);
			con_printf(CON_NORMAL, "sdl-joystick: %d hats\n", SDL_Joysticks[num_joysticks].n_hats);

			for (j=0; j < SDL_Joysticks[num_joysticks].n_axes; j++)
			{
				sprintf(temp, "J%d A%d", i + 1, j + 1);
				joyaxis_text[Joystick.n_axes] = d_strdup(temp);
				SDL_Joysticks[num_joysticks].axis_map[j] = Joystick.n_axes++;
			}
			for (j=0; j < SDL_Joysticks[num_joysticks].n_buttons; j++)
			{
				sprintf(temp, "J%d B%d", i + 1, j + 1);
				joybutton_text[Joystick.n_buttons] = d_strdup(temp);
				SDL_Joysticks[num_joysticks].button_map[j] = Joystick.n_buttons++;
			}
			for (j=0; j < SDL_Joysticks[num_joysticks].n_hats; j++)
			{
				SDL_Joysticks[num_joysticks].hat_map[j] = Joystick.n_buttons;
				//a hat counts as four buttons
				sprintf(temp, "J%d H%d%c", i + 1, j + 1, 0202);
				joybutton_text[Joystick.n_buttons++] = d_strdup(temp);
				sprintf(temp, "J%d H%d%c", i + 1, j + 1, 0177);
				joybutton_text[Joystick.n_buttons++] = d_strdup(temp);
				sprintf(temp, "J%d H%d%c", i + 1, j + 1, 0200);
				joybutton_text[Joystick.n_buttons++] = d_strdup(temp);
				sprintf(temp, "J%d H%d%c", i + 1, j + 1, 0201);
				joybutton_text[Joystick.n_buttons++] = d_strdup(temp);
			}

			num_joysticks++;
		}
		else
			con_printf(CON_NORMAL, "sdl-joystick: initialization failed!\n");

		con_printf(CON_NORMAL, "sdl-joystick: %d axes (total)\n", Joystick.n_axes);
		con_printf(CON_NORMAL, "sdl-joystick: %d buttons (total)\n", Joystick.n_buttons);
	}

	joy_num_axes = Joystick.n_axes;
}
Exemplo n.º 23
0
void fs_ml_input_init() {
    FS_ML_INIT_ONCE;

    SDL_Init(SDL_INIT_JOYSTICK);

    fs_log("fs_ml_input_init\n");

    if (fs_config_get_boolean(OPTION_MOUSE_INTEGRATION) == 1) {
        g_mouse_integration = 1;
    }

    g_cursor_mode = fs_config_get_boolean(OPTION_CURSOR);
    if (fs_config_check_auto(OPTION_CURSOR, FS_CONFIG_AUTO)) {
        if (fs_emu_mouse_integration()) {
            g_cursor_mode = 0;
        } else {
            g_cursor_mode = -1;
        }
    }

    g_input_queue = g_queue_new();
    g_input_mutex = fs_mutex_create();

    fs_log("calling fs_ml_video_init\n");
    fs_ml_video_init();

    int size = sizeof(fs_ml_input_device) * FS_ML_INPUT_DEVICES_MAX;
    // allocate zeroed memory
    g_fs_ml_input_devices = g_malloc0(size);

    fs_ml_initialize_keymap();

    int k = 0;
    g_fs_ml_first_joystick_index = 0;

    g_fs_ml_input_devices[k].type = FS_ML_KEYBOARD;
    g_fs_ml_input_devices[k].index = k;
    g_fs_ml_input_devices[k].name = g_strdup("KEYBOARD");
    g_fs_ml_input_devices[k].alias = g_strdup("KEYBOARD");
    k += 1;

    g_fs_ml_input_device_count = k;
    fs_ml_mouse_init();
    k = g_fs_ml_input_device_count;

    g_fs_ml_first_joystick_index = g_fs_ml_input_device_count;

    int num_joysticks = SDL_NumJoysticks();
    fs_log("num joystick devices: %d\n", num_joysticks);
    if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) {
        fs_log("WARNING: Joystick module not initialized\n");
    }
    for (int i = 0; i < num_joysticks; i++) {
        if (k == FS_ML_INPUT_DEVICES_MAX) {
            fs_log("WARNING: reached max num devices\n");
            break;
        }
        SDL_Joystick *joystick = SDL_JoystickOpen(i);

#ifdef USE_SDL2
        char* name = g_ascii_strup(SDL_JoystickName(joystick), -1);
#else
        char* name = g_ascii_strup(SDL_JoystickName(i), -1);
#endif
        name = g_strstrip(name);
        if (name[0] == '\0') {
            g_free(name);
            name = g_ascii_strup("Unnamed", -1);
        }

        // fs_ml_input_unique_device_name either returns name, or frees it
        // and return another name, so name must be malloced and owned by
        // caller
        name = fs_ml_input_unique_device_name(name);

        g_fs_ml_input_devices[k].type = FS_ML_JOYSTICK;
        g_fs_ml_input_devices[k].index = k;
        g_fs_ml_input_devices[k].name = name;
        if (i == 0) {
            g_fs_ml_input_devices[k].alias = g_strdup("JOYSTICK");
        }
        else {
            g_fs_ml_input_devices[k].alias = g_strdup_printf("JOYSTICK #%d",
                    i + 1);
        }

        g_fs_ml_input_devices[k].hats = SDL_JoystickNumHats(joystick);
        g_fs_ml_input_devices[k].buttons = SDL_JoystickNumButtons(joystick);
        g_fs_ml_input_devices[k].axes = SDL_JoystickNumAxes(joystick);
        g_fs_ml_input_devices[k].balls = SDL_JoystickNumBalls(joystick);

        fs_log("joystick device #%02d found: %s\n", i + 1, name);
        fs_log("- %d buttons %d hats %d axes %d balls\n",
                g_fs_ml_input_devices[k].buttons,
                g_fs_ml_input_devices[k].hats,
                g_fs_ml_input_devices[k].axes,
                g_fs_ml_input_devices[k].balls);
        k += 1;
    }

    g_fs_ml_input_device_count = k;

    fs_ml_initialize_keymap();
}
Exemplo n.º 24
0
int
main(int argc, char *argv[])
{
    const char *name;
    int i;
    SDL_Joystick *joystick;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);	

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    /* Print information about the joysticks */
    SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        name = SDL_JoystickNameForIndex(i);
        SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
        joystick = SDL_JoystickOpen(i);
        if (joystick == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
                    SDL_GetError());
        } else {
            char guid[64];
            SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                      guid, sizeof (guid));
            SDL_Log("       axes: %d\n", SDL_JoystickNumAxes(joystick));
            SDL_Log("      balls: %d\n", SDL_JoystickNumBalls(joystick));
            SDL_Log("       hats: %d\n", SDL_JoystickNumHats(joystick));
            SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
            SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
            SDL_Log("       guid: %s\n", guid);
            SDL_JoystickClose(joystick);
        }
    }

#ifdef __ANDROID__
    if (SDL_NumJoysticks() > 0) {
#else
    if (argv[1]) {
#endif
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device;
#ifdef __ANDROID__
        device = 0;
#else
        device = atoi(argv[1]);
#endif
        joystick = SDL_JoystickOpen(device);

        while ( keepGoing ) {
            if (joystick == NULL) {
                if ( !reportederror ) {
                    SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
                    keepGoing = SDL_FALSE;
                    reportederror = SDL_TRUE;
                }
            } else {
                reportederror = SDL_FALSE;
                keepGoing = WatchJoystick(joystick);
                SDL_JoystickClose(joystick);
            }

            joystick = NULL;
            if (keepGoing) {
                SDL_Log("Waiting for attach\n");
            }
            while (keepGoing) {
                SDL_WaitEvent(&event);
                if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                    || (event.type == SDL_MOUSEBUTTONDOWN)) {
                    keepGoing = SDL_FALSE;
                } else if (event.type == SDL_JOYDEVICEADDED) {
                    joystick = SDL_JoystickOpen(device);
                    break;
                }
            }
        }
    }
    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

    return 0;
}

#else

int
main(int argc, char *argv[])
{
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
    exit(1);
}
Exemplo n.º 25
0
void InputDaemon::refreshJoysticks()
{
#ifdef USE_SDL_2
    QHashIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
#else
    QHashIterator<int, InputDevice*> iter(*joysticks);
#endif
    while (iter.hasNext())
    {
        InputDevice *joystick = iter.next().value();
        if (joystick)
        {
            delete joystick;
            joystick = 0;
        }
    }

    joysticks->clear();
#ifdef USE_SDL_2
    trackjoysticks.clear();
    trackcontrollers.clear();
#endif

#ifdef USE_SDL_2
    QSettings settings(PadderCommon::configFilePath, QSettings::IniFormat);
    settings.beginGroup("Mappings");
#endif

    for (int i=0; i < SDL_NumJoysticks(); i++)
    {
#ifdef USE_SDL_2

        SDL_Joystick *joystick = SDL_JoystickOpen(i);

        QString temp;
        SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joystick);
        char guidString[65] = {'0'};
        SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
        temp = QString(guidString);

        bool disableGameController = settings.value(QString("%1Disable").arg(temp), false).toBool();

        if (SDL_IsGameController(i) && !disableGameController)
        {
            SDL_GameController *controller = SDL_GameControllerOpen(i);
            GameController *damncontroller = new GameController(controller, i, this);
            SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
            SDL_JoystickID joystickID = SDL_JoystickInstanceID(sdlStick);
            joysticks->insert(joystickID, damncontroller);
            trackcontrollers.insert(joystickID, damncontroller);
        }
        else
        {
            Joystick *curJoystick = new Joystick(joystick, i, this);
            SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
            joysticks->insert(joystickID, curJoystick);
            trackjoysticks.insert(joystickID, curJoystick);
        }
#else
        SDL_Joystick *joystick = SDL_JoystickOpen(i);
        Joystick *curJoystick = new Joystick(joystick, i, this);
        joysticks->insert(i, curJoystick);
#endif
    }

#ifdef USE_SDL_2
    settings.endGroup();
#endif

    emit joysticksRefreshed(joysticks);
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
    SDL_Joystick *joy = NULL;
    int t1, t0;

    if (!fs_init(argv[0]))
    {
        fprintf(stderr, "Failure to initialize virtual file system (%s)\n",
                fs_error());
        return 1;
    }

    opt_parse(argc, argv);

    config_paths(opt_data);
    log_init("Neverball", "neverball.log");
    make_dirs_and_migrate();

    /* Initialize SDL. */

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == -1)
    {
        log_printf("Failure to initialize SDL (%s)\n", SDL_GetError());
        return 1;
    }

    /* Intitialize configuration. */

    config_init();
    config_load();

    /* Initialize localization. */

    lang_init();

    /* Initialize joystick. */

    if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
    {
        joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
        if (joy)
            SDL_JoystickEventState(SDL_ENABLE);
    }

    /* Initialize audio. */

    audio_init();
    tilt_init();

    /* Initialize video. */

    if (!video_init())
        return 1;

    /* Material system. */

    mtrl_init();

    /* Screen states. */

    init_state(&st_null);

    /* Initialize demo playback or load the level. */

    if (opt_replay &&
        fs_add_path(dir_name(opt_replay)) &&
        progress_replay(base_name(opt_replay)))
    {
        demo_play_goto(1);
        goto_state(&st_demo_play);
    }
    else if (opt_level)
    {
        const char *path = fs_resolve(opt_level);
        int loaded = 0;

        if (path)
        {
            /* HACK: must be around for the duration of the game. */
            static struct level level;

            if (level_load(path, &level))
            {
                progress_init(MODE_STANDALONE);

                if (progress_play(&level))
                {
                    goto_state(&st_level);
                    loaded = 1;
                }
            }
        }
        else log_printf("File %s is not in game path\n", opt_level);

        if (!loaded)
            goto_state(&st_title);
    }
    else
        goto_state(&st_title);

    /* Run the main game loop. */

    t0 = SDL_GetTicks();

    while (loop())
    {
        if ((t1 = SDL_GetTicks()) > t0)
        {
            /* Step the game state. */

            st_timer(0.001f * (t1 - t0));

            t0 = t1;

            /* Render. */

            hmd_step();
            st_paint(0.001f * t0);
            video_swap();

            if (config_get_d(CONFIG_NICE))
                SDL_Delay(1);
        }
    }

    config_save();

    mtrl_quit();

    if (joy)
        SDL_JoystickClose(joy);

    tilt_free();
    hmd_free();
    SDL_Quit();

    return 0;
}
Exemplo n.º 27
0
int
main(int argc, char *argv[])
{
    int i;
    int nController = 0;
    int retcode = 0;
    char guid[64];
    SDL_GameController *gamecontroller;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER ) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
    
    SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");

    /* Print information about the controller */
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        const char *name;
        const char *description;

        SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i),
                                  guid, sizeof (guid));

        if ( SDL_IsGameController(i) )
        {
            nController++;
            name = SDL_GameControllerNameForIndex(i);
            description = "Controller";
        } else {
            name = SDL_JoystickNameForIndex(i);
            description = "Joystick";
        }
        SDL_Log("%s %d: %s (guid %s)\n", description, i, name ? name : "Unknown", guid);
    }
    SDL_Log("There are %d game controller(s) attached (%d joystick(s))\n", nController, SDL_NumJoysticks());

    if (argv[1]) {
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device = atoi(argv[1]);
        if (device >= SDL_NumJoysticks()) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%i is an invalid joystick index.\n", device);
            retcode = 1;
        } else {
            SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(device),
                                      guid, sizeof (guid));
            SDL_Log("Attempting to open device %i, guid %s\n", device, guid);
            gamecontroller = SDL_GameControllerOpen(device);

            if (gamecontroller != NULL) {
                SDL_assert(SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) == gamecontroller);
            }

            while (keepGoing) {
                if (gamecontroller == NULL) {
                    if (!reportederror) {
                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open gamecontroller %d: %s\n", device, SDL_GetError());
                        retcode = 1;
                        keepGoing = SDL_FALSE;
                        reportederror = SDL_TRUE;
                    }
                } else {
                    reportederror = SDL_FALSE;
                    keepGoing = WatchGameController(gamecontroller);
                    SDL_GameControllerClose(gamecontroller);
                }

                gamecontroller = NULL;
                if (keepGoing) {
                    SDL_Log("Waiting for attach\n");
                }
                while (keepGoing) {
                    SDL_WaitEvent(&event);
                    if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                        || (event.type == SDL_MOUSEBUTTONDOWN)) {
                        keepGoing = SDL_FALSE;
                    } else if (event.type == SDL_CONTROLLERDEVICEADDED) {
                        gamecontroller = SDL_GameControllerOpen(event.cdevice.which);
                        if (gamecontroller != NULL) {
                            SDL_assert(SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) == gamecontroller);
                        }
                        break;
                    }
                }
            }
        }
    }

    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);

    return retcode;
}
Exemplo n.º 28
0
bool GameStateConfigDesktop::parseKeyDesktop(FileParser &infile, int &x1, int &y1, int &x2, int &y2) {
	// @CLASS GameStateConfigDesktop|Description of menus/config.txt

	int keybind_num = -1;

	if (infile.key == "listbox_scrollbar_offset") {
		// overrides same key in GameStateConfigBase
		joystick_device_lstb->scrollbar_offset = x1;
		activemods_lstb->scrollbar_offset = x1;
		inactivemods_lstb->scrollbar_offset = x1;
		language_lstb->scrollbar_offset = x1;
	}
	else if (infile.key == "fullscreen") {
		// @ATTR fullscreen|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Full Screen Mode" checkbox relative to the frame.
		placeLabeledWidget(fullscreen_lb, fullscreen_cb, x1, y1, x2, y2, msg->get("Full Screen Mode"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "mouse_move") {
		// @ATTR mouse_move|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Move hero using mouse" checkbox relative to the frame.
		placeLabeledWidget(mouse_move_lb, mouse_move_cb, x1, y1, x2, y2, msg->get("Move hero using mouse"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "hwsurface") {
		// @ATTR hwsurface|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Hardware surfaces" checkbox relative to the frame.
		placeLabeledWidget(hwsurface_lb, hwsurface_cb, x1, y1, x2, y2, msg->get("Hardware surfaces"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "vsync") {
		// @ATTR vsync|label x (integer), label y (integer), x (integer), y (integer)|Position of the "V-Sync" checkbox relative to the frame.
		placeLabeledWidget(vsync_lb, vsync_cb, x1, y1, x2, y2, msg->get("V-Sync"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "texture_filter") {
		// @ATTR texture_filter|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Texture Filtering" checkbox relative to the frame.
		placeLabeledWidget(texture_filter_lb, texture_filter_cb, x1, y1, x2, y2, msg->get("Texture Filtering"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "change_gamma") {
		// @ATTR change_gamma|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Allow changing gamma" checkbox relative to the frame.
		placeLabeledWidget(change_gamma_lb, change_gamma_cb, x1, y1, x2, y2, msg->get("Allow changing gamma"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "gamma") {
		// @ATTR gamma|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Gamma" slider relative to the frame.
		placeLabeledWidget(gamma_lb, gamma_sl, x1, y1, x2, y2, msg->get("Gamma"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "hws_note") {
		// @ATTR hws_note|x (integer), y (integer)|Position of the "Disable for performance" label (next to Hardware surfaces) relative to the frame.
		hws_note_lb->setBasePos(x1, y1);
		hws_note_lb->set(msg->get("Disable for performance"));
	}
	else if (infile.key == "dbuf_note") {
		// @ATTR dbuf_note|x (integer), y (integer)|Position of the "Disable for performance" label (next to Double buffering) relative to the frame.
		dbuf_note_lb->setBasePos(x1, y1);
		dbuf_note_lb->set(msg->get("Disable for performance"));
	}
	else if (infile.key == "test_note") {
		// @ATTR test_note|x (integer), y (integer)|Position of the "Experimental" label relative to the frame.
		test_note_lb->setBasePos(x1, y1);
		test_note_lb->set(msg->get("Experimental"));
	}
	else if (infile.key == "enable_joystick") {
		// @ATTR enable_joystick|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Use joystick" checkbox relative to the frame.
		placeLabeledWidget(enable_joystick_lb, enable_joystick_cb, x1, y1, x2, y2, msg->get("Use joystick"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "joystick_device") {
		// @ATTR joystick_device|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Joystick" list box relative to the frame.
		placeLabeledWidget(joystick_device_lb, joystick_device_lstb, x1, y1, x2, y2, msg->get("Joystick"));

		for(int i = 0; i < SDL_NumJoysticks(); i++) {
			std::string joystick_name = inpt->getJoystickName(i);
			if (joystick_name != "")
				joystick_device_lstb->append(joystick_name, joystick_name);
		}
	}
	else if (infile.key == "mouse_aim") {
		// @ATTR mouse_aim|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Mouse aim" checkbox relative to the frame.
		placeLabeledWidget(mouse_aim_lb, mouse_aim_cb, x1, y1, x2, y2, msg->get("Mouse aim"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "no_mouse") {
		// @ATTR no_mouse|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Do not use mouse" checkbox relative to the frame.
		placeLabeledWidget(no_mouse_lb, no_mouse_cb, x1, y1, x2, y2, msg->get("Do not use mouse"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "joystick_deadzone") {
		// @ATTR joystick_deadzone|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Joystick Deadzone" slider relative to the frame.
		placeLabeledWidget(joystick_deadzone_lb, joystick_deadzone_sl, x1, y1, x2, y2, msg->get("Joystick Deadzone"), JUSTIFY_RIGHT);
	}
	else if (infile.key == "handheld_note") {
		// @ATTR handheld_note|x (integer), y (integer)|Position of the "For handheld devices" label relative to the frame.
		handheld_note_lb->setBasePos(x1, y1);
		handheld_note_lb->set(msg->get("For handheld devices"));
	}
	else if (infile.key == "secondary_offset") {
		// @ATTR secondary_offset|x (integer), y (integer)|Offset of the second (and third) columns of keybinds.
		secondary_offset.x = x1;
		secondary_offset.y = y1;
	}
	else if (infile.key == "keybinds_bg_color") {
		// @ATTR keybinds_bg_color|r (integer), g (integer), b (integer)|Background color for the keybindings scrollbox.
		scrollpane_color.r = x1;
		scrollpane_color.g = y1;
		scrollpane_color.b = x2;
	}
	else if (infile.key == "scrollpane") {
		// @ATTR scrollpane|x (integer), y (integer), w (integer), h (integer)|Position of the keybinding scrollbox relative to the frame.
		scrollpane.x = x1;
		scrollpane.y = y1;
		scrollpane.w = x2;
		scrollpane.h = y2;
	}
	else if (infile.key == "scrollpane_contents") {
		// @ATTR scrollpane_contents|integer|The vertical size of the keybinding scrollbox's contents.
		scrollpane_contents = x1;
	}

	// @ATTR cancel|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Cancel" keybind relative to the keybinding scrollbox.
	else if (infile.key == "cancel") keybind_num = CANCEL;
	// @ATTR accept|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Accept" keybind relative to the keybinding scrollbox.
	else if (infile.key == "accept") keybind_num = ACCEPT;
	// @ATTR up|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Up" keybind relative to the keybinding scrollbox.
	else if (infile.key == "up") keybind_num = UP;
	// @ATTR down|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Down" keybind relative to the keybinding scrollbox.
	else if (infile.key == "down") keybind_num = DOWN;
	// @ATTR left|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Left" keybind relative to the keybinding scrollbox.
	else if (infile.key == "left") keybind_num = LEFT;
	// @ATTR right|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Right" keybind relative to the keybinding scrollbox.
	else if (infile.key == "right") keybind_num = RIGHT;
	// @ATTR bar1|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar1" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar1") keybind_num = BAR_1;
	// @ATTR bar2|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar2" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar2") keybind_num = BAR_2;
	// @ATTR bar3|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar3" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar3") keybind_num = BAR_3;
	// @ATTR bar4|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar4" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar4") keybind_num = BAR_4;
	// @ATTR bar5|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar5" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar5") keybind_num = BAR_5;
	// @ATTR bar6|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar6" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar6") keybind_num = BAR_6;
	// @ATTR bar7|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar7" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar7") keybind_num = BAR_7;
	// @ATTR Bar8|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar8" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar8") keybind_num = BAR_8;
	// @ATTR bar9|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar9" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar9") keybind_num = BAR_9;
	// @ATTR bar0|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Bar0" keybind relative to the keybinding scrollbox.
	else if (infile.key == "bar0") keybind_num = BAR_0;
	// @ATTR main1|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Main1" keybind relative to the keybinding scrollbox.
	else if (infile.key == "main1") keybind_num = MAIN1;
	// @ATTR main2|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Main2" keybind relative to the keybinding scrollbox.
	else if (infile.key == "main2") keybind_num = MAIN2;
	// @ATTR character|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Character" keybind relative to the keybinding scrollbox.
	else if (infile.key == "character") keybind_num = CHARACTER;
	// @ATTR inventory|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Inventory" keybind relative to the keybinding scrollbox.
	else if (infile.key == "inventory") keybind_num = INVENTORY;
	// @ATTR powers|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Powers" keybind relative to the keybinding scrollbox.
	else if (infile.key == "powers") keybind_num = POWERS;
	// @ATTR log|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Log" keybind relative to the keybinding scrollbox.
	else if (infile.key == "log") keybind_num = LOG;
	// @ATTR ctrl|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Ctrl" keybind relative to the keybinding scrollbox.
	else if (infile.key == "ctrl") keybind_num = CTRL;
	// @ATTR shift|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Shift" keybind relative to the keybinding scrollbox.
	else if (infile.key == "shift") keybind_num = SHIFT;
	// @ATTR alt|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Alt" keybind relative to the keybinding scrollbox.
	else if (infile.key == "alt") keybind_num = ALT;
	// @ATTR delete|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Delete" keybind relative to the keybinding scrollbox.
	else if (infile.key == "delete") keybind_num = DEL;
	// @ATTR actionbar|label x (integer), label y (integer), x (integer), y (integer)|Position of the "ActionBar Accept" keybind relative to the keybinding scrollbox.
	else if (infile.key == "actionbar") keybind_num = ACTIONBAR;
	// @ATTR actionbar_back|label x (integer), label y (integer), x (integer), y (integer)|Position of the "ActionBar Left" keybind relative to the keybinding scrollbox.
	else if (infile.key == "actionbar_back") keybind_num = ACTIONBAR_BACK;
	// @ATTR actionbar_forward|label x (integer), label y (integer), x (integer), y (integer)|Position of the "ActionBar Right" keybind relative to the keybinding scrollbox.
	else if (infile.key == "actionbar_forward") keybind_num = ACTIONBAR_FORWARD;
	// @ATTR actionbar_use|label x (integer), label y (integer), x (integer), y (integer)|Position of the "ActionBar Use" keybind relative to the keybinding scrollbox.
	else if (infile.key == "actionbar_use") keybind_num = ACTIONBAR_USE;
	// @ATTR developer_menu|label x (integer), label y (integer), x (integer), y (integer)|Position of the "Developer Menu" keybind relative to the keybinding scrollbox.
	else if (infile.key == "developer_menu") keybind_num = DEVELOPER_MENU;

	else return false;

	if (keybind_num > -1 && (unsigned)keybind_num < keybinds_lb.size() && (unsigned)keybind_num < keybinds_btn.size()) {
		//keybindings
		keybinds_lb[keybind_num]->setX(x1);
		keybinds_lb[keybind_num]->setY(y1);
		keybinds_btn[keybind_num]->pos.x = x2;
		keybinds_btn[keybind_num]->pos.y = y2;
	}

	return true;
}
Exemplo n.º 29
0
static u32 sal_Input(int held)
{
#if 1
    SDL_Event event;
    int i=0;
    u32 timer=0;
#ifdef GCW_JOYSTICK
    int    deadzone = 10000;
    Sint32 x_move   = 0;
    Sint32 y_move   = 0;

#endif

    if (!SDL_PollEvent(&event))
    {
        if (held)
            return inputHeld;
        return 0;
    }

    Uint8 type = (event.key.state == SDL_PRESSED);
    switch(event.key.keysym.sym)
    {
        CASE( LCTRL,     A      );
        CASE( LALT,      B      );
        CASE( SPACE,     X      );//this triggers for some reason on the gcw0 when analogue joystick is on and in a diagonal position if sdl_updatejoystick is called before this point.
        CASE( LSHIFT,    Y      );
        CASE( TAB,       L      );
        CASE( BACKSPACE, R      );
        CASE( RETURN,    START  );
        CASE( ESCAPE,    SELECT );
        CASE( UP,        UP     );
        CASE( DOWN,      DOWN   );
        CASE( LEFT,      LEFT   );
        CASE( RIGHT,     RIGHT  );
        CASE( HOME,      MENU   );
    default:
        break;
    }
#ifdef GCW_JOYSTICK
    if(analogJoy && !key_repeat_enabled)
    {
        static int j_left = 0;
        static int j_right = 0;
        static int j_up = 0;
        static int j_down = 0;

        //Update joystick position
        if (SDL_NumJoysticks() > 0)
        {
            SDL_Joystick *joy;
            joy    = SDL_JoystickOpen(0);
            SDL_JoystickUpdate();
            x_move = SDL_JoystickGetAxis(joy, 0);
            y_move = SDL_JoystickGetAxis(joy, 1);
        }

        //Emulate keypresses with joystick
        if (x_move < -deadzone || x_move > deadzone)
        {
            if (x_move < -deadzone) inputHeld |= SAL_INPUT_LEFT;
            if (x_move >  deadzone) inputHeld |= SAL_INPUT_RIGHT;
            if (x_move < -deadzone) j_left     = 1;
            if (x_move >  deadzone) j_right    = 1;
        } else
        {
            //stop movement if previously triggered by analogue stick
            if (j_left)
            {
                j_left = 0;
                inputHeld &= ~(SAL_INPUT_LEFT );
            }
            if (j_right)
            {
                j_right = 0;
                inputHeld &= ~(SAL_INPUT_RIGHT );
            }
        }

        if (y_move < -deadzone || y_move > deadzone)
        {
            if (y_move < -deadzone) inputHeld |= SAL_INPUT_UP;
            if (y_move >  deadzone) inputHeld |= SAL_INPUT_DOWN;
            if (y_move < -deadzone) j_up       = 1;
            if (y_move >  deadzone) j_down     = 1;
        } else
        {
            //stop movement if previously triggered by analogue stick
            if (j_up)
            {
                j_up = 0;
                inputHeld &= ~(SAL_INPUT_UP );
            }
            if (j_down)
            {
                j_down = 0;
                inputHeld &= ~(SAL_INPUT_DOWN );
            }
        }
    }
#endif

    mInputRepeat = inputHeld;

#else
    int i=0;
    u32 inputHeld=0;
    u32 timer=0;
    u8 *keystate;

    SDL_PumpEvents();

    keystate = SDL_GetKeyState(NULL);

    if ( keystate[SDLK_LCTRL] ) inputHeld|=SAL_INPUT_A;
    if ( keystate[SDLK_LALT] ) inputHeld|=SAL_INPUT_B;
    if ( keystate[SDLK_SPACE] ) inputHeld|=SAL_INPUT_X;
    if ( keystate[SDLK_LSHIFT] ) inputHeld|=SAL_INPUT_Y;
    if ( keystate[SDLK_TAB] ) inputHeld|=SAL_INPUT_L;
    if ( keystate[SDLK_BACKSPACE] ) inputHeld|=SAL_INPUT_R;
    if ( keystate[SDLK_RETURN] ) inputHeld|=SAL_INPUT_START;
    if ( keystate[SDLK_ESCAPE] ) inputHeld|=SAL_INPUT_SELECT;
    if ( keystate[SDLK_UP] ) inputHeld|=SAL_INPUT_UP;
    if ( keystate[SDLK_DOWN] ) inputHeld|=SAL_INPUT_DOWN;
    if ( keystate[SDLK_LEFT] ) inputHeld|=SAL_INPUT_LEFT;
    if ( keystate[SDLK_RIGHT] ) inputHeld|=SAL_INPUT_RIGHT;

    // Process key repeats
    timer=sal_TimerRead();
    for (i=0; i<32; i++)
    {
        if (inputHeld&(1<<i))
        {
            if(mInputFirst&(1<<i))
            {
                if (mInputRepeatTimer[i]<timer)
                {
                    mInputRepeat|=1<<i;
                    mInputRepeatTimer[i]=timer+10;
                }
                else
                {
                    mInputRepeat&=~(1<<i);
                }
            }
            else
            {
                //First press of button
                //set timer to expire later than usual
                mInputFirst|=(1<<i);
                mInputRepeat|=1<<i;
                mInputRepeatTimer[i]=timer+50;
            }
        }
        else
        {
            mInputRepeatTimer[i]=timer-10;
            mInputRepeat&=~(1<<i);
            mInputFirst&=~(1<<i);
        }

    }

    if(mInputIgnore)
    {
        //A request to ignore all key presses until all keys have been released has been made
        //check for release and clear flag, otherwise clear inputHeld and mInputRepeat
        if (inputHeld == 0)
        {
            mInputIgnore=0;
        }
        inputHeld=0;
        mInputRepeat=0;
    }
#endif

    return inputHeld;
}
Exemplo n.º 30
0
void GameInfo::update() {

	if (InputControl::Instance()->joysticks.size() > 0 && SDL_NumJoysticks() > 0) {
		//AL MENOS 1 JOYS CONECTADO
		if (InputControl::Instance()->joysticks[0] != NULL){
			if (InputControl::Instance()->getActionButtonState(0, RESET_PRACTICE) && MKGame::Instance()->practiceMode) {
				this->prepareNewRound();
			}
		}
		if (InputControl::Instance()->joysticks[1] != NULL){
			if (InputControl::Instance()->getActionButtonState(1, RESET_PRACTICE) && MKGame::Instance()->practiceMode) {
				this->prepareNewRound();
			}
		}
	}

	animation();
	loadTextTimer();
	// CONDICION DE FIN DE ROUND, SI CUALQUIERA DE LOS DOS SE QUEDA SIN VIDA O SI SE ACABA EL TIEMPO
	if ( (this->characters[0]->getEnergy() <= 0.0f || this->characters[1]->getEnergy() <= 0.0f ||
			this->timer.getTicks() > 99000.f) && !MKGame::Instance()->practiceMode ) {
		// TERMINO EL ROUND, NINGUNO DEBE MOVERSE MAS, SETEO ALLOW MOVEMENTS EN FALSE
		//MKGame::Instance()->setAllowPlayerMovements(false);
		this->characters[0]->allowMovements = false;
		this->characters[1]->allowMovements = false;

		// SI EL QUE MURIO O TIENE MENOS VIDA ES EL PLAYER ONE
		if (this->characters[0]->getEnergy() <= 0.0f ||
				this->characters[0]->getEnergy() <= this->characters[1]->getEnergy() ) {
			// PREGUNTO SI NO ESTA YA SETEADO EL FLAG DE QUE MURIO EL PLAYER ONE
			if (!this->charOneAlreadyDeath) {
				// SUMO VICTORIA A PLAYER 2 Y SETEO FLAGS DE QUE GANO Y SHOW WINNER ANIMATION
				this->characterTwoWins += 1;
				this->charTwoWon = true;
				this->showWinnerAnimation = true;
			}
			this->charOneAlreadyDeath = true;
			// PREGUNTO POR CONDICION DE QUE NO SEA FIN DE PELEA (NO TENGA DOS VICTORIAS)
			if (characterTwoWins < 2){
				if (this->characters[1]->getMovement() == STANCE) {
					this->characters[1]->setMovement(VICTORY_MOVEMENT);
					this->characters[1]->setCurrentSprite();
				}
				if (this->characters[0]->isTouchingGround(this->characters[0]->getPositionY())) {
					this->characters[0]->setMovement(FALLING_MOVEMENT);
					this->characters[0]->setCurrentSprite();
					this->characters[0]->isFalling = true;
				}
			}
			FILE_LOG(logDEBUG) <<"############ RESULT: " << this->characters[1]->getName() << "Wins #############";
			// REPRODUCE SONIDO DEL PLAYER 2 WINS
			if (!this->playingCharacterWinsSound && this->characterTwoWins < 2) {
				SoundManager::Instance()->playSoundByAction(characters[1]->getName() + "Wins",0);
				this->playingCharacterWinsSound = true;
			}

		// MISMA LOGICA QUE ARRIBA PARA EL CASO EN QUE MUERE EL PLAYER TWO
		} else {
			if (!this->charTwoAlreadyDeath) {
				this->characterOneWins += 1;
				this->charOneWon = true;
				this->showWinnerAnimation = true;
			}
			this->charTwoAlreadyDeath = true;
			if (characterOneWins < 2) {
				if (this->characters[0]->getMovement() == STANCE) {
					this->characters[0]->setMovement(VICTORY_MOVEMENT);
					this->characters[0]->setCurrentSprite();
				}
				if (this->characters[1]->isTouchingGround(this->characters[1]->getPositionY())){
					this->characters[1]->setMovement(FALLING_MOVEMENT);
					this->characters[1]->setCurrentSprite();
					this->characters[1]->isFalling = true;
				}
			}
			FILE_LOG(logDEBUG) << "############ RESULT: " << this->characters[0]->getName() << " Wins #############";
			if (!this->playingCharacterWinsSound && this->characterOneWins < 2) {
				SoundManager::Instance()->playSoundByAction(characters[0]->getName() + "Wins",0);
				this->playingCharacterWinsSound = true;
			}
		}
		loadTextTimer();

		// PARA EL CASO EN QUE ALGUNO DE LOS DOS HAYA GANADO DOS PELEAS SE ACTIVA LOGICA DE FINISH HIM
		if (this->characterOneWins == 2 || this->characterTwoWins == 2) {
			this->showWinnerAnimation = false;
			this->timerPause();
			CollitionManager::Instance()->collitionEnabled = false;
			this->showFinishHimAnimation = true;
			MKGame::Instance()->isFinishimMoment = true;
			//MKGame::Instance()->setAllowPlayerMovements(true);
			this->characters[0]->allowMovements = true;
			this->characters[1]->allowMovements = true;

			//LOGICA TIMER DE FINISH HIM TIME
			if (this->isFinishHimTime) {
				if (this->finishHimToleranceTimer > 0) {
					this->finishHimToleranceTimer -= 1;
				} else {
					if (this->characterOneWins == 2) {
						this->showWinnerAnimation = true;
						this->charOneWon = true;
						this->characters[0]->allowMovements = false;
						this->characters[0]->setMovement(VICTORY_MOVEMENT);
						this->characters[0]->setCurrentSprite();
						this->characters[0]->isVictory = true;
						this->characters[0]->setPositionY(this->characters[0]->originalPosY);
						this->characters[1]->setMovement(FALLING_MOVEMENT);
						this->characters[1]->setCurrentSprite();
						this->characters[1]->isFalling = true;
						if (!this->playingCharacterWinsSound) {
							SoundManager::Instance()->playSoundByAction(characters[0]->getName() + "Wins",0);
							this->playingCharacterWinsSound = true;
						}
						if (this->winnerAnimationTimer > 0) {
							if (this->showWinnerAnimation) {
								this->timerPause();
								this->winnerAnimationTimer -= 1;
							}
						} else {
							this->showWinnerAnimation = false;
							MKGame::Instance()->setOnReset();
						}
					} else {
						this->showWinnerAnimation = true;
						this->charTwoWon = true;
						this->characters[1]->allowMovements = false;
						this->characters[1]->setMovement(VICTORY_MOVEMENT);
						this->characters[1]->setCurrentSprite();
						this->characters[1]->isVictory = true;
						this->characters[1]->setPositionY(this->characters[1]->originalPosY);
						this->characters[0]->setMovement(FALLING_MOVEMENT);
						this->characters[0]->setCurrentSprite();
						this->characters[0]->isFalling = true;
						if (!this->playingCharacterWinsSound) {
							SoundManager::Instance()->playSoundByAction(characters[1]->getName() + "Wins",0);
							this->playingCharacterWinsSound = true;
						}
						if (this->winnerAnimationTimer > 0) {
							if (this->showWinnerAnimation) {
								this->timerPause();
								this->winnerAnimationTimer -= 1;
							}
						} else {
							this->showWinnerAnimation = false;
							MKGame::Instance()->setOnReset();
						}
					}
				}
			}

			//LOGICA PARA TERMINAR PELEA CON GOLPE ORDINARIO DE CHAR 1
			if (this->characters[0]->isFalling){
				this->isFinishHimTime = false;
				this->showWinnerAnimation = true;
				this->charTwoWon = true;
				this->characters[1]->allowMovements = false;
				if (!this->playingCharacterWinsSound) {
					SoundManager::Instance()->playSoundByAction(characters[1]->getName() + "Wins",0);
					this->playingCharacterWinsSound = true;
				}
				if (this->winnerAnimationTimer > 0) {
					if (this->showWinnerAnimation) {
						this->timerPause();
						this->winnerAnimationTimer -= 1;
					}
				} else {
					this->showWinnerAnimation = false;
					MKGame::Instance()->setOnReset();
				}
			}

			//LOGICA PARA TERMINAR PELEA CON GOLPE ORDINARIO DE CHAR 0
			if (this->characters[1]->isFalling){
				this->isFinishHimTime = false;
				this->showWinnerAnimation = true;
				this->charOneWon = true;
				this->characters[0]->allowMovements = false;
				if (!this->playingCharacterWinsSound) {
					SoundManager::Instance()->playSoundByAction(characters[0]->getName() + "Wins",0);
					this->playingCharacterWinsSound = true;
				}
				if (this->winnerAnimationTimer > 0) {
					if (this->showWinnerAnimation) {
						this->timerPause();
						this->winnerAnimationTimer -= 1;
					}
				} else {
					this->showWinnerAnimation = false;
					MKGame::Instance()->setOnReset();
				}
			}


			if (this->finishHimAnimationTimer > 0) {
				this->finishHimAnimationTimer -= 1;
				//no se pueden mover durante el cartel finishim
				this->characters[0]->allowMovements = false;
				this->characters[1]->allowMovements = false;
			} else {
				this->showFinishHimAnimation = false;
				CollitionManager::Instance()->collitionEnabled = true;
				SecuenceInputManager::Instance()->fatalityTime = true;
				this->isFinishHimTime = true;
				//this->showFatalityAnimation = true;
			}
			if (MKGame::Instance()->showFatality && this->fatalityAnimationTimer > 0) {
				this->isFinishHimTime = false;
				this->showFatalityAnimation = true;
				this->fatalityAnimationTimer -= 1;
			} else if (fatalityAnimationTimer == 0){
				this->showFatalityAnimation = false;
				MKGame::Instance()->setOnReset();
			}

			if (MKGame::Instance()->showBabality && this->babalityAnimationTimer > 0) {
				this->isFinishHimTime = false;
				this->showBabalityAnimation = true;
				this->babalityAnimationTimer -= 1;
			} else if (babalityAnimationTimer == 0){
				this->showBabalityAnimation = false;
				MKGame::Instance()->setOnReset();
			}

			if (MKGame::Instance()->showFriendship && this->friendshipAnimationTimer > 0) {
				this->isFinishHimTime = false;
				this->showFriendshipAnimation = true;
				this->friendshipAnimationTimer -= 1;
			} else if (friendshipAnimationTimer == 0){
				this->showFriendshipAnimation = false;
				MKGame::Instance()->setOnReset();
			}

			//finish him logic
			if (!this->playingFinishHimSound) {
				SoundManager::Instance()->playSoundByAction("finishHim",0);
				this->playingFinishHimSound  = true;
			}
			if (this->characterOneWins == 2 && !this->lazyAnimationAlreadyTriggered) {
				//Character One won, char two receives fatality
				this->characters[1]->completeMovementAndChangeLazy = true;
				this->characters[0]->clearMovementsFlags();
//				this->characters[1]->setMovement(LAZY_MOVEMENT);
//				this->characters[1]->isLazy = true;
//				this->characters[1]->setCurrentSprite();
//				this->characters[1]->completeMovement();
				this->characters[1]->setPositionY(this->characters[1]->originalPosY);
				this->characters[1]->allowMovements = false;
				this->lazyAnimationAlreadyTriggered = true;
				MKGame::Instance()->lazyAnimationAlreadyTriggered = true;
			}
			if (this->characterTwoWins == 2 && !this->lazyAnimationAlreadyTriggered) {
				//Character One won, char two receives fatality
				this->characters[0]->completeMovementAndChangeLazy = true;
				this->characters[1]->clearMovementsFlags();
//				this->characters[0]->setMovement(LAZY_MOVEMENT);
//				this->characters[0]->isLazy = true;
//				this->characters[0]->setCurrentSprite();
//				this->characters[0]->completeMovement();
				this->characters[0]->setPositionY(this->characters[0]->originalPosY);
				this->characters[0]->allowMovements = false;
				this->lazyAnimationAlreadyTriggered = true;
				MKGame::Instance()->lazyAnimationAlreadyTriggered = true;
			}

		} else {
			//MKGame::Instance()->setOnReset();

			if (this->winnerAnimationTimer > 0) {
				if (this->showWinnerAnimation) {
					this->timerPause();
					this->winnerAnimationTimer -= 1;
				}
			} else {
				this->showWinnerAnimation = false;
			}
			if (!this->roundOneCompleted && !this->showWinnerAnimation) {
				this->roundOneCompleted = true;
				this->prepareNewRound();
			} else if (!this->roundTwoCompleted && !this->showWinnerAnimation) {
				this->roundTwoCompleted = true;
				this->prepareNewRound();
			} else if (!this->roundThreeCompleted && !this->showWinnerAnimation) {
				//MKGame::Instance()->setOnReset();
			}
		}
	}
	if (!MKGame::Instance()->practiceMode) {
		triggerSounds();
	}
}