void Platform::setWindowFullscreen(PlatformWindow *window, bool fullscreen) {
	u32 value = 0;
	if(!fullscreen) value = SDL_WINDOW_FULLSCREEN_DESKTOP;
	SDL_SetWindowFullscreen((SDL_Window *)window->handle, value);
}
Exemple #2
0
int
SDL_WM_ToggleFullScreen(SDL_Surface * surface)
{
    int length;
    void *pixels;
    Uint8 *src, *dst;
    int row;
    int window_w;
    int window_h;

    if (!SDL_PublicSurface) {
        SDL_SetError("SDL_SetVideoMode() hasn't been called");
        return 0;
    }

    /* Copy the old bits out */
    length = SDL_PublicSurface->w * SDL_PublicSurface->format->BytesPerPixel;
    pixels = SDL_malloc(SDL_PublicSurface->h * length);
    if (pixels && SDL_PublicSurface->pixels) {
        src = (Uint8*)SDL_PublicSurface->pixels;
        dst = (Uint8*)pixels;
        for (row = 0; row < SDL_PublicSurface->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += SDL_PublicSurface->pitch;
            dst += length;
        }
    }

    /* Do the physical mode switch */
    if (SDL_GetWindowFlags(SDL_VideoWindow) & SDL_WINDOW_FULLSCREEN) {
        if (SDL_SetWindowFullscreen(SDL_VideoWindow, 0) < 0) {
            return 0;
        }
        SDL_PublicSurface->flags &= ~SDL_FULLSCREEN;
    } else {
        if (SDL_SetWindowFullscreen(SDL_VideoWindow, 1) < 0) {
            return 0;
        }
        SDL_PublicSurface->flags |= SDL_FULLSCREEN;
    }

    /* Recreate the screen surface */
    SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow);
    if (!SDL_WindowSurface) {
        /* We're totally hosed... */
        return 0;
    }

    /* Center the public surface in the window surface */
    SDL_GetWindowSize(SDL_VideoWindow, &window_w, &window_h);
    SDL_VideoViewport.x = (window_w - SDL_VideoSurface->w)/2;
    SDL_VideoViewport.y = (window_h - SDL_VideoSurface->h)/2;
    SDL_VideoViewport.w = SDL_VideoSurface->w;
    SDL_VideoViewport.h = SDL_VideoSurface->h;

    /* Do some shuffling behind the application's back if format changes */
    if (SDL_VideoSurface->format->format != SDL_WindowSurface->format->format) {
        if (SDL_ShadowSurface) {
            if (SDL_ShadowSurface->format->format == SDL_WindowSurface->format->format) {
                /* Whee!  We don't need a shadow surface anymore! */
                SDL_VideoSurface->flags &= ~SDL_DONTFREE;
                SDL_FreeSurface(SDL_VideoSurface);
                SDL_free(SDL_ShadowSurface->pixels);
                SDL_VideoSurface = SDL_ShadowSurface;
                SDL_VideoSurface->flags |= SDL_PREALLOC;
                SDL_ShadowSurface = NULL;
            } else {
                /* No problem, just change the video surface format */
                SDL_FreeFormat(SDL_VideoSurface->format);
                SDL_VideoSurface->format = SDL_WindowSurface->format;
                SDL_VideoSurface->format->refcount++;
                SDL_InvalidateMap(SDL_ShadowSurface->map);
            }
        } else {
            /* We can make the video surface the shadow surface */
            SDL_ShadowSurface = SDL_VideoSurface;
            SDL_ShadowSurface->pitch = SDL_CalculatePitch(SDL_ShadowSurface);
            SDL_ShadowSurface->pixels = SDL_malloc(SDL_ShadowSurface->h * SDL_ShadowSurface->pitch);
            if (!SDL_ShadowSurface->pixels) {
                /* Uh oh, we're hosed */
                SDL_ShadowSurface = NULL;
                return 0;
            }
            SDL_ShadowSurface->flags &= ~SDL_PREALLOC;

            SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, 0, 0, 32, 0, 0, 0, 0, 0);
            SDL_VideoSurface->flags = SDL_ShadowSurface->flags;
            SDL_VideoSurface->flags |= SDL_PREALLOC;
            SDL_FreeFormat(SDL_VideoSurface->format);
            SDL_VideoSurface->format = SDL_WindowSurface->format;
            SDL_VideoSurface->format->refcount++;
            SDL_VideoSurface->w = SDL_ShadowSurface->w;
            SDL_VideoSurface->h = SDL_ShadowSurface->h;
        }
    }

    /* Update the video surface */
    SDL_VideoSurface->pitch = SDL_WindowSurface->pitch;
    SDL_VideoSurface->pixels = (void *)((Uint8 *)SDL_WindowSurface->pixels +
        SDL_VideoViewport.y * SDL_VideoSurface->pitch +
        SDL_VideoViewport.x  * SDL_VideoSurface->format->BytesPerPixel);
    SDL_SetClipRect(SDL_VideoSurface, NULL);

    /* Copy the old bits back */
    if (pixels) {
        src = (Uint8*)pixels;
        dst = (Uint8*)SDL_PublicSurface->pixels;
        for (row = 0; row < SDL_PublicSurface->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += length;
            dst += SDL_PublicSurface->pitch;
        }
        SDL_Flip(SDL_PublicSurface);
        SDL_free(pixels);
    }

    /* We're done! */
    return 1;
}
Exemple #3
0
void Game::Run(){
    if (storedState != NULL){
        stateStack.emplace(storedState);
        storedState =NULL;
    }

    while (!SDL_QuitRequested() and not stateStack.top()->RequestedQuit()){
        restart_cycle:
        frameStart = dt;
        CalculateDeltaTime();

        InputManager::GetInstance().Update();
        if (ConfigManager::GetInstance().IsResized())
            goto restart_cycle;
        Update();
        if (InputManager::GetInstance().KeyPress(SDLK_F11)){
            static bool full = false;
            if (!full)
                SDL_SetWindowFullscreen(window, SDL_TRUE);
            else
                SDL_SetWindowFullscreen(window, SDL_FALSE);
            full = !full;
        }

        Render();
        SDL_RenderPresent(GetRenderer() );

        //Limitar dinamicamente o tempo de cada frame para atingir sempre que possivel 30 fps
        float n = GetDeltaTime()*100.0;

        if (stateStack.top()->RequestedDeleted()){
            if (stateStack.empty() && storedState == NULL){
                break;
            }else{
                stateStack.pop();
            }
        }

        if (storedState != NULL){
            stateStack.emplace(storedState);
            stateStack.top()->Begin();
            storedState =NULL;
        }


        n = n-(1000.0/MAXFPS);
        n  = n < 0 ? 0 : n;
        n  = (1000.0/MAXFPS)-n < 0 ? 0 : n;


        //SDL_Delay( std::max( (1000.0/MAXFPS)-n - 5, 0.0) );

        frames++;

        UpdateTitleAsFps((1000.0/MAXFPS)-n  );

    }
    isClosing = true;


};
Exemple #4
0
rserr_t R_ChangeDisplaySettings( int width, int height, qboolean fullscreen )
{
#ifdef XASH_SDL
	SDL_DisplayMode displayMode;

	SDL_GetCurrentDisplayMode(0, &displayMode);
#ifdef __ANDROID__
	width = displayMode.w;
	height = displayMode.h;
	fullscreen = false;
#endif
	R_SaveVideoMode( width, height );

	// check our desktop attributes
	glw_state.desktopBitsPixel = SDL_BITSPERPIXEL(displayMode.format);
	glw_state.desktopWidth = displayMode.w;
	glw_state.desktopHeight = displayMode.h;

	glState.fullScreen = fullscreen;
	glState.wideScreen = true; // V_AdjustFov will check for widescreen

	if(!host.hWnd)
	{
		if( !VID_CreateWindow( width, height, fullscreen ) )
			return rserr_invalid_mode;
	}
#ifndef __ANDROID__
else if( fullscreen )
	{
		SDL_DisplayMode want, got;

		want.w = width;
		want.h = height;
		want.driverdata = NULL;
		want.format = want.refresh_rate = 0; // don't care

		if( !SDL_GetClosestDisplayMode(0, &want, &got) )
			return rserr_invalid_mode;

		MsgDev(D_NOTE, "Got closest display mode: %ix%i@%i\n", got.w, got.h, got.refresh_rate);

		if( ( SDL_GetWindowFlags(host.hWnd) & SDL_WINDOW_FULLSCREEN ) == SDL_WINDOW_FULLSCREEN)
			if( SDL_SetWindowFullscreen(host.hWnd, 0) == -1 )
				return rserr_invalid_fullscreen;

		if( SDL_SetWindowDisplayMode(host.hWnd, &got) )
			return rserr_invalid_mode;

		if( SDL_SetWindowFullscreen(host.hWnd, SDL_WINDOW_FULLSCREEN) == -1 )
			return rserr_invalid_fullscreen;

		R_ChangeDisplaySettingsFast( got.w, got.h );
	}
	else
	{
		if( SDL_SetWindowFullscreen(host.hWnd, 0) )
			return rserr_invalid_fullscreen;
		SDL_SetWindowSize(host.hWnd, width, height);
		R_ChangeDisplaySettingsFast( width, height );
	}
#endif
#endif // XASH_SDL
	return rserr_ok;
}
Exemple #5
0
/*
 * Initializes the OpenGL window
 */
static qboolean
GLimp_InitGraphics(qboolean fullscreen)
{
	int flags;
	int msaa_samples;
	int stencil_bits;
	int width, height;
	char title[24];

	if (GetWindowSize(&width, &height) && (width == vid.width) && (height == vid.height))
	{
		/* If we want fullscreen, but aren't */
		if (fullscreen != IsFullscreen())
		{
#if SDL_VERSION_ATLEAST(2, 0, 0)
			SDL_SetWindowFullscreen(window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
#else
			SDL_WM_ToggleFullScreen(window);
#endif

			Cvar_SetValue("vid_fullscreen", fullscreen);
		}

		/* Are we now? */
		if (fullscreen == IsFullscreen())
		{
			return true;
		}
	}

	/* Is the surface used? */
	if (window)
	{
#if SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(window);
#else
		SDL_FreeSurface(window);
#endif
	}

	/* Create the window */
	VID_NewWindow(vid.width, vid.height);

	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_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

	if (gl_msaa_samples->value)
	{
		msaa_samples = gl_msaa_samples->value;

		if (SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1) < 0)
		{
			Com_Printf("MSAA is unsupported: %s\n", SDL_GetError());
			Cvar_SetValue ("gl_msaa_samples", 0);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
		}
		else if (SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, msaa_samples) < 0)
		{
			Com_Printf("MSAA %ix is unsupported: %s\n", msaa_samples, SDL_GetError());
			Cvar_SetValue("gl_msaa_samples", 0);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
		}
	}

	/* Initiate the flags */
	flags = SDL_OPENGL;

	if (fullscreen)
	{
		flags |= SDL_FULLSCREEN;
	}

