Exemplo n.º 1
0
visualiserWin::visualiserWin(int argc, char* argv[])
{
    // Set the local members to default values.
    this->desiredFrameRate = 0;
    this->shouldVsync = true;
    this->currentVis = NULL;
    this->shouldCloseWindow = false;
    this->width = 800;
    this->height = 600;
    bool fullscreen = false;
    MPDMode = false;
    mpdError = false;
    char opt;
    // Parse the options. Note, we don't check the default
    // case as there may be other options that are specified
    // for other parts of the program (such as visualisers).
    opterr = 0;
    while((opt = getopt(argc, argv, "s:fm:")) != -1)
    {
        switch(opt)
        {
        case 's': // Window Size.
        {
            char* tok = strtok(optarg, "x");
            if(!tok)
                throw(argException("Window size not formatted properly."));

            // TODO: Use strtol as it has error checking.
            width = atoi(tok);

            tok = strtok(NULL, "x");
            if(!tok)
                throw(argException("Window size not formatted properly."));
            height = atoi(tok);
            break;
        }
        case 'f': // Fullscreen.
            fullscreen = true;
            break;
        case 'm':
            MPDFile = optarg;
            MPDMode = true;
            break;
        }
    }

    // If fullscreen is set, detect the resolution.
    if(fullscreen)
    {
        const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
        width = videoInfo->current_w;
        height = videoInfo->current_h;
    }

    // Set the OpenGL attributes
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    if(shouldVsync)
        SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);

    // Create the DSP manmager
    dspman = new DSPManager();

    // Create the window
    if(fullscreen)
        drawContext = SDL_SetVideoMode(width, height, 0,
                                       SDL_FULLSCREEN | SDL_OPENGL);
    else
        drawContext = SDL_SetVideoMode(width, height, 0, SDL_OPENGL);
    if(drawContext == NULL)
        throw(SDLException());

    // also initialise the standard event handlers.
    initialiseStockEventHandlers();
}
Exemplo n.º 2
0
	bool InitSDL(char* winName, int width, int height, int bpp, bool vsync, bool fscreen)
	{
		gLog.OutPut("\n[Initializing Video Settings]\n");
#ifdef USE_SDL2
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) < 0)
#else
		const SDL_VideoInfo* info = NULL;
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) < 0 || !(info = SDL_GetVideoInfo()))
#endif
		{
			gLog.OutPut("\n[Failed to initialize Video Settings]\n");
			return false;
		}
#ifdef USE_SDL2
		int flags = SDL_WINDOW_OPENGL | (fscreen?SDL_WINDOW_FULLSCREEN_DESKTOP:0);
#else
		int flags = SDL_OPENGL | (fscreen?SDL_FULLSCREEN:0);
		SDL_WM_SetIcon(SDL_LoadBMP("icon1.bmp"), NULL);
#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_STENCIL_SIZE, 16);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
		SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0);
		SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
*/
		SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
		SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, 0);
#ifdef USE_SDL2
		glWindow = SDL_CreateWindow("Prototype", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags);
		if(!glWindow)
		{
			SDL_Quit();
			return false;
		}
		glContext = SDL_GL_CreateContext(glWindow);
		if(!glContext)
		{
			SDL_Quit();
			return false;
		}
		SDL_SetWindowIcon(glWindow, SDL_LoadBMP("icon1.bmp"));
		GetWindowSizeSDL2(width, height);
#else
		if(SDL_SetVideoMode(width, height, bpp, flags) == 0)
		{
			SDL_Quit();
			return false;
		}
#endif
		stringstream(str);
		str << "Resolution Set: " << width << "x" << height << "x" << bpp << endl;
		gLog.OutPut(str.str());
/*		if(!vsync)
		{
			PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT  = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
			if(wglSwapIntervalEXT==NULL)
				PostQuitMessage(0);
			wglSwapIntervalEXT(0);
			gLog.OutPut("Vsync Disabled.\n");
		}
		else
		{
			PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT  = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
			if(wglSwapIntervalEXT==NULL)
				PostQuitMessage(0);
			wglSwapIntervalEXT(1);
			gLog.OutPut("Vsync Enabled.\n");
		}
*/		SDL_ShowCursor(0);
#ifdef USE_SDL2
		SDL_SetWindowTitle(glWindow, winName);
#else
		SDL_WM_SetCaption(winName, NULL);
#endif
		gLog.OutPut("Complete...\n\n");
		return true;
	}
Exemplo n.º 3
0
static int jiveL_initSDL(lua_State *L) {
	const SDL_VideoInfo *video_info;
#ifndef JIVE_NO_DISPLAY
	JiveSurface *srf, *splash;
	Uint16 splash_w, splash_h;
	bool fullscreen = false;
	char splashfile[32] = "jive/splash.png";
#endif
	/* logging */
	log_ui_draw = LOG_CATEGORY_GET("squeezeplay.ui.draw");
	log_ui = LOG_CATEGORY_GET("squeezeplay.ui");

	/* linux fbcon does not need a mouse */
	SDL_putenv("SDL_NOMOUSE=1");

#ifdef JIVE_NO_DISPLAY
#   define JIVE_SDL_FEATURES (SDL_INIT_EVENTLOOP)
#else
#   define JIVE_SDL_FEATURES (SDL_INIT_VIDEO)
#endif
	/* initialise SDL */
	if (SDL_Init(JIVE_SDL_FEATURES) < 0) {
		LOG_ERROR(log_ui_draw, "SDL_Init(V|T|A): %s\n", SDL_GetError());
		SDL_Quit();
		exit(-1);
	}

	/* report video info */
	if ((video_info = SDL_GetVideoInfo())) {
		LOG_INFO(log_ui_draw, "%d,%d %d bits/pixel %d bytes/pixel [R<<%d G<<%d B<<%d]", video_info->current_w, video_info->current_h, video_info->vfmt->BitsPerPixel, video_info->vfmt->BytesPerPixel, video_info->vfmt->Rshift, video_info->vfmt->Gshift, video_info->vfmt->Bshift);
		LOG_INFO(log_ui_draw, "Hardware acceleration %s available", video_info->hw_available?"is":"is not");
		LOG_INFO(log_ui_draw, "Window Manager %s available", video_info->wm_available?"is":"is not");
	}

	/* Register callback for additional events (used for multimedia keys)*/
	SDL_EventState(SDL_SYSWMEVENT,SDL_ENABLE);
	SDL_SetEventFilter(filter_events);

	// Secific magic for windows|linux|macos
	platform_init(L);

#ifndef JIVE_NO_DISPLAY

	/* open window */
	SDL_WM_SetCaption("SqueezePlay", "SqueezePlay");
	SDL_ShowCursor(SDL_DISABLE);
	SDL_EnableKeyRepeat (100, 100);
	SDL_EnableUNICODE(1);


#ifdef SCREEN_ROTATION_ENABLED
	screen_w = video_info->current_h;
	screen_h = video_info->current_w;
#else
	screen_w = video_info->current_w;
	screen_h = video_info->current_h;
#endif
	screen_bpp = video_info->vfmt->BitsPerPixel;

	if (video_info->wm_available) {
		/* desktop build */
		JiveSurface *icon;

		/* load the icon */
		icon = jive_surface_load_image("jive/app.png");
		if (icon) {
			jive_surface_set_wm_icon(icon);
			jive_surface_free(icon);
		}

		splash = jive_surface_load_image(splashfile);
		if (splash) {
			jive_surface_get_size(splash, &splash_w, &splash_h);

			screen_w = splash_w;
			screen_h = splash_h;
		}
	} else {
		/* product build and full screen...*/

		sprintf(splashfile, "jive/splash%dx%d.png", screen_w, screen_h);

		splash = jive_surface_load_image(splashfile);
		if(!splash) {
			sprintf(splashfile,"jive/splash.png");
			splash = jive_surface_load_image(splashfile);
		}

		if (splash) {
			jive_surface_get_size(splash, &splash_w, &splash_h);
		}

		fullscreen = true;
	}

	srf = jive_surface_set_video_mode(screen_w, screen_h, screen_bpp, fullscreen);
	if (!srf) {
		LOG_ERROR(log_ui_draw, "Video mode not supported: %dx%d\n", screen_w, screen_h);

		SDL_Quit();
		exit(-1);
	}

	if (splash) {
		jive_surface_blit(splash, srf, (screen_w - splash_w) > 0 ?((screen_w - splash_w) / 2):0, (screen_w - splash_w) > 0 ?((screen_w - splash_w) / 2):0);
		jive_surface_flip(srf);
		LOG_INFO(log_ui_draw, "Splash %s %dx%d Screen %dx%d", splashfile,splash_w,splash_h,screen_w,screen_h);
	}

	lua_getfield(L, 1, "screen");
	if (lua_isnil(L, -1)) {
		LOG_ERROR(log_ui_draw, "no screen table");

		SDL_Quit();
		exit(-1);
	}

	/* store screen surface */
	tolua_pushusertype(L, srf, "Surface");
	lua_setfield(L, -2, "surface");

	lua_getfield(L, -1, "bounds");
	lua_pushinteger(L, screen_w);
	lua_rawseti(L, -2, 3);
	lua_pushinteger(L, screen_h);
	lua_rawseti(L, -2, 4);
	lua_pop(L, 2);

	/* background image */
	jive_background = jive_tile_fill_color(0x000000FF);

	/* jive.ui.style = {} */
	lua_getglobal(L, "jive");
	lua_getfield(L, -1, "ui");
	lua_newtable(L);
	lua_setfield(L, -2, "style");
	lua_pop(L, 2);

	ui_watchdog = watchdog_get();
	watchdog_keepalive(ui_watchdog, 6); /* 60 seconds to start */

#endif /* JIVE_NO_DISPLAY */

	return 0;
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0)
        fprintf(stderr, "Couldn't init SDL!\n");

    atexit(SDL_Quit);

    // Get the current desktop width & height
    const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();

    // TODO: get this from config file.
    s_config = new Config(false, false, 768/2, 1024/2);
    Config& config = *s_config;
    config.title = "glyphblaster test";

    // msaa
    if (config.msaa)
    {
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, config.msaaSamples);
    }

    SDL_Surface* screen;
    if (config.fullscreen)
    {
        int width = videoInfo->current_w;
        int height = videoInfo->current_h;
        int bpp = videoInfo->vfmt->BitsPerPixel;
        screen = SDL_SetVideoMode(width, height, bpp,
                                  SDL_HWSURFACE | SDL_OPENGL | SDL_FULLSCREEN);
    }
    else
    {
        screen = SDL_SetVideoMode(config.width, config.height, 32, SDL_HWSURFACE | SDL_OPENGL);
    }

    SDL_WM_SetCaption(config.title.c_str(), config.title.c_str());

    if (!screen)
        fprintf(stderr, "Couldn't create SDL screen!\n");

    // clear to white
    Vector4f clearColor(0, 0, 0, 1);
    glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    SDL_GL_SwapBuffers();

    // create the context
    GB_ERROR err;
    GB_Context* gb;
    err = GB_ContextMake(512, 3, GB_TEXTURE_FORMAT_ALPHA, &gb);
    if (err != GB_ERROR_NONE) {
        fprintf(stderr, "GB_Init Error %d\n", err);
        exit(1);
    }

    // load lorem.txt
    int fd = open("utf8-test.txt", O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "open failed\n");
        exit(1);
    }
    struct stat s;
    if (fstat(fd, &s) < 0) {
        fprintf(stderr, "fstat failed\n errno = %d\n", errno);
        exit(1);
    }
    const uint8_t* lorem = (uint8_t*)mmap(0, s.st_size + 1, PROT_READ, MAP_PRIVATE, fd, 0);
    if (lorem < 0) {
        fprintf(stderr, "mmap failed\n errno = %d\n", errno);
        exit(1);
    }
    // we are lazy, don't unmap the file.

    // create a font
    GB_Font* mainFont = NULL;
    //err = GB_FontMake(gb, "Droid-Sans/DroidSans.ttf", 20, GB_RENDER_NORMAL, GB_HINT_FORCE_AUTO, &mainFont);
    //err = GB_FontMake(gb, "Arial.ttf", 48, GB_RENDER_NORMAL, GB_HINT_DEFAULT, &mainFont);
    //err = GB_FontMake(gb, "Ayuthaya.ttf", 16, GB_RENDER_NORMAL, GB_HINT_DEFAULT, &mainFont);
    err = GB_FontMake(gb, "dejavu-fonts-ttf-2.33/ttf/DejaVuSans.ttf", 10, GB_RENDER_NORMAL, GB_HINT_DEFAULT, &mainFont);
    //err = GB_FontMake(gb, "Zar/XB Zar.ttf", 48, GB_RENDER_NORMAL, GB_HINT_DEFAULT, &mainFont);
    //err = GB_FontMake(gb, "Times New Roman.ttf", 20, GB_RENDER_NORMAL, GB_HINT_FORCE_AUTO, &mainFont);
    if (err != GB_ERROR_NONE) {
        fprintf(stderr, "GB_MakeFont Error %s\n", GB_ErrorToString(err));
        exit(1);
    }


    GB_Font* arabicFont = NULL;
    /*
    // create an arabic font
    err = GB_FontMake(gb, "Zar/XB Zar.ttf", 48, &arabicFont);
    if (err != GB_ERROR_NONE) {
    fprintf(stderr, "GB_MakeFont Error %s\n", GB_ErrorToString(err));
    exit(1);
    }
    */

    // create a text
    uint32_t origin[2] = {0, 0};
    uint32_t size[2] = {videoInfo->current_w - 1, videoInfo->current_h};
    GB_Text* helloText = NULL;
    uint32_t textColor = MakeColor(255, 255, 255, 255);
    uint32_t* userData = (uint32_t*)malloc(sizeof(uint32_t));
    *userData = textColor;
    err = GB_TextMake(gb, (uint8_t*)lorem, mainFont, userData, origin, size,
                      GB_HORIZONTAL_ALIGN_LEFT, GB_VERTICAL_ALIGN_CENTER, 0, &helloText);
    if (err != GB_ERROR_NONE) {
        fprintf(stderr, "GB_MakeText Error %s\n", GB_ErrorToString(err));
        exit(1);
    }

    //GB_TextRelease(gb, helloText);

    /*
    // أبجد hello
    const char abjad[] = {0xd8, 0xa3, 0xd8, 0xa8, 0xd8, 0xac, 0xd8, 0xaf, 0x00};
    char XXX[1024];
    sprintf(XXX, "%s hello", abjad);
    err = GB_TextMake(gb, XXX, mainFont, 0xffffffff, origin, size,
    GB_HORIZONTAL_ALIGN_CENTER, GB_VERTICAL_ALIGN_CENTER, &helloText);
    */

    int done = 0;
    while (!done)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            switch (event.type)
            {
            case SDL_QUIT:
                done = 1;
                break;

            case SDL_MOUSEMOTION:
                if (event.motion.state & SDL_BUTTON(1)) {
                    // move touch
                }
                break;

            case SDL_MOUSEBUTTONDOWN:
                if (event.button.button == SDL_BUTTON_LEFT) {
                    // start touch
                }
                break;

            case SDL_MOUSEBUTTONUP:
                if (event.button.button == SDL_BUTTON_LEFT) {
                    // end touch
                }
                break;

            case SDL_JOYAXISMOTION:
                // stick move
                break;

            case SDL_JOYBUTTONDOWN:
            case SDL_JOYBUTTONUP:
                // joy pad press
                break;
            }
        }

        if (!done)
        {
            glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            //DebugDrawGlyphCache(gb, config);

            RenderText(helloText->glyph_quads, helloText->num_glyph_quads);

            SDL_GL_SwapBuffers();
        }
    }

    err = GB_TextRelease(gb, helloText);
    if (err != GB_ERROR_NONE) {
        fprintf(stderr, "GB_ReleaseText Error %s\n", GB_ErrorToString(err));
        exit(1);
    }
    err = GB_FontRelease(gb, mainFont);
    if (err != GB_ERROR_NONE) {
        fprintf(stderr, "GB_ReleaseFont Error %s\n", GB_ErrorToString(err));
        exit(1);
    }
    if (arabicFont) {
        err = GB_FontRelease(gb, arabicFont);
        if (err != GB_ERROR_NONE) {
            fprintf(stderr, "GB_ReleaseFont Error %s\n", GB_ErrorToString(err));
            exit(1);
        }
    }
    err = GB_ContextRelease(gb);
    if (err != GB_ERROR_NONE) {
        fprintf(stderr, "GB_Shutdown Error %s\n", GB_ErrorToString(err));
        exit(1);
    }

    return 0;
}
Exemplo n.º 5
0
BOOL scrnmng_create(int width, int height) {

    char			s[256];
    const SDL_VideoInfo	*vinfo;
    SDL_Surface		*surface;
    SDL_PixelFormat	*fmt;
    BOOL			r;

    if (SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
        fprintf(stderr, "Error: SDL_Init: %s\n", SDL_GetError());
        return(FAILURE);
    }
    SDL_WM_SetCaption(app_name, app_name);
    vinfo = SDL_GetVideoInfo();
    if (vinfo == NULL) {
        fprintf(stderr, "Error: SDL_GetVideoInfo: %s\n", SDL_GetError());
        return(FAILURE);
    }
    SDL_VideoDriverName(s, sizeof(s));

    surface = SDL_SetVideoMode(width, height, vinfo->vfmt->BitsPerPixel,
                               SDL_HWSURFACE | SDL_ANYFORMAT | SDL_DOUBLEBUF | SDL_FULLSCREEN);
    if (surface == NULL) {
        fprintf(stderr, "Error: SDL_SetVideoMode: %s\n", SDL_GetError());
        return(FAILURE);
    }

    r = FALSE;
    fmt = surface->format;
#if defined(SUPPORT_8BPP)
    if (fmt->BitsPerPixel == 8) {
        r = TRUE;
    }
#endif
#if defined(SUPPORT_16BPP)
    if ((fmt->BitsPerPixel == 16) && (fmt->Rmask == 0xf800) &&
            (fmt->Gmask == 0x07e0) && (fmt->Bmask == 0x001f)) {
        r = TRUE;
    }
#endif
#if defined(SUPPORT_24BPP)
    if (fmt->BitsPerPixel == 24) {
        r = TRUE;
    }
#endif
#if defined(SUPPORT_32BPP)
    if (fmt->BitsPerPixel == 32) {
        r = TRUE;
    }
#endif
#if defined(SCREEN_BPP)
    if (fmt->BitsPerPixel != SCREEN_BPP) {
        r = FALSE;
    }
#endif
    if (r) {
        scrnmng.enable = TRUE;
        scrnmng.width = width;
        scrnmng.height = height;
        scrnmng.bpp = fmt->BitsPerPixel;
        return(SUCCESS);
    }
    else {
        fprintf(stderr, "Error: Bad screen mode");
        return(FAILURE);
    }
}
Exemplo n.º 6
0
void SDLAppDisplay::toggleFullscreen() {

    int width  = this->width;
    int height = this->height;

    if(!fullscreen) {

        //save windowed width and height
        windowed_width  = width;
        windowed_height = height;

        int fullscreen_width  = desktop_width;
        int fullscreen_height = desktop_height;
            
        float aspect_ratio = fullscreen_width / (float) fullscreen_height;
        
        // if the aspect ratio suggests the person is using multiple monitors
        // find a supported resolution with a lower aspect ratio with the same
        // fullscreen height

#if SDL_VERSION_ATLEAST(1,3,0)
        // TODO: do something with the 1.3 API here
#else
        if(aspect_ratio >= 2.5) {
        
            SDL_Rect** modes = SDL_ListModes(0, SDLFlags(true));
        
            if(modes != (SDL_Rect**)0 && modes != (SDL_Rect**)-1) {
            
                for (int i=0; modes[i]; i++) {
                    if(modes[i]->h == fullscreen_height && (modes[i]->w/(float)modes[i]->h) < 2.5) {
                        fullscreen_width = modes[i]->w;
                        break;
                    }
                }
            }
        }
#endif

        width  = fullscreen_width;
        height = fullscreen_height;
        
    } else {
        //switch back to window dimensions, if known
        if(windowed_width != 0) {
            width  = windowed_width;
            height = windowed_height;
        }
    }

    fullscreen = !fullscreen;

    setVideoMode(width, height, fullscreen);

    int resized_width, resized_height;

#if SDL_VERSION_ATLEAST(1,3,0)
    SDL_GetWindowSize(sdl_window, &resized_width, &resized_height);
#else
    const SDL_VideoInfo* display_info = SDL_GetVideoInfo();

    resized_width  = display_info->current_w;
    resized_height = display_info->current_h;
#endif

    //set viewport to match what we ended up on
    glViewport(0, 0, resized_width, resized_height);

    this->width  = resized_width;
    this->height = resized_height;
}
Exemplo n.º 7
0
int
main(int argc, char *argv[])
{
    const SDL_VideoInfo *info;
    int i, d, n;
    const char *driver;
    SDL_DisplayMode mode;
    int bpp;
    Uint32 Rmask, Gmask, Bmask, Amask;
    int nmodes;

    /* Print available video drivers */
    n = SDL_GetNumVideoDrivers();
    if (n == 0) {
        printf("No built-in video drivers\n");
    } else {
        printf("Built-in video drivers:");
        for (i = 0; i < n; ++i) {
            if (i > 0) {
                printf(",");
            }
            printf(" %s", SDL_GetVideoDriver(i));
        }
        printf("\n");
    }

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }
    driver = SDL_GetCurrentVideoDriver();
    if (driver) {
        printf("Video driver: %s\n", driver);
    }
    printf("Number of displays: %d\n", SDL_GetNumVideoDisplays());
    for (d = 0; d < SDL_GetNumVideoDisplays(); ++d) {
        printf("Display %d:\n", d);
        SDL_SelectVideoDisplay(d);

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

        /* Print available fullscreen video modes */
        nmodes = SDL_GetNumDisplayModes();
        if (nmodes == 0) {
            printf("No available fullscreen video modes\n");
        } else {
            printf("  Fullscreen video modes:\n");
            for (i = 0; i < nmodes; ++i) {
                SDL_GetDisplayMode(i, &mode);
                SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                           &Gmask, &Bmask, &Amask);
                printf("    Mode %d: %dx%[email protected]%dHz, %d bits-per-pixel\n", i,
                       mode.w, mode.h, mode.refresh_rate, bpp);
                if (Rmask || Gmask || Bmask) {
                    printf("        Red Mask = 0x%.8x\n", Rmask);
                    printf("        Green Mask = 0x%.8x\n", Gmask);
                    printf("        Blue Mask = 0x%.8x\n", Bmask);
                    if (Amask)
                        printf("        Alpha Mask = 0x%.8x\n", Amask);
                }
            }
        }
    }

    info = SDL_GetVideoInfo();
    if (info->wm_available) {
        printf("A window manager is available\n");
    }
    if (info->hw_available) {
        printf("Hardware surfaces are available (%dK video memory)\n",
               info->video_mem);
    }
    if (info->blit_hw) {
        printf("Copy blits between hardware surfaces are accelerated\n");
    }
    if (info->blit_hw_CC) {
        printf("Colorkey blits between hardware surfaces are accelerated\n");
    }
    if (info->blit_hw_A) {
        printf("Alpha blits between hardware surfaces are accelerated\n");
    }
    if (info->blit_sw) {
        printf
            ("Copy blits from software surfaces to hardware surfaces are accelerated\n");
    }
    if (info->blit_sw_CC) {
        printf
            ("Colorkey blits from software surfaces to hardware surfaces are accelerated\n");
    }
    if (info->blit_sw_A) {
        printf
            ("Alpha blits from software surfaces to hardware surfaces are accelerated\n");
    }
    if (info->blit_fill) {
        printf("Color fills on hardware surfaces are accelerated\n");
    }
    printf("Current resolution: %dx%d\n", info->current_w, info->current_h);
