示例#1
0
bool Image::initialize ( SDL_Surface* source )
{
  // Discover the optimal pixel format using gathered device capabilities
  RendererInfo caps = RenderWindow::caps( RenderWindow::context() );

  if ( source == nullptr )
  {
    NOM_LOG_ERR ( NOM, "Could not initialize Image from existing surface: NULL" );
    priv::FreeSurface ( source );
    return false;
  }

  this->image_.reset ( SDL_ConvertSurfaceFormat ( source, caps.optimal_texture_format(), 0 ), priv::FreeSurface );

  if ( this->valid() == false )
  {
    NOM_LOG_ERR ( NOM, "Could not initialize Image from existing surface: " + std::string(SDL_GetError()) );
    priv::FreeSurface ( source );
    return false;
  }

  priv::FreeSurface ( source );

  return true;
}
示例#2
0
NP::Texture
SDL2Renderer::load(const char *filename, bool cache)
{
    std::string fn(filename);

    if (cache) {
        // Cache lookup
        for (auto &item: m_texture_cache) {
            if (item.first == fn) {
                return item.second;
            }
        }
    }

    std::string f = Config::findFile(filename);

    SDL_Surface *img = IMG_Load(f.c_str());
    SDL_Surface *tmp = SDL_ConvertSurfaceFormat(img, SDL_PIXELFORMAT_ABGR8888, 0);
    SDL_FreeSurface(img);

    NP::Texture result = GLRenderer::load((unsigned char *)tmp->pixels, img->w, img->h);
    SDL_FreeSurface(tmp);

    if (cache) {
        // Store loaded image in cache
        m_texture_cache[fn] = result;
    }

    return result;
}
示例#3
0
// Routine for loading color keyed textures and doing all the stupid stuff that comes with it
SDL_Texture* Graphics::LoadTexture(const char* sprite_sheet)
{
	// load the image
	SDL_Surface *surface = SDL_LoadBMP(sprite_sheet);
	if (!surface) {
		return NULL;
	}

	// create a duplicate of the surface with the same pixel format as the window
	SDL_Surface *newSurface = SDL_ConvertSurfaceFormat(surface, SDL_GetWindowPixelFormat(gWindow), 0);

	// no longer need to hang on to the original image
	SDL_FreeSurface(surface);

	if (!newSurface) {
		return NULL;
	}

	// set (255,0,255) as the transparent color
	if (SDL_SetColorKey(newSurface, SDL_TRUE, SDL_MapRGB(newSurface->format, 255, 0, 255))) {
		return NULL;
	}

	// create a renderable texture from the image
	SDL_Texture *texture = SDL_CreateTextureFromSurface(gRenderer, newSurface);

	// no longer need to hang on to the converted image
	SDL_FreeSurface(newSurface);

	return texture;
}
bool DataStream::loadMedia()
{
    bool success = true;

    for (int i = 0; i < 4; ++i)
    {
        char path[64] = "";
        sprintf_s(path, "42_texture_streaming/foo_walk_%d.png", i);

        SDL_Surface* loadedSurface = IMG_Load(path);
        if (loadedSurface == NULL)
        {
            printf("Unable to load %s! SDL_image error: %s\n", path, IMG_GetError());
            success = false;
        }
        else
        {
            mImages[i] = SDL_ConvertSurfaceFormat(loadedSurface, SDL_PIXELFORMAT_RGBA8888, NULL);
        }

        SDL_FreeSurface(loadedSurface);
    }

    return success;
}
示例#5
0
 static SDL_Surface* CopySurface(SDL_Surface* surface)
 {
     return SDL_ConvertSurfaceFormat(
         surface,
         PixelFormat,
         0);
 }
示例#6
0
	void* BaseManager::loadImage(int& _width, int& _height, MyGUI::PixelFormat& _format, const std::string& _filename)
	{
		std::string fullname = MyGUI::OpenGLESDataManager::getInstance().getDataPath(_filename);
		void* result = nullptr;
		SDL_Surface *image = nullptr;
		SDL_Surface *cvtImage = nullptr;		// converted surface with RGBA/RGB pixel format
		image = IMG_Load(fullname.c_str());
		MYGUI_ASSERT(image != nullptr, "Failed to load image: " + fullname);

		_width = image->w;
		_height = image->h;

		int bpp = image->format->BytesPerPixel;
		if (bpp < 3)
		{
			result = convertPixelData(image, _format);
		}
		else
		{
			Uint32 pixelFmt = bpp == 3 ? SDL_PIXELFORMAT_BGR24 : SDL_PIXELFORMAT_ARGB8888;
			cvtImage = SDL_ConvertSurfaceFormat(image, pixelFmt, 0);
			result = convertPixelData(cvtImage, _format);
			SDL_FreeSurface(cvtImage);
		}
		SDL_FreeSurface(image);

		return result;
	}