#if !SDL_VERSION_ATLEAST(2, 0, 0)
	/* For SDL1.2, these things must be done before creating the window */

	/* Set the icon */
	SetSDLIcon();

	/* Set vsync */
	SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, gl_swapinterval->value ? 1 : 0);
#endif

	while (1)
	{
		if (!CreateSDLWindow(flags))
		{
			if (gl_msaa_samples->value)
			{
				VID_Printf(PRINT_ALL, "SDL SetVideoMode failed: %s\n",
						SDL_GetError());
				VID_Printf(PRINT_ALL, "Reverting to %s gl_mode %i (%ix%i) without MSAA.\n",
						(flags & SDL_FULLSCREEN) ? "fullscreen" : "windowed",
						(int)Cvar_VariableValue("gl_mode"), vid.width, vid.height);

				/* Try to recover */
				Cvar_SetValue("gl_msaa_samples", 0);
				SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
				SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
			}
			else if (vid.width != 640 || vid.height != 480 || (flags & SDL_FULLSCREEN))
			{
				VID_Printf(PRINT_ALL, "SDL SetVideoMode failed: %s\n",
						SDL_GetError());
				VID_Printf(PRINT_ALL, "Reverting to windowed gl_mode 4 (640x480).\n");

				/* Try to recover */
				Cvar_SetValue("gl_mode", 4);
				Cvar_SetValue("vid_fullscreen", 0);
				vid.width = 640;
				vid.height = 480;
				flags &= ~SDL_FULLSCREEN;
			}
			else
			{
				VID_Error(ERR_FATAL, "Failed to revert to gl_mode 4. Exiting...\n");
				return false;
			}
		}
		else
		{
			break;
		}
	}
	if (gl_msaa_samples->value)
	{
		if (SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &msaa_samples) == 0)
		{
			Cvar_SetValue("gl_msaa_samples", msaa_samples);
		}
	}

#if SDL_VERSION_ATLEAST(2, 0, 0)
	/* For SDL2, these things must be done after creating the window */

	/* Set the icon */
	SetSDLIcon();

	/* Set vsync - TODO: -1 could be set for "late swap tearing" */
	SDL_GL_SetSwapInterval(gl_swapinterval->value ? 1 : 0);
#endif

	/* Initialize the stencil buffer */
	if (!SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil_bits))
	{
		VID_Printf(PRINT_ALL, "Got %d bits of stencil.\n", stencil_bits);

		if (stencil_bits >= 1)
		{
			have_stencil = true;
		}
	}

	/* Initialize hardware gamma */
	InitGamma();

	/* Window title */
	snprintf(title, sizeof(title), "Yamagi Quake II %s", YQ2VERSION);
#if SDL_VERSION_ATLEAST(2, 0, 0)
	SDL_SetWindowTitle(window, title);
#else
	SDL_WM_SetCaption(title, title);
#endif

	/* No cursor */
	SDL_ShowCursor(0);

	return true;
}
Exemple #6
0
 void Window::makeWindowed()
 {
     if(isLoaded())
         SDL_SetWindowFullscreen(win, 0);
     removeInitFlags(FULLSCREEN | FULLSCREEN_DESKTOP);
 }