#if 0
    if (argv[1] && (strcmp(argv[1], "-benchmark") == 0)) {
        RunVideoTests();
    }
#endif

    SDL_Quit();
    return (0);
}
Exemplo n.º 8
0
void OSystem_SDL::initBackend() {
	// Check if backend has not been initialized
	assert(!_inited);

#if SDL_VERSION_ATLEAST(2, 0, 0)
	const char *sdlDriverName = SDL_GetCurrentVideoDriver();
#else
	const int maxNameLen = 20;
	char sdlDriverName[maxNameLen];
	sdlDriverName[0] = '\0';
	SDL_VideoDriverName(sdlDriverName, maxNameLen);
#endif
	// Using printf rather than debug() here as debug()/logging
	// is not active by this point.
	debug(1, "Using SDL Video Driver \"%s\"", sdlDriverName);

	// Create the default event source, in case a custom backend
	// manager didn't provide one yet.
	if (_eventSource == 0)
		_eventSource = new SdlEventSource();

#ifdef USE_OPENGL
#if SDL_VERSION_ATLEAST(2, 0, 0)
	SDL_DisplayMode displayMode;
	if (!SDL_GetDesktopDisplayMode(0, &displayMode)) {
		_desktopWidth  = displayMode.w;
		_desktopHeight = displayMode.h;
	}
#else
	// Query the desktop resolution. We simply hope nothing tried to change
	// the resolution so far.
	const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo();
	if (videoInfo && videoInfo->current_w > 0 && videoInfo->current_h > 0) {
		_desktopWidth  = videoInfo->current_w;
		_desktopHeight = videoInfo->current_h;
	}
#endif
#endif

	if (_graphicsManager == 0) {
#ifdef USE_OPENGL
		// Setup a list with both SDL and OpenGL graphics modes. We only do
		// this whenever the subclass did not already set up an graphics
		// manager yet. This is because we don't know the type of the graphics
		// manager of the subclass, thus we cannot easily switch between the
		// OpenGL one and the set up one. It also is to be expected that the
		// subclass does not want any switching of graphics managers anyway.
		setupGraphicsModes();

		if (ConfMan.hasKey("gfx_mode")) {
			// If the gfx_mode is from OpenGL, create the OpenGL graphics manager
			Common::String gfxMode(ConfMan.get("gfx_mode"));
			for (uint i = _firstGLMode; i < _graphicsModeIds.size(); ++i) {
				if (!scumm_stricmp(_graphicsModes[i].name, gfxMode.c_str())) {
					_graphicsManager = new OpenGLSdlGraphicsManager(_desktopWidth, _desktopHeight, _eventSource, _window);
					_graphicsMode = i;
					break;
				}
			}
		}
#endif

		if (_graphicsManager == 0) {
			_graphicsManager = new SurfaceSdlGraphicsManager(_eventSource, _window);
		}
	}

	if (_savefileManager == 0)
		_savefileManager = new DefaultSaveFileManager();

	if (_mixerManager == 0) {
		_mixerManager = new SdlMixerManager();
		// Setup and start mixer
		_mixerManager->init();
	}

#ifdef ENABLE_EVENTRECORDER
	g_eventRec.registerMixerManager(_mixerManager);

	g_eventRec.registerTimerManager(new SdlTimerManager());
#else
	if (_timerManager == 0)
		_timerManager = new SdlTimerManager();
#endif

	_audiocdManager = createAudioCDManager();

	// Setup a custom program icon.
	_window->setupIcon();

	_inited = true;

	ModularBackend::initBackend();

	// We have to initialize the graphics manager before the event manager
	// so the virtual keyboard can be initialized, but we have to add the
	// graphics manager as an event observer after initializing the event
	// manager.
	dynamic_cast<SdlGraphicsManager *>(_graphicsManager)->activateManager();
}
Exemplo n.º 9
0
SDL_Surface *initialization(int flags)
{
	const SDL_VideoInfo* info = 0;
	int bpp = 0;
	SDL_Surface *screen;

	rg = new TRanrotBGenerator(0);

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Initializing SDL\n");
#endif

	if (SDL_Init(SDL_INIT_VIDEO | (sound ? SDL_INIT_AUDIO : 0) | SDL_INIT_JOYSTICK | SDL_INIT_EVENTTHREAD) < 0) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Video initialization failed: %s\n", SDL_GetError());
#endif

		return 0;
	} 

#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("SDL initialized\n");

#endif

	info = SDL_GetVideoInfo();

	if (!info) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Video query failed: %s\n", SDL_GetError());
#endif

		return 0;
	} 

	if (fullscreen) {
		bpp = COLOUR_DEPTH;
	} else {
		bpp = info->vfmt->BitsPerPixel;
	}

	desktopW = info->current_w;
	desktopH = info->current_h;
#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("Setting OpenGL attributes\n");

#endif
#ifndef HAVE_GLES
	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_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#endif
#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("OpenGL attributes set\n");

#endif

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Initializing video mode\n");

#endif
#ifdef HAVE_GLES
	fullscreen = true;
	flags = SDL_FULLSCREEN;
#else
	flags = SDL_OPENGL | flags;
#endif
	screen = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, bpp, flags);

	if (screen == 0) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Video mode set failed: %s\n", SDL_GetError());
#endif

		return 0;
	} 
#ifdef HAVE_GLES
	EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);
#endif

#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("Video mode initialized\n");

#endif

	calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);

	SDL_WM_SetCaption(application_name, 0);

	SDL_WM_SetIcon(SDL_LoadBMP("graphics/f1sicon.bmp"), NULL);

	SDL_ShowCursor(SDL_DISABLE);

	if (sound) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Initializing Audio\n");
#endif

		N_SFX_CHANNELS = Sound_initialization(N_SFX_CHANNELS, 0);

#ifdef F1SPIRIT_DEBUG_MESSAGES

		output_debug_message("Audio initialized\n");
#endif

	} 

	// Network:
#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("Initializing SDL_net...\n");

#endif

	if (SDLNet_Init() == -1) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Error initializing SDL_net: %s.\n", SDLNet_GetError());
#endif

		network = false;
	} else {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("SDL_net initialized.\n");
#endif

		network = true;
	} 

	SDL_EnableUNICODE(1);

	glGetIntegerv(GL_STENCIL_BITS, &g_stencil_bits);

#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("OpenGL stencil buffer bits: %i\n", g_stencil_bits);

#endif


	return screen;
} /* initialization */
Exemplo n.º 10
0
//
// initsystem() -- init SDL systems
//
int initsystem(void)
{
	const SDL_VideoInfo *vid;
	const SDL_version *linked = SDL_Linked_Version();
	SDL_version compiled;
	char drvname[32];

	SDL_VERSION(&compiled);

	initprintf("Initialising SDL system interface "
		  "(compiled with SDL version %d.%d.%d, DLL version %d.%d.%d)\n",
		linked->major, linked->minor, linked->patch,
		compiled.major, compiled.minor, compiled.patch);

	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER
#ifdef NOSDLPARACHUTE
			| SDL_INIT_NOPARACHUTE
#endif
		)) {
		initprintf("Initialisation failed! (%s)\n", SDL_GetError());
		return -1;
	}

	atexit(uninitsystem);

	frameplace = 0;
	lockcount = 0;

#ifdef USE_OPENGL
	if (loadgldriver(getenv("BUILD_GLDRV"))) {
#if MEGAWANG
        initprintf("Failed loading OpenGL driver. Exiting...\n");
        return 1;
#else
        initprintf("Failed loading OpenGL driver. GL modes will be unavailable.\n");
        nogl = 1;
#endif
	}
#endif

#if !MEGAWANG
#ifndef __APPLE__
	{
		SDL_Surface *icon;
		//icon = loadtarga("icon.tga");
		icon = loadappicon();
		if (icon) {
			SDL_WM_SetIcon(icon, 0);
			SDL_FreeSurface(icon);
		}
	}
#endif
#endif

	if (SDL_VideoDriverName(drvname, 32))
		initprintf("Using \"%s\" video driver\n", drvname);

	// dump a quick summary of the graphics hardware
#ifdef DEBUGGINGAIDS
	vid = SDL_GetVideoInfo();
	initprintf("Video device information:\n");
	initprintf("  Can create hardware surfaces?          %s\n", (vid->hw_available)?"Yes":"No");
	initprintf("  Window manager available?              %s\n", (vid->wm_available)?"Yes":"No");
	initprintf("  Accelerated hardware blits?            %s\n", (vid->blit_hw)?"Yes":"No");
	initprintf("  Accelerated hardware colourkey blits?  %s\n", (vid->blit_hw_CC)?"Yes":"No");
	initprintf("  Accelerated hardware alpha blits?      %s\n", (vid->blit_hw_A)?"Yes":"No");
	initprintf("  Accelerated software blits?            %s\n", (vid->blit_sw)?"Yes":"No");
	initprintf("  Accelerated software colourkey blits?  %s\n", (vid->blit_sw_CC)?"Yes":"No");
	initprintf("  Accelerated software alpha blits?      %s\n", (vid->blit_sw_A)?"Yes":"No");
	initprintf("  Accelerated colour fills?              %s\n", (vid->blit_fill)?"Yes":"No");
	initprintf("  Total video memory:                    %dKB\n", vid->video_mem);