示例#7
0
SDL_Surface* Image::clone ( void ) const
{
  // Find the optimal pixel format
  RendererInfo caps = RenderWindow::caps( RenderWindow::context() );

  return SDL_ConvertSurfaceFormat ( this->image(), caps.optimal_texture_format(), 0 );
}
示例#8
0
bool NXFont::InitChars(TTF_Font *font, uint32_t color)
{
SDL_Color fgcolor;
SDL_Surface *letter;

	fgcolor.r = (uint8_t)(color >> 16);
	fgcolor.g = (uint8_t)(color >> 8);
	fgcolor.b = (uint8_t)(color);
	
	char str[2];
	str[1] = 0;
	
	for(int i=1;i<NUM_LETTERS_RENDERED;i++)
	{
		str[0] = i;
		
		letter = TTF_RenderText_Solid(font, str, fgcolor);
		if (!letter)
		{
			staterr("InitChars: failed to render character %d: %s", i, TTF_GetError());
			return 1;
		}
		
		Uint32 format = screen->Format()->format;
		letters[i] = SDL_ConvertSurfaceFormat(letter, format, SDL_RLEACCEL);

		SDL_FreeSurface(letter);
	}
	
	return 0;
}
示例#9
0
int Pygame_SDL2_SaveJPEG(SDL_Surface *surface, const char *file) {

    SDL_Surface *rgb_surf;
    JSAMPROW *samples;
    int i, rv;

    rgb_surf = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGB24, 0);

    if (! rgb_surf) {
        return -1;
    }

    samples = (JSAMPROW *) malloc (sizeof(JSAMPROW) * rgb_surf->h);

    if (!samples) {
        SDL_FreeSurface(rgb_surf);
        return -1;
    }

    /* copy pointers to the scanlines... since they might not be packed.
     */
    for (i = 0; i < rgb_surf->h; i++) {
        samples[i] = ((unsigned char*)rgb_surf->pixels) + i * rgb_surf->pitch;
    }

    rv = write_jpeg (file, samples, surface->w, surface->h, 90);

    free(samples);
    SDL_FreeSurface(rgb_surf);

    return rv;
}
int PL_Texture_BlitSurface(int textureRefID, SDL_Surface *surface, const SDL_Rect *rect) {
    TextureRef *textureref = (TextureRef*)PL_Handle_GetData(textureRefID, DXHANDLE_TEXTURE);
    SDL_Texture *texture;
    if (textureref == NULL || textureref->texture == NULL) {
        return -1;
    }
    
    texture = textureref->texture;
    
    /* Convert to target format if different. */
    if (textureref->format != surface->format->format) {
        SDL_Surface *tempSurface = SDL_ConvertSurfaceFormat(surface, textureref->format, 0);
        if (SDL_MUSTLOCK(tempSurface)) {
            SDL_LockSurface(tempSurface);
            SDL_UpdateTexture(texture, rect, tempSurface->pixels, tempSurface->pitch);
            SDL_UnlockSurface(tempSurface);
        } else {
            SDL_UpdateTexture(texture, rect, tempSurface->pixels, tempSurface->pitch);
        }
        SDL_FreeSurface(tempSurface);
    } else {
        if (SDL_MUSTLOCK(surface)) {
            SDL_LockSurface(surface);
            SDL_UpdateTexture(texture, rect, surface->pixels, surface->pitch);
            SDL_UnlockSurface(surface);
        } else {
            SDL_UpdateTexture(texture, rect, surface->pixels, surface->pitch);
        }
    }
    
    return 0;
}
示例#11
0
static bool sdl2_gfx_read_viewport(void *data, uint8_t *buffer)
{
   SDL_Surface *surf = NULL, *bgr24 = NULL;
   sdl2_video_t *vid = (sdl2_video_t*)data;

   RARCH_PERFORMANCE_INIT(sdl2_gfx_read_viewport);
   RARCH_PERFORMANCE_START(sdl2_gfx_read_viewport);

   video_driver_cached_frame();

   surf  = SDL_GetWindowSurface(vid->window);
   bgr24 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_BGR24, 0);

   if (!bgr24)
   {
      RARCH_WARN("Failed to convert viewport data to BGR24: %s", SDL_GetError());
      return false;
   }

   memcpy(buffer, bgr24->pixels, bgr24->h * bgr24->pitch);

   RARCH_PERFORMANCE_STOP(sdl2_gfx_read_viewport);

   return true;
}
示例#12
0
void loadPicture(std::string file, GLuint tex){

    if(file.find(".png")!=string::npos){
        loadPNG(file.c_str(),tex);
        cout<<"Loaded: "<<file<<endl;
    }

	if(file.find(".bmp")==string::npos)
		return;

	cout<<"Loading: "<<file<<endl;


	SDL_Surface *image;
	SDL_Surface *fixed;
	image = SDL_LoadBMP(file.c_str());

	if(!image){
		cerr<<"error loading:"<<file;
		return;
		//system("pause");
	}

	fixed=SDL_ConvertSurfaceFormat(image,SDL_PIXELFORMAT_ABGR8888,0);
    //SDL_SetColorKey(fixed,SDL_TRUE,0xFF00FF);

	if(!fixed){
		cerr<<"error loading:"<<file;
		return;
		//system("pause");
	}



	//if(!(is2Pwr(image->w)&&is2Pwr(image->h)))
	//	cerr<<"image is not power of 2 it may load incorrectly"<<endl;
	// handle error

	glBindTexture(GL_TEXTURE_2D,tex);

	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
	//if(alpha)
	//glTexImage2D( GL_TEXTURE_2D, 0, 4, image->w, image->h, 0,GL_BGRA, GL_UNSIGNED_BYTE, image->pixels );
	//else
	glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, image->w, image->h, 0,GL_RGBA, GL_UNSIGNED_BYTE, fixed->pixels );

	if ( image ) {
		SDL_FreeSurface( image );
	}

}
示例#13
0
void
WIN_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
{
    HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd;
    HICON hicon = NULL;
    BYTE *icon_bmp;
    int icon_len;
    SDL_RWops *dst;
    SDL_Surface *surface;

    /* Create temporary bitmap buffer */
    icon_len = 40 + icon->h * icon->w * 4;
    icon_bmp = SDL_stack_alloc(BYTE, icon_len);
    dst = SDL_RWFromMem(icon_bmp, icon_len);
    if (!dst) {
        SDL_stack_free(icon_bmp);
        return;
    }

    /* Write the BITMAPINFO header */
    SDL_WriteLE32(dst, 40);
    SDL_WriteLE32(dst, icon->w);
    SDL_WriteLE32(dst, icon->h * 2);
    SDL_WriteLE16(dst, 1);
    SDL_WriteLE16(dst, 32);
    SDL_WriteLE32(dst, BI_RGB);
    SDL_WriteLE32(dst, icon->h * icon->w * 4);
    SDL_WriteLE32(dst, 0);
    SDL_WriteLE32(dst, 0);
    SDL_WriteLE32(dst, 0);
    SDL_WriteLE32(dst, 0);

    /* Convert the icon to a 32-bit surface with alpha channel */
    surface = SDL_ConvertSurfaceFormat(icon, SDL_PIXELFORMAT_ARGB8888, 0);
    if (surface) {
        /* Write the pixels upside down into the bitmap buffer */
        int y = surface->h;
        while (y--) {
            Uint8 *src = (Uint8 *) surface->pixels + y * surface->pitch;
            SDL_RWwrite(dst, src, surface->pitch, 1);
        }
        SDL_FreeSurface(surface);

/* TODO: create the icon in WinCE (CreateIconFromResource isn't available) */
#ifndef _WIN32_WCE
        hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
#endif
    }
    SDL_RWclose(dst);
    SDL_stack_free(icon_bmp);

    /* Set the icon for the window */
    SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);

    /* Set the icon in the task manager (should we do this?) */
    SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
}
示例#14
0
文件: bitmap.cpp 项目: Lobomon/mkxp
	static void ensureFormat(SDL_Surface *&surf, Uint32 format)
	{
		if (surf->format->format == format)
			return;

		SDL_Surface *surfConv = SDL_ConvertSurfaceFormat(surf, format, 0);
		SDL_FreeSurface(surf);
		surf = surfConv;
	}