Exemple #7
0
void Window_setFullScreen() {
    SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
}
void startscreen(SDL_Window *screen,uint *state,uint *grapset,uint *fullscreen) {

	/* Renderer (with VSync, nice !) */
	SDL_Renderer *renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_PRESENTVSYNC|SDL_RENDERER_ACCELERATED);
	SDL_SetHint("SDL_HINT_RENDER_SCALE_QUALITY", "0");
	SDL_RenderSetLogicalSize(renderer, 256, 192);

	uint exit = 0;
	uint musicplay = 0;

	SDL_Rect srcintro = {0,0,256,192};
	SDL_Rect desintro = {0,0,256,192};

	SDL_Event keyp;

	/* Loading PNG */
	SDL_Texture *intro = IMG_LoadTexture(renderer, DATADIR "/graphics/intro.png");
	SDL_Texture *intromd = IMG_LoadTexture(renderer, DATADIR "/graphics/intromd.png");

	/* Load audio */
	Mix_Music *music = Mix_LoadMUS(DATADIR "/sounds/MainTitleN.ogg");

	while (exit != 1) {

		/* Cleaning the renderer */
		SDL_RenderClear(renderer);

		/* Put image on renderer */
		if (*grapset == 0)
			SDL_RenderCopy(renderer, intro, &srcintro, &desintro);
		else
			SDL_RenderCopy(renderer, intromd, &srcintro, &desintro);

		/* Flip ! */
		SDL_RenderPresent(renderer);

		/* Play music if required */
		if (musicplay == 0) {
			musicplay = 1;
			Mix_PlayMusic(music, 0);
		}

		/* Check keyboard */
		if ( SDL_PollEvent(&keyp) ) {
			if (keyp.type == SDL_KEYDOWN) { /* Key pressed */
				if (keyp.key.keysym.sym == SDLK_c) { /* Change graphic set */
					if (*grapset == 0)
						*grapset = 1;
					else
						*grapset = 0;
				}
				if (keyp.key.keysym.sym == SDLK_i) { /* Show instructions */
					if (srcintro.y == 0)
						srcintro.y = 192;
					else {
						srcintro.y = 0;
						musicplay = 0;
					}
				}
				if (keyp.key.keysym.sym == SDLK_f) { /* Switch fullscreen/windowed */
					if (*fullscreen == 0) {
						SDL_SetWindowFullscreen(screen,SDL_WINDOW_FULLSCREEN_DESKTOP);
						*fullscreen = 1;
					}
					else {
						SDL_SetWindowFullscreen(screen,0);
						*fullscreen = 0;
					}
				}
				if (keyp.key.keysym.sym == SDLK_SPACE) { /* Start game */
					*state = 1;
					exit = 1;
				}
				if (keyp.key.keysym.sym == SDLK_ESCAPE) { /* Exit game */
      		exit = 1;
					*state = 6;
				}
			}
		}

	}

	/* Cleaning */
	SDL_DestroyTexture(intro);
	SDL_DestroyTexture(intromd);
	SDL_DestroyRenderer(renderer);

}
Exemple #9
0
void openvox::Window::setFullscreen(bool useFullscreen, bool overrideCheck /*= false*/) {
    if (overrideCheck || m_displayMode.isFullscreen != useFullscreen) {
        m_displayMode.isFullscreen = useFullscreen;
        SDL_SetWindowFullscreen((SDL_Window*)m_window, m_displayMode.isFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
    }
}
/* check key */
void keyPressed( SDL_Keysym* keysym  ) 
{
 
  switch ( keysym->sym ) {

  case SDLK_ESCAPE:
    closePlayer();  //close
    break;
    
  case SDLK_SPACE:
    WV_playStream(stream); //play
    break;

  case SDLK_BACKSPACE:
    WV_pauseStream(stream);  //pause
    break;

  case SDLK_KP_PLUS:
    WV_shiftDBVolume(stream, +1); //encrease volume
    break;

  case SDLK_KP_MINUS:
    WV_shiftDBVolume(stream, -1); //decrease volume
    break;

  case SDLK_f:
    if(!fullscreenFlag){   //toggle fullscreen
      fullscreenFlag = 1;
      SDL_ShowCursor(SDL_DISABLE);
      SDL_SetWindowFullscreen(screen, SDL_TRUE);
      SDL_RenderSetViewport(screenRenderer, NULL);
      if(streamObj)
	WV_resetStreamRendererOutput(streamObj, screenRenderer, NULL); 
    }
    else{
      fullscreenFlag = 0;
      SDL_ShowCursor(SDL_ENABLE);
      SDL_SetWindowFullscreen(screen, SDL_FALSE);
      SDL_RenderSetViewport(screenRenderer, NULL);
      if(streamObj)
	WV_resetStreamRendererOutput(streamObj, screenRenderer, NULL);
      
    }
    break;

    
    /********/
    /* seek */
    /********/
    uint32_t seekShift; //will be converted in milliseconds
    int seekDirection;

  case SDLK_RIGHT:
    seekShift = 10;
    seekDirection = WV_SEEK_FORWARD; 
    goto do_seek;

  case SDLK_LEFT:
    seekShift = 10;
    seekDirection = WV_SEEK_BACKWARD;
    goto do_seek;

  case SDLK_UP:
    seekShift = 60;
    seekDirection = WV_SEEK_FORWARD; 
    goto do_seek;

  case SDLK_DOWN:
    seekShift = 60;
    seekDirection = WV_SEEK_BACKWARD; 
    goto do_seek;

  do_seek:
    seekShift *= 1000;
    WV_rseekStream(stream, seekShift, seekDirection);
    break;
     
  default:
    break;
  }
}
int
SDL2TestApplication::run()
{
    m_window = SDL_CreateWindow("SDL2TestApplication",
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED, 
            0, 0, // size shouldn't matter with fullscreen mode
            SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN);

    if (m_window == NULL) {
        printf("Could not create window: %s\n", SDL_GetError());
        return 1;
    }

    int w, h;
    SDL_GetWindowSize(m_window, &w, &h);
    printf("Window size after create: (%d, %d)\n", w, h);

#if 0
    SDL_SetWindowFullscreen(window, SDL_FALSE);
    SDL_GetWindowSize(window, &w, &h);
    printf("Window size after fullscreen off: (%d, %d)\n", w, h);

    SDL_SetWindowSize(window, 200, 200);
    SDL_GetWindowSize(window, &w, &h);
    printf("Window size after resize: (%d, %d)\n", w, h);

    SDL_SetWindowFullscreen(window, SDL_TRUE);
    SDL_GetWindowSize(window, &w, &h);
    printf("Window size after fullscreen on: (%d, %d)\n", w, h);
#endif

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, m_major);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, m_minor);

    m_gl_context = SDL_GL_CreateContext(m_window);

    initGL();
    resizeGL(w, h);

    std::vector<TouchPoint>::iterator it;

    SDL_Event event;
    int quit = 0;
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    quit = 1;
                    break;
                case SDL_WINDOWEVENT:
                    printf("Window event: %d (%d, %d)\n", event.window.event,
                            event.window.data1, event.window.data2);
                    break;
                case SDL_FINGERDOWN: {
                    TouchPoint touch(event.tfinger.fingerId,
                            event.tfinger.x, event.tfinger.y);
                    m_touches.push_back(touch);
                    onPressed(touch);
                    printf("Finger down: (%.2f, %.2f)\n", touch.x, touch.y);
                    break;
                }
                case SDL_FINGERUP:
                case SDL_FINGERMOTION:
                    for (it=m_touches.begin(); it != m_touches.end(); ++it) {
                        if (it->id == event.tfinger.fingerId) {
                            if (event.type == SDL_FINGERMOTION) {
                                it->x = event.tfinger.x;
                                it->y = event.tfinger.y;
                                printf("finger move: (%.2f, %.2f)\n", it->x, it->y);
                            } else {
                                printf("Finger up: (%.2f, %.2f)\n", it->x, it->y);
                                m_touches.erase(it);
                            }
                            break;
                        }
                    }
                    break;
                default:
                    printf("SDL Event: %d\n", event.type);
                    break;
            }
        }

        if (quit) {
            /* Application has to quit - don't render anymore */
            break;
        }

        renderGL();

        SDL_GL_SwapWindow(m_window);
        SDL_Delay(10);
    }

    SDL_GL_DeleteContext(m_gl_context);
    SDL_DestroyWindow(m_window);
    SDL_Quit();

    return 0;
}
Exemple #12
0
inline void
SDLHandleUserInput(SDL_Event *Event,
                   game_code *GameCode,
                   game_memory *GameMemory,
                   keyboard_input *KeyboardInput,
                   gamepad_input *GamePadInput) {

    int KeyCode = Event->key.keysym.sym;
    uint8 GamePadButton = Event->cbutton.button;

    const uint8 *KeyState = SDL_GetKeyboardState(NULL);
    
    switch(Event->type) {
        case SDL_KEYDOWN:

            if(KeyCode == SDLK_ESCAPE) {
                HandleButtonPress(&KeyboardInput->Escape);
                GlobalRunning = false;
            }

            if(KeyCode == SDLK_a) {
                HandleButtonPress(&KeyboardInput->A);
                                                    
                UnloadGameCode(GameCode);
                *GameCode = LoadGameCode();
                GameMemory->IsInitialized = false;
            }

            if(KeyState[SDL_SCANCODE_LALT] && KeyState[SDL_SCANCODE_RETURN] ) {
                if(!Fullscreen){
                    SDL_SetWindowFullscreen(SDL_GetWindowFromID(Event->window.windowID),
                                            SDL_WINDOW_FULLSCREEN);
                    SDL_SetRelativeMouseMode((SDL_bool)SDL_ENABLE);
                    Fullscreen = true;
                } else {
                    SDL_SetWindowFullscreen(SDL_GetWindowFromID(Event->window.windowID), 0);
                    SDL_SetRelativeMouseMode((SDL_bool)SDL_DISABLE);
                    Fullscreen = false;
                }
            }

            if(KeyCode == SDLK_b) {
                HandleButtonPress(&KeyboardInput->B);
            }

            if(KeyCode == SDLK_f) {
                HandleButtonPress(&KeyboardInput->F);
            }

            if(KeyCode == SDLK_UP) {
                HandleButtonPress(&KeyboardInput->Up);
            }

            if(KeyCode == SDLK_DOWN) {
                HandleButtonPress(&KeyboardInput->Down);
            }

            if(KeyCode == SDLK_LEFT) {
                HandleButtonPress(&KeyboardInput->Left);
            }

            if(KeyCode == SDLK_RIGHT) {
                HandleButtonPress(&KeyboardInput->Right);
            }
            break;

        case SDL_KEYUP:

            if(KeyCode == SDLK_ESCAPE) {
                HandleButtonRelease(&KeyboardInput->Escape);
            }

            if(KeyCode == SDLK_b) {
                HandleButtonRelease(&KeyboardInput->B);
            }

            if(KeyCode == SDLK_f) {
                HandleButtonRelease(&KeyboardInput->F);
            }

            if(KeyCode == SDLK_a) {
                HandleButtonRelease(&KeyboardInput->A);
            }

            if(KeyCode == SDLK_UP) {
                HandleButtonRelease(&KeyboardInput->Up);
            }

            if(KeyCode == SDLK_DOWN) {
                HandleButtonRelease(&KeyboardInput->Down);
            }

            if(KeyCode == SDLK_LEFT) {
                HandleButtonRelease(&KeyboardInput->Left);
            }

            if(KeyCode == SDLK_RIGHT) {
                HandleButtonRelease(&KeyboardInput->Right);
            }
            break;

        case SDL_CONTROLLERBUTTONDOWN:

            if(GamePadButton == SDL_CONTROLLER_BUTTON_A) {
                HandleButtonPress(&GamePadInput->AButton);
            }

            if(GamePadButton == SDL_CONTROLLER_BUTTON_B) {
                HandleButtonPress(&GamePadInput->BButton);
            }

            if(GamePadButton == SDL_CONTROLLER_BUTTON_X) {
                HandleButtonPress(&GamePadInput->XButton);
            }

            if(GamePadButton == SDL_CONTROLLER_BUTTON_Y) {
                HandleButtonPress(&GamePadInput->YButton);
            }

            break;

        case SDL_CONTROLLERBUTTONUP:

            if(GamePadButton == SDL_CONTROLLER_BUTTON_A) {
                HandleButtonRelease(&GamePadInput->AButton);
            }

            if(GamePadButton == SDL_CONTROLLER_BUTTON_B) {
                HandleButtonRelease(&GamePadInput->BButton);
                GlobalRunning = false;
            }

            if(GamePadButton == SDL_CONTROLLER_BUTTON_X) {
                HandleButtonRelease(&GamePadInput->XButton);
            }

            if(GamePadButton == SDL_CONTROLLER_BUTTON_Y) {
                HandleButtonRelease(&GamePadInput->YButton);
            }

            break;
    }

    // NOTE(Redab): Get values from gamepad joysticks and normalize.
    
    real32 LSX = (real32)SDL_GameControllerGetAxis(GamePadHandle, SDL_CONTROLLER_AXIS_LEFTX);

    if(LSX < 0) {
        GamePadInput->LeftStick.X = LSX / 32768.0f;
    } else {
        GamePadInput->LeftStick.X = LSX / 32767.0f;
    }

    real32 LSY = (real32)SDL_GameControllerGetAxis(GamePadHandle, SDL_CONTROLLER_AXIS_LEFTY);

    if(LSY < 0) {
        GamePadInput->LeftStick.Y = LSY / 32768.0f;
    } else {
        GamePadInput->LeftStick.Y = LSY / 32767.0f;
    }

    real32 RSX = (real32)SDL_GameControllerGetAxis(GamePadHandle, SDL_CONTROLLER_AXIS_RIGHTX);

    if(RSX < 0) {
        GamePadInput->RightStick.X = RSX / 32768.0f;
    } else {
        GamePadInput->RightStick.X = RSX / 32767.0f;
    }

    real32 RSY = (real32)SDL_GameControllerGetAxis(GamePadHandle, SDL_CONTROLLER_AXIS_RIGHTY);

    if(RSY < 0) {
        GamePadInput->RightStick.Y = RSY / 32768.0f;
    } else {
        GamePadInput->RightStick.Y = RSY / 32767.0f;
    }

}
Exemple #13
0
int main()
{

  // Initialize SDL's Video subsystem
  if (SDL_Init(SDL_INIT_VIDEO) < 0 )
  {
    // Or die on error
    SDLErrorExit("Unable to initialize SDL");
  }

  // now get the size of the display and create a window we need to init the video
  SDL_Rect rect;
  SDL_GetDisplayBounds(0,&rect);
  // now create our window
  SDL_Window *window=SDL_CreateWindow("SDLNGL",
                                      SDL_WINDOWPOS_CENTERED,
                                      SDL_WINDOWPOS_CENTERED,
                                      rect.w/2,
                                      rect.h/2,
                                      SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
                                      );
  // check to see if that worked or exit
  if (!window)
  {
    SDLErrorExit("Unable to create window");
  }

  // Create our opengl context and attach it to our window

  SDL_GLContext glContext=createOpenGLContext(window);
  if(!glContext)
  {
    SDLErrorExit("Problem creating OpenGL context");
  }
  // make this our current GL context (we can have more than one window but in this case not)
  SDL_GL_MakeCurrent(window, glContext);
  /* This makes our buffer swap syncronized with the monitor's vertical refresh */
  SDL_GL_SetSwapInterval(1);
  // we need to initialise the NGL lib which will load all of the OpenGL functions, this must
  // be done once we have a valid GL context but before we call any GL commands. If we dont do
  // this everything will crash
  ngl::NGLInit::instance();
  // now clear the screen and swap whilst NGL inits (which may take time)
  glClear(GL_COLOR_BUFFER_BIT);
  SDL_GL_SwapWindow(window);
  // flag to indicate if we need to exit
  bool quit=false;
  // sdl event processing data structure
  SDL_Event event;
  // now we create an instance of our ngl class, this will init NGL and setup basic
  // opengl stuff ext. When this falls out of scope the dtor will be called and cleanup
  // our gl stuff
  NGLDraw ngl;
  // resize the ngl to set the screen size and camera stuff
  ngl.resize(rect.w,rect.h);
  while(!quit)
  {

    while ( SDL_PollEvent(&event) )
    {
      switch (event.type)
      {
      // this is the window x being clicked.
      case SDL_QUIT : quit = true; break;
        // process the mouse data by passing it to ngl class
      case SDL_MOUSEMOTION : ngl.mouseMoveEvent(event.motion); break;
      case SDL_MOUSEBUTTONDOWN : ngl.mousePressEvent(event.button); break;
      case SDL_MOUSEBUTTONUP : ngl.mouseReleaseEvent(event.button); break;
      case SDL_MOUSEWHEEL : ngl.wheelEvent(event.wheel);
        // if the window is re-sized pass it to the ngl class to change gl viewport
        // note this is slow as the context is re-create by SDL each time
      case SDL_WINDOWEVENT :
        int w,h;
        // get the new window size
        SDL_GetWindowSize(window,&w,&h);
        ngl.resize(w,h);
        break;

        // now we look for a keydown event
      case SDL_KEYDOWN:
      {
        ngl.keyEvent(event.key);
        switch( event.key.keysym.sym )
        {
        // if it's the escape key quit
        case SDLK_ESCAPE :  quit = true; break;
        case SDLK_w : glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); break;
        case SDLK_s : glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); break;
        case SDLK_f :
          SDL_SetWindowFullscreen(window,SDL_TRUE);
          glViewport(0,0,rect.w,rect.h);
          break;

        case SDLK_g : SDL_SetWindowFullscreen(window,SDL_FALSE); break;
        default : break;
        } // end of key process
      } // end of keydown

      default : break;
      } // end of event switch
    } // end of poll events

    // now we draw ngl
    ngl.update();
    ngl.draw();
    // swap the buffers
    SDL_GL_SwapWindow(window);

  }
  // now tidy up and exit SDL
  SDL_Quit();
}
Exemple #14
0
void EventThread::setFullscreen(SDL_Window *win, bool mode)
{
	SDL_SetWindowFullscreen
	        (win, mode ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
	fullscreen = mode;
}
Exemple #15
0
void
CommonEvent(CommonState * state, SDL_Event * event, int *done)
{
    int i;

    if (state->verbose & VERBOSE_EVENT) {
        PrintEvent(event);
    }

    switch (event->type) {
    case SDL_WINDOWEVENT:
        switch (event->window.event) {
        case SDL_WINDOWEVENT_CLOSE:
			{
                SDL_Window *window = SDL_GetWindowFromID(event->window.windowID);
                if (window) {
					SDL_DestroyWindow(window);
				}
			}
            break;
        }
        break;
    case SDL_KEYDOWN:
        switch (event->key.keysym.sym) {
            /* Add hotkeys here */
        case SDLK_PRINTSCREEN: {
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    for (i = 0; i < state->num_windows; ++i) {
                        if (window == state->windows[i]) {
                            ScreenShot(state->renderers[i]);
                        }
                    }
                }
            }
            break;
        case SDLK_c:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-C copy awesome text! */
                SDL_SetClipboardText("SDL rocks!\nYou know it!");
                printf("Copied text to clipboard\n");
            }
            break;
        case SDLK_v:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-V paste awesome text! */
                char *text = SDL_GetClipboardText();
                if (*text) {
                    printf("Clipboard: %s\n", text);
                } else {
                    printf("Clipboard is empty\n");
                }
                SDL_free(text);
            }
            break;
        case SDLK_g:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-G toggle grab */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    SDL_SetWindowGrab(window, !SDL_GetWindowGrab(window));
                }
            }
            break;
        case SDLK_m:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-M maximize */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    Uint32 flags = SDL_GetWindowFlags(window);
                    if (flags & SDL_WINDOW_MAXIMIZED) {
                        SDL_RestoreWindow(window);
                    } else {
                        SDL_MaximizeWindow(window);
                    }
                }
            }
            break;
        case SDLK_r:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-R toggle mouse relative mode */
                SDL_SetRelativeMouseMode(!SDL_GetRelativeMouseMode());
            }
            break;
        case SDLK_z:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-Z minimize */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    SDL_MinimizeWindow(window);
                }
            }
            break;
        case SDLK_RETURN:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-Enter toggle fullscreen */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    Uint32 flags = SDL_GetWindowFlags(window);
                    if (flags & SDL_WINDOW_FULLSCREEN) {
                        SDL_SetWindowFullscreen(window, SDL_FALSE);
                    } else {
                        SDL_SetWindowFullscreen(window, SDL_TRUE);
                    }
                }
            }
            break;
        case SDLK_ESCAPE:
            *done = 1;
            break;
        default:
            break;
        }
        break;
    case SDL_QUIT:
        *done = 1;
        break;
    }
}
Exemple #16
0
static void sdl_fullscreen(void *ctx, int b_fullscreen)
{
    platform_ctx *platform = (platform_ctx *)ctx;

    /*SDL_Rect bounds, usablebounds;
    float hdpi = 0;
    float vdpi = 0;
    SDL_DisplayMode mode;
    uint32_t Rmask, Gmask, Bmask, Amask;
    int bpp, i, j, m, n = SDL_GetNumVideoDisplays();
    SDL_Log("Number of displays: %d\n", n);
    for (i = 0; i < n; ++i)
    {
        SDL_Log("Display %d: %s\n", i, SDL_GetDisplayName(i));

        SDL_zero(bounds);
        SDL_GetDisplayBounds(i, &bounds);

        SDL_zero(usablebounds);
        //SDL_GetDisplayUsableBounds(i, &usablebounds);

        SDL_GetDisplayDPI(i, NULL, &hdpi, &vdpi);

        SDL_Log("Bounds: %dx%d at %d,%d\n", bounds.w, bounds.h, bounds.x, bounds.y);
        //SDL_Log("Usable bounds: %dx%d at %d,%d\n", usablebounds.w, usablebounds.h, usablebounds.x, usablebounds.y);
        SDL_Log("DPI: %fx%f\n", hdpi, vdpi);

        SDL_GetDesktopDisplayMode(i, &mode);
        SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask,
                                   &Bmask, &Amask);
        SDL_Log("  Current mode: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                mode.w, mode.h, mode.refresh_rate, bpp,
                SDL_GetPixelFormatName(mode.format));
        if (Rmask || Gmask || Bmask)
        {
            SDL_Log("      Red Mask   = 0x%.8x\n", Rmask);
            SDL_Log("      Green Mask = 0x%.8x\n", Gmask);
            SDL_Log("      Blue Mask  = 0x%.8x\n", Bmask);
            if (Amask)
                SDL_Log("      Alpha Mask = 0x%.8x\n", Amask);
        }

        m = SDL_GetNumDisplayModes(i);
        if (m == 0)
        {
            SDL_Log("No available fullscreen video modes\n");
        } else
        {
            SDL_Log("  Fullscreen video modes:\n");
            for (j = 0; j < m; ++j)
            {
                SDL_GetDisplayMode(i, j, &mode);
                SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                           &Gmask, &Bmask, &Amask);
                SDL_Log("    Mode %d: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                        j, mode.w, mode.h, mode.refresh_rate, bpp,
                        SDL_GetPixelFormatName(mode.format));
                if (Rmask || Gmask || Bmask) {
                    SDL_Log("        Red Mask   = 0x%.8x\n", Rmask);
                    SDL_Log("        Green Mask = 0x%.8x\n", Gmask);
                    SDL_Log("        Blue Mask  = 0x%.8x\n", Bmask);
                    if (Amask)
                        SDL_Log("        Alpha Mask = 0x%.8x\n", Amask);
                }
                if (b_fullscreen && 1024 == mode.w && 32 == bpp)
                {
                    SDL_SetWindowDisplayMode(platform->window, &mode);
                    SDL_SetWindowFullscreen(platform->window, SDL_WINDOW_FULLSCREEN);
                    return;
                }
            }
        }
    }*/

    SDL_SetWindowFullscreen(platform->window, b_fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
}
//-------------------------------------------------------------------------------------------------
int main( int argc, char* args[] )
{
    printf("JeZxLee's ''GT-R Twin TurboCharged'' game engine started!\n");
    argc = argc; args = args;

    if ( SDL_Init(SDL_INIT_EVERYTHING) != 0 )
    {
        printf( "Unable to initialize SDL2: %s\n", SDL_GetError() );
        return(1);
    }
    else  printf("SDL2 initialized.\n");

    visuals = new Visuals();

    if ( visuals->InitializeWindow() != true ) visuals->CoreFailure = true;
    if ( visuals->LoadFontsIntoMemory() != true )  visuals->CoreFailure = true;
    if ( visuals->LoadSpritesAndInitialize() != true )  visuals->CoreFailure = true;

    input = new Input();

    screens = new Screens();

    interface = new Interface();

    data = new Data();

    srand( (unsigned)time(NULL) ); // Place unique time seed into random number generator.
    logic = new Logic();

    audio = new Audio();
    audio->SetupAudio();

    data->LoadHighScoresAndOptions();

    if (visuals->FullScreenMode == true)  SDL_SetWindowFullscreen(visuals->Window, SDL_WINDOW_FULLSCREEN_DESKTOP);

    audio->PlayMusic(0, -1);

    //-MAIN-LOOP------------------------------------------------------------------------
    printf("Main loop started...\n");
    while (visuals->CoreFailure != true && input->EXIT_Game != true)
    {
        input->GetAllUserInput();
        visuals->CalculateFramerate();
        screens->ProcessScreenToDisplay();
        visuals->ProcessFramerate();
    }
    printf("...Main loop exited\n");
    //------------------------------------------------------------------------MAIN-LOOP-

    data->SaveHighScoresAndOptions();

    delete logic;
    delete data;
    delete audio;
    delete interface;
    delete screens;
    delete input;
    delete visuals;
    SDL_Quit();
    printf("SDL2 closed.\n");
    printf("JeZxLee's ''GT-R Twin TurboCharged'' game engine ended!\n");
    return(0);
}
Exemple #18
0
void GraphicsEngine::setFullscreen(bool b) {
	SDL_SetWindowFullscreen(window, b ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_MAXIMIZED);
}
Exemple #19
0
void Device::applyFullscreen()
{
	SDL_SetWindowFullscreen(window, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
}
extern SkinSurface*
skin_surface_create_window(int x,
                           int y,
                           int w,
                           int h,
                           int original_w,
                           int original_h,
                           int is_fullscreen)
{
    static SkinSurface* result = NULL;

    SDL_Window* window = skin_winsys_get_window();
    SDL_Renderer* renderer = globals_get_renderer();

    D("%s: x=%d y=%d w=%d h=%d original_w=%d original_h=%d is_fullscreen=%d",
      __FUNCTION__, x, y, w, h, original_w, original_h, is_fullscreen);

    // Textures do not survive window resize events, so
    globals_foreach_surface(&_skin_surface_destroy_texture, NULL);

    if (!window) {
        // NOTE: Don't use SDL_WINDOW_ALLOW_HIGHDPI here. On OS X, this will
        //       make mouse event coordinates twice smaller than needed
        //       when running on a high-dpi machine (e.g. recent MacBook Pro),
        //       making the UI unusable. Note that this doesn't happen on a
        //       'low-dpi' device such as a MacPro connected to a 30" monitor.
        int window_flags = SDL_WINDOW_OPENGL;
        if (is_fullscreen) {
            window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
        }
        window = SDL_CreateWindow("Android emulator",
                                  x, y, w, h,
                                  window_flags);
        if (!window) {
            panic("Could not create SDL2 window: %s\n", SDL_GetError());
        }
        skin_winsys_set_window(window);
    } else {
        if (is_fullscreen) {
            SDL_CHECK(SDL_SetWindowFullscreen(window,
                                              SDL_WINDOW_FULLSCREEN_DESKTOP));
#if DEBUG
#endif
        } else {
            SDL_CHECK(SDL_SetWindowFullscreen(window, 0));
            SDL_SetWindowPosition(window, x, y);
            SDL_SetWindowSize(window, w, h);
        }
    }

    // Generate renderer
    if (!renderer) {
        SDL_CHECK(SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"));
        renderer = SDL_CreateRenderer(window,
                                    -1,
                                    SDL_RENDERER_ACCELERATED|
                                    SDL_RENDERER_PRESENTVSYNC|
                                    SDL_RENDERER_TARGETTEXTURE);
        if  (!renderer) {
            panic("Could not create renderer: %s\n", SDL_GetError());
        }
        globals_set_renderer(renderer);
    }

    SDL_CHECK(SDL_RenderSetLogicalSize(renderer, original_w, original_h));

    if (DEBUG && VERBOSE_CHECK(surface)) {
        SDL_RendererInfo info;
        SDL_CHECK(SDL_GetRendererInfo(renderer, &info));
        printf("renderer.name = %s\n", info.name);
        printf("renderer.flags = 0x%x\n", info.flags);
        printf("renderer.num_texture_formats = %d\n", info.num_texture_formats);
        int nn;
        for (nn = 0; nn < info.num_texture_formats; ++nn) {
            printf("   0x%x (%s)\n", info.texture_formats[nn],
                   SDL_GetPixelFormatName(info.texture_formats[nn]));
        }
        printf("renderer.max_texture_width = %d\n", info.max_texture_width);
        printf("renderer.max_texture_height = %d\n", info.max_texture_height);
    }

    // Compute scaling parameters.
    {
        int window_x, window_y, window_w, window_h;

        SDL_GetWindowSize(window, &window_w, &window_h);
        SDL_GetWindowPosition(window, &window_x, &window_y);

        D("Window pos=(%d,%d) size=(%d,%d)", window_x, window_y, window_w, window_h);

        double x_scale = window_w * 1.0 / original_w;
        double y_scale = window_h * 1.0 / original_h;
        double scale = (x_scale <= y_scale) ? x_scale : y_scale;

        double effective_x = 0.;
        double effective_y = 0.;

        if (is_fullscreen) {
            effective_x = (window_w - original_w * scale) * 0.5;
            effective_y = (window_h - original_h * scale) * 0.5;
        }

        globals_set_window_scale(scale, effective_x, effective_y);
    }

    SDL_Texture* texture =
            SDL_CreateTexture(renderer,
                              SDL_PIXELFORMAT_ARGB8888,
                              SDL_TEXTUREACCESS_TARGET,
                              original_w,
                              original_h);
    if (!texture) {
        panic("Could not create window texture: %s", SDL_GetError());
    }

    SDL_CHECK(SDL_SetRenderTarget(renderer, texture));
    SDL_CHECK(SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255));
    SDL_CHECK(SDL_RenderClear(renderer));

    SDL_CHECK(SDL_SetRenderTarget(renderer, NULL));
    SDL_CHECK(SDL_SetRenderDrawColor(renderer, 0, 0, 128, 255));
    SDL_CHECK(SDL_RenderClear(renderer));
    SDL_CHECK(SDL_RenderCopy(renderer, texture, NULL, NULL));
    SDL_RenderPresent(renderer);

    if (!result) {
        result = _skin_surface_create(NULL, texture, original_w, original_h);
    } else {
        result->texture = texture;
        result->w = original_w;
        result->h = original_h;
    }
    skin_surface_ref(result);

    // Ensure all textures are regenerated properly.
    globals_foreach_surface(&_skin_surface_reset_texture, renderer);

    return result;
}
Exemple #21
0
qboolean VID_CreateWindow( int width, int height, qboolean fullscreen )
{
#ifdef XASH_SDL
	static string	wndname;
	Uint32 wndFlags = SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;

	Q_strncpy( wndname, GI->title, sizeof( wndname ));

	host.hWnd = SDL_CreateWindow(wndname, r_xpos->integer,
		r_ypos->integer, width, height, wndFlags);

	if( !host.hWnd )
	{
		MsgDev( D_ERROR, "VID_CreateWindow: couldn't create '%s': %s\n", wndname, SDL_GetError());

		// remove MSAA, if it present, because
		// window creating may fail on GLX visual choose
		if( gl_msaa->integer )
		{
			Cvar_Set("gl_msaa", "0");
			GL_SetupAttributes(); // re-choose attributes

			// try again
			return VID_CreateWindow( width, height, fullscreen );
		}
		return false;
	}

	if( fullscreen )
	{
		SDL_DisplayMode want, got;

		want.w = width;
		want.h = height;
		want.driverdata = NULL;
		want.format = want.refresh_rate = 0; // don't care

		if( !SDL_GetClosestDisplayMode(0, &want, &got) )
			return false;

		MsgDev(D_NOTE, "Got closest display mode: %ix%i@%i\n", got.w, got.h, got.refresh_rate);

		if( SDL_SetWindowDisplayMode(host.hWnd, &got) == -1 )
			return false;

		if( SDL_SetWindowFullscreen(host.hWnd, SDL_WINDOW_FULLSCREEN) == -1 )
			return false;

	}

	host.window_center_x = width / 2;
	host.window_center_y = height / 2;
	SDL_ShowWindow( host.hWnd );
#else
	host.hWnd = 1; //fake window
	host.window_center_x = width / 2;
	host.window_center_y = height / 2;
#endif
	if( !glw_state.initialized )
	{
		if( !GL_CreateContext( ) )
		{
			return false;
		}

		VID_StartupGamma();
	}
	else
	{
		if( !GL_UpdateContext( ))
			return false;
	}
	return true;
}
void RenderWindow::SetFullscreen(bool bFullscreen)
{
   ATLASSERT(m_spWindow != nullptr);

   SDL_SetWindowFullscreen(m_spWindow.get(), bFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
}
Exemple #23
0
/**
 * @brief Responsible for doing a swapbuffers
 */
void GLimp_EndFrame(void)
{
	// don't flip if drawing to front buffer
	//FIXME: remove this nonesense
	if (Q_stricmp(Cvar_VariableString("r_drawBuffer"), "GL_FRONT") != 0)
	{
		SDL_GL_SwapWindow(main_window);
	}

	if (r_fullscreen->modified)
	{
		qboolean fullscreen;
		qboolean needToToggle;

		// Find out the current state
		fullscreen = !!(SDL_GetWindowFlags(main_window) & SDL_WINDOW_FULLSCREEN);

		if (r_fullscreen->integer && Cvar_VariableIntegerValue("in_nograb"))
		{
			Com_Printf("Fullscreen not allowed with in_nograb 1\n");
			Cvar_Set("r_fullscreen", "0");
			r_fullscreen->modified = qfalse;
		}

		// Is the state we want different from the current state?
		needToToggle = !!r_fullscreen->integer != fullscreen;

		if (needToToggle)
		{
			// SDL_WM_ToggleFullScreen didn't work, so do it the slow way
			if (!(SDL_SetWindowFullscreen(main_window, r_fullscreen->integer) >= 0)) // !sdlToggled
			{
				Cbuf_ExecuteText(EXEC_APPEND, "vid_restart\n");
			}

			IN_Restart();
		}

#ifdef MACOS_X_GAMMA_RESET_FIX
		// OS X 10.9 has a bug where toggling in or out of fullscreen mode
		// will cause the gamma to reset to the system default after an unknown
		// short delay. This little fix simply causes the gamma to be reset
		// again after a hopefully-long-enough-delay of 3 seconds.
		// Radar 15961845
		gammaResetTime = CL_ScaledMilliseconds() + 3000;
#endif
		r_fullscreen->modified = qfalse;
	}

#ifdef MACOS_X_GAMMA_RESET_FIX
	if ((gammaResetTime != 0) && (gammaResetTime < CL_ScaledMilliseconds()))
	{
		// Circuitous way of resetting the gamma to its current value.
		char old[6] = { 0 };
		Q_strncpyz(old, va("%i", Cvar_VariableIntegerValue("r_gamma")), 5);
		if (strlen(old))
		{
			Cvar_Set("r_gamma", "1");
			Cvar_Set("r_gamma", old);
		}

		gammaResetTime = 0;
	}
#endif
}
Exemple #24
0
static void event_sdl(player_ctx_t *ctx, int *is_min)
{
    SDL_Event event;
    double x_scale, y_scale;
    int w, h;
    event_code_t code = L_EVENT_NONE;
    uint32_t data = 0;

    while (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
        case SDL_WINDOWEVENT:
            switch (event.window.event)
            {
            case SDL_WINDOWEVENT_MINIMIZED:
                *is_min = 1;
                break;
            case SDL_WINDOWEVENT_MAXIMIZED:
            case SDL_WINDOWEVENT_RESTORED:
                *is_min = 0;
                break;
            case SDL_WINDOWEVENT_SIZE_CHANGED:
                w = event.window.data1;
                h = event.window.data2;
                x_scale = (double)w / (double)ctx->width;
                y_scale = (double)h / (double)ctx->height;
                if (x_scale > y_scale)
                {
                    ctx->vp_rect.w = y_scale * ctx->width;
                    ctx->vp_rect.h = y_scale * ctx->height;
                    ctx->vp_rect.x = (w - ctx->vp_rect.w) / 2;
                    ctx->vp_rect.y = 0;
                }
                else
                {
                    ctx->vp_rect.w = x_scale * ctx->width;
                    ctx->vp_rect.h = x_scale * ctx->height;
                    ctx->vp_rect.x = 0;
                    ctx->vp_rect.y = (h - ctx->vp_rect.h) / 2;
                }
                break;
            default:
                break;
            }
            break;
        case SDL_KEYDOWN:
            break;
        case SDL_KEYUP:
            switch (event.key.keysym.scancode)
            {
            case SDL_SCANCODE_Q:
                code = L_EVENT_QUIT;
                break;
            case SDL_SCANCODE_SPACE:
                code = L_EVENT_PAUSE;
                break;
            case SDL_SCANCODE_RIGHT:
                code = L_EVENT_SEEK_RIGHT;
                data = 60;
                break;
            case SDL_SCANCODE_LEFT:
                code = L_EVENT_SEEK_LEFT;
                data = 60;
                break;
            case SDL_SCANCODE_A:
                code = L_EVENT_AUDIO_STREEM;
                break;
            case SDL_SCANCODE_M:
                code = L_EVENT_MUTE;
                break;
            case SDL_SCANCODE_I:
                code = L_EVENT_INFO;
                break;
            default:
                break;
            }
            if (code != L_EVENT_NONE)
            {
                user_event_t *event;

                event = (user_event_t *)malloc(sizeof(user_event_t));
                if (event)
                {
                    event->code = code;
                    event->data = data;
                    queue_push(ctx->common.event_queue, (queue_node_t *)event);
                }
                break;
            }
            if (event.key.keysym.scancode == SDL_SCANCODE_F)
                SDL_SetWindowFullscreen(ctx->window, SDL_WINDOW_FULLSCREEN_DESKTOP);
            else if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
                SDL_SetWindowFullscreen(ctx->window, 0);
            break;
        default:
            break;
        }
    }
}
Exemple #25
0
void LWindow::handleEvent(SDL_Event &e) {
  //Window event occured
  if(e.type == SDL_WINDOWEVENT) {
    //Caption update flag
    bool updateCaption = false;
    
    switch(e.window.event) {
      //Get new dimensions and repaint on window size change
    case SDL_WINDOWEVENT_SIZE_CHANGED:
      m_width  = e.window.data1;
      m_height = e.window.data2;
      SDL_RenderPresent(g_renderer);
      break;
      
      //Repaint on exposure
    case SDL_WINDOWEVENT_EXPOSED:
      SDL_RenderPresent(g_renderer);
      break;

      //Mouse entered window
    case SDL_WINDOWEVENT_ENTER:
      m_mouseFocus  = true;
      updateCaption = true;
      break;

      //Mouse left window
    case SDL_WINDOWEVENT_LEAVE:
      m_mouseFocus  = false;
      updateCaption = true;
      
      //Window has keyboard focus
    case SDL_WINDOWEVENT_FOCUS_GAINED:
      m_keyboardFocus  = true;
      updateCaption    = true;
      break;

      //Window lost keyboard focus
    case SDL_WINDOWEVENT_FOCUS_LOST:
      m_keyboardFocus  = false;
      updateCaption    = true;
      break;

      //Window minimized
    case SDL_WINDOWEVENT_MINIMIZED:
      m_minimized = true;
      break;

      //Window maximized
    case SDL_WINDOWEVENT_MAXIMIZED:
      m_minimized = false;
      break;

      //Window restored
    case SDL_WINDOWEVENT_RESTORED:
      m_minimized = false;
      break;
    }
    //Update window caption with new data
    if(updateCaption) {
      std::stringstream caption;
      caption << "SDL Tutorial - MouseFocus:" << ((m_mouseFocus) ? "On" : "Off") << "KeyboardFocus:" << ((m_keyboardFocus) ? "On" : "Off");
      SDL_SetWindowTitle(m_window, caption.str().c_str());
    }
  } else if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_RETURN) {
    if(m_fullScreen) {
      SDL_SetWindowFullscreen(m_window, SDL_FALSE);
      m_fullScreen = false;
    } else {
      SDL_SetWindowFullscreen(m_window, SDL_TRUE);
      m_fullScreen = true;
      m_minimized  = false;
    }
  }
}
int SetVideoMode(int w, int h, int bpp, bool gl)
{
	int flags = SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_FOCUS;
	static bool last_gl = false;
	static int last_x = SDL_WINDOWPOS_UNDEFINED;
	static int last_y = SDL_WINDOWPOS_UNDEFINED;

	if(gl) flags |= SDL_WINDOW_OPENGL;
	if(savedata.fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;

	if(!(SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN_DESKTOP))
		SDL_GetWindowPosition(window, &last_x, &last_y);

	if(window && gl != last_gl)
	{
		SDL_DestroyWindow(window);
		window = NULL;
	}
	last_gl = gl;

	if(renderer) SDL_DestroyRenderer(renderer);
	if(texture)  SDL_DestroyTexture(texture);
	renderer = NULL;
	texture = NULL;

	if(window)
	{
		if(savedata.fullscreen)
		{
			SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
		}
		else
		{
#ifndef WIN // hiding and showing the window is problematic on Windows
			if(SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN_DESKTOP)
				SDL_HideWindow(window);
#endif
			SDL_SetWindowFullscreen(window, 0);
			SDL_SetWindowSize(window, w, h);
			SDL_SetWindowPosition(window, last_x, last_y);
			SDL_ShowWindow(window);
		}
	}
	else
	{
		window = SDL_CreateWindow(windowTitle, last_x, last_y, w, h, flags);
		if(!window)
		{
			printf("Error: failed to create window: %s\n", SDL_GetError());
			return 0;
		}
		SDL_Surface* icon = (SDL_Surface*)pngToSurface((void*)openbor_icon_32x32_png.data);
		SDL_SetWindowIcon(window, icon);
		SDL_FreeSurface(icon);
		if(!savedata.fullscreen) SDL_GetWindowPosition(window, &last_x, &last_y);
	}
	
	if(!gl)
	{
		renderer = SDL_CreateRenderer(window, -1, 0);
		if(!renderer)
		{
			printf("Error: failed to create renderer: %s\n", SDL_GetError());
			return 0;
		}
	}

	return 1;
}
Exemple #27
0
bool window_set_fullscreen_windowed()
{
    if (SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP) < 0)
        printf("Error while setting fullscreen window: %s\n", SDL_GetError());
}
Exemple #28
0
int main(int argc, char **argv)
{
	MemStartCheck();
	{ char* test = new char[16]; delete[] test; }
	grinliz::TestContainers();

	{
		grinliz::GLString releasePath;
		GetSystemPath(GAME_SAVE_DIR, "release_log.txt", &releasePath);
		SetReleaseLog(fopen(releasePath.c_str(), "w"));
	}
	GLOUTPUT_REL(("Altera startup. version'%s'\n", VERSION));

	SDL_version compiled;
	SDL_version linked;

	SDL_VERSION(&compiled);
	SDL_GetVersion(&linked);

	GLOUTPUT_REL(("SDL version compiled: %d.%d.%d\n", compiled.major, compiled.minor, compiled.patch));
	GLOUTPUT_REL(("SDL version linked:   %d.%d.%d\n", linked.major, linked.minor, linked.patch));
	GLASSERT((linked.major == compiled.major && linked.minor == compiled.minor));

	// SDL initialization steps.
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_EVENTS) < 0)
	{
		fprintf(stderr, "SDL initialization failed: %s\n", SDL_GetError());
		exit(1);
	}

	//  OpenGL 4.3 provides full compatibility with OpenGL ES 3.0.
	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);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