#endif

	return 0;
}
Exemplo n.º 11
0
void render_window()
{
    game_config = GetGameConfig();
    game_levels = GetGameLevels();
    game_levels_count = GetGameLevelsCount();

    arguments = GetArguments();
    user_set = GetUserSettings();
    int start_level = get_start_level();

    save_dir_full = GetSaveDir();
    cache_dir_full = GetCacheDir();
    can_cache = (save_dir_full && cache_dir_full);

//------------------------------------------------------------------------------
    ApplyArguments();

    const SDL_VideoInfo *video_info = SDL_GetVideoInfo();
    if (user_set->geom_x > 0 && user_set->geom_y > 0)
    {
        disp_x = user_set->geom_x;
        disp_y = user_set->geom_y;
    }
    else
    {
        disp_x = video_info->current_w;
        disp_y = video_info->current_h;
    }

    int probe_bpp = (user_set->bpp == 0 ? video_info->vfmt->BitsPerPixel : user_set->bpp);
    disp_bpp = (probe_bpp == 32 ? probe_bpp : 16);

    bool rot = TransformGeom();

//------------------------------------------------------------------------------
#define BTN_SPACE_KOEF 4.5
    int btn_side = disp_y / 7;
    int btn_space = btn_side / BTN_SPACE_KOEF;
    int btns_padded_width = btn_side * 4 + btn_space * 5;
    if (btns_padded_width > disp_x)
    {
        //btn_side = ( wnd_w - 5 * ( btn_side / BTN_SPACE_KOEF ) ) / 4
        btn_side = (int)(disp_x / (4 + 5 / BTN_SPACE_KOEF));
        btn_space = btn_side / BTN_SPACE_KOEF;
    }
    int btns_width = btn_side * 4 + btn_space * 3;
    int font_height = btn_side / 3;
    int font_padding = font_height / 2;

//-- font and labels -----------------------------------------------------------
    TTF_Font *font = TTF_OpenFont(DEFAULT_FONT_FILE, font_height);
    if (!font)
    {
        log_error("Can't load font '%s'. Exiting.", DEFAULT_FONT_FILE);
        return;
    }

    SDL_Surface *levelTextSurface = NULL;
    SDL_Rect levelTextLocation;
    levelTextLocation.y = font_padding;

    SDL_Color fontColor = {0};
#ifndef RGBSWAP
    fontColor.r = 231;
    fontColor.g = 190;
    fontColor.b = 114;
#else
    //--enable-rgb-swap
    fontColor.r = 114;
    fontColor.g = 190;
    fontColor.b = 231;
#endif

    /* Window initialization */
    ingame = true;
    Uint32 sdl_flags = SDL_SWSURFACE;
    if (user_set->fullscreen_mode != FULLSCREEN_NONE)
        sdl_flags |= SDL_FULLSCREEN;
    SDL_Surface *disp = SDL_SetVideoMode(disp_x, disp_y, disp_bpp, sdl_flags);
    if (disp == NULL)
    {
        log_error("Can't set video mode %dx%dx%dbpp. Exiting.", disp_x, disp_y, disp_bpp);
        return;
    }
    screen = disp;
    SDL_Surface *gui_surface = disp;
    SDL_WM_SetCaption("Mokomaze", "Mokomaze");

    /* Draw loading screen */
    SDL_Color whiteColor = {0};
    whiteColor.r = whiteColor.g = whiteColor.b = 255;
    SDL_Surface *titleSurface = TTF_RenderText_Blended(font, "Loading...", whiteColor);
    SDL_Rect title_rect;
    title_rect.x = (disp_x - titleSurface->w) / 2;
    title_rect.y = (disp_y - titleSurface->h) / 2;
    title_rect.w = titleSurface->w;
    title_rect.h = titleSurface->h;
    SDL_BlitSurface(titleSurface, NULL, screen, &title_rect);
    SDL_UpdateRect(screen, title_rect.x, title_rect.y, title_rect.w, title_rect.h);
    SDL_FreeSurface(titleSurface);

//-- load pictures -------------------------------------------------------------
    SDL_Surface *back_pic     = LoadSvg(MDIR "prev-main.svg", btn_side, btn_side, false, false);
    SDL_Surface *forward_pic  = LoadSvg(MDIR "next-main.svg", btn_side, btn_side, false, false);
    SDL_Surface *settings_pic = LoadSvg(MDIR "settings-main.svg", btn_side, btn_side, false, false);
    SDL_Surface *exit_pic     = LoadSvg(MDIR "close-main.svg", btn_side, btn_side, false, false);

    SDL_Surface *back_i_pic    = LoadSvg(MDIR "prev-grey.svg", btn_side, btn_side, false, false);
    SDL_Surface *forward_i_pic = LoadSvg(MDIR "next-grey.svg", btn_side, btn_side, false, false);

    SDL_Surface *back_p_pic    = LoadSvg(MDIR "prev-light.svg", btn_side, btn_side, false, false);
    SDL_Surface *forward_p_pic = LoadSvg(MDIR "next-light.svg", btn_side, btn_side, false, false);

    int tmpx = (rot ? game_config.wnd_h : game_config.wnd_w);
    int tmpy = (rot ? game_config.wnd_w : game_config.wnd_h);
    desk_pic = LoadSvg(MDIR "desk.svg", tmpx, tmpy, rot, true);
    wall_pic = LoadSvg(MDIR "wall.svg", tmpx, tmpy, rot, true);
    int hole_d = game_config.hole_r * 2;
    fin_pic = LoadSvg(MDIR "openmoko.svg", hole_d, hole_d, rot, false);

    if (LoadImgErrors > 0)
    {
        log_error("Some images were not loaded. Exiting.");
        return;
    }

//-- positions of buttons ------------------------------------------------------
    SDL_Rect gui_rect_1, gui_rect_2, gui_rect_3, gui_rect_4;
    gui_rect_1.y = gui_rect_2.y = gui_rect_3.y = gui_rect_4.y = levelTextLocation.y + font_height + font_padding;
    gui_rect_1.x = (disp_x - btns_width) / 2;
    gui_rect_2.x = gui_rect_1.x + btn_side + btn_space;
    gui_rect_3.x = gui_rect_2.x + btn_side + btn_space;
    gui_rect_4.x = gui_rect_3.x + btn_side + btn_space;
//-- for click detection -------------------------------------------------------
    Box gui_box_1, gui_box_2, gui_box_3, gui_box_4;
    gui_box_1.x1 = gui_rect_1.x;
    gui_box_1.y1 = gui_rect_1.y;
    gui_box_1.x2 = gui_rect_1.x + btn_side;
    gui_box_1.y2 = gui_rect_1.y + btn_side;
    gui_box_2.x1 = gui_rect_2.x;
    gui_box_2.y1 = gui_rect_2.y;
    gui_box_2.x2 = gui_rect_2.x + btn_side;
    gui_box_2.y2 = gui_rect_2.y + btn_side;
    gui_box_3.x1 = gui_rect_3.x;
    gui_box_3.y1 = gui_rect_3.y;
    gui_box_3.x2 = gui_rect_3.x + btn_side;
    gui_box_3.y2 = gui_rect_3.y + btn_side;
    gui_box_4.x1 = gui_rect_4.x;
    gui_box_4.y1 = gui_rect_4.y;
    gui_box_4.x2 = gui_rect_4.x + btn_side;
    gui_box_4.y2 = gui_rect_4.y + btn_side;

    //create surface for rendering the level
    render_pic = CreateSurface(SDL_SWSURFACE, game_config.wnd_w, game_config.wnd_h, disp);

    if (user_set->scrolling)
        screen = CreateSurface(SDL_SWSURFACE, game_config.wnd_w, game_config.wnd_h, disp);

    if (user_set->fullscreen_mode != FULLSCREEN_NONE)
        SDL_ShowCursor(!ingame);

    desk_rect.x = 0;
    desk_rect.y = 0;
    desk_rect.w = game_config.wnd_w;
    desk_rect.h = game_config.wnd_h;

    SDL_Rect ball_rect;

    int disp_scroll_border = min(disp_x, disp_y) * 0.27;
    SDL_Rect screen_rect;
    screen_rect.x = 0;
    screen_rect.y = 0;
    screen_rect.w = disp_x;
    screen_rect.h = disp_y;
    SDL_Rect disp_rect;
    disp_rect = screen_rect;

    SDL_Color ballColor = {0};
    ballColor.r = 255;
    ballColor.g = 127;
    ballColor.b = 0;

    User user_set_new = *user_set;
    bool video_set_modified = false;

    /* Settings window initialization */
    settings_init(disp, font_height, user_set, &user_set_new);

    /* Render initialization */
    InitRender();

    /* Input system initialization */
    input_get_dummy(&input);
    SetInput();

    /* Vibro system initialization */
    vibro_get_dummy(&vibro);
    SetVibro();

    /* MazeCore initialization */
    maze_init();
    maze_set_config(game_config);
    maze_set_vibro_callback(BumpVibrate);
    maze_set_levels_data(game_levels, game_levels_count);

    cur_level = start_level;
    RenderLevel();
    RedrawDesk();
    maze_set_level(cur_level);
    ResetPrevPos();

    SDL_Event event;
    bool done = false;
    bool redraw_all = true;
    bool ingame_changed = false;
    int prev_ticks = SDL_GetTicks();
    Point mouse = {0};

//== Game Loop =================================================================
    while (!done)
    {
        bool wasclick = false;
        bool show_settings = false;
        while (SDL_PollEvent(&event))
        {
            bool btndown = false;
            bool btnesc = false;
            if (event.type == SDL_QUIT)
            {
                done = true;
            }
            else if (event.type == SDL_ACTIVEEVENT)
            {
                int g = event.active.gain;
                int s = event.active.state;
                if (ingame && !g && ((s & SDL_APPINPUTFOCUS) || (s & SDL_APPACTIVE)))
                {
                    btndown = true;
                }
            }
            else if (event.type == SDL_MOUSEMOTION)
            {
                mouse.x = event.motion.x;
                mouse.y = event.motion.y;
            }
            else if (event.type == SDL_MOUSEBUTTONUP)
            {
                StopFastChange();
            }
            else if (event.type == SDL_MOUSEBUTTONDOWN)
            {
                btndown = true;
            }
            else if (event.type == SDL_KEYDOWN)
            {
                switch(event.key.keysym.sym)
                {
                case SDLK_q:
                case SDLK_ESCAPE:
                    btnesc = true;
                case SDLK_SPACE:
                case SDLK_p:
                case SDLK_PAUSE:
                    btndown = true;
                    break;
                default:
                    break;
                }
            }
            else if (event.type == SDL_KEYUP)
            {
                switch(event.key.keysym.sym)
                {
                case SDLK_q:
                case SDLK_ESCAPE:
                    if( !wasclick || ingame || show_settings )
                        StopFastChange();
                    else
                        done = true;
                    break;
                case SDLK_SPACE:
                case SDLK_p:
                case SDLK_PAUSE:
                    StopFastChange();
                    break;
                default:
                    break;
                }
            }

            if (btndown)
            {
                if (!ingame)
                {
                    if (inbox(mouse.x, mouse.y, gui_box_1) && !btnesc)
                    {
                        if (cur_level > 0)
                        {
                            SDL_BlitSurface(back_p_pic, NULL, gui_surface, &gui_rect_1);
                            SDL_UpdateRect(gui_surface, gui_rect_1.x, gui_rect_1.y, gui_rect_1.w, gui_rect_1.h);

                            ChangeLevel(cur_level-1, &redraw_all, &wasclick);

                            fastchange_step = -10;
                            StopFastChange();
                            fastchange_timer = SDL_AddTimer(FASTCHANGE_INTERVAL, fastchange_callback, NULL);
                        }
                        continue;
                    }
                    else if (inbox(mouse.x, mouse.y, gui_box_2) && !btnesc)
                    {
                        if (cur_level < game_levels_count - 1)
                        {
                            SDL_BlitSurface(forward_p_pic, NULL, gui_surface, &gui_rect_2);
                            SDL_UpdateRect(gui_surface, gui_rect_2.x, gui_rect_2.y, gui_rect_2.w, gui_rect_2.h);

                            ChangeLevel(cur_level+1, &redraw_all, &wasclick);

                            fastchange_step = +10;
                            StopFastChange();
                            fastchange_timer = SDL_AddTimer(FASTCHANGE_INTERVAL, fastchange_callback, NULL);
                        }
                        continue;
                    }
                    else if (inbox(mouse.x, mouse.y, gui_box_3) && !btnesc)
                    {
                        show_settings = true;
                        RedrawDesk();
                        redraw_all = true;
                        wasclick = true;
                        continue;
                    }
                    else if (inbox(mouse.x, mouse.y, gui_box_4) || btnesc)
                    {
                        done = true;
                        continue;
                    }
                }
                ingame_changed = true;
            } //if (btndown)
        }

        if (ingame_changed)
        {
            ingame = !ingame;
            if (!ingame)
            {
                wasclick = true;
            }
            else
            {
                RedrawDesk();
                redraw_all = true;
            }

            if (user_set->fullscreen_mode == FULLSCREEN_INGAME)
                SDL_WM_ToggleFullScreen(disp);
            if (user_set->fullscreen_mode != FULLSCREEN_NONE)
                SDL_ShowCursor(!ingame);

            prev_ticks = SDL_GetTicks();
            ingame_changed = false;
        }

        if ((!ingame) && (!wasclick) && (must_fastchange))
        {
            int new_cur_level = cur_level + fastchange_dostep;
            clamp_max(new_cur_level, game_levels_count - 1);
            clamp_min(new_cur_level, 0);

            if (new_cur_level != cur_level)
            {
                if (fastchange_dostep < 0)
                {
                    SDL_BlitSurface(back_p_pic, NULL, gui_surface, &gui_rect_1);
                    SDL_UpdateRect(gui_surface, gui_rect_1.x, gui_rect_1.y, gui_rect_1.w, gui_rect_1.h);
                }
                else
                {
                    SDL_BlitSurface(forward_p_pic, NULL, gui_surface, &gui_rect_2);
                    SDL_UpdateRect(gui_surface, gui_rect_2.x, gui_rect_2.y, gui_rect_2.w, gui_rect_2.h);
                }

                ChangeLevel(new_cur_level, &redraw_all, &wasclick);
            }
            must_fastchange = false;
        }

        if (!ingame && !wasclick)
        {
            SDL_Delay(user_set->frame_delay);
            continue;
        }

//-- physics step --------------------------------------------------------------
        int ticks = SDL_GetTicks();
        int delta_ticks = ticks - prev_ticks;
        prev_ticks = ticks;
        clamp_min(delta_ticks, 1);
        clamp_max(delta_ticks, 1000 / 15);

        float acx = 0, acy = 0;
        input.read(&acx, &acy, NULL);
        if (input_cal_cycle)
            input_cal_cycle = (input_calibration_sample(&user_set->input_calibration_data, &acx, &acy, NULL) < MAX_CALIBRATION_SAMPLES);
        input_calibration_adjust(&user_set->input_calibration_data, &acx, &acy, NULL);
        maze_set_speed(user_set->ball_speed);
        maze_set_tilt(acx, acy, 0);
        GameState game_state = maze_step(delta_ticks);

        const dReal *R;
        int tk_px, tk_py, tk_pz;
        maze_get_ball(&tk_px, &tk_py, &tk_pz, &R);
        maze_get_animations(&keys_anim, &final_anim);
//------------------------------------------------------------------------------

        //restore the background
        ball_rect.w = game_config.ball_r * 2;
        ball_rect.h = game_config.ball_r * 2; //
        ball_rect.x = prev_px - game_config.ball_r;
        ball_rect.y = prev_py - game_config.ball_r;
        SDL_BlitSurface(render_pic, &ball_rect, screen, &ball_rect);

        UpdateBufAnimation();
        DrawBall(tk_px, tk_py, tk_pz, R, ballColor);

        //update the screen
        if (!redraw_all && !user_set->scrolling)
        {
            int min_px, max_px;
            int min_py, max_py;
            if (prev_px <= tk_px)
            {
                min_px = prev_px;
                max_px = tk_px;
            }
            else
            {
                min_px = tk_px;
                max_px = prev_px;
            }

            if (prev_py <= tk_py)
            {
                min_py = prev_py;
                max_py = tk_py;
            }
            else
            {
                min_py = tk_py;
                max_py = prev_py;
            }
            min_px -= game_config.ball_r;
            max_px += game_config.ball_r;
            min_py -= game_config.ball_r;
            max_py += game_config.ball_r;
            clamp_min(min_px, 0);
            clamp_max(max_px, game_config.wnd_w - 1);
            clamp_min(min_py, 0);
            clamp_max(max_py, game_config.wnd_h - 1);
            SDL_UpdateRect(screen, min_px, min_py, max_px - min_px, max_py - min_py);
            UpdateScreenAnimation();
        }

        if (user_set->scrolling)
        {
            clamp_min(screen_rect.x, tk_px - disp_x + disp_scroll_border);
            clamp_max(screen_rect.x, tk_px - disp_scroll_border);
            clamp_min(screen_rect.y, tk_py - disp_y + disp_scroll_border);
            clamp_max(screen_rect.y, tk_py - disp_scroll_border);
            clamp(screen_rect.x, 0, game_config.wnd_w - disp_x);
            clamp(screen_rect.y, 0, game_config.wnd_h - disp_y);
            SDL_BlitSurface(screen, &screen_rect, disp, &disp_rect);
        }

        prev_px = tk_px;
        prev_py = tk_py;

//-- GUI -----------------------------------------------------------------------
        if (wasclick && !ingame && !show_settings)
        {
            char txt[32];
            sprintf(txt, "Level %d/%d", cur_level + 1, game_levels_count);
            SDL_FreeSurface(levelTextSurface);
            levelTextSurface = TTF_RenderText_Blended(font, txt, fontColor);
            levelTextLocation.x = (disp_x - levelTextSurface->w) / 2;
            SDL_BlitSurface(levelTextSurface, NULL, gui_surface, &levelTextLocation);

            if (cur_level > 0)
                SDL_BlitSurface(back_pic, NULL, gui_surface, &gui_rect_1);
            else
                SDL_BlitSurface(back_i_pic, NULL, gui_surface, &gui_rect_1);

            if (cur_level < game_levels_count - 1)
                SDL_BlitSurface(forward_pic, NULL, gui_surface, &gui_rect_2);
            else
                SDL_BlitSurface(forward_i_pic, NULL, gui_surface, &gui_rect_2);

            SDL_BlitSurface(settings_pic, NULL, gui_surface, &gui_rect_3);
            SDL_BlitSurface(exit_pic, NULL, gui_surface, &gui_rect_4);
            redraw_all = true;
        }
//------------------------------------------------------------------------------

        //update the whole screen if needed
        if (user_set->scrolling)
        {
            SDL_Flip(disp);
        }
        else if (redraw_all)
        {
            SDL_Flip(screen);
        }
        redraw_all = false;

        if (show_settings)
        {
            bool _video_set_modified = false;
            bool _input_set_modified = false;
            bool _vibro_set_modified = false;
            settings_show(&input_cal_cycle, &_video_set_modified, &_input_set_modified, &_vibro_set_modified);
            if (input_cal_cycle)
                input_calibration_reset();
            if (_video_set_modified)
                video_set_modified = true;
            if (_input_set_modified)
                SetInput();
            if (_vibro_set_modified)
                SetVibro();
            SDL_GetMouseState(&mouse.x, &mouse.y);
            ingame_changed = true;
        }

        switch (game_state)
        {
        case GAME_STATE_FAILED:
            RedrawDesk();
            maze_restart_level();
            ResetPrevPos();
            redraw_all = true;
            break;
        case GAME_STATE_SAVED:
            RedrawDesk();
            maze_reload_level();
            ResetPrevPos();
            redraw_all = true;
            break;
        case GAME_STATE_WIN:
            if (++cur_level >= game_levels_count) cur_level=0;
            RenderLevel();
            RedrawDesk();
            maze_set_level(cur_level);
            ResetPrevPos();
            redraw_all = true;
            break;
        default:
            break;
        }

        SDL_Delay(user_set->frame_delay);
    }
//==============================================================================

    if (video_set_modified)
    {
        user_set->scrolling = user_set_new.scrolling;
        user_set->geom_x = user_set_new.geom_x;
        user_set->geom_y = user_set_new.geom_y;
        user_set->bpp = user_set_new.bpp;
        user_set->fullscreen_mode = user_set_new.fullscreen_mode;
        user_set->frame_delay = user_set_new.frame_delay;
    }

    user_set->level = cur_level + 1;
    SaveUserSettings();

    settings_shutdown();

    SDL_FreeSurface(levelTextSurface);
    TTF_CloseFont(font);
    vibro.shutdown();
    input.shutdown();
}
Exemplo n.º 12
0
SDL_Surface *initsdl(int *w,int *h,int *bppp,Uint32 flags)
{
	// SDL_INIT_EVENTTHREAD
	if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
		fprintf(stderr,"Couldn't initialize SDL: %s\n",SDL_GetError());
		exit( 1 );
	}
	
	SDL_Surface *s;
	static int bpp=0; 
	Uint32 video_flags;
	video_flags = flags;
	int rgb_size[3]={0,0,0};
	printf("yoyoyo\n");
	if (flags& SDL_OPENGL)
	{
/*
	if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 ) {
		bpp = 8;
	} else {
		bpp = 16;  // More doesn't seem to work 
	}*/
	bpp=SDL_GetVideoInfo()->vfmt->BitsPerPixel;
	switch (bpp) {
	    case 8:
		rgb_size[0] = 3;
		rgb_size[1] = 3;
		rgb_size[2] = 2;
		break;
	    case 15:
	    case 16:
		rgb_size[0] = 5;
		rgb_size[1] = 5;
		rgb_size[2] = 5;
		break;
            default:
		rgb_size[0] = 8;
		rgb_size[1] = 8;
		rgb_size[2] = 8;
		break;
	}
	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, rgb_size[0] );
	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, rgb_size[1] );
	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, rgb_size[2] );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	}
	
	video_flags|=(SDL_RESIZABLE|SDL_ANYFORMAT|SDL_DOUBLEBUF);
	
	s= SDL_SetVideoMode( *w, *h, bpp, video_flags );
	if (s == NULL ) {
		fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(1);
	}
	