示例#15
0
文件: Texture.cpp 项目: neo333/XGame
	void Texture::LoadTexture_fromMemoryPage(const MemoryPage& input_page, const ScreenVideo& makerVideo) throw(Error){
		this->Clean();
		if(makerVideo.m_renderer==nullptr)
			throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile caricare una texture con uno specifico renderer nullo!");
		if(makerVideo.m_renderer!=m_render) m_render = makerVideo.m_renderer;
		if(input_page.GetSize()==0) return;
		if(m_render==nullptr) 
			throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile caricare la texture richiesta!\nRenderer non inizializzato!");

		SDL_RWops* data_access = SDL_RWFromConstMem(input_page.Get_PtrMemory(),input_page.GetSize());
		if(data_access==nullptr){
			throw Error("Texture","LoadTexture_fromMemoryPage","Pagina di memoria corrotta!\n%s",SDL_GetError());
		}else{
			SDL_Surface* image_load = IMG_Load_RW(data_access,1);
			if(image_load==nullptr){
				throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile caricare correttamente la texture richiesta\n%s",SDL_GetError());
			}else{
				SDL_Surface* image_opt = SDL_ConvertSurfaceFormat(image_load,SDL_PIXELFORMAT_RGBA8888,0);
				SDL_FreeSurface(image_load);
				image_load=nullptr;
				if(image_opt==nullptr){
					throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile ottimizzare correttamente la texture richiesta\n%s",SDL_GetError());
				}

				this->m_texture = SDL_CreateTexture(m_render,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_STREAMING,image_opt->w,image_opt->h);
				if(this->m_texture==nullptr){
					SDL_FreeSurface(image_opt);
					throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile creare una texture grafica!\n%s",SDL_GetError());
				}

				void* data_pixel_texture;
				int pitch_pixel_texture;

				if(SDL_LockTexture(m_texture,NULL,&data_pixel_texture,&pitch_pixel_texture)!=0){
					SDL_FreeSurface(image_opt);
					SDL_DestroyTexture(m_texture);
					throw Error("Texture","LoadTexture_fromMemoryPage","Impossibile scrivere la texture grafica!\n%s",SDL_GetError());
				}
				memcpy(data_pixel_texture,image_opt->pixels,image_opt->pitch * image_opt->h);
				SDL_UnlockTexture(m_texture);
				data_pixel_texture=nullptr;

				m_w_size = image_opt->w;
				m_h_size = image_opt->h;
				m_w_size_scaled = image_opt->w;
				m_h_size_scaled = image_opt->h;
				m_drawnable_area.Set_AllComponent(0,0,image_opt->w,image_opt->h);
				m_alpha_mod = SDL_ALPHA_OPAQUE;
				
				SDL_FreeSurface(image_opt);
				image_opt=nullptr;

				SDL_SetTextureBlendMode(m_texture,SDL_BLENDMODE_BLEND);
			}
		}
	}
