Пример #1
0
/**
 * @brief Enable and disable screensaver while checking state
 */
int
video_enableDisableScreensaver(void *arg)
{
	SDL_bool initialResult;
	SDL_bool result;

	/* Get current state and proceed according to current state */
	initialResult = SDL_IsScreenSaverEnabled();
	SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");	
	if (initialResult == SDL_TRUE) {
	
	  /* Currently enabled: disable first, then enable again */
	  
	  /* Disable screensaver and check */	
	  SDL_DisableScreenSaver();
	  SDLTest_AssertPass("Call to SDL_DisableScreenSaver()");	
	  result = SDL_IsScreenSaverEnabled();
	  SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
	  SDLTest_AssertCheck(result == SDL_FALSE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_FALSE, result);
	
	  /* Enable screensaver and check */	
	  SDL_EnableScreenSaver();
	  SDLTest_AssertPass("Call to SDL_EnableScreenSaver()");
	  result = SDL_IsScreenSaverEnabled();
	  SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
	  SDLTest_AssertCheck(result == SDL_TRUE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_TRUE, result);

	} else {

	  /* Currently disabled: enable first, then disable again */
	  
	  /* Enable screensaver and check */	
	  SDL_EnableScreenSaver();
	  SDLTest_AssertPass("Call to SDL_EnableScreenSaver()");
	  result = SDL_IsScreenSaverEnabled();
	  SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
	  SDLTest_AssertCheck(result == SDL_TRUE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_TRUE, result);

	  /* Disable screensaver and check */	
	  SDL_DisableScreenSaver();
	  SDLTest_AssertPass("Call to SDL_DisableScreenSaver()");	
	  result = SDL_IsScreenSaverEnabled();
	  SDLTest_AssertPass("Call to SDL_IsScreenSaverEnabled()");
	  SDLTest_AssertCheck(result == SDL_FALSE, "Verify result from SDL_IsScreenSaverEnabled, expected: %i, got: %i", SDL_FALSE, result);	
	}	
	
	return TEST_COMPLETED;
}
Пример #2
0
void Window::setDisplaySleepEnabled(bool enable)
{
	if (enable)
		SDL_EnableScreenSaver();
	else
		SDL_DisableScreenSaver();
}
Пример #3
0
/**
 * @return whether window initialization succeeded
 * @param title char* string with window title
 *
 * Initializes the game window
 */
bool SpringApp::InitWindow(const char* title)
{
	// SDL will cause a creation of gpu-driver thread that will clone its name from the starting threads (= this one = mainthread)
	Threading::SetThreadName("gpu-driver");

	// the crash reporter should be catching errors, not SDL
	if ((SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) == -1)) {
		LOG_L(L_FATAL, "Could not initialize SDL: %s", SDL_GetError());
		return false;
	}

	PrintAvailableResolutions();
	SDL_DisableScreenSaver();

	if (!CreateSDLWindow(title)) {
		LOG_L(L_FATAL, "Failed to set SDL video mode: %s", SDL_GetError());
		return false;
	}

	if (cmdline->IsSet("minimise")) {
		SDL_HideWindow(window);
	}

	// anyone other thread spawned from the main-process should be `unknown`
	Threading::SetThreadName("unknown");
	return true;
}
Пример #4
0
/******************************************************************************
 * Fullscreen management
******************************************************************************/
void display::setFullscreen(bool fs) {
    if (fs == true) {
        SDL_SetWindowFullscreen(pWindow, SDL_WINDOW_FULLSCREEN);
        SDL_DisableScreenSaver();
    }
    else {
        SDL_SetWindowFullscreen(pWindow, 0);
        SDL_EnableScreenSaver();
    }
}
Пример #5
0
	bool System::SetAllowScreenTimeout (bool allow) {
		
		if (allow) {
			
			SDL_EnableScreenSaver ();
			
		} else {
			
			SDL_DisableScreenSaver ();
			
		}
		
		return allow;
		
	}
