/** * Initialize SDL * * @param int rows the number of rows that will be displayed * @param int cols the number of columns that will be displayed * @param int i the time interval in milliseconds after which the next * generation is drawn * @param ConwaysGameOfLife *cgol pointer to the object that encapsulates the * game's actual logic * @param positions_t positions the first generation of cells to be displayed * * @throws SDLException if SDL coudn't be initialized * * @see{ * game::getWindowSize * } * * TODO: allow the user to draw his own pattern using the mouse at the start * A nice feature for this would be to highlight the cell under the and only * set it if the user clicks on it */ Game::Game(int rows, int cols, unsigned int i, SDL_Color acolor, SDL_Color dcolor, ConwaysGameOfLife *cgol, positions_t pos) : no_rows(rows), no_columns(cols), interval(i), life(cgol){ if(SDL_Init(SDL_INIT_VIDEO) < 0){ throw SDLException("Couldn't initialize SDL!"); } const SDL_VideoInfo* vinfo = SDL_GetVideoInfo(); unsigned int length = std::min(vinfo->current_w, vinfo->current_h) - 50; setCellSideLength(length); SDL_Rect size = getWindowSize(length); screen = SDL_SetVideoMode(size.w, size.h, vinfo->vfmt->BitsPerPixel, flags); if(screen == nullptr){ throw SDLException("Couldn't set SDL video mode!"); } alive_color = SDL_MapRGB(vinfo->vfmt, acolor.r, acolor.g, acolor.b); dead_color = SDL_MapRGB(vinfo->vfmt, dcolor.r, dcolor.g, dcolor.b); std::vector<SDL_Rect> rects = setCells(pos, alive_color); SDL_UpdateRects(screen, rects.size(), rects.data()); running = true; }
Image* RenderBackendSDL::createMainScreen(unsigned int width, unsigned int height, unsigned char bitsPerPixel, bool fs, const std::string& title, const std::string& icon) { Uint32 flags = 0; if (fs) { flags |= SDL_FULLSCREEN; } if(icon != "") { SDL_Surface *img = IMG_Load(icon.c_str()); if(img != NULL) { SDL_WM_SetIcon(img, 0); } } SDL_Surface* screen = NULL; if( 0 == bitsPerPixel ) { /// autodetect best mode unsigned char possibleBitsPerPixel[] = {16, 24, 32, 0}; int i = 0; while( true ) { bitsPerPixel = possibleBitsPerPixel[i]; if( !bitsPerPixel ) { // Last try, sometimes VideoModeOK seems to lie. // Try bpp=0 screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( !screen ) { throw SDLException("Videomode not available"); } break; } bitsPerPixel = SDL_VideoModeOK(width, height, bitsPerPixel, flags); if ( bitsPerPixel ) { screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( screen ) { break; } } ++i; } } else { if ( !SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) { throw SDLException("Videomode not available"); } screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); } FL_LOG(_log, LMsg("RenderBackendSDL") << "Videomode " << width << "x" << height << " at " << int(screen->format->BitsPerPixel) << " bpp"); SDL_WM_SetCaption(title.c_str(), NULL); if (!screen) { throw SDLException(SDL_GetError()); } m_screen = new SDLImage(screen); return m_screen; }
void ImageLoader::load(IResource* res) { VFS* vfs = VFS::instance(); Image* img = dynamic_cast<Image*>(res); //Have to save the images x and y shift or it gets lost when it's //loaded again. int32_t xShiftSave = img->getXShift(); int32_t yShiftSave = img->getYShift(); if(!img->isSharedImage()) { const std::string& filename = img->getName(); boost::scoped_ptr<RawData> data (vfs->open(filename)); size_t datalen = data->getDataLength(); boost::scoped_array<uint8_t> darray(new uint8_t[datalen]); data->readInto(darray.get(), datalen); SDL_RWops* rwops = SDL_RWFromConstMem(darray.get(), static_cast<int>(datalen)); SDL_Surface* surface = IMG_Load_RW(rwops, false); if (!surface) { throw SDLException(std::string("Fatal Error when loading image into a SDL_Surface: ") + SDL_GetError()); } RenderBackend* rb = RenderBackend::instance(); // in case of SDL we don't need to convert the surface if (rb->getName() == "SDL") { img->setSurface(surface); // in case of OpenGL we need a 32bit surface } else { SDL_PixelFormat dst_format = rb->getPixelFormat(); SDL_PixelFormat src_format = *surface->format; uint8_t dstbits = dst_format.BitsPerPixel; uint8_t srcbits = src_format.BitsPerPixel; if (srcbits != 32 || dst_format.Rmask != src_format.Rmask || dst_format.Gmask != src_format.Gmask || dst_format.Bmask != src_format.Bmask || dst_format.Amask != src_format.Amask) { dst_format.BitsPerPixel = 32; SDL_Surface* conv = SDL_ConvertSurface(surface, &dst_format, 0); dst_format.BitsPerPixel = dstbits; if (!conv) { throw SDLException(std::string("Fatal Error when converting surface to the screen format: ") + SDL_GetError()); } img->setSurface(conv); SDL_FreeSurface(surface); } else { img->setSurface(surface); } } SDL_FreeRW(rwops); } //restore saved x and y shifts img->setXShift(xShiftSave); img->setYShift(yShiftSave); }
void Application::InitializeSDLSystem() { if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { throw SDLException(); } if (SDL_EnableKeyRepeat(1, SDL_DEFAULT_REPEAT_INTERVAL / 3) == -1) { throw SDLException(); } }
SDL::SDL() { if (SDL_Init(SDL_INIT_VIDEO) < 0) throw SDLException(SDL_GetError(), HERE); LOG4CXX_INFO(m_logger, "SDL initialized."); if (TTF_Init() < 0) throw SDLException(SDL_GetError(), HERE); LOG4CXX_INFO(m_logger, "SDL_ttf initialized."); }
void Canvas::init() { Uint32 sdlFlags = SDL_HWSURFACE | SDL_DOUBLEBUF; if(isFullscreen) sdlFlags |= SDL_FULLSCREEN; if(SDL_Init(SDL_INIT_EVERYTHING) < 0) throw SDLException("SDL init failed"); if((canvas = SDL_SetVideoMode(width, height, 32, sdlFlags)) == NULL) throw SDLException("Screen initialization failed"); }
void SoundProcessor::initSoundEngine() { // TODO start a 'watchdog' thread (FMOD waits indefinitely if the sound is currently used!) toInfoLog(TextStorage::instance().get(IDS::START_INIT_SOUND_TEXT_ID)->getText()); #ifdef _FMOD_SOUND unsigned int version; if(!ERRCHECK(FMOD::System_Create(&soundEngine))) { throw SDLException(TextStorage::instance().get(IDS::START_INIT_FMOD_SYSTEM_CREATE_ERROR_TEXT_ID)->getText()); } BOOST_ASSERT(soundEngine); if(!ERRCHECK(soundEngine->getVersion(&version))) { throw SDLException(TextStorage::instance().get(IDS::START_INIT_FMOD_GET_VERSION_ERROR_TEXT_ID)->getText()); } if (version < FMOD_VERSION) { std::ostringstream os; os << TextStorage::instance().get(IDS::START_INIT_FMOD_VERSION_ERROR_TEXT_ID)->getText() << "[" << version << " < " << FMOD_VERSION << "]"; throw SDLException(os.str()); } printSoundInformation(); if(!ERRCHECK(soundEngine->init(32, FMOD_INIT_NORMAL, 0))) { throw SDLException(TextStorage::instance().get(IDS::START_INIT_FMOD_SYSTEM_INIT_ERROR_TEXT_ID)->getText()); } #elif _SDL_MIXER_SOUND if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048)==-1) { std::ostringstream os; os << "ERROR (SoundProcessor::initSoundEngine()): " << Mix_GetError(); throw SDLException(os.str()); } Mix_ChannelFinished(::soundChannelDone); /* int flags = MIX_INIT_MP3; // TODO MOD! int initted = Mix_Init(flags); if(initted&flags != flags) { std::ostringstream os; os << "ERROR (SoundProcessor::initSoundEngine()): " << Mix_GetError(); throw SDLException(os.str()); }*/ #endif soundInitialized = true; }
void InputImpl::Init( ) { if ( m_initialized ) return; m_initialized = true; uint32_t ignoreTypes = Input::Instance().IgnoreTypes(); #ifdef SUPPORT_WIIMOTE if ( (ignoreTypes & InputDevice::Wiimote) == 0 ) { Wiimote::FindAll( &m_wiimotes ); } #endif SDL::Instance().Init( ); Assert( ::SDL_WasInit( SDL_INIT_VIDEO ) != 0 ); if ( (ignoreTypes & InputDevice::Keyboard) == 0 ) { m_pKeyboard = shared_ptr< Keyboard >( new Keyboard( "Keyboard" ) ); } if ( (ignoreTypes & InputDevice::Mouse) == 0 ) { m_pMouse = shared_ptr< Mouse >( new Mouse( "Mouse" ) ); } if ( (ignoreTypes & InputDevice::Gamepad) == 0 ) { if ( ::SDL_WasInit( SDL_INIT_JOYSTICK ) == 0 ) { int initRslt = ::SDL_InitSubSystem( SDL_INIT_JOYSTICK ); if ( initRslt != 0 ) throw SDLException( "SDL_InitSubSystem( SDL_INIT_JOYSTICK )" ); } int joystickEventState = ::SDL_JoystickEventState( SDL_ENABLE ); if ( joystickEventState != SDL_ENABLE ) throw SDLException( "SDL_JoystickEventState" ); for ( int i = 0; i < ::SDL_NumJoysticks( ); ++i ) { shared_ptr< Gamepad > pJoy( new Gamepad( ::SDL_JoystickName( i ), i ) ); m_joysticks.push_back( pJoy ); } } }
/** * Reinit the sound subsystem. */ void SDLSoundAgent::reinit() { m_music = NULL; m_looper = NULL; m_soundVolume = MIX_MAX_VOLUME; m_musicVolume = MIX_MAX_VOLUME; if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { throw SDLException(ExInfo("SDL_InitSubSystem")); } SDL_AudioSpec spec, have; spec.freq =48000; spec.format=AUDIO_S16SYS; spec.channels = 2; spec.samples=4096; spec.callback = 0; SDL_OpenAudio(&spec, &have); Mix_Init(MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG); int frequency = OptionAgent::agent()->getAsInt("sound_frequency", 44100); if(Mix_OpenAudio(frequency, MIX_DEFAULT_FORMAT, 2, 1024) < 0) { throw MixException(ExInfo("Mix_OpenAudio")); } Mix_AllocateChannels(16); SoundAgent::reinit(); }
visualiserWin::visualiserWin(int desiredFrameRate, bool vsync, int width, int height, Uint32 flags) { // Set the local members this->desiredFrameRate = desiredFrameRate; this->shouldVsync = vsync; this->currentVis = NULL; this->shouldCloseWindow = false; this->width = width; this->height = height; // Set the OpenGL attributes SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); if(vsync) SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); // Create the DSP manmager dspman = new DSPManager(); // Create the window drawContext = SDL_SetVideoMode(width, height, 0, flags | SDL_OPENGL); if(drawContext == NULL) throw(SDLException()); // also initialise the standard event handlers. initialiseStockEventHandlers(); }
RT::Texture::Texture(const std::string &path) : surface(NULL) { surface = IMG_Load(path.c_str()); if(surface == NULL) throw SDLException(); }
Surface::Surface(int width, int height) : width(width) , height(height) { Uint32 rmask, gmask, bmask, amask; #if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x000000ff; #else rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; #endif surface = SDL_CreateRGBSurface(0, width, height, 32, rmask, gmask, bmask, amask); if (surface == nullptr) { throw SDLException("SDL_CreateRGBSurface"); } }
ApplicationSDL::ApplicationSDL(int resx, int resy, const std::string& name, bool fullscreen) : Application(resx, resy, name, fullscreen) { if( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_NOPARACHUTE) == -1 ) throw SDLException("SDL init error: "); }
bool Application::OnInit() { std::string textException = "OnInit() => "; try { SettingsCreator::ConfigureSettingsFile(); InitializeSDLSystem(); InitializeVideoSystem(); InitializeTTFSystem(); InitializeAudioSystem(); InitializeResources(); StateManager::SetActiveState(STATE_MENU); return true; } catch (const SDLException& sdlException) { textException.append(sdlException.WhatHappens()); throw SDLException(textException); } catch (const TTFException& ttfException) { textException.append(ttfException.WhatHappens()); throw TTFException(textException); } catch (const MixerException& mixerException) { textException.append(mixerException.WhatHappens()); throw MixerException(textException); } catch (const GenericException& exception) { textException.append(exception.WhatHappens()); throw GenericException(textException); } return false; }
void Surface::AALine (const Point & begin, const Point & end, const Color & c) { if (aalineColor (surface, begin.x, begin.y, end.x, end.y, c.GetRGBAColor ())) throw SDLException (); }
void Graphics2D::SetupScreen( int width, int height, const char * title, EPixelType pixelType, bool fullScreen, bool openGL ) { const ::SDL_VideoInfo * videoInfo = ::SDL_GetVideoInfo( ); if ( videoInfo == 0 ) throw SDLException( "SDL_GetVideoInfo" ); if ( videoInfo->wm_available ) { ::SDL_WM_SetCaption( title, 0 ); //!!!SDL_WM_SetIcon(...); } Uint32 flags = 0; if ( fullScreen ) flags |= SDL_FULLSCREEN; ::SDL_PixelFormat pxlFmt = DetermineSDLPixelFormat( pixelType ); if ( openGL ) { flags |= SDL_OPENGL; int glRslt = ::SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); if ( glRslt != 0 ) throw SDLException( "SDL_GL_SetAttribute(DOUBLEBUFFER)" ); glRslt = ::SDL_GL_SetAttribute( SDL_GL_RED_SIZE, (8 - pxlFmt.Rloss) ); if ( glRslt != 0 ) throw SDLException( "SDL_GL_SetAttribute(RED_SIZE)" ); glRslt = ::SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, (8 - pxlFmt.Gloss) ); if ( glRslt != 0 ) throw SDLException( "SDL_GL_SetAttribute(GREEN_SIZE)" ); glRslt = ::SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, (8 - pxlFmt.Bloss) ); if ( glRslt != 0 ) throw SDLException( "SDL_GL_SetAttribute(BLUE_SIZE)" ); glRslt = ::SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, (8 - pxlFmt.Aloss) ); if ( glRslt != 0 ) throw SDLException( "SDL_GL_SetAttribute(ALPHA_SIZE)" ); glRslt = ::SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); if ( glRslt != 0 ) throw SDLException( "SDL_GL_SetAttribute(DEPTH_SIZE)" ); //!!!SDL_GL_STENCIL_SIZE //!!!SDL_GL_ACCUM_RED_SIZE, ..., SDL_GL_ACCUM_ALPHA_SIZE } else { flags |= (SDL_HWSURFACE | SDL_DOUBLEBUF); } ::SDL_Surface * sdlScreenSurface = ::SDL_SetVideoMode( width, height, pxlFmt.BitsPerPixel, flags ); if ( sdlScreenSurface == 0 ) throw SDLException( "SDL_SetVideoMode" ); m_spScreenSurface.reset( new Surface( sdlScreenSurface, false ) ); m_spScreenSurface->MakeCurrent( ); }
shared_ptr<SDL_Surface> SDL::renderText(const string & text, TTF_Font & font, const SDL_Color & color) { shared_ptr<SDL_Surface> renderedText(TTF_RenderText_Solid(&font, text.c_str(), color), &freeSurface); if (renderedText == NULL) throw SDLException(string("text \"") + text + "\" could not be rendered: " + SDL_GetError()); return renderedText; }
void Surface::Blit(const Surface &surf, SDL_Rect *src, SDL_Rect *dest) { int ret = SDL_BlitSurface(surf.GetSurface(), src, surface, dest); if (ret < 0) { throw SDLException("SDL_BlitSurface"); } }
void SDLPP::SDLPP::InitImage() noexcept(false) { int res = IMG_Init(IMG_INIT_PNG); if (res <= 0) { throw SDLException(ErrorCode::FailedInitializingSDLImage); } }
SDLInitSubSystem::SDLInitSubSystem(SDLSubSystem subsystem) : m_subsystem(subsystem) { if (SDL_InitSubSystem(static_cast<uint32_t>(m_subsystem)) != 0) { auto message = "SDL_InitSubsystem(" + ToString(static_cast<uint32_t>(subsystem)) + ") failed with '" + SDLGetError() + "'."; throw SDLException(message); } }
void SDLPP::SDLPP::InitTTF() noexcept(false) { int res = TTF_Init(); if (res <= 0) { throw SDLException(ErrorCode::FailedInitializingSDLTTF); } }
TTFInit::TTFInit() { if (TTF_Init() != 0) { auto message = "TTF_Init() failed with '" + TTFGetError() + "'."; throw SDLException(message); } }
SDLInit::SDLInit() { if (SDL_Init(0) != 0) { auto message = "SDL_Init(0) failed with '" + SDLGetError() + "'."; throw SDLException(message); } }
void SoundProcessor::printSoundInformation() const { #ifdef _FMOD_SOUND FMOD_RESULT result; int driver_num; result = soundEngine->getNumDrivers(&driver_num); ERRCHECK(result); std::ostringstream os; os << "* Available sound drivers: "; for(unsigned int i = driver_num; i--;) { char driver_name[256]; result = soundEngine->getDriverInfo(i, driver_name, 256, 0); ERRCHECK(result); os << driver_name << " "; } toInfoLog(os.str()); os.str(""); int current_driver; result = soundEngine->getDriver(¤t_driver); ERRCHECK(result); os << "* Driver used: "; if(current_driver == -1) { os << "Primary or main sound device as selected by the operating system settings"; if(driver_num == 1) { char driver_name[256]; result = soundEngine->getDriverInfo(current_driver, driver_name, 256, 0); ERRCHECK(result); os << "(probably '" << driver_name << "')"; } } else { char driver_name[256]; result = soundEngine->getDriverInfo(current_driver, driver_name, 256, 0); ERRCHECK(result); os << driver_name; } toInfoLog(os.str()); #elif _SDL_MIXER_SOUND int audio_rate, audio_channels; Uint16 audio_format; int success = Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels); if(!success) { std::ostringstream os; os << "ERROR (SoundProcessor::printSoundInformation()): " << Mix_GetError(); throw SDLException(os.str()); } int bits = audio_format & 0xFF; std::ostringstream os; os << "* Opened audio at " << audio_rate << "Hz " << bits << "bit " << ((audio_channels>1)?"stereo":"mono");// << ", " << audio_buffers << " bytes audio buffer"; toInfoLog(os.str()); #endif }
Graphics::Graphics(int width, int height, const char* title): width(width), height(height){ //If another instance already exists, we need to bail out if(exists) throw SDLException("Multiple Graphics objects instantiated"); else exists=true; //Initializing SDL and creating the window surface SDL_Init(SDL_INIT_EVERYTHING); TTF_Init(); window = SDL_SetVideoMode(width, height, bitsPerPixel, SDL_SWSURFACE); if(!window) throw SDLException("Error creating window"); SDL_WM_SetCaption(title, NULL); }
TTFFont::TTFFont(const boost::filesystem::path& fileName, int size) { m_pFont = TTF_OpenFont(fileName.string().c_str(), size); if (m_pFont == nullptr) { auto message = "TTF_OpenFont(" + fileName.string() + ") failed with '" + TTFGetError() + "'."; throw SDLException(message); } }
shared_ptr<SDL_Surface> SDL::rotate(SDL_Surface & surface, double degrees, bool smoothing) { shared_ptr<SDL_Surface> image( rotozoomSurface(&surface, degrees, 1, smoothing ? SMOOTHING_ON : SMOOTHING_OFF), &freeSurface); if (image == NULL) throw SDLException(IMG_GetError(), HERE); return image; }
void Application::OnRender() { try { // Increiblemente importante // Limpiar la pantalla de "suciedad" if (SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0)) == -1) { throw SDLException(); } StateManager::OnRender(screen); if (SDL_Flip(screen) == -1) { throw SDLException(); } } catch (const SDLException& sdlException) { throw sdlException; } catch (const TTFException& ttfException) { throw ttfException; } }
Bitmap::Bitmap(const std::string& fileName, const boost::shared_ptr<const ObjectSize> objectSize, const bool transparent): fileName(fileName), objectSize(objectSize), transparent(transparent), bitmap(IMG_Load((BITMAP_DIRECTORY + fileName).c_str())) { if(!bitmap) { throw SDLException("ERROR (Bitmap::Bitmap()): Loading file " + (BITMAP_DIRECTORY + fileName) + " (" + IMG_GetError() + ")."); } }
SDLSurface::SDLSurface(const boost::filesystem::path& fileName) : m_pSurface(nullptr) { assert(IMGInit::IsInit()); m_pSurface = IMG_Load(fileName.string().c_str()); if (m_pSurface == nullptr) { auto message = "IMG_Load(" + fileName.string() + ") failed with '" + IMGGetError() + "'."; throw SDLException(message); } }