#ifdef chaos
	printf("Screen BPP: %d\n", SDL_GetVideoSurface()->format->BitsPerPixel);
	printf("\n");
#ifdef GL

	printf( "Vendor     : %s\n", glGetString( GL_VENDOR ) );
	printf( "Renderer   : %s\n", glGetString( GL_RENDERER ) );
	printf( "Version    : %s\n", glGetString( GL_VERSION ) );
	printf( "Extensions : %s\n", glGetString( GL_EXTENSIONS ) );
	printf("\n");
	int value;
	SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &value );
	printf( "SDL_GL_RED_SIZE: requested %d, got %d\n", rgb_size[0],value);
	SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &value );
	printf( "SDL_GL_GREEN_SIZE: requested %d, got %d\n", rgb_size[1],value);
	SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &value );
	printf( "SDL_GL_BLUE_SIZE: requested %d, got %d\n", rgb_size[2],value);
	SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &value );
	printf( "SDL_GL_DEPTH_SIZE: requested %d, got %d\n", bpp, value );
	SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &value );
	printf( "SDL_GL_DOUBLEBUFFER: requested 1, got %d\n", value );
#endif
#endif
	
	printf("mustlock=%i\n", SDL_MUSTLOCK(s));

	const SDL_VideoInfo* m = SDL_GetVideoInfo();
	*w=m->current_w;
	*h=m->current_h;
	*bppp=bpp;
	char * x= (char*)malloc(20);
	if(x&&SDL_VideoDriverName(x,20))
	    printf("Current SDL video driver is %s.\n",x);
    printf("%i x %i\n",*w,*h);
	   


	return s;
}
Exemplo n.º 13
0
/***************************
	GraphicsInit: Initializes the graphic system
****************************/
void GraphicsInit(void)
{
  const SDL_VideoInfo* video_info = SDL_GetVideoInfo();
  Uint32 surface_mode = 0;

  DEBUGCODE
  { fprintf(stderr, "Entering GraphicsInit()\n"); };

  //Set application's icon:
  seticon();
  //Set caption:
  SDL_WM_SetCaption("Tux Typing", "TuxType");

  if (video_info->hw_available)
  {
    surface_mode = SDL_HWSURFACE;
    LOG("HW mode\n");
  }
  else
  {
    surface_mode = SDL_SWSURFACE;
    LOG("SW mode\n");
  }

  // Determine the current resolution: this will be used as the
  // fullscreen resolution, if the user wants fullscreen.
  DEBUGCODE
  {
    fprintf(stderr, "Current resolution: w %d, h %d.\n", 
            video_info->current_w, video_info->current_h);
  }

  /* For fullscreen, we try to use current resolution from OS: */
  
  fs_res_x = video_info->current_w;
  fs_res_y = video_info->current_h;

  if (settings.fullscreen == 1)
  {
    screen = SDL_SetVideoMode(fs_res_x, fs_res_y, BPP, SDL_FULLSCREEN | surface_mode);
    if (screen == NULL)
    {
      fprintf(stderr,
            "\nWarning: I could not open the display in fullscreen mode.\n"
            "The Simple DirectMedia error that occured was:\n"
            "%s\n\n", SDL_GetError());
      settings.fullscreen = 0;
    }
  }

  /* Either fullscreen not requested, or couldn't get fullscreen in SDL: */
  if (settings.fullscreen == 0)
  {
    screen = SDL_SetVideoMode(RES_X, RES_Y, BPP, surface_mode);
  }

  /* Failed to get a usable screen - must bail out! */
  if (screen == NULL)
  {
    fprintf(stderr,
          "\nError: I could not open the display.\n"
          "The Simple DirectMedia error that occured was:\n"
          "%s\n\n", SDL_GetError());
    exit(2);
  }

  InitBlitQueue();



  DEBUGCODE 
  {
    video_info = SDL_GetVideoInfo();
    fprintf(stderr, "-SDL VidMode successfully set to %ix%ix%i\n",
            video_info->current_w,
            video_info->current_h,
            video_info->vfmt->BitsPerPixel);
  }

	LOG( "GraphicsInit():END\n" );
}
Exemplo n.º 14
0
int main( int argc, char* argv[] )
{
    /* Information about the current video settings. */
    const SDL_VideoInfo* info = NULL;

    g_Time = InitTime();

    /* First, initialize SDL's video subsystem. */
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
        /* Failed, exit. */
        fprintf( stderr, "Video initialization failed: %s\n",
             SDL_GetError( ) );
        quit_tutorial( 1 );
    }

    /* Let's get some video information. */
    info = SDL_GetVideoInfo( );

    if( !info ) {
        /* This should probably never happen. */
        fprintf( stderr, "Video query failed: %s\n",
             SDL_GetError( ) );
        quit_tutorial( 1 );
    }

    g_bpp = info->vfmt->BitsPerPixel;

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

	g_flags = SDL_OPENGL|SDL_HWPALETTE|/*SDL_NOFRAME|*/SDL_HWSURFACE/*|SDL_RESIZABLE*//*| SDL_FULLSCREEN*/;

    /*
     * Set the video mode
     */
    if( SDL_SetVideoMode( g_width, g_height, g_bpp, g_flags ) == 0 ) {
        /* 
         * This could happen for a variety of reasons,
         * including DISPLAY not being set, the specified
         * resolution not being available, etc.
         */
        fprintf( stderr, "Video mode set failed: %s\n",
             SDL_GetError( ) );
        quit_tutorial( 1 );
    }

    /*
     * At this point, we should have a properly setup
     * double-buffered window for use with OpenGL.
     */
    setup_opengl( g_width, g_height );


    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
        quit_tutorial(1);
    }

    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    if (!GLEW_ARB_vertex_program || !GLEW_ARB_vertex_program)
    {
        fprintf(stderr, "No shader program support\n");
        quit_tutorial(1);
    }

    if (glewIsSupported("GL_VERSION_2_0"))
        printf("Ready for OpenGL 2.0\n");
    else {
        printf("OpenGL 2.0 not supported\n");
        quit_tutorial(1);
    }

	/*
	 * Init OpenGL text driver which will 
	 * be used by GraphicsConsole
	 */
	g_pTextDriver = new OGLTextDriver();
	if( false == g_pTextDriver->init("FixedWidth.bmp", 8, 16, 16, g_width, g_height))
		quit_tutorial( 1 );


	register_commands();
	GraphicsConsole::Instance().setTextDriver(g_pTextDriver);
	SDL_EnableKeyRepeat(500, 30);

	draw_velocity = glsl_program::makeProgram("drawVelocity", DATA_PATH"quad.vs", DATA_PATH"draw_velocity.fs");
	draw_fluids = glsl_program::makeProgram("drawFluids", DATA_PATH"quad.vs", DATA_PATH"draw_fluids.fs");
	assert(draw_velocity);

	start_time = time(0);

	g_fluids.createShaders();
	g_fluids.createBuffers();
	
	UI::Init(g_width, g_height);
	g_fluids.createUI();

	SDL_WM_SetCaption("console", 0);

    /*
     * Now we want to begin our normal app process--
     * an event loop with a lot of redrawing.
     */
    while( !g_exit ) {
        UpdateTime(&g_Time);
        /* Process incoming events. */
        process_events( );
        /* Draw the screen. */
        draw_screen( );
    }

	quit_tutorial(0);

    return 0;
}
Exemplo n.º 15
0
/**
 * Handle mouse events.
 *
 * @param[in] lpEvent - pointer to the event.
 * @return None
 */