Пример #6
0
static void
SetupScreenSaver(int flags)
{
    const char *env;
    SDL_bool allow_screensaver;

    /* Allow environment override of screensaver disable */
    env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
    if (env) {
        allow_screensaver = SDL_atoi(env) ? SDL_TRUE : SDL_FALSE;
    } else if (flags & SDL_FULLSCREEN) {
        allow_screensaver = SDL_FALSE;
    } else {
        allow_screensaver = SDL_TRUE;
    }
    if (allow_screensaver) {
        SDL_EnableScreenSaver();
    } else {
        SDL_DisableScreenSaver();
    }
}
Пример #7
0
int PL_Window_Init(void) {
    const char *windowTitle = s_windowTitle;
    if (windowTitle == NULL) {
        windowTitle = "DxPortLib App";
    }
    s_windowFlags |= 
        SDL_WINDOW_OPENGL |
        SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS;
    
    s_window = SDL_CreateWindow(
        windowTitle,
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        PL_windowWidth, PL_windowHeight,
        s_windowFlags
        );
    
    if (s_windowIcon != NULL) {
        SDL_SetWindowIcon(s_window, s_windowIcon);
    }
    
    SDL_ShowWindow(s_window);
    
    SDL_DisableScreenSaver();
    
    PL_Draw_Init(s_window, PL_windowWidth, PL_windowHeight, s_windowVSync);
    
    s_windowRealWidth = 0;
    s_windowRealHeight = 0;
    
    s_initialized = DXTRUE;
    
    SDL_ShowCursor(s_mouseVisible);
    PL_Window_Refresh();
    
    return 0;
}
Пример #8
0
bool Window::initialize()
{
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_EVENTS) != 0)
	{
		Log::instance()->logError("Unable to initialize SDL\n%s", SDL_GetError());

		return	false;
	}

	const GameHeader&	gameHeader	= System::getGameHeader();
	
	bool	bFullscreen	= gameHeader.bFullScreen;

	if (true == bFullscreen)
	{
		SDL_DisplayMode	displayMode;

		if (SDL_GetCurrentDisplayMode(0, &displayMode) != 0)
		{
			Log::instance()->logError("Unable to get current display mode\n%s", SDL_GetError());
			
			return	false;
		}

		m_iWidth	= displayMode.w;
		m_iHeight	= displayMode.h;
	}

	else
	{
		m_iWidth	= gameHeader.iWindowedWidth;
		m_iHeight	= gameHeader.iWindowedHeight;
	}

	int	iFlags	= SDL_WINDOW_OPENGL;
	
	if (true == gameHeader.bFullScreen)
	{
		iFlags	|= SDL_WINDOW_FULLSCREEN_DESKTOP;
	}
	
	else
	{
		iFlags	|= SDL_WINDOW_RESIZABLE;
	}

	if (SDL_CreateWindowAndRenderer(m_iWidth, m_iHeight, iFlags, &m_pWindow, &m_pRenderer) != 0)
	{
		Log::instance()->logError("Unable to create windows and renderer\n%s", SDL_GetError());
			
		return	false;
	}

	if (false == checkRenderer())
	{
		return	false;
	}

	if (true == bFullscreen)
	{
		showMouse(false);
	}

	SDL_SetWindowTitle(m_pWindow, gameHeader.strAppName.c_str());

	// Create app icon
	Image*	pImage	= Image::create("AppIcon.png");

	if (pImage != NULL)
	{
		SDL_Surface*	pIconSurface	= SDL_CreateRGBSurfaceFrom(pImage->getPixels(), pImage->getWidth(), pImage->getHeight(), 32, 
			pImage->getWidth() * 4, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);

		if (pIconSurface != NULL)
		{
			SDL_SetWindowIcon(m_pWindow, pIconSurface);

			SDL_FreeSurface(pIconSurface);
		}
	
		delete	pImage;
	}

	SDL_DisableScreenSaver();

	return	true;
}
Пример #9
0
void init_sdl() {
	SDL_version sdl_compiled_version, sdl_linked_version;
	SDL_VERSION(&sdl_compiled_version);
	SDL_GetVersion(&sdl_linked_version);
	printf("Using SDL backend. Compiled against SDL %d.%d.%d, linked to SDL %d.%d.%d.\n",
			sdl_compiled_version.major, sdl_compiled_version.minor, sdl_compiled_version.patch,
			sdl_linked_version.major, sdl_linked_version.minor, sdl_linked_version.patch);

	// SDL and video

	// Make this configurable later
	SDL_DisableScreenSaver();

	fail_if(SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) != 0,
			"failed to initialize SDL: %s", SDL_GetError());

	fail_if(!(screen =
				SDL_CreateWindow(
					"Nesalizer",
					SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
					640, 480,
					SDL_WINDOW_RESIZABLE)),
			"failed to create window: %s", SDL_GetError());

	fail_if(!(renderer = SDL_CreateRenderer(screen, -1, 0)),
			"failed to create rendering context: %s", SDL_GetError());
	SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");

	// Display some information about the renderer
	SDL_RendererInfo renderer_info;
	if (SDL_GetRendererInfo(renderer, &renderer_info))
		puts("Failed to get renderer information from SDL");
	else {
		if (renderer_info.name)
			printf("renderer: uses renderer \"%s\"\n", renderer_info.name);
		if (renderer_info.flags & SDL_RENDERER_SOFTWARE)
			puts("renderer: uses software rendering");
		if (renderer_info.flags & SDL_RENDERER_ACCELERATED)
			puts("renderer: uses hardware-accelerated rendering");
		if (renderer_info.flags & SDL_RENDERER_PRESENTVSYNC)
			puts("renderer: uses vsync");
		if (renderer_info.flags & SDL_RENDERER_TARGETTEXTURE)
			puts("renderer: supports rendering to texture");
		printf("renderer: available texture formats:");
		unsigned const n_texture_formats = min(16u, (unsigned)renderer_info.num_texture_formats);
		for (unsigned i = 0; i < n_texture_formats; ++i)
			printf(" %s", SDL_GetPixelFormatName(renderer_info.texture_formats[i]));
		putchar('\n');
	}

	fail_if(!(screen_tex =
				SDL_CreateTexture(
					renderer,
					// SDL takes endianess into account, so this becomes GL_RGBA8
					// internally on little-endian systems
					SDL_PIXELFORMAT_ARGB8888,
					SDL_TEXTUREACCESS_STREAMING,
					256, 240)),
			"failed to create texture for screen: %s", SDL_GetError());

	static Uint32 render_buffers[2][240*256];
	back_buffer  = render_buffers[0];
	front_buffer = render_buffers[1];

	// Audio

	SDL_AudioSpec want;
	SDL_zero(want);
	want.freq     = sample_rate;
	want.format   = AUDIO_S16SYS;
	want.channels = 1;
	want.samples  = sdl_audio_buffer_size;
	want.callback = audio_callback;

	fail_if(!(audio_device_id = SDL_OpenAudioDevice(0, 0, &want, 0, 0)),
			"failed to initialize audio: %s\n", SDL_GetError());

	// Input

	// We use SDL_GetKey/MouseState() instead
	SDL_EventState(SDL_KEYDOWN        , SDL_IGNORE);
	SDL_EventState(SDL_KEYUP          , SDL_IGNORE);
	SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_IGNORE);
	SDL_EventState(SDL_MOUSEBUTTONUP  , SDL_IGNORE);
	SDL_EventState(SDL_KEYUP          , SDL_IGNORE);
	SDL_EventState(SDL_MOUSEMOTION    , SDL_IGNORE);

	// Ignore window events for now
	//SDL_EventState(SDL_WINDOWEVENT, SDL_IGNORE);

	keys = SDL_GetKeyboardState(0);

	// SDL thread synchronization

	fail_if(!(event_lock = SDL_CreateMutex()),
			"failed to create event mutex: %s", SDL_GetError());

	fail_if(!(frame_lock = SDL_CreateMutex()),
			"failed to create frame mutex: %s", SDL_GetError());
	fail_if(!(frame_available_cond = SDL_CreateCond()),
			"failed to create frame condition variable: %s", SDL_GetError());
}
Пример #10
0
/*virtual*/ void Framework3D::Initialize()
{
	XTRACE_FUNCTION;

	m_IsInitializing = true;

#if BUILD_SDL
	const int Error = SDL_Init( SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS | SDL_INIT_NOPARACHUTE );
	ASSERT( 0 == Error );
	Unused( Error );
	if( 0 != Error )
	{
		PRINTF( "SDL_Init: %s\n", SDL_GetError() );
	}

	SDL_DisableScreenSaver();
#endif

	STATICHASH( Framework );

#if BUILD_WINDOWS
#if BUILD_FINAL
	STATICHASH( ShowConsole );
	const bool ShowConsole = ConfigManager::GetBool( sShowConsole, false, sFramework );
	if( ShowConsole )
#endif
	{
		Console::GetInstance()->SetPos( 0, 0 );
	}
#endif

	STATICHASH( UseRandomSeed );
	const bool UseRandomSeed = ConfigManager::GetBool( sUseRandomSeed, false, sFramework );

	STATICHASH( RandomSeed );
	const int RandomSeed = ConfigManager::GetInt( sRandomSeed, 0, sFramework );

	if( UseRandomSeed )
	{
		Math::SeedGenerator( RandomSeed );
	}
	else
	{
		Math::SeedGenerator();
	}

	STATICHASH( UseFixedFrameTime );
	m_UseFixedFrameTime	= ConfigManager::GetBool( sUseFixedFrameTime, true, sFramework );

	STATICHASH( FixedFrameTime );
	m_FixedFrameTime = ConfigManager::GetFloat( sFixedFrameTime, 1.0f / 60.0f, sFramework );

	STATICHASH( FramesLimit );
	const int FramesLimit = ConfigManager::GetInt( sFramesLimit, 5, sFramework );
	m_FrameTimeLimit = m_FixedFrameTime * static_cast<float>( FramesLimit );

	STATICHASH( DoVideoCapture );
	m_DoVideoCapture = ConfigManager::GetBool( sDoVideoCapture, false, sFramework );

	STATICHASH( VideoCaptureFixedFrameTime );
	m_VideoCaptureFixedFrameTime = ConfigManager::GetFloat( sVideoCaptureFixedFrameTime, 1.0f / 30.0f, sFramework );

	uint DisplayWidth = 0;
	uint DisplayHeight = 0;
	SimpleString WindowTitle;

	// Loads display parameters from config, so GetInitialDisplaySize can use that.
	m_Display = new Display;

	// Make sure that we use a supported resolution regardless of what the config file said.
	const SDisplayMode BestDisplayMode = m_Display->GetBestDisplayMode( m_Display->m_Width, m_Display->m_Height );
	m_Display->SetResolution( BestDisplayMode.Width, BestDisplayMode.Height );

	uint WindowIcon = 0;
	GetInitialWindowIcon( WindowIcon );
	GetInitialDisplaySize( DisplayWidth, DisplayHeight );
	GetInitialWindowTitle( WindowTitle );

	CreateSplashWindow( WindowIcon, WindowTitle.CStr() );

	m_Window = new Window;

#if BUILD_WINDOWS_NO_SDL
	DWORD WindowStyle = 0;
	if( m_Display->m_Fullscreen ||
		(	m_Display->m_ScreenWidth == m_Display->m_Width &&
			m_Display->m_ScreenHeight == m_Display->m_Height ) )
	{
		WindowStyle = WS_POPUP;
	}
	else
	{
		WindowStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
	}

	m_Window->Init( WindowTitle.CStr(), "Class1", WindowStyle, 0, DisplayWidth, DisplayHeight, m_hInstance, WindowProc, WindowIcon, m_Display->m_ScreenWidth, m_Display->m_ScreenHeight );
#elif BUILD_SDL
	uint WindowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN;
	if( m_Display->m_Fullscreen ||
		(	m_Display->m_ScreenWidth == m_Display->m_Width &&
			m_Display->m_ScreenHeight == m_Display->m_Height ) )
	{
		WindowFlags |= SDL_WINDOW_BORDERLESS;
	}
	// TODO SDL: Unify interface?
	m_Window->Init( WindowTitle.CStr(), WindowFlags, DisplayWidth, DisplayHeight );

	STATICHASH( IconImage );
	const char* const	pIconImage	= ConfigManager::GetString( sIconImage, NULL, sFramework );
	ASSERT( pIconImage );
	const Surface		IconSurface	= Surface( PackStream( pIconImage ), Surface::ESFT_BMP );
	SDL_SetWindowIcon( m_Window->GetSDLWindow(), IconSurface.GetSDLSurface() );
#endif

	m_Window->SetFullscreen( m_Display->m_Fullscreen );
	if( m_Display->m_Fullscreen )
	{
		m_Window->SetPosition( 0, 0 );
	}

	m_Clock = new Clock;

	XTRACE_BEGIN( InitializeDevices );
		m_Keyboard	= new Keyboard;
#if BUILD_WINDOWS_NO_SDL
		m_Mouse		= new Mouse( m_hInstance, m_Window->GetHWnd() );
#elif BUILD_SDL
		m_Mouse		= new Mouse( m_Window );
#endif
	XTRACE_END;

	InitializeUIInputMap();

	XTRACE_BEGIN( InitializeAudioSystem );
		InitializeAudioSystem();
	XTRACE_END;

	XTRACE_BEGIN( InitializeRenderer );
#if BUILD_WINDOWS_NO_SDL
		STATICHASH( OpenGL );
		const bool OpenGL = ConfigManager::GetBool( sOpenGL );
		if( OpenGL )
#endif
		{
			PRINTF( "Using OpenGL renderer.\n" );
			m_Renderer = CreateGL2Renderer( m_Window );
		}
#if BUILD_WINDOWS_NO_SDL
		else
		{
			PRINTF( "Using Direct3D renderer.\n" );
			m_Renderer = CreateD3D9Renderer( m_Window->GetHWnd(), m_Display->m_Fullscreen );
		}
#endif

		IRenderer::SRestoreDeviceCallback Callback;
		Callback.m_Callback = &Framework3D::RendererRestoreDeviceCallback;
		Callback.m_Void = this;
		m_Renderer->SetRestoreDeviceCallback( Callback );

		InitializeRender();
		m_Renderer->Initialize();
		m_Renderer->SetDisplay( m_Display );
		m_Renderer->SetClock( m_Clock );
	XTRACE_END;

	if( ShowWindowASAP() )
	{
		SafeDelete( m_SplashWindow );
#if BUILD_WINDOWS_NO_SDL
		m_Window->Show( m_CmdShow );
#elif BUILD_SDL
		m_Window->Show();
#endif

		// Reattach GL context if needed.
		m_Renderer->Refresh();
	}

	if( UseClassicTargetManager() )
	{
		m_TargetManager = new TargetManager( m_Renderer, DisplayWidth, DisplayHeight );
	}

	XTRACE_BEGIN( InitializeUI );
		SimpleString UIManagerDefinitionName;
		GetUIManagerDefinitionName( UIManagerDefinitionName );

		m_UIManager = new UIManagerFramework( this );
		m_UIManager->InitializeFromDefinition( UIManagerDefinitionName );
		m_UIManager->GetUIStack()->SetFadeOverlay( m_UIManager->GetScreen( "Fade" ) );
		UIScreen::UpdateMouseButtonsSwapped();
	XTRACE_END;

	m_IsInitializing = false;
}
Пример #11
0
// Constructor and destructor
c_video_screen::c_video_screen(
    uint id, const std::string& name, const std::string& color,
    int view_cols, int view_rows,
    int pos_x, int pos_y, int width, int height, bool fullscreen
) :
    // Info
    m_id(id), m_name(name), m_color(color),
    // View
    m_view_cols(view_cols), m_view_rows(view_rows),
    // Window
    m_window_pos_x(pos_x), m_window_pos_y(pos_y),
    m_window_width(width), m_window_height(height),
    m_window_fullscreen(fullscreen),
    // Timing
    m_time(0)
{
    // Debug
    std::cout <<
        boost::format("Screen (%s): id=%d, pos_x=%d, pos_y=%d, width=%d, height=%d, fullscreen=%s") %
        m_name % m_id % m_window_pos_x % m_window_pos_y % m_window_width % m_window_height %
        std::string(m_window_fullscreen ? "true" : "false") << std::endl;

    // SDL
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)
        throw c_exception("Screen: Failed to initalize SDL!", { throw_format("name", m_name), throw_format("error", SDL_GetError()) });

    // Attributes
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);

    // Create window
    std::string title = std::string("madj - ") + m_name;
    Uint32 flags =
        SDL_WINDOW_OPENGL | (m_window_fullscreen ? (SDL_WINDOW_BORDERLESS | SDL_WINDOW_FULLSCREEN_DESKTOP) : SDL_WINDOW_RESIZABLE);
    m_window = SDL_CreateWindow(title.c_str(), m_window_pos_x, m_window_pos_y, m_window_width, m_window_height, flags);
    if (m_window == nullptr)
        throw c_exception("Screen: Failed to create window!", { throw_format("name", m_name), throw_format("error", SDL_GetError()) });

    // OpenGL context
    m_context = c_global::video->context(m_window);
    gl_init();

    // Window settings
    SDL_DisableScreenSaver();
    if (SDL_GL_SetSwapInterval(-1) != 0) {
        // 0 = immediate, 1 = vertical retrace sync, -1 = late swap tearing
        //std::cout << "Screen: Failed to set swap interval to late swap tearing!" << std::endl;
        if (SDL_GL_SetSwapInterval(1) != 0)
            std::cout << "Screen: Failed to set swap interval to vsync!" << std::endl;
    }

    // Display mode
    SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
    if (SDL_GetWindowDisplayMode(m_window, &mode) == 0 && mode.refresh_rate != 0) {
        std::cout << "Screen: refresh_rate = " << mode.refresh_rate << std::endl;
    }

    // Rendering area
    SDL_GL_GetDrawableSize(m_window, &m_window_width, &m_window_height);
    CEGUI::Rectf area(CEGUI::Vector2f(0.0f, 0.0f), CEGUI::Sizef(m_window_width, m_window_height));
    m_context->cegui_renderer().getDefaultRenderTarget().setArea(area);
    m_context->cegui_renderer().getDefaultRenderTarget().activate();

    // Timing
    m_time = SDL_GetTicks() / 1000.f;

    // CEGUI
    m_cegui = std::unique_ptr<c_cegui>(new c_cegui(m_context));

    // Scheme
    CEGUI::SchemeManager::getSingleton().createFromFile("GWEN.scheme");

    // Defaults
    //m_cegui->context().setDefaultFont("OpenSans-8");
    m_cegui->context().setDefaultFont("DroidSansMono-10");
    //m_cegui->context().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
    //m_cegui->context().setDefaultTooltipType("TaharezLook/Tooltip");

    // Root window
    m_cegui_root = reinterpret_cast<CEGUI::DefaultWindow*>(CEGUI::WindowManager::getSingleton().loadLayoutFromFile("screen.layout"));
    m_cegui_root->setUsingAutoRenderingSurface(false);
    //m_cegui_client = dynamic_cast<CEGUI::DefaultWindow*>(m_cegui_root->getChildRecursive("TrackerClient"));
    m_cegui->context().setRootWindow(m_cegui_root);

    // Error check
    g_opengl_check();

    // Viewport check
    if (
        m_view_rows < 1 || m_view_cols < 1 ||
        m_view_rows > 10 || m_view_cols > 10
    ) {
        throw c_exception("Screen: Wrong number of view columns/rows specified!", { throw_format("name", m_name) });
    }
}
Пример #12
0
// Actually put us in windowed or full screen mode.  Pass true the first time this is used, false subsequently.
// This has the unfortunate side-effect of triggering a mouse move event.
void VideoSystem::actualizeScreenMode(GameSettings *settings, bool changingInterfaces, bool currentUIUsesEditorScreenMode)
{
   DisplayMode displayMode = settings->getSetting<DisplayMode>(IniKey::WindowMode);

   DisplayManager::getScreenInfo()->resetGameCanvasSize();     // Set GameCanvasSize vars back to their default values
   DisplayManager::getScreenInfo()->setActualized();


   // If old display mode is windowed or current is windowed but we change interfaces,
   // save the window position
   if(settings->getIniSettings()->oldDisplayMode == DISPLAY_MODE_WINDOWED ||
         (changingInterfaces && displayMode == DISPLAY_MODE_WINDOWED))
   {
      settings->setWindowPosition(VideoSystem::getWindowPositionX(), VideoSystem::getWindowPositionY());
   }

   // When we're in the editor, let's take advantage of the entire screen unstretched
   // We might want to disallow this when we're in split screen mode?
   if(currentUIUsesEditorScreenMode &&
         (displayMode == DISPLAY_MODE_FULL_SCREEN_STRETCHED || displayMode == DISPLAY_MODE_FULL_SCREEN_UNSTRETCHED))
   {
      // Smaller values give bigger magnification; makes small things easier to see on full screen
      F32 magFactor = 0.85f;

      // For screens smaller than normal, we need to readjust magFactor to make sure we get the full canvas height crammed onto
      // the screen; otherwise our dock will break.  Since this mode is only used in the editor, we don't really care about
      // screen width; tall skinny screens will work just fine.
      magFactor = max(magFactor, (F32)DisplayManager::getScreenInfo()->getGameCanvasHeight() / (F32)DisplayManager::getScreenInfo()->getPhysicalScreenHeight());

      DisplayManager::getScreenInfo()->setGameCanvasSize(S32(DisplayManager::getScreenInfo()->getPhysicalScreenWidth() * magFactor), S32(DisplayManager::getScreenInfo()->getPhysicalScreenHeight() * magFactor));

      displayMode = DISPLAY_MODE_FULL_SCREEN_STRETCHED;
   }


   // Set up video/window flags amd parameters and get ready to change the window
   S32 sdlWindowWidth, sdlWindowHeight;
   F64 orthoLeft, orthoRight, orthoTop, orthoBottom;

   getWindowParameters(settings, displayMode, sdlWindowWidth, sdlWindowHeight, orthoLeft, orthoRight, orthoTop, orthoBottom);

   // Change video modes based on selected display mode
   // Note:  going into fullscreen you have to do in order:
   //  - SDL_SetWindowSize()
   //  - SDL_SetWindowFullscreen()
   //
   // However, coming out of fullscreen mode you must do the reverse
   switch (displayMode)
   {
   case DISPLAY_MODE_FULL_SCREEN_STRETCHED:
      SDL_SetWindowSize(DisplayManager::getScreenInfo()->sdlWindow, sdlWindowWidth, sdlWindowHeight);
      SDL_SetWindowFullscreen(DisplayManager::getScreenInfo()->sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);

      break;

   case DISPLAY_MODE_FULL_SCREEN_UNSTRETCHED:
      SDL_SetWindowSize(DisplayManager::getScreenInfo()->sdlWindow, sdlWindowWidth, sdlWindowHeight);
      SDL_SetWindowFullscreen(DisplayManager::getScreenInfo()->sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);

      break;

   case DISPLAY_MODE_WINDOWED:
   default:
      // Reverse order, leave fullscreen before setting size
      SDL_SetWindowFullscreen(DisplayManager::getScreenInfo()->sdlWindow, 0);
      SDL_SetWindowSize(DisplayManager::getScreenInfo()->sdlWindow, sdlWindowWidth, sdlWindowHeight);
      break;
   }

   if(settings->getSetting<YesNo>(IniKey::DisableScreenSaver))
      SDL_DisableScreenSaver();
   else
      SDL_EnableScreenSaver();

   // Flush window events because SDL_SetWindowSize triggers a SDL_WINDOWEVENT_RESIZED 
   // event (which in turn triggers another SDL_SetWindowSize)
   SDL_FlushEvent(SDL_WINDOWEVENT);

   SDL_GL_SetSwapInterval(settings->getSetting<YesNo>(IniKey::Vsync) ? 1 : 0);

   // Now save the new window dimensions in ScreenInfo
   DisplayManager::getScreenInfo()->setWindowSize(sdlWindowWidth, sdlWindowHeight);

   mGL->glClearColor(0, 0, 0, 0);

   mGL->glViewport(0, 0, sdlWindowWidth, sdlWindowHeight);

   mGL->glMatrixMode(GLOPT::Projection);
   mGL->glLoadIdentity();

   // The best understanding I can get for glOrtho is that these are the coordinates you want to appear at the four corners of the
   // physical screen. If you want a "black border" down one side of the screen, you need to make left negative, so that 0 would
   // appear some distance in from the left edge of the physical screen.  The same applies to the other coordinates as well.
   mGL->glOrtho(orthoLeft, orthoRight, orthoBottom, orthoTop, 0, 1);

   mGL->glMatrixMode(GLOPT::Modelview);
   mGL->glLoadIdentity();

   // Do the scissoring
   if(displayMode == DISPLAY_MODE_FULL_SCREEN_UNSTRETCHED)
   {
      mGL->glScissor(DisplayManager::getScreenInfo()->getHorizPhysicalMargin(),    // x
                DisplayManager::getScreenInfo()->getVertPhysicalMargin(),     // y
                DisplayManager::getScreenInfo()->getDrawAreaWidth(),          // width
                DisplayManager::getScreenInfo()->getDrawAreaHeight());        // height
   }
   else
   {
      // Enabling scissor appears to fix crashing problem switching screen mode
      // in linux and "Mobile 945GME Express Integrated Graphics Controller",
      // probably due to lines and points was not being clipped,
      // causing some lines to wrap around the screen, or by writing other
      // parts of RAM that can crash Bitfighter, graphics driver, or the entire computer.
      // This is probably a bug in the Linux Intel graphics driver.
      mGL->glScissor(0, 0, DisplayManager::getScreenInfo()->getWindowWidth(), DisplayManager::getScreenInfo()->getWindowHeight());
   }

   mGL->glEnable(GLOPT::ScissorTest);    // Turn on clipping

   mGL->setDefaultBlendFunction();
   mGL->glLineWidth(RenderUtils::DEFAULT_LINE_WIDTH);

   // Enable Line smoothing everywhere!  Make sure to disable temporarily for filled polygons and such
   if(settings->getSetting<YesNo>(IniKey::LineSmoothing))
   {
      mGL->glEnable(GLOPT::LineSmooth);
      //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
   }

   mGL->glEnable(GLOPT::Blend);

   // Now set the window position
   if(displayMode == DISPLAY_MODE_WINDOWED)
   {
      // Sometimes it happens to be (0,0) hiding the top title bar preventing ability to
      // move the window, in this case we are not moving it unless it is not (0,0).
      // Note that ini config file will default to (0,0).
      if(settings->getWindowPositionX() != 0 || settings->getWindowPositionY() != 0)
         setWindowPosition(settings->getWindowPositionX(), settings->getWindowPositionY());
   }
   else
      setWindowPosition(0, 0);

   // Notify all active UIs that the screen has changed mode.  This will likely need some work to not do something
   // horrible in split-screen mode.
   const Vector<ClientGame *> *clientGames = GameManager::getClientGames();
   for(S32 i = 0; i < clientGames->size(); i++)
      if(clientGames->get(i)->getUIManager()->getCurrentUI())
         clientGames->get(i)->getUIManager()->getCurrentUI()->onDisplayModeChange();

   // Re-initialize our fonts because OpenGL textures can be lost upon screen change
   FontManager::reinitialize(settings);

   // This needs to happen after font re-initialization because I think fontstash interferes
   // with the oglconsole font somehow...
   GameManager::gameConsole->onScreenModeChanged();
}
Пример #13
0
int SDLFrontend::init (int width, int height, bool fullscreen, EventHandler &eventHandler)
{
	if (width == -1 && height == -1)
		fullscreen = true;

	info(LOG_CLIENT,
			String::format("initializing: %i:%i - fullscreen: %s", width, height, fullscreen ? "true" : "false"));

	INIT_Subsystem(SDL_INIT_VIDEO, true);

	INIT_Subsystem(SDL_INIT_JOYSTICK, false);
	INIT_Subsystem(SDL_INIT_GAMECONTROLLER, false);
	INIT_Subsystem(SDL_INIT_HAPTIC, false);

	initJoystickAndHaptic();

	SDL_DisplayMode displayMode;
	SDL_GetDesktopDisplayMode(0, &displayMode);
	const char *name = SDL_GetPixelFormatName(displayMode.format);
	info(LOG_CLIENT, String::format("current desktop mode: %dx%d@%dHz (%s)",
			displayMode.w, displayMode.h, displayMode.refresh_rate, name));
	if (width == -1)
		width = 800;//displayMode.w;
	if (height == -1)
		height = 480; //displayMode.h;

	setGLAttributes();
	setHints();

	int doubleBuffered = 0;
	SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doubleBuffered);

	info(LOG_CLIENT, String::format("doublebuffer: %s", doubleBuffered ? "activated" : "disabled"));

	int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
