Exemple #1
0
int
main(int argc, char *argv[])
{
    char buffer[BUFSIZ + 1];

    SDL_SetError("Hi there!");
    printf("Error 1: %s\n", SDL_GetError());
    SDL_ClearError();
    SDL_memset(buffer, '1', BUFSIZ);
    buffer[BUFSIZ] = 0;
    SDL_SetError("This is the error: %s (%f)", buffer, 1.0);
    printf("Error 2: %s\n", SDL_GetError());
    exit(0);
}
/* 
 * Local helper to check for the invalid scancode error message
 */
void
_checkInvalidNameError()
{
   const char *expectedError = "Parameter 'name' is invalid";
   const char *error;   
   error = SDL_GetError();
   SDLTest_AssertPass("Call to SDL_GetError()");
   SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
   if (error != NULL) {
      SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0, 
          "Validate error message, expected: '%s', got: '%s'", expectedError, error);
      SDL_ClearError();
      SDLTest_AssertPass("Call to SDL_ClearError()");
   }
}
Exemple #3
0
int SDL_Init(Uint32 flags)
{
	/* Clear the error message */
	SDL_ClearError();

	/* Initialize the desired subsystems */
	if ( SDL_InitSubSystem(flags) < 0 ) {
		return(-1);
	}

	/* Everything is initialized */
	if ( !(flags & SDL_INIT_NOPARACHUTE) ) {
		SDL_InstallParachute();
	}
	return(0);
}
Exemple #4
0
/*
Returns the first image found at the provided path
This method attempts all the suffices stored in Texture::IMAGE_EXTS
@imagePath Path to search for images
*/
SDL_Surface *Texture::findImage(const char *imagePath)
{
    if (!imagePath)
        return 0;
    SDL_Surface *image=0;
    for (int i = 0; i < sizeof(IMAGE_EXTS) / sizeof(char*);i++)
    {
        image = IMG_Load(std::string(imagePath).append(IMAGE_EXTS[i]).c_str());
        if (image)
        {
            SDL_ClearError();//Clear the img errorS  
            break;          
        }
    }
    return image;
}
Exemple #5
0
/* returns non-zero if all needed symbols were loaded. */
int
SDL_WAYLAND_LoadSymbols(void)
{
    int rc = 1;                 /* always succeed if not using Dynamic WAYLAND stuff. */

    /* deal with multiple modules (dga, wayland, etc) needing these symbols... */
    if (wayland_load_refcount++ == 0) {
#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC
        int i;
        int *thismod = NULL;
        for (i = 0; i < SDL_TABLESIZE(waylandlibs); i++) {
            if (waylandlibs[i].libname != NULL) {
                waylandlibs[i].lib = SDL_LoadObject(waylandlibs[i].libname);
            }
        }

#define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 1; /* default yes */
#include "SDL_waylandsym.h"

#define SDL_WAYLAND_MODULE(modname) thismod = &SDL_WAYLAND_HAVE_##modname;
#define SDL_WAYLAND_SYM(rc,fn,params) WAYLAND_##fn = (SDL_DYNWAYLANDFN_##fn) WAYLAND_GetSym(#fn,thismod);
#define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = (struct wl_interface *) WAYLAND_GetSym(#iface,thismod);
#include "SDL_waylandsym.h"

        if (SDL_WAYLAND_HAVE_WAYLAND_CLIENT) {
            /* all required symbols loaded. */
            SDL_ClearError();
        } else {
            /* in case something got loaded... */
            SDL_WAYLAND_UnloadSymbols();
            rc = 0;
        }

#else  /* no dynamic WAYLAND */

#define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 1; /* default yes */
#define SDL_WAYLAND_SYM(rc,fn,params) WAYLAND_##fn = fn;
#define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = &iface;
#include "SDL_waylandsym.h"

#endif
    }

    return rc;
}
Exemple #6
0
int
main(int argc, char *argv[])
{
	if (SDL_Init(SDL_INIT_VIDEO) == -1) {
		fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	SDL_ClearError();
	printf("SDL initialized\n");

	atexit(end_SDL);


	/* Creat a SDL window, and get the window's surface. */
	SDL_Surface *screen = NULL;
	screen = SDL_SetVideoMode(459, 732, 24, SDL_SWSURFACE);
	if (screen == NULL) {
		fprintf(stderr, "SDL_SetVideoMode() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Load a BMP file, and convert it as a surface */
	SDL_Surface *bmp = NULL;
	bmp = SDL_LoadBMP("1.bmp");
	if (bmp == NULL) {
		fprintf(stderr, "SDL_LoadBMP() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Put the BMP's surface on the SDL window's surface. */
	if (SDL_BlitSurface(bmp, NULL, screen, NULL) == -1) {
		fprintf(stderr, "SDL_BlitSurface() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Show the SDL window's surface */
	if (SDL_Flip(screen) == -1) {
		fprintf(stderr, "SDL_Flip() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	press_ESC_to_quit();

	return 0;
}
Exemple #7
0
/*-------------------------------------
 * System Runtime
-------------------------------------*/
void MainState::on_run() {
    LS_LOG_GL_ERR();

    renderContext.make_current(*global::pDisplay);
    LS_LOG_GL_ERR();

    renderContext.flip(*global::pDisplay);
    LS_LOG_GL_ERR();
    
    const char* const pSdlErr = SDL_GetError();
    if (pSdlErr && pSdlErr[0] != '\0') {
        LS_LOG_ERR("SDL_ERROR: ", pSdlErr);
        SDL_ClearError();
    }

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    LS_LOG_GL_ERR();
}
Exemple #8
0
void MainManager::run() {
  assert(basicRender_ && "You need a renderer, fool!");

  SDL_Event event;

  uint frameNumber = 0;
  float previousTime = runtime_->getSeconds();

  while (isRunning_) {
#ifndef NDEBUG
    const char* err = SDL_GetError();
    if (err[0] != '\0') {
      log_.e() << "SDL_GetError(): " << err << Log::end;
    }
#endif
    SDL_ClearError();


    while (SDL_PollEvent(&event)) {
      handleEvent(event);
      basicRender_->handleEvent(event);
      if (scene_) scene_->handleEvent(event);
    }

    ++frameNumber;

    if (scene_) scene_->refresh();

    basicRender_->refresh();
    textRenderer_.refresh();

    currentTimeDelta_ = runtime_->getSeconds() - previousTime;
    previousTime = runtime_->getSeconds();
    physics_->stepSimulation(currentTimeDelta_);

    basicRender_->render(runtime_->getSeconds());
    textRenderer_.render(0);
    graphics_->swapBuffers();

    fpsCounter_.tic();
    if (frameNumber % 30 == 0)
      updateFpsText(fpsCounter_.getFps());
  }
}
Exemple #9
0
/* returns non-zero if all needed symbols were loaded. */
int SDL_X11_LoadSymbols(void)
{
	int rc = 1;  /* always succeed if not using Dynamic X11 stuff. */

	#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
	/* deal with multiple modules (dga, x11, etc) needing these symbols... */
	if (x11_load_refcount++ == 0) {
		int i;
		int *thismod = NULL;
		for (i = 0; i < SDL_TABLESIZE(x11libs); i++) {
			if (x11libs[i].libname != NULL) {
				x11libs[i].lib = SDL_LoadObject(x11libs[i].libname);
			}
		}
		#define SDL_X11_MODULE(modname) thismod = &SDL_X11_HAVE_##modname;
		#define SDL_X11_SYM(a,fn,x,y,z) X11_GetSym(#fn,thismod,(void**)&p##fn);
		#include "SDL_x11sym.h"
		#undef SDL_X11_MODULE
		#undef SDL_X11_SYM

		#ifdef X_HAVE_UTF8_STRING
		X11_GetSym("XCreateIC",&SDL_X11_HAVE_UTF8,(void **)&pXCreateIC);
		X11_GetSym("XGetICValues",&SDL_X11_HAVE_UTF8,(void **)&pXGetICValues);
		#endif

		if (SDL_X11_HAVE_BASEXLIB) {  /* all required symbols loaded. */
			SDL_ClearError();
		} else {
			SDL_X11_UnloadSymbols();  /* in case something got loaded... */
			rc = 0;
		}
	}
	#else
		#if DEBUG_DYNAMIC_X11
		printf("X11: No dynamic X11 support in this build of SDL.\n");
		#endif
		#ifdef X_HAVE_UTF8_STRING
		pXCreateIC = XCreateIC;
		pXGetICValues = XGetICValues;
		#endif
	#endif

	return rc;
}
Exemple #10
0
int
main(int argc, char *argv[])
{
	if (SDL_Init(SDL_INIT_VIDEO) == -1) {
		fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	SDL_ClearError();
	printf("SDL initialized\n");

	atexit(end_SDL);


	/* Creat a SDL window, and get the window's surface. */
	//SDL_Surface *screen = NULL;
	screen = SDL_SetVideoMode(640, 480, 32, SDL_FULLSCREEN);
	if (screen == NULL) {
		fprintf(stderr, "SDL_SetVideoMode() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Load a BMP file, and convert it as a surface */
	//SDL_Surface *back = NULL;
	back = SDL_LoadBMP("back.bmp");
	if (back == NULL) {
		fprintf(stderr, "SDL_LoadBMP() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Load a BMP file, and convert it as a surface */
	//SDL_Surface *front = NULL;
	front = SDL_LoadBMP("front.bmp");
	if (front == NULL) {
		fprintf(stderr, "SDL_LoadBMP() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	press_ESC_to_quit();

	return 0;
}
Exemple #11
0
void music_play (const char *file,
                 const char *alias,
                 uint32_t rate)
{
    int audio_format = MIX_DEFAULT_FORMAT;
    int audio_channels = 2;
    int audio_buffers = 4096;

    if (!music_init_done) {
        if (Mix_OpenAudio(rate,
                          audio_format,
                          audio_channels,
                          audio_buffers) != 0) {

            MSG_BOX("Mix_OpenAudio fail: %s %s",
                    Mix_GetError(), SDL_GetError());
            SDL_ClearError();
        }

        music_init_done = true;
    }

    musicp music = music_load(file, alias);

    music_update_volume();

    static int sound_loaded;
    if (!sound_loaded) {
        sound_loaded = true;
        sound_load_all();
    }

    if (HEADLESS) {
        return;
    }

    if (Mix_FadeInMusicPos(music->music, -1, 2000, 0) == -1) {
//    if (Mix_PlayMusic(music->music, -1) == -1) {
        WARN("cannot play music %s: %s", music->tree.key, Mix_GetError());
    }
}
/**
 * @brief SDL_GetScancodeName negative cases
 *
 * @sa http://wiki.libsdl.org/moin.cgi/SDL_GetScancodeName
 */
int
keyboard_getScancodeNameNegative(void *arg)
{
    SDL_Scancode scancode;
    char *result;
    char *expected = "";

    /* Clear error message */
    SDL_ClearError();
    SDLTest_AssertPass("Call to SDL_ClearError()");

    /* Out-of-bounds scancode */
    scancode = (SDL_Scancode)SDL_NUM_SCANCODES;
    result = (char *)SDL_GetScancodeName(scancode);
    SDLTest_AssertPass("Call to SDL_GetScancodeName(%d/large)", scancode);
    SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
    SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
    _checkInvalidScancodeError();

    return TEST_COMPLETED;
}
Exemple #13
0
DECLSPEC int SDLCALL SDL_Init(Uint32 flags) {
#if !SDL_THREADS_DISABLED && SDL_THREAD_PTH
    if (!pth_init()) {
        return -1;
    }
#endif

    /* Clear the error message */
    SDL_ClearError();

    /* Initialize the desired subsystems */
    if ( SDL_InitSubSystem(flags) < 0 ) {
        return(-1);
    }

    /* Everything is initialized */
    if ( !(flags & SDL_INIT_NOPARACHUTE) ) {
        SDL_InstallParachute();
    }
    return(0);
}
Exemple #14
0
TTF_system::TTF_system()
{
  SDL_version compiled;

  SDL_TTF_VERSION(&compiled);
  SDL_version const* linked = TTF_Linked_Version();

  log_status(log_scope::ENGINE, log_line_seperator);
  log_status(log_scope::ENGINE, "Compiled against SDL_ttf version {}.{}.{}",
    (unsigned)compiled.major, (unsigned)compiled.minor, (unsigned)compiled.patch);
  log_status(log_scope::ENGINE, "Linked against SDL_ttf version {}.{}.{}",
    (unsigned)linked->major, (unsigned)linked->minor, (unsigned)linked->patch);
  log_status(log_scope::ENGINE, log_line_seperator);

  if(TTF_Init() != 0)
  {
    log_error(log_scope::ENGINE, "Error initializing SDL_ttf: {}", TTF_GetError());
    SDL_ClearError();
    throw fatal_construction_exception{};
  }
}
Exemple #15
0
static SDL_Surface* ConvertSurface(bool* Continue, bool* Error, SDL_Surface* Source, const char* Name)
{
	SDL_Surface* Dest;
	if (Source->format->Amask != 0)
		Dest = SDL_DisplayFormatAlpha(Source);
	else
		Dest = SDL_DisplayFormat(Source);
	if (Dest == NULL)
	{
		*Continue = false;  *Error = true;
		printf("%s: SDL_ConvertSurface failed: %s\n", Name, SDL_GetError());
		SDL_ClearError();
		return NULL;
	}
	else
	{
		printf("Successfully converted %s to the screen's pixel format\n", Name);
		SDL_FreeSurface(Source);
		return Dest;
	}
}
int SDL_SetGamma(float red, float green, float blue)
{
	int succeeded;
	SDL_VideoDevice *video = current_video;
	SDL_VideoDevice *this  = current_video;	

	succeeded = -1;
	/* Prefer using SetGammaRamp(), as it's more flexible */
	{
		Uint16 ramp[3][256];

		CalculateGammaRamp(red, ramp[0]);
		CalculateGammaRamp(green, ramp[1]);
		CalculateGammaRamp(blue, ramp[2]);
		succeeded = SDL_SetGammaRamp(ramp[0], ramp[1], ramp[2]);
	}
	if ( (succeeded < 0) && video->SetGamma ) {
		SDL_ClearError();
		succeeded = video->SetGamma(this, red, green, blue);
	}
	return succeeded;
}
Exemple #17
0
Image::Image(std::string filename)
{
	GLTextureId = 0;
	try
	{
		SDL_ClearError();
		SDL_Surface* surface = IMG_Load(filename.c_str());

		std::string error = std::string("SDL Error: ") + std::string(SDL_GetError());

		glPixelStorei(GL_UNPACK_ALIGNMENT,4);
		glGenTextures(1, &GLTextureId);
		glBindTexture(GL_TEXTURE_2D, GLTextureId);
		glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
		glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_REPLACE);
		
		

		SDL_PixelFormat *format = surface->format;
		if (format->Amask)
		{
			gluBuild2DMipmaps(GL_TEXTURE_2D, 4,
				surface->w, surface->h, GL_RGBA,GL_UNSIGNED_BYTE, surface->pixels);
		}
		else
		{
			gluBuild2DMipmaps(GL_TEXTURE_2D, 3,
				surface->w, surface->h, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);
		}
		Width = surface->w;
		Height = surface->h;
		SDL_FreeSurface(surface);
	}
	catch (...)
	{
		printf("Failed to load texture: %s",filename.c_str());
	}
}
/**
 * @brief Check call to SDL_GetScancodeFromName with invalid data
 * 
 * @sa http://wiki.libsdl.org/moin.cgi/SDL_GetScancodeFromName
 * @sa http://wiki.libsdl.org/moin.cgi/SDL_Keycode
 */
int
keyboard_getScancodeFromNameNegative(void *arg)
{      
   char *name;
   SDL_Scancode scancode;

   /* Clear error message */
   SDL_ClearError();
   SDLTest_AssertPass("Call to SDL_ClearError()");

   /* Random string input */
   name = SDLTest_RandomAsciiStringOfSize(32);
   SDLTest_Assert(name != NULL, "Check that random name is not NULL");
   if (name == NULL) {
      return TEST_ABORTED;
   }   
   scancode = SDL_GetScancodeFromName((const char *)name);
   SDLTest_AssertPass("Call to SDL_GetScancodeFromName('%s')", name);
   SDL_free(name);
   SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
   _checkInvalidNameError();
         
   /* Zero length string input */
   name = "";
   scancode = SDL_GetScancodeFromName((const char *)name);
   SDLTest_AssertPass("Call to SDL_GetScancodeFromName(NULL)");
   SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
   _checkInvalidNameError();

   /* NULL input */
   name = NULL;
   scancode = SDL_GetScancodeFromName((const char *)name);
   SDLTest_AssertPass("Call to SDL_GetScancodeFromName(NULL)");
   SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
   _checkInvalidNameError();
   
   return TEST_COMPLETED;
}
 void check_SDL_error(int line = -1, bool throw_ex = false)
 {
   const char *error = SDL_GetError();
   if (*error != '\0')
   {
     stringstream os;
     os << "SDL Error: " << error;
     if (line != -1)
       os << " on line " << line;
     
     SDL_ClearError();
     if ( !throw_ex )
     {
       logerr << os.str() << endl;
     }
     else
     {
       BOOST_THROW_EXCEPTION(
         SDL_exception()
           << errinfo_str(os.str())
       );
     }
   }
 }
Exemple #20
0
/**
 * @brief The entry point of this force feedback demo.
 * @param[in] argc Number of arguments.
 * @param[in] argv Array of argc arguments.
 */
int
main(int argc, char **argv)
{
    int i;
    char *name;
    int index;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    name = NULL;
    index = -1;
    if (argc > 1) {
        size_t l;
        name = argv[1];
        if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) {
            SDL_Log("USAGE: %s [device]\n"
                   "If device is a two-digit number it'll use it as an index, otherwise\n"
                   "it'll use it as if it were part of the device's name.\n",
                   argv[0]);
            return 0;
        }

        l = SDL_strlen(name);
        if ((l < 3) && SDL_isdigit(name[0]) && ((l == 1) || SDL_isdigit(name[1]))) {
            index = SDL_atoi(name);
            name = NULL;
        }
    }

    /* Initialize the force feedbackness */
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK |
             SDL_INIT_HAPTIC);
    SDL_Log("%d Haptic devices detected.\n", SDL_NumHaptics());
    if (SDL_NumHaptics() > 0) {
        /* We'll just use index or the first force feedback device found */
        if (name == NULL) {
            i = (index != -1) ? index : 0;
        }
        /* Try to find matching device */
        else {
            for (i = 0; i < SDL_NumHaptics(); i++) {
                if (strstr(SDL_HapticName(i), name) != NULL)
                    break;
            }

            if (i >= SDL_NumHaptics()) {
                SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to find device matching '%s', aborting.\n",
                       name);
                return 1;
            }
        }

        haptic = SDL_HapticOpen(i);
        if (haptic == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create the haptic device: %s\n",
                   SDL_GetError());
            return 1;
        }
        SDL_Log("Device: %s\n", SDL_HapticName(i));
    } else {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Haptic devices found!\n");
        return 1;
    }

    /* We only want force feedback errors. */
    SDL_ClearError();

    if (SDL_HapticRumbleSupported(haptic) == SDL_FALSE) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Rumble not supported!\n");
        return 1;
    }
    if (SDL_HapticRumbleInit(haptic) != 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize rumble: %s\n", SDL_GetError());
        return 1;
    }
    SDL_Log("Playing 2 second rumble at 0.5 magnitude.\n");
    if (SDL_HapticRumblePlay(haptic, 0.5, 5000) != 0) {
       SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() );
       return 1;
    }
    SDL_Delay(2000);
    SDL_Log("Stopping rumble.\n");
    SDL_HapticRumbleStop(haptic);
    SDL_Delay(2000);
    SDL_Log("Playing 2 second rumble at 0.3 magnitude.\n");
    if (SDL_HapticRumblePlay(haptic, 0.3f, 5000) != 0) {
       SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() );
       return 1;
    }
    SDL_Delay(2000);

    /* Quit */
    if (haptic != NULL)
        SDL_HapticClose(haptic);
    SDL_Quit();

    return 0;
}
int
RunGLTest(int argc, char *argv[],
          int logo, int logocursor, int slowly, int bpp, float gamma,
          int noframe, int fsaa, int sync, int accel)
{
    int i;
    int rgb_size[3];
    int w = 640;
    int h = 480;
    int done = 0;
    int frames;
    Uint32 start_time, this_time;
    float color[8][3] = { {1.0, 1.0, 0.0},
    {1.0, 0.0, 0.0},
    {0.0, 0.0, 0.0},
    {0.0, 1.0, 0.0},
    {0.0, 1.0, 1.0},
    {1.0, 1.0, 1.0},
    {1.0, 0.0, 1.0},
    {0.0, 0.0, 1.0}
    };
    float cube[8][3] = { {0.5, 0.5, -0.5},
    {0.5, -0.5, -0.5},
    {-0.5, -0.5, -0.5},
    {-0.5, 0.5, -0.5},
    {-0.5, 0.5, 0.5},
    {0.5, 0.5, 0.5},
    {0.5, -0.5, 0.5},
    {-0.5, -0.5, 0.5}
    };
    Uint32 video_flags;
    int value;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    /* See if we should detect the display depth */
    if (bpp == 0) {
        if (SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8) {
            bpp = 8;
        } else {
            bpp = 16;           /* More doesn't seem to work */
        }
    }

    /* Set the flags we want to use for setting the video mode */
    video_flags = SDL_OPENGL;
    for (i = 1; argv[i]; ++i) {
        if (strcmp(argv[i], "-fullscreen") == 0) {
            video_flags |= SDL_FULLSCREEN;
        }
    }

    if (noframe) {
        video_flags |= SDL_NOFRAME;
    }

    /* Initialize the display */
    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);
    if (fsaa) {
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa);
    }
    if (accel >= 0) {
        SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, accel);
    }
    if (SDL_SetVideoMode(w, h, bpp, video_flags) == NULL) {
        fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }
    if (sync) {
        SDL_GL_SetSwapInterval(1);
    } else {
        SDL_GL_SetSwapInterval(0);
    }

    printf("Screen BPP: %d\n", SDL_GetVideoSurface()->format->BitsPerPixel);
    printf("\n");
    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");

    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);
    if (fsaa) {
        SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
        printf("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
        SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
        printf("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
               value);
    }
    if (accel >= 0) {
        SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
        printf("SDL_GL_ACCELERATED_VISUAL: requested %d, got %d\n", accel,
               value);
    }
    if (sync) {
        printf("Buffer swap interval: requested 1, got %d\n",
               SDL_GL_GetSwapInterval());
    }

    /* Set the window manager title bar */
    SDL_WM_SetCaption("SDL GL test", "testgl");

    /* Set the gamma for the window */
    if (gamma != 0.0) {
        SDL_SetGamma(gamma, gamma, gamma);
    }

    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(-2.0, 2.0, -2.0, 2.0, -20.0, 20.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glEnable(GL_DEPTH_TEST);

    glDepthFunc(GL_LESS);

    glShadeModel(GL_SMOOTH);

    /* Loop until done. */
    start_time = SDL_GetTicks();
    frames = 0;
    while (!done) {
        GLenum gl_error;
        char *sdl_error;
        SDL_Event event;

        /* Do our drawing, too. */
        glClearColor(0.0, 0.0, 0.0, 1.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBegin(GL_QUADS);

#ifdef SHADED_CUBE
        glColor3fv(color[0]);
        glVertex3fv(cube[0]);
        glColor3fv(color[1]);
        glVertex3fv(cube[1]);
        glColor3fv(color[2]);
        glVertex3fv(cube[2]);
        glColor3fv(color[3]);
        glVertex3fv(cube[3]);

        glColor3fv(color[3]);
        glVertex3fv(cube[3]);
        glColor3fv(color[4]);
        glVertex3fv(cube[4]);
        glColor3fv(color[7]);
        glVertex3fv(cube[7]);
        glColor3fv(color[2]);
        glVertex3fv(cube[2]);

        glColor3fv(color[0]);
        glVertex3fv(cube[0]);
        glColor3fv(color[5]);
        glVertex3fv(cube[5]);
        glColor3fv(color[6]);
        glVertex3fv(cube[6]);
        glColor3fv(color[1]);
        glVertex3fv(cube[1]);

        glColor3fv(color[5]);
        glVertex3fv(cube[5]);
        glColor3fv(color[4]);
        glVertex3fv(cube[4]);
        glColor3fv(color[7]);
        glVertex3fv(cube[7]);
        glColor3fv(color[6]);
        glVertex3fv(cube[6]);

        glColor3fv(color[5]);
        glVertex3fv(cube[5]);
        glColor3fv(color[0]);
        glVertex3fv(cube[0]);
        glColor3fv(color[3]);
        glVertex3fv(cube[3]);
        glColor3fv(color[4]);
        glVertex3fv(cube[4]);

        glColor3fv(color[6]);
        glVertex3fv(cube[6]);
        glColor3fv(color[1]);
        glVertex3fv(cube[1]);
        glColor3fv(color[2]);
        glVertex3fv(cube[2]);
        glColor3fv(color[7]);
        glVertex3fv(cube[7]);
#else /* flat cube */
        glColor3f(1.0, 0.0, 0.0);
        glVertex3fv(cube[0]);
        glVertex3fv(cube[1]);
        glVertex3fv(cube[2]);
        glVertex3fv(cube[3]);

        glColor3f(0.0, 1.0, 0.0);
        glVertex3fv(cube[3]);
        glVertex3fv(cube[4]);
        glVertex3fv(cube[7]);
        glVertex3fv(cube[2]);

        glColor3f(0.0, 0.0, 1.0);
        glVertex3fv(cube[0]);
        glVertex3fv(cube[5]);
        glVertex3fv(cube[6]);
        glVertex3fv(cube[1]);

        glColor3f(0.0, 1.0, 1.0);
        glVertex3fv(cube[5]);
        glVertex3fv(cube[4]);
        glVertex3fv(cube[7]);
        glVertex3fv(cube[6]);

        glColor3f(1.0, 1.0, 0.0);
        glVertex3fv(cube[5]);
        glVertex3fv(cube[0]);
        glVertex3fv(cube[3]);
        glVertex3fv(cube[4]);

        glColor3f(1.0, 0.0, 1.0);
        glVertex3fv(cube[6]);
        glVertex3fv(cube[1]);
        glVertex3fv(cube[2]);
        glVertex3fv(cube[7]);
#endif /* SHADED_CUBE */

        glEnd();

        glMatrixMode(GL_MODELVIEW);
        glRotatef(5.0, 1.0, 1.0, 1.0);

        /* Draw 2D logo onto the 3D display */
        if (logo) {
            DrawLogoTexture();
        }
        if (logocursor) {
            DrawLogoCursor();
        }

        SDL_GL_SwapBuffers();

        /* Check for error conditions. */
        gl_error = glGetError();

        if (gl_error != GL_NO_ERROR) {
            fprintf(stderr, "testgl: OpenGL error: %d\n", gl_error);
        }

        sdl_error = (char *)SDL_GetError();

        if (sdl_error[0] != '\0') {
            fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error);
            SDL_ClearError();
        }

        /* Allow the user to see what's happening */
        if (slowly) {
            SDL_Delay(20);
        }

        /* Check if there's a pending event. */
        while (SDL_PollEvent(&event)) {
            done |= HandleEvent(&event);
        }
        ++frames;
    }

    /* Print out the frames per second */
    this_time = SDL_GetTicks();
    if (this_time != start_time) {
        printf("%2.2f FPS\n",
               ((float) frames / (this_time - start_time)) * 1000.0);
    }

    if (global_image) {
        SDL_FreeSurface(global_image);
        global_image = NULL;
    }
    if (global_texture) {
        glDeleteTextures(1, &global_texture);
        global_texture = 0;
    }
    if (cursor_texture) {
        glDeleteTextures(1, &cursor_texture);
        cursor_texture = 0;
    }

    /* Destroy our GL context, etc. */
    SDL_Quit();
    return (0);
}
Exemple #22
0
int RunGLTest ()
{
	int bpp;
	int w = 500;
	int h = 500;
	int done = 0;
	int shrink=0;
	int grow=0;

	xy s	   	=		   parsemodes(w,h,"mode",1,0,0);
	if (s.x!=-1){w=s.x;h=s.y;};
	
	Uint32 video_flags=initsdl(w,h,&bpp);
    
	/* Set the window manager title bar */
	SDL_WM_SetCaption( "SDL GL test", "testgl" );
	SDL_EnableUNICODE(1);
	
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
	
	wm(w,h);
	glDepthFunc(GL_LESS);
	glEnable(GL_BLEND);
	glShadeModel(GL_SMOOTH);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);

	add_terminal();
	glLineWidth(1);
	glClearColor( 0.0, 0.0, 0.0, 1.0 );
	while( !done )
	{
		GLenum gl_error;
		char* sdl_error;
		SDL_Event event;
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
				
		rote_vt_update(t);
		glPushMatrix();
		glRotatef(rot,1,0,0);
		glPushMatrix();
		    glTranslatef(-2.52,1.92,0);
		    glPushMatrix();
		    activetext=(active==2);
		    if (active==2)
			glScalef(0.003,-0.003,1);
		    else
			glScalef(0.002,-0.002,1);
		    draw_terminal(t);
		    glPopMatrix();
		    glPushMatrix();
		    activetext=(active==1);
		    if (active==1)
			glScalef(0.003,-0.003,1);
		    else
			glScalef(0.002,-0.002,1);
		    glTranslatef(0,plscroll*60,0);
		    PyRun_SimpleString("dr_aw()");
		    glPopMatrix();
		glPopMatrix();
		glPopMatrix();

		SDL_GL_SwapBuffers( );
    
		gl_error = glGetError( );

		if( gl_error != GL_NO_ERROR )
			fprintf( stderr, "testgl: OpenGL error: %d\n", gl_error );

		sdl_error = SDL_GetError( );

		if( sdl_error[0] != '\0' ) 
		{
		    fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error);
		    SDL_ClearError();
		}
		
		{
		}
		
		/* Check if there's a pending event. */
		while( SDL_PollEvent( &event ) )
		{
			switch( event.type )
			{
			case SDL_KEYDOWN:
				printf("%i\n",event.key.keysym.unicode);
				int key=event.key.keysym.sym;
				if ( key==SDLK_UP )
				{
					PyRun_SimpleString("pl_up()");
					active=1;
				}
				if ( key==(SDLK_DOWN) )
				{
					PyRun_SimpleString("pl_down()");
					active=1;
				}
				if ( key==(SDLK_PAGEUP) )
				{
					PyRun_SimpleString("pl_pgup()");
					active=1;
				}
				if ( key==(SDLK_PAGEDOWN) )
				{
					PyRun_SimpleString("pl_pgdown()");
					active=1;
				}
				else
				if ( (key == SDLK_SPACE) )
				    keyp(32);
				else
				if ( (key == SDLK_q) )
				    rot++;
				else
				if ( (key == SDLK_w) )
				    rot--;
				else
				if ( (key == SDLK_e) )
				    glLineWidth(3);
				else
				if ( (key == SDLK_r) )
				    glLineWidth(4);
				else
				if ( (key == SDLK_t) )
				    glLineWidth(5);
				else
				if ( (key == SDLK_y) )
				    glLineWidth(6);
				else
				if ( (key == SDLK_F1) )
					shrink=1;
				else
				if ( (key == SDLK_F2) )
					grow=1;
				else
				if ( (key == SDLK_END) )
				{
					PyRun_SimpleString("pl_end()");
					active=1;
				}
				else
				if ( (key == SDLK_HOME) )
				{
					PyRun_SimpleString("pl_home()");
					active=1;
				}
				else
				if ( (key == SDLK_q) )
				{
					PyRun_SimpleString("wanna_play()");
					wannaplay=1;
					active=2;
				}
				else
				if ( (key == SDLK_RETURN) )
				{
					keyp(10);					
					PyRun_SimpleString("wanna_play()");
					wannaplay=1;
					active=2;
				}
				else
				if ( (key == SDLK_c) )
					done=1;
				break;
	 		case SDL_QUIT:
				done = 1;
			break;
			}
		}
		if (wannaplay)
		{
		    FILE *f;
		    if (f=fopen("/tmp/sftkoko","r"))
			fclose(f);
		    else
		    {
			wannaplay=0;
			PyRun_SimpleString("pl_ay()");
		    }
		}
		if (shrink||grow)
		    resize(&w,&h,&bpp,&video_flags,&shrink,&grow);
	}
	SDL_Quit( );
	return(0);
}
Exemple #23
0
int
SDL_InitSubSystem(Uint32 flags)
{
    if (!SDL_MainIsReady) {
        SDL_SetError("Application didn't initialize properly, did you include SDL_main.h in the file containing your main() function?");
        return -1;
    }

    /* Clear the error message */
    SDL_ClearError();

    if ((flags & SDL_INIT_GAMECONTROLLER)) {
        /* game controller implies joystick */
        flags |= SDL_INIT_JOYSTICK;
    }

    if ((flags & (SDL_INIT_VIDEO|SDL_INIT_JOYSTICK))) {
        /* video or joystick implies events */
        flags |= SDL_INIT_EVENTS;
    }

#if SDL_VIDEO_DRIVER_WINDOWS
	if ((flags & (SDL_INIT_HAPTIC|SDL_INIT_JOYSTICK))) {
		if (SDL_HelperWindowCreate() < 0) {
			return -1;
		}
	}
#endif

#if !SDL_TIMERS_DISABLED
    SDL_TicksInit();
#endif

    /* Initialize the event subsystem */
    if ((flags & SDL_INIT_EVENTS)) {
#if !SDL_EVENTS_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_EVENTS)) {
            if (SDL_StartEventLoop() < 0) {
                return (-1);
            }
            SDL_QuitInit();
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_EVENTS);
#else
        return SDL_SetError("SDL not built with events support");
#endif
    }

    /* Initialize the timer subsystem */
    if ((flags & SDL_INIT_TIMER)){
#if !SDL_TIMERS_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_TIMER)) {
            if (SDL_TimerInit() < 0) {
                return (-1);
            }
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_TIMER);
#else
        return SDL_SetError("SDL not built with timer support");
#endif
    }

    /* Initialize the video subsystem */
    if ((flags & SDL_INIT_VIDEO)){
#if !SDL_VIDEO_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_VIDEO)) {
            if (SDL_VideoInit(NULL) < 0) {
                return (-1);
            }
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_VIDEO);
#else
        return SDL_SetError("SDL not built with video support");
#endif
    }

    /* Initialize the audio subsystem */
    if ((flags & SDL_INIT_AUDIO)){
#if !SDL_AUDIO_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_AUDIO)) {
            if (SDL_AudioInit(NULL) < 0) {
                return (-1);
            }
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_AUDIO);
#else
        return SDL_SetError("SDL not built with audio support");
#endif
    }

    /* Initialize the joystick subsystem */
    if ((flags & SDL_INIT_JOYSTICK)){
#if !SDL_JOYSTICK_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_JOYSTICK)) {
           if (SDL_JoystickInit() < 0) {
               return (-1);
           }
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_JOYSTICK);
#else
        return SDL_SetError("SDL not built with joystick support");
#endif
    }

    if ((flags & SDL_INIT_GAMECONTROLLER)){
#if !SDL_JOYSTICK_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_GAMECONTROLLER)) {
            if (SDL_GameControllerInit() < 0) {
                return (-1);
            }
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_GAMECONTROLLER);
#else
        return SDL_SetError("SDL not built with joystick support");