static VOID PAL_MouseEventFilter(const SDL_Event *lpEvent)
{
#ifdef PAL_HAS_MOUSE
    static short hitTest = 0; // Double click detect;
    const SDL_VideoInfo *vi;

    double       screenWidth, gridWidth;
    double       screenHeight, gridHeight;
    double       mx, my;
    double       thumbx;
    double       thumby;
    INT          gridIndex;
    BOOL         isLeftMouseDBClick = FALSE;
    BOOL         isLeftMouseClick = FALSE;
    BOOL         isRightMouseClick = FALSE;
    static INT   lastReleaseButtonTime, lastPressButtonTime, betweenTime;
    static INT   lastPressx = 0;
    static INT   lastPressy = 0;
    static INT   lastReleasex = 0;
    static INT   lastReleasey = 0;

    if (lpEvent->type!= SDL_MOUSEBUTTONDOWN && lpEvent->type != SDL_MOUSEBUTTONUP)
       return;

    vi = SDL_GetVideoInfo();
    screenWidth = vi->current_w;
    screenHeight = vi->current_h;
    gridWidth = screenWidth / 3;
    gridHeight = screenHeight / 3;
    mx = lpEvent->button.x;
    my = lpEvent->button.y;
    thumbx = ceil(mx / gridWidth);
    thumby = floor(my / gridHeight);
    gridIndex = thumbx + thumby * 3 - 1;

    switch (lpEvent->type)
    {
    case SDL_MOUSEBUTTONDOWN:
       lastPressButtonTime = SDL_GetTicks();
       lastPressx = lpEvent->button.x;
       lastPressy = lpEvent->button.y;
       switch (gridIndex)
       {
       case 2:
          g_InputState.prevdir = g_InputState.dir;
          g_InputState.dir = kDirNorth;
          break;
       case 6:
          g_InputState.prevdir = g_InputState.dir;
          g_InputState.dir = kDirSouth;
          break;
       case 0:
          g_InputState.prevdir = g_InputState.dir;
          g_InputState.dir = kDirWest;
          break;
       case 8:
          g_InputState.prevdir = g_InputState.dir;
          g_InputState.dir = kDirEast;
          break;
       case 1:
         //g_InputState.prevdir = g_InputState.dir;
         //g_InputState.dir = kDirNorth;
          g_InputState.dwKeyPress |= kKeyUp;
          break;
       case 7:
         //g_InputState.prevdir = g_InputState.dir;
         //g_InputState.dir = kDirSouth;
          g_InputState.dwKeyPress |= kKeyDown;
          break;
       case 3:
         //g_InputState.prevdir = g_InputState.dir;
         //g_InputState.dir = kDirWest;
         g_InputState.dwKeyPress |= kKeyLeft;
          break;
       case 5:
          //g_InputState.prevdir = g_InputState.dir;
          //g_InputState.dir = kDirEast;
          g_InputState.dwKeyPress |= kKeyRight;
          break;
       }
       break;
    case SDL_MOUSEBUTTONUP:
       lastReleaseButtonTime = SDL_GetTicks();
       lastReleasex = lpEvent->button.x;
       lastReleasey = lpEvent->button.y;
       hitTest ++;
       if (abs(lastPressx - lastReleasex) < 25 &&
                      abs(lastPressy - lastReleasey) < 25)
       {
         betweenTime = lastReleaseButtonTime - lastPressButtonTime;
         if (betweenTime >500)
         {
            isRightMouseClick = TRUE;
         }
         else if (betweenTime >=0)
         {
            if((betweenTime < 100) && (hitTest >= 2))
            {
               isLeftMouseClick = TRUE;
                 hitTest = 0;
            }
            else
            {
               isLeftMouseClick = TRUE;
               if(betweenTime > 100)
               {
                  hitTest = 0;
               }

            }
         }
       }
       switch (gridIndex)
       {
       case 2:
         if( isLeftMouseDBClick )
        {
           SOUND_AdjustVolume(1);
           break;
        }
       case 6:
       case 0:
         if( isLeftMouseDBClick )
        {
           SOUND_AdjustVolume(0);
           break;
        }
       case 7:
          if (isRightMouseClick) //repeat attack
          {
             g_InputState.dwKeyPress |= kKeyRepeat;
             break;
          }
       case 8:
          g_InputState.dir = kDirUnknown;
          g_InputState.prevdir = kDirUnknown;
          break;
       case 1:
         if( isRightMouseClick )
        {
           g_InputState.dwKeyPress |= kKeyForce;
        }
         break;
       case 3:
         if( isRightMouseClick )
        {
           g_InputState.dwKeyPress |= kKeyAuto;
        }
         break;
       case 5:
         if( isRightMouseClick )
        {
           g_InputState.dwKeyPress |= kKeyDefend;
        }
        break;
       case 4:
       if (isRightMouseClick) // menu
       {
          g_InputState.dwKeyPress |= kKeyMenu;
       }
       else if (isLeftMouseClick) // search
       {
          g_InputState.dwKeyPress |= kKeySearch;
       }

         break;
       }
       break;
    }
#endif
}
Exemplo n.º 16
0
void init_video()
{
	char str[400];
	int rgb_size[3];

	setup_video_mode(full_screen, video_mode);

	/* Detect the display depth */
	if(!bpp)
		{
			if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 )
				{
					bpp = 8;
				}
			else
				if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 16 )
					{
						bpp = 16;  /* More doesn't seem to work */
					}
				else bpp=32;
		}

	//adjust the video mode accordingly
	if (video_mode == 0)
	{
		//do nothing
	} else if(bpp==16) {
		if(!(video_mode%2))
			video_mode-=1;
	} else {
		if(video_mode%2)
			video_mode+=1;
	}
	/* Initialize the display */
	switch (bpp) {
	case 8:
		rgb_size[0] = 2;
		rgb_size[1] = 3;
		rgb_size[2] = 3;
		break;
	case 15:
	case 16:
		rgb_size[0] = 5;
		rgb_size[1] = 5;
		rgb_size[2] = 5;
		break;
	default:
		rgb_size[0] = 8;
		rgb_size[1] = 8;
		rgb_size[2] = 8;
		break;
	}
	//    Mac OS X will always use 8-8-8-8 ARGB for 32-bit screens and 5-5-5 RGB for 16-bit screens
#ifndef OSX
	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, rgb_size[0] );
	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, rgb_size[1] );
	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, rgb_size[2] );
#endif
#ifdef OSX
	// enable V-SYNC
	SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1 );
#endif
	SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 0 );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );
	SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
#ifdef	FSAA
	if (fsaa > 1)
	{
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa);
		glDisable(GL_MULTISAMPLE);
	}
#endif	/* FSAA */
	check_gl_mode();

#ifdef OTHER_LIFE
	SDL_WM_SetIcon(SDL_LoadBMP("ol_icon.bmp"), NULL);   
#else
	SDL_WM_SetIcon(SDL_LoadBMP("icon.bmp"), NULL);
#endif
        /* Set the window manager title bar */

#ifdef	FSAA
	if (fsaa > 1)
	{
		if (!SDL_SetVideoMode(window_width, window_height, bpp, flags))
		{
			safe_snprintf(str, sizeof(str), "Can't use fsaa mode x%d, disabling it.", fsaa);
			LOG_TO_CONSOLE(c_yellow1, str);
			LOG_WARNING("%s\n", str);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
			fsaa = 0;
		}
	}
#endif	/* FSAA */

	//try to find a stencil buffer (it doesn't always work on Linux)
	if(!SDL_SetVideoMode(window_width, window_height, bpp, flags))
    	{
			LOG_TO_CONSOLE(c_red1,no_hardware_stencil_str);
			LOG_ERROR("%s\n",no_hardware_stencil_str);
			if(bpp!=32)
            {
                   LOG_TO_CONSOLE(c_grey1,suggest_24_or_32_bit);
                   LOG_ERROR("%s\n",suggest_24_or_32_bit);
            }
			SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);
			SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,0);
			if(!SDL_SetVideoMode( window_width, window_height, bpp, flags))
			    {
					LOG_ERROR("%s: %s\n", fail_opengl_mode, SDL_GetError());
					SDL_Quit();
					exit(1);
			    }
			have_stencil=0;

    	}
#ifdef WINDOWS
	//try to see if we get hardware acceleration, or the windows generic shit
	{
		int len;
		GLubyte *my_string;
		int have_hardware;

		my_string=(GLubyte *)glGetString(GL_RENDERER);        
        if (my_string == NULL) {
            len = 0;
            have_hardware = 0;
            LOG_TO_CONSOLE(c_red1,"glGetString(GL_RENDERER) failed");
            LOG_ERROR("%s\n","glGetString(GL_RENDERER) failed");
        } else {
            len=strlen(my_string);
            have_hardware=get_string_occurance("gdi generic",my_string,len,0);
        }
        if(have_hardware != -1) {
			//let the user know there is a problem
			LOG_TO_CONSOLE(c_red1,stencil_falls_back_on_software_accel);
			LOG_ERROR("%s\n",stencil_falls_back_on_software_accel);
			
			//first, shut down this mode we have now.
			SDL_GL_SetAttribute( SDL_GL_RED_SIZE, rgb_size[0] );
			SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, rgb_size[1] );
			SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, rgb_size[2] );
			SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 0);
			SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24);
			SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0);
			SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1);
			if(full_screen)flags=SDL_OPENGL|SDL_FULLSCREEN;
			SDL_SetVideoMode(window_width, window_height, bpp, flags);
			have_stencil=0;
	
			my_string=(GLubyte *)glGetString(GL_RENDERER);
            if (my_string == NULL) {
                len = 0;
                have_hardware = 0;
                LOG_TO_CONSOLE(c_red1,"glGetString(GL_RENDERER) failed");
                LOG_ERROR("%s\n","glGetString(GL_RENDERER) failed");
            } else {
                len=strlen(my_string);
                have_hardware=get_string_occurance("gdi generic",my_string,len,0);
            }
			if(have_hardware != -1) {
				//wtf, this really shouldn't happen....
				//let's try a default mode, maybe Quake 2's mode, and pray it works
				LOG_TO_CONSOLE(c_red1,last_chance_str);
				LOG_ERROR("%s\n",last_chance_str);
				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, 0);
				SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24);
				SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0);
				SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1);
				flags=SDL_OPENGL|SDL_FULLSCREEN;
				full_screen=1;
				video_mode=2;
				window_width=640;
				window_height=480;
				bpp=32;
				SDL_SetVideoMode(window_width, window_height, bpp, flags);
				//see if it worked...
				my_string=(GLubyte *)glGetString(GL_RENDERER);
                if (my_string == NULL) {
                    len = 0;
                    have_hardware = 0;
                    LOG_TO_CONSOLE(c_red1,"glGetString(GL_RENDERER) failed");
                    LOG_ERROR("%s\n","glGetString(GL_RENDERER) failed");
                } else {
                    len=strlen(my_string);
                    have_hardware=get_string_occurance("gdi generic",my_string,len,0);
                }
				if(have_hardware != -1) {
					//wtf, this really shouldn't happen....
					//let's try a default mode, maybe Quake 2's mode, and pray it works
					LOG_TO_CONSOLE(c_red1,software_mode_str);
					LOG_ERROR("%s\n",software_mode_str);
				}
			}
		}
	}
#endif

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	//glDepthFunc(GL_LEQUAL);
    glEnable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glEnable(GL_NORMALIZE);
	glClearStencil(0);

#ifdef ANTI_ALIAS
	if (anti_alias) {
		glHint(GL_POINT_SMOOTH_HINT,   GL_NICEST);	
		glHint(GL_LINE_SMOOTH_HINT,    GL_NICEST);	
		glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);	
		glEnable(GL_POINT_SMOOTH);
		glEnable(GL_LINE_SMOOTH);
		glEnable(GL_POLYGON_SMOOTH);
	} else {
		glHint(GL_POINT_SMOOTH_HINT,   GL_FASTEST);	
		glHint(GL_LINE_SMOOTH_HINT,    GL_FASTEST);	
		glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST);	
		glDisable(GL_POINT_SMOOTH);
		glDisable(GL_LINE_SMOOTH);
		glDisable(GL_POLYGON_SMOOTH);
	}
#endif
	SDL_EnableKeyRepeat(200, 100);
	SDL_EnableUNICODE(1);
	build_video_mode_array();
	SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &have_stencil);
	last_texture=-1;	//no active texture
