示例#1
0
int detect_joypad(int numJoy)
{
	SDL_Event event;
	Uint32 startTime = 0;
	const int detectionTime = 4000;
	
	SDL_Joystick **checkJoystick = NULL;
	int i = 0;
	int chosen = -1;

	if(numJoy <= 0) return chosen;

	checkJoystick = (SDL_Joystick **)malloc(sizeof(SDL_Joystick *) * numJoy);

	for(i = 0; i < numJoy; i++)
	{
		*(checkJoystick + i) = SDL_JoystickOpen(i);
		SDL_JoystickEventState(SDL_ENABLE);

		if (checkJoystick) {
			printf("Opened Joystick %d\n", i);
			printf("Name: %s\n", SDL_JoystickNameForIndex(i));
			printf("Number of Axes: %d\n", SDL_JoystickNumAxes(*(checkJoystick + i)));
			printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(*(checkJoystick + i)));
			printf("Number of Balls: %d\n", SDL_JoystickNumBalls(*(checkJoystick + i)));

		} else {
			printf("Couldn't open Joystick %d\n", i);
		}

		if(!SDL_strcmp(SDL_JoystickNameForIndex(i), settings.joystickName))
		{
			return i;
		}
	}

	SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, 
                         "Joystick detection",
                         "Multiple joysticks detected. Please press a button from the joystick you wish to use. (within the next 4 seconds after pressing OK)",
                         NULL);

	startTime = SDL_GetTicks();

	while(((SDL_GetTicks() - startTime) < detectionTime) && chosen == -1)
	{
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
				case SDL_JOYBUTTONDOWN:
				case SDL_JOYBUTTONUP:

				chosen = event.jbutton.which;

				break;

				default:
				break;
			}
		}
	}

	for(i = 0; i < numJoy; i++)
	{
		SDL_JoystickClose(*(checkJoystick + i));
	}

	return chosen;
}
示例#2
0
/**
 * Initialises OpenJazz.
 *
 * Establishes the paths from which to read files, loads configuration, sets up
 * the game window and loads required data.
 *
 * @param argc Number of arguments, as passed to main function
 * @param argv Array of argument strings, as passed to main function
 */
void startUp (int argc, char *argv[]) {

	File* file;
	unsigned char* pixels = NULL;
	int count;
	int screenW = DEFAULT_SCREEN_WIDTH;
	int screenH = DEFAULT_SCREEN_HEIGHT;
	int scaleFactor = 1;
#ifdef FULLSCREEN_ONLY
	bool fullscreen = true;
#else
	bool fullscreen = false;
#endif


	// Determine paths

	// Use hard-coded paths, if available

#ifdef DATAPATH
	firstPath = new Path(NULL, createString(DATAPATH));
#else
	firstPath = NULL;
#endif

#ifdef __HAIKU__
	dev_t volume = dev_for_path("/boot");
	char buffer[10 + B_PATH_NAME_LENGTH + B_FILE_NAME_LENGTH];
	status_t result;

	result = find_directory(B_SYSTEM_DATA_DIRECTORY,
		volume, false, buffer, sizeof(buffer));
	strncat(buffer, "/openjazz/", sizeof(buffer));
	firstPath = new Path(firstPath, createString(buffer));

	result = find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY,
		volume, false, buffer, sizeof(buffer));
	strncat(buffer, "/openjazz/", sizeof(buffer));
	firstPath = new Path(firstPath, createString(buffer));
#endif

#ifdef __SYMBIAN32__
	#ifdef UIQ3
	firstPath = new Path(firstPath, createString("c:\\shared\\openjazz\\"));
	#else
	firstPath = new Path(firstPath, createString("c:\\data\\openjazz\\"));
	#endif
	firstPath = new Path(firstPath, createString(KOpenJazzPath));
#endif


	// Use any provided paths, appending a directory separator as necessary

	for (count = 1; count < argc; count++) {

		// If it isn't an option, it should be a path
		if (argv[count][0] != '-') {

#ifdef _WIN32
			if (argv[count][strlen(argv[count]) - 1] != '\\') {

				firstPath = new Path(firstPath, createString(argv[count], "\\"));
#else
			if (argv[count][strlen(argv[count]) - 1] != '/') {

				firstPath = new Path(firstPath, createString(argv[count], "/"));
#endif

			} else {

				firstPath = new Path(firstPath, createString(argv[count]));

			}

		}

	}

	// Use the path of the program, but not on Wii as this does crash in
	// dolphin emulator. Also is not needed, because CWD is used there

#ifndef WII
	count = strlen(argv[0]) - 1;

	// Search for directory separator
#ifdef _WIN32
	while ((argv[0][count] != '\\') && (count >= 0)) count--;
#else
	while ((argv[0][count] != '/') && (count >= 0)) count--;
#endif

	// If a directory was found, copy it to the path
	if (count > 0) {

		firstPath = new Path(firstPath, new char[count + 2]);
		memcpy(firstPath->path, argv[0], count + 1);
		firstPath->path[count + 1] = 0;

	}
#endif


	// Use the user's home directory, if available

#ifdef HOMEDIR
	#ifdef _WIN32
	firstPath = new Path(firstPath, createString(getenv("HOME"), "\\"));
	#else
	firstPath = new Path(firstPath, createString(getenv("HOME"), "/."));
	#endif
#endif


	// Use the current working directory

	firstPath = new Path(firstPath, createString(""));



	// Default settings

	// Sound settings
#if defined(WIZ) || defined(GP2X)
	volume = 40;
#endif

	// Create the network address
	netAddress = createString(NET_ADDRESS);


	// Load settings from config file
	setup.load(&screenW, &screenH, &fullscreen, &scaleFactor);


	// Get command-line override
	for (count = 1; count < argc; count++) {

		// If there's a hyphen, it should be an option
		if (argv[count][0] == '-') {

#ifndef FULLSCREEN_ONLY
			if (argv[count][1] == 'f') fullscreen = true;
#endif
			if (argv[count][1] == 'm') {
				setMusicVolume(0);
				setSoundVolume(0);
			}

		}

	}


	// Create the game's window

	canvas = NULL;

	if (!video.init(screenW, screenH, fullscreen)) {

		delete firstPath;

		throw E_VIDEO;

	}

#ifdef SCALE
	video.setScaleFactor(scaleFactor);
#endif


	if (SDL_NumJoysticks() > 0) SDL_JoystickOpen(0);


	// Set up audio
	openAudio();



	// Load fonts

	// Open the panel, which contains two fonts

	try {

		file = new File("PANEL.000", false);

	} catch (int e) {

		closeAudio();

		delete firstPath;

		log("Unable to find game data files. When launching OpenJazz, pass the location");
		log("of the original game data, eg:");
		log("  OpenJazz ~/jazz1");

#ifdef __HAIKU__
		char alertBuffer[100+B_PATH_NAME_LENGTH+B_FILE_NAME_LENGTH];
		strcpy(alertBuffer, "Unable to find game data files!\n"
			"Put the data into the folder:\n");
		strncat(alertBuffer, buffer, sizeof(alertBuffer));
		BAlert* alert = new BAlert("OpenJazz", alertBuffer, "Exit", NULL, NULL,
			B_WIDTH_AS_USUAL, B_STOP_ALERT);
		alert->Go();
#endif

		throw e;

	}

	pixels = file->loadRLE(46272);

	delete file;

	panelBigFont = NULL;
	panelSmallFont = NULL;
	font2 = NULL;
	fontbig = NULL;
	fontiny = NULL;
	fontmn1 = NULL;

	try {

		panelBigFont = new Font(pixels + (40 * 320), true);
		panelSmallFont = new Font(pixels + (48 * 320), false);
		font2 = new Font("FONT2.0FN");
		fontbig = new Font("FONTBIG.0FN");
		fontiny = new Font("FONTINY.0FN");
		fontmn1 = new Font("FONTMN1.0FN");
		fontmn2 = new Font("FONTMN2.0FN");

	} catch (int e) {

		if (panelBigFont) delete panelBigFont;
		if (panelSmallFont) delete panelSmallFont;
		if (font2) delete font2;
		if (fontbig) delete fontbig;
		if (fontiny) delete fontiny;
		if (fontmn1) delete fontmn1;

		delete[] pixels;

		closeAudio();

		delete firstPath;

		throw e;

	}

	delete[] pixels;


	// Establish arbitrary timing
	globalTicks = SDL_GetTicks() - 20;


	// Fill trigonometric function look-up tables
	for (count = 0; count < 1024; count++)
		sinLut[count] = fixed(sinf(2 * PI * float(count) / 1024.0f) * 1024.0f);


	// Initiate networking
	net = new Network();


	level = NULL;
	jj2Level = NULL;

}


/**
 * De-initialises OpenJazz.
 *
 * Frees data, writes configuration, and shuts down SDL.
 */
void shutDown () {

	delete net;

	delete panelBigFont;
	delete panelSmallFont;
	delete font2;
	delete fontbig;
	delete fontiny;
	delete fontmn1;
	delete fontmn2;

#ifdef SCALE
	if (video.getScaleFactor() > 1) SDL_FreeSurface(canvas);
#endif

	closeAudio();


	// Save settings to config file
	setup.save();


	delete firstPath;

}
示例#3
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 );

	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" );

	SDL_JoystickEventState(SDL_QUERY);
}
示例#4
0
string SDLInit(const char *title, const int2 &desired_screensize, bool isfullscreen, int vsync)
{
    //SDL_SetMainReady();
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER /* | SDL_INIT_AUDIO*/) < 0)
    {
        return SDLError("Unable to initialize SDL");
    }

    SDL_SetEventFilter(SDLHandleAppEvents, nullptr);

    Output(OUTPUT_INFO, "SDL initialized...");

    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);

    // on demand now
    //extern bool sfxr_init();
    //if (!sfxr_init())
    //   return SDLError("Unable to initialize audio");

    #ifdef PLATFORM_ES2
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    #else
        //certain older Intel HD GPUs and also Nvidia Quadro 1000M don't support 3.1 ? the 1000M is supposed to support 4.2
        //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
        //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
        #ifdef __APPLE__
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
        #elif defined(_WIN32)
            //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
            //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
            //SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
        #endif
        #if defined(__APPLE__) || defined(_WIN32)
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
        #endif
    #endif

    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);      // set this if we're in 2D mode for speed on mobile?
    SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);    // because we redraw the screen each frame

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    Output(OUTPUT_INFO, "SDL about to figure out display mode...");

    #ifdef PLATFORM_ES2
        landscape = desired_screensize.x() >= desired_screensize.y();
        int modes = SDL_GetNumDisplayModes(0);
        screensize = int2(1280, 720);
        for (int i = 0; i < modes; i++)
        {
            SDL_DisplayMode mode;
            SDL_GetDisplayMode(0, i, &mode);
            Output(OUTPUT_INFO, "mode: %d %d", mode.w, mode.h);
            if (landscape ? mode.w > screensize.x() : mode.h > screensize.y())
            {
                screensize = int2(mode.w, mode.h);
            }
        }

        Output(OUTPUT_INFO, "chosen resolution: %d %d", screensize.x(), screensize.y());
        Output(OUTPUT_INFO, "SDL about to create window...");

        _sdl_window = SDL_CreateWindow(title,
                                        0, 0,
                                        screensize.x(), screensize.y(),
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS);

        Output(OUTPUT_INFO, _sdl_window ? "SDL window passed..." : "SDL window FAILED...");

        if (landscape) SDL_SetHint("SDL_HINT_ORIENTATIONS", "LandscapeLeft LandscapeRight");

        int ax = 0, ay = 0;
        SDL_GetWindowSize(_sdl_window, &ax, &ay);
        int2 actualscreensize(ax, ay);
        //screenscalefactor = screensize.x / actualscreensize.x;  // should be 2 on retina
        #ifdef __IOS__
            assert(actualscreensize == screensize);
            screensize = actualscreensize;
        #else
            screensize = actualscreensize;  // __ANDROID__
            Output(OUTPUT_INFO, "obtained resolution: %d %d", screensize.x(), screensize.y());
        #endif
    #else
        screensize = desired_screensize;
        _sdl_window = SDL_CreateWindow(title,
                                        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                        screensize.x(), screensize.y(),
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE |
                                            (isfullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));
    #endif

    if (!_sdl_window)
        return SDLError("Unable to create window");

    Output(OUTPUT_INFO, "SDL window opened...");


    _sdl_context = SDL_GL_CreateContext(_sdl_window);
    Output(OUTPUT_INFO, _sdl_context ? "SDL context passed..." : "SDL context FAILED...");
    if (!_sdl_context) return SDLError("Unable to create OpenGL context");

    Output(OUTPUT_INFO, "SDL OpenGL context created...");

    /*
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
    */

    #ifndef __IOS__
        SDL_GL_SetSwapInterval(vsync);
    #endif

    SDL_JoystickEventState(SDL_ENABLE);
    SDL_JoystickUpdate();
    for(int i = 0; i < SDL_NumJoysticks(); i++)
    {
        SDL_Joystick *joy = SDL_JoystickOpen(i);
        if (joy)
        {
            Output(OUTPUT_INFO, "Detected joystick: %s (%d axes, %d buttons, %d balls, %d hats)",
                                SDL_JoystickName(joy), SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy),
                                SDL_JoystickNumBalls(joy), SDL_JoystickNumHats(joy));
        };
    };

    timestart = SDL_GetPerformanceCounter();
    timefreq = SDL_GetPerformanceFrequency();

    lasttime = -0.02f;    // ensure first frame doesn't get a crazy delta

    return "";
}
示例#5
0
文件: gamepad.c 项目: bart9h/meritous
void HandleGamepad (int key_held[])
{
	static char state = '0';
#define MAX 32
	static int axes[MAX];
	static int buttons[MAX];
	static int num_axes;
	static int num_buttons;
	static SDL_Joystick* joy;

	if (state == '0') {
		state = '?';
		memset (joy_held, 0, sizeof(joy_held));

		if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
			fprintf (stderr, "SDL_init(): %s\n", SDL_GetError());
			return;
		}

		// select joystick
		int num_joysticks = SDL_NumJoysticks();
		int i;
		for (i = 0; i < num_joysticks; i++)
			printf ("joystick %d = \"%s\"\n", i, SDL_JoystickName (i));

		if (num_joysticks != 1) {
			printf ("error: %d joysticks detected\n", num_joysticks);
			return;
		}
		int joystick_index = 0;

		joy = SDL_JoystickOpen (joystick_index);
		if (joy == NULL) {
			fprintf (stderr, "SDL_JoystickOpen(): %s\n", SDL_GetError());
			return;
		}

		printf ("Number of Axes: %d\n", num_axes = SDL_JoystickNumAxes(joy));
		printf ("Number of Buttons: %d\n", num_buttons = SDL_JoystickNumButtons(joy));
		printf ("Number of Balls: %d\n", SDL_JoystickNumBalls(joy));
		printf ("Number of Hats: %d\n", SDL_JoystickNumHats(joy));

		state = '1';
	}
	else if (state == '1') {

		SDL_JoystickUpdate();

		int i;
		for (i = 0;  i < num_axes && i < MAX;  ++i)
			axes[i] = SDL_JoystickGetAxis (joy, i);

		for (i = 0;  i < num_buttons && i < MAX;  ++i)
			buttons[i] = SDL_JoystickGetButton (joy, i);

		hold (key_held, K_UP, axes[1] < -1000 || axes[3] < -1000 || buttons[4]);
		hold (key_held, K_RT, axes[0] >  1000 || axes[2] >  1000 || buttons[5]);
		hold (key_held, K_DN, axes[1] >  1000 || axes[3] >  1000 || buttons[6]);
		hold (key_held, K_LT, axes[0] < -1000 || axes[2] < -1000 || buttons[7]);
		hold (key_held, K_SP, buttons[14]);
	}
}
示例#6
0
文件: sdlgui.c 项目: r-type/hatari
/**
 * Show and process a dialog. Returns either:
 * - index of the GUI item that was invoked
 * - SDLGUI_UNKNOWNEVENT if an unsupported event occurred
 *   (will be stored in parameter pEventOut)
 * - SDLGUI_QUIT if user wants to close Hatari
 * - SDLGUI_ERROR if unable to show dialog
 * GUI item indeces are positive, other return values are negative
 */