TextureLoaderSDLSurfaceImpl::TextureLoaderSDLSurfaceImpl(SDL_Surface * surface):
    m_surface(nullptr)
{
    auto format = surface->format->format;

    switch (format)
    {
    case SDL_PIXELFORMAT_RGB888:
        m_surface = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGB888, 0);
        break;
    case SDL_PIXELFORMAT_RGBA8888:
    case SDL_PIXELFORMAT_ARGB8888:
    case SDL_PIXELFORMAT_ABGR8888:
        m_surface = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA8888, 0);
        break;
    default:
        Fail(std::string("Yet unsupported SDL Format: ") + SDL_GetPixelFormatName(format));
    }
}
示例#17
0
 void convert()
 {
     SDL_Surface *convertedSurface =
         SDL_ConvertSurfaceFormat(surface_,
                                  SDL_PIXELFORMAT_ABGR8888, 0);
     if (convertedSurface == 0) {
         throw std::runtime_error(std::string("Failed to convert image to RGBA format: ") +
                                  SDL_GetError());
     }
     SDL_FreeSurface(surface_);
     surface_ = convertedSurface;
 }
示例#18
0
TexturePtr
TextureManager::create_image_texture_raw(const std::string& filename, const Rect& rect)
{
  SDL_Surface *image = nullptr;

  Surfaces::iterator i = m_surfaces.find(filename);
  if (i != m_surfaces.end())
  {
    image = i->second;
  }
  else
  {
    image = IMG_Load_RW(get_physfs_SDLRWops(filename), 1);
    if (!image)
    {
      std::ostringstream msg;
      msg << "Couldn't load image '" << filename << "' :" << SDL_GetError();
      throw std::runtime_error(msg.str());
    }

    m_surfaces[filename] = image;
  }

  SDL_PixelFormat* format = image->format;
  if(format->Rmask == 0 && format->Gmask == 0 && format->Bmask == 0 && format->Amask == 0) {
    log_debug << "Wrong surface format for image " << filename << ". Compensating." << std::endl;
    image = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_RGBA8888, 0);
  }

  SDLSurfacePtr subimage(SDL_CreateRGBSurfaceFrom(static_cast<uint8_t*>(image->pixels) +
                                                  rect.top * image->pitch +
                                                  rect.left * image->format->BytesPerPixel,
                                                  rect.get_width(), rect.get_height(),
                                                  image->format->BitsPerPixel,
                                                  image->pitch,
                                                  image->format->Rmask,
                                                  image->format->Gmask,
                                                  image->format->Bmask,
                                                  image->format->Amask));
  if (!subimage)
  {
    throw std::runtime_error("SDL_CreateRGBSurfaceFrom() call failed");
  }