#endif
    }

    /* Initialize the haptic subsystem */
    if ((flags & SDL_INIT_HAPTIC)){
#if !SDL_HAPTIC_DISABLED
        if (SDL_PrivateShouldInitSubsystem(SDL_INIT_HAPTIC)) {
            if (SDL_HapticInit() < 0) {
                return (-1);
            }
        }
        SDL_PrivateSubsystemRefCountIncr(SDL_INIT_HAPTIC);
#else
        return SDL_SetError("SDL not built with haptic (force feedback) support");
#endif
    }

    return (0);
}
SDL_Surface *
SDL_LoadBMP_RW(SDL_RWops * src, int freesrc)
{
    SDL_bool was_error;
    long fp_offset;
    int bmpPitch;
    int i, pad;
    SDL_Surface *surface;
    Uint32 Rmask;
    Uint32 Gmask;
    Uint32 Bmask;
    Uint32 Amask;
    SDL_Palette *palette;
    Uint8 *bits;
    Uint8 *top, *end;
    SDL_bool topDown;
    int ExpandBMP;

    /* The Win32 BMP file header (14 bytes) */
    char magic[2];
    Uint32 bfSize;
    Uint16 bfReserved1;
    Uint16 bfReserved2;
    Uint32 bfOffBits;

    /* The Win32 BITMAPINFOHEADER struct (40 bytes) */
    Uint32 biSize;
    Sint32 biWidth;
    Sint32 biHeight;
    Uint16 biPlanes;
    Uint16 biBitCount;
    Uint32 biCompression;
    Uint32 biSizeImage;
    Sint32 biXPelsPerMeter;
    Sint32 biYPelsPerMeter;
    Uint32 biClrUsed;
    Uint32 biClrImportant;

    /* Make sure we are passed a valid data source */
    surface = NULL;
    was_error = SDL_FALSE;
    if (src == NULL) {
        was_error = SDL_TRUE;
        goto done;
    }

    /* Read in the BMP file header */
    fp_offset = SDL_RWtell(src);
    SDL_ClearError();
    if (SDL_RWread(src, magic, 1, 2) != 2) {
        SDL_Error(SDL_EFREAD);
        was_error = SDL_TRUE;
        goto done;
    }
    if (SDL_strncmp(magic, "BM", 2) != 0) {
        SDL_SetError("File is not a Windows BMP file");
        was_error = SDL_TRUE;
        goto done;
    }
    bfSize = SDL_ReadLE32(src);
    bfReserved1 = SDL_ReadLE16(src);
    bfReserved2 = SDL_ReadLE16(src);
    bfOffBits = SDL_ReadLE32(src);

    /* Read the Win32 BITMAPINFOHEADER */
    biSize = SDL_ReadLE32(src);
    if (biSize == 12) {
        biWidth = (Uint32) SDL_ReadLE16(src);
        biHeight = (Uint32) SDL_ReadLE16(src);
        biPlanes = SDL_ReadLE16(src);
        biBitCount = SDL_ReadLE16(src);
        biCompression = BI_RGB;
        biSizeImage = 0;
        biXPelsPerMeter = 0;
        biYPelsPerMeter = 0;
        biClrUsed = 0;
        biClrImportant = 0;
    } else {
        biWidth = SDL_ReadLE32(src);
        biHeight = SDL_ReadLE32(src);
        biPlanes = SDL_ReadLE16(src);
        biBitCount = SDL_ReadLE16(src);
        biCompression = SDL_ReadLE32(src);
        biSizeImage = SDL_ReadLE32(src);
        biXPelsPerMeter = SDL_ReadLE32(src);
        biYPelsPerMeter = SDL_ReadLE32(src);
        biClrUsed = SDL_ReadLE32(src);
        biClrImportant = SDL_ReadLE32(src);
    }
    if (biHeight < 0) {
        topDown = SDL_TRUE;
        biHeight = -biHeight;
    } else {
        topDown = SDL_FALSE;
    }

    /* Check for read error */
    if (SDL_strcmp(SDL_GetError(), "") != 0) {
        was_error = SDL_TRUE;
        goto done;
    }

    /* Expand 1 and 4 bit bitmaps to 8 bits per pixel */
    switch (biBitCount) {
    case 1:
    case 4:
        ExpandBMP = biBitCount;
        biBitCount = 8;
        break;
    default:
        ExpandBMP = 0;
        break;
    }

    /* We don't support any BMP compression right now */
    Rmask = Gmask = Bmask = Amask = 0;
    switch (biCompression) {
    case BI_RGB:
        /* If there are no masks, use the defaults */
        if (bfOffBits == (14 + biSize)) {
            /* Default values for the BMP format */
            switch (biBitCount) {
            case 15:
            case 16:
                Rmask = 0x7C00;
                Gmask = 0x03E0;
                Bmask = 0x001F;
                break;
            case 24:
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
                Rmask = 0x000000FF;
                Gmask = 0x0000FF00;
                Bmask = 0x00FF0000;
#else
                Rmask = 0x00FF0000;
                Gmask = 0x0000FF00;
                Bmask = 0x000000FF;
#endif
                break;
            case 32:
                Amask = 0xFF000000;
                Rmask = 0x00FF0000;
                Gmask = 0x0000FF00;
                Bmask = 0x000000FF;
                break;
            default:
                break;
            }
            break;
        }
        /* Fall through -- read the RGB masks */

    case BI_BITFIELDS:
        switch (biBitCount) {
        case 15:
        case 16:
            Rmask = SDL_ReadLE32(src);
            Gmask = SDL_ReadLE32(src);
            Bmask = SDL_ReadLE32(src);
            break;
        case 32:
            Rmask = SDL_ReadLE32(src);
            Gmask = SDL_ReadLE32(src);
            Bmask = SDL_ReadLE32(src);
            Amask = SDL_ReadLE32(src);
            break;
        default:
            break;
        }
        break;
    default:
        SDL_SetError("Compressed BMP files not supported");
        was_error = SDL_TRUE;
        goto done;
    }

    /* Create a compatible surface, note that the colors are RGB ordered */
    surface =
        SDL_CreateRGBSurface(0, biWidth, biHeight, biBitCount, Rmask, Gmask,
                             Bmask, Amask);
    if (surface == NULL) {
        was_error = SDL_TRUE;
        goto done;
    }

    /* Load the palette, if any */
    palette = (surface->format)->palette;
    if (palette) {
        if (biClrUsed == 0) {
            biClrUsed = 1 << biBitCount;
        }
        if ((int) biClrUsed > palette->ncolors) {
            palette->ncolors = biClrUsed;
            palette->colors =
                (SDL_Color *) SDL_realloc(palette->colors,
                                          palette->ncolors *
                                          sizeof(*palette->colors));
            if (!palette->colors) {
                SDL_OutOfMemory();
                was_error = SDL_TRUE;
                goto done;
            }
        } else if ((int) biClrUsed < palette->ncolors) {
            palette->ncolors = biClrUsed;
        }
        if (biSize == 12) {
            for (i = 0; i < (int) biClrUsed; ++i) {
                SDL_RWread(src, &palette->colors[i].b, 1, 1);
                SDL_RWread(src, &palette->colors[i].g, 1, 1);
                SDL_RWread(src, &palette->colors[i].r, 1, 1);
                palette->colors[i].unused = SDL_ALPHA_OPAQUE;
            }
        } else {
            for (i = 0; i < (int) biClrUsed; ++i) {
                SDL_RWread(src, &palette->colors[i].b, 1, 1);
                SDL_RWread(src, &palette->colors[i].g, 1, 1);
                SDL_RWread(src, &palette->colors[i].r, 1, 1);
                SDL_RWread(src, &palette->colors[i].unused, 1, 1);
            }
        }
    }

    /* Read the surface pixels.  Note that the bmp image is upside down */
    if (SDL_RWseek(src, fp_offset + bfOffBits, RW_SEEK_SET) < 0) {
        SDL_Error(SDL_EFSEEK);
        was_error = SDL_TRUE;
        goto done;
    }
    top = (Uint8 *)surface->pixels;
    end = (Uint8 *)surface->pixels+(surface->h*surface->pitch);
    switch (ExpandBMP) {
    case 1:
        bmpPitch = (biWidth + 7) >> 3;
        pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0);
        break;
    case 4:
        bmpPitch = (biWidth + 1) >> 1;
        pad = (((bmpPitch) % 4) ? (4 - ((bmpPitch) % 4)) : 0);
        break;
    default:
        pad = ((surface->pitch % 4) ? (4 - (surface->pitch % 4)) : 0);
        break;
    }
    if (topDown) {
        bits = top;
    } else {
        bits = end - surface->pitch;
    }
    while (bits >= top && bits < end) {
        switch (ExpandBMP) {
        case 1:
        case 4:{
                Uint8 pixel = 0;
                int shift = (8 - ExpandBMP);
                for (i = 0; i < surface->w; ++i) {
                    if (i % (8 / ExpandBMP) == 0) {
                        if (!SDL_RWread(src, &pixel, 1, 1)) {
                            SDL_SetError("Error reading from BMP");
                            was_error = SDL_TRUE;
                            goto done;
                        }
                    }
                    *(bits + i) = (pixel >> shift);
                    pixel <<= ExpandBMP;
                }
            }
            break;

        default:
            if (SDL_RWread(src, bits, 1, surface->pitch)
                != surface->pitch) {
                SDL_Error(SDL_EFREAD);
                was_error = SDL_TRUE;
                goto done;
            }
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
            /* Byte-swap the pixels if needed. Note that the 24bpp
               case has already been taken care of above. */
            switch (biBitCount) {
            case 15:
            case 16:{
                    Uint16 *pix = (Uint16 *) bits;
                    for (i = 0; i < surface->w; i++)
                        pix[i] = SDL_Swap16(pix[i]);
                    break;
                }

            case 32:{
                    Uint32 *pix = (Uint32 *) bits;
                    for (i = 0; i < surface->w; i++)
                        pix[i] = SDL_Swap32(pix[i]);
                    break;
                }
            }
#endif
            break;
        }
        /* Skip padding bytes, ugh */
        if (pad) {
            Uint8 padbyte;
            for (i = 0; i < pad; ++i) {
                SDL_RWread(src, &padbyte, 1, 1);
            }
        }
        if (topDown) {
            bits += surface->pitch;
        } else {
            bits -= surface->pitch;
        }
    }
  done:
    if (was_error) {
        if (src) {
            SDL_RWseek(src, fp_offset, RW_SEEK_SET);
        }
        if (surface) {
            SDL_FreeSurface(surface);
        }
        surface = NULL;
    }
    if (freesrc && src) {
        SDL_RWclose(src);
    }
    return (surface);
}
int
SDL_SaveBMP_RW(SDL_Surface * saveme, SDL_RWops * dst, int freedst)
{
    long fp_offset;
    int i, pad;
    SDL_Surface *surface;
    Uint8 *bits;

    /* The Win32 BMP file header (14 bytes) */
    char magic[2] = { 'B', 'M' };
    Uint32 bfSize;
    Uint16 bfReserved1;
    Uint16 bfReserved2;
    Uint32 bfOffBits;

    /* The Win32 BITMAPINFOHEADER struct (40 bytes) */
    Uint32 biSize;
    Sint32 biWidth;
    Sint32 biHeight;
    Uint16 biPlanes;
    Uint16 biBitCount;
    Uint32 biCompression;
    Uint32 biSizeImage;
    Sint32 biXPelsPerMeter;
    Sint32 biYPelsPerMeter;
    Uint32 biClrUsed;
    Uint32 biClrImportant;

    /* Make sure we have somewhere to save */
    surface = NULL;
    if (dst) {
        SDL_bool save32bit = SDL_FALSE;
#ifdef SAVE_32BIT_BMP
        /* We can save alpha information in a 32-bit BMP */
        if (saveme->map->info.flags & SDL_COPY_COLORKEY ||
            saveme->format->Amask) {
            save32bit = SDL_TRUE;
        }
#endif /* SAVE_32BIT_BMP */

        if (saveme->format->palette && !save32bit) {
            if (saveme->format->BitsPerPixel == 8) {
                surface = saveme;
            } else {
                SDL_SetError("%d bpp BMP files not supported",
                             saveme->format->BitsPerPixel);
            }
        } else if ((saveme->format->BitsPerPixel == 24) &&
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                   (saveme->format->Rmask == 0x00FF0000) &&
                   (saveme->format->Gmask == 0x0000FF00) &&
                   (saveme->format->Bmask == 0x000000FF)
#else
                   (saveme->format->Rmask == 0x000000FF) &&
                   (saveme->format->Gmask == 0x0000FF00) &&
                   (saveme->format->Bmask == 0x00FF0000)
#endif
            ) {
            surface = saveme;
        } else {
            SDL_PixelFormat format;

            /* If the surface has a colorkey or alpha channel we'll save a
               32-bit BMP with alpha channel, otherwise save a 24-bit BMP. */
            if (save32bit) {
                SDL_InitFormat(&format, 
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                               SDL_PIXELFORMAT_ARGB8888
#else
                               SDL_PIXELFORMAT_BGRA8888
#endif
                               );
            } else {
                SDL_InitFormat(&format, SDL_PIXELFORMAT_BGR24);
            }
            surface = SDL_ConvertSurface(saveme, &format, 0);
            if (!surface) {
                SDL_SetError("Couldn't convert image to %d bpp",
                             format.BitsPerPixel);
            }
        }
    }

    if (surface && (SDL_LockSurface(surface) == 0)) {
        const int bw = surface->w * surface->format->BytesPerPixel;

        /* Set the BMP file header values */
        bfSize = 0;             /* We'll write this when we're done */
        bfReserved1 = 0;
        bfReserved2 = 0;
        bfOffBits = 0;          /* We'll write this when we're done */

        /* Write the BMP file header values */
        fp_offset = SDL_RWtell(dst);
        SDL_ClearError();
        SDL_RWwrite(dst, magic, 2, 1);
        SDL_WriteLE32(dst, bfSize);
        SDL_WriteLE16(dst, bfReserved1);
        SDL_WriteLE16(dst, bfReserved2);
        SDL_WriteLE32(dst, bfOffBits);

        /* Set the BMP info values */
        biSize = 40;
        biWidth = surface->w;
        biHeight = surface->h;
        biPlanes = 1;
        biBitCount = surface->format->BitsPerPixel;
        biCompression = BI_RGB;
        biSizeImage = surface->h * surface->pitch;
        biXPelsPerMeter = 0;
        biYPelsPerMeter = 0;
        if (surface->format->palette) {
            biClrUsed = surface->format->palette->ncolors;
        } else {
            biClrUsed = 0;
        }
        biClrImportant = 0;

        /* Write the BMP info values */
        SDL_WriteLE32(dst, biSize);
        SDL_WriteLE32(dst, biWidth);
        SDL_WriteLE32(dst, biHeight);
        SDL_WriteLE16(dst, biPlanes);
        SDL_WriteLE16(dst, biBitCount);
        SDL_WriteLE32(dst, biCompression);
        SDL_WriteLE32(dst, biSizeImage);
        SDL_WriteLE32(dst, biXPelsPerMeter);
        SDL_WriteLE32(dst, biYPelsPerMeter);
        SDL_WriteLE32(dst, biClrUsed);
        SDL_WriteLE32(dst, biClrImportant);

        /* Write the palette (in BGR color order) */
        if (surface->format->palette) {
            SDL_Color *colors;
            int ncolors;

            colors = surface->format->palette->colors;
            ncolors = surface->format->palette->ncolors;
            for (i = 0; i < ncolors; ++i) {
                SDL_RWwrite(dst, &colors[i].b, 1, 1);
                SDL_RWwrite(dst, &colors[i].g, 1, 1);
                SDL_RWwrite(dst, &colors[i].r, 1, 1);
                SDL_RWwrite(dst, &colors[i].unused, 1, 1);
            }
        }

        /* Write the bitmap offset */
        bfOffBits = SDL_RWtell(dst) - fp_offset;
        if (SDL_RWseek(dst, fp_offset + 10, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }
        SDL_WriteLE32(dst, bfOffBits);
        if (SDL_RWseek(dst, fp_offset + bfOffBits, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }

        /* Write the bitmap image upside down */
        bits = (Uint8 *) surface->pixels + (surface->h * surface->pitch);
        pad = ((bw % 4) ? (4 - (bw % 4)) : 0);
        while (bits > (Uint8 *) surface->pixels) {
            bits -= surface->pitch;
            if (SDL_RWwrite(dst, bits, 1, bw) != bw) {
                SDL_Error(SDL_EFWRITE);
                break;
            }
            if (pad) {
                const Uint8 padbyte = 0;
                for (i = 0; i < pad; ++i) {
                    SDL_RWwrite(dst, &padbyte, 1, 1);
                }
            }
        }

        /* Write the BMP file size */
        bfSize = SDL_RWtell(dst) - fp_offset;
        if (SDL_RWseek(dst, fp_offset + 2, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }
        SDL_WriteLE32(dst, bfSize);
        if (SDL_RWseek(dst, fp_offset + bfSize, RW_SEEK_SET) < 0) {
            SDL_Error(SDL_EFSEEK);
        }

        /* Close it up.. */
        SDL_UnlockSurface(surface);
        if (surface != saveme) {
            SDL_FreeSurface(surface);
        }
    }

    if (freedst && dst) {
        SDL_RWclose(dst);
    }
    return ((SDL_strcmp(SDL_GetError(), "") == 0) ? 0 : -1);
}
Exemple #26
0
/**
 * @brief The entry point of this force feedback demo.
 * @param[in] argc Number of arguments.
 * @param[in] argv Array of argc arguments.
 */
int
main(int argc, char **argv)
{
    int i;
    char *name;
    int index;
    SDL_HapticEffect efx[5];
    int id[5];
    int nefx;
    unsigned int supported;

    name = NULL;
    index = -1;
    if (argc > 1) {
        name = argv[1];
        if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) {
            printf("USAGE: %s [device]\n"
                   "If device is a two-digit number it'll use it as an index, otherwise\n"
                   "it'll use it as if it were part of the device's name.\n",
                   argv[0]);
            return 0;
        }

        i = strlen(name);
        if ((i < 3) && isdigit(name[0]) && ((i == 1) || isdigit(name[1]))) {
            index = atoi(name);
            name = NULL;
        }
    }

    /* Initialize the force feedbackness */
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK |
             SDL_INIT_HAPTIC);
    printf("%d Haptic devices detected.\n", SDL_NumHaptics());
    if (SDL_NumHaptics() > 0) {
        /* We'll just use index or the first force feedback device found */
        if (name == NULL) {
            i = (index != -1) ? index : 0;
        }
        /* Try to find matching device */
        else {
            for (i = 0; i < SDL_NumHaptics(); i++) {
                if (strstr(SDL_HapticName(i), name) != NULL)
                    break;
            }

            if (i >= SDL_NumHaptics()) {
                printf("Unable to find device matching '%s', aborting.\n",
                       name);
                return 1;
            }
        }

        haptic = SDL_HapticOpen(i);
        if (haptic == NULL) {
            printf("Unable to create the haptic device: %s\n",
                   SDL_GetError());
            return 1;
        }
        printf("Device: %s\n", SDL_HapticName(i));
        HapticPrintSupported(haptic);
    } else {
        printf("No Haptic devices found!\n");
        return 1;
    }

    /* We only want force feedback errors. */
    SDL_ClearError();

    /* Create effects. */
    memset(&efx, 0, sizeof(efx));
    nefx = 0;
    supported = SDL_HapticQuery(haptic);

    printf("\nUploading effects\n");
    /* First we'll try a SINE effect. */
    if (supported & SDL_HAPTIC_SINE) {
        printf("   effect %d: Sine Wave\n", nefx);
        efx[nefx].type = SDL_HAPTIC_SINE;
        efx[nefx].periodic.period = 1000;
        efx[nefx].periodic.magnitude = 0x4000;
        efx[nefx].periodic.length = 5000;
        efx[nefx].periodic.attack_length = 1000;
        efx[nefx].periodic.fade_length = 1000;
        id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
        if (id[nefx] < 0) {
            printf("UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
            abort_execution();
        }
        nefx++;
    }
    /* Now we'll try a SAWTOOTHUP */
    if (supported & SDL_HAPTIC_SAWTOOTHUP) {
        printf("   effect %d: Sawtooth Up\n", nefx);
        efx[nefx].type = SDL_HAPTIC_SQUARE;
        efx[nefx].periodic.period = 500;
        efx[nefx].periodic.magnitude = 0x5000;
        efx[nefx].periodic.length = 5000;
        efx[nefx].periodic.attack_length = 1000;
        efx[nefx].periodic.fade_length = 1000;
        id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
        if (id[nefx] < 0) {
            printf("UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
            abort_execution();
        }
        nefx++;
    }
    /* Now the classical constant effect. */
    if (supported & SDL_HAPTIC_CONSTANT) {
        printf("   effect %d: Constant Force\n", nefx);
        efx[nefx].type = SDL_HAPTIC_CONSTANT;
        efx[nefx].constant.direction.type = SDL_HAPTIC_POLAR;
        efx[nefx].constant.direction.dir[0] = 20000;    /* Force comes from the south-west. */
        efx[nefx].constant.length = 5000;
        efx[nefx].constant.level = 0x6000;
        efx[nefx].constant.attack_length = 1000;
        efx[nefx].constant.fade_length = 1000;
        id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
        if (id[nefx] < 0) {
            printf("UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
            abort_execution();
        }
        nefx++;
    }
    /* The cute spring effect. */
    if (supported & SDL_HAPTIC_SPRING) {
        printf("   effect %d: Condition Spring\n", nefx);
        efx[nefx].type = SDL_HAPTIC_SPRING;
        efx[nefx].condition.length = 5000;
        for (i = 0; i < SDL_HapticNumAxes(haptic); i++) {
            efx[nefx].condition.right_sat[i] = 0x7FFF;
            efx[nefx].condition.left_sat[i] = 0x7FFF;
            efx[nefx].condition.right_coeff[i] = 0x2000;
            efx[nefx].condition.left_coeff[i] = 0x2000;
            efx[nefx].condition.center[i] = 0x1000;     /* Displace the center for it to move. */
        }
        id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
        if (id[nefx] < 0) {
            printf("UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
            abort_execution();
        }
        nefx++;
    }
    /* The pretty awesome inertia effect. */
    if (supported & SDL_HAPTIC_INERTIA) {
        printf("   effect %d: Condition Inertia\n", nefx);
        efx[nefx].type = SDL_HAPTIC_SPRING;
        efx[nefx].condition.length = 5000;
        for (i = 0; i < SDL_HapticNumAxes(haptic); i++) {
            efx[nefx].condition.right_sat[i] = 0x7FFF;
            efx[nefx].condition.left_sat[i] = 0x7FFF;
            efx[nefx].condition.right_coeff[i] = 0x2000;
            efx[nefx].condition.left_coeff[i] = 0x2000;
        }
        id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
        if (id[nefx] < 0) {
            printf("UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
            abort_execution();
        }
        nefx++;
    }

    printf
        ("\nNow playing effects for 5 seconds each with 1 second delay between\n");
    for (i = 0; i < nefx; i++) {
        printf("   Playing effect %d\n", i);
        SDL_HapticRunEffect(haptic, id[i], 1);
        SDL_Delay(6000);        /* Effects only have length 5000 */
    }

    /* Quit */
    if (haptic != NULL)
        SDL_HapticClose(haptic);
    SDL_Quit();

    return 0;
}
Exemple #27
0
int main(int argc, char *argv[])
{

  app.SetEmergencyQuit(true);
  app.LoadTheme("default");
	int i;
	int rgb_size[3];
	int w = 640;
	int h = 480;
  int bpp=16;

	Uint32 video_flags;
	int value;

	if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
		fprintf(stderr,"Couldn't initialize SDL: %s\n",SDL_GetError());
		exit( 1 );
  }


	/* Set the flags we want to use for setting the video mode */
	video_flags = SDL_OPENGLBLIT;

	for ( i=1; argv[i]; ++i ) {
		if ( strcmp(argv[i], "-fullscreen") == 0 ) {
			video_flags |= SDL_FULLSCREEN;
		}
	}

	/* 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] = 6;
		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 );



  if (!app.InitScreen(640, 480, 0, video_flags)) {
      fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
     exit(1);
  }
	app.EnableBackground();
 	SDL_WM_SetCaption( "MadIVS", "madivs" );




  GLWidget gl_view1(NULL, PG_Rect(100,100,200,200));
	new PG_Label(&gl_view1, PG_Rect(0,0,90,20), "GL View 1");


    // now we have to make the button visible

  gl_view1.Show();

	PG_Button* btn1 = new PG_Button(NULL, 1, PG_Rect(30,30,100,50), "Quit");
	btn1->Show();


	PG_Rect rs(0,0, PG_Application::GetScreenWidth(), PG_Application::GetScreenHeight());
  PG_Widget::UpdateRect(rs);
  SDL_UpdateRects(SDL_GetVideoSurface(), 1, &rs);
	
  int done=0;	
	while( !done ) {
		GLenum gl_error;
		char* pg_error;
		SDL_Event event;


		gl_view1.Update();

		glRotatef(1, 1.0, 1.0, 1.0);

		SDL_GL_SwapBuffers( );

		/* Check for error conditions. */
		gl_error = glGetError( );

		if( gl_error != GL_NO_ERROR ) {
			fprintf( stderr, "testgl: OpenGL error: %d\n", gl_error );
		}

		pg_error = SDL_GetError( );

		if( pg_error[0] != '\0' ) {
			fprintf(stderr, "testgl: SDL error '%s'\n", pg_error);
			SDL_ClearError();
		}


		/* Check if there's a pending event. */
/*		if ( SDL_PollEvent( &event ) ) {
			HandleEvent(&event, &app);
		}*/
		

	}


	return(0);
}
Exemple #28
0
int
SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_display)
{
    void *dll_handle = NULL, *egl_dll_handle = NULL; /* The naming is counter intuitive, but hey, I just work here -- Gabriel */
    char *path = NULL;
#if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
    const char *d3dcompiler;
#endif

    if (_this->egl_data) {
        return SDL_SetError("OpenGL ES context already created");
    }

    _this->egl_data = (struct SDL_EGL_VideoData *) SDL_calloc(1, sizeof(SDL_EGL_VideoData));
    if (!_this->egl_data) {
        return SDL_OutOfMemory();
    }

#if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
    d3dcompiler = SDL_GetHint(SDL_HINT_VIDEO_WIN_D3DCOMPILER);
    if (!d3dcompiler) {
        if (WIN_IsWindowsVistaOrGreater()) {
            //WPB Changed to from d3dcompiler_46.dll to d3dcompiler_47.dll
            d3dcompiler = "d3dcompiler_47.dll";
        } else {
            d3dcompiler = "d3dcompiler_43.dll";
        }
    }
    if (SDL_strcasecmp(d3dcompiler, "none") != 0) {
        SDL_LoadObject(d3dcompiler);
    }
#endif

    /* A funny thing, loading EGL.so first does not work on the Raspberry, so we load libGL* first */
    path = SDL_getenv("SDL_VIDEO_GL_DRIVER");
    if (path != NULL) {
        egl_dll_handle = SDL_LoadObject(path);
    }

    if (egl_dll_handle == NULL) {
        if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) {
            if (_this->gl_config.major_version > 1) {
                path = DEFAULT_OGL_ES2;
                egl_dll_handle = SDL_LoadObject(path);
            } else {
                path = DEFAULT_OGL_ES;
                egl_dll_handle = SDL_LoadObject(path);
                if (egl_dll_handle == NULL) {
                    path = DEFAULT_OGL_ES_PVR;
                    egl_dll_handle = SDL_LoadObject(path);
                }
            }
        }
#ifdef DEFAULT_OGL
        else {
            path = DEFAULT_OGL;
            egl_dll_handle = SDL_LoadObject(path);
        }
#endif
    }
    _this->egl_data->egl_dll_handle = egl_dll_handle;

    if (egl_dll_handle == NULL) {
        return SDL_SetError("Could not initialize OpenGL / GLES library");
    }

    /* Loading libGL* in the previous step took care of loading libEGL.so, but we future proof by double checking */
    if (egl_path != NULL) {
        dll_handle = SDL_LoadObject(egl_path);
    }
    /* Try loading a EGL symbol, if it does not work try the default library paths */
    if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) {
        if (dll_handle != NULL) {
            SDL_UnloadObject(dll_handle);
        }
        path = SDL_getenv("SDL_VIDEO_EGL_DRIVER");
        if (path == NULL) {
            path = DEFAULT_EGL;
        }
        dll_handle = SDL_LoadObject(path);
        if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) {
            if (dll_handle != NULL) {
                SDL_UnloadObject(dll_handle);
            }
            return SDL_SetError("Could not load EGL library");
        }
        SDL_ClearError();
    }

    _this->egl_data->dll_handle = dll_handle;

    /* Load new function pointers */
    LOAD_FUNC(eglGetDisplay);
    LOAD_FUNC(eglInitialize);
    LOAD_FUNC(eglTerminate);
    LOAD_FUNC(eglGetProcAddress);
    LOAD_FUNC(eglChooseConfig);
    LOAD_FUNC(eglGetConfigAttrib);
    LOAD_FUNC(eglCreateContext);
    LOAD_FUNC(eglDestroyContext);
    LOAD_FUNC(eglCreateWindowSurface);
    LOAD_FUNC(eglDestroySurface);
    LOAD_FUNC(eglMakeCurrent);
    LOAD_FUNC(eglSwapBuffers);
    LOAD_FUNC(eglSwapInterval);
    LOAD_FUNC(eglWaitNative);
    LOAD_FUNC(eglWaitGL);
    LOAD_FUNC(eglBindAPI);
    LOAD_FUNC(eglQueryString);

#if !defined(__WINRT__)
    _this->egl_data->egl_display = _this->egl_data->eglGetDisplay(native_display);
    if (!_this->egl_data->egl_display) {
        return SDL_SetError("Could not get EGL display");
    }

    if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
        return SDL_SetError("Could not initialize EGL");
    }