int SDLGui_DoDialog(SGOBJ *dlg, SDL_Event *pEventOut, bool KeepCurrentObject)
{
	int oldbutton = SDLGUI_NOTFOUND;
	int retbutton = SDLGUI_NOTFOUND;
	int i, j, b, value, obj;
	SDLKey key;
	int focused;
	SDL_Event sdlEvent;
	SDL_Surface *pBgSurface;
	SDL_Rect dlgrect, bgrect;
	SDL_Joystick *joy = NULL;
#if !WITH_SDL2
	int nOldUnicodeMode;
#endif

	/* In the case of dialog using a scrollbar, we must keep the previous */
	/* value of current_object, as the same dialog is displayed in a loop */
	/* to handle scrolling. For other dialogs, we need to reset current_object */
	/* (ie no object selected at start when displaying the dialog) */
	if ( !KeepCurrentObject )
		current_object = 0;

	if (pSdlGuiScrn->h / sdlgui_fontheight < dlg[0].h)
	{
		fprintf(stderr, "Screen size too small for dialog!\n");
		return SDLGUI_ERROR;
	}

	dlgrect.x = dlg[0].x * sdlgui_fontwidth;
	dlgrect.y = dlg[0].y * sdlgui_fontheight;
	dlgrect.w = dlg[0].w * sdlgui_fontwidth;
	dlgrect.h = dlg[0].h * sdlgui_fontheight;

	bgrect.x = bgrect.y = 0;
	bgrect.w = dlgrect.w;
	bgrect.h = dlgrect.h;

	/* Save background */
	pBgSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, dlgrect.w, dlgrect.h, pSdlGuiScrn->format->BitsPerPixel,
	                                  pSdlGuiScrn->format->Rmask, pSdlGuiScrn->format->Gmask, pSdlGuiScrn->format->Bmask, pSdlGuiScrn->format->Amask);
	if (pSdlGuiScrn->format->palette != NULL)
	{
		SDL_SetColors(pBgSurface, pSdlGuiScrn->format->palette->colors, 0, pSdlGuiScrn->format->palette->ncolors-1);
	}

	if (pBgSurface != NULL)
	{
		SDL_BlitSurface(pSdlGuiScrn,  &dlgrect, pBgSurface, &bgrect);
	}
	else
	{
		fprintf(stderr, "SDLGUI_DoDialog: CreateRGBSurface failed: %s\n", SDL_GetError());
	}
	SDLGui_DebugPrintDialog(dlg);

	/* focus default button if nothing else is focused */
	focused = SDLGui_SearchState(dlg, SG_FOCUSED);
	if (focused == SDLGUI_NOTFOUND)
	{
		int defbutton = SDLGui_SearchFlags(dlg, SG_DEFAULT);
		if (defbutton != SDLGUI_NOTFOUND)
		{
			dlg[defbutton].state |= SG_FOCUSED;
			focused = defbutton;
		}
	}
	Dprintf(("focused: %d\n", focused));
	SDLGui_SetShortcuts(dlg);

	/* (Re-)draw the dialog */
	SDLGui_DrawDialog(dlg);

	/* Is the left mouse button still pressed? Yes -> Handle TOUCHEXIT objects here */
	SDL_PumpEvents();
	b = SDL_GetMouseState(&i, &j);

	/* If current object is the scrollbar, and mouse is still down, we can scroll it */
	/* also if the mouse pointer has left the scrollbar */
	if (current_object != SDLGUI_NOTFOUND && dlg[current_object].type == SGSCROLLBAR) {
		obj = current_object;
		retbutton = obj;
		oldbutton = obj;
		if (b & SDL_BUTTON(1))
		{
			dlg[obj].state |= SG_MOUSEDOWN;
		}
		else
		{
			current_object = 0;
			dlg[obj].state &= ~SG_MOUSEDOWN;
		}
	}
	else {
		obj = SDLGui_FindObj(dlg, i, j);
		current_object = obj;
		if (obj != SDLGUI_NOTFOUND && (dlg[obj].flags&SG_TOUCHEXIT) )
		{
			oldbutton = obj;
			if (b & SDL_BUTTON(1))
			{
				dlg[obj].state |= SG_SELECTED;
				retbutton = obj;
			}
		}
	}

	if (SDL_NumJoysticks() > 0)
		joy = SDL_JoystickOpen(0);

#if !WITH_SDL2
	/* Enable unicode translation to get shifted etc chars with SDL_PollEvent */
	nOldUnicodeMode = SDL_EnableUNICODE(true);
#endif
	Dprintf(("ENTER - obj: %d, old: %d, ret: %d\n", obj, oldbutton, retbutton));

	/* The main loop */
	while (retbutton == SDLGUI_NOTFOUND && !bQuitProgram)
	{
		if (SDL_WaitEvent(&sdlEvent) == 1)  /* Wait for events */
		
			switch (sdlEvent.type)
			{
			 case SDL_QUIT:
				retbutton = SDLGUI_QUIT;
				break;

			 case SDL_MOUSEBUTTONDOWN:
				if (sdlEvent.button.button != SDL_BUTTON_LEFT)
				{
					/* Not left mouse button -> unsupported event */
					if (pEventOut)
						retbutton = SDLGUI_UNKNOWNEVENT;
					break;
				}
				/* It was the left button: Find the object under the mouse cursor */
				SDLGui_ScaleMouseButtonCoordinates(&sdlEvent.button);
				obj = SDLGui_FindObj(dlg, sdlEvent.button.x, sdlEvent.button.y);
				if (obj != SDLGUI_NOTFOUND)
				{
					if (dlg[obj].type==SGBUTTON)
					{
						dlg[obj].state |= SG_SELECTED;
						SDLGui_DrawButton(dlg, obj);
						SDL_UpdateRect(pSdlGuiScrn, (dlg[0].x+dlg[obj].x)*sdlgui_fontwidth-2, (dlg[0].y+dlg[obj].y)*sdlgui_fontheight-2,
						               dlg[obj].w*sdlgui_fontwidth+4, dlg[obj].h*sdlgui_fontheight+4);
						oldbutton=obj;
					}
					if (dlg[obj].type==SGSCROLLBAR)
					{
						dlg[obj].state |= SG_MOUSEDOWN;
						oldbutton=obj;
					}
					if ( dlg[obj].flags&SG_TOUCHEXIT )
					{
						dlg[obj].state |= SG_SELECTED;
						retbutton = obj;
					}
				}
				break;

			 case SDL_MOUSEBUTTONUP:
				if (sdlEvent.button.button != SDL_BUTTON_LEFT)
				{
					/* Not left mouse button -> unsupported event */
					if (pEventOut)
						retbutton = SDLGUI_UNKNOWNEVENT;
					break;
				}
				/* It was the left button: Find the object under the mouse cursor */
				SDLGui_ScaleMouseButtonCoordinates(&sdlEvent.button);
				obj = SDLGui_FindObj(dlg, sdlEvent.button.x, sdlEvent.button.y);
				if (obj != SDLGUI_NOTFOUND)
				{
					retbutton = SDLGui_HandleSelection(dlg, obj, oldbutton);
				}
				if (oldbutton != SDLGUI_NOTFOUND && dlg[oldbutton].type == SGBUTTON)
				{
					dlg[oldbutton].state &= ~SG_SELECTED;
					SDLGui_DrawButton(dlg, oldbutton);
					SDL_UpdateRect(pSdlGuiScrn, (dlg[0].x+dlg[oldbutton].x)*sdlgui_fontwidth-2, (dlg[0].y+dlg[oldbutton].y)*sdlgui_fontheight-2,
					               dlg[oldbutton].w*sdlgui_fontwidth+4, dlg[oldbutton].h*sdlgui_fontheight+4);
					oldbutton = SDLGUI_NOTFOUND;
				}
				break;

			 case SDL_JOYAXISMOTION:
				value = sdlEvent.jaxis.value;
				if (value < -3200 || value > 3200)
				{
					if(sdlEvent.jaxis.axis == 0)
					{
						/* Left-right movement */
						if (value < 0)
							retbutton = SDLGui_HandleShortcut(dlg, SG_SHORTCUT_LEFT);
						else
							retbutton = SDLGui_HandleShortcut(dlg, SG_SHORTCUT_RIGHT);
					}
					else if(sdlEvent.jaxis.axis == 1)
					{
						/* Up-Down movement */
						if (value < 0)
						{
							SDLGui_RemoveFocus(dlg, focused);
							focused = SDLGui_FocusNext(dlg, focused, -1);
						}
						else
						{
							SDLGui_RemoveFocus(dlg, focused);
							focused = SDLGui_FocusNext(dlg, focused, +1);
						}
					}
				}
				break;

			 case SDL_JOYBUTTONDOWN:
				retbutton = SDLGui_HandleSelection(dlg, focused, focused);
				break;

			 case SDL_JOYBALLMOTION:
			 case SDL_JOYHATMOTION:
			 case SDL_MOUSEMOTION:
				break;

			 case SDL_KEYDOWN:                     /* Key pressed */
				key = sdlEvent.key.keysym.sym;
				/* keyboard shortcuts are with modifiers */
				if (sdlEvent.key.keysym.mod & KMOD_LALT
				    || sdlEvent.key.keysym.mod & KMOD_RALT)
				{
					if (key == SDLK_LEFT)
						retbutton = SDLGui_HandleShortcut(dlg, SG_SHORTCUT_LEFT);
					else if (key == SDLK_RIGHT)
						retbutton = SDLGui_HandleShortcut(dlg, SG_SHORTCUT_RIGHT);
					else if (key == SDLK_UP)
						retbutton = SDLGui_HandleShortcut(dlg, SG_SHORTCUT_UP);
					else if (key == SDLK_DOWN)
						retbutton = SDLGui_HandleShortcut(dlg, SG_SHORTCUT_DOWN);
					else
					{
#if !WITH_SDL2
						/* unicode member is needed to handle shifted etc special chars */
						key = sdlEvent.key.keysym.unicode;
#endif
						if (key >= 33 && key <= 126)
							retbutton = SDLGui_HandleShortcut(dlg, toupper(key));
					}
					if (!retbutton && pEventOut)
						retbutton = SDLGUI_UNKNOWNEVENT;
					break;
				}
				switch (key)
				{
				 case SDLK_UP:
				 case SDLK_LEFT:
					SDLGui_RemoveFocus(dlg, focused);
					focused = SDLGui_FocusNext(dlg, focused, -1);
					break;
				 case SDLK_TAB:
				 case SDLK_DOWN:
				 case SDLK_RIGHT:
					SDLGui_RemoveFocus(dlg, focused);
					focused = SDLGui_FocusNext(dlg, focused, +1);
					break;
				 case SDLK_HOME:
					SDLGui_RemoveFocus(dlg, focused);
					focused = SDLGui_FocusNext(dlg, 1, +1);
					break;
				 case SDLK_END:
					SDLGui_RemoveFocus(dlg, focused);
					focused = SDLGui_FocusNext(dlg, 1, -1);
					break;
				 case SDLK_SPACE:
				 case SDLK_RETURN:
				 case SDLK_KP_ENTER:
					retbutton = SDLGui_HandleSelection(dlg, focused, focused);
					break;
				 case SDLK_ESCAPE:
					retbutton = SDLGui_SearchFlags(dlg, SG_CANCEL);
					break;
				 default:
					if (pEventOut)
						retbutton = SDLGUI_UNKNOWNEVENT;
					break;
				}
				break;

#if WITH_SDL2
			 case SDL_WINDOWEVENT:
				if (sdlEvent.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
				{
					SDL_UpdateRect(pSdlGuiScrn, 0, 0, 0, 0);
				}
				break;
#endif

			 default:
				if (pEventOut)
					retbutton = SDLGUI_UNKNOWNEVENT;
				break;
			}
	}

	/* Restore background */
	if (pBgSurface)
	{
		SDL_BlitSurface(pBgSurface, &bgrect, pSdlGuiScrn,  &dlgrect);
		SDL_FreeSurface(pBgSurface);
	}

	/* Copy event data of unsupported events if caller wants to have it */
	if (retbutton == SDLGUI_UNKNOWNEVENT && pEventOut)
		memcpy(pEventOut, &sdlEvent, sizeof(SDL_Event));

	if (retbutton == SDLGUI_QUIT)
		bQuitProgram = true;

#if !WITH_SDL2
	SDL_EnableUNICODE(nOldUnicodeMode);
#endif
	if (joy)
		SDL_JoystickClose(joy);

	Dprintf(("EXIT - ret: %d, current: %d\n", retbutton, current_object));
	return retbutton;
}
示例#7
0
文件: main.c 项目: manolaz/Wizznic
int main(int argc, char *argv[])
{
  int doScale=0; // 0=Undefined, 1=320x240, -1=OpenGL, >1=SwScale
  char* dumpPack=NULL;
  int state=1; //Game, Menu, Editor, Quit
  int sdlVideoModeFlags = SDL_SWSURFACE;

  #ifdef PSP
    //Note to PSP porter, please test if HW is actually faster, Wizznic does a lot of memory-manipulation in the screen-surface, each call might initiate a full copy back/forth from video memory. Remove comment when read. :)
    sdlVideoModeFlags = (SDL_HWSURFACE | SDL_DOUBLEBUF |SDL_HWACCEL);
    SetupCallbacks();//Callbacks actifs
    scePowerSetClockFrequency(333,333,166);
  #endif

//  #ifdef WIN32
//Redirect stdout to console on windows, so we can see what's going in.
//  FILE *stream;
//  stream = freopen("CON", "w", stdout);
//  #endif

  //Print welcome message
  printf( "Wizznic "VERSION_STRING". GPLv3 or newer Copyleft 2010-2013\n\n");

  //initialize path strings
  initUserPaths();

  //Tell where stuff's at.
  printf("Directories:\n    Settings: %s\n    DLC: %s\n    Highscores: %s\n    Editorlevels: %s\n    Datafiles: %s\n\n", \
                            getConfigDir(), getUsrPackDir(), getHighscoreDir(), getUserLevelDir(), (!strlen(DATADIR))?".":DATADIR);

  //Print the command line parameters
  printf("Command-line parameters:\n"STR_VID_OPTIONS);

  //Quit if user wants help
  if( argc > 1 && ( strcmp(argv[1], "-h")==0 || strcmp(argv[1], "--help")==0 || strcmp(argv[1], "-help")==0 ))
  {
    printf("Please see readme.txt or http://wizznic.org/ for more help.\n");
    return(0);
  }

  //Read settings
  printf("Loading settings...\n");
  initSettings();

  #if defined(WITH_OPENGL)
  //We start by enabling glScaling if it was enabled in settings, it can then be overwritten by command line options.
  if( setting()->glEnable && doScale==0 )
    doScale=-1;
  #endif

  //Set scaling
  setting()->scaleFactor=1.0;

  atexit(SDL_Quit);

  //Init SDL
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_TIMER ) <0 )
  {
    printf("SDL_Init failed: %s\n",SDL_GetError());
    return(-1);
  }

  //Setup display
  #if defined (GP2X) || defined (PSP) || defined (WIZ)
  SDL_Surface* screen = SDL_SetVideoMode(SCREENW,SCREENH,16, sdlVideoModeFlags);
  #else
  SDL_Surface* screen=NULL;

  int i;
  for( i=0; i < argc; i++ )
  {
    if( strcmp( argv[i], "-sw" ) == 0 )
    {
      setting()->glEnable=0;
      doScale=0;
      saveSettings();
    } else
    if( strcmp( argv[i], "-gl" ) == 0 )
    {
      setting()->glEnable=1;
      doScale=-1;
      saveSettings();
    } else
    if( strcmp( argv[i], "-z" ) == 0 )
    {
      if( i+1 < argc )
      {
        doScale = atoi( argv[i+1] );
        setting()->glEnable=0;
        i++;
        saveSettings();
      } else {
        printf(" -z requires zoom level ( -z 2 for example ).\n");
        return(1);
      }
    } else
    if( strcmp( argv[i], "-f" ) == 0 )
    {
        setting()->fullScreen=1;
        saveSettings();
    } else
    if( strcmp( argv[i], "-w" ) == 0 )
      {
        setting()->fullScreen=0;
        saveSettings();
    } else if( strcmp( argv[i], "-glheight" ) == 0 )
    {
      if( i+1 < argc )
      {
        setting()->glHeight = atoi( argv[i+1] );
        setting()->glEnable=1;
        doScale=-1;
        i++;
        printf("Setting OpenGL window height to %i.\n", setting()->glHeight);
        saveSettings();
      } else {
        printf(" -glheight requires an argument (-1 or size in pixels).\n");
        return(1);
      }
    } else if( strcmp( argv[i], "-glwidth" ) == 0 )
    {
      if( i+1 < argc )
      {
        setting()->glWidth = atoi( argv[i+1] );
        setting()->glEnable=1;
        doScale=-1;
        i++;
        printf("Setting OpenGL window width to %i.\n", setting()->glWidth);
        saveSettings();
      } else {
        printf(" -glwidth requires an argument (-1 or size in pixels).\n");
        return(1);
      }
    } else if( strcmp( argv[i], "-glfilter" ) == 0 )
    {
      if( i+1 < argc )
      {
        setting()->glFilter=atoi(argv[i+1]);
        printf("OpenGL texture filtering set to %s.\n", (setting()->glFilter)?"Smooth":"Off");
        i++;
        saveSettings();
      } else {
        printf("-glfilter requires 0 or 1 as argument.\n");
        return(1);
      }
    } else if( strcmp( argv[i] , "-d" ) == 0 )
    {
      if( argc == 3 && i < argc+1 )
      {
        dumpPack = malloc( sizeof(char)*strlen(argv[i+1])+1 );
        strcpy( dumpPack, argv[i+1] );
        doScale=0;
        setting()->glEnable=0;
        i++;
      } else {
        printf("-d requires a packname, and must not be used with other parameters.\n");
        return(1);
      }
    } else if( strcmp( argv[i], "-rift") == 0 )
    {
      setting()->glWidth = 1280;
      setting()->glHeight = 800;
      setting()->glEnable=1;
      setting()->rift=1;
      doScale=-1;
    } else if( i > 0 )
    {
      printf("\nError: Invalid argument '%s', quitting.\n", argv[i]);
      return(1);
    }

  }

  if( setting()->fullScreen )
  {
    sdlVideoModeFlags |= SDL_FULLSCREEN;
  }

  if(doScale)
  {
    //Hardware accelerated scaling
    if( doScale == -1 )
    {
    #ifdef HAVE_ACCELERATION
      printf("Enabling platform specific accelerated scaling.\n");
      screen = platformInitAccel(sdlVideoModeFlags);
      if( !screen )
      {
        printf("Failed to set platform accelerated scaling, falling back to software window.\n");
        screen=swScreen(SDL_SWSURFACE);
        doScale=0;
      }
    #else
      printf("\nError:\n  Not compiled with hardware-scaling support, don't give me -z -1\n  Exiting...\n");
      return(-1);
    #endif
    } else if( doScale > 0 )
    {
    #ifdef WANT_SWSCALE
      //Set up software scaling
      printf("Enabling slow software-based scaling to %ix%i.\n",320*doScale, 240*doScale);
      screen = swScaleInit(sdlVideoModeFlags,doScale);
    #else
      printf("\nError:\n  I don't support software scaling, don't give me any -z options\n  Exiting...\n");
      return(-1);
    #endif
    }
  } else {
    screen=swScreen(sdlVideoModeFlags);
    doScale=0;
  }

  printf("Scaling factor: %f\n", setting()->scaleFactor);

  if( screen == NULL )
  {
    printf("ERROR: Couldn't init video.\n");
    return(-1);
  }


  //Set window title
  SDL_WM_SetCaption("Wizznic!", "Wizznic!");
  //Set window icon
  SDL_Surface* icon = IMG_Load( DATADIR"data/wmicon.png");
  SDL_WM_SetIcon(icon, NULL);
  SDL_FreeSurface(icon);

  #endif

  setting()->bpp = screen->format->BytesPerPixel;
  setAlphaCol( setting()->bpp );

  printf("Screen surface using %i bytes per pixel.\n",setting()->bpp);

  //Open Joysticks (for wiz)
  if (SDL_NumJoysticks() > 0) SDL_JoystickOpen(0);

  //Hide mouse cursor
  SDL_ShowCursor(SDL_DISABLE);

  //Load fonts
  txtInit();

  //Load sounds
  if(!initSound())
  {
    printf("Couldn't init sound.\n");
    return(-1);
  }

  //Menu Graphics
  if(!initMenu(screen))
  {
    printf("Couldn't load menu graphics.\n");
    return(-1);
  }

  //Init controls
  initControls();

  //Init stats
  statsInit();

  //Init packs
  packInit();

  //Scan userlevels dir
  makeUserLevelList(screen);

  //Init particles
  initParticles(screen);

  //Seed the pseudo random number generator (for particles 'n' stuff)
  srand( (int)time(NULL) );

  #if defined(PC)
  //Need to dump level-screenshots?
  if(dumpPack)
  {
    printf("Dumping level-images for pack: %s\n", dumpPack);
    dumplevelimages(screen, dumpPack, 0);
    return(0);
  }
  #endif

  //init starfield
  initStars(screen);

  //Init pointer
  initPointer(screen);

  printf("Applying settings..\n");
  //Apply settings (has to be done after packs are inited)
  applySettings();
  //Set Pack
  packSetByPath( setting()->packDir );

  #if defined( PLATFORM_SUPPORTS_STATSUPLOAD )
  if( (setting()->uploadStats) && !(setting()->firstRun) )
  {
    statsUpload(0,0,0,0,0,"check",1, &(setting()->session) );
    statsUpload(0,0,0,0,0,"q_solved",1, &(setting()->solvedWorldWide) );

    //DLC only works when stats-uploading is enabled so we can use the same nag-screen.
    dlcCheckOnline();
  }
  #endif

  printf("Setting Music...\n");
  //Start playing music (has to be done after readong settings)
  soundSetMusic();

  //Initialize credits
  initCredits(screen);

  initTransition();