#ifdef __IPHONEOS__
	flags |= SDL_WINDOW_RESIZABLE;
#endif


#if 1 //defined __IPHONEOS__ || defined __ANDROID__
	if (fullscreen)
		flags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
#else
	if (fullscreen)
		flags |= SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_BORDERLESS;
#endif

	const int videoDrivers = SDL_GetNumVideoDrivers();
	for (int i = 0; i < videoDrivers; ++i) {
		info(LOG_CLIENT, String::format("available driver: %s", SDL_GetVideoDriver(i)));
	}

	info(LOG_CLIENT, String::format("driver: %s", SDL_GetCurrentVideoDriver()));
	const int displays = SDL_GetNumVideoDisplays();
	info(LOG_CLIENT, String::format("found %i display(s)", displays));
	if (fullscreen && displays > 1) {
		width = displayMode.w;
		height = displayMode.h;
		info(LOG_CLIENT, String::format("use fake fullscreen for the first display: %i:%i", width, height));
	}

	_window = SDL_CreateWindow(Singleton<Application>::getInstance().getName().c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags);
	if (!_window) {
		sdlCheckError();
		return -1;
	}

	SDL_DisableScreenSaver();

	initRenderer();
	resetColor();
	GLContext::get().init();

	if (SDL_SetWindowBrightness(_window, 1.0f) == -1)
		sdlCheckError();

	if (Config.isGrabMouse() && (!fullscreen || displays > 1)) {
		SDL_SetWindowGrab(_window, SDL_TRUE);
	}

	int screen = 0;
	int modes = SDL_GetNumDisplayModes(screen);
	info(LOG_CLIENT, "possible display modes:");
	for (int i = 0; i < modes; i++) {
		SDL_GetDisplayMode(screen, i, &displayMode);
		name = SDL_GetPixelFormatName(displayMode.format);
		info(LOG_CLIENT, String::format("%dx%d@%dHz %s",
				displayMode.w, displayMode.h, displayMode.refresh_rate, name));
	}

	// some platforms may override or hardcode the resolution - so
	// we have to query it here to get the actual resolution
	SDL_GetWindowSize(_window, &width, &height);
	if (SDL_SetRelativeMouseMode(SDL_TRUE) == -1)
		error(LOG_CLIENT, "no relative mouse mode support");

	SDL_ShowCursor(0);
	info(LOG_CLIENT, String::format("actual resolution: %dx%d", width, height));
	setVSync(ConfigManager::get().isVSync());

	const int initState = IMG_Init(IMG_INIT_PNG);
	if (!(initState & IMG_INIT_PNG)) {
		sdlCheckError();
		System.exit("No png support", 1);
	}

	_width = width;
	_height = height;
	updateViewport(0, 0, getWidth(), getHeight());

	onInit();

	_eventHandler = &eventHandler;
	_eventHandler->registerObserver(_console.get());
	_eventHandler->registerObserver(this);

	info(LOG_CLIENT, "init the shader manager");
	ShaderManager::get().init();

	if (!Config.isSoundEnabled()) {
		info(LOG_CLIENT, "sound disabled");
	} else if (!SoundControl.init(true)) {
		error(LOG_CLIENT, "sound initialization failed");
	}

	return 0;
}
Пример #14
0
int video_init(int window_w,
               int window_h,
               int fullscreen,
               int vsync,
               const char* scaler_name,
               int scale_factor) {
    state.w = window_w;
    state.h = window_h;
    state.fs = fullscreen;
    state.vsync = vsync;
    state.fade = 1.0f;
    state.target = NULL;
    state.target_move_x = 0;
    state.target_move_y = 0;

    // Load scaler (if any)
    memset(state.scaler_name, 0, sizeof(state.scaler_name));
    strncpy(state.scaler_name, scaler_name, sizeof(state.scaler_name)-1);
    if(video_load_scaler(scaler_name, scale_factor)) {
        DEBUG("Scaler \"%s\" plugin not found; using Nearest neighbour scaling.", scaler_name);
        state.scale_factor = 1;
    } else {
        DEBUG("Scaler \"%s\" loaded w/ factor %d", scaler_name, scale_factor);
        state.scale_factor = scale_factor;
    }

    // Clear palettes
    state.cur_palette = malloc(sizeof(screen_palette));
    state.base_palette = malloc(sizeof(palette));
    memset(state.cur_palette, 0, sizeof(screen_palette));
    state.cur_palette->version = 1;

    // Form title string
    char title[32];
    sprintf(title, "OpenOMF v%d.%d.%d", V_MAJOR, V_MINOR, V_PATCH);

    // Open window
    state.window = SDL_CreateWindow(
        title,
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        window_w,
        window_h,
        SDL_WINDOW_SHOWN);
    if(state.window == NULL) {
        PERROR("Could not create window: %s", SDL_GetError());
        return 1;
    }

    // Set fullscreen if needed
    if(state.fs) {
        if(SDL_SetWindowFullscreen(state.window, SDL_WINDOW_FULLSCREEN) != 0) {
            PERROR("Could not set fullscreen mode!");
        } else {
            DEBUG("Fullscreen enabled!");
        }
    } else {
        SDL_SetWindowFullscreen(state.window, 0);
    }

    // Form flags
    int renderer_flags = SDL_RENDERER_ACCELERATED;
    if(state.vsync) {
        renderer_flags |= SDL_RENDERER_PRESENTVSYNC;
    }

    // Create renderer
    state.renderer = SDL_CreateRenderer(
        state.window,
        -1,
        renderer_flags);
    if(state.renderer == NULL) {
        PERROR("Could not create renderer: %s", SDL_GetError());
        return 1;
    }

    // Default resolution for renderer. This will them get scaled up to screen size.
    SDL_RenderSetLogicalSize(state.renderer,
                             NATIVE_W * state.scale_factor,
                             NATIVE_H * state.scale_factor);

    // Disable screensaver :/
    SDL_DisableScreenSaver();

    // Set rendertargets
    reset_targets();

    // Init texture cache
    tcache_init(state.renderer, state.scale_factor, &state.scaler);

    // Init hardware renderer
    state.cur_renderer = VIDEO_RENDERER_HW;
    video_hw_init(&state);

    // Get renderer data
    SDL_RendererInfo rinfo;
    SDL_GetRendererInfo(state.renderer, &rinfo);

    // Show some info
    INFO("Video Init OK");
    INFO(" * Driver: %s", SDL_GetCurrentVideoDriver());
    INFO(" * Renderer: %s", rinfo.name);
    INFO(" * Accelerated: %s", (rinfo.flags & SDL_RENDERER_ACCELERATED) ? "Yes" : "No");
    INFO(" * VSync support: %s", (rinfo.flags & SDL_RENDERER_PRESENTVSYNC) ? "Yes" : "No");
    INFO(" * Target support: %s", (rinfo.flags & SDL_RENDERER_TARGETTEXTURE) ? "Yes" : "No");
    return 0;
}
Пример #15
0
int XResetScreenSaver(Display *display) {
    // https://tronche.com/gui/x/xlib/window-and-session-manager/XResetScreenSaver.html
    SDL_DisableScreenSaver();
    SDL_EnableScreenSaver();
    return 1;
}
Пример #16
0
void Window_InitializeVideo(void)
{
	int	iFlags =
		SDL_WINDOW_SHOWN |
		SDL_WINDOW_OPENGL |
		SDL_WINDOW_FULLSCREEN;
	SDL_Surface	*sIcon;

	// [28/7/2013] Moved check here and corrected, seems more secure ~hogsy
	if (SDL_VideoInit(NULL) < 0)
		Sys_Error("Failed to initialize video!\n%s\n", SDL_GetError());

	SDL_DisableScreenSaver();

	// Get display information.
	if (SDL_GetCurrentDisplayMode(0, &sDisplayMode) != 0)
		Sys_Error("Failed to get current display information!\n%s\n", SDL_GetError());

	if (!Video.fullscreen)
		iFlags &= ~SDL_WINDOW_FULLSCREEN;

#if 0
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 8);
#if 0
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
#endif
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	sMainWindow = SDL_CreateWindow(
		Game->Name,				// [9/7/2013] Window name is based on the name given by Game ~hogsy
		SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED,
		Video.iWidth,
		Video.iHeight,
		iFlags);
	if (!sMainWindow)
		Sys_Error("Failed to create window!\n%s\n", SDL_GetError());

	// Attempt to grab the window icon from the game directory.
	sIcon = SDL_LoadBMP(va("%s/icon.bmp", com_gamedir));
	if (sIcon)
	{
		// [25/3/2014] Set the transparency key... ~hogsy
		SDL_SetColorKey(sIcon, true, SDL_MapRGB(sIcon->format, 0, 0, 0));
		SDL_SetWindowIcon(sMainWindow, sIcon);
		SDL_FreeSurface(sIcon);
	}
	else
		// Give us a warning, but continue.
		Con_Warning("Failed to load window icon! (%s)\n", SDL_GetError());

	sMainContext = SDL_GL_CreateContext(sMainWindow);
	if (!sMainContext)
		Sys_Error("Failed to create context!\n%s\n", SDL_GetError());

	SDL_GL_SetSwapInterval(0);