#endif

    _this->gl_config.driver_loaded = 1;

    if (path) {
        SDL_strlcpy(_this->gl_config.driver_path, path, sizeof(_this->gl_config.driver_path) - 1);
    } else {
        *_this->gl_config.driver_path = '\0';
    }

    return 0;
}
Exemple #29
0
int RunGLTest (void)
{

#ifdef GL
	int mm=1;
#else
	int mm = 0;
#endif
	int mode=0;
	cam.x=0;
	cam.y=0;
	int bpp;
	int w = 200;
	int h = 200;
	int done = 0;
	int shrink=0;
	int grow=0;
	int gofullscreen=0;
	int mustresize = 1;
	int justresized = 0;
	xy  ss = parsemodes(w,h,"mode",1,0,0);
	printf("wtf\n");
	if (ss.x!=-1){w=ss.x;h=ss.y;};
	SDL_Surface* s;
#ifdef GL
	s=initsdl(w,h,&bpp,SDL_OPENGL

#else
	gltextsdlsurface=s=initsdl(w,h,&bpp,
#endif

	+0);printf("inito\n");
	SDL_InitSubSystem( SDL_INIT_TIMER);
	SDL_EnableUNICODE(1);
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY/2, SDL_DEFAULT_REPEAT_INTERVAL*2);
#ifdef GL
	newtermmsg=GetFileIntoCharPointer1("newtermmsg");
	printf("pretty far\n");
	wm(w,h);
	int down=0;
	glEnable(GL_BLEND);
	glShadeModel(GL_FLAT);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	glClearColor( 0.0, 0.0, 0.04, 0.0 );
	glLineWidth(lv);
#else
	gltextsdlsurface=s;
#endif
	roteface *face1;
	roteface *activeface;
	face1=add_face();
	activeface =face1 ;
	face1->next=add_face();
	printf("still?\n");
	add_terminal(face1);
	printf("2threaad\n");
	loadl2();
	struct state *nerv=0;
#ifdef nerve
	nerv=nerverot_init(w,h);
#endif

	int dirty=1;
	printf("mainloop descent commencing\n");
	while( !done )
	{	
	        lockterms(face1);


		if(dirty||faces_dirty(face1))
		{
			dirty=0;
			facesclean(face1);
#ifdef GL
			glClear(GL_COLOR_BUFFER_BIT);
#else
			SDL_FillRect	( s, NULL, 0 );

#endif

#ifndef GL

#else

				if(nerv)
				{
				    shownerv(nerv);
				    dirty=1;
				}
				glPushMatrix();
				glScalef(sx,sy,0.004);
				glTranslatef(cam.x,cam.y,0);
				

#endif
				Uint8 * k;
				int integer;

				k=SDL_GetKeyState(&integer);
				if(k[SDLK_RCTRL])
					focusline(activeface);
				int nf;
				switch(mode)
				{
				    case 0:
					showfaces(face1);
				    break;
#ifdef GL
				    case 1:
					krychlus(face1);
				    break;
#endif
				}
#ifdef GL
				glPopMatrix();
#endif


#ifndef GL
			SDL_UpdateRect(s,0,0,0,0);
#else
			SDL_GL_SwapBuffers( );
#endif
			facesclean(face1);
			
		}
#ifdef GL
		GLenum gl_error;
		gl_error = glGetError( );
		if( gl_error != GL_NO_ERROR )
		{
			if(gl_error==GL_STACK_OVERFLOW)
				printf("QUACK QUACK QUACK, OVERFLOVING STACK\n");
			else if(gl_error==GL_INVALID_OPERATION)
				printf("INVALID OPERATION, PATIENT EXPLODED\n");
			else	fprintf( stderr, "testgl: OpenGL error: %d\n", gl_error );
			
		}
#endif
		char* sdl_error;
		sdl_error = SDL_GetError( );
		if( sdl_error[0] != '\0' )
		{
		    fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error);
		    SDL_ClearError();
		}

		SDL_TimerID x=0;
		if(dirty)
		    x= SDL_AddTimer(55, NewTimerCallback, 0);
		                     
		unlockterms(face1);
//		printf("---------unlocked wating\n");
		SDL_Event event;
		if(SDL_WaitEvent( &event ))
		{
	    	    lockterms(face1);
//		    printf("---------locked goooin %i\n", event.type);
		    if(x)SDL_RemoveTimer(x);x=0;	    	    
		    do {
			int mod=event.key.keysym.mod;
			int key=event.key.keysym.sym;
    			Uint8 *keystate = SDL_GetKeyState(NULL);

			switch( event.type )
			{
			
#ifdef GL
				case SDL_MOUSEMOTION:
				if((SDL_BUTTON(1)|SDL_BUTTON(2))&SDL_GetMouseState(0,0))
				{
					activeface->x+=event.motion.xrel;
					activeface->y+=event.motion.yrel;
				}
				if((SDL_BUTTON(3)|SDL_BUTTON(2))&SDL_GetMouseState(0,0))
				{
					cam.x-=event.motion.xrel;
					cam.y-=event.motion.yrel;
				}
				
				break;
#endif
				case SDL_KEYUP:
				{
					if ( (key == SDLK_RCTRL) )
					{
						dirty=1;
					}
				}
				break;
				case SDL_KEYDOWN:
				

					if(mod&KMOD_RSHIFT&&(key==SDLK_PAGEUP||key==SDLK_PAGEDOWN))
					{
						if(key==SDLK_PAGEUP)
							tscroll+=9;
						if(key==SDLK_PAGEDOWN)
							tscroll-=9;
						if(tscroll<0)tscroll=0;
//						printf("scroll:%i,logl:%i, log&%i, t:%i ,b:%i\n", tscroll,activeface->t->logl, activeface->t->log,activeface->t->scrolltop,activeface->t->scrollbottom);
					}
					else
					if(key==SDLK_RCTRL||mod&KMOD_RCTRL)
					{
						dirty=1;
						switch (key)
						{
							case SDLK_TAB:
							    cycle(face1, &activeface);
							break;
							case SDLK_F2:
							    gofullscreen=1;
							break;
							case SDLK_F3:
							    rastio+=0.05;
							    mustresize=1;
							    dirty=1;
							break;
							case SDLK_F4:
							    rastio-=0.05;
							    mustresize=1;
							    dirty=1;
							break;
							case SDLK_F5:
							    sx-=0.001;
							    sy+=0.001;
							break;
							case SDLK_F6:
							    sx+=0.001;
							    sy-=0.001;
							break;

							case SDLK_F7:
							    savemode(w,h);
							break;
							case SDLK_F8:
							    loadl2();
							break;
							case SDLK_p:
							    saveScreenshot();
							break;
#ifdef GL
							case SDLK_F9:
							    lv-=1;	glLineWidth(lv);
							break;
							case SDLK_F10:
							    lv+=1;	glLineWidth(lv);
							break;
#endif
							case SDLK_F11:
							    shrink=1;
							break;
							case SDLK_F12:
							    grow=1;
							break;
							case SDLK_PAGEUP:
							     mode++;
							     if(mode>mm)mode= mm;
							break;
							case SDLK_INSERT:
							     mode--;
							     if(mode<0)mode= 0;
							break;
							case SDLK_END:
							    resizooo(activeface, 0,1,keystate);
							break;
							case SDLK_HOME:
							    resizooo(activeface, 0,-1,keystate);
							break;
							case SDLK_DELETE:
							    resizooo(activeface, -1,0,keystate);
							break;
							case SDLK_PAGEDOWN:
							    resizooo(activeface, 1,0,keystate);
							break;
#ifdef nerve
							case SDLK_F1:
								if(nerv)
								{
									nerverot_free(nerv);
							        	dirty=1;
									nerv=0;
								}
								else
								{
							        	nerv=nerverot_init(w,h);
									
									dirty=1;
								}
							break;
#endif
						}
					}
					else
					{
					    if(activeface->t==0)
					    {
						printf("debug messages r fun\n");
						add_terminal(activeface);
						activeface->next=add_face();
					    }
					    if ( (key >= SDLK_F1) && (key <= SDLK_F15) )
					    {
						char *k;
						if(asprintf(&k ,"kf%i", key-SDLK_F1+1)!=-1)
						{
						    rote_vt_terminfo(activeface->t, k);
						    free(k);
						}
					    }
					    else
					    if ( (key == SDLK_SPACE) )
						keyp(activeface,32);
					    else
					    #define magic(x) rote_vt_terminfo(activeface->t, x )
					    if ( (key == SDLK_BACKSPACE) )
						magic( "kbs");
					    else
					    if ( (key == SDLK_ESCAPE) )
						keyp(activeface,27);
					    else
					    if ( (key == SDLK_LEFT) )
						magic("kcub1");
					    else
					    if ( (key == SDLK_RIGHT) )
						magic( "kcuf1");
					    else
					    if ( (key == SDLK_UP) )
						magic( "kcuu1");
					    else
					    if ( (key == SDLK_DOWN) )
						magic( "kcud1");
					    else
					    if ( (key == SDLK_END) )
						magic( "kend");
					    else
					    if ( (key == SDLK_HOME) )
						magic("khome");
					    else
					    if ( (key == SDLK_DELETE) )
						magic( "kdch1");
					    else
					    if ( (key == SDLK_PAGEDOWN) )
						magic( "knp");
					    else
					    if ( (key == SDLK_INSERT) )
					    	magic( "kich1");
					    else
					    if ( (key == SDLK_PAGEUP) )
						magic ( "kpp" );
					    else
					    if ( (key == SDLK_RETURN) )
						keyp(activeface,10);
					    else
					    if( event.key.keysym.unicode && ( (event.key.keysym.unicode & 0xFF80) == 0 ) )
						keyp(activeface, event.key.keysym.unicode);
					}
				break;
	 			case SDL_QUIT:
					done = 1;
					break;
#ifndef GL
	 			case SDL_MOUSEBUTTONDOWN:
					rote_vt_mousedown(activeface->t,event.button.x/13, event.button.y/26);
					break;
	 			case SDL_MOUSEBUTTONUP:
					rote_vt_mouseup  (activeface->t,event.button.x/13, event.button.y/26);
					break;
	 			case SDL_MOUSEMOTION:
					rote_vt_mousemove(activeface->t,event.button.x/13, event.button.y/26);
					break;
#endif
				case SDL_VIDEORESIZE:
				    {
					w=event.resize.w;h=event.resize.h;
//					printf("videoresize %i %i\n", w,h);
					dirty=1;
					if (s=SDL_SetVideoMode( w,h, bpp, s->flags ) ) 
//						printf("hmm\n");
					wm(w,h);
				    if(!justresized)

					mustresize=1;
				        justresized=0;
				        
				    }

					break;
				case SDL_USEREVENT:
					if(event.user.code==1)
					    RemoveTerm(&activeface,&face1, event.user.data1);
					break;
			}
		    }
		    while (SDL_PollEvent(&event));
		    if (shrink||grow)
		    { 
		        resize(&w,&h,&bpp,&s->flags,&shrink,&grow);
		        wm(w,h);
		    }
		    if (mustresize)
		    {
			mustresize=0;
			justresized=1;
//			if(activeface->t->cols!=event.resize.w/13/rastio||
//			    activeface->t->rows!=event.resize.h/26/rastio)
				//rote_vt_resize(activeface->t,event.resize.h/26/rastio ,event.resize.w/13/rastio);
		    }
		    if(gofullscreen)
			if(s->flags & SDL_FULLSCREEN )
			{
    			    s=SDL_SetVideoMode( w,h, bpp, (s->flags & ~SDL_FULLSCREEN ));
			
			}
			else
    			    s=SDL_SetVideoMode( w,h, bpp, (s->flags | SDL_FULLSCREEN ));
		    gofullscreen=0;
		    unlockterms(face1);
		}

	}
	SDL_Quit( );
	return(0);
}
Exemple #30
0
void Initialize(bool* Continue, bool* Error)
{
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0)
	{
		*Continue = false;  *Error = true;
		printf("SDL initialisation failed: %s\n", SDL_GetError());
		SDL_ClearError();
		return;
	}
	else
		printf("SDL initialisation succeeded\n");

	Screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_HWSURFACE |