#ifdef OLD_SDL
  if (image->format->palette)
  { // copy the image palette to subimage if present
    SDL_SetSurfacePalette(subimage.get(), image->format->palette->colors);
  }
#endif

  return VideoSystem::current()->new_texture(subimage.get());
}
示例#19
0
OpenGLImage::OpenGLImage(SDL_Surface *surface)
    : Image(std::string()), tex(genTexture(true)), w(surface->w), h(surface->h) {
    int texture_format;
    bool colorNoAlpha = (surface->format->BitsPerPixel == 24 && surface->format->BytesPerPixel==3);
    bool colorAlpha = (surface->format->BitsPerPixel == 32 && surface->format->BytesPerPixel==4);
    uint32_t v255shift24 = 255;
    v255shift24 <<= 24;
    if (colorNoAlpha && surface->format->Rmask == 255 && surface->format->Gmask == (255 << 8) && surface->format->Bmask == (255 << 16)) {
        texture_format = GL_RGB;
#ifndef USE_GLES
    } else if (colorNoAlpha && surface->format->Bmask == 255 && surface->format->Gmask == (255 << 8) && surface->format->Rmask == (255 << 16)) {
        texture_format = GL_BGR;
    } else if (colorAlpha && surface->format->Bmask == 255 && surface->format->Gmask == (255 << 8) && surface->format->Rmask == (255 << 16)  && surface->format->Amask == v255shift24) {
        texture_format = GL_BGRA;
#endif
    } else if (colorAlpha && surface->format->Rmask == 255 && surface->format->Gmask == (255 << 8) && surface->format->Bmask == (255 << 16)  && surface->format->Amask == v255shift24) {
        texture_format = GL_RGBA;
    } else {
#ifdef USE_SDL2
        SDL_Surface *newSurf = SDL_ConvertSurfaceFormat(
                surface, SDL_PIXELFORMAT_ABGR8888, 0);
#else
        SDL_Surface *newSurf = SDL_CreateRGBSurface(
                SDL_SWSURFACE, surface->w, surface->h, 32,
                255, (255 << 8), (255 << 16), v255shift24);
        SDL_Rect r;
        r.x = 0;
        r.y = 0;
        r.w = surface->w;
        r.h = surface->h;
        if ( (surface->flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
            surface->flags &= ~SDL_SRCALPHA;
        }
        SDL_LowerBlit(surface, &r, newSurf, &r);
#endif
        SDL_FreeSurface(surface);
        surface = newSurf;
        texture_format = GL_RGBA;
        colorNoAlpha = false;
        colorAlpha = true;
    }

    if (!SDL_LockSurface(surface)) {
        glTexImage2D( GL_TEXTURE_2D, 0, colorAlpha ? GL_RGBA : GL_RGB, w, h, 0,
                      texture_format, GL_UNSIGNED_BYTE, surface->pixels);
        stage = COMPLETE;
#ifndef EMSCRIPTEN
        SDL_UnlockSurface(surface);
#endif
    }
    SDL_FreeSurface(surface);
}
示例#20
0
static SDL_Surface* load_sdl_surface_from_file(const std::string& Path) {
	SDL_Surface* Surface = IMG_Load(Path.c_str());
	if (!Surface) {
		DEBUG(0, NE_WARNING, "Failed to load image. Surface is nullpointer. Error: " << IMG_GetError());
		return nullptr;
	}
	SDL_Surface *ARGBSurface = SDL_ConvertSurfaceFormat(Surface, SDL_PIXELFORMAT_ARGB8888, 0);
	if (!ARGBSurface) {
		DEBUG(0, NE_WARNING, "Failed call to SDL_ConvertSurfaceFormat. Nullpointer returned.");
	}
	SDL_FreeSurface(Surface);
	return ARGBSurface;
}
示例#21
0
/* implementation */
SDL_Surface* RenderManagerSDL::colorSurface(SDL_Surface *surface, Color color)
{
    // Create new surface
    SDL_Surface *newSurface = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ABGR8888, 0);

    SDL_LockSurface(newSurface);
    for (int p = 0; p < newSurface->w * newSurface->h; ++p)
    {
        SDL_Color* pixel = &(((SDL_Color*)newSurface->pixels)[p]);

        int rr = (int(pixel->r) * int(color.r)) >> 8;
        int rg = (int(pixel->g) * int(color.g)) >> 8;
        int rb = (int(pixel->b) * int(color.b)) >> 8;
        int fak = int(pixel->r) * 5 - 4 * 256 - 138;

        bool colorkey = !(pixel->r | pixel->g | pixel->b);

        if (colorkey)
        {
            pixel->r = 0;
            pixel->g = 0;
            pixel->b = 0;
            pixel->a = 0;
            continue;
        }

        if (fak > 0)
        {
            rr += fak;
            rg += fak;
            rb += fak;
        }
        rr = rr < 255 ? rr : 255;
        rg = rg < 255 ? rg : 255;
        rb = rb < 255 ? rb : 255;

        // This is clamped to 1 because dark colors may would be
        // colorkeyed otherwise
        pixel->r = rr > 0 ? rr : 1;
        pixel->g = rg > 0 ? rg : 1;
        pixel->b = rb > 0 ? rb : 1;

    }
    SDL_UnlockSurface(newSurface);

    // Use a black colorkey
    SDL_SetColorKey(newSurface, SDL_TRUE,
                    SDL_MapRGB(newSurface->format, 0, 0, 0));

    return newSurface;
}
Texture::Texture(SDL_Surface &surface, GLenum texUnit) {
    GLint intFormat;
    GLenum format, type;
    bool recognised;

    _refCount = 0;

    glGenTextures(1, &_GLtexture);
    Logger::logprintf(Logger::LOG_VERBOSEINFO, Logger::LOG_TEXTURES, "Loading SDL Surface 0x%X (Pixel Format %s) to OpenGL name %i and Texture Unit GL_TEXTURE%i\n", &surface,SDL_GetPixelFormatName(surface.format->format), _GLtexture, texUnit - GL_TEXTURE0);

    switch(surface.format->format) {
    case SDL_PIXELFORMAT_ABGR8888:
        intFormat = GL_RGBA8;
        format = GL_RGBA;
        type = GL_UNSIGNED_BYTE;
        recognised = true;
        break;
    case SDL_PIXELFORMAT_ARGB8888:
        intFormat = GL_RGBA8;
        format = GL_BGRA;
        type = GL_UNSIGNED_BYTE;
        recognised = true;
        break;
    default:
        Logger::logprintf(Logger::LOG_WARN, Logger::LOG_TEXTURES, "No mapped GL format for SDL pixel format %s, will be reformatted internally\n", SDL_GetPixelFormatName(surface.format->format));
        recognised = false;
        break;
    }

    glActiveTexture(texUnit);
    glBindTexture( GL_TEXTURE_2D, _GLtexture);
    _loaded = checkGLError("glBindTexture failed: %s\n", Logger::LOG_ERROR );

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        
    if ( recognised ) {
        glTexImage2D( GL_TEXTURE_2D, 0, intFormat, surface.w, surface.h
                    , 0, format, type, surface.pixels );
    } else {
        SDL_Surface *surface_bgra;

        Logger::logprintf(Logger::LOG_INFO, Logger::LOG_TEXTURES, "Converting source SDL pixel format %s to SDL_PIXELFORMAT_ABGR8888\n", SDL_GetPixelFormatName(surface.format->format));
        surface_bgra = SDL_ConvertSurfaceFormat(&surface, SDL_PIXELFORMAT_ABGR8888, 0);
        
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, surface_bgra->w, surface_bgra->h
                    , 0, GL_RGBA, GL_UNSIGNED_BYTE, surface_bgra->pixels );
        SDL_FreeSurface(surface_bgra);
    }
    _loaded &= checkGLError("Failed to load texture from SDL Surface: %s\n", Logger::LOG_ERROR);
}
示例#23
0
 /**
  * @brief Convert The Surface to match Texture Pixel Format
  * @return
  */
 bool convert()
 {
     if (!m_is_converted)
     {
         m_surface = SDL_ConvertSurfaceFormat(m_surface, SDL_PIXELFORMAT_ARGB8888, 0);
         if(!m_surface)
         {
             SDL_Log("Unable to Convert Surface");
             return false;
         }
         m_is_converted = true;
     }
     return true;
 }
