当前位置: 首页>>代码示例>>C++>>正文


C++ SDL_JoystickOpen函数代码示例

本文整理汇总了C++中SDL_JoystickOpen函数的典型用法代码示例。如果您正苦于以下问题:C++ SDL_JoystickOpen函数的具体用法?C++ SDL_JoystickOpen怎么用?C++ SDL_JoystickOpen使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了SDL_JoystickOpen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: detect_joypad

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;
}
开发者ID:sigt44,项目名称:ravage-sdl,代码行数:69,代码来源:INPUT.CPP

示例2: startUp


//.........这里部分代码省略.........
		// 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);
开发者ID:AlisterT,项目名称:openjazz,代码行数:67,代码来源:main.cpp

示例3: IN_InitJoystick

/*
===============
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);
}
开发者ID:metivett,项目名称:OpenJK,代码行数:69,代码来源:sdl_input.cpp

示例4: SDLInit


//.........这里部分代码省略.........
            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 "";
}
开发者ID:The-Mad-Pirate,项目名称:lobster,代码行数:101,代码来源:sdlsystem.cpp

示例5: HandleGamepad

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]);
	}
}
开发者ID:bart9h,项目名称:meritous,代码行数:62,代码来源:gamepad.c

示例6: SDLGui_DoDialog


//.........这里部分代码省略.........
	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)
开发者ID:r-type,项目名称:hatari,代码行数:67,代码来源:sdlgui.c

示例7: main


//.........这里部分代码省略.........
      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);
开发者ID:manolaz,项目名称:Wizznic,代码行数:67,代码来源:main.c

示例8: IN_InitJoystick

/*
===============
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");
    }
}
开发者ID:Kangz,项目名称:Unvanquished,代码行数:79,代码来源:sdl_input.cpp

示例9: WinCreate

//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;
};
开发者ID:Tearlach,项目名称:Cataclysm-DDA,代码行数:71,代码来源:sdltiles.cpp

示例10: printf

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;
}
开发者ID:nbu-gamedev,项目名称:spacewar-2014,代码行数:82,代码来源:World.cpp

示例11: gfctrlJoyInit

// 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
//.........这里部分代码省略.........
开发者ID:rongzhou,项目名称:speed-dreams,代码行数:101,代码来源:control.cpp

示例12: PAL_JoystickEventFilter


//.........这里部分代码省略.........
    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)
开发者ID:neonmori,项目名称:sdlpalX,代码行数:67,代码来源:input.c

示例13: sal_Input

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 );
            }
        }
    }
//.........这里部分代码省略.........
开发者ID:DavidKnight247,项目名称:PocketSNES,代码行数:101,代码来源:sal.c

示例14: SDL_GameControllerOpen

/*
 * 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);
}
开发者ID:abakobo,项目名称:monkey2,代码行数:77,代码来源:SDL_gamecontroller.c

示例15: main

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;
}
开发者ID:sub77,项目名称:hobbycode,代码行数:100,代码来源:main.cpp


注:本文中的SDL_JoystickOpen函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。