#if SCREENW != 320 || SCREENH != 240
  SDL_Rect *borderSrcRect = malloc(sizeof(SDL_Rect));
  SDL_Surface* border = loadImg( BORDER_IMAGE );
  if( border )
  {
    printf("Border image loaded.\n");
    borderSrcRect->x=(border->w-SCREENW)/2;
    borderSrcRect->y=(border->h-SCREENH)/2;
    borderSrcRect->w=SCREENW;
    borderSrcRect->h=SCREENH;
    SDL_BlitSurface( border, borderSrcRect, screen, NULL );
    SDL_FreeSurface(border);
  } else {
    printf("Could not load border image: %s\n", BORDER_IMAGE);
    SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0,0,0));
  }
  free(borderSrcRect);
  borderSrcRect=NULL;

#endif

  int lastTick;
  while(state!=STATEQUIT)
  {
    lastTick=SDL_GetTicks();

    frameStart();

    if(runControls()) state=STATEQUIT;
    switch(state)
    {
      case STATEPLAY:
        state = runGame(screen);
      break;

      case STATEMENU:
        state = runMenu(screen);
      break;

      case STATEEDIT:
        state=runEditor(screen);
      break;
    }

    drawPointer(screen);

    soundRun(screen,state);

    runTransition(screen);

    if(setting()->showFps)
      drawFPS(screen);

    switch( doScale )
    {
      #if defined(HAVE_ACCELERATION)
      case -1:
        platformDrawScaled(screen);
        break;
      #endif
      case 0:
        SDL_Flip(screen);
        break;
      #if defined(WANT_SWSCALE)
      default:
        swScale(screen,doScale);
        break;
      #else
      default:
        state=STATEQUIT;
      break;
      #endif
    }

    #if defined(CRUDE_TIMING)
    //Oh how I loathe this, is there no better way?
    while(SDL_GetTicks()-lastTick <= PLATFORM_CRUDE_TIMING_TICKS)
    {
      //Burn, burn baby burn!
    }
    #else
    int t=SDL_GetTicks()-lastTick;
    if(t < 20)
    {
      SDL_Delay( 20 -t);
    }
    #endif
  }

  #if defined(PLATFORM_NEEDS_EXIT)
  platformExit();
  #endif

  SDL_Quit();

  return(0);
}
示例#8
0
/*
===============
IN_InitJoystick
===============
*/
static void IN_InitJoystick() {
    int i = 0;
    int total = 0;

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

    stick = nullptr;
    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_JoystickNameForIndex(i));
    }

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

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

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

    stick = SDL_JoystickOpen(in_joystickNo->integer);

    if (stick == nullptr) {
        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");

    SDL_JoystickEventState(SDL_QUERY);

    // XBox 360 controller support
    if (!Q_stricmp(SDL_JoystickNameForIndex(in_joystickNo->integer),
                   "Microsoft X-Box 360 pad")) {
        Cvar_Set("in_xbox360ControllerAvailable", "1");
    } else {
        Cvar_Set("in_xbox360ControllerAvailable", "0");
    }
}
示例#9
0
//Registers, creates, and shows the Window!!
bool WinCreate()
{
    std::string version = string_format("Cataclysm: Dark Days Ahead - %s", getVersionString());

    //Flags used for setting up SDL VideoMode
    int window_flags = 0;

    //If FULLSCREEN was selected in options add SDL_WINDOW_FULLSCREEN flag to screen_flags, causing screen to go fullscreen.
    if(OPTIONS["FULLSCREEN"]) {
        window_flags = window_flags | SDL_WINDOW_FULLSCREEN;
    }

    window = SDL_CreateWindow(version.c_str(),
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            WindowWidth,
            WindowHeight,
            window_flags
        );

	//create renderer and convert that to a SDL_Surface?

    if (window == NULL) return false;

    format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window));

    bool software_renderer = OPTIONS["SOFTWARE_RENDERING"];
    if( !software_renderer ) {
        DebugLog() << "Attempting to initialize accelerated SDL renderer.\n";

        renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED |
                                       SDL_RENDERER_PRESENTVSYNC );
        if( renderer == NULL ) {
            DebugLog() << "Failed to initialize accelerated renderer, falling back to software rendering: " << SDL_GetError() << "\n";
            software_renderer = true;
        }
    }
    if( software_renderer ) {
        renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_SOFTWARE );
        if( renderer == NULL ) {
            DebugLog() << "Failed to initialize software renderer: " << SDL_GetError() << "\n";
            return false;
        }
    }

    ClearScreen();

    if(OPTIONS["HIDE_CURSOR"] != "show" && SDL_ShowCursor(-1)) {
        SDL_ShowCursor(SDL_DISABLE);
    } else {
        SDL_ShowCursor(SDL_ENABLE);
    }

    // Initialize joysticks.
    int numjoy = SDL_NumJoysticks();

    if(numjoy > 1) {
        DebugLog() << "You have more than one gamepads/joysticks plugged in, only the first will be used.\n";
    }

    if(numjoy >= 1) {
        joystick = SDL_JoystickOpen(0);
    } else {
        joystick = NULL;
    }

    SDL_JoystickEventState(SDL_ENABLE);

    return true;
};
示例#10
0
bool World::InitScreen()
{
     bool run = true;
     if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
        {
            printf("Fail initialize : %s\n",SDL_GetError());
            run = false;
        }
        else
        {
            printf("Initialization Success!\n");

            if(!SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1"))
            {
                printf("Warning: VSync not enabled!\n");
                run = false;
            }

            m_window = SDL_CreateWindow(TITLE,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,g_WINDOW_WIDTH,g_WINDOW_HEIGHT,SDL_WINDOW_SHOWN);

            if(m_window == NULL)
            {
                printf("ERROR creting Window : %s\n",SDL_GetError());
                run = false;
            }
            else
            {
                printf("Created Window .\n");

                m_render = SDL_CreateRenderer(m_window,-1,SDL_RENDERER_ACCELERATED);

                if(m_render == NULL)
                {
                    printf("Failed creating Render : %s\n",SDL_GetError());
                    run = false;
                }
                else
                {
                    printf("Creted Render.\n");
                    SDL_SetRenderDrawColor( m_render, 0xFF, 0xFF, 0xFF, 0xFF );

                    int picFlag = IMG_INIT_PNG;
                    if(!(IMG_Init(picFlag))& picFlag)
                    {
                        printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                        run = false;
                    }
                    else
                    {
                        if(!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
                        {
                            printf("Warning: Scale Quality not enabled!\n");
                            run = false;
                        }
                        else
                        {
                            m_Stick1 = SDL_JoystickOpen(0);
                            if(m_Stick1 == NULL)
                            {
                                printf("Warning: 1st Joystick FAIL\n");
                            }
                            m_Stick2 = SDL_JoystickOpen(1);
                            if(m_Stick2 == NULL)
                            {
                                printf("Warning: 2nd Joystick FAIL\n");
                            }
                                if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 4, 4048 ) < 0 )
                            {
                                printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
                            }
                        }
                    }

                }
            }
        }
        m_main_music= new Sound();
        m_main_music->Init("data/music.txt");
        m_main_music->Play(true);
        SDL_JoystickEventState(SDL_ENABLE);
        return run;
}
示例#11
0
// First time (lazy) initialization.
void
gfctrlJoyInit(void)
{
#ifndef SDL_JOYSTICK
    gfctrlJoyPresent = GFCTRL_JOY_NONE;

    for (int index = 0; index < GFCTRL_JOY_NUMBER; index++) {
		if (!Joysticks[index]) {
			Joysticks[index] = new jsJoystick(index);
		}
    
		// Don't configure the joystick if it doesn't work
		if (Joysticks[index]->notWorking()) {
			delete Joysticks[index];
			Joysticks[index] = 0;
		} else {
			gfctrlJoyPresent = GFCTRL_JOY_PRESENT;
		}
    }
#else
#if SDL_MAJOR_VERSION >= 2
    memset(&cfx, 0, sizeof(cfx));

    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC) < 0) {
#else
    if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
#endif
        GfLogError("Couldn't initialize SDL: %s\n", SDL_GetError());
        gfctrlJoyPresent = GFCTRL_JOY_UNTESTED;
	return;
    }