#ifdef _WIN32
	if (SDL_GetWindowWMInfo(sMainWindow, &sSystemInfo))
		g_mainwindow.instance = sSystemInfo.info.win.window;
	else
		Con_Warning("Failed to get WM information! (%s)\n", SDL_GetError());
#endif
}
Пример #17
0
	static int lua_SDL_DisableScreenSaver(lutok::state& state){
		SDL_DisableScreenSaver();
		return 0;
	}
Пример #18
0
int PL_Window_ProcessMessages() {
    SDL_Event event;
    
    if (s_initialized == DXFALSE) {
        return -1;
    }
    
    do {
        while (SDL_PollEvent(&event)) {
            switch(event.type) {
                case SDL_WINDOWEVENT:
                    switch(event.window.event) {
                        case SDL_WINDOWEVENT_ENTER:
                            SDL_DisableScreenSaver();
                            s_lacksFocus &= ~1;
                            break;
                        case SDL_WINDOWEVENT_FOCUS_GAINED:
                            SDL_DisableScreenSaver();
                            s_lacksFocus &= ~2;
                            break;
                        case SDL_WINDOWEVENT_LEAVE:
                            SDL_EnableScreenSaver();
                            s_lacksFocus |= 1;
                            break;
                        case SDL_WINDOWEVENT_FOCUS_LOST:
                            SDL_EnableScreenSaver();
                            s_lacksFocus |= 2;
                            break;
                        case SDL_WINDOWEVENT_EXPOSED:
                        case SDL_WINDOWEVENT_RESTORED:
                            PL_Window_Refresh();
                            break;
                        case SDL_WINDOWEVENT_RESIZED:
                            PL_Window_HandleResize(event.window.data1, event.window.data2);
                            break;
                        case SDL_WINDOWEVENT_CLOSE:
                            PL_Window_End();
                            return -1;
                        default:
                            break;
                    }
                    break;
#ifndef DX_NON_INPUT
                case SDL_KEYDOWN:
                    PL_Input_HandleKeyDown(&event.key.keysym);
                    break;
                case SDL_KEYUP:
                    PL_Input_HandleKeyUp(&event.key.keysym);
                    break;
                case SDL_JOYDEVICEADDED:
                    PL_Input_AddController(event.jdevice.which);
                    break;
                case SDL_JOYDEVICEREMOVED:
                    PL_Input_RemoveController(event.jdevice.which);
                    break;
                case SDL_MOUSEWHEEL:
                    PL_Input_HandleWheelMotion(event.wheel.x, event.wheel.y);
                    break;
#endif /* #ifndef DX_NON_INPUT */
                case SDL_QUIT:
                    return -1;
            }
        }
        
        if (s_lacksFocus) {
            if (s_alwaysRunFlag) {
                s_lacksFocus = 0;
            } else {
                SDL_Delay(1);
            }
        }
    } while (s_lacksFocus);
    
    return 0;
}
Пример #19
0
int main (int argc, char **argv)
{
    SDL_Window *window;
    double newtime, oldtime;
    int previous_key_dest = 0;

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        printf("SDL_Init error: %s\n", SDL_GetError());
        return 1;
    }

    window = SDL_CreateWindow("NullQuake", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0);
    if (window == NULL) {
        Con_Printf("SDL_CreateWindow error: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }
    windowID = SDL_GetWindowID(window);
    SDL_DisableScreenSaver();

	static quakeparms_t parms;

	parms.memsize = 8*1024*1024;
	parms.membase = malloc (parms.memsize);

    char *base_path = SDL_GetBasePath();
    if (base_path) {
        parms.basedir = SDL_strdup(base_path);
        SDL_free(base_path);
    } else {
        parms.basedir = SDL_strdup("./");
    }

	COM_InitArgv (argc, argv);

	parms.argc = com_argc;
	parms.argv = com_argv;

	printf ("Host_Init\n");
	Host_Init (&parms);

    oldtime = Sys_FloatTime();
	while (1)
	{
        // release mouse cursor in menus
        if (previous_key_dest != key_dest) {
            if (key_dest == key_game) {
                SDL_SetRelativeMouseMode(SDL_TRUE);
            } else {
                SDL_SetRelativeMouseMode(SDL_FALSE);
            }
            previous_key_dest = key_dest;
        }
        // throttle in background
        if (!isFocused) {
            SDL_Delay(32);
        }
		newtime = Sys_FloatTime();
        Host_Frame(newtime - oldtime);
        oldtime = newtime;
	}

    return 0;
}
Пример #20
0
int LancerJeu(gpointer *pData)
{
    /* Cette fonction va appeler les fonctions d'initialisations de la SDL et lancer le jeu ou l'éditeur */

    SDL_Renderer *pMoteurRendu = NULL;  //Pointeurs sur le moteur de rendu
    SDL_Window *pFenetre = NULL;        //Pointeur sur la fenêtre
    FMOD_CHANNEL *channelEnCours = NULL;    //Pour le contrôle des différents canaux audios

    Sprite images[50] = {{NULL}, {0,0}};   //Tableau des images (textures + positions)
    TTF_Font *polices[10] = {NULL};		//Tableau des polices

    Options *pOptions = NULL;	//Pointeur sur une structure Options

    FILE *pFichierErreur = fopen("ressources/ErreursLog.txt", "a");        //Pointeur sur le fichier d'erreurs

    SDL_Surface *surf = NULL;	//Pointeur sur une surface
    SDL_Texture *pEcranChargement = NULL;	//Pointeur sur une texture pour l'écran de chargement

    Animation anim[10];	//Tableau de structures Animation

    int erreur=0;	//Code d'erreur

    Joueur *pJoueur = (Joueur *)g_slist_nth_data((GSList*)pData, 6);	//On récupère le pointeur vers la structure Joueur dans la liste chaînée
    Sons *pSons = (Sons*)g_slist_nth_data((GSList*)pData, 4);		//De même avec celui vers la structure Sons
    FMOD_SYSTEM *pMoteurSon = (FMOD_SYSTEM *)g_slist_nth_data((GSList*)pData, 3);	//De même avec celui vers la structure FMOD_SYSTEM

    if(pFichierErreur == NULL)	//Vérification
    {
        exit(EXIT_FAILURE);
    }

    /* On lit les options et on remplit la structure */
    pOptions = DefinirOptions();

    Initialisation(&pMoteurRendu, pFichierErreur, &pFenetre, pOptions);     //Initialisation des principaux éléments (SDL, fenêtre, moteur de rendu)

    FMOD_System_GetChannel(pMoteurSon, M_MENU, &channelEnCours);	//On met en pause la musique du menu
    FMOD_Channel_SetPaused(channelEnCours, true);

    if(BMusique)	//S'il y a de la musique
    {
        FMOD_System_PlaySound(pMoteurSon, M_LOAD, pSons->music[M_LOAD], true, NULL);        // On lit la musique de chargement
        FMOD_System_GetChannel(pMoteurSon, M_LOAD, &channelEnCours);
        FMOD_Channel_SetVolume(channelEnCours, (float)(Volume/100.0));
        FMOD_Channel_SetPaused(channelEnCours, false);
    }

    /* On charge l'image de chargement et on vérifie */
    surf = IMG_Load("ressources/img/load.png");

    if (surf == NULL)
    {
        fprintf(pFichierErreur, "Erreur: impossible d'ouvrir le fichier ressources/img/load.png");
        exit(EXIT_FAILURE);
    }

    /* On transforme la surface en texture pour l'affichage et on libère la mémoire occupée par la surface */
    pEcranChargement = SDL_CreateTextureFromSurface(pMoteurRendu, surf);
    SDL_FreeSurface(surf);

    SDL_ShowCursor(false);	//On masque le curseur pendant le jeu (on affichera un curseur personnalisé dans l'éditeur)

    /* On efface l'écran et on colle l'image de chargement */
    SDL_SetRenderDrawColor(pMoteurRendu, 0, 0, 0, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(pMoteurRendu);
    SDL_RenderCopy(pMoteurRendu, pEcranChargement, NULL, NULL);
    SDL_RenderPresent(pMoteurRendu);

    SDL_EventState(SDL_TEXTEDITING, SDL_DISABLE);   //Désactivation des événements dont on a pas besoin.
    SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE);

    SDL_DisableScreenSaver();       //Désactivation de l'écran de veille.

    erreur = Chargements(images, pMoteurRendu, polices, anim);	//On charge tout !

    /* Traitement des éventuelles erreurs */
    if(erreur == 1)
    {
        fprintf(pFichierErreur, "Erreur lors du chargement des images. Veuillez vérifier ressources\\img\\... \n");
        exit(EXIT_FAILURE);
    }
    else if (erreur == 2)
    {
        fprintf(pFichierErreur, "Erreur lors du chargement des polices. Veuillez vérifier ressources\\fonts\\... \n");
        exit(EXIT_FAILURE);
    }
    else if (erreur == 3)
    {
        fprintf(pFichierErreur, "Erreur lors du chargement des animations. Veuillez vérifier ressources\\anim\\... \n");
        exit(EXIT_FAILURE);
    }

    if (BMusique)
    {
        FMOD_System_GetChannel(pMoteurSon, M_LOAD, &channelEnCours);	//On arrête la musique du chargement
        FMOD_Channel_SetPaused(channelEnCours, true);

        FMOD_Sound_SetLoopCount(pSons->music[M_JEU], -1);      // On active la lecture en boucle

        FMOD_System_PlaySound(pMoteurSon, M_JEU, pSons->music[M_JEU], true, NULL);        // On lit la musique du jeu
        FMOD_System_GetChannel(pMoteurSon, M_JEU, &channelEnCours);
        FMOD_Channel_SetVolume(channelEnCours, (float)(Volume/100.0));
        FMOD_Channel_SetPaused(channelEnCours, false);
    }

    /* On regarde si on a appelé la fonction en mode jeu ou en mode éditeur */
    if (pJoueur->mode == MODE_CAMPAGNE)
    {
        InitialiserInfos(pOptions, pJoueur);	//On définit les infos sur la partie en cours
        erreur = BouclePrincipale(pJoueur, images, anim, pMoteurRendu, pMoteurSon, pSons, polices);    //Boucle du jeu

        if(erreur == JEU_FIN_ERREUR_CHARGEMENT)
        {
            MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL);
        }

        SauverMySql(pJoueur);	//On sauvegarde l'avancée du joueur
    }
    else if(pJoueur->mode == MODE_PERSO)
    {
        InitialiserInfos(pOptions, pJoueur);	//On définit les infos sur la partie en cours
        erreur = BouclePrincipale(pJoueur, images, anim, pMoteurRendu, pMoteurSon, pSons, polices);    //Boucle du jeu

        if(erreur == JEU_FIN_ERREUR_CHARGEMENT)
        {
            MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL);
        }
    }
    else if (pJoueur->mode == MODE_EDITEUR)
    {
        erreur = Editeur(pMoteurRendu, images, pMoteurSon, pSons, polices, pJoueur);	//On lance la boucle de l'éditeur

        if(erreur == JEU_FIN_ERREUR_CHARGEMENT)
        {
            MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL);
        }
    }

    /* Libération de la mémoire */
    LibererMemoire(pMoteurRendu, images, anim, polices, pFenetre, pOptions);

    fclose(pFichierErreur);	//On ferme le fichier d'erreur

    return 0;
}
Пример #21
0
int main(int argc, char **argv) {
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
		return -1;
	}

	if(TTF_Init() < 0) {
		fprintf(stderr, "Couldn't initialize font rendering: %s\n", TTF_GetError());
		return -1;
	}

  int width = 800;
  int height = 600;
  Uint32 frameRate = BASE_FRAME_RATE_MS;
  SDL_bool vsync = SDL_FALSE;