#ifdef OPENGL_TRACE
CHECK_GL_ERRORS();
#endif //OPENGL_TRACE

	change_minimap();

	check_options();
}
Exemplo n.º 17
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdLine, int cmdShow) {
#else
int main(int argc, char** argv) {
#endif
  // Start by opening a debug log.
  Debug::openLog(true);
  Debug::logger->message("\n ----- Engine Loading -----");

  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    Debug::logger->message("Error: Could not load SDL");
    Destroy();
    return 1;
  } else {
    Debug::logger->message("SDL loaded..");
  }

  // Setup OpenGL.
  SDL_GL_SetAttribute(SDL_GL_RED_SIZE,            5);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,          5);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,           5);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,        1);

  flags = SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE;

  screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, flags);
  Debug::logger->message("Video mode set..");

  if(Mix_OpenAudio(44100, AUDIO_S16, 2, 4096)) {
    Debug::logger->message("Audio opened..");
  }

  if(TTF_Init()) {
    Debug::logger->message("SDL_ttf initialized.\n");
  }

  info = SDL_GetVideoInfo();
  if(!info) {
    // This should never accur.
    Debug::logger->message("Video query failed!");
    Destroy();
    return 1;
  }

  SDL_WM_SetCaption("LibD", NULL);

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

  Debug::logger->message("\n ----- Engine Initialization Complete -----");
  Debug::logger->message("\n ----- Logic -----");

  Game game;
  game.Init();
  CreateInput();

  Uint32 timeStart = SDL_GetTicks();
  float dt = 1.0f / 60.0f;

  // We need to give OnResize()'s width and height params an initial value
  // Otherwise it is just garbage, and the orthorgraphic view
  // screws up for me. -- Allanis.
  game.OnResize(windowWidth, windowHeight);

  while(game.IsRunning()) {

    while(SDL_PollEvent(&event)) {
      if((event.type == SDL_QUIT) || KeyStillDown(SDLK_ESCAPE)) {
        game.SetRunning(false);
        break;
      }
      if(event.type == SDL_VIDEORESIZE) {
        // Resize the window.
        ResizeWindow(game, event.resize.w, event.resize.h);
        break;
      }
    }

    UpdateInput();
    game.Prepare(dt);
    game.ProcessEvents(dt);
    game.Render();
    SDL_GL_SwapBuffers();

    Uint32 timeEnd = SDL_GetTicks();
    dt = (float)(timeEnd - timeStart) / 1000.0f;
    timeStart = timeEnd;
  }

  game.Shutdown();

  Destroy();

  Debug::closeLog();
  return 0;
}
int main(int argc, char* argv[])
{
    SDL_Surface *screen = NULL;
    SDL_Surface *image = NULL;
    const SDL_VideoInfo *videoInfo = NULL;

    /*-----------------------------------------------------------------*/

    if (argc != 2)
    {
        fprintf(stderr, "single argument ... name of image to display\n");
        return 1;
    }

    /*-----------------------------------------------------------------*/

    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        fprintf(stderr, "SDL_Init failed - %s\n", SDL_GetError());
        return 1;
    }

    /*-----------------------------------------------------------------*/

    videoInfo = SDL_GetVideoInfo();

    if (videoInfo == 0)
    {
        fprintf(stderr, "SDL_GetVideoInfo failed - %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    /*-----------------------------------------------------------------*/

    image = IMG_Load(argv[1]);

    if (!image)
    {
        fprintf(stderr, "IMG_Load failed - %s\n", IMG_GetError());
        SDL_Quit();
        return 1;
    }

    /*-----------------------------------------------------------------*/

    screen = SDL_SetVideoMode(image->w,
                              image->h,
                              videoInfo->vfmt->BitsPerPixel,
                              SDL_HWSURFACE);

    if (!screen)
    {
        fprintf(stderr, "SetVideoMode failed - %s\n", SDL_GetError());
        SDL_FreeSurface(image);
        SDL_Quit();
        return 1;
    }

    /*-----------------------------------------------------------------*/

    SDL_BlitSurface(image, 0, screen, 0);
    
    SDL_Delay(5000);

    SDL_FreeSurface(image);

    SDL_Quit();

    return 0;
}
Exemplo n.º 19
0
GameSettings::GameSettings()
	: Panel("GameSettings", (GameControl::Get()->Width() - WIDTH)/2, 
	(GameControl::Get()->Height() - getHeight())/2,
						  WIDTH, getHeight())
{
	SetModal();
	SetToolTip(TIP_GAMESETTINGS);

	gameSettings = this;
	listSuspend = listESC = listMotion = NULL;
	editViewSafeMargin = NULL;
	gamePort = gameID = NULL;
	listAutoStartNetwork = listGameServer = NULL;

	Text *text;
	Button *button;	
	int y, editSize = 40, editStart = 22;

	if(!Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		editSize = 45;
		editStart = 8;
	}

	//Title
	text = AddText("Game Properties", CENTER_TEXT, 5);
	y = DrawHLine(text->Down() + 2);

	//Body
	text = AddText("Game resolution: ", 10, y);
	listRes = AddListPop(text->Right(), text->Top(), 128, 0, LS_RES); listRes->SetToolTip(TIP_GAMESETTINGS_RESOLUTION);

	editX = AddEditBox(listRes->Right() + editStart, listRes->Top(), editSize); editX->SetNumeric(2, 2000, 1);
	text = AddText("x", editX->Right()+1, editX->Top());
	editY = AddEditBox(text->Right() + 4, text->Top(), editSize); editY->SetNumeric(2, 2000, 1);

	text = AddText("Mode:            ", 10, editY->Down() + 4);
	listFull = AddListPop(text->Right(), text->Top(), 128, 0, LS_FULL); listFull->SetToolTip(TIP_GAMESETTINGS_MODE);

	if(Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		text = AddText(" Safe margin: ", listFull->Right(), listFull->Top());
		editViewSafeMargin = AddEditBox(editY->Left(), text->Top(), editSize); editViewSafeMargin->SetNumeric(0, 2000, 1);
	}

	text = AddText("Frame rate:      ", 10, listFull->Down() + 4);
	editFps = AddEditBox(text->Right(), text->Top(), 50); editFps->SetNumeric(1, 512, 1);
	text = AddText("fps", editFps->Right() + 2, editFps->Top());

	listMouse = AddListPop(text->Right() + 32, text->Top(), 128, 0, LS_MOUSE); listMouse->SetToolTip(TIP_GAMESETTINGS_MOUSE);

	if(Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		text = AddText("Suspend game if lost focus: ", 10, editFps->Down() + 6);
		listSuspend = AddListPop(text->Right() + 48, text->Top(), 32, 0, LS_SUSPEND); listSuspend->SetToolTip(TIP_GAMESETTINGS_SUSPEND);

		if(Tutorial::IsCompatible(VERSION_ESC_TO_EXIT))
		{
			text = AddText("  Use ESC key to exit game: ", 10, listSuspend->Down() + 6);
			listESC = AddListPop(text->Right() + 48, text->Top(), 32, 0, LS_ESC); listESC->SetToolTip(TIP_GAMESETTINGS_ESC);

			text = AddText("       Motion Compensation: ", 10, listESC->Down() + 6);
			listMotion = AddListPop(text->Right() + 48, text->Top(), 32, 0, LS_MOTION); listMotion->SetToolTip(TIP_GAMESETTINGS_MOTION_COMPENSATION);
		}
		
		
		y = DrawHLine(text->Down() + 8);
	}
	else
	{
		y = DrawHLine(editFps->Down() + 4);
	}
	
	text = AddText("Audio format: ", 10, y);
	listHz = AddListPop(text->Right(), text->Top(), 128, 0, LS_HZ); listHz->SetToolTip(TIP_GAMESETTINGS_AUDIO_HZ);
	listStereo = AddListPop(listHz->Right() + 4, listHz->Top(), 128, 0, LS_STEREO); listStereo->SetToolTip(TIP_GAMESETTINGS_AUDIO_STEREO);
	text = AddText("Maximum number of simultaneous sounds: ", 10, listStereo->Down()+4);
	editMaxSounds = AddEditBox(text->Right(), text->Top(), 50); editMaxSounds->SetNumeric(1, 512, 1);
	
	y = DrawHLine(editMaxSounds->Down() + 2);

	text = AddText("            Icon file:  ", 10, y + 2);
	iconPath = AddListDirectory(text->Right(), text->Top()); iconPath->SetToolTip(TIP_GAMESETTINGS_ICON);

	text = AddText("           Game title: ", 10, iconPath->Down() + 4);
	gameTitle = AddEditBox(text->Right(), text->Top(), 150);

	text = AddText("Game background color: ", 10, gameTitle->Down() + 4);
	backgroundColor = new ColorSample(this, text->Right(), text->Top(), 32); backgroundColor->SetToolTip(TIP_GAMESETTINGS_BACKGROUNDCOLOR);

	//Network
	if(Tutorial::IsCompatible(VERSION_NETWORK) && GAME_EDITOR_VERSION >= VERSION_NETWORK)
	{
		y = DrawHLine(backgroundColor->Down() + 2);

		text = AddText("     Game ID: ", 10, y);		
		gameID = AddEditBox(text->Right(), text->Top(), 256);

		text = AddText("Network Port: ", 10, gameID->Down() + 4);		
		gamePort = AddEditBox(text->Right(), text->Top(), 64);

		text = AddText("Use Game Editor Server: ", 10, gamePort->Down() + 4);
		listGameServer = AddListPop(text->Right() + 2, text->Top(), 32, 0, LS_GAMESERVER); listGameServer->SetToolTip(TIP_GAMESETTINGS_GAME_SERVER);

		text = AddText("    Auto Start Network: ", 10, listGameServer->Down() + 4);
		listAutoStartNetwork = AddListPop(text->Right() + 2, text->Top(), 32, 0, LS_AUTOSTART_NETWORK); listAutoStartNetwork->SetToolTip(TIP_GAMESETTINGS_AUTO_START_NETWORK);

		y = listAutoStartNetwork->Down() + 2;
	}
	else
	{
		y = backgroundColor->Down() + 2;
	}

	//PocketPC
	y = DrawHLine(y);
	listPocketKeys = AddListPop(10, y, 256, 0, LS_POCKET_KEYS, "Pocket PC and GP2X Keys"); listPocketKeys->SetToolTip(TIP_GAMESETTINGS_POCKET_KEYS);
	
	//Close
	y = DrawHLine(listPocketKeys->Down() + 2);
	button = AddButton("Ok", Width()/2 - 70, y, 0, 0, BT_ADD); SetConfirmButton(button);
	button = AddButton("Cancel", button->Right()+8, y, 0, 0, BT_CLOSE); SetCancelButton(button);


	//Populate resolutions
	char buf[64];
	if(Tutorial::IsOff())
	{
		SDL_Rect **modes;
		const SDL_VideoInfo *vinfo = SDL_GetVideoInfo();
		
		/* Get available fullscreen/hardware modes */
		modes=SDL_ListModes(vinfo->vfmt, VIDEO_FLAGS | SDL_FULLSCREEN);
		
		if(modes != (SDL_Rect **)0 && modes != (SDL_Rect **)-1)
		{		
			for(int i=0;modes[i];++i)
			{
				sprintf(buf, "%d x %d", modes[i]->w, modes[i]->h);
				listRes->AddText(buf);
			}
		}
	}
	else
	{
		//Don't change in different machines
		listRes->AddText("1280 x 1024");
		listRes->AddText("1280 x 960");
		listRes->AddText("1280 x 768");
		listRes->AddText("1280 x 720");
		listRes->AddText("1152 x 864");
		listRes->AddText("1024 x 768");
		listRes->AddText("848 x 480");
		listRes->AddText("800 x 600");
		listRes->AddText("720 x 576");
		listRes->AddText("720 x 480");
		listRes->AddText("640 x 480");
		listRes->AddText("640 x 400");
		listRes->AddText("512 x 384");
		listRes->AddText("480 x 360");
		listRes->AddText("400 x 300");
		listRes->AddText("320 x 240");
		listRes->AddText("320 x 200");		
	}

	if(Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		listRes->AddText("240 x 320");
		listRes->AddText("240 x 320 Pocket PC");
		listRes->AddText("240 x 320 Pocket PC Upside down");
		listRes->AddText("320 x 240 Pocket PC Rotate left");
		listRes->AddText("320 x 240 Pocket PC Rotate right");

		listRes->AddText("480 x 640 Pocket PC");
		listRes->AddText("480 x 640 Pocket PC Upside down");
		listRes->AddText("640 x 480 Pocket PC Rotate left");
		listRes->AddText("640 x 480 Pocket PC Rotate right");
		listRes->AddText("800 x 480 Pocket PC Rotate left");
		listRes->AddText("800 x 480 Pocket PC Rotate right");

		//No changes in screen orientation now (don't have the w > h information)
		listRes->AddText("240 x 240 Pocket PC");
		listRes->AddText("480 x 480 Pocket PC");

		//Smartphone
		listRes->AddText("176 x 220 Smartphone");
		listRes->AddText("160 x 240 Smartphone");
		listRes->AddText("208 x 240 Smartphone");
		listRes->AddText("240 x 320 Smartphone");

		//HPC
		listRes->AddText("640 x 240 Handheld PC");
		listRes->AddText("640 x 480 Handheld PC");
		listRes->AddText("800 x 480 Handheld PC");
		listRes->AddText("800 x 600 Handheld PC");

		//GP2X
		listRes->AddText("320 x 240 GP2X");
		listRes->AddText("640 x 480 GP2X");

		// Apple iPhone // AKR
		listRes->AddText("320 x 480 iPhone");
		listRes->AddText("480 x 320 iPhone Rotate left");

		// Apple iPad // AKR
		listRes->AddText("768 x 1024 iPad");
		listRes->AddText("1024 x 768 iPad Rotate left");

	}
	else
	{
		listRes->AddText("240 x 320 Pocket PC");
	}

	listFull->AddText("Full screen");
	listFull->AddText("Window");


	listHz->AddText("44100 Hz");
	listHz->AddText("22050 Hz");
	listHz->AddText("11025 Hz");


	listStereo->AddText("Stereo");
	listStereo->AddText("Mono");

	listMouse->AddText("Show mouse");
	listMouse->AddText("Hide mouse");

	if(listSuspend)
	{
		listSuspend->AddText("Yes");
		listSuspend->AddText("No");
		
		if(GameControl::Get()->getSuspendGameIfLostFocus()) listSuspend->SetItem("Yes");
		else listSuspend->SetItem("No");
	}

	if(listAutoStartNetwork)
	{
		listAutoStartNetwork->AddText("Yes");
		listAutoStartNetwork->AddText("No");
				
		if(GameControl::Get()->getAutoStartNetwork()) listAutoStartNetwork->SetItem("Yes");
		else listAutoStartNetwork->SetItem("No");
	}

	if(listGameServer)
	{
		listGameServer->AddText("Yes");
		listGameServer->AddText("No");
				
		if(GameControl::Get()->getUseGameEditorServer()) listGameServer->SetItem("Yes");
		else listGameServer->SetItem("No");
	}

	if(listESC)
	{
		listESC->AddText("Yes");
		listESC->AddText("No");
		
		if(GameControl::Get()->getUseESCKeyToExit()) listESC->SetItem("Yes");
		else listESC->SetItem("No");
	}

	if(listMotion)
	{
		listMotion->AddText("Yes");
		listMotion->AddText("No");
		
		if(GameControl::Get()->getUseMotionCorrection()) listMotion->SetItem("Yes");
		else listMotion->SetItem("No");
	}

	if(gameID)
	{		
		gameID->SetText(GameControl::Get()->getGameID());
	}

	if(gamePort)
	{		
		gamePort->SetText(GameControl::Get()->getGamePort());
	}


	if(GameControl::Get()->getFullScreen()) listFull->SetItem("Full screen");
	else listFull->SetItem("Window");

	if(GameControl::Get()->getStereo()) listStereo->SetItem("Stereo");
	else listStereo->SetItem("Mono");

	if(GameControl::Get()->getShowMouse()) listMouse->SetItem("Show mouse");
	else listMouse->SetItem("Hide mouse");

	if(editViewSafeMargin)
	{
		editViewSafeMargin->SetText((int)GameControl::Get()->getViewSafeMargin());
	}
	

	sprintf(buf, "%ld Hz", GameControl::Get()->getAudioSamplerRate()); 
	listHz->SetItem(buf);

	sprintf(buf, "%d x %d", GameControl::Get()->getGameWidth(), GameControl::Get()->getGameHeight());
	listRes->SetItem(buf);

	editX->SetText(GameControl::Get()->getGameWidth());
	editY->SetText(GameControl::Get()->getGameHeight());
	editFps->SetText(GameControl::Get()->getFrameRate());
	editMaxSounds->SetText(GameControl::Get()->getMaximumSounds());

	bFlipPocketPCScreen = GameControl::Get()->getFlipPocketPCScreen();

	gedString res(buf);
	if(res == "240 x 320")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("240 x 320 Up. down");
		}
	}
	else if(res == "320 x 240")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("320 x 240 Rot.right");
		}
		else
		{
			listRes->SetText("320 x 240 Rot. left");
		}
	}
	else if(res == "480 x 640")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("480 x 640 Up. down");
		}
		else
		{
			listRes->SetText("480 x 640 Pocket PC");
		}
	}
	else if(res == "640 x 480")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("640 x 480 Rot.right");
		}
		else
		{
			//listRes->SetText("640 x 480 Rot. left");
			listRes->SetText("640 x 480");
		}
	}
	else if(res == "320 x 480")
	{
			listRes->SetText("320 x 480 iPhone");
	}
	else if(res == "480 x 320")
	{
		listRes->SetText("480 x 320 Rot.left");
	}
	else if(res == "768 x 1024")
	{
			listRes->SetText("768x1024 iPad");
	}
	else if(res == "800 x 480")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("800 x 480 Rot.right");
		}
		else
		{			
			listRes->SetText("800 x 480");
		}
	}
	else if(res == "240 x 240")
	{
		listRes->SetText("240 x 240 Pocket PC");
	}
	else if(res == "480 x 480")
	{
		listRes->SetText("480 x 480 Pocket PC");
	}
	else if(res == "176 x 220")
	{
		listRes->SetText("176 x 220 Smartphone");
	}
	else if(res == "160 x 240")
	{
		listRes->SetText("160 x 240 Smartphone");
	}
	else if(res == "208 x 240")
	{
		listRes->SetText("208 x 240 Smartphone");
	}



	iconPath->AddFilter("tga");
	iconPath->AddFilter("bmp");
	iconPath->AddFilter("pnm");
	iconPath->AddFilter("xpm");
	iconPath->AddFilter("xcf");
	iconPath->AddFilter("pcx");
	iconPath->AddFilter("gif");
	iconPath->AddFilter("jpg");
	iconPath->AddFilter("jpeg");
	iconPath->AddFilter("jpe");
	iconPath->AddFilter("jfif");
	iconPath->AddFilter("tif");
	iconPath->AddFilter("tiff");
	iconPath->AddFilter("iff");
	iconPath->AddFilter("lbm");
	iconPath->AddFilter("png");
	iconPath->AddFilter("ico");

	//iconPath->SetText(GameControl::Get()->getIconPath());

	if(!GameControl::Get()->getIconPath().empty())
	{
		gedString file, dir;
		SplitPath(GameControl::Get()->getIconPath(), file, dir);
		chdir(dir.c_str());

		iconPath->AddText(file);
		iconPath->SetItem(file);
	}

	gameTitle->SetText(GameControl::Get()->getGameTitle());

	backgroundColor->setColor(GameControl::Get()->getBackGroundColor());

	SetPocketKeys();
}
Exemplo n.º 20
0
Arquivo: camera.cpp Projeto: sol/cg1
Camera::Camera()
{
	m_pAssociatedScene = NULL;

    //initialise OpenGL
    const SDL_VideoInfo* VideoInfo = SDL_GetVideoInfo();

    int bpp = VideoInfo->vfmt->BitsPerPixel;

    int width = 1024;
    int height = 768;

    if( SDL_SetVideoMode( width, height, bpp, SDL_OPENGL /*| SDL_FULLSCREEN*/ ) == 0)
    {
        fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError() );
        SDL_Quit();
        exit(1);
    }

    float ratio = (float) width / (float) height;

    //attributes of camera should be configured dynamically
    
    glShadeModel( GL_SMOOTH );
    glCullFace( GL_BACK );

    glFrontFace(GL_CCW);

//    glEnable( GL_CULL_FACE );
    glEnable( GL_DEPTH_TEST );

    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

//    glClearColor(1, 1, 1, 1);
    glClearColor(0, 0, 0, 0);

    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glEnable(GL_RENDER);
    glEnable(GL_LIGHTING);

    glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);

	//FOG