#if SDL_MAJOR_VERSION >= 2
    // Ignore the joystick events, we will poll directly as it is faster
    SDL_JoystickEventState(SDL_IGNORE);
#endif
    gfctrlJoyPresent = SDL_NumJoysticks();
    if (gfctrlJoyPresent > GFCTRL_JOY_NUMBER) gfctrlJoyPresent = GFCTRL_JOY_NUMBER;

    for (int index = 0; index < gfctrlJoyPresent; index++) {
		if (!Joysticks[index]) {
			Joysticks[index] = SDL_JoystickOpen(index);
		}
    
		// Don't configure the joystick if it doesn't work
		if (Joysticks[index] ==  NULL) {
			GfLogError("Couldn't open joystick %d: %s\n", index, SDL_GetError());
#if SDL_MAJOR_VERSION >= 2
		} else {
			cfx_timeout[index] = 0;
			rfx_timeout[index] = 0;
			
			// Find which Haptic device relates to this joystick
			Haptics[index] = SDL_HapticOpenFromJoystick(Joysticks[index]);

			if (!Haptics[index]) {
				GfLogInfo("Joystick %d does not support haptic\n", index);
				break;
#if 0
			} else {
				// add an CF effect on startup
				gfctrlJoyConstantForce(index, 50000, 9000);
#endif
			}

			// Check for Rumble capability
			if (SDL_HapticRumbleSupported(Haptics[index]) == SDL_TRUE) {
				if (SDL_HapticRumbleInit(Haptics[index]) != 0) 
					GfLogError("Couldn't init rumble on joystick %d: %s\n", index, SDL_GetError());
#if 0
				else
					gfctrlJoyRumble(index, 0.5);
#endif
			}
#endif
                }
     }
#endif
}

#if SDL_JOYSTICK
void
gfctrlJoyConstantForce(int index, unsigned int level, int dir)
{
#if SDL_MAJOR_VERSION >= 2
	if (!Haptics[index]) return;

	if ((SDL_HapticQuery(Haptics[index]) & SDL_HAPTIC_CONSTANT) == 0) return;

	cfx[index].type = SDL_HAPTIC_CONSTANT;
	cfx[index].constant.direction.type = SDL_HAPTIC_POLAR;
	cfx[index].constant.direction.dir[0] = dir;
	cfx[index].constant.length = 1000;
	cfx[index].constant.level = level;
	cfx[index].constant.attack_length = 0;
	cfx[index].constant.fade_length = 1000;

#if __WIN32__
	if (SDL_HapticGetEffectStatus(Haptics[index], id[index]) == SDL_TRUE)
#else
	// Linux SDL doesn't support checking status at the moment :-(
	if (cfx_timeout[index] > SDL_GetTicks())
#endif
		SDL_HapticUpdateEffect(Haptics[index], id[index], &cfx[index]);
	else {
		SDL_HapticDestroyEffect(Haptics[index], id[index]);
		id[index] = SDL_HapticNewEffect(Haptics[index], &cfx[index]);
		SDL_HapticRunEffect(Haptics[index], id[index], 1);
	}

	cfx_timeout[index] = SDL_GetTicks() + cfx[index].constant.length;
#endif
}

void
gfctrlJoyRumble(int index, float level)
{
#if SDL_MAJOR_VERSION >= 2
	if (!Haptics[index]) return;

	if (SDL_HapticRumbleSupported(Haptics[index]) != SDL_TRUE) return;

	// we have to stop the rumble before updating
	if (rfx_timeout[index] > SDL_GetTicks()) {
		if (SDL_HapticRumbleStop(Haptics[index]) != 0)
			GfLogError("Failed to stop rumble: %s\n", SDL_GetError() );
	}

	if (SDL_HapticRumblePlay(Haptics[index], level, 100) != 0)
		GfLogError("Failed to play rumble: %s\n", SDL_GetError() );

	rfx_timeout[index] = SDL_GetTicks() + 100;
#endif
}
#endif

// Shutdown time.
void
gfctrlJoyShutdown(void)
{
   if (gfctrlJoyPresent != GFCTRL_JOY_UNTESTED)
#ifndef SDL_JOYSTICK
	
		for (int index = 0; index < GFCTRL_JOY_NUMBER; index++)
			delete Joysticks[index];

	
#else
      for (int index = 0; index < gfctrlJoyPresent; index++) {
			SDL_JoystickClose(Joysticks[index]);
			Joysticks[index] = NULL;
#if SDL_MAJOR_VERSION >= 2
			if (Haptics[index]) {
				SDL_HapticClose(Haptics[index]);
				Haptics[index] = NULL;
			}			
#endif
		}
#endif
      gfctrlJoyPresent = GFCTRL_JOY_UNTESTED;
}

/** Create the joystick control
    @ingroup	ctrl
    @return	pointer on a tCtrlJoyInfo structure
		<br>0 .. if no joystick present
    @note	call GfctrlJoyRelease to free the tCtrlJoyInfo structure
    @see	GfctrlJoyRelease
    @see	tCtrlJoyInfo
*/
tCtrlJoyInfo *
GfctrlJoyCreate(void)
{
    if (gfctrlJoyPresent == GFCTRL_JOY_UNTESTED)
       gfctrlJoyInit();

    tCtrlJoyInfo* joyInfo = (tCtrlJoyInfo *)calloc(1, sizeof(tCtrlJoyInfo));

#if SDL_JOYSTICK
    joyInfoCopy = joyInfo;
#endif

    return joyInfo;
}

/** Release the tCtrlJoyInfo structure
    @ingroup	ctrl
    @param	joyInfo	joystick structure
    @return	none
*/
void
GfctrlJoyRelease(tCtrlJoyInfo *joyInfo)
{
    freez(joyInfo);
}
示例#12
0
文件: input.c 项目: neonmori/sdlpalX
/**
 * Handle joystick events.
 *
 * @param[in] lpEvent - pointer to the event.
 * @return None
 */