#ifdef SDL_TRIPLEBUF
		SDL_TRIPLEBUF
#else
		SDL_DOUBLEBUF
#endif
		);

	if (Screen == NULL)
	{
		*Continue = false;  *Error = true;
		printf("SDL_SetVideoMode failed: %s\n", SDL_GetError());
		SDL_ClearError();
		return;
	}
	else
		printf("SDL_SetVideoMode succeeded\n");

	SDL_ShowCursor(0);

	uint32_t i;
	for (i = 0; i < BG_LAYER_COUNT; i++)
	{
		BackgroundImages[i] = IMG_Load(BackgroundImageNames[i]);
		if (!CheckImage(Continue, Error, BackgroundImages[i], BackgroundImageNames[i]))
			return;
		if ((BackgroundImages[i] = ConvertSurface(Continue, Error, BackgroundImages[i], BackgroundImageNames[i])) == NULL)
			return;
	}
	CharacterFrames = IMG_Load("Bee.png");
	if (!CheckImage(Continue, Error, CharacterFrames, "Bee.png"))
		return;
	if ((CharacterFrames = ConvertSurface(Continue, Error, CharacterFrames, "Bee.png")) == NULL)
		return;
	CollisionImage = IMG_Load("Crash.png");
	if (!CheckImage(Continue, Error, CollisionImage, "Crash.png"))
		return;
	if ((CollisionImage = ConvertSurface(Continue, Error, CollisionImage, "Crash.png")) == NULL)
		return;
	ColumnImage = IMG_Load("Bamboo.png");
	if (!CheckImage(Continue, Error, ColumnImage, "Bamboo.png"))
		return;
	if ((ColumnImage = ConvertSurface(Continue, Error, ColumnImage, "Bamboo.png")) == NULL)
		return;

	InitializePlatform();

	// Title screen. (-> title.c)
	ToTitleScreen();
}