Exemplo n.º 1
0
void tglBuildMipmaps(std::vector<TRaster32P> &rasters,
					 const TFilePath &filepath)
{
	assert(rasters.size() > 0);
	TRop::ResampleFilterType resampleFilter = TRop::ClosestPixel;
	TRasterP ras;
	TImageReader::load(filepath, ras);
	int rasLx = ras->getLx();
	int rasLy = ras->getLy();

	int lx = 1;
	while (lx < rasLx)
		lx <<= 1;

	int ly = 1;
	while (ly < rasLy)
		ly <<= 1;

	TRaster32P ras2(lx, ly);
	double sx = (double)lx / (double)ras->getLx();
	double sy = (double)ly / (double)ras->getLy();
#ifndef SCALE_BY_GLU
	TRop::resample(ras2, ras, TScale(sx, sy), resampleFilter);
#else
	ras->lock();
	gluScaleImage(GL_RGBA, ras->getLx(), ras->getLy(), GL_UNSIGNED_BYTE, ras->getRawData(),
				  lx, ly, GL_UNSIGNED_BYTE, ras2->getRawData());
	ras->unlock();
#endif

	rasters[0] = ras2;
	int ras2Lx = ras2->getLx();
	int ras2Ly = ras2->getLy();
	for (int i = 1; i < (int)rasters.size(); ++i) {
		lx >>= 1;
		ly >>= 1;
		if (lx < 1)
			lx = 1;
		if (ly < 1)
			ly = 1;
		rasters[i] = TRaster32P(lx, ly);
		sx = (double)lx / (double)ras2Lx;
		sy = (double)ly / (double)ras2Ly;
		rasters[i] = TRaster32P(lx, ly);
#ifndef SCALE_BY_GLU
		TRop::resample(rasters[i], ras2, TScale(sx, sy), resampleFilter);
#else
		ras2->lock();
		gluScaleImage(GL_RGBA, ras->getLx(), ras->getLy(), GL_UNSIGNED_BYTE, ras2->getRawData(),
					  lx, ly, GL_UNSIGNED_BYTE, rasters[i]->getRawData());
		ras2->unlock();
#endif
	}
}
Exemplo n.º 2
0
int SimulatorGetImageFromScreen (GLubyte *pImage, int nImageWidth, int nImageHeight, GLsizei *p_nViewport)
{	
	int nWidth, nHeight;
	static int nPreviusWidth = 0, nPreviusHeight = 0;
	static GLubyte *pScreenPixels = (GLubyte *) NULL;
	
	nWidth = p_nViewport[2];
	nHeight = p_nViewport[3];
	
	if ((nWidth != nPreviusWidth) || (nHeight != nPreviusHeight))
	{
		delete pScreenPixels;
		if ((pScreenPixels = new GLubyte[3 * nWidth * nHeight]) == (GLubyte *) NULL)
		{
			Error ("Cannot allocate more memory", "", "");
			return (-1);
		}
		nPreviusWidth = nWidth;
		nPreviusHeight = nHeight;
	}
	
	glReadBuffer (GL_BACK);
	glEnable(GL_READ_BUFFER);
	glReadPixels(p_nViewport[0], p_nViewport[1], p_nViewport[2], p_nViewport[3], GL_RGB, GL_UNSIGNED_BYTE, pScreenPixels);
	glDisable(GL_READ_BUFFER);
	gluScaleImage (GL_RGB, nWidth, nHeight, GL_UNSIGNED_BYTE, pScreenPixels, nImageWidth, nImageHeight, GL_UNSIGNED_BYTE, pImage);

	return (0);
}
Exemplo n.º 3
0
/*glu.ScaleImage(format, widthin, heightin, pixelsArrayin, widthout, heightout) -> error, pixelsArrayout */
static int luaglu_scaleimage(lua_State *L)
{
  GLenum format;
  GLfloat *pixelsin, *pixelsout;
  int widthout, heightout, sizeout, depth, error;

  format = luagl_get_gl_enum(L, 1);
  depth = luaglu_get_depth(format);
  if (depth == 0)
    luaL_argerror(L, 1, "unknown format");

  luagl_get_arrayf(L, 4, &pixelsin);

  widthout = luaL_checkinteger(L, 5);
  heightout = luaL_checkinteger(L, 6);
  sizeout = widthout*heightout*depth;

  pixelsout = LUAGL_NEW_ARRAY(GLfloat, sizeout);

  error = gluScaleImage(format, luaL_checkinteger(L, 2), luaL_checkinteger(L, 3), GL_FLOAT, pixelsin,
                                widthout, heightout, GL_FLOAT, pixelsout);
  lua_pushnumber(L, error);

  if (error == 0)
    luagl_push_arrayf(L, pixelsout, sizeout);
  else
    lua_pushnil(L);

  LUAGL_DELETE_ARRAY(pixelsin);
  LUAGL_DELETE_ARRAY(pixelsout);

  return 2;
}
Exemplo n.º 4
0
bool installtex(int tnum, char *texname, int &xs, int &ys, bool clamp)
{
    SDL_Surface *s = IMG_Load(texname);
    if(!s) { conoutf("couldn't load texture %s", texname); return false; };
    if(s->format->BitsPerPixel!=24) { conoutf("texture must be 24bpp: %s", texname); return false; };
    // loopi(s->w*s->h*3) { uchar *p = (uchar *)s->pixels+i; *p = 255-*p; };  
    glBindTexture(GL_TEXTURE_2D, tnum);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //NEAREST);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); 
    xs = s->w;
    ys = s->h;
    while(xs>glmaxtexsize || ys>glmaxtexsize) { xs /= 2; ys /= 2; };
    void *scaledimg = s->pixels;
    if(xs!=s->w)
    {
        conoutf("warning: quality loss: scaling %s", texname);     // for voodoo cards under linux
        scaledimg = alloc(xs*ys*3);
        gluScaleImage(GL_RGB, s->w, s->h, GL_UNSIGNED_BYTE, s->pixels, xs, ys, GL_UNSIGNED_BYTE, scaledimg);
    };
    if(gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, xs, ys, GL_RGB, GL_UNSIGNED_BYTE, scaledimg)) fatal("could not build mipmaps");
    if(xs!=s->w) free(scaledimg);
    SDL_FreeSurface(s);
    return true;
};
Exemplo n.º 5
0
void BL_Texture::InitNonPow2Tex(unsigned int *pix,int x,int y,bool mipmap)
{
	int nx= smaller_pow2(x);
	int ny= smaller_pow2(y);

	unsigned int *newPixels = (unsigned int *)malloc(nx*ny*sizeof(unsigned int));
	
	gluScaleImage(GL_RGBA, x, y, GL_UNSIGNED_BYTE, pix, nx,ny, GL_UNSIGNED_BYTE, newPixels);
	glBindTexture(GL_TEXTURE_2D, mTexture );

	if( mipmap ) {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, nx, ny, GL_RGBA, GL_UNSIGNED_BYTE, newPixels );
	}
	else {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nx, ny, 0, GL_RGBA, GL_UNSIGNED_BYTE, newPixels );
	}

	if (GLEW_EXT_texture_filter_anisotropic)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	free(newPixels);
}
Exemplo n.º 6
0
void
sharpen(void)
{
  if (reset) {
    gluScaleImage(format, width, height, GL_UNSIGNED_BYTE, image,
      width / 4, height / 4, GL_UNSIGNED_BYTE, null);
    gluScaleImage(format, width / 4, height / 4, GL_UNSIGNED_BYTE, null,
      width, height, GL_UNSIGNED_BYTE, null);
    reset = 0;
  }
  glDrawPixels(width, height, format, GL_UNSIGNED_BYTE, image);
  glAccum(GL_LOAD, alpha / 2.);
  glDrawPixels(width, height, format, GL_UNSIGNED_BYTE, null);
  glAccum(GL_ACCUM, (1 - alpha) / 2.);
  glAccum(GL_RETURN, 2.0);
}
Exemplo n.º 7
0
bool CLoadPic::AdjustPic(GLint new_wide, GLint new_height, GLint new_posx, GLint new_posy)
{
	//ת»»Í¼Æ¬´óС
	m_pixelLength = new_wide * 3;

	while((m_pixelLength % 4) != 0 )
	{
		//pixelLength = pixelLength + 4 - ( pixelLength % 4 );
		m_pixelLength++;
	}
	m_pixelLength = m_pixelLength * new_height;
	GLubyte *new_pixelDate = ( GLubyte * )malloc( m_pixelLength );
	if ( m_pixelDate == NULL )
	{
		printf( "\aΪÏñËØÉêÇëÄÚ´æ¿Õ¼äʧ°Ü" );
		return false;
	}
	gluScaleImage(GL_RGB, m_wide, m_height, GL_UNSIGNED_BYTE, m_pixelDate, new_wide, new_height, GL_UNSIGNED_BYTE, new_pixelDate);
	free(m_pixelDate);
	m_pixelDate = new_pixelDate;
	m_wide = new_wide;
    m_height = new_height;
	m_posx = new_posx;
	m_posy = new_posy;
	return true;
}
Exemplo n.º 8
0
	////////////////////////////////////
	// Texture::Image::Resize
	void Texture::Image::Resize(float newWidth, float newHeight)
	{
		if(!this->data)
			return;

		if(newHeight <0)
		{
			newHeight = this->height * (newWidth/this->width);
		}

		unsigned char* newData = new unsigned char[ newWidth * newHeight * this->components];
		gluScaleImage (
				this->format,
				this->width,
				this->height,
				GL_UNSIGNED_BYTE,
				this->data,
				newWidth, 
				newHeight, 
				GL_UNSIGNED_BYTE, 
				newData);
		delete [] this->data;
		this->data = newData;
		this->width = newWidth;
		this->height = newHeight;
	}