示例#24
0
SDL_Surface* Surface::OnLoad(const char* File) {
	SDL_Surface* Surf_Temp = NULL;
	SDL_Surface* Surf_Return = NULL;

	if ((Surf_Temp = SDL_LoadBMP(File)) == NULL) {
		GameError(SDL_GetError());
		return NULL;
	}
	Surf_Return = SDL_ConvertSurfaceFormat(Surf_Temp, SDL_PIXELFORMAT_RGB888, 0);
	//Surf_Return = SDL_DisplayFormat(Surf_Temp);
	SDL_FreeSurface(Surf_Temp);

	return Surf_Return;
}
示例#25
0
Sprite* SpriteManager::CreateSprite(const std::string& filename, int x, int y, int w, int h)
{
	// first we search for if the texture is already loaded
	auto it = m_textures.find(filename);
	if (it == m_textures.end())
	{
		// if not, we create a new one
		SDL_Surface* surface = IMG_Load(filename.c_str());
		SDL_Surface* optimizedSurface;

		if (surface != nullptr)
		{
			optimizedSurface = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ABGR4444, 0);
			SDL_FreeSurface(surface);

			SDL_Texture* texture = SDL_CreateTextureFromSurface(m_renderer, optimizedSurface);

			// we save the texture in the map for later reuse
			m_textures.insert(std::pair<std::string, SDL_Texture*>(filename, texture));

			// we can destroy the surface
			// since we now have a texture
			// that we use instead
			if (optimizedSurface != nullptr)
			{
				SDL_FreeSurface(optimizedSurface);
			}
			else
			{
				const char* error = SDL_GetError();
			}

			// now we get the texture so we can return it with a sprite
			it = m_textures.find(filename);
		}
	}

	// then we create a new sprite 
	// with the texture associated
	Sprite* sprite = new Sprite(it->second);
	sprite->GetRegion()->x = x;
	sprite->GetRegion()->y = y;
	sprite->GetRegion()->w = w;
	sprite->GetRegion()->h = h;
	m_sprites.push_back(sprite);

	// return the newly newed sprite
	return sprite;
}
示例#26
0
/* Adds  background image to the console, x and y based on consoles x and y */
int CON_Background(ConsoleInformation *console, const char *image, int x, int y, SDL_Surface* displayScreen) {
    SDL_Surface *temp;
    SDL_Rect backgroundsrc, backgrounddest;

    if(!console)
        return 1;

    /* Free the background from the console */
    if(image == NULL) {
        if(console->BackgroundImage ==NULL)
            SDL_FreeSurface(console->BackgroundImage);
        console->BackgroundImage = NULL;
        SDL_FillRect(console->InputBackground, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE));
        return 0;
    }

    /* Load a new background */