#ifdef DEBUG
#if 0	// I was hoping to get to Angle on intel - may still be able to. But
	// as is this gets HW mode, which crashes in a function that should
	// be supported. The Intel drivers are so terrible. As of this writing,
	// you can't specify the DX version of ES:
	//		http://forums.libsdl.org/viewtopic.php?t=9770&highlight=angle+opengl
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);	// driver supports 2 and 3. Both crash.
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif
#if 0
	// 3.0 context.
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif
#if 0
	// The trickier 3.2 context.
	// No GL_QUADs anymore.
	// All the attributes need to be floats.
	// No ALPHA textures.
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
#endif
#if 0
	// In theory the minimum supported version:
	// has instancing, and modern shader syntax
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif
#if 0
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif
#endif

	if (multisample) {
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multisample);
	}

	SDL_DisplayMode displayMode;
	SDL_GetCurrentDisplayMode(0, &displayMode);

	int screenX = displayMode.w / 8;
	int screenY = displayMode.h / 8;
	int screenWidth = displayMode.w * 3 / 4;
	int screenHeight = displayMode.h * 3 / 4;

	if (argc == 3) {
		screenWidth = atoi(argv[1]);
		screenHeight = atoi(argv[2]);
		if (screenWidth <= 0) screenWidth = SCREEN_WIDTH;
		if (screenHeight <= 0) screenHeight = SCREEN_HEIGHT;
	}

	restoreWidth = screenWidth;
	restoreHeight = screenHeight;

	SDL_Window *screen = SDL_CreateWindow("Altera",
		screenX, screenY, screenWidth, screenHeight,
		/*SDL_WINDOW_FULLSCREEN | */ SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	GLASSERT(screen);
	SDL_GL_CreateContext(screen);

	int stencil = 0;
	int depth = 0;
	CHECK_GL_ERROR;
	SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil);
	SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth);
	glGetError();	// the above stencil/depth query sometimes does throw an error.
	glGetError();	// 2 queries, 2 errors.
	CHECK_GL_ERROR;
	GLOUTPUT_REL(("SDL screen created. stencil=%d depthBits=%d\n", stencil, depth));

	/* Verify there is a surface */
	if (!screen) {
		fprintf(stderr, "Video mode set failed: %s\n", SDL_GetError());
		exit(1);
	}

	CHECK_GL_ERROR;
	glewExperimental = GL_TRUE;
	int r = glewInit();
	GLASSERT(r == GL_NO_ERROR);
	(void)r;

	while (glGetError() != GL_NO_ERROR) {
		// around again
	}
	CHECK_GL_ERROR;

	const unsigned char* vendor = glGetString(GL_VENDOR);
	const unsigned char* renderer = glGetString(GL_RENDERER);
	const unsigned char* version = glGetString(GL_VERSION);

	GLOUTPUT_REL(("OpenGL vendor: '%s'  Renderer: '%s'  Version: '%s'\n", vendor, renderer, version));
	CHECK_GL_ERROR;

	bool done = false;
	bool zooming = false;
	SDL_Event event;

	grinliz::Vector2I mouseDown = { 0, 0 };
	grinliz::Vector2I rightMouseDown = { 0, 0 };

	int zoomX = 0;
	int zoomY = 0;
	// Used to compute fingers close, but problems:
	// - really to the OS to do that, because of all the tuning
	// - the coordinates are in windows normalized, so can't get the physical distance reliably.
	//bool fingersClose = true;
	int nFingers = 0;

	void* game = NewGame(screenWidth, screenHeight, 0);

	int modKeys = SDL_GetModState();
	U32 tickTimer = 0, lastTick = 0, thisTick = 0;