Exemplo n.º 9
0
gliGenericImage *
gliScaleImage(gliGenericImage *image, int nw, int nh)
{
  gliGenericImage *newImage;
  GLubyte *newPixels;
  GLenum status;

  /* Cannot scale paletted images; application must gliDepalette first. */
  assert(image->cmap == NULL);
  assert(image->cmapEntries == 0);
  assert(image->cmapFormat == GL_NONE);

  newPixels = (GLubyte*) malloc(nw*nh*image->components);
  assert(newPixels);

  status = gluScaleImage(image->format, image->width, image->height, image->type,
    image->pixels, nw, nh, image->type, newPixels);
  /* gluScalImage may fail for formats introduced by extensions.
     For example, GL_BGR and GL_BGRA (introduced by the EXT_bgra
     extension though now part of OpenGL 1.2) are not recognized
     by some early GLU implementations.  In particular, the
     Macintosh GLU lacks BGR and BGRA support.  In such cases,
     gluScaleImage may fail with GLU_INVALID_ENUM and we may
     have to convert the image from BGR or BGRA to RGB or RGBA
     to ensure gluScaleImage can scale the image correctly. */
  if (status == GLU_INVALID_ENUM) {
    gliConvertImageToCoreFormat(image);
    status = gluScaleImage(image->format,
      image->width, image->height, image->type,
      image->pixels, nw, nh, image->type, newPixels);
  }
  assert(status == 0);

  newImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
  newImage->width = nw;
  newImage->height = nh;
  newImage->format = image->format;
  newImage->internalFormat = image->internalFormat;
  newImage->type = image->type;
  newImage->components = image->components;
  newImage->cmapEntries = 0;
  newImage->cmapFormat = GL_NONE;
  newImage->cmap = NULL;
  newImage->pixels = newPixels;

  return newImage;
}
Exemplo n.º 10
0
void pripremiTex1() {
  // reskaliraj slika1 (350x350) u slika2 (256x256)
  slika2.pixmap = (GLubyte *)malloc(slika2.dimY *
    slika2.dimX * 3 * sizeof(GLubyte));
  gluScaleImage(GL_RGB,
    slika1.dimX, slika1.dimY, GL_UNSIGNED_BYTE, slika1.pixmap,
    slika2.dimX, slika2.dimY, GL_UNSIGNED_BYTE, slika2.pixmap);

  glBindTexture(GL_TEXTURE_2D, tekstura[1]);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, slika2.dimX, slika2.dimY, 
    0, GL_RGB, GL_UNSIGNED_BYTE, slika2.pixmap);
} // pripremiTex1
Exemplo n.º 11
0
Arquivo: tex.c Projeto: Borf/CaveQuake
static void
tex_loadtexture(byte_t *rgb, int w, int h, int format, uint_t flags)
{
    byte_t *tex = rgb;
    int width = w, height = h;
    int size = width*height* (format == GL_RGB ? 3 : 4);

    /* Scale image down for biased level of detail (lowered texture quality) */
    if (!(flags & TEXFILE_FULL_LOD) && g->r_lodbias > 0)
    {
	width /= 1 << g->r_lodbias;
	height /= 1 << g->r_lodbias;
        tex = (byte_t *) rc_malloc(size);

        gluScaleImage(format, w, h, GL_UNSIGNED_BYTE, rgb,
		      width, height, GL_UNSIGNED_BYTE, tex);
    }


    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
	    GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    if (flags & TEXFILE_CLAMP)
    {
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    }
    else
    {
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    }

    if (flags & TEXFILE_NOMIPMAPS)
    {
	glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format,
		     GL_UNSIGNED_BYTE, tex);
    }
    else
    {
	gluBuild2DMipmaps(GL_TEXTURE_2D, format, width, height, format,
			  GL_UNSIGNED_BYTE, tex);
    }

    if (g->r_lodbias > 0)
      free(tex);
}
Exemplo n.º 12
0
/////////////////////////////////////////////////////////
// processImage
//
/////////////////////////////////////////////////////////
void pix_resize :: processImage(imageStruct &image)
{
  // do we need to resize the image?
  // need to check if dimensions are a power of two

  int wN = (m_width>0)?m_width:powerOfTwo(image.xsize);
  int hN = (m_height>0)?m_height:powerOfTwo(image.ysize);

  if (wN != image.xsize || hN != image.ysize) {
    m_image.xsize=wN;
    m_image.ysize=hN;
    m_image.setCsizeByFormat(image.format);
    m_image.reallocate();

    // just for safety: it seems like gluScaleImage needs more memory then just the x*y*c
    m_image.reallocate(wN*hN*4);

    GLint gluError = 0;
#ifdef GEM_HAVE_GLU
    gluError = gluScaleImage(image.format,
                             image.xsize, image.ysize,
                             image.type, image.data,
                             wN, hN,
                             image.type, m_image.data);
#else
    static bool firsttime = true;
    if(firsttime) {
      firsttime = false;
      error("Gem has been compiled without GLU - disabled pix resizing");
      return;
    }
#endif
    if ( gluError ) {
      post("gluError %d: unable to resize image", gluError);
      return;
    }
    //      image.clear();
    image.data  = m_image.data;
    image.xsize = m_image.xsize;
    image.ysize = m_image.ysize;
  }
}
Exemplo n.º 13
0
bool OpenGLRenderer::getSnapshot(Image & image, size_t width, size_t height) {
	
	// TODO handle scaling on the GPU so we don't need to download the whole image
	
	Image fullsize;
	
	getSnapshot(fullsize);
	
 	image.Create(width, height, Image::Format_R8G8B8);
	
	GLint ret = gluScaleImage(GL_RGB, fullsize.GetWidth(), fullsize.GetHeight(), GL_UNSIGNED_BYTE,
	                          fullsize.GetData(), width, height, GL_UNSIGNED_BYTE, image.GetData());
	
	if(ret) {
		LogWarning << "Failed to scaled down screen capture: " << ret << " = " << gluErrorString(ret);
		return false;
	}
	
	return true;
}
Exemplo n.º 14
0
static int tolua_glu_gluScaleImage00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
 tolua_Error tolua_err;
 if (
     !tolua_isnumber(tolua_S,1,0,&tolua_err) ||
     !tolua_isnumber(tolua_S,2,0,&tolua_err) ||
     !tolua_isnumber(tolua_S,3,0,&tolua_err) ||
     !tolua_isnumber(tolua_S,4,0,&tolua_err) ||
     !tolua_isusertype(tolua_S,5,"GLLbuffer",0,&tolua_err) ||
     !tolua_isnumber(tolua_S,6,0,&tolua_err) ||
     !tolua_isnumber(tolua_S,7,0,&tolua_err) ||
     !tolua_isnumber(tolua_S,8,0,&tolua_err) ||
     !tolua_isusertype(tolua_S,9,"GLLbuffer",0,&tolua_err) ||
     !tolua_isnoobj(tolua_S,10,&tolua_err)
 )
  goto tolua_lerror;
 else
#endif
 {
   int format = ((  int)  tolua_tonumber(tolua_S,1,0));
   int widthin = ((  int)  tolua_tonumber(tolua_S,2,0));
   int heightin = ((  int)  tolua_tonumber(tolua_S,3,0));
   int typein = ((  int)  tolua_tonumber(tolua_S,4,0));
  GLLbuffer* datain = ((GLLbuffer*)  tolua_tousertype(tolua_S,5,0));
   int widthout = ((  int)  tolua_tonumber(tolua_S,6,0));
   int heightout = ((  int)  tolua_tonumber(tolua_S,7,0));
   int typeout = ((  int)  tolua_tonumber(tolua_S,8,0));
  GLLbuffer* dataout = ((GLLbuffer*)  tolua_tousertype(tolua_S,9,0));
  {
    int tolua_ret = (  int)  gluScaleImage(format,widthin,heightin,typein,datain,widthout,heightout,typeout,dataout);
   tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
  }
 }
 return 1;
#ifndef TOLUA_RELEASE
 tolua_lerror:
 tolua_error(tolua_S,"#ferror in function 'gluScaleImage'.",&tolua_err);
 return 0;