#if SDL_MAJOR_VERSION == 2
  SDL_DisplayMode current;
  for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i){
    if(SDL_GetCurrentDisplayMode(i, &current) != 0)
			fprintf(stderr, "Couldn't get display mode: %s\n", SDL_GetError());
    else {
      printf("Display %d is %dx%d\n", i, current.w, current.h);
      width = current.w;
      height = current.h;
    }
  }

	Uint32 flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
	if(argc > 1) {
		if(strncmp(argv[1], "-novsync", 8) == 0)
			flags &= ~SDL_RENDERER_PRESENTVSYNC;
		if(strncmp(argv[1], "-software", 9) == 0)
			flags = SDL_RENDERER_SOFTWARE;

		char *n = strchr(argv[1], '=');
		if(n) {
			n++;
			frameRate = strtoul(n, 0, 0);
		}
	}

	SDL_Window *window = SDL_CreateWindow(argv[0], SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width + GetIntelOffset(), height, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN);
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, flags);
	SDL_ShowCursor(SDL_DISABLE);
	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_DisableScreenSaver();

	SDL_RendererInfo info;
	if(SDL_GetRendererInfo(renderer, &info) == 0) {
		printf("Using video driver: %s with renderer %s\n", SDL_GetCurrentVideoDriver(), info.name);
		if(info.flags & SDL_RENDERER_SOFTWARE)
			printf("*** Using SDL_RENDERER_SOFTWARE\n");
		if(info.flags & SDL_RENDERER_ACCELERATED)
			printf("*** Using SDL_RENDERER_ACCELERATED\n");
		if(info.flags & SDL_RENDERER_PRESENTVSYNC) {
			printf("*** Using SDL_RENDERER_PRESENTVSYNC\n");
			vsync = SDL_TRUE;
		}
		if(info.flags & SDL_RENDERER_TARGETTEXTURE)
			printf("*** Using SDL_RENDERER_TARGETTEXTURE\n");
	}