/*	glEnable(GL_FOG);

	GLfloat rgba[] = {1, 1, 1, 1};
	glFogfv(GL_FOG_COLOR, rgba);

	glFogi(GL_FOG_MODE, GL_LINEAR);
	glFogf(GL_FOG_DENSITY, .5);

	glFogf(GL_FOG_START, .5);
	glFogf(GL_FOG_END, .6);

	glHint(GL_FOG_HINT, GL_FASTEST|GL_NICEST|GL_DONT_CARE);*/

	gluPerspective(60.0, ratio, 1.0, 1024.0);
}
Exemplo n.º 21
0
int RenderManager::initializeRender()
{

	try
	{
		
		SDL_Surface *surface;
		/* Flags to pass to SDL_SetVideoMode */
		int videoFlags;
		/* main loop variable */
		int done = FALSE;
		/* used to collect events */
		SDL_Event event;
		/* this holds some info about our display */
		const SDL_VideoInfo *videoInfo;



		/* initialize SDL */
		if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
		{
			fprintf( stderr, "Video initialization failed: %s\n",
				 SDL_GetError( ) );
			Quit( 1 );
		}

		/* Fetch the video info */
		videoInfo = SDL_GetVideoInfo( );

		if ( !videoInfo )
		{
			fprintf( stderr, "Video query failed: %s\n",
				 SDL_GetError( ) );
			Quit( 1 );
		}

		/* the flags to pass to SDL_SetVideoMode */
		videoFlags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
		videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
		videoFlags |= SDL_HWPALETTE;       /* Store the palette in hardware */
		videoFlags |= SDL_RESIZABLE;       /* Enable window resizing */

		/* This checks to see if surfaces can be stored in memory */
		if ( videoInfo->hw_available )
			videoFlags |= SDL_HWSURFACE;
		else
			videoFlags |= SDL_SWSURFACE;

		/* This checks if hardware blits can be done */
		if ( videoInfo->blit_hw )
			videoFlags |= SDL_HWACCEL;

		/* Sets up OpenGL double buffering */
		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

		/* get a SDL surface */
		surface = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
					videoFlags );

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

		
		/* initialize OpenGL */
		/* Enable smooth shading */
		glShadeModel( GL_SMOOTH );

		/* Set the background Color*/
		glClearColor( .0f, .0f, .0f, 0.0f );

		/* Depth buffer setup */
		glClearDepth( 17.0f );

		/* Enables Depth Testing */
		glEnable( GL_DEPTH_TEST );

		/* Enables Light */
		glEnable( GL_LIGHTING);
		

		/*Enable gouraud shading */
		glShadeModel(GL_SMOOTH);	

		/* The Type Of Depth Test To Do */
		glDepthFunc( GL_LEQUAL );

		/* Really Nice Perspective Calculations */
		glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );

		GLfloat ratio;

		/* Protect against a divide by zero */
		

		ratio = SCREEN_WIDTH/SCREEN_HEIGHT;
		/* Setup our viewport. */
		glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );

		/* change to the projection matrix and set our viewing volume. */
		glMatrixMode( GL_PROJECTION );
		glLoadIdentity( );

		/* Set our perspective */
		gluPerspective( 45.0f, ratio, 0.1f, 10000.0f );

		/* Make sure we're chaning the model view and not the projection */
		glMatrixMode( GL_MODELVIEW );

		/* Reset The View */
		glLoadIdentity( );

		glewInit();
		if(glewIsSupported("GL_VERSION_3_2"))
			cout << "Ready for OpenGL 3.2 \n" << endl;
		else
		{
			cout << "OpenGL 3.2 not supported \n" << endl;
			//exit(1);
		}

		/* Should never get here */
		return( 0 );
	}
		catch(char e)
		{		
			std::cout << "error  " << e << std::endl; 
		}

}
Exemplo n.º 22
0
/**************************************************************************
  Do any necessary pre-initialization of the UI, if necessary.
**************************************************************************/
void ui_init(void)
{
    char device[20];
    /*  struct widget *pInit_String = NULL;*/
    SDL_Surface *pBgd;
    Uint32 iSDL_Flags;

    button_behavior.counting = FALSE;
    button_behavior.button_down_ticks = 0;
    button_behavior.hold_state = MB_HOLD_SHORT;
    button_behavior.event = fc_calloc(1, sizeof(SDL_MouseButtonEvent));

    SDL_Client_Flags = 0;
    iSDL_Flags = SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE;

    /* auto center new windows in X enviroment */
    putenv((char *)"SDL_VIDEO_CENTERED=yes");

    init_sdl(iSDL_Flags);

    log_normal(_("Using Video Output: %s"),
               SDL_VideoDriverName(device, sizeof(device)));

    /* create splash screen */
#ifdef SMALL_SCREEN
    {
        SDL_Surface *pTmpSurf = load_surf(fileinfoname(get_data_dirs(),
                                          "misc/intro.png"));
        pBgd = zoomSurface(pTmpSurf, DEFAULT_ZOOM, DEFAULT_ZOOM, 0);
        FREESURFACE(pTmpSurf);
    }
#else  /* SMALL_SCREEN */
    pBgd = load_surf(fileinfoname(get_data_dirs(), "misc/intro.png"));
#endif /* SMALL_SCREEN */

    if (pBgd && SDL_GetVideoInfo()->wm_available) {
        set_video_mode(pBgd->w, pBgd->h, SDL_SWSURFACE | SDL_ANYFORMAT);
#if 0
        /*
         * call this for other than X enviroments - currently not supported.
         */
        center_main_window_on_screen();
#endif /* 0 */
        alphablit(pBgd, NULL, Main.map, NULL);
        putframe(Main.map,
                 0, 0, Main.map->w - 1, Main.map->h - 1,
        &(SDL_Color) {
            255, 255, 255, 255
        });
        FREESURFACE(pBgd);
        SDL_WM_SetCaption(_("SDL Client for Freeciv"), _("Freeciv"));
    } else {

#ifndef SMALL_SCREEN
        set_video_mode(640, 480, SDL_SWSURFACE | SDL_ANYFORMAT);
#else  /* SMALL_SCREEN */
        set_video_mode(320, 240, SDL_SWSURFACE | SDL_ANYFORMAT);
#endif /* SMALL_SCREEN */

        if(pBgd) {
            blit_entire_src(pBgd, Main.map, (Main.map->w - pBgd->w) / 2,
                            (Main.map->h - pBgd->h) / 2);
            FREESURFACE(pBgd);
        } else {
            SDL_FillRect(Main.map, NULL, SDL_MapRGB(Main.map->format, 0, 0, 128));
            SDL_WM_SetCaption(_("SDL Client for Freeciv"), _("Freeciv"));
        }
    }

#if 0
    /* create label beackground */
    pBgd = create_surf_alpha(adj_size(350), adj_size(50), SDL_SWSURFACE);

    SDL_FillRect(pBgd, NULL, SDL_MapRGBA(pBgd->format, 255, 255, 255, 128));
    putframe(pBgd, 0, 0, pBgd->w - 1, pBgd->h - 1, SDL_MapRGB(pBgd->format, 0, 0, 0));

    pInit_String = create_iconlabel(pBgd, Main.gui,
                                    create_str16_from_char(_("Initializing Client"), adj_font(20)),
                                    WF_ICON_CENTER|WF_FREE_THEME);
    pInit_String->string16->style |= SF_CENTER;

    draw_label(pInit_String,
               (Main.screen->w - pInit_String->size.w) / 2,
               (Main.screen->h - pInit_String->size.h) / 2);

    flush_all();

    copy_chars_to_string16(pInit_String->string16,
                           _("Waiting for the beginning of the game"));

#endif /* 0 */

    flush_all();
}
Exemplo n.º 23
0
SWError st_CreateStaticText(
	const char* string,
	const char* fontPath,
	int fontSize,
	SWRect* bounds,
	int wrap,
	StaticTextPtr* newStaticTextPP )
{
	SWError err = kNoError;
	FramePtr frameP = NULL;
	StaticTextPtr tempStaticTextP = NULL;
	
	*newStaticTextPP = 0;
	
	if( ! gSTHasBeenInitialized )
		err = kSTHasNotBeenInitedError;
	
	if( err == kNoError )
		if( strlen( string ) > kMaxStringLength - 1 )
			err = kSTStringTooLongError;

	if( err == kNoError )
		if( strlen( fontPath ) > kMaxPathLength - 1 )
			err = kSTPathTooLongError;
	
	if( err == kNoError )
	{
		tempStaticTextP = malloc( sizeof( StaticTextRec ) );
		if( ! tempStaticTextP ) err = kMemoryAllocationError;
	}
	
	if( err == kNoError )
		err = SWCreateSprite( (SpritePtr*)&tempStaticTextP, tempStaticTextP, 1 );		

	if( err == kNoError )
	{
		SWSetSpriteMoveProc( (SpritePtr)tempStaticTextP, handleStaticText );
		
			// make the frame to which we will be copying each line of text
		err = SWCreateBlankFrame(
			&frameP,
			SW_RECT_WIDTH( *bounds ),
			SW_RECT_HEIGHT( *bounds ),
			SDL_GetVideoInfo()->vfmt->BitsPerPixel,
			true );
	}
				
	if( err == kNoError )
	{
		SWSetSpriteLocation( (SpritePtr)tempStaticTextP, bounds->left, bounds->top );
		err = SWAddFrame( (SpritePtr)tempStaticTextP, frameP );
	}
	
	if( err == kNoError )
	{
		strcpy( tempStaticTextP->string, string );
		strcpy( tempStaticTextP->fontPath, fontPath );
		tempStaticTextP->fontSize = fontSize;
		tempStaticTextP->fontStyle = gDefaultStyle;
		tempStaticTextP->wrap = wrap;
		tempStaticTextP->bounds = *bounds;
		tempStaticTextP->align = gDefaultAlign;
		tempStaticTextP->rendering = gDefaultRendering;
		tempStaticTextP->textColor = gDefaultTextColor;
		tempStaticTextP->backColor = gDefaultBackColor;
		
		err = SWSetCurrentFrameIndex( (SpritePtr)tempStaticTextP, 0 );
	}
		
	if( err == kNoError )
		err = renderStaticText( tempStaticTextP );

	if( err == kNoError )
	{
		SWLockSprite( (SpritePtr)tempStaticTextP );
		*newStaticTextPP = tempStaticTextP;
	}
	
	if( err != kNoError )
	{
			// clean up what we can
		if( tempStaticTextP ) st_DisposeStaticText( &tempStaticTextP );
		if( frameP ) SWDisposeFrame( &frameP );
	}
	
	SWSetStickyIfError( err );
	return err;
}
Exemplo n.º 24
0
void TCOD_sys_get_current_resolution(int *w, int *h) {
	const SDL_VideoInfo *info=SDL_GetVideoInfo();
	*w=info->current_w;
	*h=info->current_h;
}
Exemplo n.º 25
0
/*
===============
GLimp_SetMode
===============
*/
static int GLimp_SetMode(int mode, qboolean fullscreen, qboolean noborder)
{
	const char*   glstring;
	int sdlcolorbits;
	int colorbits, depthbits, stencilbits;
	int tcolorbits, tdepthbits, tstencilbits;
	int samples;
	int i = 0;
	SDL_Surface *vidscreen = NULL;
	Uint32 flags = SDL_OPENGL;

	ri.Printf( PRINT_DEVELOPER, "Initializing OpenGL display\n");

	if ( r_allowResize->integer )
		flags |= SDL_RESIZABLE;

	if( videoInfo == NULL )
	{
		static SDL_VideoInfo sVideoInfo;
		static SDL_PixelFormat sPixelFormat;

		videoInfo = SDL_GetVideoInfo( );

		// Take a copy of the videoInfo
		Com_Memcpy( &sPixelFormat, videoInfo->vfmt, sizeof( SDL_PixelFormat ) );
		sPixelFormat.palette = NULL; // Should already be the case
		Com_Memcpy( &sVideoInfo, videoInfo, sizeof( SDL_VideoInfo ) );
		sVideoInfo.vfmt = &sPixelFormat;
		videoInfo = &sVideoInfo;

		if( videoInfo->current_h > 0 )
		{
			// Guess the display aspect ratio through the desktop resolution
			// by assuming (relatively safely) that it is set at or close to
			// the display's native aspect ratio
			displayAspect = (float)videoInfo->current_w / (float)videoInfo->current_h;

			ri.Printf( PRINT_DEVELOPER, "Estimated display aspect: %.3f\n", displayAspect );
		}
		else
		{
			ri.Printf( PRINT_DEVELOPER,
					"Cannot estimate display aspect, assuming 1.333\n" );
		}
	}

	ri.Printf (PRINT_DEVELOPER, "...setting mode %d:", mode );

	if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) )
	{
		ri.Printf( PRINT_ALL, " invalid mode\n" );
		return RSERR_INVALID_MODE;
	}
	ri.Printf( PRINT_DEVELOPER, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight);

	if (fullscreen)
	{
		flags |= SDL_FULLSCREEN;
		glConfig.isFullscreen = qtrue;
	}
	else
	{
		if (noborder)
			flags |= SDL_NOFRAME;

		glConfig.isFullscreen = qfalse;
	}

	colorbits = r_colorbits->value;
	if ((!colorbits) || (colorbits >= 32))
		colorbits = 24;

	if (!r_depthbits->value)
		depthbits = 24;
	else
		depthbits = r_depthbits->value;
	stencilbits = r_stencilbits->value;
	samples = r_ext_multisample->value;

	for (i = 0; i < 16; i++)
	{
		// 0 - default
		// 1 - minus colorbits
		// 2 - minus depthbits
		// 3 - minus stencil
		if ((i % 4) == 0 && i)
		{
			// one pass, reduce
			switch (i / 4)
			{
				case 2 :
					if (colorbits == 24)
						colorbits = 16;
					break;
				case 1 :
					if (depthbits == 24)
						depthbits = 16;
					else if (depthbits == 16)
						depthbits = 8;
				case 3 :
					if (stencilbits == 24)
						stencilbits = 16;
					else if (stencilbits == 16)
						stencilbits = 8;
			}
		}

		tcolorbits = colorbits;
		tdepthbits = depthbits;
		tstencilbits = stencilbits;

		if ((i % 4) == 3)
		{ // reduce colorbits
			if (tcolorbits == 24)
				tcolorbits = 16;
		}

		if ((i % 4) == 2)
		{ // reduce depthbits
			if (tdepthbits == 24)
				tdepthbits = 16;
			else if (tdepthbits == 16)
				tdepthbits = 8;
		}

		if ((i % 4) == 1)
		{ // reduce stencilbits
			if (tstencilbits == 24)
				tstencilbits = 16;
			else if (tstencilbits == 16)
				tstencilbits = 8;
			else
				tstencilbits = 0;
		}

		sdlcolorbits = 4;
		if (tcolorbits == 24)
			sdlcolorbits = 8;

#ifdef __sgi /* Fix for SGIs grabbing too many bits of color */
		if (sdlcolorbits == 4)
			sdlcolorbits = 0; /* Use minimum size for 16-bit color */

		/* Need alpha or else SGIs choose 36+ bit RGB mode */
		SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1);
#endif

		SDL_GL_SetAttribute( SDL_GL_RED_SIZE, sdlcolorbits );
		SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, sdlcolorbits );
		SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, sdlcolorbits );
		SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, tdepthbits );
		SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, tstencilbits );

		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 );
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples );

		if(r_stereoEnabled->integer)
		{
			glConfig.stereoEnabled = qtrue;
			SDL_GL_SetAttribute(SDL_GL_STEREO, 1);
		}
		else
		{
			glConfig.stereoEnabled = qfalse;
			SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
		}
		
		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

#if 0 // See http://bugzilla.icculus.org/show_bug.cgi?id=3526
		// If not allowing software GL, demand accelerated
		if( !r_allowSoftwareGL->integer )
		{
			if( SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ) < 0 )
			{
				ri.Printf( PRINT_ALL, "Unable to guarantee accelerated "
						"visual with libSDL < 1.2.10\n" );
			}
		}
#endif

		if( SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, r_swapInterval->integer ) < 0 )
			ri.Printf( PRINT_ALL, "r_swapInterval requires libSDL >= 1.2.10\n" );

#ifdef USE_ICON
		{
			SDL_Surface *icon = SDL_CreateRGBSurfaceFrom(
					(void *)CLIENT_WINDOW_ICON.pixel_data,
					CLIENT_WINDOW_ICON.width,
					CLIENT_WINDOW_ICON.height,
					CLIENT_WINDOW_ICON.bytes_per_pixel * 8,
					CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width,
#ifdef Q3_LITTLE_ENDIAN
					0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000
#else
					0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF
#endif
					);

			SDL_WM_SetIcon( icon, NULL );
			SDL_FreeSurface( icon );
		}