#ifdef HAVE_SDLIMAGE
    temp = IMG_Load(image);
#else
    temp = SDL_LoadBMP(image);
#endif
    if(!temp) {
        CON_Out(console, "Cannot load background %s.", image);
        return 1;
    }

    //console->BackgroundImage = SDL_DisplayFormat(temp);
    console->BackgroundImage = SDL_ConvertSurfaceFormat(temp, displayScreen->format->format, displayScreen->flags);
    SDL_FreeSurface(temp);
    console->BackX = x;
    console->BackY = y;

    backgroundsrc.x = 0;
    backgroundsrc.y = console->ConsoleSurface->h - console->FontHeight - console->BackY;
    backgroundsrc.w = console->BackgroundImage->w;
    backgroundsrc.h = console->InputBackground->h;

    backgrounddest.x = console->BackX;
    backgrounddest.y = 0;
    backgrounddest.w = console->BackgroundImage->w;
    backgrounddest.h = console->FontHeight;

    SDL_FillRect(console->InputBackground, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE));
    SDL_BlitSurface(console->BackgroundImage, &backgroundsrc, console->InputBackground, &backgrounddest);

    CON_UpdateConsole(console);
    return 0;
}
示例#27
0
bool Image::load_bmp ( const std::string& filename, uint32 pixel_format )
{
  SDL_Surface *buffer = IMG_Load ( filename.c_str() );
  if ( buffer == nullptr )
  {
    NOM_LOG_ERR ( NOM, IMG_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, pixel_format, 0 ), priv::FreeSurface );
  priv::FreeSurface ( buffer );

  return true;
}
示例#28
0
		virtual Bitmap *Load(IStream *stream) {
			SPADES_MARK_FUNCTION();

			// read all
			std::string data = stream->ReadAllBytes();

			auto deleter = [](SDL_Surface *s) { SDL_FreeSurface(s); };

			// copy to buffer
			std::unique_ptr<SDL_Surface, decltype(deleter)> imgraw(LoadSdlImage(data), deleter);
			if (imgraw == nullptr) {
				SPRaise("SDL surface was not loaded.");
			}

			std::unique_ptr<SDL_Surface, decltype(deleter)> img(
			  SDL_ConvertSurfaceFormat(imgraw.get(), SDL_PIXELFORMAT_ABGR8888, 0), deleter);
			if (img == nullptr) {
				SPRaise("SDL surface was loaded, but format conversion failed.");
			}

			const unsigned char *inPixels = (const unsigned char *)img->pixels;
			int width = img->w;
			int height = img->h;
			int pitch = img->pitch;

			Handle<Bitmap> bmp;
			bmp.Set(new Bitmap(width, height), false);
			try {
				unsigned char *outPixels = (unsigned char *)bmp->GetPixels();

				if (pitch == width * 4) {
					// if the pitch matches the requirement of Bitmap,
					// just use it
					memcpy(outPixels, inPixels, pitch * height);
				} else {
					// convert
					for (int y = 0; y < height; y++) {
						memcpy(outPixels, inPixels, width * 4);
						outPixels += width * 4;
						inPixels += pitch;
					}
				}
				return bmp.Unmanage();
			} catch (...) {
				throw;
			}
		}
