int main(int argc, char* args[]) { if ( is_window_created() ) { // for "libpng warning: iCCP: known incorrect sRGB profile" // http://stackoverflow.com/questions/22745076/libpng-warning-iccp-known-incorrect-srgb-profile // load sdl2_image int image_flags = IMG_INIT_PNG; if ( !(IMG_Init(image_flags) & image_flags) ) { printf("main: sdl2_image err: %s\n", IMG_GetError()); return 1; } // http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_11.html if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "main: SDL_mixer Error: %s\n", Mix_GetError() ); return 1; } // load sdl ttf: https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_8.html // if ( TTF_Init() == -1 ) { // printf("sdl2_ttf err: %s\n", TTF_GetError()); // return 1; // } if ( !load_media() ) { user_quit = true; } // the LOOP while ( !user_quit ) { process_events(&g_event); game_update(); } } /** closing **/ // Deallocate textures texture_free(&g_current_texture); // joystick // SDL_JoystickClose(g_gamepad); // g_gamepad = 0; // sfx Mix_FreeChunk( g_scratch ); Mix_FreeChunk( g_hig ); Mix_FreeChunk( g_med ); Mix_FreeChunk( g_low ); g_scratch = 0; g_hig = 0; g_med = 0; g_low = 0; // music Mix_FreeMusic( g_music ); g_music = 0; SDL_DestroyRenderer(g_render); SDL_DestroyWindow(g_window); g_window = 0; g_render = 0; // https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf_10.html // TTF_Quit(); Mix_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create vsynced renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); // gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if( !( IMG_Init( imgFlags ) & imgFlags ) ) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); success = false; } //Initialize SDL_ttf if( TTF_Init() == -1 ) { printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } } } } return success; }
//==================== // Methods //==================== //////////////////////////////////////////////////////////// bool Window::create(const std::string& title, const Vector2i& position, const Vector2i& size, const ContextSettings_t& settings) { m_title = title; m_position = position; m_size = size; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO)) { log.error(log.function(__FUNCTION__, title, position, size), "SDL failed to initialize:", SDL_GetError()); return false; } if (IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG) == 0) { log.error(log.function(__FUNCTION__, title, position, size), "SDL image failed to initialize:", IMG_GetError()); return false; } m_pWindow = SDL_CreateWindow(m_title.c_str(), m_position.x, m_position.y, m_size.x, m_size.y, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!m_pWindow) { log.error(log.function(title, position, size), "Failed to create window:", SDL_GetError()); return false; } m_context = SDL_GL_CreateContext(m_pWindow); SDL_GL_SetSwapInterval(1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, m_settings.depthBits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, m_settings.stencilBits); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, m_settings.majorVersion); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, m_settings.minorVersion); m_running = true; if (!m_pMain) { glewExperimental = GL_TRUE; GLenum error = glewInit(); if (error != GLEW_OK) { log.error(log.function(__FUNCTION__, title, position, size), "GLEW failed to initialize:", glewGetErrorString(error)); return false; } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); log.debug(log.function(__FUNCTION__, title, position, size), "Main window set."); m_pMain = this; } glEnable(GL_DEPTH_TEST); log.debug(log.function(__FUNCTION__, title, position, size), "Created successfully."); return true; }
void TextureResource::Load() { tacAssert( GetFileName() != "" ); // load an image LogInfo( std::string("Loading image: ") + GetFileName() ); mSurface = IMG_Load( (IMG_DIR + GetFileName()).c_str() ); tacAssert( mSurface ); if ( !mSurface ) { LogError( std::string("Unable to load bitmap: ") + GetFileName() + std::string(" SDL_image error: ") + std::string( IMG_GetError() ) ); } }
//! initialize sdl window bool initialize() { // Initialization flag bool success = true; // Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { std::cerr << "SDL could not initialize. SDL_Error: " << SDL_GetError() << std::endl; success = false; } else { // Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { std::cerr << "Warning: Linear texture filtering not enabled!" << std::endl; } // Create window g_window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_width_height[0], screen_width_height[1], SDL_WINDOW_SHOWN ); if( g_window == NULL ) { std::cerr << "Window could not be created. SDL_Error: " << SDL_GetError() << std::endl; success = false; } else { // Create the renderer for the window g_renderer = SDL_CreateRenderer( g_window, -1, SDL_RENDERER_ACCELERATED); if( g_renderer == NULL ) { std::cerr << "Renderer could not be created! SDL_Error: " << SDL_GetError() << std::endl; success = false; } else { // Initialize renderer color SDL_SetRenderDrawColor( g_renderer, 0xFF, 0xFF, 0xFF, 0xFF ); // Initialize PNG loading int img_flags = IMG_INIT_PNG; if( !( IMG_Init( img_flags ) & img_flags ) ) { std::cerr << "SDL_image extension could not initialize! " << "SDL_image Error: " << IMG_GetError() << std::endl; success = false; } } } } return success; }
Image *SDLHardwareRenderDevice::loadImage(const std::string& filename, int error_type) { // lookup image in cache Image *img; img = cacheLookup(filename); if (img != NULL) return img; // load image SDLHardwareImage *image = new SDLHardwareImage(this, renderer); if (!image) return NULL; image->surface = IMG_LoadTexture(renderer, mods->locate(filename).c_str()); if(image->surface == NULL) { delete image; if (error_type != ERROR_NONE) Utils::logError("SDLHardwareRenderDevice: Couldn't load image: '%s'. %s", filename.c_str(), IMG_GetError()); if (error_type == ERROR_EXIT) { Utils::logErrorDialog("SDLHardwareRenderDevice: Couldn't load image: '%s'.\n%s", filename.c_str(), IMG_GetError()); mods->resetModConfig(); Utils::Exit(1); } return NULL; } // store image to cache cacheStore(filename, image); return image; }
Image *SDLHardwareRenderDevice::loadImage(std::string filename, std::string errormessage, bool IfNotFoundExit) { // lookup image in cache Image *img; img = cacheLookup(filename); if (img != NULL) return img; // load image SDLHardwareImage *image = new SDLHardwareImage(this, renderer); if (!image) return NULL; image->surface = IMG_LoadTexture(renderer, mods->locate(filename).c_str()); if(image->surface == NULL) { delete image; if (!errormessage.empty()) logError("SDLHardwareRenderDevice: [%s] %s: %s", filename.c_str(), errormessage.c_str(), IMG_GetError()); if (IfNotFoundExit) { Exit(1); } return NULL; } // store image to cache cacheStore(filename, image); return image; }
bool ColorKeyingApp::initApp() { // flag to return bool success = true; /***** * Use this function to initialize the SDL library. This must be called before using any other SDL function. * INFO: http://wiki.libsdl.org/SDL_Init?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29 *****/ // Initialize SDL // see following for remarks on flag http://wiki.libsdl.org/SDL_Init#Remarks if (SDL_Init( SDL_INIT_VIDEO) < 0) { std::cout << "SDL ould not initalize! SDLError: " << SDL_GetError() << std::endl; success = false; } else { //Set texture filtering to linear // INFO ON SDL_SetHint: see https://wiki.libsdl.org/SDL_SetHint // INFO ON SDL_HINT_RENDER_SCALE_QUALITY: see https://wiki.libsdl.org/SDL_HINT_RENDER_SCALE_QUALITY?highlight=%28\bCategoryDefine\b%29|%28CategoryHints%29 if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { std::cout << "Warning: Linear texture filtering not enabled!" << std::endl; } /***** * Returns the window that was created or NULL on failure * INFO: http://wiki.libsdl.org/SDL_CreateWindow?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29 ******/ // Create Window // INFO: see following for remarks on flags http://wiki.libsdl.org/SDL_CreateWindow#flags gWindow = SDL_CreateWindow("SDL Tutorial 10", // the title of the window in UTF-8 encoding SDL_WINDOWPOS_UNDEFINED, // the x position of the window SDL_WINDOWPOS_UNDEFINED, // the y position of the window SCREEN_WIDTH, // the width of the window SCREEN_HEIGHT, // the height of the window SDL_WINDOW_SHOWN // 0 or more SDL_WindowFlags OR'd together ); if (gWindow == nullptr) { std::cout << "Window could not be created! SDL_Error:" << SDL_GetError() << std::endl; success = false; } else { // Get window surface // INFO: http://wiki.libsdl.org/SDL_GetWindowSurface?highlight=%28\bCategoryAPI\b%29|%28SDLFunctionTemplate%29 // gScreenSurface = SDL_GetWindowSurface(gWindow); gCurrentRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); if (gCurrentRenderer == nullptr) { std::cout << "Renderer could not be created! SDL Error: " << SDL_GetError() << std::endl; } else { // Initalize renderer color SDL_SetRenderDrawColor(gCurrentRenderer, 0xFF, 0xFF, 0xFF, 0xFF); // initialize the SDL image auto imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) && imgFlags)) { std::cout << "SDL Image could not be initialized! SDL Img Error: " << IMG_GetError() << std::endl; } } } } return success; }
int SDL_main (int argc,char* argv[]) { #elif __APPLE__ int SDL_main (int argc,char* argv[]) { #else #ifdef main #undef main #endif int main(int argc,char* argv[]) { #endif printf("[INFO] Entering main\n"); uint32_t flags=SDL_INIT_VIDEO; #ifndef WIN32 flags|=SDL_INIT_EVENTTHREAD; #endif #ifdef __MACH__ flags = SDL_INIT_EVERYTHING; #endif if (SDL_Init(flags)==-1) { printf("SDL_Init: %s\n", SDL_GetError ()); return -1; } screen=SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT, 32, SDL_SWSURFACE); if(screen == NULL) { printf("SDL_SetVideoMode failed!\n"); return -2; } SDL_WM_SetCaption ("Pebble Local Simulator - 24H Style",0); pebbleScreen = createScreen; if(TTF_Init()==-1) { printf("TTF_Init: %s\n", TTF_GetError()); return -3; } if (IMG_Init (IMG_INIT_PNG)==-1) { printf("IMG_Init: %s\n", IMG_GetError()); return -4; } if (!loadSimulatorImages()) return -5; bodyImg=getSimulatorImage(SIM_IMG_BODY); shadowImg=getSimulatorImage(SIM_IMG_SCREEN_SHADOW); vibeImg=getSimulatorImage(SIM_IMG_VIBE); lightImg=getSimulatorImage(SIM_IMG_BACKLIGHT); logFile=fopen (LOG_FILE,"a"); if (!initRender(pebbleScreen)) return -9; persistent_storage_load(); initHardwareOutput (); initButtons(); pbl_main(); unloadSystemFonts (); quitRender(); persistent_storage_free(); if (logFile!=0) fclose(logFile); freeSimulatorImages(); IMG_Quit (); TTF_Quit (); SDL_Quit (); return 0; }
/****************************************************************************** * Display Initialization ******************************************************************************/ bool display::init(const math::vec2i inResolution, bool isFullScreen) { Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS | //SDL_WINDOW_INPUT_GRABBED| 0; if (isFullScreen) { windowFlags |= SDL_WINDOW_FULLSCREEN; } /* * Create the window */ pWindow = SDL_CreateWindow( _GAME_NAME, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, inResolution[0], inResolution[1], windowFlags ); if (!pWindow) { std::cerr << SDL_GetError() << std::endl; return false; } /* * Create a renderer that will be used for the window */ pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_ACCELERATED); if (!pRenderer) { std::cerr << SDL_GetError() << std::endl; SDL_DestroyWindow(pWindow); return false; } /* * Attempt to initialize additional image format support */ const int imgFlags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF; if ((IMG_Init(imgFlags)&imgFlags) != imgFlags) { std::cerr << "Warning: Unable to initialize JPG, PNG, and TIF image loaders.\n" << IMG_GetError() << std::endl; } /* * Initialize the TTF addon */ if (TTF_Init() < 0) { std::cerr << "Warning: Unable to initialize the TTF add-on.\n" << TTF_GetError() << std::endl; } /* * Misc */ SDL_SetRenderDrawBlendMode(pRenderer, SDL_BLENDMODE_BLEND); SDL_GL_SetSwapInterval(1); return true; }
int main(int argc, char **argv) { // the character returned from the getopt function char c; // now loop and parse the command line options while( (c=getopt(argc,argv,ARGUMENTS)) !=EOF) { switch(c) // which option has been chosen { case 'h' : std::cout<<"TextureCompressor [filename(s)] for default DXT1 compression\n"; std::cout<<"-e [name] to change extension from default .cmp\n"; std::cout<<"-c [1][3][5] for DxT1 DxT3 or Dxt5 compression \n"; std::cout<<"-v verbose \n"; std::cout<<"it will process all files on command line\n"; exit(EXIT_SUCCESS); case 'e' : g_ext=optarg; break; case 'v' : g_verbose=true; break; case '?' : // unknown option report this and exit // where optopt is the current option std::cout<<"Unknown argument "<<optopt<<std::endl; exit(EXIT_FAILURE); break; case 'o' : g_output=optarg; break; case 'c' : if(optarg[0]=='1') { // this is the default but set it anyway g_comp=DXT1; g_scomp=squish::kDxt1; } else if(optarg[0]=='3') { g_comp=DXT3; g_scomp=squish::kDxt3; } else if(optarg[0]=='5') { g_comp=DXT5; g_scomp=squish::kDxt5; } break; } } // Initialize SDL's Video subsystem if (SDL_Init(SDL_INIT_VIDEO) < 0 ) { // Or die on error std::cerr<<"Problem with SDL\n"; std::exit(EXIT_FAILURE); } // image data to load SDL_Surface *image; std::ofstream fileOut; fileOut.open(g_output.c_str(),std::ios::out | std::ios::binary); const std::string header("ngl::packtexture"); fileOut.write(header.c_str(),header.length()); int numFiles=0; // need to store this position for later so we can write out // the actual number of files packed. int numFileLocation=fileOut.tellp(); // now write out dummy size; fileOut.write(reinterpret_cast<char *>(&numFiles),sizeof(int)); for(int file=optind; file<argc; ++file) { // load current file and see if it is ok image=IMG_Load(argv[file]); if(!image) { std::cerr<<"Problem loading "<<argv[file]<<" " <<IMG_GetError()<<"\n"; continue; } // now compress. createCompressedTexture(fileOut,image,argv[file]); // and free the image SDL_free(image); ++numFiles; } fileOut.seekp(numFileLocation,std::ios_base::beg ); fileOut.write(reinterpret_cast<char *>(&numFiles),sizeof(int)); // close file fileOut.close(); // now tidy up and exit SDL SDL_Quit(); }
void ReinforcementPictures<T>::displayLoop() { #if 0 // initialization logging.info("Starting SDL init (0).."); SDL_Init(0); logging.info("Starting SDL subsystem init (events, video, audio).."); if(SDL_InitSubSystem(SDL_INIT_EVENTS) != 0){ logging.error("SDL_Init(EVENTS) failed."); SDL_Quit(); running = false; return; } if(SDL_InitSubSystem(SDL_INIT_VIDEO) != 0){ logging.error("SDL_Init(VIDEO) failed."); SDL_Quit(); running = false; return; } if(SDL_InitSubSystem(SDL_INIT_AUDIO) != 0){ logging.error("SDL_Init(AUDIO) failed."); SDL_Quit(); running = false; return; } logging.info("SDL_Init() events, video, audio successful."); #endif // opens SDL display SDL_Window* window = NULL; int W = 640; int H = 480; SDL_DisplayMode mode; if(SDL_GetCurrentDisplayMode(0, &mode) == 0){ W = (3*mode.w)/4; H = (3*mode.h)/4; } else{ whiteice::logging.error("SDL_GetCurrentDisplayMode() failed"); running = false; SDL_Quit(); return; } #if 0 if(TTF_Init() != 0){ char buffer[80]; snprintf(buffer, 80, "TTF_Init failed: %s\n", TTF_GetError()); logging.error(buffer); TTF_Quit(); SDL_Quit(); running = false; return; } else logging.info("Starting TTF_Init() done.."); int flags = IMG_INIT_JPG | IMG_INIT_PNG; if(IMG_Init(flags) != flags){ char buffer[80]; snprintf(buffer, 80, "IMG_Init failed: %s\n", IMG_GetError()); logging.error(buffer); IMG_Quit(); TTF_Quit(); SDL_Quit(); running = false; return; } #endif window = SDL_CreateWindow("Tranquility", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, W, H, SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_INPUT_FOCUS); if(window == NULL){ whiteice::logging.error("SDL_CreateWindow() failed\n"); running = false; return; } SDL_RaiseWindow(window); SDL_UpdateWindowSurface(window); SDL_RaiseWindow(window); // loads font TTF_Font* font = NULL; TTF_Font* font2 = NULL; { double fontSize = 100.0*sqrt(((float)(W*H))/(640.0*480.0)); unsigned int fs = (unsigned int)fontSize; if(fs <= 0) fs = 10; font = TTF_OpenFont(fontname.c_str(), fs); fontSize = 25.0*sqrt(((float)(W*H))/(640.0*480.0)); fs = (unsigned int)fontSize; if(fs <= 0) fs = 10; font2 = TTF_OpenFont(fontname.c_str(), fs); } // loads all pictures std::vector<SDL_Surface*> images; images.resize(pictures.size()); actionFeatures.resize(pictures.size()); { for(unsigned int i=0;i<pictures.size();i++) images[i] = NULL; unsigned int numLoaded = 0; #pragma omp parallel for shared(images) shared(numLoaded) schedule(dynamic) for(unsigned int i=0;i<pictures.size();i++) { if(running == false) continue; SDL_Surface* image = NULL; #pragma omp critical { // IMG_loader functions ARE NOT thread-safe so // we cannot load files parallel image = IMG_Load(pictures[i].c_str()); } if(image == NULL){ char buffer[120]; snprintf(buffer, 120, "Loading image FAILED (%s): %s", SDL_GetError(), pictures[i].c_str()); whiteice::logging.warn(buffer); printf("ERROR: %s\n", buffer); image = SDL_CreateRGBSurface(0, W, H, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(image == NULL){ whiteice::logging.error("Creating RGB surface failed"); running = false; continue; } SDL_FillRect(image, NULL, SDL_MapRGB(image->format, 0, 0, 0)); } SDL_Rect imageRect; SDL_Surface* scaled = NULL; if(image->w >= image->h){ double wscale = ((double)W)/((double)image->w); scaled = SDL_CreateRGBSurface(0, (int)(image->w*wscale), (int)(image->h*wscale), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(scaled == NULL){ whiteice::logging.error("Creating RGB surface failed"); running = false; continue; } if(SDL_BlitScaled(image, NULL, scaled, NULL) != 0) whiteice::logging.warn("SDL_BlitScaled fails"); } else{ double hscale = ((double)H)/((double)image->h); scaled = SDL_CreateRGBSurface(0, (int)(image->w*hscale), (int)(image->h*hscale), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if(scaled == NULL){ whiteice::logging.error("Creating RGB surface failed"); running = false; continue; } if(SDL_BlitScaled(image, NULL, scaled, NULL) != 0) whiteice::logging.warn("SDL_BlitScaled fails"); } images[i] = scaled; if(image) SDL_FreeSurface(image); // creates feature vector (mini picture) of the image { actionFeatures[i].resize(this->dimActionFeatures); calculateFeatureVector(images[i], actionFeatures[i]); } numLoaded++; // displays pictures that are being loaded #pragma omp critical { imageRect.w = scaled->w; imageRect.h = scaled->h; imageRect.x = (W - scaled->w)/2; imageRect.y = (H - scaled->h)/2; SDL_Surface* surface = SDL_GetWindowSurface(window); if(surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0, 0, 0)); SDL_BlitSurface(scaled, NULL, surface, &imageRect); if(font){ SDL_Color white = { 255, 255, 255 }; char message[80]; snprintf(message, 80, "%d/%d", numLoaded, pictures.size()); SDL_Surface* msg = TTF_RenderUTF8_Blended(font, message, white); if(msg != NULL){ SDL_Rect messageRect; messageRect.x = (W - msg->w)/2; messageRect.y = (H - msg->h)/2; messageRect.w = msg->w; messageRect.h = msg->h; SDL_BlitSurface(msg, NULL, surface, &messageRect); SDL_FreeSurface(msg); } } SDL_UpdateWindowSurface(window); SDL_ShowWindow(window); SDL_FreeSurface(surface); } } SDL_Event event; while(SDL_PollEvent(&event)){ if(event.type == SDL_KEYDOWN){ keypresses++; continue; } } } } long long start_ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count(); unsigned int index = 0; // selects HMM initial state randomly according to starting state probabilities auto pi = hmm.getPI(); currentHMMstate = hmm.sample(pi); while(running){ initialized = true; SDL_Event event; while(SDL_PollEvent(&event)){ if(event.type == SDL_KEYDOWN){ keypresses++; continue; } } if(dev->connectionOk() == false){ whiteice::logging.info("ReinforcementPictures: Device connection failed"); running = false; continue; } // waits for full picture show time { const long long end_ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count(); long long delta_ms = end_ms - start_ms; if(delta_ms < DISPLAYTIME){ std::this_thread::sleep_for(std::chrono::milliseconds(DISPLAYTIME - delta_ms)); // usleep((DISPLAYTIME - delta_ms)*1000); } } // updates HMM hidden state after action { std::vector<float> after; std::vector<T> state; after.resize(dev->getNumberOfSignals()); for(auto& a : after) a = 0.0f; dev->data(after); state.resize(after.size()); for(unsigned int i=0;i<state.size();i++){ state[i] = after[i]; } const unsigned int o = clusters.getClusterIndex(state); unsigned int nextState = currentHMMstate; const double p = hmm.next_state(currentHMMstate, nextState, o); currentHMMstate = nextState; } // adds previous action to performedActionsQueue { std::lock_guard<std::mutex> lock(performedActionsMutex); performedActionsQueue.push_back(index); } // waits for a command (picture) to show index = 0; { while(running){ { std::lock_guard<std::mutex> lock(actionMutex); if(actionQueue.size() > 0){ index = actionQueue.front(); actionQueue.pop_front(); break; } } usleep(10); } if(!running) continue; } // if we are in random mode we choose random pictures if(random) index = rng.rand() % images.size(); { SDL_Surface* surface = SDL_GetWindowSurface(window); if(surface != NULL){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0, 0, 0)); SDL_Rect imageRect; imageRect.w = images[index]->w; imageRect.h = images[index]->h; imageRect.x = (W - images[index]->w)/2; imageRect.y = (H - images[index]->h)/2; SDL_BlitSurface(images[index], NULL, surface, &imageRect); if(font2 && message.size() > 0){ SDL_Color white = { 255, 255, 255 }; SDL_Surface* msg = TTF_RenderUTF8_Blended(font2, message.c_str(), white); if(msg != NULL){ SDL_Rect messageRect; messageRect.x = (W - msg->w)/2; messageRect.y = (H - msg->h)/2; messageRect.w = msg->w; messageRect.h = msg->h; SDL_BlitSurface(msg, NULL, surface, &messageRect); SDL_FreeSurface(msg); } } SDL_UpdateWindowSurface(window); SDL_ShowWindow(window); SDL_FreeSurface(surface); } } start_ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch()).count(); } SDL_DestroyWindow(window); if(font){ TTF_CloseFont(font); font = NULL; } if(font2){ TTF_CloseFont(font2); font2 = NULL; } #if 0 logging.info("SDL deinitialization started"); IMG_Quit(); TTF_Quit(); SDL_Quit(); logging.info("SDL deinitialization.. DONE"); #endif }
bool World::InitScreen() { bool run = true; if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { printf("Fail initialize : %s\n",SDL_GetError()); run = false; } else { printf("Initialization Success!\n"); if(!SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1")) { printf("Warning: VSync not enabled!\n"); run = false; } m_window = SDL_CreateWindow(TITLE,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,g_WINDOW_WIDTH,g_WINDOW_HEIGHT,SDL_WINDOW_SHOWN); if(m_window == NULL) { printf("ERROR creting Window : %s\n",SDL_GetError()); run = false; } else { printf("Created Window .\n"); m_render = SDL_CreateRenderer(m_window,-1,SDL_RENDERER_ACCELERATED); if(m_render == NULL) { printf("Failed creating Render : %s\n",SDL_GetError()); run = false; } else { printf("Creted Render.\n"); SDL_SetRenderDrawColor( m_render, 0xFF, 0xFF, 0xFF, 0xFF ); int picFlag = IMG_INIT_PNG; if(!(IMG_Init(picFlag))& picFlag) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); run = false; } else { if(!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { printf("Warning: Scale Quality not enabled!\n"); run = false; } else { m_Stick1 = SDL_JoystickOpen(0); if(m_Stick1 == NULL) { printf("Warning: 1st Joystick FAIL\n"); } m_Stick2 = SDL_JoystickOpen(1); if(m_Stick2 == NULL) { printf("Warning: 2nd Joystick FAIL\n"); } if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 4, 4048 ) < 0 ) { printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() ); } } } } } } m_main_music= new Sound(); m_main_music->Init("data/music.txt"); m_main_music->Play(true); SDL_JoystickEventState(SDL_ENABLE); return run; }
/* * Initializes the window and set it's corresponding Surface */ bool Graphics::init() { bool success; int imgFlags; success = true; imgFlags = IMG_INIT_JPG | IMG_INIT_PNG; if (SDL_Init(SDL_INIT_VIDEO) < 0) { success = false; std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl; } else { this->_window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (this->_window == NULL) { success = false; std::cerr << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl; } else { this->_renderer = SDL_CreateRenderer(this->_window, -1, SDL_RENDERER_ACCELERATED); if (this->_renderer == NULL) { success = false; std::cerr << "Renderer could not be created! SDL Error: " << SDL_GetError() << std::endl; } else { SDL_SetRenderDrawColor(this->_renderer, 255, 0, 0, 255); if (!(IMG_Init(imgFlags) & imgFlags)) { std::cerr << "SDL_Image could not initialize! SDL_Image error: " << IMG_GetError() << std::endl; success = false; } } } } return success; }
bool init(int screen)//0 = windowed (default), 1 = 1.5x screen, 2 = fullscreen, 3 = 1.5x fullscreen mode { //Initialization flag bool success = true; //Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); success = false; } else { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); //Use OpenGL 2.1 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); //Create window switch (screen) { case 1: gWindow = SDL_CreateWindow("Frictionless", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); break; case 2: gWindow = SDL_CreateWindow("Frictionless", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN); break; case 3: gWindow = SDL_CreateWindow("Frictionless", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN); break; default: gWindow = SDL_CreateWindow("Frictionless", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); } SDLNet_Init(); if (gWindow == NULL) { printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Create context gContext = SDL_GL_CreateContext(gWindow); if (gContext == NULL) { printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Use Vsync if (SDL_GL_SetSwapInterval(0) < 0) { printf("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); } //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); success = false; } //Initialize OpenGL if (!initGL()) { printf("Unable to initialize OpenGL!\n"); success = false; } } } } return success; }
texture_impl::texture_impl(const string & fname, const int & format, const GLenum opengl_texture_unit, const bool compress) : shared_object(), name(fname), format(format), compress(compress), opengl_texture_unit(opengl_texture_unit), opengl_id(0), buffer(0) { if (!file::exists(fname)) throw io_exception(L"Texture file %ls not found.", fname.w_string()); SDL_Surface *surface = IMG_Load(fname.c_string()); if (!surface) throw runtime_exception(L"Unable to load texture file %ls: %hs", fname.w_string(), IMG_GetError()); buffer = new rgba_buffer(surface); SDL_FreeSurface(surface); } // texture_impl::texture_impl()
void PseuGUI::_Init(void) { if(SDL_Init(SDL_INIT_VIDEO) < 0)//initialisation de la SDL { logerror("Erreur d'initialisation de la SDL : %s",SDL_GetError()); // return EXIT_FAILURE; } // Initialise SDL Video screen = SDL_CreateWindow("Handmade Hero", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_RESIZABLE); renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE); /* ///// // Create window and renderer. /// screen = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN); // renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE); */ if (screen == NULL || renderer == NULL) { logerror("Impossible d'initialiser le mode écran à %d x %d: %s\n", 800, 600, SDL_GetError()); // exit(1); } //Initialisation du chargement des images png avec la SDL 2.0 - Voir les commentaires du chapitre 9 int imgFlags = IMG_INIT_PNG; if( !( IMG_Init( imgFlags ) & imgFlags ) ) { logerror( "SDL_image n'a pu être initialisée! SDL_image Error: %s\n", IMG_GetError() ); //exit(1); } // Cache le curseur de la souris //SDL_ShowCursor(SDL_DISABLE); /* Initialise SDL_TTF */ if (TTF_Init() < 0) { logerror("Impossible d'initialiser SDL TTF: %s\n", TTF_GetError()); // exit(1); } SDL_SetRenderDrawColor( renderer, 255, 255, 255, 255 ); font[0] = loadFont("./font/Kraash_Black.ttf", 48); font[1] = loadFont("./font/GenBasB.ttf", 24); font[2] = loadFont("./font/Super_Mario_Bros.ttf", 32); font[3] = loadFont("./font/MORPHEUS.TTF", 48); font[4] = loadFont("./font/MORPHEUS.TTF", 18); font[5] = loadFont("./font/GenBasB.TTF", 18); font[6] = loadFont("./font/Kraash_Black.TTF", 16); font[7] = loadFont("verdana.ttf", 16); //SDL_Texture *background; /* _device = createDevice(_driverType,dimension2d<u32>(_xres,_yres),_colordepth,!_windowed,_shadows,_vsync); if(!_device) { logerror("PseuGUI: Can't use specified video driver, trying software mode..."); _device = createDevice(video::EDT_SOFTWARE,dimension2d<u32>(_xres,_yres),_colordepth,!_windowed,false,false); if(!_device) { logerror("ERROR: PseuGUI::_Init() failed, no video driver available!"); return; } else { logerror("PseuGUI: Software mode OK!"); } } DEBUG(logdebug("PseuGUI::Init() _device=%X",_device)); _device->setWindowCaption(L"PseuWoW - Initializing"); _device->setResizable(true); */ //_driver = _device->getVideoDriver(); // _smgr = _device->getSceneManager(); // _guienv = _device->getGUIEnvironment(); _timer = SDL_GetTicks(); // _screendimension = _driver->getScreenSize(); //... // disable crappy irrlicht logging // _device->getLogger()->setLogLevel(ELL_NONE); // register external loaders for not supported filetypes // scene::CM2MeshFileLoader* m2loader = new scene::CM2MeshFileLoader(_device); //_smgr->addExternalMeshLoader(m2loader); // scene::CWMOMeshFileLoader* wmoloader = new scene::CWMOMeshFileLoader(_device); //_smgr->addExternalMeshLoader(wmoloader); _throttle=0; _initialized = true; }
//Basic Init, create the font, backbuffer, etc WINDOW *curses_init(void) { lastchar = -1; inputdelay = -1; std::string typeface = "Terminus"; std::string blending = "solid"; std::ifstream fin; int faceIndex = 0; int fontsize = 0; //actuall size fin.open("data/FONTDATA"); if (!fin.is_open()){ fontwidth = 8; fontheight = 16; std::ofstream fout;//create data/FONDATA file fout.open("data/FONTDATA"); if(fout.is_open()) { fout << typeface << "\n"; fout << fontwidth << "\n"; fout << fontheight; fout.close(); } } else { getline(fin, typeface); fin >> fontwidth; fin >> fontheight; fin >> fontsize; fin >> blending; if ((fontwidth <= 4) || (fontheight <= 4)) { fontheight = 16; fontwidth = 8; } fin.close(); } fontblending = (blending=="blended"); halfwidth=fontwidth / 2; halfheight=fontheight / 2; if(!InitSDL()) { DebugLog() << "Failed to initialize SDL: " << SDL_GetError() << "\n"; return NULL; } TERMINAL_WIDTH = OPTIONS["TERMINAL_X"]; TERMINAL_HEIGHT = OPTIONS["TERMINAL_Y"]; if(OPTIONS["FULLSCREEN"]) { // Fullscreen mode overrides terminal width/height SDL_DisplayMode display_mode; SDL_GetDesktopDisplayMode(0, &display_mode); TERMINAL_WIDTH = display_mode.w / fontwidth; TERMINAL_HEIGHT = display_mode.h / fontheight; WindowWidth = display_mode.w; WindowHeight = display_mode.h; } else { WindowWidth= OPTIONS["TERMINAL_X"]; if (WindowWidth < FULL_SCREEN_WIDTH) WindowWidth = FULL_SCREEN_WIDTH; WindowWidth *= fontwidth; WindowHeight = OPTIONS["TERMINAL_Y"] * fontheight; } if(!WinCreate()) { DebugLog() << "Failed to create game window: " << SDL_GetError() << "\n"; return NULL; } #ifdef SDLTILES DebugLog() << "Initializing SDL Tiles context\n"; tilecontext = new cata_tiles(renderer); try { tilecontext->init("gfx"); DebugLog() << "Tiles initialized successfully.\n"; } catch(std::string err) { // use_tiles is the cached value of the USE_TILES option. // most (all?) code refers to this to see if cata_tiles should be used. // Setting it to false disables this from getting used. use_tiles = false; } #endif // SDLTILES #ifdef SDLTILES while(!strcasecmp(typeface.substr(typeface.length()-4).c_str(),".bmp") || !strcasecmp(typeface.substr(typeface.length()-4).c_str(),".png")) { DebugLog() << "Loading bitmap font [" + typeface + "].\n" ; typeface = "data/font/" + typeface; SDL_Surface *asciiload = IMG_Load(typeface.c_str()); if(!asciiload || asciiload->w*asciiload->h < (fontwidth * fontheight * 256)) { DebugLog() << "Failed to load bitmap font: " << IMG_GetError() << "\n"; SDL_FreeSurface(asciiload); break; } Uint32 key = SDL_MapRGB(asciiload->format, 0xFF, 0, 0xFF); SDL_SetColorKey(asciiload,SDL_TRUE,key); SDL_Surface *ascii_surf[16]; ascii_surf[0] = SDL_ConvertSurface(asciiload,format,0); SDL_SetSurfaceRLE(ascii_surf[0], true); SDL_FreeSurface(asciiload); for(int a = 1; a < 16; ++a) { ascii_surf[a] = SDL_ConvertSurface(ascii_surf[0],format,0); SDL_SetSurfaceRLE(ascii_surf[a], true); } init_colors(); for(int a = 0; a < 15; ++a) { SDL_LockSurface(ascii_surf[a]); int size = ascii_surf[a]->h * ascii_surf[a]->w; Uint32 *pixels = (Uint32 *)ascii_surf[a]->pixels; Uint32 color = (windowsPalette[a].r << 16) | (windowsPalette[a].g << 8) | windowsPalette[a].b; for(int i=0;i<size;i++) { if(pixels[i] == 0xFFFFFF) pixels[i] = color; } SDL_UnlockSurface(ascii_surf[a]); } if(fontwidth) tilewidth = ascii_surf[0]->w / fontwidth; OutputChar = &OutputImageChar; //convert ascii_surf to SDL_Texture for(int a = 0; a < 16; ++a) { ascii[a] = SDL_CreateTextureFromSurface(renderer,ascii_surf[a]); SDL_FreeSurface(ascii_surf[a]); } mainwin = newwin(get_terminal_height(), get_terminal_width(),0,0); return mainwin; } #endif // SDLTILES std::string sysfnt = find_system_font(typeface, faceIndex); if(sysfnt != "") typeface = sysfnt; //make fontdata compatible with wincurse if(!fexists(typeface.c_str())) { faceIndex = 0; typeface = "data/font/" + typeface + ".ttf"; } //different default font with wincurse if(!fexists(typeface.c_str())) { faceIndex = 0; typeface = "data/font/fixedsys.ttf"; } DebugLog() << "Loading truetype font [" + typeface + "].\n" ; if(fontsize <= 0) fontsize = fontheight - 1; // SDL_ttf handles bitmap fonts size incorrectly if(0 == strcasecmp(typeface.substr(typeface.length() - 4).c_str(), ".fon")) faceIndex = test_face_size(typeface, fontsize, faceIndex); font = TTF_OpenFontIndex(typeface.c_str(), fontsize, faceIndex); if (font == NULL) { DebugLog() << "Failed to load truetype font: " << TTF_GetError() << "\n"; return NULL; } TTF_SetFontStyle(font, TTF_STYLE_NORMAL); // glyph height hack by utunnels // SDL_ttf doesn't use FT_HAS_VERTICAL for function TTF_GlyphMetrics // this causes baseline problems for certain fonts // I can only guess by check a certain tall character... cache_glyphs(); init_colors(); OutputChar = &OutputFontChar; mainwin = newwin(get_terminal_height(), get_terminal_width(),0,0); return mainwin; //create the 'stdscr' window and return its ref }
/* Inicjacja programu wraz z ladowanie obiektow */ bool Engine::init() { bool success = true; if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { printf( "Nie zainicjowano SDL Error %s\n", SDL_GetError() ); success = false; } else { if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Ostrzezenie: Liniowe filtrowanie tekstur jest wylaczone!\n " ); } width = 800; height = 600; Uint32 flags = SDL_WINDOW_SHOWN; window = SDL_CreateWindow( "CD2", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags ); if( window == NULL ) { printf( "Nie utworzono okna! Error %s\n", SDL_GetError() ); success = false; } else { int index = -1; Uint32 flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC; renderer = SDL_CreateRenderer( window, index, flags ); if( renderer == NULL ) { printf( "Nie utworzono renderera! Error %s\n", SDL_GetError() ); success = false; } else { SDL_SetRenderDrawColor( renderer, 11, 11, 11, 0xFF ); if( !( IMG_Init( IMG_INIT_PNG )&IMG_INIT_PNG ) ) { printf( "Nie zainicjowano IMG Error %s\n", IMG_GetError() ); success = false; } if( TTF_Init() < 0 ) { printf( "Nie zainicjowano TTF Error %s\n", TTF_GetError() ); success = false; } else if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "Nie zainicjowano MIX Error %s\n", Mix_GetError() ); success = false; } else if( !load() ) { printf( "Nie wczytano wszystkich obiektow!\n" ); success = false; } } } } return success; }
void Texture::load() { SDL_Surface *surface; GLuint textureid; int texture_format_in; int texture_format_out; surface = IMG_Load(this->filename.c_str()); if (!surface) { throw util::Error("Could not load texture from '%s': %s", filename.c_str(), IMG_GetError()); } else { log::dbg1("Loaded texture from '%s'", filename.c_str()); } // glTexImage2D format determination switch (surface->format->BytesPerPixel) { case 3: // RGB 24 bit texture_format_in = GL_RGB8; texture_format_out = GL_RGB; break; case 4: // RGBA 32 bit texture_format_in = GL_RGBA8; texture_format_out = GL_RGBA; break; default: throw util::Error("Unknown texture bit depth for '%s': %d bytes per pixel)", filename.c_str(), surface->format->BytesPerPixel); break; } this->w = surface->w; this->h = surface->h; // generate 1 texture handle glGenTextures(1, &textureid); glBindTexture(GL_TEXTURE_2D, textureid); // sdl surface -> opengl texture glTexImage2D( GL_TEXTURE_2D, 0, texture_format_in, surface->w, surface->h, 0, texture_format_out, GL_UNSIGNED_BYTE, surface->pixels ); // later drawing settings glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); SDL_FreeSurface(surface); this->id = textureid; if (use_metafile) { // change the suffix to .docx (lol) size_t m_len = filename.length() + 2; char *meta_filename = new char[m_len]; strncpy(meta_filename, filename.c_str(), m_len - 5); strncpy(meta_filename + m_len - 5, "docx", 5); log::msg("loading meta file %s", meta_filename); // get subtexture information by meta file exported by script this->subtextures = util::read_csv_file<gamedata::subtexture>(meta_filename); this->subtexture_count = this->subtextures.size(); // TODO: use information from empires.dat for that, also use x and y sizes: this->atlas_dimensions = sqrt(this->subtexture_count); delete[] meta_filename; } else { // we don't have a texture description file. // use the whole image as one texture then. gamedata::subtexture s{0, 0, this->w, this->h, this->w/2, this->h/2}; this->subtexture_count = 1; this->subtextures.push_back(s); } glGenBuffers(1, &this->vertbuf); }
int WinMain() { #else int main() { #endif try { if(SDL_Init(SDL_INIT_VIDEO) < 0) { throw Game::SDLError(); } { int imgFlags = IMG_INIT_PNG; if(!(IMG_Init(imgFlags) & imgFlags)) { throw Game::SDLError(IMG_GetError()); } } if (TTF_Init() < 0) { throw Game::SDLError(TTF_GetError()); } if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { printf("Error starting SDL_Mix: %s\n", Mix_GetError()); } auto gs = std::make_shared<Game::sdl_info>("Letvezi", "art/font.ttf"); auto persistent = std::make_shared<Persistent>("user_info.dat"); if (persistent == NULL) throw std::runtime_error("Failed to create user settings object"); gs->loading_screen([persistent](auto& ch) { auto set_bg = [&ch](std::string file) { ch.push(std::tuple<std::string,std::function<void(Game::sdl_info&)>>( "background music", [file](auto& gs) { gs.set_background(file); } ) ); }; auto load_sfx = [&ch](std::string key, Game::SFX_ID xkey, std::string file) { ch.push( std::tuple<std::string,std::function<void(Game::sdl_info&)>>( key, [xkey,file](auto& gs) { gs.load_sfx(xkey,file); } ) ); }; auto load_png = [&ch](std::string key, Game::TextureID xkey, std::string file) { ch.push( std::tuple<std::string,std::function<void(Game::sdl_info&)>>( key, [xkey,file](auto& gs) { gs.load_png(xkey,file); } ) ); }; auto do_ = [&ch](std::string key, std::function<void()> fn) { ch.push( std::tuple<std::string,std::function<void(Game::sdl_info&)>>( key, [fn](auto&) { fn(); } )); }; set_bg("art/background.ogg"); load_png("bg_star" , Game::TEX_BackgroundStar , "art/img/bg_star.png" ); load_png("player" , Game::TEX_Player , "art/img/player.png" ); load_png("player_laser" , Game::TEX_PlayerLaser , "art/img/player_laser.png" ); load_png("player_life" , Game::TEX_PlayerLife , "art/img/player_life.png" ); load_png("player_shield" , Game::TEX_PlayerShield , "art/img/player_shield.png" ); load_png("enemy_1" , Game::TEX_Enemy1 , "art/img/enemy_1.png" ); load_png("enemy_2" , Game::TEX_Enemy2 , "art/img/enemy_2.png" ); load_png("enemy_3" , Game::TEX_Enemy3 , "art/img/enemy_3.png" ); load_png("enemy_boss" , Game::TEX_EnemyBoss , "art/img/enemy_boss.png" ); load_png("enemy_laser" , Game::TEX_EnemyLaser , "art/img/enemy_laser.png" ); load_png("enemy_boss_laser", Game::TEX_EnemyBossLaser , "art/img/enemy_boss_laser.png" ); load_png("enemy_boss_squad", Game::TEX_EnemyBossSquad , "art/img/enemy_boss_squad.png" ); load_png("powerup_shield" , Game::TEX_PowerupShield , "art/img/powerup_shield.png" ); load_png("powerup_bolt" , Game::TEX_PowerupBolt , "art/img/powerup_bolt.png" ); load_sfx("player_laser" , Game::SFX_PlayerLaser , "art/sfx/player_laser.ogg" ); load_sfx("shield_enabled" , Game::SFX_ShieldEnabled , "art/sfx/player_laser.ogg" ); do_("user info", [persistent]() { persistent->load(); }); }); Game::Resolution res = gs->get_current_res(); Letvezi::GameState::Type start_state = Letvezi::GameState::Type(persistent, gs, res, Letvezi::Position(res.width/2, res.height-70-gs->textures().at(Game::TEX_Player).height)); std::function<void(Conc::Chan<SDL_Event>&,Conc::Chan<Letvezi::Events::Type>&)> event_fn = Letvezi::event_handler; std::function<void(Conc::Chan<Letvezi::Events::Type>&,Conc::VarL<Letvezi::GameState::Type>&)> game_fn = Letvezi::game_handler; std::function<Game::LSit(Conc::VarL<Letvezi::GameState::Type>&,uint16_t)> render_fn = [gs](Conc::VarL<Letvezi::GameState::Type>& typ,uint16_t fps_rel) { return Letvezi::Render::handler_game(gs,typ,fps_rel); }; std::function<void(Conc::VarL<Letvezi::GameState::Type>&)> expensive_handler = Letvezi::Render::expensive_handler; gs->loop(event_fn, game_fn, expensive_handler, render_fn, start_state); persistent->save(); printf("Game over!\n"); } catch (Game::SDLError& err) { printf("SDL Error: %s\n", err.what()); } std::cout << "SDL_Quit()" << std::endl; SDL_Quit(); return 0; }
GExL::Int32 init() { gWindow = SDL_CreateWindow("GExL Asset Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, gScreenWidth, gScreenHeight, SDL_WINDOW_SHOWN); if (gWindow == NULL) { FLOG(GExL::StatusAppInitFailed) << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl; return GExL::StatusAppInitFailed; } //Create renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); if (gRenderer != NULL) { SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { FLOG(GExL::StatusAppInitFailed) << "SDL_image could not be loaded! IMG_Error: " << IMG_GetError() << std::endl; return GExL::StatusAppInitFailed; } //Initialize SDL_ttf if (TTF_Init() == -1) { FLOG(GExL::StatusAppInitFailed) << "SDL_ttf could not be loaded! TTF_Error: " << TTF_GetError() << std::endl; return GExL::StatusAppInitFailed; } //Initialize SDL_mixer if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { FLOG(GExL::StatusAppInitFailed) << "SDL_Mixer could not be loaded! Mix_Error: " << Mix_GetError() << std::endl; return GExL::StatusAppInitFailed; } } //Asset Handlers must be registerd prior to loading assets and only once per asset type. gAssetManager.RegisterHandler(new(std::nothrow) TextureHandler(gRenderer)); gAssetManager.RegisterHandler(new(std::nothrow) FontHandler(16)); return GExL::StatusAppOK; }
Skybox::Skybox(string right, string left, string top, string bottom, string back, string front) { vector<const GLchar*> faces; faces.push_back(right.c_str()); faces.push_back(left.c_str()); faces.push_back(top.c_str()); faces.push_back(bottom.c_str()); faces.push_back(back.c_str()); faces.push_back(front.c_str()); skyboxProgram.CreateProgram(); skyboxProgram.AddShaderFromFile("Shaders/skyVert.glsl", GL_VERTEX_SHADER); skyboxProgram.AddShaderFromFile("Shaders/skyFrag.glsl", GL_FRAGMENT_SHADER); skyboxProgram.LinkProgram(); glGenTextures(1, &textureID); glActiveTexture(GL_TEXTURE0); SDL_Surface* image = NULL; glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); for(GLuint i = 0; i < faces.size(); i++) { image = IMG_Load(faces[i]); // Check for errors if (image == NULL) { printf("Couldn't load skybox image %s.\nIMG_Error: %s\n", faces[i], IMG_GetError()); break; } // Set pixel mode int pixelMode = GL_RGB; // Check for alpha component and set pixel mode appropriately if (image->format->BytesPerPixel == 4) { pixelMode = GL_RGBA; } glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, pixelMode, image->w, image->h, 0, pixelMode, GL_UNSIGNED_BYTE, image->pixels); glGenerateMipmap(GL_TEXTURE_2D); SDL_FreeSurface(image); image = NULL; } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); GLfloat skyboxVertices[] = { // Positions -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; skyboxVAO.Create(); skyboxVBO.Create(); skyboxVAO.Bind(); skyboxVBO.Bind(); skyboxVBO.AddData(&skyboxVertices, sizeof(skyboxVertices)); skyboxVBO.UploadData(); skyboxVAO.EnableAttribute(0); skyboxVAO.ConfigureAttribute(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GLfloat), (GLvoid*)0); skyboxVAO.Unbind(); }
bool LTexture::loadFromFile( std::string path ) { //Get rid of preexisting texture free(); //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); if( loadedSurface == NULL ) { printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() ); } else { //Convert surface to display format SDL_Surface* formattedSurface = SDL_ConvertSurfaceFormat( loadedSurface, SDL_PIXELFORMAT_RGBA8888, NULL ); if( formattedSurface == NULL ) { printf( "Unable to convert loaded surface to display format! %s\n", SDL_GetError() ); } else { //Create blank streamable texture newTexture = SDL_CreateTexture( gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, formattedSurface->w, formattedSurface->h ); if( newTexture == NULL ) { printf( "Unable to create blank texture! SDL Error: %s\n", SDL_GetError() ); } else { //Enable blending on texture SDL_SetTextureBlendMode( newTexture, SDL_BLENDMODE_BLEND ); //Lock texture for manipulation SDL_LockTexture( newTexture, &formattedSurface->clip_rect, &mPixels, &mPitch ); //Copy loaded/formatted surface pixels memcpy( mPixels, formattedSurface->pixels, formattedSurface->pitch * formattedSurface->h ); //Get image dimensions mWidth = formattedSurface->w; mHeight = formattedSurface->h; //Get pixel data in editable format Uint32* pixels = (Uint32*)mPixels; int pixelCount = ( mPitch / 4 ) * mHeight; //Map colors Uint32 colorKey = SDL_MapRGB( formattedSurface->format, 0, 0xFF, 0xFF ); Uint32 transparent = SDL_MapRGBA( formattedSurface->format, 0x00, 0xFF, 0xFF, 0x00 ); //Color key pixels for( int i = 0; i < pixelCount; ++i ) { if( pixels[ i ] == colorKey ) { pixels[ i ] = transparent; } } //Unlock texture to update SDL_UnlockTexture( newTexture ); mPixels = NULL; } //Get rid of old formatted surface SDL_FreeSurface( formattedSurface ); } //Get rid of old loaded surface SDL_FreeSurface( loadedSurface ); } //Return success mTexture = newTexture; return mTexture != NULL; }
bool Texture::loadFromFile(const std::string& path, SDL_Renderer*& renderer, const double zoomX, const double zoomY) { destroy(); SDL_Texture* newTexture = nullptr; SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); if( loadedSurface == nullptr ) { SDL_LogMessage(SDL_LOG_CATEGORY_VIDEO, SDL_LOG_PRIORITY_ERROR, "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); } else { if (zoomX != 1 && zoomY != 1) { SDL_Surface* zoomedSurface = zoomSurface( loadedSurface, zoomX, zoomY, SMOOTHING_OFF ); if (zoomedSurface != nullptr) { SDL_FreeSurface( loadedSurface ); loadedSurface = nullptr; loadedSurface = zoomedSurface; } else { SDL_LogMessage(SDL_LOG_CATEGORY_VIDEO, SDL_LOG_PRIORITY_WARN, "Unable to resize image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); } } if (SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, transparentColor.r, transparentColor.g, transparentColor.b ) ) != 0) { SDL_LogMessage(SDL_LOG_CATEGORY_VIDEO, SDL_LOG_PRIORITY_WARN, "Unable to set transparent color."); } newTexture = SDL_CreateTextureFromSurface( renderer, loadedSurface ); if( newTexture == nullptr ) { SDL_LogMessage(SDL_LOG_CATEGORY_VIDEO, SDL_LOG_PRIORITY_ERROR, "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() ); } else { pixelWidth = loadedSurface->w; pixelHeight = loadedSurface->h; } SDL_FreeSurface( loadedSurface ); loadedSurface = nullptr; } texture = newTexture; return texture != NULL; }
gboolean hello_world_init (HelloWorld* self) { gboolean result = FALSE; gint _tmp0_ = 0; gint _tmp3_ = 0; gboolean _tmp6_ = FALSE; SDL_Window* _tmp8_ = NULL; SDL_Window* _tmp9_ = NULL; SDL_Window* _tmp12_ = NULL; SDL_Renderer* _tmp13_ = NULL; SDL_Renderer* _tmp14_ = NULL; SDL_Renderer* _tmp17_ = NULL; gint imgInitFlags = 0; gint initResult = 0; gint _tmp18_ = 0; gint _tmp19_ = 0; gint _tmp20_ = 0; gint _tmp21_ = 0; gint _tmp22_ = 0; g_return_val_if_fail (self != NULL, FALSE); _tmp0_ = SDL_Init ((guint32) SDL_INIT_VIDEO); if (_tmp0_ < 0) { FILE* _tmp1_ = NULL; const gchar* _tmp2_ = NULL; _tmp1_ = stdout; _tmp2_ = SDL_GetError (); fprintf (_tmp1_, "SDL could not initialize! SDL Error: %s\n", _tmp2_); result = FALSE; return result; } _tmp3_ = IMG_Init ((gint) IMG_INIT_PNG); if (_tmp3_ < 0) { FILE* _tmp4_ = NULL; const gchar* _tmp5_ = NULL; _tmp4_ = stdout; _tmp5_ = IMG_GetError (); fprintf (_tmp4_, "SDL_image could not initialize! SDL_image Error: %s\n", _tmp5_); result = FALSE; return result; } _tmp6_ = SDL_SetHint ("SDL_RENDER_SCALE_QUALITY", "1"); if (!_tmp6_) { FILE* _tmp7_ = NULL; _tmp7_ = stdout; fputs ("Warining: Linear texture filtering not enabled!", _tmp7_); } _tmp8_ = SDL_CreateWindow ("SDL Tutorial", (gint) SDL_WINDOWPOS_CENTERED_MASK, (gint) SDL_WINDOWPOS_CENTERED_MASK, HELLO_WORLD_SCREEN_WIDTH, HELLO_WORLD_SCREEN_HEIGHT, (guint32) SDL_WINDOW_SHOWN); _SDL_DestroyWindow0 (self->priv->window); self->priv->window = _tmp8_; _tmp9_ = self->priv->window; if (_tmp9_ == NULL) { FILE* _tmp10_ = NULL; const gchar* _tmp11_ = NULL; _tmp10_ = stdout; _tmp11_ = SDL_GetError (); fprintf (_tmp10_, "Window could not be created! SDL Error: %s\n", _tmp11_); result = FALSE; return result; } _tmp12_ = self->priv->window; _tmp13_ = SDL_CreateRenderer (_tmp12_, -1, (guint32) (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)); _SDL_DestroyRenderer0 (self->priv->renderer); self->priv->renderer = _tmp13_; _tmp14_ = self->priv->renderer; if (_tmp14_ == NULL) { FILE* _tmp15_ = NULL; const gchar* _tmp16_ = NULL; _tmp15_ = stdout; _tmp16_ = SDL_GetError (); fprintf (_tmp15_, "Renderer could not be created! SDL Error: %s\n", _tmp16_); result = FALSE; return result; } _tmp17_ = self->priv->renderer; SDL_SetRenderDrawColor (_tmp17_, (guint8) 0xFF, (guint8) 0xFF, (guint8) 0xFF, (guint8) SDL_ALPHA_OPAQUE); imgInitFlags = (gint) IMG_INIT_PNG; _tmp18_ = imgInitFlags; _tmp19_ = IMG_Init (_tmp18_); initResult = _tmp19_; _tmp20_ = initResult; _tmp21_ = imgInitFlags; _tmp22_ = imgInitFlags; if ((_tmp20_ & _tmp21_) != _tmp22_) { FILE* _tmp23_ = NULL; const gchar* _tmp24_ = NULL; _tmp23_ = stdout; _tmp24_ = IMG_GetError (); fprintf (_tmp23_, "SDL_image could not initialize! SDL_image Error: %s\n", _tmp24_); result = FALSE; return result; } result = TRUE; return result; }
static void raise_failure(void) { raise_with_string(*caml_named_value("SDL_failure"), IMG_GetError()); }
//Starts up SDL and creates window bool Application::init() { //Initialization flag bool success = true; if (TTF_Init() == -1) { printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError()); success = false; } int result = 0; int flags = MIX_INIT_MP3; //Initialize SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Set texture filtering to linear if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { printf("Warning: Linear texture filtering not enabled!"); } //Create window gWindow = SDL_CreateWindow("Rally", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (gWindow == NULL) { printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Create vsynced renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (gRenderer == NULL) { printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); success = false; } if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 640) < 0) { printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); success = false; } if (flags != (result = Mix_Init(flags))) { printf("Could not initialize mixer (result: %d).\n", result); printf("Mix_Init: %s\n", Mix_GetError()); std::exit(1); } } } } return success; }
SDL_Surface* loadSurface( const std::string& path, SDL_PixelFormat* format) { //Load image at specified path SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); if( loadedSurface == NULL) { std::cout << std::string("Unable to load image ") + path + "! SDL_image Error: " + IMG_GetError() + "\n"; //TODO it would be okay for now, but then we need to specify the exception throw std::exception(); } if(format) { //The optimized image SDL_Surface* optimizedSurface = SDL_ConvertSurface( loadedSurface, format, NULL ); if( optimizedSurface != NULL ) { //Get rid of old loaded surface SDL_FreeSurface( loadedSurface ); return optimizedSurface; } std::cout << "Unable to optimize image " + path + "! SDL Error: " + SDL_GetError() + "\n"; } return loadedSurface; }
Graphics::Texture* ResourceManager::texture(const string& filename) { if (_textures.count(filename)) { return _textures.at(filename).get(); } string ext = filename.substr(filename.length() - 4); Graphics::Texture* texture = nullptr; if (ext == ".png") { // @fixme: this section looks quite ugly. we should try to do something with it someday SDL_Surface* tempSurface = IMG_Load(string(CrossPlatform::findFalltergeistDataPath() + "/" +filename).c_str()); if (tempSurface == NULL) { throw Exception("ResourceManager::texture(name) - cannot load texture from file " + filename + ": " + IMG_GetError()); } SDL_PixelFormat* pixelFormat = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888); SDL_Surface* tempSurface2 = SDL_ConvertSurface(tempSurface, pixelFormat, 0); texture = new Graphics::Texture(tempSurface2); SDL_FreeFormat(pixelFormat); SDL_FreeSurface(tempSurface); SDL_FreeSurface(tempSurface2); } else if (ext == ".rix") { auto rix = rixFileType(filename); if (!rix) return nullptr; texture = new Graphics::Texture(rix->width(), rix->height()); texture->loadFromRGBA(rix->rgba()); } else if (ext == ".frm") { auto frm = frmFileType(filename); if (!frm) return nullptr; texture = new Graphics::Texture(frm->width(), frm->height()); texture->loadFromRGBA(frm->rgba(palFileType("color.pal"))); texture->setMask(*frm->mask(palFileType("color.pal"))); } else { throw Exception("ResourceManager::surface() - unknown image type:" + filename); } _textures.insert(make_pair(filename, unique_ptr<Graphics::Texture>(texture))); return texture; }