#endif

		SDL_WM_SetCaption(CLIENT_WINDOW_TITLE, CLIENT_WINDOW_MIN_TITLE);
		SDL_ShowCursor(0);

		if (!(vidscreen = SDL_SetVideoMode(glConfig.vidWidth, glConfig.vidHeight, colorbits, flags)))
		{
			ri.Printf( PRINT_DEVELOPER, "SDL_SetVideoMode failed: %s\n", SDL_GetError( ) );
			continue;
		}

		opengl_context = GLimp_GetCurrentContext();

		ri.Printf( PRINT_DEVELOPER, "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n",
				sdlcolorbits, sdlcolorbits, sdlcolorbits, tdepthbits, tstencilbits);

		glConfig.colorBits = tcolorbits;
		glConfig.depthBits = tdepthbits;
		glConfig.stencilBits = tstencilbits;
		break;
	}

	GLimp_DetectAvailableModes();

	if (!vidscreen)
	{
		ri.Printf( PRINT_ALL, "Couldn't get a visual\n" );
		return RSERR_INVALID_MODE;
	}

	screen = vidscreen;

	glstring = (char *) qglGetString (GL_RENDERER);
	ri.Printf( PRINT_DEVELOPER, "GL_RENDERER: %s\n", glstring );

	return RSERR_OK;
}
Exemplo n.º 26
0
int main(int argc, char *argv[]) {
	SDL_Surface *screen;

	GError *error = NULL;
	RsvgHandle *handle;
	struct svgviewer_view vw;
	char *filename;
	//const char *output_filename = argv[2];
	cairo_surface_t *surface;
	cairo_t *cr;
	cairo_t *cr2;
	cairo_status_t status;
	int c;
	int rerender = 0;

	SDL_VideoInfo* info;
	vw.zoom = 1;

	/* Process options */
	while (1) {
	  int option_index = 0;
	  
	  c = getopt_long (argc, argv, "d:v:",
			   long_options, &option_index);

	  /* Detect the end of the options. */
	  if (c == -1) break;
	  switch (c) {
	  case 0:
	    break;
	  case 'z':
	    errno = 0;
	    vw.zoom = strtod(optarg, NULL);
	    DEBUG("Zoom set to %g\n", vw.zoom);
	    if (errno) FAIL("Usage: -z or --zoom requires a floating point argument");
	    break;
	  default:
	    abort();
	  };
	}
     
	if (argc != optind+1) FAIL("Usage: %s OPTIONS input_file.svg\n", argv[0]);
	filename = argv[optind];

	g_type_init();

	rsvg_set_default_dpi(72.0);
	handle = rsvg_handle_new_from_file(filename, &error);
	if (error != NULL)
		FAIL(error->message);

	rsvg_handle_get_dimensions(handle, &dim);
	vw.x = 0; vw.y = 0;
	vw.zoom    = 1;

	/* Initialize SDL */
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
		fprintf(stderr, "Unable to initialize SDL: %s\n",
			SDL_GetError());
		exit(1);
	}

	int videomodeflags;
	if (fullscreen_flag) {
	  screen = SDL_SetVideoMode(0, 0, 32,
				    videomodeflags =
				    SDL_FULLSCREEN | SDL_SWSURFACE | SDL_RESIZABLE);
	} else {
	  const SDL_VideoInfo* info = SDL_GetVideoInfo(); 
	  if ((dim.width  >= info->current_w) ||
	      (dim.height >= info->current_h)) {
	    screen = SDL_SetVideoMode(0, 0, 32,
				      videomodeflags =
				      SDL_SWSURFACE | SDL_RESIZABLE);
	  } else {
	    screen = SDL_SetVideoMode(dim.width, dim.height, 32,
				      videomodeflags =
				      SDL_SWSURFACE | SDL_RESIZABLE);
	  }
	}

	if (screen == NULL) {
	  fprintf(stderr, "Unable to set video mode: %s\n", SDL_GetError());
	  exit(1);
	}
	
	vw.pixel_width   = screen->w;
	vw.pixel_height  = screen->h;

	surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, vw.pixel_width, vw.pixel_height);
	cr2 = cairo_create (surface); 
	//cairo_translate(cr2, ((double)dim.width)/-2, ((double)dim.height)/-2);
	//surface = cairo_pdf_surface_create (output_filename, width, height);
	// SDL_LockSurface(screen);
	//cairo_scale (cr, screen->w, screen->h);
	cairo_save(cr2);
	view_transform(cr2, &vw);
	rsvg_handle_render_cairo(handle, cr2);
	status = cairo_status(cr2);
	if (status) FAIL(cairo_status_to_string(status));
	cairo_restore(cr2);
	cr = cairosdl_create(screen);

	// cairo_set_source_rgb(cr, 1, 1, 1);
	// cairo_paint(cr);
	
	cairo_save(cr);
	//cairo_scale(cr, .5, .5);
	//cairo_translate(cr, width/2, height/2 );
	//cairo_rotate( cr, 3.14/2 );
	//cairo_translate(cr, -width/2, -height/2 );
	cairo_set_source_surface (cr, surface, 0, 0);
	cairo_paint(cr);
	cairo_restore(cr);
	
	status = cairo_status(cr);
	if (status)
	  FAIL(cairo_status_to_string(status));
	
	// SDL_UnlockSurface(screen);
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	{
	  SDL_Event event;
	  while (SDL_WaitEvent(&event)) {
	    switch (event.type) {
	    case SDL_KEYDOWN:
	      switch (event.key.keysym.sym) {
	      case SDLK_UP:
		vw.y -= 0.1 / vw.zoom;
		rerender = 1;
		break;
	      case SDLK_DOWN:
		vw.y += 0.1 / vw.zoom;
		rerender = 1;
		break;
	      case SDLK_LEFT:
		vw.x -= 0.1 / vw.zoom;
		rerender = 1;
		break;
	      case SDLK_RIGHT:
		vw.x += 0.1 / vw.zoom;
		rerender = 1;
		break;
	      case SDLK_a:
		vw.zoom *= 1.025;
		rerender = 1;
		break;
	      case SDLK_z:
		vw.zoom /= 1.025;
		rerender = 1;
		break;
	      case SDLK_ESCAPE:
		goto exit;
	      default:
		break;
	      }
	      break;
	    case SDL_VIDEORESIZE:
	      {
		vw.pixel_width = event.resize.w;
		vw.pixel_height = event.resize.h;
		cairo_destroy(cr2);
		cairo_surface_destroy(surface);
		surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, vw.pixel_width, vw.pixel_height);
		cr2 = cairo_create(surface);
		//cairo_translate(cr2, ((double)dim.width)/-2, ((double)dim.height)/-2);
		cairo_save(cr2);
		view_transform(cr2, &vw);
		rsvg_handle_render_cairo(handle, cr2);
		cairo_restore(cr2);
		screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 32, videomodeflags);
		cairosdl_destroy(cr);
		cr = cairosdl_create(screen);
		cairo_save(cr);
		cairo_set_source_surface(cr, surface, 0, 0);
		cairo_paint(cr);
		cairo_restore(cr);
	      };
	      break;
	    case SDL_QUIT:
	      goto exit;
	    default:
	      break;
	    }
	    if (rerender) {
		cairo_save(cr2);
		view_transform(cr2, &vw);
		rsvg_handle_render_cairo(handle, cr2);
		status = cairo_status(cr2);
		if (status) FAIL(cairo_status_to_string(status));
		cairo_restore(cr2);
		cairo_set_source_surface(cr, surface, 0, 0);
		cairo_paint(cr);
		rerender = 0;
	    }
	    SDL_UpdateRect(screen, 0, 0, 0, 0);
	  };
	};

 exit:
	cairosdl_destroy(cr);
	if (status)
		FAIL(cairo_status_to_string(status));

	cairo_destroy (cr2);
	cairo_surface_destroy(surface);
	SDL_Quit();
	exit(EXIT_SUCCESS);
}
Exemplo n.º 27
0
int display_init()
{
    /* this holds some info about our display */
    const SDL_VideoInfo *videoInfo;

    /* initialize SDL */
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
	    fprintf( stderr, "Video initialization failed: %s\n",
		     SDL_GetError( ) );
	    Quit( 1 );
	}

    /* Fetch the video info */
    videoInfo = SDL_GetVideoInfo( );

    if ( !videoInfo )
	{
	    fprintf( stderr, "Video query failed: %s\n",
		     SDL_GetError( ) );
	    Quit( 1 );
	}

    /* the flags to pass to SDL_SetVideoMode */
    videoFlags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
    videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
    videoFlags |= SDL_HWPALETTE;       /* Store the palette in hardware */
    videoFlags |= SDL_RESIZABLE;       /* Enable window resizing */

    /* This checks to see if surfaces can be stored in memory */
    if ( videoInfo->hw_available )
	videoFlags |= SDL_HWSURFACE;
    else
	videoFlags |= SDL_SWSURFACE;

    /* This checks if hardware blits can be done */
    if ( videoInfo->blit_hw )
	videoFlags |= SDL_HWACCEL;

    /* Sets up OpenGL double buffering */
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

    /* get a SDL surface */
    surface = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
				videoFlags );

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

    /* initialize OpenGL */
    initGL( );

    /* resize the initial window */
    resizeWindow( SCREEN_WIDTH, SCREEN_HEIGHT );

    return 0;
}
Exemplo n.º 28
0
int main( int argc, char* argv[] ) {
    bool fullscreen = false;
    char* world = "world";
    for (int i=0; i<argc; i++) {
        if (strcmp(argv[i], "-win") == 0) fullscreen = false;
        if (strcmp(argv[i], "-f") == 0) fullscreen = true;
        if (strcmp(argv[i], "-w") == 0)
            world = argv[i+1];
        if (strcmp(argv[i], "-d") == 0) debug = true;
    }
    SetupWorld(world);
    you_x = getWorldX();
    you_z = getWorldZ();
    you_angle = getWorldAngle();

    const SDL_VideoInfo* info = NULL;
    int width = 0;
    int height = 0;
    int bpp = 0;
    int flags = 0;
    
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
        fprintf( stderr, "Video initialization failed: %s\n",
             SDL_GetError( ) );
        quit_app( 1 );
    }

    info = SDL_GetVideoInfo( );
    if( !info ) {
        fprintf( stderr, "Video query failed: %s\n",
             SDL_GetError( ) );
        quit_app( 1 );
    }

    width = 640;
    height = 480;
    bpp = info->vfmt->BitsPerPixel;

    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    flags = SDL_OPENGL;
    if (fullscreen)
        flags |= SDL_FULLSCREEN;
    if( SDL_SetVideoMode( width, height, bpp, flags ) == 0 ) {
        fprintf( stderr, "Video mode set failed: %s\n",
             SDL_GetError( ) );
        quit_app( 1 );
    }

    setup_opengl( width, height );
    bool init = true;
    while( 1 ) {
        process_events( );
        draw_screen( );
        if (init) { glEnable( GL_LIGHTING ); init=false; }
    }
    
    return 0;
}
Exemplo n.º 29
0
int init() {
	if (SDL_Init(SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_VIDEO)) {
		fprintf(stderr,"Error initiating SDL. %s\n",SDL_GetError());
		return 1;
	}
	atexit(SDL_Quit);
	if (SDLNet_Init()) {
		fprintf(stderr,"Error initiating SDL network library. %s\n",SDL_GetError());
		return 1;
	}
	atexit(SDLNet_Quit);
	SDL_Rect **sizes = SDL_ListModes(0,SDL_FULLSCREEN|SDL_OPENGL);//Only get fullscreen sizes. It makes more sense.
	int a;
	for (a = 0;sizes[a];a++) {
		printf("Size[%i]: %i x %i\n",a,sizes[a]->w,sizes[a]->h);
	}
	char *index = malloc(4);
	int i = 0;
	while (1) {
		printf("Please enter the index of the size you want to use.\n");
		fgets(index,4,stdin);
		i = atoi(index);
		if (index[0] != '\n' && index[1] != '\n' && index[2] != '\n' && index[3] != '\n') {
			while (fgetc(stdin) != '\n');
		}
		if (i >= a) {
			printf("Invalid size\n");
			continue;
		}
		break;
	}
	while (1) {
		printf("Use fullscreen: [yn]");
		fflush(stdout);
		fgets(index,2,stdin);//Index can be reused
		if (*index != '\n') {
			while (fgetc(stdin) != '\n');
		}
		if (*index == 'y' || *index == 'Y') {
			fullscreen = 1;
		} else if (*index == 'n' || *index == 'N') {
			fullscreen = 0;
		} else {
			printf("Please enter y or n\n");
			continue;
		}
		break;
	}
	printf("%i %i\n",((fullscreen)?SDL_FULLSCREEN:0),SDL_FULLSCREEN);
	video_info = SDL_GetVideoInfo();
	window = SDL_SetVideoMode(sizes[i]->w,sizes[i]->h,0,SDL_OPENGL/*|((fullscreen)?SDL_FULLSCREEN:0)*/);
	if (!window) {
		fprintf(stderr,"Error in creating window. %s\n",SDL_GetError());
		return 1;
	}
	width = sizes[i]->w;
	height = sizes[i]->h;
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

	// DevIL init

	ilInit();
	
	if (init_freetype())
		return 1;

	//input reader init
	read_config("config/input.conf");
	
	// init camera position
	ex = malloc(sizeof(int));
	ey = malloc(sizeof(int));
	ez = malloc(sizeof(int));
	angle = malloc(sizeof(float));
	*ex = 2; *ey = 2; *ez = 0;
	*angle = 45.0f;



	return 0;
}
Exemplo n.º 30
0
static SDL_Overlay * video_init(void *data, SDL_Surface **pscreen)
{
    struct ALL_DATA *all_data = (struct ALL_DATA *) data;
    struct GLOBAL *global = all_data->global;

    int width = global->width;
    int height = global->height;

    if (*pscreen == NULL) //init SDL
    {
        char driver[128];
        /*----------------------------- Test SDL capabilities ---------------------*/
        if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
        {
            g_printerr("Couldn't initialize SDL: %s\n", SDL_GetError());
            exit(1);
        }

        /* For this version, we will use hardware acceleration as default*/
        if(global->hwaccel)
        {
            if ( ! getenv("SDL_VIDEO_YUV_HWACCEL") ) putenv("SDL_VIDEO_YUV_HWACCEL=1");
            if ( ! getenv("SDL_VIDEO_YUV_DIRECT") ) putenv("SDL_VIDEO_YUV_DIRECT=1");
        }
        else
        {
            if ( ! getenv("SDL_VIDEO_YUV_HWACCEL") ) putenv("SDL_VIDEO_YUV_HWACCEL=0");
            if ( ! getenv("SDL_VIDEO_YUV_DIRECT") ) putenv("SDL_VIDEO_YUV_DIRECT=0");
        }

        if (SDL_VideoDriverName(driver, sizeof(driver)) && global->debug)
        {
            g_print("Video driver: %s\n", driver);
        }

        info = SDL_GetVideoInfo();

        if (info->wm_available && global->debug) g_print("A window manager is available\n");

        if (info->hw_available)
        {
            if (global->debug)
                g_print("Hardware surfaces are available (%dK video memory)\n", info->video_mem);

            SDL_VIDEO_Flags |= SDL_HWSURFACE;
            SDL_VIDEO_Flags |= SDL_DOUBLEBUF;
        }
        else
        {
            SDL_VIDEO_Flags |= SDL_SWSURFACE;
        }

        if (info->blit_hw)
        {
            if (global->debug) g_print("Copy blits between hardware surfaces are accelerated\n");

            SDL_VIDEO_Flags |= SDL_ASYNCBLIT;
        }

        if(!global->desktop_w) global->desktop_w = info->current_w; //get desktop width
        if(!global->desktop_h) global->desktop_h = info->current_h; //get desktop height

        if (global->debug)
        {
            if (info->blit_hw_CC) g_print ("Colorkey blits between hardware surfaces are accelerated\n");
            if (info->blit_hw_A) g_print("Alpha blits between hardware surfaces are accelerated\n");
            if (info->blit_sw) g_print ("Copy blits from software surfaces to hardware surfaces are accelerated\n");
            if (info->blit_sw_CC) g_print ("Colorkey blits from software surfaces to hardware surfaces are accelerated\n");
            if (info->blit_sw_A) g_print("Alpha blits from software surfaces to hardware surfaces are accelerated\n");
            if (info->blit_fill) g_print("Color fills on hardware surfaces are accelerated\n");
        }

        SDL_WM_SetCaption(global->WVcaption, NULL);

        /* enable key repeat */
        SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,SDL_DEFAULT_REPEAT_INTERVAL);
    }
    /*------------------------------ SDL init video ---------------------*/
    if(global->debug)
        g_print("(Desktop resolution = %ix%i)\n", global->desktop_w, global->desktop_h);
    g_print("Checking video mode %ix%[email protected] : ", width, height);
    int bpp = SDL_VideoModeOK(
        width,
        height,
        32,
        SDL_VIDEO_Flags);

    if(!bpp)
    {
        g_print("Not available \n");
        /*resize video mode*/
        if ((width > global->desktop_w) || (height > global->desktop_h))
        {
            width = global->desktop_w; /*use desktop video resolution*/
            height = global->desktop_h;
        }
        else
        {
            width = 800;
            height = 600;
        }
        g_print("Resizing to %ix%i\n", width, height);

    }
    else
    {
        g_print("OK \n");
        if ((bpp != 32) && global->debug) g_print("recomended color depth = %i\n", bpp);
        global->bpp = bpp;
    }

    *pscreen = SDL_SetVideoMode(
        width,
        height,
        global->bpp,
        SDL_VIDEO_Flags);

    if(*pscreen == NULL)
    {
        return (NULL);
    }
    //use requested resolution for overlay even if not available as video mode
    SDL_Overlay* overlay=NULL;
    overlay = SDL_CreateYUVOverlay(global->width, global->height,
        SDL_YUY2_OVERLAY, *pscreen);

    SDL_ShowCursor(SDL_DISABLE);
    return (overlay);
}