#ifdef OUTPUT_MOUSE_AND_TOUCH
	int value = GetSystemMetrics(SM_DIGITIZER);
	if (value & NID_INTEGRATED_TOUCH) GLOUTPUT(("NID_INTEGRATED_TOUCH\n"));
	if (value & NID_MULTI_INPUT) GLOUTPUT(("NID_MULTI_INPUT\n"));
	if (value & NID_READY) GLOUTPUT(("NID_READY\n"));
#endif

	grinliz::Vector2F multiTouchStart = { 0, 0 };

	// ---- Main Loop --- //
	while (!done) {
		while (SDL_PollEvent(&event)) {

			switch (event.type)
			{
				case SDL_WINDOWEVENT:
				if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
					screenWidth = event.window.data1;
					screenHeight = event.window.data2;
					GameDeviceLoss(game);
					GameResize(game, screenWidth, screenHeight, 0);
				}
				break;

				case SDL_KEYUP:
				switch (event.key.keysym.scancode)
				{
					case SDL_SCANCODE_LCTRL:	modKeys = modKeys & (~KMOD_LCTRL);		break;
					case SDL_SCANCODE_RCTRL:	modKeys = modKeys & (~KMOD_RCTRL);		break;
					case SDL_SCANCODE_LSHIFT:	modKeys = modKeys & (~KMOD_LSHIFT);		break;
					case SDL_SCANCODE_RSHIFT:	modKeys = modKeys & (~KMOD_RSHIFT);		break;
					default:
					break;
				}
				break;

				case SDL_KEYDOWN:
				{
					// sym or scancode? I used a dvorak keyboard, so appreciate
					// every day the difference. However, AWSD support is the 
					// primary thing so scancode is hopefully the better choice.
					switch (event.key.keysym.scancode)
					{
						case SDL_SCANCODE_LCTRL:	modKeys = modKeys | KMOD_LCTRL;		break;
						case SDL_SCANCODE_RCTRL:	modKeys = modKeys | KMOD_RCTRL;		break;
						case SDL_SCANCODE_LSHIFT:	modKeys = modKeys | KMOD_LSHIFT;	break;
						case SDL_SCANCODE_RSHIFT:	modKeys = modKeys | KMOD_RSHIFT;	break;

						case SDL_SCANCODE_F4:
						{
							int sdlMod = SDL_GetModState();
							if (sdlMod & (KMOD_RALT | KMOD_LALT))
								done = true;
						}
						break;

						case SDL_SCANCODE_ESCAPE:	GameHotKey(game, GAME_HK_ESCAPE);			break;
						case SDL_SCANCODE_SPACE:	GameHotKey(game, GAME_HK_TOGGLE_PAUSE);		break;
						case SDL_SCANCODE_RETURN:	GameHotKey(game, GAME_HK_DEBUG_ACTION);		break;
						case SDL_SCANCODE_F1:	GameHotKey(game, GAME_HK_TOGGLE_DEBUG_TEXT);	break;
						case SDL_SCANCODE_F2:	GameHotKey(game, GAME_HK_TOGGLE_DEBUG_UI);		break;
							// F3: screenshot
						case SDL_SCANCODE_TAB:	GameHotKey(game, GAME_HK_CAMERA_TOGGLE);		break;
						case SDL_SCANCODE_HOME:	GameHotKey(game, GAME_HK_CAMERA_CORE);			break;
						case SDL_SCANCODE_END:	GameHotKey(game, GAME_HK_CAMERA_AVATAR);		break;
						case SDL_SCANCODE_PAGEUP:	GameHotKey(game, GAME_HK_TELEPORT_AVATAR);	break;

							//case SDLK_a: reserved
						case SDL_SCANCODE_B:	GameHotKey(game, GAME_HK_CHEAT_GOLD);			break;
						case SDL_SCANCODE_C:	GameHotKey(game, GAME_HK_ATTACH_CORE);			break;
							//case SDLK_d: reserved
						case SDL_SCANCODE_E:	GameHotKey(game, GAME_HK_CHEAT_ELIXIR);			break;
						case SDL_SCANCODE_H:	GameHotKey(game, GAME_HK_TOGGLE_PATHING);		break;
						case SDL_SCANCODE_I:	GameHotKey(game, GAME_HK_TOGGLE_AI_DEBUG);		break;
						case SDL_SCANCODE_K:	GameHotKey(game, GAME_HK_CHEAT_CRYSTAL);		break;
						case SDL_SCANCODE_M:	GameHotKey(game, GAME_HK_MAP);					break;
						case SDL_SCANCODE_P:	GameHotKey(game, GAME_HK_TOGGLE_PERF);			break;
						case SDL_SCANCODE_Q:	GameHotKey(game, GAME_HK_CHEAT_HERD);			break;
							//case SDLK_s: reserved
						case SDL_SCANCODE_T:	GameHotKey(game, GAME_HK_CHEAT_TECH);			break;
						case SDL_SCANCODE_U:	GameHotKey(game, GAME_HK_TOGGLE_UI);			break;
							//case SDLK_w: reserved

						case SDL_SCANCODE_1:	GameHotKey(game, GAME_HK_TOGGLE_GLOW);			break;
						case SDL_SCANCODE_2:	GameHotKey(game, GAME_HK_TOGGLE_PARTICLE);		break;
						case SDL_SCANCODE_3:	GameHotKey(game, GAME_HK_TOGGLE_VOXEL);			break;
						case SDL_SCANCODE_4:	GameHotKey(game, GAME_HK_TOGGLE_SHADOW);		break;
						case SDL_SCANCODE_5:	GameHotKey(game, GAME_HK_TOGGLE_BOLT);			break;

						case SDL_SCANCODE_F3:
						GameDoTick(game, SDL_GetTicks());
						SDL_GL_SwapWindow(screen);
						ScreenCapture();
						break;

						case SDL_SCANCODE_F11:
						{
							if (fullscreen) {
								// SDL_RestoreWindow doesn't seem to work as I expect.
								SDL_SetWindowFullscreen(screen, 0);
								SDL_SetWindowSize(screen, restoreWidth, restoreHeight);
								fullscreen = false;
							}
							else {
								restoreWidth = screenWidth;
								restoreHeight = screenHeight;
								SDL_SetWindowFullscreen(screen, SDL_WINDOW_FULLSCREEN_DESKTOP);
								fullscreen = true;
							}
						}
						break;

						default:
						break;
					}
				}
				break;

				case SDL_MOUSEBUTTONDOWN:
				{
					int x = event.button.x;
					int y = event.button.y;

					int mod = 0;
					if (modKeys & (KMOD_LSHIFT | KMOD_RSHIFT))    mod = GAME_TAP_MOD_SHIFT;
					else if (modKeys & (KMOD_LCTRL | KMOD_RCTRL)) mod = GAME_TAP_MOD_CTRL;

					if (nFingers > 1) {
						// do nothing
					}
					else if (event.button.button == SDL_BUTTON_LEFT) {
						#ifdef OUTPUT_MOUSE_AND_TOUCH
						GLOUTPUT(("Left mouse down %d %d\n", x, y));
						#endif
						mouseDown.Set(event.button.x, event.button.y);
						GameTap(game, GAME_TAP_DOWN, x, y, mod);
					}
					else if (event.button.button == SDL_BUTTON_RIGHT) {
						#ifdef OUTPUT_MOUSE_AND_TOUCH
						GLOUTPUT(("Right mouse down %d %d\n", x, y));
						#endif
						GameTap(game, GAME_TAP_CANCEL, x, y, mod);
						rightMouseDown.Zero();
						if (mod == 0) {
							rightMouseDown.Set(event.button.x, event.button.y);
							GameCameraPan(game, GAME_PAN_START, float(x), float(y));
						}
						else if (mod == GAME_TAP_MOD_CTRL) {
							zooming = true;
							//GameCameraRotate( game, GAME_ROTATE_START, 0.0f );
							SDL_GetRelativeMouseState(&zoomX, &zoomY);
						}
					}
				}
				break;

				case SDL_MOUSEBUTTONUP:
				{
					int x = event.button.x;
					int y = event.button.y;

					if (event.button.button == SDL_BUTTON_RIGHT) {
						#ifdef OUTPUT_MOUSE_AND_TOUCH
						GLOUTPUT(("Right mouse up %d %d\n", x, y));
						#endif
						zooming = false;
						if (!rightMouseDown.IsZero()) {
							GameCameraPan(game, GAME_PAN_END, float(x), float(y));
							rightMouseDown.Zero();
						}
					}
					if (event.button.button == SDL_BUTTON_LEFT) {
						if (!mouseDown.IsZero()) {	// filter out mouse events that become finger events.
							#ifdef OUTPUT_MOUSE_AND_TOUCH
							GLOUTPUT(("Left mouse up %d %d\n", x, y));
							#endif
							int mod = 0;
							if (modKeys & (KMOD_LSHIFT | KMOD_RSHIFT))    mod = GAME_TAP_MOD_SHIFT;
							else if (modKeys & (KMOD_LCTRL | KMOD_RCTRL)) mod = GAME_TAP_MOD_CTRL;
							GameTap(game, GAME_TAP_UP, x, y, mod);
						}
					}
				}
				break;

				case SDL_MOUSEMOTION:
				{
					SDL_GetRelativeMouseState(&zoomX, &zoomY);
					int state = event.motion.state;
					int x = event.motion.x;
					int y = event.motion.y;

					int mod = 0;
					if (modKeys & (KMOD_LSHIFT | KMOD_RSHIFT))    mod = GAME_TAP_MOD_SHIFT;
					else if (modKeys & (KMOD_LCTRL | KMOD_RCTRL)) mod = GAME_TAP_MOD_CTRL;

					if (nFingers > 1) {
						// Do nothing.
						// Multi touch in progress.
					}
					else if (state & SDL_BUTTON(SDL_BUTTON_LEFT)) {
						if (!mouseDown.IsZero()) {
							#ifdef OUTPUT_MOUSE_AND_TOUCH
							GLOUTPUT(("Left Mouse move %d %d\n", x, y));
							#endif
							GameTap(game, GAME_TAP_MOVE, x, y, mod);
//							mouseMoveCount = 0;
						}
					}
					else if (!rightMouseDown.IsZero()) {
						GLASSERT(state & SDL_BUTTON(SDL_BUTTON_RIGHT));
						GameCameraPan(game, GAME_PAN_END, float(x), float(y));
					}
					else if (zooming && (state & SDL_BUTTON(SDL_BUTTON_RIGHT))) {
						float deltaZoom = 0.01f * (float)zoomY;
						GameZoom(game, GAME_ZOOM_DISTANCE, deltaZoom);
						GameCameraRotate(game, (float)(zoomX)*0.5f);
					}
					else if (state ==0) {
						GameTap(game, GAME_MOVE_WHILE_UP, x, y, mod);
					}
				}
				break;

				case SDL_MOUSEWHEEL:
				{
					if (event.wheel.y) {
						float deltaZoom = -0.1f * float(event.wheel.y);
						GameZoom(game, GAME_ZOOM_DISTANCE, deltaZoom);
					}
				}
				break;

				case SDL_FINGERUP:
				{
					const SDL_TouchFingerEvent* tfe = &event.tfinger;
					nFingers = SDL_GetNumTouchFingers(tfe->touchId);
					if (nFingers < 2 && !multiTouchStart.IsZero()) {
						#ifdef OUTPUT_MOUSE_AND_TOUCH
						GLOUTPUT(("2 finger END.\n"));
						#endif
						multiTouchStart.Zero();
					}
				}
				break;

				case SDL_FINGERDOWN:
				{
					const SDL_TouchFingerEvent* tfe = &event.tfinger;
					nFingers = SDL_GetNumTouchFingers(tfe->touchId);
					if (nFingers > 1) {
						if (!mouseDown.IsZero()) {
							// Wrap up the existing action.
							#ifdef OUTPUT_MOUSE_AND_TOUCH
							GLOUTPUT(("Switch to gesture.\n"));
							#endif
							mouseDown.Zero();
						}
					}
				}
				break;

				case SDL_MULTIGESTURE:
				{
					const SDL_MultiGestureEvent* mge = &event.mgesture;
					nFingers = SDL_GetNumTouchFingers(mge->touchId);
					if (nFingers > 1 && multiTouchStart.IsZero()) {
						#ifdef OUTPUT_MOUSE_AND_TOUCH
						GLOUTPUT(("2 finger START.\n"));
						#endif
						multiTouchStart.Set(mge->x, mge->y);
					}
					else if (!multiTouchStart.IsZero()) {
						// The Pan interacts badly with zoom and rotated. So instead of a continuous,
						// multi-event action do a bunch of "mini pans".
						GameCameraPan(game, GAME_PAN_START,
									  multiTouchStart.x * float(screenWidth), multiTouchStart.y*float(screenHeight));
						multiTouchStart.Set(mge->x, mge->y);
						GameCameraPan(game, GAME_PAN_MOVE,
									  multiTouchStart.x * float(screenWidth), multiTouchStart.y*float(screenHeight));
						GameCameraPan(game, GAME_PAN_END,
									  multiTouchStart.x * float(screenWidth), multiTouchStart.y*float(screenHeight));
					}

					if (nFingers == 2) {
						GameZoom(game, GAME_ZOOM_DISTANCE, -mge->dDist * 10.f);
						GameCameraRotate(game, -mge->dTheta * 100.0f);
						//GLOUTPUT(("MultiGestureEvent dTheta=%.4f dDist=%.4f x=%.4f y=%.4f nFing=%d\n", mge->dTheta, mge->dDist, mge->x, mge->y, mge->numFingers));
					}
				}
				break;

				case SDL_DOLLARGESTURE:
				{
					GLOUTPUT(("DollarGestureEvent\n"));
				}
				break;


				case SDL_QUIT:
				{
					done = true;
				}
				break;

				default:
				break;
			}
		}
		U32 delta = SDL_GetTicks() - tickTimer;
		if (delta < TIME_BETWEEN_FRAMES) {
			SDL_Delay(1);
			continue;
		}
		tickTimer = SDL_GetTicks();
		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LEQUAL);

		const U8* keys = SDL_GetKeyboardState(0);
		U32 tickDelta = thisTick - lastTick;
		if (tickDelta > 100) tickDelta = 100;

		float keyMoveSpeed = KEY_MOVE_SPEED * float(tickDelta) / float(TIME_BETWEEN_FRAMES);
		float keyZoomSpeed = KEY_ZOOM_SPEED * float(tickDelta) / float(TIME_BETWEEN_FRAMES);
		float keyRotatepeed = KEY_ROTATE_SPEED * float(tickDelta) / float(TIME_BETWEEN_FRAMES);

		if (keys[SDL_SCANCODE_DOWN] || keys[SDL_SCANCODE_S]) {
			if (modKeys & KMOD_CTRL)
				GameZoom(game, GAME_ZOOM_DISTANCE, keyZoomSpeed);
			else
				GameCameraMove(game, 0, -keyMoveSpeed);
		}
		if (keys[SDL_SCANCODE_UP] || keys[SDL_SCANCODE_W]) {
			if (modKeys & KMOD_CTRL)
				GameZoom(game, GAME_ZOOM_DISTANCE, -keyZoomSpeed);
			else
				GameCameraMove(game, 0, keyMoveSpeed);
		}
		if (keys[SDL_SCANCODE_LEFT] || keys[SDL_SCANCODE_A]) {
			if (modKeys & KMOD_CTRL)
				GameCameraRotate(game, keyRotatepeed);
			else
				GameCameraMove(game, -keyMoveSpeed, 0);
		}
		if (keys[SDL_SCANCODE_RIGHT] || keys[SDL_SCANCODE_D]) {
			if (modKeys & KMOD_CTRL)
				GameCameraRotate(game, -keyRotatepeed);
			else
				GameCameraMove(game, keyMoveSpeed, 0);
		}

		if (game) {
			lastTick = thisTick;
			thisTick = SDL_GetTicks();
			PROFILE_BLOCK(GameDoTick);
			GameDoTick(game, thisTick);
		}
		{
			PROFILE_BLOCK(Swap);
			SDL_GL_SwapWindow(screen);
		}
	}

	GameSave(game);
	DeleteGame(game);

	for (int i = 0; i < nModDB; ++i) {
		delete databases[i];
	}

	SDL_Quit();