示例#29
0
/** Create a copy of an SDL surface using a bit format that can be fed straight
 *  to libpng. This will create a surface in 24 bit R, G, B or 32bit R, G, B, A
 *  so that libpng can process it directly, avoiding the need for on-the-fly
 *  format conversion shenanigans.
 *
 *  \param surf  The surface to convert.
 *  \param alpha True if the converted surface should have an alpha channel.
 *  \return A pointer to a copy of the surface in the usable format. The caller must
 *          free this surface when done with it.
 */
static SDL_Surface *make_usable_format(SDL_Surface *surf, int alpha)
{
    // Yes, it's probably horrible to just straight up declare these two, but ffs
    // it takes up all of 80 bytes of stack space for these...
#if SDL_BYTEORDER == SDL_BIG_ENDIAN

    Uint32 f24 = SDL_PIXELFORMAT_BGR24;
    Uint32 f32 = SDL_PIXELFORMAT_ABGR8888;
#else
    Uint32 f24 = SDL_PIXELFORMAT_RGB24;
    Uint32 f32 = SDL_PIXELFORMAT_RGBA8888;
#endif

    // Make a copy of our errant surface
    SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, alpha > 0 ? f32 : f24, 0);

    return rgb_surf;
}
示例#30
0
文件: Button.cpp 项目: j4qfrost/Pyman
void Button::setSource(const string& file)
{
    SDL_Surface* loaded = NULL;
	string ext = file.substr(file.size() - 4);
	if (ext == ".bmp")
		loaded = SDL_LoadBMP(file.c_str());
	else if (ext == ".png")
		loaded = IMG_Load(file.c_str());
	else
		printf("Unsupported format!\n");

    if (loaded != NULL)
    {
        source = SDL_ConvertSurfaceFormat(loaded, surface->getSurface()->format->format,
        									surface->getSurface()->flags);
		SDL_FreeSurface(loaded);
    }
}