static VOID PAL_JoystickEventFilter(const SDL_Event *lpEvent)
{
#ifdef PAL_HAS_JOYSTICKS
    switch (lpEvent->type) {
#if defined (GEKKO)
        case SDL_JOYHATMOTION:
           switch (lpEvent->jhat.value)
           {
           case SDL_HAT_LEFT:
             g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
             g_InputState.dir = kDirWest;
             g_InputState.dwKeyPress = kKeyLeft;
             break;

           case SDL_HAT_RIGHT:
             g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
             g_InputState.dir = kDirEast;
             g_InputState.dwKeyPress = kKeyRight;
             break;

           case SDL_HAT_UP:
             g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
             g_InputState.dir = kDirNorth;
             g_InputState.dwKeyPress = kKeyUp;
             break;

           case SDL_HAT_DOWN:
             g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
             g_InputState.dir = kDirSouth;
             g_InputState.dwKeyPress = kKeyDown;
             break;
           }
           break;
#else
        case SDL_JOYAXISMOTION:
            //
            // Moved an axis on joystick
            //
            switch (lpEvent->jaxis.axis) {
                case 0:
                    //
                    // X axis
                    //
#if defined(GPH)
                    if (lpEvent->jaxis.value > MAX_DEADZONE) {
                       g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
                       g_InputState.dir = kDirEast;
                       g_InputState.dwKeyPress = kKeyRight;
                    } else if (lpEvent->jaxis.value < MIN_DEADZONE) {
                       g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
                       g_InputState.dir = kDirWest;
                       g_InputState.dwKeyPress = kKeyLeft;
                    } else {
                       g_InputState.dir = kDirUnknown;
                    }
#else
                    if (lpEvent->jaxis.value > 20000) {
                        if (g_InputState.dir != kDirEast) {
                            g_InputState.dwKeyPress |= kKeyRight;
                        }
                        g_InputState.prevdir = g_InputState.dir;
                        g_InputState.dir = kDirEast;
                    } else if (lpEvent->jaxis.value < -20000) {
                        if (g_InputState.dir != kDirWest) {
                            g_InputState.dwKeyPress |= kKeyLeft;
                        }
                        g_InputState.prevdir = g_InputState.dir;
                        g_InputState.dir = kDirWest;
                    } else {
                        if (g_InputState.prevdir != kDirEast &&
                                g_InputState.prevdir != kDirWest) {
                            g_InputState.dir = g_InputState.prevdir;
                        }
                        g_InputState.prevdir = kDirUnknown;
                    }
#endif
                    break;

                case 1:
                    //
                    // Y axis
                    //
#if defined(GPH)
                    if (lpEvent->jaxis.value > MAX_DEADZONE) {
                       g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
                       g_InputState.dir = kDirSouth;
                       g_InputState.dwKeyPress = kKeyDown;
                    } else if (lpEvent->jaxis.value < MIN_DEADZONE) {
                       g_InputState.prevdir = (gpGlobals->fInBattle ? kDirUnknown : g_InputState.dir);
                       g_InputState.dir = kDirNorth;
                       g_InputState.dwKeyPress = kKeyUp;
                    } else {
                       g_InputState.dir = kDirUnknown;
                    }
#else
                    if (lpEvent->jaxis.value > 20000) {
                        if (g_InputState.dir != kDirSouth) {
                            g_InputState.dwKeyPress |= kKeyDown;
                        }
                        g_InputState.prevdir = g_InputState.dir;
                        g_InputState.dir = kDirSouth;
                    } else if (lpEvent->jaxis.value < -20000) {
                        if (g_InputState.dir != kDirNorth) {
                            g_InputState.dwKeyPress |= kKeyUp;
                        }
                        g_InputState.prevdir = g_InputState.dir;
                        g_InputState.dir = kDirNorth;
                    } else {
                        if (g_InputState.prevdir != kDirNorth &&
                                g_InputState.prevdir != kDirSouth) {
                            g_InputState.dir = g_InputState.prevdir;
                        }
                        g_InputState.prevdir = kDirUnknown;
                    }
#endif
                    break;
            }
            break;
#endif

        case SDL_JOYBUTTONDOWN:
            //
            // Pressed the joystick button
            //
#if defined(GPH)
            switch (lpEvent->jbutton.button)
            {
#if defined(GP2XWIZ)
            case 14:
#elif defined(CAANOO)
            case 3:
#endif
               g_InputState.dwKeyPress = kKeyMenu;
               break;

#if defined(GP2XWIZ)
            case 13:
#elif defined(CAANOO)
            case 2:
#endif
               g_InputState.dwKeyPress = kKeySearch;
               break;
#else
#if defined(GEKKO)
            switch (lpEvent->jbutton.button)
            {
            case 2:
               g_InputState.dwKeyPress |= kKeyMenu;
               break;

            case 3:
               g_InputState.dwKeyPress |= kKeySearch;
               break;
#else
            switch (lpEvent->jbutton.button & 1) {
                case 0:
                    g_InputState.dwKeyPress |= kKeyMenu;
                    break;

                case 1:
                    g_InputState.dwKeyPress |= kKeySearch;
                    break;
#endif
#endif
            }
            break;
    }
#endif
}

#ifdef PAL_HAS_TOUCH

#define  TOUCH_NONE     0
#define    TOUCH_UP      1
#define    TOUCH_DOWN      2
#define    TOUCH_LEFT      3
#define    TOUCH_RIGHT   4
#define    TOUCH_BUTTON1   5
#define    TOUCH_BUTTON2   6
#define  TOUCH_BUTTON3  7
#define  TOUCH_BUTTON4  8

static int
PAL_GetTouchArea(
   float X,
   float Y
)
{
   if (Y < 0.5)
   {
      //
      // Upper area
      //
      return TOUCH_NONE;
   }
   else if (X < 1.0 / 3)
   {
      if (Y - 0.5 < (1.0 / 6 - fabs(X - 1.0 / 3 / 2)) * (0.5 / (1.0 / 3)))
      {
         return TOUCH_UP;
      }
      else if (Y - 0.75 > fabs(X - 1.0 / 3 / 2) * (0.5 / (1.0 / 3)))
      {
         return TOUCH_DOWN;
      }
      else if (X < 1.0 / 3 / 2 && fabs(Y - 0.75) < 0.25 - X * (0.5 / (1.0 / 3)))
      {
         return TOUCH_LEFT;
      }
      else
      {
         return TOUCH_RIGHT;
      }
   }
   else if (X > 1.0 - 1.0 / 3)
   {
      if (X < 1.0 - (1.0 / 3 / 2))
      {
         if (Y < 0.75)
         {
            return TOUCH_BUTTON1;
         }
         else
         {
            return TOUCH_BUTTON3;
         }
      }
      else
      {
         if (Y < 0.75)
         {
            return TOUCH_BUTTON2;
         }
         else
         {
            return TOUCH_BUTTON4;
         }
      }
   }

   return TOUCH_NONE;
}

static VOID
PAL_SetTouchAction(
  int area
)
{
   switch (area)
   {
   case TOUCH_UP:
      g_InputState.dir = kDirNorth;
      g_InputState.dwKeyPress |= kKeyUp;
      break;

   case TOUCH_DOWN:
      g_InputState.dir = kDirSouth;
      g_InputState.dwKeyPress |= kKeyDown;
      break;

   case TOUCH_LEFT:
      g_InputState.dir = kDirWest;
      g_InputState.dwKeyPress |= kKeyLeft;
      break;

   case TOUCH_RIGHT:
      g_InputState.dir = kDirEast;
      g_InputState.dwKeyPress |= kKeyRight;
      break;

   case TOUCH_BUTTON1:
      if (gpGlobals->fInBattle)
      {
         g_InputState.dwKeyPress |= kKeyRepeat;
      }
      else
      {
         g_InputState.dwKeyPress |= kKeyForce;
      }
      break;

   case TOUCH_BUTTON2:
      g_InputState.dwKeyPress |= kKeyMenu;
      break;

   case TOUCH_BUTTON3:
      g_InputState.dwKeyPress |= kKeyUseItem;
      break;

   case TOUCH_BUTTON4:
      g_InputState.dwKeyPress |= kKeySearch;
      break;
   }
}

static VOID
PAL_UnsetTouchAction(
  int area
)
{
   switch (area)
   {
   case TOUCH_UP:
   case TOUCH_DOWN:
   case TOUCH_LEFT:
   case TOUCH_RIGHT:
      g_InputState.dir = kDirUnknown;
      break;
   }
}
#endif

/**
 * Handle touch events.
 *
 * @param[in] lpEvent - pointer to the event.
 * @return None
 */
static VOID PAL_TouchEventFilter(const SDL_Event *lpEvent)
{
#ifdef PAL_HAS_TOUCH
    static SDL_TouchID finger1 = -1, finger2 = -1;
    static int prev_touch1 = TOUCH_NONE;
    static int prev_touch2 = TOUCH_NONE;

    switch (lpEvent->type)
    {
    case SDL_FINGERDOWN:
      if (finger1 == -1)
      {
         int area = PAL_GetTouchArea(lpEvent->tfinger.x, lpEvent->tfinger.y);

         finger1 = lpEvent->tfinger.fingerId;
         prev_touch1 = area;
         PAL_SetTouchAction(area);
      }
      else if (finger2 == -1)
      {
         int area = PAL_GetTouchArea(lpEvent->tfinger.x, lpEvent->tfinger.y);

         finger2 = lpEvent->tfinger.fingerId;
         prev_touch2 = area;
         PAL_SetTouchAction(area);
      }
      break;

    case SDL_FINGERUP:
      if (lpEvent->tfinger.fingerId == finger1)
      {
         PAL_UnsetTouchAction(prev_touch1);
         finger1 = -1;
         prev_touch1 = TOUCH_NONE;
      }
      else if (lpEvent->tfinger.fingerId == finger2)
      {
         PAL_UnsetTouchAction(prev_touch2);
         finger2 = -1;
         prev_touch2 = TOUCH_NONE;
      }
      break;

    case SDL_FINGERMOTION:
       if (lpEvent->tfinger.fingerId == finger1)
       {
          int area = PAL_GetTouchArea(lpEvent->tfinger.x, lpEvent->tfinger.y);
          if (prev_touch1 != area && area != TOUCH_NONE)
          {
             PAL_UnsetTouchAction(prev_touch1);
             prev_touch1 = area;
             PAL_SetTouchAction(area);
          }
       }
       else if (lpEvent->tfinger.fingerId == finger2)
       {
          int area = PAL_GetTouchArea(lpEvent->tfinger.x, lpEvent->tfinger.y);
          if (prev_touch2 != area && area != TOUCH_NONE)
          {
             PAL_UnsetTouchAction(prev_touch2);
             prev_touch2 = area;
             PAL_SetTouchAction(area);
          }
       }
       break;
    }
#endif
}

/**
 * SDL event filter function. A filter to process all events.
 *
 * @param[in] lpEvent - pointer to the event.
 * @retval 1 = the event will be added to the internal queue.
 * @retval 0 = the event will be dropped from the queue.
 */
static int SDLCALL PAL_EventFilter(const SDL_Event *lpEvent)
{
    switch (lpEvent->type) {
#if SDL_VERSION_ATLEAST(2, 0, 0)
        case SDL_WINDOWEVENT:
            if (lpEvent->window.event == SDL_WINDOWEVENT_RESIZED) {
                //
                // resized the window
                //
                VIDEO_Resize(lpEvent->window.data1, lpEvent->window.data2);
            }
            break;

#ifdef __IOS__
        case SDL_APP_WILLENTERBACKGROUND:
           g_bRenderPaused = TRUE;
           break;

        case SDL_APP_DIDENTERFOREGROUND:
           g_bRenderPaused = FALSE;
           VIDEO_UpdateScreen(NULL);
           break;
#endif

#else

        case SDL_VIDEORESIZE:
           //
           // resized the window
           //
           VIDEO_Resize(lpEvent->resize.w, lpEvent->resize.h);
           break;
#endif

        case SDL_QUIT:
            //
            // clicked on the close button of the window. Quit immediately.
            //
            PAL_Shutdown();
            exit(0);
    }

    PAL_KeyboardEventFilter(lpEvent);
    PAL_MouseEventFilter(lpEvent);
    PAL_JoystickEventFilter(lpEvent);
    PAL_TouchEventFilter(lpEvent);

    //
    // All events are handled here; don't put anything to the internal queue
    //
    return 0;
}

/**
 * Clear the record of pressed keys.

 */
VOID PAL_ClearKeyState(VOID)
{
    g_InputState.dwKeyPress = 0;
}

/**
 * Initialize the input subsystem.
 */
VOID PAL_InitInput(VOID)
{
    memset((void *) &g_InputState, 0, sizeof(g_InputState));
    g_InputState.dir = kDirUnknown;
    g_InputState.prevdir = kDirUnknown;

    //
    // Check for joystick
    //
#ifdef PAL_HAS_JOYSTICKS
    if (SDL_NumJoysticks() > 0 && g_fUseJoystick) {
        g_pJoy = SDL_JoystickOpen(0);

        //
        // HACKHACK: applesmc and Android Accelerometer shouldn't be considered as real joysticks
        //
        if (strcmp(SDL_JoystickName(g_pJoy), "applesmc") == 0 || strcmp(SDL_JoystickName(g_pJoy), "Android Accelerometer") == 0) {
            SDL_JoystickClose(g_pJoy);

            if (SDL_NumJoysticks() > 1) {
                g_pJoy = SDL_JoystickOpen(1);
            } else {
                g_pJoy = NULL;
            }
        }

        if (g_pJoy != NULL) {
            SDL_JoystickEventState(SDL_ENABLE);
        }
    }
#endif

#ifdef PAL_ALLOW_KEYREPEAT
    SDL_EnableKeyRepeat(0, 0);
#endif
}

/**
 * Shutdown the input subsystem.
 */
VOID PAL_ShutdownInput(VOID)
{
#ifdef PAL_HAS_JOYSTICKS
#if SDL_VERSION_ATLEAST(2, 0, 0)
    if (g_pJoy != NULL) {
        SDL_JoystickClose(g_pJoy);
        g_pJoy = NULL;
    }
#else
    if (SDL_JoystickOpened(0))
    {
       assert(g_pJoy != NULL);
       SDL_JoystickClose(g_pJoy);
       g_pJoy = NULL;
    }
#endif
#endif
}


/**
 * Process all events.
 */
VOID PAL_ProcessEvent(VOID)
{
#ifdef PAL_HAS_NATIVEMIDI
    MIDI_CheckLoop();
#endif
    while (PAL_PollEvent(NULL));
}

/**
 * Poll and process one event.
 *
 * @param[out] event - Events polled from SDL.
 * @return value of PAL_PollEvent
 */
int PAL_PollEvent(SDL_Event *event)
{
    SDL_Event evt;

    int ret = SDL_PollEvent(&evt);
    if (ret != 0) {
        PAL_EventFilter(&evt);
    }

    if (event != NULL) {
        *event = evt;
    }

    return ret;
}
示例#13
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;
}
示例#14
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);
}
示例#15
0
文件: main.cpp 项目: sub77/hobbycode
int main(int argc, char* argv[])
{
	srand((unsigned int)time(NULL));

	SDL_Init(SDL_INIT_JOYSTICK);
	if(SDL_NumJoysticks() > 0)
	{
		// Setup the joystick.
		std::cout << "========================================" << std::endl;
		std::cout << "Initializing game controller: " << SDL_JoystickName(0) 
			<< std::endl;
		gGamePad = SDL_JoystickOpen(0);
		std::cout << SDL_JoystickNumAxes(gGamePad) << " axes" << std::endl;
		std::cout << SDL_JoystickNumBalls(gGamePad) << " trackballs" << std::endl;
		std::cout << SDL_JoystickNumHats(gGamePad) << " hats" << std::endl;
		std::cout << SDL_JoystickNumButtons(gGamePad) << " buttons" << std::endl;
		std::cout << "========================================" << std::endl;
	}
	else
	{
		std::cout << "========================================" << std::endl;
		std::cout << "No game controller detected" << std::endl;
		std::cout << "========================================" << std::endl;
	}

	//Ogre::Overlay* trialOverlay;

	///// The current amount of elapsed time within a trial.
	//Ogre::Real mCurrentTrialTime;

	///// The length of each trial in seconds.
	//Ogre::Real mTrialLength;

	///// The rewards received during a single trial, in rewards per step.
	//verve::real mAvgRewardPerStep;

	if (!gEngine.init())
	{
		return 0;
	}

	gEngine.setUpdateMode(SimulationEngine::SIMULATE_REAL_TIME_MULTIPLE, 1);

	//// Set to capture frames at 29.97 fps.
	//engine.setUpdateMode(SIMULATE_CONSTANT_CHUNK, 0.0333667);

	// Use feet for this simulation.
	gEngine.getSimulator()->setGravity(opal::Vec3r(0, -30, 0));
	gEngine.getSimulator()->setStepSize(gPhysicsStepSize);

	// Make sure we get notified at the end of each step.
	gEngine.getSimulator()->addPostStepEventHandler(&gPostStepEventHandler);

	// Create the robot.
	opal::Matrix44r robotTransform;
	robotTransform.translate(0, 1, 0);
	gRobot = new Robot(gEngine, 5);
	gRobot->init("../data/blueprints/robot1.xml", "Plastic/LightBlue", 
		0.5, robotTransform, 2);
	gRobot->resetBodyAndCreateNewAgent();
	gRobot->resetBodyAndSTM();
	gRobot->randomizeState();
	gRobot->getFLMotor()->setMaxTorque((opal::real)2);
	gRobot->getFRMotor()->setMaxTorque((opal::real)2);
	gRobot->getFLMotor()->setMaxVelocity(1000);
	gRobot->getFRMotor()->setMaxVelocity(1000);

	// Create the car.
	opal::Matrix44r carTransform;
	carTransform.translate(-12, 2, 4);
	gCar = new Car(gEngine);
	gCar->init("../data/blueprints/car1.xml", "Plastic/Blue", 1, 
		carTransform, 1);

	//DataFile dataFile(mNumTrialsPerRun);
	//updateOverlayData(trial);
	//mAvgRewardPerStep = 0;
	//mCurrentTrialTime = 0;

	gAgentDebugger = new AgentVisualDebugger(gEngine.getSceneManager());
	gAgentDebugger->setAgent(gRobot->getAgent());
	gAgentDebugger->setDisplayEnabled(false);

	Ogre::OverlayManager::getSingleton().getByName("Verve/Debug")->hide();
	Ogre::OverlayManager::getSingleton().getByName("Core/DebugOverlay")->hide();

	// Setup camera.
	gEngine.getCamera()->setPosition(opal::Point3r(0, 25, 25));
	gEngine.getCamera()->lookAt(opal::Point3r(0, (opal::real)0.1, 0));
	gEngine.setCameraMoveSpeed(15);

	setupEnvironment();

	mainLoop();

	delete gRobot;
	delete gCar;
	delete gAgentDebugger;
	return 0;
}
示例#16
0
int main(int argc,char **argv)
{
	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
	// init window and renderer
	// TODO: query the screen and set the resolution based on the screen size.
	SDL_Window *window=SDL_CreateWindow("Super Trump Jump",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,640,384,0);
	World::setWidthHeight(640,384);
	SDL_Renderer *renderer=SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
    World::setRenderer(renderer);
    World::setScale(0.0f);


	// Init joystick
	SDL_Joystick *joy=0;
	if(SDL_NumJoysticks()>0) {
		joy=SDL_JoystickOpen(0);
	}
	if(SDL_NumJoysticks()>1) {
		joy=SDL_JoystickOpen(1);
	}
	if(joy) {
        printf("Joystick activated.\n");
	}

	// Init audio
	Sound::init();

	// Init image loader
	Image::init();

	// Init font loader
	Font::init();

	srand((unsigned int)time(NULL));

	game.init(renderer);

	// TODO calculatre this with acutal time in ms.
	int elapsed=16;
	bool done=false;
	unsigned int old=SDL_GetTicks();
	while(!done) {
		// handle events
		SDL_Event event;

		while(SDL_PollEvent(&event)) {
			// dispatch to game object.
			if(event.type==SDL_QUIT) {
				done=true;
            } else if(event.type==SDL_KEYUP) {
                if(event.key.keysym.sym==27) done=true;
				if(event.key.keysym.sym==' ') {
					game.handleKey(' ',false);
				}
			} else if(event.type==SDL_KEYDOWN) {
				if(event.key.keysym.sym==' ') {
					game.handleKey(' ',true);
				}
			} else if(event.type==SDL_MOUSEBUTTONDOWN) {
				int x=event.button.x;
				int y=event.button.y;
				game.handleButton(x,y,true);
			} else if(event.type==SDL_MOUSEBUTTONUP) {
				int x=event.button.x;
				int y=event.button.y;
				game.handleButton(x,y,false);
			} else if(event.type==SDL_MOUSEMOTION) {
				int x=event.motion.x;
				int y=event.motion.y;
				game.handleMotion(x,y);
			}
		}
		// draw screen
		game.draw(renderer);

        unsigned int now=SDL_GetTicks();
        elapsed=now-old;
        if(elapsed>1000) elapsed=16;
		if(elapsed>0) game.update(elapsed);
        //printf("Elapsed: %d\n",elapsed);

        int delay=(old+16)-now;
        if(delay>0) SDL_Delay(delay);
		// update game state
        old=now;
	}
	SDL_Quit();
	return 0;
}
示例#17
0
文件: cfg.c 项目: Devil084/pcsxr
int ReadAnalogEvent(int padnum, int analognum, int analogdir)
{
	SDL_Joystick *js;
	int i, changed = 0, t;
	Sint16 axis;
	
	if (g.cfg.PadDef[padnum].DevNum >= 0) {
		js = SDL_JoystickOpen(g.cfg.PadDef[padnum].DevNum);
		SDL_JoystickEventState(SDL_IGNORE);
	} else {
		js = NULL;
	}
	
	for (t = 0; t < 1000000 / 1000; t++) {
		// check joystick events
		if (js != NULL) {
			SDL_JoystickUpdate();
			
			for (i = 0; i < SDL_JoystickNumButtons(js); i++) {
				if (SDL_JoystickGetButton(js, i)) {
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].JoyEvType = BUTTON;
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Button = i;
					changed = 1;
					goto end;
				}
			}
			
			for (i = 0; i < NUM_AXES(js); i++) {
				axis = SDL_JoystickGetAxis(js, i);
				if (abs(axis) > 16383 && (abs(axis - PrevAxisPos[i]) > 4096 || abs(axis - InitialAxisPos[i]) > 4096)) {
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].JoyEvType = AXIS;
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Axis = (i + 1) * (axis > 0 ? 1 : -1);
					changed = 1;
					goto end;
				}
				PrevAxisPos[i] = axis;
			}
			
			for (i = 0; i < SDL_JoystickNumHats(js); i++) {
				axis = SDL_JoystickGetHat(js, i);
				if (axis != SDL_HAT_CENTERED) {
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].JoyEvType = HAT;
					
					if (axis & SDL_HAT_UP) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_UP);
					} else if (axis & SDL_HAT_DOWN) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_DOWN);
					} else if (axis & SDL_HAT_LEFT) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_LEFT);
					} else if (axis & SDL_HAT_RIGHT) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_RIGHT);
					}
					
					changed = 1;
					goto end;
				}
			}
		}
		
		// check keyboard events
		i = CheckKeyDown();
		if (i != 0) {
			if (i != (kVK_Escape + 1)) g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].Key = i;
			changed = 1;
			goto end;
		}
		
		// check mouse events
		if (GetCurrentButtonState()) {
			changed = 2;
			goto end;
		}
		
		usleep(1000);
	}
	