#if SEND_CRASH_LOGS
	// Empty the file - quit went just fine.
	{
		FILE* fp = FOpen( "UFO_Running.txt", "w" );
		if ( fp )
			fclose( fp );
	}
#endif

	MemLeakCheck();
	return 0;
}
static bool sdl_ctx_set_video_mode(void *data, unsigned width, unsigned height,
                                   bool fullscreen)
{
   unsigned fsflag = 0;
   driver_t *driver     = driver_get_ptr();
   settings_t *settings = config_get_ptr();
   gfx_ctx_sdl_data_t *sdl = (gfx_ctx_sdl_data_t*)driver->video_context_data;

   (void)data;

   sdl->g_new_width  = width;
   sdl->g_new_height = height;

#ifdef HAVE_SDL2

   if (fullscreen)
   {
      if (settings->video.windowed_fullscreen)
         fsflag = SDL_WINDOW_FULLSCREEN_DESKTOP;
      else
         fsflag = SDL_WINDOW_FULLSCREEN;
   }

   if (sdl->g_win)
   {
      SDL_SetWindowSize(sdl->g_win, width, height);

      if (fullscreen)
         SDL_SetWindowFullscreen(sdl->g_win, fsflag);
   }
   else
   {
      unsigned display = settings->video.monitor_index;

      sdl->g_win = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED_DISPLAY(display),
                               SDL_WINDOWPOS_UNDEFINED_DISPLAY(display),
                               width, height, SDL_WINDOW_OPENGL | fsflag);
   }