#else
  const SDL_VideoInfo *pVideoInfo = SDL_GetVideoInfo();
  if(pVideoInfo == 0) {
    fprintf(stderr, "Couldn't get display information: %s\n", SDL_GetError());
    exit(1);
  }
  printf("Display is %dx%d\n", pVideoInfo->current_w, pVideoInfo->current_h);
  width = pVideoInfo->current_w;
  height = pVideoInfo->current_h;

  SDL_Surface *screen = SDL_SetVideoMode(width, height, pVideoInfo->vfmt->BitsPerPixel, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
  if(screen == 0) {
    fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
    exit(1);
  }

  SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_ShowCursor(SDL_DISABLE);

#endif

	TTF_Font *font = TTF_OpenFont("AlteHaasGroteskBold.ttf", 60);
	if(font == 0) {
		fprintf(stderr, "Can't open font for stats: %s", TTF_GetError());
		goto cleanup;
	}

	SDL_Event event;
	SDL_bool m_run = SDL_TRUE;
	Uint32 lastFrame = 0;
	float fps = 0.0f;
	SDL_Color foregroundColor = { 0xff, 0xff, 0 };
	char tmp[64];
	int delta = 1;
	int position = 0;
	while(m_run) {
		while(SDL_PollEvent(&event)) {
			switch (event.type) {
			case SDL_KEYDOWN:
				if(event.key.keysym.sym == SDLK_ESCAPE)
				m_run = SDL_FALSE;
				break;
			case SDL_QUIT:
				m_run = SDL_FALSE;
				break;
			default:
				break;
			}
		}

		Uint32 start = SDL_GetTicks();

#if SDL_MAJOR_VERSION == 2
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff);
		SDL_RenderClear(renderer);
#else
    SDL_FillRect(screen, 0, 0);
#endif

		snprintf(tmp, sizeof(tmp), "Current fps = %.1f", fps);
		SDL_Surface *textSurface = TTF_RenderText_Solid(font, tmp, foregroundColor);

		if(textSurface) {
#if SDL_MAJOR_VERSION == 2
			SDL_Texture *textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
#endif

			SDL_Rect location;
			location.h = textSurface->h;
			location.w = textSurface->w;
			location.x = position;
			location.y = height / 2 - textSurface->h / 2;
#if SDL_MAJOR_VERSION == 1
      SDL_BlitSurface(textSurface, 0, screen, &location);
#endif
			SDL_FreeSurface(textSurface);

			position += delta;
			if(position >= width - textSurface->w || position <= 0)
				delta *= -1;

#if SDL_MAJOR_VERSION == 2
			if(textTexture) {
				SDL_RenderCopy(renderer, textTexture, 0, &location);
				SDL_DestroyTexture(textTexture);
			}
#endif
		}

#if SDL_MAJOR_VERSION == 2
		SDL_RenderPresent(renderer);
#else
    SDL_Flip(screen);
#endif

		Uint32 end = SDL_GetTicks();
		Uint32 elapsed = end - lastFrame;

		// delay for the remainder of the base rate so we keep a decent frame rate if there's no vsync
		if(vsync == SDL_FALSE && frameRate > elapsed)
			SDL_Delay(frameRate - elapsed);

		if(elapsed > frameRate * 3) {
			struct timeb tp;
			ftime(&tp);
			time_t now;
			struct tm *ti;
			char buf[255];
			time(&now);
			ti = localtime(&now);
			strftime(buf, sizeof(buf), "%I:%M:%S", ti);
			printf("%s.%d: Frame took %ums\n", buf, tp.millitm, elapsed);
		}

		// remember now as the starting point for the next frame
		lastFrame = SDL_GetTicks();

		// update statistics
		elapsed = lastFrame - start;
		fps = 1000.0f / (float)elapsed;
		//printf("Current frame rate is %6.3f fps (%ums)              \r", fps, elapsed);
	}
	printf("\n");

cleanup:
#if SDL_MAJOR_VERSION == 2
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
#else
  SDL_FreeSurface(screen);
#endif
	TTF_Quit();
	SDL_Quit();

	return 0;
}