end:
	if (js != NULL) {
		SDL_JoystickClose(js);
	}
	
	return changed;
}
示例#18
0
文件: Menu.cpp 项目: it-tommy/gameDev
// run
int Menu::run(){
	int dy = 0;
	js = SDL_JoystickOpen(0);
	bool b1 = glIsEnabled(GL_LIGHTING);
	glDisable(GL_LIGHTING);
	glDisable(GL_DEPTH_TEST);
	glLoadIdentity();
	currentSelection = 0;
	Uint32 start;
	SDL_Event event;
	int MENU_FLAG = 0;
	while(true){
		start = SDL_GetTicks();
		glLoadIdentity();
		glClear(GL_COLOR_BUFFER_BIT);
		test();
		while(SDL_PollEvent(&event)){
			switch(event.type){
				case SDL_KEYDOWN:
					switch(event.key.keysym.sym){
						case SDLK_ESCAPE:
							if(b1)
								glEnable(GL_LIGHTING);
							glColor3f(1,1,1);
							return 1;
							break;
						case SDLK_UP:
							currentSelection--;
							if(currentSelection < 0)
								 currentSelection = planes.size()-1;
							break;
						case SDLK_DOWN:
							currentSelection++;
							if(currentSelection > planes.size() -1)
								currentSelection = 0;
							break;
						case SDLK_RETURN:
							if(b1)
								glEnable(GL_LIGHTING);
							glColor3f(1,1,1);
							return currentSelection;
							break;
						}
						break;
						// Joystick Axis
						case SDL_JOYAXISMOTION:
							dy = SDL_JoystickGetAxis(js, 1);
						    if(event.jaxis.value < -3200 || event.jaxis.value > 3200){
						    	if(event.jaxis.axis == 1){
						    		if(dy <= 1){
										currentSelection--;
										if(currentSelection < 0)
											 currentSelection = planes.size()-1;
										break;
						    		}else{
										currentSelection++;
										if(currentSelection > planes.size() -1)
											currentSelection = 0;
										break;
						    		}
						      }
						   }
						  break;
	                       case SDL_JOYBUTTONDOWN:
	                     	   if (event.jbutton.button == 0){
	                     		  return currentSelection;
	                     	   }
	                       break;
			}
		}
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D,background);
		glColor3f(1,1,1);
		glBegin(GL_QUADS);
			glTexCoord2f(0.0,0.0);
			glVertex3f(backPosition->getPlaneVertex1().x, backPosition->getPlaneVertex1().y, backPosition->getPlaneVertex1().z);
			glTexCoord2f(0.0,1.0);
			glVertex3f(backPosition->getPlaneVertex2().x, backPosition->getPlaneVertex2().y, backPosition->getPlaneVertex2().z);
			glTexCoord2f(1.0,1.0);
			glVertex3f(backPosition->getPlaneVertex3().x, backPosition->getPlaneVertex3().y, backPosition->getPlaneVertex3().z);
			glTexCoord2f(1.0,0.0);
			glVertex3f(backPosition->getPlaneVertex4().x, backPosition->getPlaneVertex4().y, backPosition->getPlaneVertex4().z);
	//		glVertex3f(-1,1,-2);
	//		glVertex3f(-1,-1,-2);
	//		glVertex3f(1,-1,-2);
	//		glVertex3f(1,1,-2);
		glEnd();
		glDisable(GL_TEXTURE_2D);
		std::cout << currentSelection << std::endl;
		for(int i=0;i < planes.size(); i++){
			if(i == currentSelection){
				std::cout << "i n" << std::endl;
				glBegin(GL_QUADS);
					glColor3f(1,0,0);
					glVertex3f(planes[i].getPlaneVertex1().x, planes[i].getPlaneVertex1().y + 0.04, planes[i].getPlaneVertex1().z);
					glColor3f(0,0,0);
					glVertex3f(planes[i].getPlaneVertex1().x, planes[i].getPlaneVertex1().y, planes[0].getPlaneVertex1().z);
					glVertex3f(planes[i].getPlaneVertex1().x +strings[i].length() * 0.032, planes[i].getPlaneVertex1().y, planes[i].getPlaneVertex1().z);
					glColor3f(1,0,0);
					glVertex3f(planes[i].getPlaneVertex1().x + strings[i].length() * 0.032,planes[i].getPlaneVertex1().y + 0.04, planes[i].getPlaneVertex1().z);
				glEnd();
			}
			glColor3f(0,0,0);
			Vector3d texPos(planes[i].getPlaneVertex1().getX() + .01, (planes[i].getPlaneVertex1().getY() + .01), planes[i].getPlaneVertex1().getZ());
			text->drawText(texPos, Vector3d(0, 0, 0), Vector3d(0.035, 0.035, 0.035), strings[i].c_str());
		}
		SDL_GL_SwapBuffers();
		if(1000/30>(SDL_GetTicks() - start))
			SDL_Delay(1000/30-(SDL_GetTicks() - start));
	}
	return 0;
}
示例#19
0
int main(int argc, char* argv[])
{
	ballfield_t	*balls;
	SDL_Surface	*screen;
	SDL_Surface	*temp_image;
	SDL_Surface	*back, *logo, *font, *font_hex;
	SDL_Event	event;
	int		bpp = 32,
			flags = 0,
			alpha = 1;
	int		x_offs = 0, y_offs = 0;
	long		tick,
			last_tick,
			last_avg_tick;
	double		t = 0;
	float		dt;
	int		i;
	float		fps = 0.0;
	int		fps_count = 0;
	int		fps_start = 0;
	float		x_speed, y_speed, z_speed;

	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK);

	atexit(SDL_Quit);

	screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, bpp, flags);
	if(!screen)
	{
		fprintf(stderr, "Failed to open screen!\n");
		exit(-1);
	}

	SDL_WM_SetCaption("Ballfield", "Ballfield");
	if(flags & SDL_FULLSCREEN)
		SDL_ShowCursor(0);

	balls = ballfield_init();
	if(!balls)
	{
		fprintf(stderr, "Failed to create ballfield!\n");
		exit(-1);
	}

	/*
	 * Load and prepare balls...
	 */
	balls->use_alpha = alpha;
	if( ballfield_load_gfx(balls, "blueball.png", 0)
				||
			ballfield_load_gfx(balls, "redball.png", 1) )
	{
		fprintf(stderr, "Could not load balls!\n");
		exit(-1);
	}

	/*
	 * Load background image
	 */
	temp_image = IMG_Load("sun.gif");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load background!\n");
		exit(-1);
	}
	back = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	/*
	 * Load logo
	 */
	temp_image = SDL_LoadBMP("logo.bmp");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load logo!\n");
		exit(-1);
	}
	SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY,
			SDL_MapRGB(temp_image->format, 255, 0, 255));
	logo = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	/*
	 * Load font
	 */
	temp_image = SDL_LoadBMP("font7x10.bmp");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load font!\n");
		exit(-1);
	}
	SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY,
			SDL_MapRGB(temp_image->format, 255, 0, 255));
	font = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	temp_image = SDL_LoadBMP("font7x10-hex.bmp");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load hex font!\n");
		exit(-1);
	}
	SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY,
			SDL_MapRGB(temp_image->format, 255, 0, 255));
	font_hex = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	last_avg_tick = last_tick = SDL_GetTicks();
	
	enum { MAX_POINTERS = 16, PTR_PRESSED = 4 };
	int touchPointers[MAX_POINTERS][5];
	
	memset(touchPointers, 0, sizeof(touchPointers));
	SDL_Joystick * joysticks[MAX_POINTERS+1];
	for(i=0; i<MAX_POINTERS; i++)
		joysticks[i] = SDL_JoystickOpen(i);

	while(1)
	{
		SDL_Rect r;

		/* Timing */
		tick = SDL_GetTicks();
		dt = (tick - last_tick) * 0.001f;
		last_tick = tick;
		
		if( bpp == 32 )
			SDL_FillRect(screen, NULL, 0); // Clear alpha channel

		/* Background image */
		tiled_back(back, screen, x_offs>>11, y_offs>>11);

		/* Ballfield */
		ballfield_render(balls, screen);

		/* Logo */
		r.x = 2;
		r.y = 2;
		SDL_BlitSurface(logo, NULL, screen, &r);

		/* FPS counter */
		if(tick > fps_start + 500)
		{
			fps = (float)fps_count * 1000.0 / (tick - fps_start);
			fps_count = 0;
			fps_start = tick;
		}
		++fps_count;

		for(i=0; i<MAX_POINTERS; i++)
		{
			if( !touchPointers[i][PTR_PRESSED] )
				continue;
			r.x = touchPointers[i][0];
			r.y = touchPointers[i][1];
			r.w = 80 + touchPointers[i][2] / 10; // Pressure
			r.h = 80 + touchPointers[i][3] / 10; // Touch point size
			r.x -= r.w/2;
			r.y -= r.h/2;
			SDL_FillRect(screen, &r, 0xaaaaaa);
			print_num(screen, font, r.x, r.y, i+1);
		}
		int mx, my;
		int b = SDL_GetMouseState(&mx, &my);
		Uint32 color = 0xff;
		if( b )
		{
			color = 0;
			if( b & SDL_BUTTON_LEFT )
				color |= 0xff00;
			if( b & SDL_BUTTON_RIGHT )
				color |= 0xff0000;
		}
		r.x = mx;
		r.y = my;
		r.w = 30;
		r.h = 30;
		r.x -= r.w/2;
		r.y -= r.h/2;
		SDL_FillRect(screen, &r, color);

		SDL_Flip(SDL_GetVideoSurface());
		SDL_Event evt;
		while( SDL_PollEvent(&evt) )
		{
			if(evt.type == SDL_KEYUP || evt.type == SDL_KEYDOWN)
			{
				if(evt.key.keysym.sym == SDLK_ESCAPE)
					return 0;
				__android_log_print(ANDROID_LOG_INFO, "Ballfield", "SDL key event: evt %s state %s key %d scancode %d mod %d unicode %d", evt.type == SDL_KEYUP ? "UP  " : "DOWN" , evt.key.state == SDL_PRESSED ? "PRESSED " : "RELEASED", (int)evt.key.keysym.sym, (int)evt.key.keysym.scancode, (int)evt.key.keysym.mod, (int)evt.key.keysym.unicode);
			}
			if(evt.type == SDL_VIDEORESIZE)
				__android_log_print(ANDROID_LOG_INFO, "Ballfield", "SDL resize event: %d x %d", evt.resize.w, evt.resize.h);
			if(evt.type == SDL_ACTIVEEVENT)
				__android_log_print(ANDROID_LOG_INFO, "Ballfield", "======= SDL active event: gain %d state %d", evt.active.gain, evt.active.state);
			/*
			if( evt.type == SDL_ACTIVEEVENT && evt.active.gain == 0 && evt.active.state & SDL_APPACTIVE )
			{
				// We've lost GL context, we are not allowed to do any GFX output here, or app will crash!
				while( 1 )
				{
					SDL_PollEvent(&evt);
					if( evt.type == SDL_ACTIVEEVENT && evt.active.gain && evt.active.state & SDL_APPACTIVE )
					{
						__android_log_print(ANDROID_LOG_INFO, "Ballfield", "======= SDL active event: gain %d state %d", evt.active.gain, evt.active.state);
						SDL_Flip(SDL_GetVideoSurface()); // One SDL_Flip() call is required here to restore OpenGL context
						// Re-load all textures, matrixes and all other GL states if we're in SDL+OpenGL mode
						// Re-load all images to SDL_Texture if we're using it
						// Now we can draw
						break;
					}
					// Process network stuff, maybe play some sounds using SDL_ANDROID_PauseAudioPlayback() / SDL_ANDROID_ResumeAudioPlayback()
					SDL_Delay(300);
					__android_log_print(ANDROID_LOG_INFO, "Ballfield", "Waiting");
				}
			}
			*/
			if( evt.type == SDL_JOYAXISMOTION )
			{
				if( evt.jaxis.which == 0 ) // 0 = The accelerometer
					continue;
				int joyid = evt.jaxis.which - 1;
				touchPointers[joyid][evt.jaxis.axis] = evt.jaxis.value; // Axis 0 and 1 are coordinates, 2 and 3 are pressure and touch point radius
			}
			if( evt.type == SDL_JOYBUTTONDOWN || evt.type == SDL_JOYBUTTONUP )
			{
				if( evt.jbutton.which == 0 ) // 0 = The accelerometer
					continue;
				int joyid = evt.jbutton.which - 1;
				touchPointers[joyid][PTR_PRESSED] = (evt.jbutton.state == SDL_PRESSED);
			}
		}

		/* Animate */
		x_speed = 500.0 * sin(t * 0.37);
		y_speed = 500.0 * sin(t * 0.53);
		z_speed = 400.0 * sin(t * 0.21);

		ballfield_move(balls, x_speed, y_speed, z_speed);
		x_offs -= x_speed;
		y_offs -= y_speed;

		t += dt;
	}

	ballfield_free(balls);
	SDL_FreeSurface(back);
	SDL_FreeSurface(logo);
	SDL_FreeSurface(font);
	std::ostringstream os;
	os << "lalala" << std::endl << "more text" << std::endl;
	std::cout << os.str() << std::endl << "text text" << std::endl;
	exit(0);
}
示例#20
0
void SDLInteraction::addGameControllerKeys() const
{
    QStringList result;

#if SDL_VERSION_ATLEAST(2, 0, 0)
    int i = 0;
    while(i < 1024 && sdlkeys[i][1][0] != '\0')
        i++;

    // Iterate through all game controllers
    qDebug("Detecting controllers ...");
    for(int jid = 0; jid < SDL_NumJoysticks(); jid++)
    {
        SDL_Joystick* joy = SDL_JoystickOpen(jid);

        // Retrieve the game controller's name
        QString joyname = QString(SDL_JoystickNameForIndex(jid));

        // Strip "Controller (...)" that's added by some drivers (English only)
        joyname.replace(QRegExp("^Controller \\((.*)\\)$"), "\\1");

        qDebug("- Controller no. %d: %s", jid, qPrintable(joyname));

        // Connected Xbox 360 controller? Use specific button names then
        // Might be interesting to add 'named' buttons for the most often used gamepads
        bool isxb = joyname.contains("Xbox 360");

        // This part of the string won't change for multiple keys/hats, so keep it
        QString prefix = QString("%1 (%2): ").arg(joyname).arg(jid + 1);

        // Register entries for missing axes not assigned to sticks of this joystick/gamepad
        for(int aid = 0; aid < SDL_JoystickNumAxes(joy) && i < 1021; aid++)
        {
            QString axis = prefix + HWApplication::translate("binds (keys)", controlleraxis).arg(aid + 1);

            // Entry for "Axis Up"
            sprintf(sdlkeys[i][0], "j%da%du", jid, aid);
            sprintf(sdlkeys[i++][1], "%s", ((isxb && aid < 5) ? (prefix + HWApplication::translate("binds (keys)", xbox360axes[aid * 2])) : (axis.arg(HWApplication::translate("binds (keys)", controllerup)))).toUtf8().constData());

            // Entry for "Axis Down"
            sprintf(sdlkeys[i][0], "j%da%dd", jid, aid);
            sprintf(sdlkeys[i++][1], "%s", ((isxb && aid < 5) ? (prefix + HWApplication::translate("binds (keys)", xbox360axes[aid * 2 + 1])) : (axis.arg(HWApplication::translate("binds (keys)", controllerdown)))).toUtf8().constData());
        }

        // Register entries for all coolie hats of this joystick/gamepad
        for(int hid = 0; hid < SDL_JoystickNumHats(joy) && i < 1019; hid++)
        {
            // Again store the part of the string not changing for multiple uses
            QString hat = prefix + (isxb ? (HWApplication::translate("binds (keys)", xb360dpad) + QString(" ")) : HWApplication::translate("binds (keys)", controllerhat).arg(hid + 1));

            // Entry for "Hat Up"
            sprintf(sdlkeys[i][0], "j%dh%du", jid, hid);
            sprintf(sdlkeys[i++][1], "%s", hat.arg(HWApplication::translate("binds (keys)", controllerup)).toUtf8().constData());

            // Entry for "Hat Down"
            sprintf(sdlkeys[i][0], "j%dh%dd", jid, hid);
            sprintf(sdlkeys[i++][1], "%s", hat.arg(HWApplication::translate("binds (keys)", controllerdown)).toUtf8().constData());

            // Entry for "Hat Left"
            sprintf(sdlkeys[i][0], "j%dh%dl", jid, hid);
            sprintf(sdlkeys[i++][1], "%s", hat.arg(HWApplication::translate("binds (keys)", controllerleft)).toUtf8().constData());

            // Entry for "Hat Right"
            sprintf(sdlkeys[i][0], "j%dh%dr", jid, hid);
            sprintf(sdlkeys[i++][1], "%s", hat.arg(HWApplication::translate("binds (keys)", controllerright)).toUtf8().constData());
        }

        // Register entries for all buttons of this joystick/gamepad
        for(int bid = 0; bid < SDL_JoystickNumButtons(joy) && i < 1022; bid++)
        {
            // Buttons
            sprintf(sdlkeys[i][0], "j%db%d", jid, bid);
            sprintf(sdlkeys[i++][1], "%s", (prefix + ((isxb && bid < 10) ? (HWApplication::translate("binds (keys)", xb360buttons[bid]) + QString(" ")) : HWApplication::translate("binds (keys)", controllerbutton).arg(bid + 1))).toUtf8().constData());
        }
        // Close the game controller as we no longer need it
        SDL_JoystickClose(joy);
    }

    if(i >= 1024)
        i = 1023;

    // Terminate the list
    sdlkeys[i][0][0] = '\0';
    sdlkeys[i][1][0] = '\0';   
#endif
}
示例#21
0
/* Function to open a joystick for use.
   The joystick to open is specified by the index field of the joystick.
   This should fill the nbuttons and naxes fields of the joystick structure.
   It returns 0, or -1 if there is an error.
 */
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
    int fd;
    char *fname;
    SDL_logical_joydecl(int realindex);
    SDL_logical_joydecl(SDL_Joystick * realjoy = NULL);

    /* Open the joystick and set the joystick file descriptor */