#endif
}
Exemplo n.º 15
0
void Texture2D::Init()
{

	GLsizei xdim2, ydim2;
	void *imgp;

	xdim2 = 1;
	while (xdim2 <= _width)
		xdim2 *= 2;
	xdim2 /= 2;
	ydim2 = 1;
	while (ydim2 <= _height)
		ydim2 *= 2;
	ydim2 /= 2;

	// rescale it is not a 
	if ((_width != xdim2) || (_height != ydim2))
	{
		_rescaledImageData = (unsigned long *) ::realloc(_rescaledImageData,
			xdim2 * ydim2 * sizeof(unsigned long));
		gluScaleImage(GL_RGBA, _width, _height,
			GL_UNSIGNED_BYTE, _image, xdim2, ydim2,
			GL_UNSIGNED_BYTE, _rescaledImageData);
		imgp = _rescaledImageData;
	}
	else
		imgp = _image;

	glBindTexture(GL_TEXTURE_2D, _id);
	{
		// Set textre parameters
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xdim2, ydim2, 0, GL_RGBA,
			GL_UNSIGNED_BYTE, imgp);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	}
	glBindTexture(GL_TEXTURE_2D, 0);

}
Exemplo n.º 16
0
int gld_BuildTexture(GLTexture *gltexture, void *data, dboolean readonly, int width, int height)
{
  int result = false;

  int tex_width, tex_height, tex_buffer_size;
  unsigned char *tex_buffer = NULL;

  tex_width  = gld_GetTexDimension(width);
  tex_height = gld_GetTexDimension(height);
  tex_buffer_size = tex_width * tex_height * 4;

  //your video is modern
  if (gl_arb_texture_non_power_of_two)
  {
    qglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP,
      ((gltexture->flags & GLTEXTURE_MIPMAP) ? GL_TRUE : GL_FALSE));

    qglTexImage2D( GL_TEXTURE_2D, 0, gl_tex_format,
      tex_width, tex_height,
      0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    gld_RecolorMipLevels(data);

    gld_SetTexFilters(gltexture);

    result = true;
    goto l_exit;
  }

#ifdef USE_GLU_MIPMAP
  if (gltexture->flags & GLTEXTURE_MIPMAP)
  {
    gluBuild2DMipmaps(GL_TEXTURE_2D, gl_tex_format,
      width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);

    gld_RecolorMipLevels(data);

    gld_SetTexFilters(gltexture);

    result = true;
    goto l_exit;
  }
  else
#endif // USE_GLU_MIPMAP
  {
#ifdef USE_GLU_IMAGESCALE
    if ((width != tex_width) || (height != tex_height))
    {
      tex_buffer = malloc(tex_buffer_size);
      if (!tex_buffer)
      {
        goto l_exit;
      }

      gluScaleImage(GL_RGBA, width, height,
        GL_UNSIGNED_BYTE, data,
        tex_width, tex_height,
        GL_UNSIGNED_BYTE, tex_buffer);

      qglTexImage2D( GL_TEXTURE_2D, 0, gl_tex_format,
        tex_width, tex_height,
        0, GL_RGBA, GL_UNSIGNED_BYTE, tex_buffer);
    }
    else
#endif // USE_GLU_IMAGESCALE
    {
      if ((width != tex_width) || (height != tex_height))
      {
        if (width == tex_width)
        {
          tex_buffer = malloc(tex_buffer_size);
          memcpy(tex_buffer, data, width * height * 4);
        }
        else
        {
          int y;
          tex_buffer = calloc(1, tex_buffer_size);
          for (y = 0; y < height; y++)          
          {
            memcpy(tex_buffer + y * tex_width * 4,
              ((unsigned char*)data) + y * width * 4, width * 4);
          }
        }
      }
      else
      {
        tex_buffer = data;
      }

      if (gl_paletted_texture) {
        gld_SetTexturePalette(GL_TEXTURE_2D);
        qglTexImage2D( GL_TEXTURE_2D, 0, GL_COLOR_INDEX8_EXT,
          tex_width, tex_height,
          0, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, tex_buffer);
      } else {
        qglTexImage2D( GL_TEXTURE_2D, 0, gl_tex_format,
          tex_width, tex_height,
          0, GL_RGBA, GL_UNSIGNED_BYTE, tex_buffer);
      }
    }

    gltexture->flags &= ~GLTEXTURE_MIPMAP;
    gld_SetTexFilters(gltexture);
    result = true;
  }

l_exit:
  if (result)
  {
    qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  }

  if (tex_buffer && tex_buffer != data)
  {
    free(tex_buffer);
    tex_buffer = NULL;
  }

  if (!readonly)
  {
    free(data);
    data = NULL;
  }

  return result;
}
Exemplo n.º 17
0
/*glu.ScaleImageRaw(format, widthin, heightin, typein, pixelsin, widthout, heightout, typeout, pixelsout) -> error */
static int luaglu_scaleimageraw(lua_State *L)
{
  lua_pushnumber(L, gluScaleImage(luagl_get_gl_enum(L, 1), luaL_checkinteger(L, 2), luaL_checkinteger(L, 3), luagl_get_gl_enum(L, 4), luagl_checkuserdata(L, 5),
                                                           luaL_checkinteger(L, 6), luaL_checkinteger(L, 7), luagl_get_gl_enum(L, 8), luagl_checkuserdata(L, 9)));
  return 1;
}
Exemplo n.º 18
0
void PTexture::loadCubeMap(const std::string &filenamePrefix, const std::string &filenameSuffix, bool genMipmaps)
{
  PUtil::outLog() << "loading \"" << filenamePrefix << "*" << filenameSuffix << "\" (cube map)" << std::endl;
  unload();

  textarget = GL_TEXTURE_CUBE_MAP;

#ifdef USE_GEN_MIPMAPS
/*  if (genMipmaps && !extgl_Extensions.SGIS_generate_mipmap) {
    PUtil::outLog() << "warning: can't generate mipmaps for texture" << std::endl;
    genMipmaps = false;
  }*/
#endif

  PImage img;

  glGenTextures(1,&texid);
  bind();

#ifdef USE_GEN_MIPMAPS
  GLenum sidetarget[6] = {
    GL_TEXTURE_CUBE_MAP_POSITIVE_X,
    GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
    GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
    GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
    GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
    GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  };
#endif

  const char *middlename[6] = { "px", "nx", "py", "ny", "pz", "nz" };

  for (int side=0; side<6; side++) {
    std::string filename = filenamePrefix + middlename[side] + filenameSuffix;

    img.load(filename);

    GLuint fmt,fmt2;

    switch (img.getcc()) {
    case 1:
      fmt = GL_LUMINANCE; fmt2 = GL_LUMINANCE8; break;
    case 2:
      fmt = GL_LUMINANCE_ALPHA; fmt2 = GL_LUMINANCE8_ALPHA8; break;
    case 3:
      fmt = GL_RGB; fmt2 = GL_RGB8; break;
    case 4:
      fmt = GL_RGBA; fmt2 = GL_RGBA8; break;
    default:
      throw MakePException (filename + " load failed, unknown image format");
    }

    int cx = img.getcx(), cy = img.getcy();
    int newcx=1, newcy=1, max;
    while (newcx < cx) newcx *= 2;
    while (newcy < cy) newcy *= 2;
    glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max);
    if (newcx > max) newcx = max;
    if (newcy > max) newcy = max;

    if (newcx != cx || newcy != cy) {
      PImage newimage (newcx, newcy, img.getcc ());
      
      gluScaleImage (fmt,
          cx, cy, GL_UNSIGNED_BYTE, img.getData (),
          newcx, newcy, GL_UNSIGNED_BYTE, newimage.getData ());
      
      img.swap (newimage);
    }

    glTexParameteri(textarget,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    if (genMipmaps)
      glTexParameteri(textarget,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
    else
      glTexParameteri(textarget,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

    glTexParameteri(textarget,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(textarget,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);

    glPixelStorei(GL_UNPACK_ALIGNMENT,1);

    if (genMipmaps) {
#ifdef USE_GEN_MIPMAPS

      glTexParameteri(textarget, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);

      glTexImage2D(sidetarget[side],0,fmt2,
        newcx,newcy,
        0,fmt,GL_UNSIGNED_BYTE,img.getData());

#else

      int level = 0;
      uint8 *imd = img.getData();
      int cc = img.getcc();
      while (1) {
        glTexImage2D(GL_TEXTURE_2D,level,fmt2,
          newcx,newcy,
          0,fmt,GL_UNSIGNED_BYTE,imd);
        //break;
        if (newcx <= 1 && newcy <= 1) break;

        if (newcx > 1) newcx /= 2;
        if (newcy > 1) newcy /= 2;
        level++;

        for (int y=0; y<newcy; y++) {
          for (int x=0; x<newcx; x++) {
            for (int z=0; z<cc; z++) {
              imd[(y*newcx+x)*cc+z] = (uint8)(((int)
                imd[(y*newcx*4+x*2+0)*cc+z] +
                imd[(y*newcx*4+x*2+1)*cc+z] +
                imd[(y*newcx*4+x*2+0+newcx*2)*cc+z] +
                imd[(y*newcx*4+x*2+1+newcx*2)*cc+z]) / 4);
            }
          }
        }
      }

#endif
    } else {
      glTexImage2D(GL_TEXTURE_2D,0,fmt2,
        newcx,newcy,
        0,fmt,GL_UNSIGNED_BYTE,img.getData());
    }

    img.unload();
  }

  name = filenamePrefix;
}
Exemplo n.º 19
0
void PTexture::loadAlpha(PImage &img, bool genMipmaps, bool clamp)
{
  unload();

  textarget = GL_TEXTURE_2D;

#ifdef USE_GEN_MIPMAPS
/*  if (genMipmaps && !extgl_Extensions.SGIS_generate_mipmap) {
    PUtil::outLog() << "warning: can't generate mipmaps for texture" << std::endl;
    genMipmaps = false;
  }*/
#endif

  GLuint fmt,fmt2;

  switch (img.getcc()) {
  case 1:
    fmt = GL_ALPHA; fmt2 = GL_ALPHA8; break;
  case 2:
    fmt = GL_LUMINANCE_ALPHA; fmt2 = GL_LUMINANCE8_ALPHA8;
    PUtil::outLog() << "Warning: loadAlpha() has been used for image with 2 channels" << std::endl;
    break;
  case 3:
    fmt = GL_RGB; fmt2 = GL_RGB8;
    PUtil::outLog() << "Warning: loadAlpha() has been used for RGB image" << std::endl;
    break;
  case 4:
    fmt = GL_RGBA; fmt2 = GL_RGBA8;
    PUtil::outLog() << "Warning: loadAlpha() has been used for RGBA image" << std::endl;
    break;
  default:
    throw MakePException ("loading texture failed, unknown image format");
  }

  int cx = img.getcx(), cy = img.getcy();
  int newcx=1, newcy=1, max;
  while (newcx < cx) newcx *= 2;
  while (newcy < cy) newcy *= 2;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max);
  if (newcx > max) newcx = max;
  if (newcy > max) newcy = max;

  if (newcx != cx || newcy != cy) {
    PImage newimage (newcx, newcy, img.getcc ());
    
    gluScaleImage (fmt,
        cx, cy, GL_UNSIGNED_BYTE, img.getData (),
        newcx, newcy, GL_UNSIGNED_BYTE, newimage.getData ());
    
    img.swap (newimage);
  }

  glGenTextures(1,&texid);
  bind();

  glTexParameteri(textarget,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  if (genMipmaps)
    glTexParameteri(textarget,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
  else
    glTexParameteri(textarget,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

  if (clamp) {
    glTexParameteri(textarget,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(textarget,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
  } else {
    glTexParameteri(textarget,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(textarget,GL_TEXTURE_WRAP_T,GL_REPEAT);
  }

  glPixelStorei(GL_UNPACK_ALIGNMENT,1);

  if (genMipmaps) {
#ifdef USE_GEN_MIPMAPS

    glTexParameteri(textarget, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);

    glTexImage2D(GL_TEXTURE_2D,0,fmt2,
      newcx,newcy,
      0,fmt,GL_UNSIGNED_BYTE,img.getData());

#else

    int level = 0;
    uint8 *imd = img.getData();
    int cc = img.getcc();
    while (1) {
      glTexImage2D(GL_TEXTURE_2D,level,fmt2,
        newcx,newcy,
        0,fmt,GL_UNSIGNED_BYTE,imd);

      if (newcx <= 1 && newcy <= 1) break;

      if (newcx > 1) newcx /= 2;
      if (newcy > 1) newcy /= 2;
      level++;

      for (int y=0; y<newcy; y++) {
        for (int x=0; x<newcx; x++) {
          for (int z=0; z<cc; z++) {
            imd[(y*newcx+x)*cc+z] = (uint8)(((int)
              imd[(y*newcx*4+x*2+0)*cc+z] +
              imd[(y*newcx*4+x*2+1)*cc+z] +
              imd[(y*newcx*4+x*2+0+newcx*2)*cc+z] +
              imd[(y*newcx*4+x*2+1+newcx*2)*cc+z]) / 4);
          }
        }
      }
    }

#endif
  } else {
    glTexImage2D(GL_TEXTURE_2D,0,fmt2,
      newcx,newcy,
      0,fmt,GL_UNSIGNED_BYTE,img.getData());
  }
}
Exemplo n.º 20
0
void PTexture::loadPiece(PImage &img, int offx, int offy, int sizex, int sizey, bool genMipmaps, bool clamp)
{
  unload();

  textarget = GL_TEXTURE_2D;

#ifdef USE_GEN_MIPMAPS
/*  if (genMipmaps && !extgl_Extensions.SGIS_generate_mipmap) {
    PUtil::outLog() << "warning: can't generate mipmaps for texture" << std::endl;
    genMipmaps = false;
  }*/
#else
  genMipmaps = false;
#endif

  GLuint fmt,fmt2;

  switch (img.getcc()) {
  case 1:
    fmt = GL_LUMINANCE; fmt2 = GL_LUMINANCE8; break;
  case 2:
    fmt = GL_LUMINANCE_ALPHA; fmt2 = GL_LUMINANCE8_ALPHA8; break;
  case 3:
    fmt = GL_RGB; fmt2 = GL_RGB8; break;
  case 4:
    fmt = GL_RGBA; fmt2 = GL_RGBA8; break;
  default:
    throw MakePException ("loading texture failed, unknown image format");
  }

  int cx = sizex, cy = sizey;
  int newcx=1, newcy=1, max;
  while (newcx < cx) newcx *= 2;
  while (newcy < cy) newcy *= 2;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max);
  if (newcx > max) newcx = max;
  if (newcy > max) newcy = max;

  if (newcx != cx || newcy != cy) {
    PImage newimage (newcx, newcy, img.getcc ());
    
    gluScaleImage (fmt,
        cx, cy, GL_UNSIGNED_BYTE, img.getData (),
        newcx, newcy, GL_UNSIGNED_BYTE, newimage.getData ());
    
    img.swap (newimage);
  }

  glGenTextures(1,&texid);
  bind();

  glTexParameteri(textarget,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  if (genMipmaps)
    glTexParameteri(textarget,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
  else
    glTexParameteri(textarget,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

  if (clamp) {
    glTexParameteri(textarget,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(textarget,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
  } else {
    glTexParameteri(textarget,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(textarget,GL_TEXTURE_WRAP_T,GL_REPEAT);
  }

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

#ifndef HAVE_GLES
	// *TODO*, broken on GLES
  glPixelStorei(GL_UNPACK_ROW_LENGTH, img.getcx());
  glPixelStorei(GL_UNPACK_SKIP_ROWS, offy);
  glPixelStorei(GL_UNPACK_SKIP_PIXELS, offx);
#endif
  //uint8 *offsetdata = img.getData() + ((offy*img.getcx())+offx)*img.getcc();

  if (genMipmaps)
    glTexParameteri(textarget, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);

#ifdef HAVE_GLES
  if (offx != 0 || offy != 0) {
	int bpp = img.getcc();
	int width = img.getcx();
    PImage newimage (newcx, newcy, bpp);
	uint8 *imgd = img.getData();
	uint8 *newd = newimage.getData();
	for (int y=0; y<newcy; y++) {
		memcpy(newd+y*newcx*bpp, imgd+(offx*bpp)+(offy*bpp*width)+y*width*bpp, newcx*bpp);
    }
    glTexImage2D(GL_TEXTURE_2D,0,fmt2,
      newcx,newcy,
      0,fmt,GL_UNSIGNED_BYTE,newimage.getData());
  }
#else
  glTexImage2D(GL_TEXTURE_2D,0,fmt2,
    newcx,newcy,
    0,fmt,GL_UNSIGNED_BYTE,img.getData());
#endif

#ifndef HAVE_GLES
  glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
  glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
#endif
}
GLboolean OPENGL_3D_ENGNIE::load_bmp24_texture(const char* file_name, int type)
{
    GLint width, height, total_bytes;
    GLubyte* pixels = 0;
    GLuint last_texture_ID, texture_ID = 0;

     // 打开文件,如果失败,返回
    FILE* pFile = fopen(file_name, "rb");
    if( pFile == 0 )
        return GL_FALSE;

    if(type > MAX_BUFFER_DEPTH_2D_TXETURE)
    {
        return GL_FALSE;
    }
    // 读取文件中图象的宽度和高度
    fseek(pFile, 0x0012, SEEK_SET);
    fread(&width, 4, 1, pFile);
    fread(&height, 4, 1, pFile);
    fseek(pFile, BMP_Header_Length, SEEK_SET);

     // 计算每行像素所占字节数,并根据此数据计算总像素字节数
     {
         GLint line_bytes = width * 3;
        while( line_bytes % 4 != 0 )
             ++line_bytes;
         total_bytes = line_bytes * height;
     }

     // 根据总像素字节数分配内存
     pixels = (GLubyte*)malloc(total_bytes);
    if( pixels == 0 )
     {
        fclose(pFile);
        return GL_FALSE;
     }

     // 读取像素数据
    if( fread(pixels, total_bytes, 1, pFile) <= 0 )
     {
        free(pixels);
        fclose(pFile);
        return GL_FALSE;
     }

     // 在旧版本的OpenGL中
     // 如果图象的宽度和高度不是的整数次方,则需要进行缩放
     // 这里并没有检查OpenGL版本,出于对版本兼容性的考虑,按旧版本处理
     // 另外,无论是旧版本还是新版本,
     // 当图象的宽度和高度超过当前OpenGL实现所支持的最大值时,也要进行缩放
     {
         GLint max;
         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max);
        if( !power_of_two(width)
          || !power_of_two(height)
          || width > max
          || height > max )
         {
            const GLint new_width = 256;
            const GLint new_height = 256; // 规定缩放后新的大小为边长的正方形
             GLint new_line_bytes, new_total_bytes;
             GLubyte* new_pixels = 0;

             // 计算每行需要的字节数和总字节数
             new_line_bytes = new_width * 3;
            while( new_line_bytes % 4 != 0 )
                 ++new_line_bytes;
             new_total_bytes = new_line_bytes * new_height;

             // 分配内存
             new_pixels = (GLubyte*)malloc(new_total_bytes);
            if( new_pixels == 0 )
             {
                free(pixels);
                fclose(pFile);
                return GL_FALSE;
             }

             // 进行像素缩放
             gluScaleImage(GL_RGB,
                 width, height, GL_UNSIGNED_BYTE, pixels,
                 new_width, new_height, GL_UNSIGNED_BYTE, new_pixels);

             // 释放原来的像素数据,把pixels指向新的像素数据,并重新设置width和height
            free(pixels);
             pixels = new_pixels;
             width = new_width;
             height = new_height;
         }
     }

     // 分配一个新的纹理编号
     glGenTextures(1, &texture_ID);
    if( texture_ID == 0 )
     {
        free(pixels);
        fclose(pFile);
        return GL_FALSE;
     }

     // 绑定新的纹理,载入纹理并设置纹理参数
     // 在绑定前,先获得原来绑定的纹理编号,以便在最后进行恢复
     glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture_ID);
     glBindTexture(GL_TEXTURE_2D, texture_ID);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
         GL_BGR_EXT, GL_UNSIGNED_BYTE, pixels);
     glBindTexture(GL_TEXTURE_2D, last_texture_ID);

     // 之前为pixels分配的内存可在使用glTexImage2D以后释放
     // 因为此时像素数据已经被OpenGL另行保存了一份(可能被保存到专门的图形硬件中)
    free(pixels);
    
    texturelist[type] = texture_ID;
    return GL_TRUE;
}
Exemplo n.º 22
0
/**************************************************************************
	Add an image buffer given in s as a new texture page in the texture
	table.  We check first if the given image has already been loaded,
	as a sanity check (should never happen).  The texture numbers are
	stored in a special texture table, not in the resource system, for
	some unknown reason. Start looking for an available slot in the
	texture table at the given slot number.

	Returns the texture number of the image.
**************************************************************************/
int pie_AddTexPage(iV_Image *s, const char* filename, int slot, int maxTextureSize, bool useMipmaping)
{
    unsigned int i = 0;
    int width, height;
    void *bmp;
    bool scaleDown = false;
    GLint minfilter;

    /* Have we already loaded this one? Should not happen here. */
    while (i < _TEX_INDEX)
    {
        if (strncmp(filename, _TEX_PAGE[i].name, iV_TEXNAME_MAX) == 0)
        {
            pie_PrintLoadedTextures();
        }
        ASSERT(strncmp(filename, _TEX_PAGE[i].name, iV_TEXNAME_MAX) != 0,
               "pie_AddTexPage: %s loaded again! Already loaded as %s|%u", filename,
               _TEX_PAGE[i].name, i);
        i++;
    }

    /* Use first unused slot */
    for (i = slot; i < iV_TEX_MAX && _TEX_PAGE[i].name[0] != '\0'; i++) {}

    if (i == _TEX_INDEX)
    {
        _TEX_INDEX++; // increase table
    }
    ASSERT(i != iV_TEX_MAX, "pie_AddTexPage: too many texture pages");

    debug(LOG_TEXTURE, "pie_AddTexPage: %s page=%d", filename, _TEX_INDEX);
    assert(s != NULL);

    /* Stick the name into the tex page structures */
    sstrcpy(_TEX_PAGE[i].name, filename);

    glGenTextures(1, &_TEX_PAGE[i].id);
    // FIXME: This function is used instead of glBindTexture, but we're juggling with difficult to trace global state here. Look into pie_SetTexturePage's definition for details.
    pie_SetTexturePage(i);

    width = s->width;
    height = s->height;
    bmp = s->bmp;
    if ((width & (width-1)) == 0 && (height & (height-1)) == 0)
    {
        if (maxTextureSize > 0 && width > maxTextureSize)
        {
            width = maxTextureSize;
            scaleDown = true;
        }
        if (maxTextureSize > 0 && height > maxTextureSize)
        {
            height = maxTextureSize;
            scaleDown = true;
        }
        if (scaleDown)
        {
            debug(LOG_TEXTURE, "scaling down texture %s from %ix%i to %ix%i", filename, s->width, s->height, width, height);
            bmp = malloc(4 * width * height); // FIXME: don't know for sure it is 4 bytes per pixel
            gluScaleImage(iV_getPixelFormat(s), s->width, s->height, GL_UNSIGNED_BYTE, s->bmp,
                          width,    height,    GL_UNSIGNED_BYTE, bmp);
            free(s->bmp);
        }

        if (maxTextureSize)
        {
            // this is a 3D texture, use texture compression
            gluBuild2DMipmaps(GL_TEXTURE_2D, wz_texture_compression, width, height, iV_getPixelFormat(s), GL_UNSIGNED_BYTE, bmp);
        }
        else
        {
            // this is an interface texture, do not use compression
            gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, iV_getPixelFormat(s), GL_UNSIGNED_BYTE, bmp);
        }
    }
    else
    {
        debug(LOG_ERROR, "pie_AddTexPage: non POT texture %s", filename);
    }

    // it is uploaded, we do not need it anymore
    free(bmp);
    s->bmp = NULL;

    if (useMipmaping)
    {
        minfilter = GL_LINEAR_MIPMAP_LINEAR;
    }
    else
    {
        minfilter = GL_LINEAR;
    }

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Use anisotropic filtering, if available, but only max 4.0 to reduce processor burden
    if (GLEW_EXT_texture_filter_anisotropic)
    {
        GLfloat max;

        glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, MIN(4.0f, max));
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

    /* Send back the texpage number so we can store it in the IMD */

    _TEX_INDEX++;

    return i;
}
Exemplo n.º 23
0
Arquivo: epx_gl.c Projeto: tonyrog/epx
//
// useAlpha=false make alpha channel opaque
// useAlpha=true  use alpha value as is
// useClient=true make use of client stored data, assume texture data
//                survive the rendering phase.
// wrap=GL_CLAMP, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER,
//      GL_REPEAT or GL_MIRRORED_REPEAT
//
// Load textures formats:
//    1 - ARB_texture_non_power_of_two
//    2 - ARB_texture_rectangle  (used if non normalized is request)
//    3 - GL_TEXTURE_2D (possibly scaled otherwise)
//
//
int epx_gl_load_texture(epx_pixmap_t* pic, GLuint* textureName,
                        int useAlpha, int useClient, GLuint wrap,
                        int src_x, int src_y,
                        unsigned int width,unsigned int height)
{
    GLint  tx_iformat;
    GLenum tx_format;
    GLenum tx_type;
    float  saveScale;
    float  saveBias;
    GLenum target;
    int normalized = 1;
    epx_pixmap_t* pic2 = NULL;

    switch(pic->pixel_format) {
    case EPX_FORMAT_R8G8B8:
        tx_iformat = GL_RGB8;
        tx_format  = GL_RGB;
        tx_type    = GL_UNSIGNED_BYTE;
        break;
    case EPX_FORMAT_565_BE:
        tx_iformat = GL_RGB5;
        tx_format  = GL_RGB;
#if BYTE_ORDER == BIG_ENDIAN
        tx_type    = GL_UNSIGNED_SHORT_5_6_5;
#else
        tx_type    = GL_UNSIGNED_SHORT_5_6_5_REV;
#endif
        break;
    case EPX_FORMAT_565_LE:
        tx_iformat = GL_RGB5;
        tx_format  = GL_RGB;
#if BYTE_ORDER == BIG_ENDIAN
        tx_type    = GL_UNSIGNED_SHORT_5_6_5_REV;
#else
        tx_type    = GL_UNSIGNED_SHORT_5_6_5;
#endif
        break;
    case EPX_FORMAT_B8G8R8:
        tx_iformat = GL_RGB8;
        tx_format  = GL_BGR;
        tx_type    = GL_UNSIGNED_BYTE;
        break;
    case EPX_FORMAT_A8R8G8B8:
        tx_iformat = GL_RGBA8;
        tx_format  = GL_BGRA_EXT;
#if BYTE_ORDER == BIG_ENDIAN
        tx_type    = GL_UNSIGNED_INT_8_8_8_8_REV;
#else
        tx_type    = GL_UNSIGNED_INT_8_8_8_8;
#endif
        break;
    case EPX_FORMAT_R8G8B8A8:
        tx_iformat = GL_RGBA8;
        tx_format  = GL_RGBA;
#if BYTE_ORDER == BIG_ENDIAN
        tx_type    = GL_UNSIGNED_INT_8_8_8_8;
#else
        tx_type    = GL_UNSIGNED_INT_8_8_8_8_REV;
#endif
        break;
    case EPX_FORMAT_B8G8R8A8:
        tx_iformat = GL_RGBA8;
        tx_format  = GL_BGRA;
#if BYTE_ORDER == BIG_ENDIAN
        tx_type    = GL_UNSIGNED_INT_8_8_8_8;
#else
        tx_type    = GL_UNSIGNED_INT_8_8_8_8_REV;
#endif
        break;
    default:
        return -1; // Better error code?
    }

    if (*textureName == 0)
        glGenTextures(1, textureName);

    /* FIXME check extensions better */
    if (normalized) {
#ifndef GL_ARB_texture_non_power_of_two
        unsigned int width2 = nearest_pow2(width);
        unsigned int height2 = nearest_pow2(height);

        printf("POT: width2=%d, height2=%d\n", width2, height2);
        if ((width2==0) || (height2==0))
            return -1;

        if ((width2 != width) || (height2 != height)) {
            epx_pixmap_t* pic2 = epx_pixmap_create(width2, height2,
                                                   pic->pixel_format);
            printf("POT: scale image\n");
            gluScaleImage(tx_format,
                          width, height, tx_type, EPX_PIXEL_ADDR(pic,src_x,src_y),
                          width2, height2, tx_type, EPX_PIXEL_ADDR(pic2,0,0));
            width = width2;
            height = height2;
            pic = pic2;
        }
#endif
        target = GL_TEXTURE_2D;
    }
    else {
#ifdef GL_ARB_texture_rectangle
        target = GL_TEXTURE_RECTANGLE_ARB;

#endif
    }
    glBindTexture (target, *textureName);
    glTexParameteri(target,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(target,GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(target,GL_TEXTURE_WRAP_S, wrap);
    glTexParameteri(target,GL_TEXTURE_WRAP_T, wrap);

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glPixelStorei (GL_UNPACK_ROW_LENGTH,
                   pic->bytes_per_row/pic->bytes_per_pixel);
    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
#ifdef GL_UNPACK_CLIENT_STORAGE_APPLE
    if (useClient)
        // This speeds processing up from 40-50 => 50-60  fps :-)
        // BUT WE MUST PRESERVE THE PIXELS until next reload!!!!!!
        // this is what useClient is for
        glPixelStorei (GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
#endif

    if (!useAlpha) {
        // Do not use possibly bad alpha value
        glGetFloatv(GL_ALPHA_SCALE, &saveScale);
        glGetFloatv(GL_ALPHA_BIAS, &saveBias);
        glPixelTransferf(GL_ALPHA_SCALE, 0.0);
        glPixelTransferf(GL_ALPHA_BIAS,  1.0);
    }
    // FIXME Update with:
    // glTexSubImage2D(target, 0, 0, 0, width, height, tx_format, tx_type,
    //                 EPIXEL_ADDR(pic, src_x, src_y))
    //  but only if width & height is same as original texture
    glTexImage2D (target,
                  0,
                  tx_iformat,
                  width,
                  height,
                  0,
                  tx_format,
                  tx_type,
                  EPX_PIXEL_ADDR(pic, src_x, src_y));

    if (!useAlpha) {
        // Reset saved values
        glPixelTransferf(GL_ALPHA_SCALE, saveScale);
        glPixelTransferf(GL_ALPHA_BIAS,  saveBias);
    }
    if (pic2)
        epx_pixmap_destroy(pic2);
    return 0;
}
Exemplo n.º 24
0
GLint GLAPIENTRY
gluBuild2DMipmaps(GLenum target, GLint components,
		  GLsizei width, GLsizei height, GLenum format,
		  GLenum type, const void *data)
{
   GLint w, h, maxsize;
   void *image, *newimage;
   GLint neww, newh, level, bpp;
   int error;
   GLboolean done;
   GLint retval = 0;
   GLint unpackrowlength, unpackalignment, unpackskiprows, unpackskippixels;
   GLint packrowlength, packalignment, packskiprows, packskippixels;

   if (width < 1 || height < 1)
      return GLU_INVALID_VALUE;

   glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxsize);

   w = round2(width);
   if (w > maxsize) {
      w = maxsize;
   }
   h = round2(height);
   if (h > maxsize) {
      h = maxsize;
   }

   bpp = bytes_per_pixel(format, type);
   if (bpp == 0) {
      /* probably a bad format or type enum */
      return GLU_INVALID_ENUM;
   }

   /* Get current glPixelStore values */
   glGetIntegerv(GL_UNPACK_ROW_LENGTH, &unpackrowlength);
   glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpackalignment);
   glGetIntegerv(GL_UNPACK_SKIP_ROWS, &unpackskiprows);
   glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &unpackskippixels);
   glGetIntegerv(GL_PACK_ROW_LENGTH, &packrowlength);
   glGetIntegerv(GL_PACK_ALIGNMENT, &packalignment);
   glGetIntegerv(GL_PACK_SKIP_ROWS, &packskiprows);
   glGetIntegerv(GL_PACK_SKIP_PIXELS, &packskippixels);

   /* set pixel packing */
   glPixelStorei(GL_PACK_ROW_LENGTH, 0);
   glPixelStorei(GL_PACK_ALIGNMENT, 1);
   glPixelStorei(GL_PACK_SKIP_ROWS, 0);
   glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

   done = GL_FALSE;

   if (w != width || h != height) {
      /* must rescale image to get "top" mipmap texture image */
      image = malloc((w + 4) * h * bpp);
      if (!image) {
	 return GLU_OUT_OF_MEMORY;
      }
      error = gluScaleImage(format, width, height, type, data,
			    w, h, type, image);
      if (error) {
	 retval = error;
	 done = GL_TRUE;
      }
   }
   else {
      image = (void *) data;
   }

   level = 0;
   while (!done) {
      if (image != data) {
	 /* set pixel unpacking */
	 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
	 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	 glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
	 glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
      }

      glTexImage2D(target, level, components, w, h, 0, format, type, image);

      if (w == 1 && h == 1)
	 break;

      neww = (w < 2) ? 1 : w / 2;
      newh = (h < 2) ? 1 : h / 2;
      newimage = malloc((neww + 4) * newh * bpp);
      if (!newimage) {
	 return GLU_OUT_OF_MEMORY;
      }

      error = gluScaleImage(format, w, h, type, image,
			    neww, newh, type, newimage);
      if (error) {
	 retval = error;
	 done = GL_TRUE;
      }

      if (image != data) {
	 free(image);
      }
      image = newimage;

      w = neww;
      h = newh;
      level++;
   }

   if (image != data) {
      free(image);
   }

   /* Restore original glPixelStore state */
   glPixelStorei(GL_UNPACK_ROW_LENGTH, unpackrowlength);
   glPixelStorei(GL_UNPACK_ALIGNMENT, unpackalignment);
   glPixelStorei(GL_UNPACK_SKIP_ROWS, unpackskiprows);
   glPixelStorei(GL_UNPACK_SKIP_PIXELS, unpackskippixels);
   glPixelStorei(GL_PACK_ROW_LENGTH, packrowlength);
   glPixelStorei(GL_PACK_ALIGNMENT, packalignment);
   glPixelStorei(GL_PACK_SKIP_ROWS, packskiprows);
   glPixelStorei(GL_PACK_SKIP_PIXELS, packskippixels);

   return retval;
}
Exemplo n.º 25
0
int
GlWindow::loadTexture (const char *filename, int name)
{
	if (!filename || !strlen (filename))
	{
		if (d_textureNames[name])
		{
			//glDeleteTextures (1, &d_textureNames[name]);
			d_textureNames[name] = 0;
		}

#ifdef WIN32
		if (name == TEXTURE_MODEL)
			strcpy (modelTexFile, "");
		else if (name == TEXTURE_WEAPON)
			strcpy (weaponTexFile, "");
		else if (name == TEXTURE_BACKGROUND)
			strcpy (backgroundTexFile, "");
		else if (name == TEXTURE_WATER)
			strcpy (waterTexFile, "");
#endif
		return 0;
	}

	mxImage *image = 0;

	if (strstr (filename, ".tga"))
		image = mxTgaRead (filename);
	else if (strstr (_strlwr ((char *) filename), ".pcx"))
	{
		mxImage *tmp = mxPcxRead (filename);
		if (tmp)
		{
			image = new mxImage ();
			if (image && image->create (tmp->width, tmp->height, 24))
			{
				byte *dataout = (byte *) image->data;
				byte *datain = (byte *) tmp->data;
				byte *palette = (byte *) tmp->palette;
				int ptr = 0;
				for (int y = 0; y < tmp->height; y++)
				{
					for (int x = 0; x < tmp->width; x++)
					{
						dataout[ptr++] = palette[datain[y * tmp->width + x] * 3 + 0];
						dataout[ptr++] = palette[datain[y * tmp->width + x] * 3 + 1];
						dataout[ptr++] = palette[datain[y * tmp->width + x] * 3 + 2];
					}
				}
			}
			else
			{
				if (image)
					delete image;
				image = 0;
			}
		}

		if (tmp)
			delete tmp;
	}

	if (image)
	{
#ifdef WIN32
		if (name == TEXTURE_MODEL)
			strcpy (modelTexFile, filename);
		else if (name == TEXTURE_WEAPON)
			strcpy (weaponTexFile, filename);
		else if (name == TEXTURE_BACKGROUND)
			strcpy (backgroundTexFile, filename);
		else if (name == TEXTURE_WATER)
			strcpy (waterTexFile, filename);
#endif
		d_textureNames[name] = name;

		// scale texture to power of 2
		int w = image->width;
		int h = image->height;
		int w2 = w, h2 = h;

		if (w2 > d_textureLimit)
			w2 = d_textureLimit;

		if (w2 > 128)
			w2 = 256;
		else if (w2 > 64)
			w2 = 128;
		else if (w2 > 32)
			w2 = 64;
		else if (w2 > 16)
			w2 = 32;
		else if (w2 > 8)
			w2 = 16;
		else if (w2 > 4)
			w2 = 8;
		else if (w2 > 2)
			w2 = 4;
		else if (w2 > 1)
			w2 = 2;

		if (h2 > d_textureLimit)
			h2 = d_textureLimit;

		if (h2 > 128)
			h2 = 256;
		else if (h2 > 64)
			h2 = 128;
		else if (h2 > 32)
			h2 = 64;
		else if (h2 > 16)
			h2 = 32;
		else if (h2 > 8)
			h2 = 16;
		else if (h2 > 4)
			h2 = 8;
		else if (h2 > 2)
			h2 = 4;
		else if (h2 > 1)
			h2 = 2;

		mxImage *image2 = new mxImage ();
		image2->create (w2, h2, 24);

		gluScaleImage(GL_RGB, w, h, GL_UNSIGNED_BYTE, image->data, w2, h2, GL_UNSIGNED_BYTE, image2->data);
		delete image;

		//glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
		glBindTexture (GL_TEXTURE_2D, d_textureNames[name]);
		//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_MIN_FILTER, GL_LINEAR);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, image2->width, image2->height, 0, GL_RGB, GL_UNSIGNED_BYTE, image2->data);
		glBindTexture (GL_TEXTURE_2D, 0);

		delete image2;

		return name;
	}

	return 0;
}
Exemplo n.º 26
0
/* Load the image file specified on the command line as the current texture */
static void
loadImageTextures(void)
{
  GLfloat borderColor[4] =
  {1.0, 1.0, 1.0, 1.0};
  int tex;

  for (tex = 0; tex < NumTextures; tex++) {
     GLubyte *image, *texData3, *texData4;
     GLint imgWidth, imgHeight;
     GLenum imgFormat;
     int i, j;

     printf("loading %s\n", texFilename[tex]);
     image = LoadRGBImage(texFilename[tex], &imgWidth, &imgHeight, &imgFormat);
     if (!image) {
        printf("can't find %s\n", texFilename[tex]);
        exit(1);
     }
     assert(imgFormat == GL_RGB);

     /* scale to 256x256 */
     texData3 = malloc(256 * 256 * 4);
     texData4 = malloc(256 * 256 * 4);
     assert(texData3);
     assert(texData4);
     gluScaleImage(imgFormat, imgWidth, imgHeight, GL_UNSIGNED_BYTE, image,
                   256, 256, GL_UNSIGNED_BYTE, texData3);

     /* convert to rgba */
     for (i = 0; i < 256 * 256; i++) {
        texData4[i*4+0] = texData3[i*3+0];
        texData4[i*4+1] = texData3[i*3+1];
        texData4[i*4+2] = texData3[i*3+2];
        texData4[i*4+3] = 128;
     }

     /* put transparent border around image */
     for (i = 0; i < 256; i++) {
        texData4[i*4+0] = 255;
        texData4[i*4+1] = 255;
        texData4[i*4+2] = 255;
        texData4[i*4+3] = 0;
     }
     j = 256 * 255 * 4;
     for (i = 0; i < 256; i++) {
        texData4[j + i*4+0] = 255;
        texData4[j + i*4+1] = 255;
        texData4[j + i*4+2] = 255;
        texData4[j + i*4+3] = 0;
     }
     for (i = 0; i < 256; i++) {
        j = i * 256 * 4;
        texData4[j+0] = 255;
        texData4[j+1] = 255;
        texData4[j+2] = 255;
        texData4[j+3] = 0;
     }
     for (i = 0; i < 256; i++) {
        j = i * 256 * 4 + 255 * 4;
        texData4[j+0] = 255;
        texData4[j+1] = 255;
        texData4[j+2] = 255;
        texData4[j+3] = 0;
     }

     ActiveTexture(GL_TEXTURE0_ARB + tex);
     glBindTexture(GL_TEXTURE_2D, tex + 1);

     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, texData4);

     if (linearFilter) {
       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
     } else {
       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
     }
     glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);

     free(texData3);
     free(texData4);
     free(image);
  }
}
Exemplo n.º 27
0
static void
loadtiles(void) {
    int lx, rx, ty, by;	/* image bounding box */
    static int ox = TILES*TILESIZE/2, oy = TILES*TILESIZE/2;  /* image origin */
    static int ot = 0, os = 0;
    int dx = 0, dy = 0, nx = -1, ny = -1;
    float trx, try;
#define S_TSIZE	(TSIZE-TILESIZE)	/* visible portion of texture = TSIZE less one tile for slop */

    /* calculate tile #'s at corners of visible region */
    lx = x - S_TSIZE/2;
    rx = lx + S_TSIZE;
    by = y - S_TSIZE/2;
    ty = by + S_TSIZE;
    lx /= TILESIZE; rx /= TILESIZE;
    by /= TILESIZE; ty /= TILESIZE;

    dx = ((x - S_TSIZE/2)/TILESIZE) - ((ox - S_TSIZE/2)/TILESIZE);
    
    nx = lx; ny = by;
    if (dx < 0) {
	/* add on left */
	os -= TILESIZE;
	if (os < 0) os += TSIZE;
	nx = lx;
    } else if (dx > 0) {
	nx = rx;
    }

    dy = ((y - S_TSIZE/2) / TILESIZE) - ((oy - S_TSIZE/2) / TILESIZE);
    if (dy > 0) {
	/* add on bottom */
	ny = ty;
    } else if (dy < 0) {
	/* add on top */
	ot -= TILESIZE;
	if (ot < 0) ot += TSIZE;
	ny = by;
    }
if (dx || dy) printf("dx %d dy %d   lx %d rx %d   by %d ty %d   nx %d ny %d   os %d ot %d\n", dx, dy, lx, rx, by, ty, nx, ny, os, ot);
    if (dx) {
	int t;
	for(t = 0; t < TSIZE; t += TILESIZE) {
	    glTexSubImage2D(GL_TEXTURE_2D, 0, os, (t+ot) % TSIZE, TILESIZE,
                 TILESIZE, GL_RGBA, GL_UNSIGNED_BYTE,
                 tiles[ny+t/TILESIZE][nx].data);
printf("load %d %d  %d %d\n", nx, ny+t/TILESIZE, os, (t+ot) % TSIZE);
	}
    }

    if (dy) {
	int s;
	for(s = 0; s < TSIZE; s += TILESIZE) {
	    glTexSubImage2D(GL_TEXTURE_2D, 0, (s+os) % TSIZE, ot, TILESIZE,
                 TILESIZE, GL_RGBA, GL_UNSIGNED_BYTE,
                 tiles[ny][nx+s/TILESIZE].data);
printf("load %d %d  %d %d\n", nx+s/TILESIZE, ny, (s+os) % TSIZE, ot);
	}
    }
    if (dx > 0) {
	os += TILESIZE;
	if (os >= TSIZE) os -= TSIZE;
    }
    if (dy > 0) {
	ot += TILESIZE;
	if (ot >= TSIZE) ot -= TSIZE;
    }
    ox = x; oy = y;
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    trx = (float)((x-TILES*TILESIZE/2) % TSIZE)/TSIZE;
    try = (float)((y-TILES*TILESIZE/2) % TSIZE)/TSIZE;
    glTranslatef(trx, try, 0.f);
    glMatrixMode(GL_MODELVIEW);
}

static void
init(char *filename) {
    int i;

    mesh0(-1.f,1.f,-1.f,1.f,0.f,1.f,0.f,1.f,0.f,64,64);
    if (filename) {
	image = read_texture(filename, &width, &height, &components);
	if (image == NULL) {
	    fprintf(stderr, "Error: Can't load image file \"%s\".\n",
		    filename);
	    exit(EXIT_FAILURE);
	} else {
	    printf("%d x %d image loaded\n", width, height);
	}
	if (components < 3 || components > 4) {
	    printf("must be RGB or RGBA image\n");
	    exit(EXIT_FAILURE);
	}
    } else {
	int i, j;
	components = 4; width = height = TSIZE;
	image = (unsigned *) malloc(width*height*sizeof(unsigned));
	for (j = 0; j < height; j++)
	    for (i = 0; i < width; i++) {
		if (i & 1)
		    image[i+j*width] = 0xff;
		else
		    image[i+j*width] = 0xff00;
		if (j&1)
		    image[i+j*width] |= 0xff0000;
	    }

    }
    if (width % TILESIZE || height % TILESIZE) {
#define TXSIZE 192
	unsigned *newimage = malloc(TXSIZE*TXSIZE*sizeof *newimage);
	gluScaleImage(GL_RGBA, width, height, GL_UNSIGNED_BYTE, image,
		TXSIZE, TXSIZE, GL_UNSIGNED_BYTE, newimage);
	free(image);
	image = newimage; width = height = TXSIZE; components = 4;
    }
    tile_image(image);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TSIZE,
                 TSIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    for(i = 0; i < TILES; i++) {
	int j;
	for(j = 0; j < TILES; j++) {
	    glTexSubImage2D(GL_TEXTURE_2D, 0, i*TILESIZE, j*TILESIZE, TILESIZE,
		 TILESIZE, GL_RGBA, GL_UNSIGNED_BYTE, 
		 tiles[(TILES-TSIZE/TILESIZE)/2+j][(TILES-TSIZE/TILESIZE)/2+i].data);
	}
    }
    glEnable(GL_TEXTURE_2D);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90.,1.,.1,10.);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.,0.,-1.0);
    glLineWidth(3.0);
    glClearColor(.25, .25, .25, .25);

    /* start at center of image */
    x = TILES*TILESIZE/2;
    y = TILES*TILESIZE/2;
}
Exemplo n.º 28
0
void Image::loadWithBmp()
{
	GLint width, height, total_bytes;
	GLubyte* pixels = 0;

	FILE* pFile = fopen(file.c_str(), "rb");

	fseek(pFile, 0x0012, SEEK_SET);
	fread(&width, 4, 1, pFile);
	fread(&height, 4, 1, pFile);
	fseek(pFile, 54, SEEK_SET);

	{
		GLint line_bytes = width * 3;
		while (line_bytes % 4 != 0)
			++line_bytes;
		total_bytes = line_bytes * height;
	}


	pixels = (GLubyte*)malloc(total_bytes);
	if (pixels == 0)
	{
		fclose(pFile);
		ASSERT(false, " alloc error");

	}


	if (fread(pixels, total_bytes, 1, pFile) <= 0)
	{
		free(pixels);
		fclose(pFile);
		ASSERT(false, "read file error");


	}
	GLint new_line_bytes, new_total_bytes;


	static int points[] = { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 };


	GLint new_width = width;
	GLint new_height = height;

	//cache real file width and height
	_rect.x = width;
	_rect.y = height;


	for (int i = 0; i < 11; i++)
	{
		if (new_width>points[i] && new_width <= points[1 + i])
		{
			new_width = points[1 + i];
			break;
		}


	}


	for (int i = 0; i < 11; i++)
	{
		if (new_height>points[i] && new_height <= points[1 + i])
		{
			new_height = points[1 + i];
			break;
		}


	}

	{
		GLint max;
		glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max);

		{

			GLubyte* new_pixels = 0;

			new_line_bytes = new_width * 3;
			while (new_line_bytes % 4 != 0)
				++new_line_bytes;
			new_total_bytes = new_line_bytes * new_height;

			// alloc memeory
			new_pixels = (GLubyte*)malloc(new_total_bytes);

			// scale image to fix 2^n;
			gluScaleImage(GL_RGB,
				width, height, GL_UNSIGNED_BYTE, pixels,
				new_width, new_height, GL_UNSIGNED_BYTE, new_pixels);

			free(pixels);
			pixels = new_pixels;
			this->width = new_width;
			this->height = new_height;

		}
	}

	_data = pixels;

	size = new_total_bytes;
	fclose(pFile);
}
Exemplo n.º 29
0
GLint gluBuild2DMipmaps( GLenum target, GLint components,
                         GLint width, GLint height, GLenum format,
                         GLenum type, const void *data )
{
   GLint w, h, maxsize;
   void *image, *newimage;
   GLint neww, newh, level, bpp;
   int error;

   glGetIntegerv( GL_MAX_TEXTURE_SIZE, &maxsize );

   w = round2( width );
   if (w>maxsize) {
      w = maxsize;
   }
   h = round2( height );
   if (h>maxsize) {
      h = maxsize;
   }

   bpp = bytes_per_pixel( format, type );
   if (bpp==0) {
      /* probably a bad format or type enum */
      return GLU_INVALID_ENUM;
   }

   if (w!=width || h!=height) {
      /* must rescale image to get "top" mipmap texture image */
      image = malloc( (w+4) * h * bpp );
      if (!image) {
	 return GLU_OUT_OF_MEMORY;
      }
      error = gluScaleImage( format, width, height, type, data,
			     w, h, type, image );
      if (error) {
	 return error;
      }
   }
   else {
      image = (void *) data;
   }

   level = 0;
   while (1) {
      glTexImage2D( target, level, components, w, h, 0, format, type, image );

      if (w==1 && h==1)  break;

      neww = (w<2) ? 1 : w/2;
      newh = (h<2) ? 1 : h/2;
      newimage = malloc( (neww+4) * newh * bpp );
      if (!newimage) {
	 return GLU_OUT_OF_MEMORY;
      }

      error =  gluScaleImage( format, w, h, type, image,
			      neww, newh, type, newimage );
      if (error) {
	 return error;
      }

      if (image!=data) {
	 free( image );
      }
      image = newimage;

      w = neww;
      h = newh;
      level++;
   }

   if (image!=data) {
      free( image );
   }

   return 0;
}
Exemplo n.º 30
0
/* don't try alpha=GL_FALSE: gluScaleImage implementations seem to be buggy */
GLuint
glmLoadTexture(const char *filename, GLboolean alpha, GLboolean repeat, GLboolean filtering, GLboolean mipmaps, GLfloat *texcoordwidth, GLfloat *texcoordheight)
{
    GLuint tex;
    int width, height,pixelsize;
    int type;
    int filter_min, filter_mag;
    GLubyte *data, *rdata;
    double xPow2, yPow2;
    int ixPow2, iyPow2;
    int xSize2, ySize2;
    GLint retval;

    if(glm_do_init)
	glmImgInit();
        
#ifdef HAVE_SOIL
    tex = SOIL_load_OGL_texture(filename,
                                   SOIL_LOAD_AUTO,
                                   SOIL_CREATE_NEW_ID,
                                   SOIL_FLAG_POWER_OF_TWO
                                   );
    
    glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
    glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &height);
    //glTexEnvf(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    
    
    *texcoordwidth = width;		
	*texcoordheight = height;
    
    return tex;
#endif
    
    /* fallback solution (PPM only) */
    data = glmReadPPM(filename, alpha, &width, &height, &type);
    if(data != NULL) {
        DBG_(__glmWarning("glmLoadTexture(): got PPM for %s",filename));
        goto DONE;
    }


#ifdef HAVE_DEVIL
    data = glmReadDevIL(filename, alpha, &width, &height, &type);
    if(data != NULL) {
	DBG_(__glmWarning("glmLoadTexture(): got DevIL for %s",filename));
	goto DONE;
    }
#endif
#ifdef HAVE_LIBJPEG
    data = glmReadJPG(filename, alpha, &width, &height, &type);
    if(data != NULL) {
	DBG_(__glmWarning("glmLoadTexture(): got JPG for %s",filename));
	goto DONE;
    }
#endif
#ifdef HAVE_LIBPNG
    data = glmReadPNG(filename, alpha, &width, &height, &type);
    if(data != NULL) {
	DBG_(__glmWarning("glmLoadTexture(): got PNG for %s",filename));
	goto DONE;
    }
#endif
#ifdef HAVE_LIBSDL_IMAGE
    data = glmReadSDL(filename, alpha, &width, &height, &type);
    if(data != NULL) {
	DBG_(__glmWarning("glmLoadTexture(): got SDL for %s",filename));
	goto DONE;
    }
#endif
#ifdef HAVE_LIBSIMAGE
    data = glmReadSimage(filename, alpha, &width, &height, &type);
    if(data != NULL) {
	DBG_(__glmWarning("glmLoadTexture(): got simage for %s",filename));
	goto DONE;
    }
#endif

    __glmWarning("glmLoadTexture() failed: Unable to load texture from %s!", filename);
    DBG_(__glmWarning("glmLoadTexture() failed: tried PPM"));
#ifdef HAVE_LIBJPEG
    DBG_(__glmWarning("glmLoadTexture() failed: tried JPEG"));
#endif
#ifdef HAVE_LIBSDL_IMAGE
    DBG_(__glmWarning("glmLoadTexture() failed: tried SDL_image"));
#endif
    return 0;

  DONE:
/*#define FORCE_ALPHA*/
#ifdef FORCE_ALPHA
    if(alpha && type == GL_RGB) {
	/* if we really want RGBA */
	const unsigned int size = width * height;
	
	unsigned char *rgbaimage;
	unsigned char *ptri, *ptro;
	int i;
	
	rgbaimage = (unsigned char*)malloc(sizeof(unsigned char)* size * 4);
	ptri = data;
	ptro = rgbaimage;
	for(i=0; i<size; i++) {
	    *(ptro++) = *(ptri++);
	    *(ptro++) = *(ptri++);
	    *(ptro++) = *(ptri++);
	    *(ptro++) = 255;
	}
	free(data);
	data = rgbaimage;
	type = GL_RGBA;
    }
#endif /* FORCE_ALPHA */
    switch(type) {
    case GL_LUMINANCE:
	pixelsize = 1;
	break;
    case GL_RGB:
    case GL_BGR:
	pixelsize = 3;
	break;
    case GL_RGBA:
    case GL_BGRA:
	pixelsize = 4;
	break;
    default:
	__glmFatalError( "glmLoadTexture(): unknown type 0x%x", type);
	pixelsize = 0;
	break;
    }

    if((pixelsize*width) % 4 == 0)
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    else
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    xSize2 = width;
    if (xSize2 > gl_max_texture_size)
	xSize2 = gl_max_texture_size;
    ySize2 = height;
    if (ySize2 > gl_max_texture_size)
	ySize2 = gl_max_texture_size;

    if (_glmTextureTarget == GL_TEXTURE_2D) {
	//if(1) {
	/* scale image to power of 2 in height and width */
	xPow2 = log((double)xSize2) / log(2.0);
	yPow2 = log((double)ySize2) / log(2.0);

	ixPow2 = (int)xPow2;
	iyPow2 = (int)yPow2;

	if (xPow2 != (double)ixPow2)
	    ixPow2++;
	if (yPow2 != (double)iyPow2)
	    iyPow2++;

	xSize2 = 1 << ixPow2;
	ySize2 = 1 << iyPow2;
    }
	    
    DBG_(__glmWarning("gl_max_texture_size=%d / width=%d / xSize2=%d / height=%d / ySize2 = %d", gl_max_texture_size, width, xSize2, height, ySize2));
    if((width != xSize2) || (height != ySize2)) {
	/* TODO: use glTexSubImage2D instead */
	DBG_(__glmWarning("scaling texture"));
	rdata = (GLubyte*)malloc(sizeof(GLubyte) * xSize2 * ySize2 * pixelsize);
	if (!rdata)
	    return 0;
	    
	retval = gluScaleImage(type, width, height,
			       GL_UNSIGNED_BYTE, data,
			       xSize2, ySize2, GL_UNSIGNED_BYTE,
			       rdata);

	free(data);
	data = rdata;
    }

    glGenTextures(1, &tex);		/* Generate texture ID */
    glBindTexture(_glmTextureTarget, tex);
    DBG_(__glmWarning("building texture %d",tex));
   
    if(mipmaps && _glmTextureTarget != GL_TEXTURE_2D) {
	DBG_(__glmWarning("mipmaps only work with GL_TEXTURE_2D"));
	mipmaps = 0;
    }
    if(filtering) {
	filter_min = (mipmaps) ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR;
	filter_mag = GL_LINEAR;
    }
    else {
	filter_min = (mipmaps) ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST;
	filter_mag = GL_NEAREST;
    }
    glTexParameteri(_glmTextureTarget, GL_TEXTURE_MIN_FILTER, filter_min);
    glTexParameteri(_glmTextureTarget, GL_TEXTURE_MAG_FILTER, filter_mag);
   
    glTexParameteri(_glmTextureTarget, GL_TEXTURE_WRAP_S, (repeat) ? GL_REPEAT : GL_CLAMP);
    glTexParameteri(_glmTextureTarget, GL_TEXTURE_WRAP_T, (repeat) ? GL_REPEAT : GL_CLAMP);
    if(mipmaps && _glmTextureTarget == GL_TEXTURE_2D) {
	/* only works for GL_TEXTURE_2D */
#ifdef GL_GENERATE_MIPMAP_SGIS
	if(gl_sgis_generate_mipmap) {
	    DBG_(__glmWarning("sgis mipmapping"));
	    glTexParameteri(_glmTextureTarget, GL_GENERATE_MIPMAP_SGIS, GL_TRUE );
	    glTexImage2D(_glmTextureTarget, 0, type, xSize2, ySize2, 0, type, 
			 GL_UNSIGNED_BYTE, data);
	}
	else
#endif
	    {
		DBG_(__glmWarning("glu mipmapping"));
		gluBuild2DMipmaps(_glmTextureTarget, type, xSize2, ySize2, type, 
				  GL_UNSIGNED_BYTE, data);
	    }
    }
    else {
	glTexImage2D(_glmTextureTarget, 0, type, xSize2, ySize2, 0, type, 
		     GL_UNSIGNED_BYTE, data);
    }
   
   
    /* Clean up and return the texture ID */
    free(data);

    if (_glmTextureTarget == GL_TEXTURE_2D) {
	*texcoordwidth = 1.;		/* texcoords are in [0,1] */
	*texcoordheight = 1.;
    }
    else {
	*texcoordwidth = xSize2;		/* size of texture coords */
	*texcoordheight = ySize2;
    }
   
    return tex;
}