#else
   if (fullscreen)
      fsflag = SDL_FULLSCREEN;

   sdl->g_win = SDL_SetVideoMode(width, height, 0, SDL_OPENGL | fsflag);
#endif

   if (!sdl->g_win)
      goto error;

#ifdef HAVE_SDL2
   if (sdl->g_ctx)
      driver->video_cache_context_ack = true;
   else
   {
      sdl->g_ctx = SDL_GL_CreateContext(sdl->g_win);

      if (!sdl->g_ctx)
         goto error;
   }
#endif

   sdl->g_full   = fullscreen;
   sdl->g_width  = width;
   sdl->g_height = height;

   return true;

error:
   RARCH_WARN("[SDL_GL]: Failed to set video mode: %s\n", SDL_GetError());
   return false;
}
Exemple #30
0
void
SDLTest_CommonEvent(SDLTest_CommonState * state, SDL_Event * event, int *done)
{
    int i;
    static SDL_MouseMotionEvent lastEvent;

    if (state->verbose & VERBOSE_EVENT) {
        SDLTest_PrintEvent(event);
    }

    switch (event->type) {
    case SDL_WINDOWEVENT:
        switch (event->window.event) {
        case SDL_WINDOWEVENT_CLOSE:
            {
                SDL_Window *window = SDL_GetWindowFromID(event->window.windowID);
                if (window) {
                    SDL_DestroyWindow(window);
                    for (i = 0; i < state->num_windows; ++i) {
                        if (window == state->windows[i]) {
                            state->windows[i] = NULL;
                            break;
                        }
                    }
                }
            }
            break;
        }
        break;
    case SDL_KEYDOWN:
        switch (event->key.keysym.sym) {
            /* Add hotkeys here */
        case SDLK_PRINTSCREEN: {
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    for (i = 0; i < state->num_windows; ++i) {
                        if (window == state->windows[i]) {
                            SDLTest_ScreenShot(state->renderers[i]);
                        }
                    }
                }
            }
            break;
        case SDLK_EQUALS:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-+ double the size of the window */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    int w, h;
                    SDL_GetWindowSize(window, &w, &h);
                    SDL_SetWindowSize(window, w*2, h*2);
                }
            }
            break;
        case SDLK_MINUS:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-- half the size of the window */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    int w, h;
                    SDL_GetWindowSize(window, &w, &h);
                    SDL_SetWindowSize(window, w/2, h/2);
                }
            }
            break;
        case SDLK_c:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-C copy awesome text! */
                SDL_SetClipboardText("SDL rocks!\nYou know it!");
                printf("Copied text to clipboard\n");
            }
            if (event->key.keysym.mod & KMOD_ALT) {
                /* Alt-C toggle a render clip rectangle */
                for (i = 0; i < state->num_windows; ++i) {
                    int w, h;
                    if (state->renderers[i]) {
                        SDL_Rect clip;
                        SDL_GetWindowSize(state->windows[i], &w, &h);
                        SDL_RenderGetClipRect(state->renderers[i], &clip);
                        if (SDL_RectEmpty(&clip)) {
                            clip.x = w/4;
                            clip.y = h/4;
                            clip.w = w/2;
                            clip.h = h/2;
                            SDL_RenderSetClipRect(state->renderers[i], &clip);
                        } else {
                            SDL_RenderSetClipRect(state->renderers[i], NULL);
                        }
                    }
                }
            }
            break;
        case SDLK_v:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-V paste awesome text! */
                char *text = SDL_GetClipboardText();
                if (*text) {
                    printf("Clipboard: %s\n", text);
                } else {
                    printf("Clipboard is empty\n");
                }
                SDL_free(text);
            }
            break;
        case SDLK_g:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-G toggle grab */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    SDL_SetWindowGrab(window, !SDL_GetWindowGrab(window) ? SDL_TRUE : SDL_FALSE);
                }
            }
            break;
        case SDLK_m:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-M maximize */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    Uint32 flags = SDL_GetWindowFlags(window);
                    if (flags & SDL_WINDOW_MAXIMIZED) {
                        SDL_RestoreWindow(window);
                    } else {
                        SDL_MaximizeWindow(window);
                    }
                }
            }
            break;
        case SDLK_r:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-R toggle mouse relative mode */
                SDL_SetRelativeMouseMode(!SDL_GetRelativeMouseMode() ? SDL_TRUE : SDL_FALSE);
            }
            break;
        case SDLK_z:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-Z minimize */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    SDL_MinimizeWindow(window);
                }
            }
            break;
        case SDLK_RETURN:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-Enter toggle fullscreen */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    Uint32 flags = SDL_GetWindowFlags(window);
                    if (flags & SDL_WINDOW_FULLSCREEN) {
                        SDL_SetWindowFullscreen(window, SDL_FALSE);
                    } else {
                        SDL_SetWindowFullscreen(window, SDL_TRUE);
                    }
                }
            } else if (event->key.keysym.mod & KMOD_ALT) {
                /* Alt-Enter toggle fullscreen desktop */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    Uint32 flags = SDL_GetWindowFlags(window);
                    if (flags & SDL_WINDOW_FULLSCREEN) {
                        SDL_SetWindowFullscreen(window, SDL_FALSE);
                    } else {
                        SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
                    }
                }
            }
            break;
        case SDLK_b:
            if (event->key.keysym.mod & KMOD_CTRL) {
                /* Ctrl-B toggle window border */
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                if (window) {
                    const Uint32 flags = SDL_GetWindowFlags(window);
                    const SDL_bool b = ((flags & SDL_WINDOW_BORDERLESS) != 0) ? SDL_TRUE : SDL_FALSE;
                    SDL_SetWindowBordered(window, b);
                }
            }
            break;
        case SDLK_0:
            if (event->key.keysym.mod & KMOD_CTRL) {
                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
                SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Test Message", "You're awesome!", window);
            }
            break;
        case SDLK_1:
            if (event->key.keysym.mod & KMOD_CTRL) {
                FullscreenTo(0, event->key.windowID);
            }
            break;
        case SDLK_2:
            if (event->key.keysym.mod & KMOD_CTRL) {
                FullscreenTo(1, event->key.windowID);
            }
            break;
        case SDLK_ESCAPE:
            *done = 1;
            break;
        case SDLK_SPACE:
        {
            char message[256];
            SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);

            SDL_snprintf(message, sizeof(message), "(%i, %i), rel (%i, %i)\n", lastEvent.x, lastEvent.y, lastEvent.xrel, lastEvent.yrel);
            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Last mouse position", message, window);
            break;
        }
        default:
            break;
        }
        break;
    case SDL_QUIT:
        *done = 1;
        break;
    case SDL_MOUSEMOTION:
        lastEvent = event->motion;
        break;
    }
}