#ifndef NO_LOGICAL_JOYSTICKS
    if (SDL_joylist[joystick->index].fname == NULL) {
        SDL_joylist_head(realindex, joystick->index);
        realjoy = SDL_JoystickOpen(realindex);

        if (realjoy == NULL)
            return (-1);

        fd = realjoy->hwdata->fd;
        fname = realjoy->hwdata->fname;

    } else {
        fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0);
        fname = SDL_joylist[joystick->index].fname;
    }
    SDL_joylist[joystick->index].joy = joystick;
#else
    fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0);
    fname = SDL_joylist[joystick->index].fname;
#endif

    if (fd < 0) {
        SDL_SetError("Unable to open %s\n", SDL_joylist[joystick->index]);
        return (-1);
    }
    joystick->hwdata = (struct joystick_hwdata *)
        SDL_malloc(sizeof(*joystick->hwdata));
    if (joystick->hwdata == NULL) {
        SDL_OutOfMemory();
        close(fd);
        return (-1);
    }
    SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
    joystick->hwdata->fd = fd;
    joystick->hwdata->fname = fname;

    /* Set the joystick to non-blocking read mode */
    fcntl(fd, F_SETFL, O_NONBLOCK);

    /* Get the number of buttons and axes on the joystick */
#ifndef NO_LOGICAL_JOYSTICKS
    if (realjoy)
        ConfigLogicalJoystick(joystick);
    else
#endif
#if SDL_INPUT_LINUXEV
    if (!EV_ConfigJoystick(joystick, fd))
#endif
        JS_ConfigJoystick(joystick, fd);

    return (0);
}
示例#22
0
文件: window.c 项目: you-chan/Game
/*****************************************************************
関数名	: InitWindows
機能	: メインウインドウの表示,設定を行う
引数	: なし
出力	: 正常に設定できたとき0,失敗したとき-1
*****************************************************************/
int InitWindow()
{
    int i;
	/* SDLの初期化 */
	if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
		printf("failed to initialize SDL.\n");
		return -1;
	}

	/* 画像の読み込み */
	BRSWindow = IMG_Load(BRSImgFile);
    if(BRSWindow == NULL){
        printf("failed to open BRS image.");
        return -1;
    }

    TitleWindow = IMG_Load(TitleImgFile);
    if(TitleWindow == NULL){
        printf("failed to open title image.");
        return -1;
    }

    for(i=0; i<2; i++){
    	ResultWindow[i] = IMG_Load(ResultImgFile[i]);
    	if(ResultWindow[i] == NULL){
    		printf("failed to open result image.\n");
    		return -1;
    	}
    }

    NumWindow = IMG_Load(NumberImgFile);
    	if(NumWindow == NULL){
        		printf("failed to open num image.");
        		return -1;
        	}

    for(i=0; i < MAX_CT; i++){
		ShipWindow[i] = IMG_Load(ShipImgFile[i % 4]);
		if(ShipWindow[i] == NULL){
			printf("failed to open ship image.");
			return -1;
		}
    }

    for(i=0; i<MAX_BOSS; i++){
    	BossWindow[i] = IMG_Load(BossImgFile[i]);
    	if(BossWindow[i] == NULL){
    		printf("failed to open boss image.");
    		return -1;
    	}
    }

    for(i=0; i<MAX_MOB; i++){
    	MobWindow[i] = IMG_Load(MobImgFile[i]);
    	if(MobWindow[i] == NULL){
    		printf("failed to open mob image.");
    		return -1;
    	}
    }

    GunWindow = IMG_Load(GunImgFile);
    	if(GunWindow == NULL){
    		printf("failed to open gun image.");
    		return -1;
    	}

    ArmorWindow = IMG_Load(ArmorImgFile);
    	if(ArmorWindow == NULL){
    		printf("failed to open armor image.");
    	    return -1;
    	}

    BombWindow = IMG_Load(BombImgFile);
        if(BombWindow == NULL){
        	printf("failed to bomb armor image.");
        	return -1;
        }

    ArrowWindow = IMG_Load(ArrowImgFile);
        if(ArrowWindow == NULL){
        	printf("failed to open arrow image.");
        	return -1;
        }

    ChooseWindow = IMG_Load(ChooseImgFile);
   		if(ChooseWindow == NULL){
    		printf("failed to open choose image.");
    		return -1;
    	}

	CommandWindow = IMG_Load(CommandImgFile);
    if(CommandWindow == NULL){
        printf("failed to open command image.");
        return -1;
    }

	miniCommandWindow = IMG_Load(miniCommandImgFile);
    if(CommandWindow == NULL){
        printf("failed to open minicommand image.");
        return -1;
    }

    InfoWindow = IMG_Load(InfoImgFile);
    	if(InfoWindow == NULL){
        		printf("failed to open info image.");
        		return -1;
        }

	/* メインウインドウの作成 */
	if((gMainWindow = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_SWSURFACE)) == NULL) {
		printf("failed to initialize videomode.\n");
		return -1;
	}
	/* ウインドウのタイトルをセット */
	SDL_WM_SetCaption("BattRoutinShip",NULL);

	// 接続されているジョイスティックの名前を表示
	for(i=0;i<SDL_NumJoysticks();i++){
		if(strcmp(SDL_JoystickName(0), "ST LIS3LV02DL Accelerometer") != 0)
			printf("Connecting %s\n ", SDL_JoystickName(i));
	}

	if(SDL_NumJoysticks() > 0 && strcmp(SDL_JoystickName(0),
										"ST LIS3LV02DL Accelerometer") != 0)
		joystick=SDL_JoystickOpen(0);// ジョイスティックを開く
	SDL_JoystickEventState(SDL_ENABLE);// ジョイスティック関連のイベントを取得可能にする

	/* 背景を白にする */
	SDL_FillRect(gMainWindow,NULL,0xffffff);
	SDL_Flip(gMainWindow);
	return 0;
}
示例#23
0
int
main(int argc, char *argv[])
{
    const char *name;
    int i;
    SDL_Joystick *joystick;

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

    /* Print information about the joysticks */
    printf("There are %d joysticks attached\n", SDL_NumJoysticks());
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        name = SDL_JoystickNameForIndex(i);
        printf("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
        joystick = SDL_JoystickOpen(i);
        if (joystick == NULL) {
            fprintf(stderr, "SDL_JoystickOpen(%d) failed: %s\n", i,
                    SDL_GetError());
        } else {
            char guid[64];
            SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                      guid, sizeof (guid));
            printf("       axes: %d\n", SDL_JoystickNumAxes(joystick));
            printf("      balls: %d\n", SDL_JoystickNumBalls(joystick));
            printf("       hats: %d\n", SDL_JoystickNumHats(joystick));
            printf("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
            printf("instance id: %d\n", SDL_JoystickInstanceID(joystick));
            printf("       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;
#ifdef ANDROID
        joystick = SDL_JoystickOpen(0);
#else
        joystick = SDL_JoystickOpen(atoi(argv[1]));
#endif
        while ( keepGoing ) {
            if (joystick == NULL) {
                if ( !reportederror ) {
                    printf("Couldn't open joystick %d: %s\n", atoi(argv[1]), SDL_GetError());
                    keepGoing = SDL_FALSE;
                    reportederror = SDL_TRUE;
                }
            } else {
                reportederror = SDL_FALSE;
                keepGoing = WatchJoystick(joystick);
                SDL_JoystickClose(joystick);
            }

            joystick = NULL;
            if (keepGoing) {
                printf("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(atoi(argv[1]));
                    break;
                }
            }
        }
    }
    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

#ifdef ANDROID
    exit(0);
#else
    return 0;
#endif
}

#else

int
main(int argc, char *argv[])
{
    fprintf(stderr, "SDL compiled without Joystick support.\n");
    exit(1);
}
示例#24
0
int joy_init()
{
	int i, n;

	if (Joy_inited)
		return 0;

	if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
		mprintf(("Could not initialize joystick\n"));
		return 0;
	}

	// enable event processing of the joystick
	if ( (SDL_JoystickEventState(SDL_ENABLE)) != SDL_ENABLE ) {
		mprintf(("ERROR: Unable to initialize joystick event processing!\n"));
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return 0;
	}

	n = SDL_NumJoysticks();

	if (n < 1) {
		mprintf(("No joysticks found\n"));
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return 0;
	}

	joy_get_caps(n);

	Cur_joystick = os_config_read_uint(NULL, "CurrentJoystick", JOYSTICKID1);

	sdljoy = SDL_JoystickOpen(Cur_joystick);

	if (sdljoy == NULL) {
		mprintf(("Unable to init joystick %d\n", Cur_joystick));
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return 0;
	}

	joy_flush();

	joy_num_sticks = n;

	joy_num_buttons = SDL_JoystickNumButtons(sdljoy);
	joy_num_axes = SDL_JoystickNumAxes(sdljoy);
	joy_num_hats = SDL_JoystickNumHats(sdljoy);

	mprintf(( "\nJoystick INITTED!\n\n" ));
	mprintf(( "Using '%s' as the primary joystick:\n", SDL_JoystickName(SDL_JoystickOpen(Cur_joystick)) ));
	mprintf(( "  Number of axes: %i\n", joy_num_axes ));
	mprintf(( "  Number of buttons: %i\n", joy_num_buttons ));
	mprintf(( "  Number of hats: %i\n", joy_num_hats ));
	mprintf(( "  Number of trackballs: %i\n\n", SDL_JoystickNumBalls(sdljoy) ));

	// Fake a calibration
	if (joy_num_sticks > 0) {
		for (i=0; i<JOY_NUM_AXES; i++) {
			joystick.axis_center[i] = 32768;
			joystick.axis_min[i] = 0;
			joystick.axis_max[i] = 65536;
		}
	}

	// we poll for axis type motion so be sure to ignore that during normal event state polling
	SDL_EventState( SDL_JOYAXISMOTION, SDL_IGNORE );
	SDL_EventState( SDL_JOYBALLMOTION, SDL_IGNORE );

	// we do want to make sure that hat/button presses go through event polling though
	// (should be on by default already, just here as a reminder)
	SDL_EventState( SDL_JOYBUTTONDOWN, SDL_ENABLE );
	SDL_EventState( SDL_JOYBUTTONUP, SDL_ENABLE );
	SDL_EventState( SDL_JOYHATMOTION, SDL_ENABLE );

	Joy_inited = 1;

	return joy_num_sticks;
}
示例#25
0
void GamePadDialog::on_SelectPadBtn_clicked()
{
#if QT_HAS_SDL
	int selectedJoy = -1;
	if(ui->GamePadList->currentItem() == 0)
	{
		return;
	}
	selectedJoy = ui->GamePadList->currentItem()->data(Qt::UserRole).toInt();
	m_joyId = selectedJoy;
	m_joystick = SDL_JoystickOpen(selectedJoy);

	ui->padValues->clear();
	ui->padValues->setColumnCount(3);
	ui->padValues->setColumnWidth(0,100);
	ui->padValues->setColumnWidth(1,50);
	ui->padValues->setColumnWidth(2,50);

	ui->comboPadInput->clear();
	ui->comboPSPButton->clear();

	QTreeWidgetItem* buttonItem = new QTreeWidgetItem();
	buttonItem->setText(0,tr("Buttons"));
	ui->padValues->addTopLevelItem(buttonItem);

	for(int i = 0; i < SDL_JoystickNumButtons(m_joystick); i++)
	{
		QTreeWidgetItem* item = new QTreeWidgetItem();
		item->setText(0,QVariant(i).toString());
		item->setText(1,QVariant(0).toString());
		item->setData(0, Qt::UserRole,0);
		item->setData(0, Qt::UserRole+1,i);
		item->setData(0, Qt::UserRole+2,0);
		buttonItem->addChild(item);

		int id = i << 8;
		ui->comboPadInput->addItem(tr("Button %1").arg(i),GetIntFromMapping(i,0,0));
	}
	QTreeWidgetItem* axesItem = new QTreeWidgetItem();
	axesItem->setText(0,tr("Axes"));
	ui->padValues->addTopLevelItem(axesItem);

	for(int i = 0; i < SDL_JoystickNumAxes(m_joystick); i++)
	{
		QTreeWidgetItem* item = new QTreeWidgetItem();
		item->setText(0,tr("%1 Neg").arg(i));
		item->setText(1,QVariant(0).toString());
		item->setData(0, Qt::UserRole,1);
		item->setData(0, Qt::UserRole+1,i);
		item->setData(0, Qt::UserRole+2,-1);
		axesItem->addChild(item);

		ui->comboPadInput->addItem(tr("Axes %1 Neg").arg(i),GetIntFromMapping(i,1,-1));

		item = new QTreeWidgetItem();
		item->setText(0,tr("%1 Pos").arg(i));
		item->setText(1,QVariant(0).toString());
		item->setData(0, Qt::UserRole,1);
		item->setData(0, Qt::UserRole+1,i);
		item->setData(0, Qt::UserRole+2,1);
		axesItem->addChild(item);

		ui->comboPadInput->addItem(tr("Axes %1 Pos").arg(i),GetIntFromMapping(i,1,1));
	}

	QTreeWidgetItem* hatsItem = new QTreeWidgetItem();
	hatsItem->setText(0,tr("Hats"));
	ui->padValues->addTopLevelItem(hatsItem);

	for(int i = 0; i < SDL_JoystickNumHats(m_joystick); i++)
	{
		QTreeWidgetItem* item = new QTreeWidgetItem();
		item->setText(0,QVariant(i).toString());
		item->setText(1,QVariant(0).toString());
		item->setData(0, Qt::UserRole,2);
		item->setData(0, Qt::UserRole+1,i);
		item->setData(0, Qt::UserRole+2,0);
		hatsItem->addChild(item);

		ui->comboPadInput->addItem(tr("Button %1").arg(i),GetIntFromMapping(i,2,0));
	}

	for(int i = 0; i < 18; i++)
	{
		if(GamepadPadMapping[i].Name != "")
		{
			ui->comboPSPButton->addItem(QApplication::translate("gamepadMapping", GamepadPadMapping[i].Name.toStdString().c_str()),i);
		}
	}

	SetViewMode();
#endif
}
示例#26
0
bool PrintSystemInformation() {
	printf("\n===== System Information\n");

	// Initialize SDL and its subsystems and make sure it shutdowns properly on exit
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0) {
		cerr << "ERROR: Unable to initialize SDL: " << SDL_GetError() << endl;
		return false;
	}
	atexit(SDL_Quit);

	printf("SDL version (compiled):  %d.%d.%d\n", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL);
	printf("SDL version (linked):    %d.%d.%d\n", SDL_Linked_Version()->major, SDL_Linked_Version()->minor, SDL_Linked_Version()->patch);

	SDL_Joystick *js_test;
	int32 js_num = SDL_NumJoysticks();
	printf("Number of joysticks found:  %d\n", js_num);

	// Print out information about each joystick
	for (int32 i = 0; i < js_num; i++) {
		printf("  Joystick #%d\n", i);
		printf("    Joystick Name: %s\n", SDL_JoystickName(i));
		js_test = SDL_JoystickOpen(i);
		if (js_test == NULL)
			printf("    ERROR: SDL was unable to open joystick #%d!\n", i);
		else {
			printf("    Number Axes: %d\n", SDL_JoystickNumAxes(js_test));
			printf("    Number Buttons: %d\n", SDL_JoystickNumButtons(js_test));
			printf("    Number Trackballs: %d\n", SDL_JoystickNumBalls(js_test));
			printf("    Number Hat Switches: %d\n", SDL_JoystickNumHats(js_test));
			SDL_JoystickClose(js_test);
		}
	}

	printf("\n===== Video Information\n");

	// TODO: This code should be re-located to a function (DEBUG_PrintInfo()) in the video engine
// 	hoa_video::VideoManager = hoa_video::VideoEngine::SingletonCreate();
// 	if (hoa_video::VideoManager->SingletonInitialize() == false) {
// 		cerr << "ERROR: unable to initialize the VideoManager" << endl;
// 		return false;
// 	}
// 	else {
// 		hoa_video::VideoManager->DEBUG_PrintInfo();
// 	}
// 	hoa_video::VideoEngine::SingletonDestroy();

	// TODO: print the OpenGL version number here

	printf("SDL_ttf version (compiled): %d.%d.%d\n", SDL_TTF_MAJOR_VERSION, SDL_TTF_MINOR_VERSION, SDL_TTF_PATCHLEVEL);
	// printf("SDL_ttf version (linked):   %d.%d.%d\n", Ttf_Linked_Version()->major, Ttf_Linked_Version()->minor, Ttf_Linked_Version()->patch);

	char video_driver[80];
	SDL_VideoDriverName(video_driver, 80);
	printf("Name of video driver: %s\n", video_driver);

	const SDL_VideoInfo *user_video;
	user_video = SDL_GetVideoInfo(); // Get information about the user's video system
	cout << "  Best available video mode" << endl;
	cout << "    Creates hardware surfaces: ";
	if (user_video->hw_available == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Has window manager available: ";
	if (user_video->wm_available == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Hardware to hardware blits accelerated: ";
	if (user_video->blit_hw == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Hardware to hardware colorkey blits accelerated: ";
	if (user_video->blit_hw_CC == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Hardware to hardware alpha blits accelerated: ";
	if (user_video->blit_hw_A == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Software to hardware blits acceleerated: ";
	if (user_video->blit_sw == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Software to hardware colorkey blits accelerated: ";
	if (user_video->blit_sw_CC == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Software to hardware alpha blits accelerated: ";
	if (user_video->blit_sw_A == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Color fills accelerated: ";
	if (user_video->blit_fill == 1)
		cout << "yes\n";
	else
		cout << "no\n";
	cout << "    Total video memory: " << user_video->video_mem << " kilobytes" << endl;
	// cout << "    Best pixel format: " << user_video->vfmt << endl;

	printf("\n===== Audio Information\n");

	hoa_audio::AudioManager = hoa_audio::AudioEngine::SingletonCreate();
	if (hoa_audio::AudioManager->SingletonInitialize() == false) {
		cerr << "ERROR: unable to initialize the AudioManager" << endl;
		return false;
	}
	else {
		hoa_audio::AudioManager->DEBUG_PrintInfo();
	}
	hoa_audio::AudioEngine::SingletonDestroy();

	printf("\n");

	return true;
} // bool PrintSystemInformation()
示例#27
0
文件: sdl.c 项目: Pickle/yquake2
/*
 * Initializes the backend
 */
void
IN_Init(void)
{
	Com_Printf("------- input initialization -------\n");

	mouse_x = mouse_y = 0;
	joystick_yaw = joystick_pitch = joystick_forwardmove = joystick_sidemove = 0;

	exponential_speedup = Cvar_Get("exponential_speedup", "0", CVAR_ARCHIVE);
	freelook = Cvar_Get("freelook", "1", 0);
	in_grab = Cvar_Get("in_grab", "2", CVAR_ARCHIVE);
	lookstrafe = Cvar_Get("lookstrafe", "0", 0);
	m_filter = Cvar_Get("m_filter", "0", CVAR_ARCHIVE);
	m_up = Cvar_Get("m_up", "1", 0);
	m_forward = Cvar_Get("m_forward", "1", 0);
	m_pitch = Cvar_Get("m_pitch", "0.022", 0);
	m_side = Cvar_Get("m_side", "0.8", 0);
	m_yaw = Cvar_Get("m_yaw", "0.022", 0);
	sensitivity = Cvar_Get("sensitivity", "3", 0);

	joy_haptic_magnitude = Cvar_Get("joy_haptic_magnitude", "0.0", CVAR_ARCHIVE);

	joy_yawsensitivity = Cvar_Get("joy_yawsensitivity", "1.0", CVAR_ARCHIVE);
	joy_pitchsensitivity = Cvar_Get("joy_pitchsensitivity", "1.0", CVAR_ARCHIVE);
	joy_forwardsensitivity = Cvar_Get("joy_forwardsensitivity", "1.0", CVAR_ARCHIVE);
	joy_sidesensitivity = Cvar_Get("joy_sidesensitivity", "1.0", CVAR_ARCHIVE);
	joy_upsensitivity = Cvar_Get("joy_upsensitivity", "1.0", CVAR_ARCHIVE);

	joy_axis_leftx = Cvar_Get("joy_axis_leftx", "sidemove", CVAR_ARCHIVE);
	joy_axis_lefty = Cvar_Get("joy_axis_lefty", "forwardmove", CVAR_ARCHIVE);
	joy_axis_rightx = Cvar_Get("joy_axis_rightx", "yaw", CVAR_ARCHIVE);
	joy_axis_righty = Cvar_Get("joy_axis_righty", "pitch", CVAR_ARCHIVE);
	joy_axis_triggerleft = Cvar_Get("joy_axis_triggerleft", "triggerleft", CVAR_ARCHIVE);
	joy_axis_triggerright = Cvar_Get("joy_axis_triggerright", "triggerright", CVAR_ARCHIVE);

	joy_axis_leftx_threshold = Cvar_Get("joy_axis_leftx_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_lefty_threshold = Cvar_Get("joy_axis_lefty_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_rightx_threshold = Cvar_Get("joy_axis_rightx_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_righty_threshold = Cvar_Get("joy_axis_righty_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_triggerleft_threshold = Cvar_Get("joy_axis_triggerleft_threshold", "0.15", CVAR_ARCHIVE);
	joy_axis_triggerright_threshold = Cvar_Get("joy_axis_triggerright_threshold", "0.15", CVAR_ARCHIVE);

	vid_fullscreen = Cvar_Get("vid_fullscreen", "0", CVAR_ARCHIVE);
	windowed_mouse = Cvar_Get("windowed_mouse", "1", CVAR_USERINFO | CVAR_ARCHIVE);

	Cmd_AddCommand("+mlook", IN_MLookDown);
	Cmd_AddCommand("-mlook", IN_MLookUp);

	SDL_StartTextInput();

	/* Joystick init */
	if (!SDL_WasInit(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC))
	{
		if (SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) == -1)
		{
			Com_Printf ("Couldn't init SDL joystick: %s.\n", SDL_GetError ());
		}
		else
		{
			Com_Printf ("%i joysticks were found.\n", SDL_NumJoysticks());

			if (SDL_NumJoysticks() > 0) {
				for (int i = 0; i < SDL_NumJoysticks(); i++) {
					joystick = SDL_JoystickOpen(i);

					Com_Printf ("The name of the joystick is '%s'\n", SDL_JoystickName(joystick));
					Com_Printf ("Number of Axes: %d\n", SDL_JoystickNumAxes(joystick));
					Com_Printf ("Number of Buttons: %d\n", SDL_JoystickNumButtons(joystick));
					Com_Printf ("Number of Balls: %d\n", SDL_JoystickNumBalls(joystick));
					Com_Printf ("Number of Hats: %d\n", SDL_JoystickNumHats(joystick));

					joystick_haptic = SDL_HapticOpenFromJoystick(joystick);

					if (joystick_haptic == NULL)
					{
						Com_Printf("Most likely joystick isn't haptic\n");
					}
					else
					{
						IN_Haptic_Effects_Info();
					}

					if(SDL_IsGameController(i))
					{
						SDL_GameControllerButtonBind backBind;
						controller = SDL_GameControllerOpen(i);

						Com_Printf ("Controller settings: %s\n", SDL_GameControllerMapping(controller));
						Com_Printf ("Controller axis: \n");
						Com_Printf (" * leftx = %s\n", joy_axis_leftx->string);
						Com_Printf (" * lefty = %s\n", joy_axis_lefty->string);
						Com_Printf (" * rightx = %s\n", joy_axis_rightx->string);
						Com_Printf (" * righty = %s\n", joy_axis_righty->string);
						Com_Printf (" * triggerleft = %s\n", joy_axis_triggerleft->string);
						Com_Printf (" * triggerright = %s\n", joy_axis_triggerright->string);

						Com_Printf ("Controller thresholds: \n");
						Com_Printf (" * leftx = %f\n", joy_axis_leftx_threshold->value);
						Com_Printf (" * lefty = %f\n", joy_axis_lefty_threshold->value);
						Com_Printf (" * rightx = %f\n", joy_axis_rightx_threshold->value);
						Com_Printf (" * righty = %f\n", joy_axis_righty_threshold->value);
						Com_Printf (" * triggerleft = %f\n", joy_axis_triggerleft_threshold->value);
						Com_Printf (" * triggerright = %f\n", joy_axis_triggerright_threshold->value);

						backBind = SDL_GameControllerGetBindForButton(controller, SDL_CONTROLLER_BUTTON_BACK);

						if (backBind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
						{
							back_button_id = backBind.value.button;
							Com_Printf ("\nBack button JOY%d will be unbindable.\n", back_button_id+1);
						}

						break;
					}
					else
					{
						char joystick_guid[256] = {0};

						SDL_JoystickGUID guid;
						guid = SDL_JoystickGetDeviceGUID(i);

						SDL_JoystickGetGUIDString(guid, joystick_guid, 255);

						Com_Printf ("To use joystick as game controller please set SDL_GAMECONTROLLERCONFIG:\n");
						Com_Printf ("e.g.: SDL_GAMECONTROLLERCONFIG='%s,%s,leftx:a0,lefty:a1,rightx:a2,righty:a3,back:b1,...\n", joystick_guid, SDL_JoystickName(joystick));
					}
				}
			}
			else
			{
				joystick_haptic = SDL_HapticOpenFromMouse();

				if (joystick_haptic == NULL)
				{
					Com_Printf("Most likely mouse isn't haptic\n");
				}
				else
				{
					IN_Haptic_Effects_Info();
				}
			}
		}
	}

	Com_Printf("------------------------------------\n\n");
}
示例#28
0
文件: joystick.hpp 项目: Rapptz/gum
 joystick(int index = 0): ptr(SDL_JoystickOpen(index)) {
     if(ptr == nullptr) {
         GUM_ERROR_HANDLER_VOID();
     }
 }
示例#29
0
int
main(int argc, char *argv[])
{

    SDL_Window *window;         /* main window */
    SDL_Renderer *renderer;
    Uint32 startFrame;          /* time frame began to process */
    Uint32 endFrame;            /* time frame ended processing */
    Sint32 delay;               /* time to pause waiting to draw next frame */
    int done;                   /* should we clean up and exit? */
    int w, h;

    /* initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        fatalError("Could not initialize SDL");
    }

    /* create main window and renderer */
    window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT,
                                SDL_WINDOW_OPENGL |
                                SDL_WINDOW_FULLSCREEN);
    renderer = SDL_CreateRenderer(window, 0, 0);
    
    SDL_GetWindowSize(window, &w, &h);

    /* print out some info about joysticks and try to open accelerometer for use */
    printf("There are %d joysticks available\n", SDL_NumJoysticks());
    printf("Default joystick (index 0) is %s\n", SDL_JoystickName(0));
    accelerometer = SDL_JoystickOpen(0);
    if (accelerometer == NULL) {
        fatalError("Could not open joystick (accelerometer)");
    }
    printf("joystick number of axis = %d\n",
           SDL_JoystickNumAxes(accelerometer));
    printf("joystick number of hats = %d\n",
           SDL_JoystickNumHats(accelerometer));
    printf("joystick number of balls = %d\n",
           SDL_JoystickNumBalls(accelerometer));
    printf("joystick number of buttons = %d\n",
           SDL_JoystickNumButtons(accelerometer));

    /* load graphics */
    initializeTextures(renderer);

    /* setup ship */
    shipData.x = (w - shipData.rect.w) / 2;
    shipData.y = (h - shipData.rect.h) / 2;
    shipData.vx = 0.0f;
    shipData.vy = 0.0f;

    done = 0;
    /* enter main loop */
    while (!done) {
        SDL_Event event;
        startFrame = SDL_GetTicks();
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                done = 1;
            }
        }
        render(renderer, w, h);
        endFrame = SDL_GetTicks();

        /* figure out how much time we have left, and then sleep */
        delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame);
        if (delay < 0) {
            delay = 0;
        } else if (delay > MILLESECONDS_PER_FRAME) {
            delay = MILLESECONDS_PER_FRAME;
        }
        SDL_Delay(delay);
    }

    /* delete textures */
    SDL_DestroyTexture(ship);
    SDL_DestroyTexture(space);

    /* shutdown SDL */
    SDL_Quit();

    return 0;

}
示例#30
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);
}