Ejemplo n.º 1
0
BearTexture* Painter::MakeTexture(PointInt size,int mode,unsigned char* pixels,TextureLoadMethod &filter){
    if (size.x == 0 || size.y == 0){
        return nullptr;
    }
    GLuint texId = 0;
    glGenTextures(1, &texId);
    DisplayGlError("glGenTextures");
    if (texId == 0){
        return nullptr;
    }

    unsigned int pow_w = powerOfTwo(size.x);
    unsigned int pow_h = powerOfTwo(size.y); //No need to this on opengl. only on opengles

    glBindTexture(GL_TEXTURE_2D, texId);
    filter.ApplyFilter();
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, mode, pow_w, pow_h, 0, mode, GL_UNSIGNED_BYTE, nullptr);
    if (pixels != nullptr){

        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size.x, size.y, mode, GL_UNSIGNED_BYTE, pixels);
    }
    glBindTexture(GL_TEXTURE_2D, 0);
    BearTexture *ret = new BearTexture(texId,size.x,size.y,pow_w,pow_h,mode);
    ret->textureMode = filter;
    DisplayGlError("MakeTexture");
    return ret;
}
Ejemplo n.º 2
0
/*!
    Returns the registered object that is under the mouse position
    specified by \a point.  This function may need to regenerate
    the contents of the pick buffer by repainting the scene
    with paintGL().

    \sa registerObject()
*/
QObject *QGLView::objectForPoint(const QPoint &point)
{
    // Check the window boundaries in case a mouse move has
    // moved the pointer outside the window.
    if (!rect().contains(point))
        return 0;

    // Do we need to refresh the pick buffer contents?
    QGLPainter painter(this);
    if (d->pickBufferForceUpdate) {
        // Initialize the painter, which will make the window context current.
        painter.setPicking(true);
        painter.clearPickObjects();

        // Create a framebuffer object as big as the window to act
        // as the pick buffer if we are single buffered.  If we are
        // double-buffered, then use the window back buffer.
        bool useBackBuffer = doubleBuffer();
        if (!useBackBuffer) {
            QSize fbosize = size();
            fbosize = QSize(powerOfTwo(fbosize.width()), powerOfTwo(fbosize.height()));
            if (!d->fbo) {
                d->fbo = new QGLFramebufferObject(fbosize, QGLFramebufferObject::CombinedDepthStencil);
            } else if (d->fbo->size() != fbosize) {
                delete d->fbo;
                d->fbo = new QGLFramebufferObject(fbosize, QGLFramebufferObject::CombinedDepthStencil);
            }
        }

        // Render the pick version of the scene into the framebuffer object.
        if (d->fbo)
            d->fbo->bind();
        painter.clear();
        painter.setEye(QGL::NoEye);
        painter.setCamera(d->camera);
        paintGL(&painter);
        painter.setPicking(false);

        // The pick buffer contents are now valid, unless we are using
        // the back buffer - we cannot rely upon it being valid next time.
        d->pickBufferForceUpdate = useBackBuffer;
        d->pickBufferMaybeInvalid = false;
    } else {
        // Bind the framebuffer object to the window's context.
        makeCurrent();
        if (d->fbo)
            d->fbo->bind();
    }

    // Pick the object under the mouse.
    int objectId = painter.pickObject(point.x(), height() - 1 - point.y());
    QObject *object = d->objects.value(objectId, 0);
    
    // Release the framebuffer object and return.
    painter.end();
    if (d->fbo)
        d->fbo->release();
    doneCurrent();
    return object;
}
Ejemplo n.º 3
0
void PostProcessor::render(sf::RenderTarget& window)
{
    if (!enabled || !sf::Shader::isAvailable() || !global_post_processor_enabled)
    {
        chain->render(window);
        return;
    }
    if (renderTexture.getSize().x < 1)
    {
        //Setup a backBuffer to render the game on. Then we can render the backbuffer back to the main screen with full-screen shader effects
        int w = window.getView().getViewport().width * window.getSize().x;
        int h = window.getView().getViewport().height * window.getSize().y;
        int tw = powerOfTwo(w);
        int th = powerOfTwo(h);
        sf::View view(window.getView());
        view.setViewport(sf::FloatRect(0, 1.0 - float(h) / float(th), float(w) / float(tw), float(h) / float(th)));

        renderTexture.create(tw, th, true);
        renderTexture.setRepeated(true);
        renderTexture.setSmooth(true);
        renderTexture.setView(view);

        shader.setUniform("inputSize", sf::Vector2f(window.getSize().x, window.getSize().y));
        shader.setUniform("textureSize", sf::Vector2f(renderTexture.getSize().x, renderTexture.getSize().y));
    }

    renderTexture.clear(sf::Color(20, 20, 20));
    chain->render(renderTexture);

    renderTexture.display();
    sf::Sprite backBufferSprite(renderTexture.getTexture(), sf::IntRect(0, renderTexture.getSize().y - window.getView().getViewport().height * window.getSize().y, window.getView().getViewport().width * window.getSize().x, window.getView().getViewport().height * window.getSize().y));
    backBufferSprite.setScale(window.getView().getSize().x/float(renderTexture.getSize().x)/renderTexture.getView().getViewport().width, window.getView().getSize().y/float(renderTexture.getSize().y)/renderTexture.getView().getViewport().height);

    window.draw(backBufferSprite, &shader);
}
Ejemplo n.º 4
0
SDL_Surface *OpenGLImageHelper::convertSurface(SDL_Surface *tmpImage,
                                               int width, int height)
{
    if (!tmpImage)
        return nullptr;

    int realWidth = powerOfTwo(width);
    int realHeight = powerOfTwo(height);

    if (realWidth < width || realHeight < height)
    {
        logger->log("Warning: image too large, cropping to %dx%d texture!",
                    tmpImage->w, tmpImage->h);
    }

#ifdef USE_SDL2
    SDL_SetSurfaceAlphaMod(tmpImage, SDL_ALPHA_OPAQUE);
#else
    // Make sure the alpha channel is not used, but copied to destination
    SDL_SetAlpha(tmpImage, 0, SDL_ALPHA_OPAQUE);
#endif

    // Determine 32-bit masks based on byte order
    uint32_t rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x000000ff;
#else
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0xff000000;
#endif

    if (tmpImage->format->BitsPerPixel != 32
        || realWidth != width || realHeight != height
        || rmask != tmpImage->format->Rmask
        || gmask != tmpImage->format->Gmask
        || amask != tmpImage->format->Amask)
    {
        SDL_Surface *oldImage = tmpImage;
#ifdef USE_SDL2
        SDL_SetSurfaceBlendMode(oldImage, SDL_BLENDMODE_NONE);
#endif
        tmpImage = MSDL_CreateRGBSurface(SDL_SWSURFACE, realWidth, realHeight,
            32, rmask, gmask, bmask, amask);

        if (!tmpImage)
        {
            logger->log("Error, image convert failed: out of memory");
            return nullptr;
        }
        SDL_BlitSurface(oldImage, nullptr, tmpImage, nullptr);
    }
    return tmpImage;
}
bool LTexture::loadTextureFromFile32( std::string path )
{
    //Texture loading success
    bool textureLoaded = false;

    //Generate and set current image ID
    ILuint imgID = 0;
    ilGenImages( 1, &imgID );
    ilBindImage( imgID );

    //Load image
    ILboolean success = ilLoadImage( path.c_str() );

    //Image loaded successfully
    if( success == IL_TRUE )
    {
        //Convert image to RGBA
        success = ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );
        if( success == IL_TRUE )
        {
            //Initialize dimensions
            GLuint imgWidth = (GLuint)ilGetInteger( IL_IMAGE_WIDTH );
            GLuint imgHeight = (GLuint)ilGetInteger( IL_IMAGE_HEIGHT );

            //Calculate required texture dimensions
            GLuint texWidth = powerOfTwo( imgWidth );
            GLuint texHeight = powerOfTwo( imgHeight );

            //Texture is the wrong size
            if( imgWidth != texWidth || imgHeight != texHeight )
            {
                //Place image at upper left
                iluImageParameter( ILU_PLACEMENT, ILU_UPPER_LEFT );

                //Resize image
                iluEnlargeCanvas( (int)texWidth, (int)texHeight, 1 );
            }

            //Create texture from file pixels
            textureLoaded = loadTextureFromPixels32( (GLuint*)ilGetData(), imgWidth, imgHeight, texWidth, texHeight );
        }

        //Delete file from memory
        ilDeleteImages( 1, &imgID );

        //Set pixel format
        mPixelFormat = GL_RGBA;
    }

    //Report error
    if( !textureLoaded )
    {
        printf( "Unable to load %s\n", path.c_str() );
    }

    return textureLoaded;
}
Ejemplo n.º 6
0
int main(int argc, char* argv[]) {
  if( argc != 2){
    std::cout<< "Usage: "<<argv[0]<<" <path to file>" << std::endl;
    return 1;
  }

  std::string outputstr = "";
  std::ostringstream oss;
  
  //change this to actually read a file from disk instead of stdin
  mpz_class filedata(argv[1]);

  //if compiler supported c++11 we could use this to search for filedata in TWOS[], but I'm on debian stable w gcc 4.6 :/
  //bool exists = std::find(std::begin(TWOS), std::end(TWOS), filedata) != std::end(TWOS);

  int exponent = powerOfTwo(filedata);
  mpz_class remainder( filedata - TWOS[exponent]);

  if( remainder == 0 ){
    oss << exponent;
    outputstr = "2^" + oss.str();
    std::cout << outputstr << std::endl;
    return 0;
  }

  std::cout << "exponent is " << exponent << std::endl;
  std::cout << "twos[exponent] is " << TWOS[exponent] << std::endl;
  std::cout << TWOS[exponent] << std:: endl;
  std::cout << filedata <<  std::endl;
  std::cout << "iterating on remainder which equals" << remainder << std::endl;
  while(remainder >= 128){
    //can't just concatenate an int to a string
    oss << exponent;
    outputstr+="2^" +oss.str()+ "+";

    //see if the remainder is near any powers of two
    exponent = powerOfTwo(remainder);
    remainder = remainder - TWOS[exponent];
    std::cout << exponent << std::endl;

    //set stringstream to empty string and then clear error flag(s)
    oss.str("");
    oss.clear();
  }
  oss.str("");
  oss.clear();
  oss << remainder;
  outputstr += oss.str();

  std::cout << outputstr << std::endl;
  
  return 0;
}
MarSystem*
TranscriberExtract::makePitchNet(const mrs_real srate, const mrs_real lowFreq, MarSystem* rvSink)
{
	mrs_real highFreq = 5000.0;

	MarSystem *net = mng.create("Series", "pitchNet");
	net->addMarSystem(mng.create("ShiftInput", "sfi"));
	net->addMarSystem(mng.create("PitchPraat", "pitch"));
	if (rvSink != NULL)
		net->addMarSystem(rvSink);

	// yes, this is the right way around (lowSamples<-highFreq)
	net->updControl("PitchPraat/pitch/mrs_natural/lowSamples",
	             hertz2samples(highFreq, srate) );
	net->updControl("PitchPraat/pitch/mrs_natural/highSamples",
	             hertz2samples(lowFreq, srate) );

	// The window should be just long enough to contain three periods
	// (for pitch detection) of MinimumPitch.
	mrs_real windowSize = 3.0/lowFreq*srate;
	net->updControl("mrs_natural/inSamples", 512);
	net->updControl("ShiftInput/sfi/mrs_natural/winSize",
	             powerOfTwo(windowSize));

	return net;
}
Ejemplo n.º 8
0
/////////////////////////////////////////////////////////
// Buffer for Frames
//
/////////////////////////////////////////////////////////
void pix_movieOS :: createBuffer()
{
  int neededXSize = powerOfTwo(m_xsize);
  int neededYSize = powerOfTwo(m_ysize);

  deleteBuffer();
  int dataSize = neededXSize * neededYSize * m_csize;
  m_pixBlock.image.data = new unsigned char[dataSize];
  m_data=m_pixBlock.image.data; // ??????????????
  memset(m_pixBlock.image.data, 0, dataSize);
  m_frame =/*(char*)*/m_pixBlock.image.data;

  m_pixBlock.image.xsize  = neededXSize;
  m_pixBlock.image.ysize  = neededYSize;
  m_pixBlock.image.csize  = m_csize;
  m_pixBlock.image.format = m_format;
}
Ejemplo n.º 9
0
	bool loadTexture()
	{
		SDL_Surface *pic;

		pic = IMG_Load(imagePath.c_str());

		if(!pic)
		{
		printf("Error: image %s cannot be loaded\n", imagePath.c_str());
		return false;
		}
		if(pic->format->BitsPerPixel != 32 && pic->format->BitsPerPixel != 24)
		{
		printf("Error: image %s is %dbpp - it should be either 24bpp or 32bpp, images with palette are not supported\n", imagePath.c_str(), pic->format->BitsPerPixel);
		SDL_FreeSurface(pic);
		return false;
		}

		GLenum glFormat = (pic->format->BitsPerPixel == 32 ? GL_RGBA : GL_RGB);
		w = pic->w;
		h = pic->h;
		// All OpenGL textures must have size which is power of 2, such as 128, 256, 512 etc
		int upload_w = powerOfTwo(w);
		int upload_h = powerOfTwo(h);
		texcoord_w = (float) w / (float) upload_w;
		texcoord_h = (float) h / (float) upload_h;

		glGenTextures(1, &texture);

		glBindTexture(GL_TEXTURE_2D, texture);
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

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

		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, glFormat, upload_w, upload_h, 0, glFormat, GL_UNSIGNED_BYTE, NULL);
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, glFormat, GL_UNSIGNED_BYTE, pic->pixels);

		SDL_FreeSurface(pic);

		return true;
	}
Ejemplo n.º 10
0
Sprite *LoadFrame( char *filename, int sizex, int sizey)
{
  SDL_Surface *temp;
  SDL_Surface *temp1;
  int w, h;
  
  temp = IMG_Load(filename);
  if(temp == NULL)
  {
    fprintf(stderr,"unable to load a frame: %s\n",SDL_GetError());
    exit(0);
  }
  
  temp1 = SDL_DisplayFormat(temp);

  frame.framesperline = 16;
  /*makes sure the width and height of each frame is opengl compatable*/
  frame.w = powerOfTwo(sizex);
  frame.h = powerOfTwo(sizey);
  frame.used++;
  /*makes sure the width and height of the entire surface is opengl compatable*/
  w = powerOfTwo(temp1->w);
  h = powerOfTwo(temp1->h);
  frame.w2 = (float)sizex/(float)w;
  frame.h2 = (float)sizey/(float)h;
  frame.dimen = GetGlCoord((Camera.w>>1)+frame.w,(Camera.h>>1)+frame.h,_2DPLANE_,modelview,projection,viewport);
  /*Creates an opengl compatable RGBA surface*/
  frame.surface = SDL_CreateRGBSurface(SDL_SWSURFACE,w, h,S_Data.depth,rmask,gmask,bmask,amask);
  
  SDL_BlitSurface(temp1, NULL, frame.surface, NULL);
  /*Sets the clear color on the surface*/
  glGenTextures(1, &frame.image);
  glBindTexture(GL_TEXTURE_2D,frame.image);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.surface->pixels);
  SDL_FreeSurface(frame.surface);
  frame.surface = NULL;
  SDL_FreeSurface(temp1);
  temp1 = NULL;
  SDL_FreeSurface(temp);
  temp = NULL;
  return &frame;
}
Ejemplo n.º 11
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;
  }
}
Ejemplo n.º 12
0
void pix_sig2pix :: dspMess(void *data, t_signal** sp)
{
    if (m_width==0 && m_height==0) {
        int w = powerOfTwo((int)sqrt((double)sp[0]->s_n));
        int h = (sp[0]->s_n / w);
        dimenMess(w, h);
        m_width = 0;
        m_height= 0;
    }
    m_pixBlock.image.setBlack();
    dsp_add(perform, 6, data, sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[3]->s_vec, sp[0]->s_n);
}
Ejemplo n.º 13
0
SDL_Surface *OpenGLImageHelper::create32BitSurface(int width,
                                                   int height) const
{
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    const int rmask = 0xff000000;
    const int gmask = 0x00ff0000;
    const int bmask = 0x0000ff00;
    const int amask = 0x000000ff;
#else
    const int rmask = 0x000000ff;
    const int gmask = 0x0000ff00;
    const int bmask = 0x00ff0000;
    const int amask = 0xff000000;
#endif

    width = powerOfTwo(width);
    height = powerOfTwo(height);

    return MSDL_CreateRGBSurface(SDL_SWSURFACE,
        width, height, 32, rmask, gmask, bmask, amask);
}
Ejemplo n.º 14
0
void GuiElement::adjustRenderTexture(sf::RenderTexture& texture)
{
    P<WindowManager> window_manager = engine->getObject("windowManager");
    //Hack the rectangle for this element so it sits perfectly on pixel boundaries.
    sf::Vector2f half_pixel = (window_manager->mapPixelToCoords(sf::Vector2i(1, 1)) - window_manager->mapPixelToCoords(sf::Vector2i(0, 0))) / 2.0f;
    sf::Vector2f top_left = window_manager->mapPixelToCoords(window_manager->mapCoordsToPixel(sf::Vector2f(rect.left, rect.top) + half_pixel));
    sf::Vector2f bottom_right = window_manager->mapPixelToCoords(window_manager->mapCoordsToPixel(sf::Vector2f(rect.left + rect.width, rect.top + rect.height) + half_pixel));
    rect.left = top_left.x;
    rect.top = top_left.y;
    rect.width = bottom_right.x - top_left.x;
    rect.height = bottom_right.y - top_left.y;

    sf::Vector2i texture_size = window_manager->mapCoordsToPixel(sf::Vector2f(rect.width, rect.height) + half_pixel) - window_manager->mapCoordsToPixel(sf::Vector2f(0, 0));
    unsigned int sx = powerOfTwo(texture_size.x);
    unsigned int sy = powerOfTwo(texture_size.y);
    if (texture.getSize().x != sx && texture.getSize().y != sy)
    {
        texture.create(sx, sy, false);
    }
    //Set the view so it covers this elements normal rect. So we can draw exactly the same on this texture as no the normal screen.
    sf::View view(rect);
    view.setViewport(sf::FloatRect(0, 0, float(texture_size.x) / float(sx), float(texture_size.y) / float(sy)));
    texture.setView(view);
}
void sal_init(u_int32_t size)
{

	//fprintf(stderr, "sal_init: insufficient memory");
	//abort();

	int count = powerOfTwo(size);
	//initialise global variables
	memory_size = count;
	memory = malloc(count);
	free_list_ptr = 0;
	
	//initialise first free_list_header	
	free_header_t *first = (free_header_t *) memory;
	first->magic = MAGIC_FREE;
	first->size = memory_size;
	first->next = free_list_ptr;
	first->prev = free_list_ptr;

}
Ejemplo n.º 16
0
bool Lua_MonsterClass_Valid(int32 index)
{
    return index >= 1 && index <= _class_yeti && powerOfTwo(index);
}
Ejemplo n.º 17
0
////////////////////////////////////////////////////////
// render
//
/////////////////////////////////////////////////////////
void pix_texture :: render(GemState *state) {
  m_didTexture=false;
  pushTexCoords(state);

  if(!m_textureOnOff)return;

  bool upsidedown=false;
  bool normalized=true;
  bool canMipmap=m_canMipmap;

  int texType = m_textureType;
  int x_2=1, y_2=1;
  bool useExternalTexture=false;
  int do_rectangle = (m_rectangle)?m_canRectangle:0;
  int newfilm = 0;
  pixBlock*img=NULL;


  state->get(GemState::_PIX, img);
  if(img)
    newfilm = img->newfilm;

  if (!img || !img->image.data){
    if(m_extTextureObj>0) {
      useExternalTexture= true;
      m_rebuildList     = false;
      m_textureObj      = m_extTextureObj;
      if(m_extType)m_textureType=m_extType;
      texType=m_textureType;
      upsidedown=m_extUpsidedown;
      m_xRatio=m_extWidth;
      m_yRatio=m_extHeight;
      m_upsidedown=upsidedown;
    } else
      /* neither do we have an image nor an external texture */
      return;
  }
  tex2state(state, m_coords, 4);

  if(!useExternalTexture){
    upsidedown = img->image.upsidedown;
    if (img->newimage) m_rebuildList = true;

    m_imagebuf.xsize =img->image.xsize;
    m_imagebuf.ysize =img->image.ysize;
    m_imagebuf.csize =img->image.csize;
    m_imagebuf.format=img->image.format;
    m_imagebuf.type  =img->image.type;
    m_imagebuf.data  =img->image.data;

    x_2 = powerOfTwo(m_imagebuf.xsize);
    y_2 = powerOfTwo(m_imagebuf.ysize);

    normalized = ((m_imagebuf.xsize==x_2) && (m_imagebuf.ysize==y_2));

    debug("normalized=%d\t%d - %d\t%d - %d", normalized, m_imagebuf.xsize, x_2, m_imagebuf.ysize, y_2);

    switch(do_rectangle) {
    case 2:
      m_textureType = GL_TEXTURE_RECTANGLE_ARB;
      debug("using mode 1:GL_TEXTURE_RECTANGLE_ARB");
      normalized = 0;
      canMipmap = false;
      break;
    case 1:
      m_textureType = GL_TEXTURE_RECTANGLE_EXT;
      debug("using mode 1:GL_TEXTURE_RECTANGLE_EXT");
      normalized = 0;
      canMipmap = false;
      break;
    default:
      m_textureType = GL_TEXTURE_2D;
      debug("using mode 0:GL_TEXTURE_2D");
      normalized = 0;
      break;
    }

    debug("normalized=%d", normalized);
  }

  if (m_textureType!=texType){
    debug("texType != m_textureType");
    stopRendering();startRendering();
  }

  if(GLEW_VERSION_1_3) {
    glActiveTexture(GL_TEXTURE0_ARB + m_texunit);
  }
  glEnable(m_textureType);
  glBindTexture(m_textureType, m_textureObj);

  if ((!useExternalTexture)&&newfilm ){
    //  tigital:  shouldn't we also allow TEXTURE_2D here?
    if(NULL!=glTextureRangeAPPLE) {
      if ( GLEW_APPLE_texture_range ){
        if(glTextureRangeAPPLE == NULL) {
          glTextureRangeAPPLE( m_textureType,
                               m_imagebuf.xsize * m_imagebuf.ysize * m_imagebuf.csize,
                               m_imagebuf.data );
          debug("using glTextureRangeAPPLE()");
        }else{
          glTextureRangeAPPLE( m_textureType, 0, NULL );
        }
      }
    }

    /* hmm, GL_TEXTURE_STORAGE_HINT_APPLE throws a GL-error on linux (and probably on w32 too)
     * how to do a run-time check for it?
     *
     * according to http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_texturedata/chapter_10_section_2.html
     * this seems to be a part of the texture_range extension, so we check for that!
     */
    if(GLEW_APPLE_texture_range)
       glTexParameteri( m_textureType, GL_TEXTURE_STORAGE_HINT_APPLE, GL_STORAGE_SHARED_APPLE );
    // GL_STORAGE_SHARED_APPLE -  AGP texture path
    // GL_STORAGE_CACHED_APPLE - VRAM texture path
    // GL_STORAGE_PRIVATE_APPLE - normal texture path
    if(m_clientStorage) glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
  }



  /* here comes the work: a new image has to be transfered from main memory to GPU and attached to a texture object */

  if (m_rebuildList) {
    // if YUV is not supported on this platform, we have to convert it to RGB
    //(skip Alpha since it isnt used)
    const bool do_yuv = m_yuv && GLEW_APPLE_ycbcr_422;
    if (!do_yuv && m_imagebuf.format == GL_YUV422_GEM){
      m_imagebuf.format=GL_RGB;
      m_imagebuf.csize=3;
      m_imagebuf.reallocate();
      if(img)m_imagebuf.fromYUV422(img->image.data);
    }
    if (normalized) {
      m_buffer.xsize = m_imagebuf.xsize;
      m_buffer.ysize = m_imagebuf.ysize;
      m_buffer.csize  = m_imagebuf.csize;
      m_buffer.format = m_imagebuf.format;
      m_buffer.type   = m_imagebuf.type;
      m_buffer.reallocate();
      m_xRatio=1.0;
      m_yRatio=1.0;
      m_upsidedown=upsidedown;

      tex2state(state, m_coords, 4);
      if (m_buffer.csize != m_dataSize[0] ||
          m_buffer.xsize != m_dataSize[1] ||
          m_buffer.ysize != m_dataSize[2]){
        m_dataSize[0] = m_buffer.csize;
        m_dataSize[1] = m_buffer.xsize;
        m_dataSize[2] = m_buffer.ysize;

      }
      //if the texture is a power of two in size then there is no need to subtexture
      glTexImage2D(m_textureType, 0,
                   m_imagebuf.csize,
                   m_imagebuf.xsize,
                   m_imagebuf.ysize, 0,
                   m_imagebuf.format,
                   m_imagebuf.type,
                   m_imagebuf.data);
      m_hasMipmap = false;

    } else { // !normalized
      m_xRatio = (float)m_imagebuf.xsize;
      m_yRatio = (float)m_imagebuf.ysize;
      if ( !do_rectangle ) {
        m_xRatio /= (float)x_2;
        m_yRatio /= (float)y_2;
        m_buffer.xsize = x_2;
        m_buffer.ysize = y_2;
      } else {
        m_buffer.xsize = m_imagebuf.xsize;
        m_buffer.ysize = m_imagebuf.ysize;
      }

      m_buffer.csize  = m_imagebuf.csize;
      m_buffer.format = m_imagebuf.format;
      m_buffer.type   = m_imagebuf.type;
      m_buffer.reallocate();
      m_upsidedown=upsidedown;
      tex2state(state, m_coords, 4);

      if (m_buffer.csize != m_dataSize[0] ||
          m_buffer.xsize != m_dataSize[1] ||
          m_buffer.ysize != m_dataSize[2]){
        newfilm = 1;

      } //end of loop if size has changed

      // okay, load in the actual pixel data

      //when doing rectangle textures the buffer changes after every film is loaded this call makes sure the
      //texturing is updated as well to prevent crashes
      if(newfilm) {
        m_dataSize[0] = m_buffer.csize;
        m_dataSize[1] = m_buffer.xsize;
        m_dataSize[2] = m_buffer.ysize;

        if (m_buffer.format == GL_YUV422_GEM && !m_rectangle)m_buffer.setBlack();

        if(m_numPbo>0) {
          if(GLEW_ARB_pixel_buffer_object) {
            if(m_pbo) {
              delete[]m_pbo;
              m_pbo=NULL;
            }
            m_pbo=new GLuint[m_numPbo];
            glGenBuffersARB(m_numPbo, m_pbo);
            int i=0;
            for(i=0; i<m_numPbo; i++) {
              glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pbo[i]);
              glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB,
                              m_buffer.xsize*m_buffer.ysize*m_buffer.csize,
                              0, GL_STREAM_DRAW_ARB);
            }
            glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

          } else {
            verbose(1, "PBOs not supported! disabling");
            m_numPbo=0;

          }
        }

        //this is for dealing with power of 2 textures which need a buffer that's 2^n
        if ( !do_rectangle ) {
          glTexImage2D(	m_textureType, 0,
                        //m_buffer.csize,
                        GL_RGBA,
                        m_buffer.xsize,
                        m_buffer.ysize, 0,
                        m_buffer.format,
                        m_buffer.type,
                        m_buffer.data);
          m_hasMipmap = false;
          debug("TexImage2D non rectangle");
        } else {//this deals with rectangle textures that are h*w
          glTexImage2D(m_textureType, 0,
                       //  m_buffer.csize,
                       GL_RGBA,
                       m_imagebuf.xsize,
                       m_imagebuf.ysize, 0,
                       m_imagebuf.format,
                       m_imagebuf.type,
                       m_imagebuf.data);
          m_hasMipmap = false;
          debug("TexImage2D  rectangle");
        }

        // just to make sure...
        img->newfilm = 0;
      }

      if(m_pbo && m_numPbo) {
        m_curPbo=(m_curPbo+1)%m_numPbo;
        int index=m_curPbo;
        int nextIndex=(m_curPbo+1)%m_numPbo;

        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pbo[index]);
        glTexSubImage2D(m_textureType, 0,
                        0, 0,
                        m_imagebuf.xsize,
                        m_imagebuf.ysize,
                        m_imagebuf.format,
                        m_imagebuf.type,
                        NULL); /* <-- that's the key */
        m_hasMipmap = false;

        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pbo[nextIndex]);
        glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB,  m_imagebuf.xsize * m_imagebuf.ysize * m_imagebuf.csize, 0, GL_STREAM_DRAW_ARB);

        GLubyte* ptr = (GLubyte*)glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB);
        if(ptr)
          {
            // update data off the mapped buffer
            memcpy(ptr, m_imagebuf.data,  m_imagebuf.xsize * m_imagebuf.ysize * m_imagebuf.csize);
            glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB); // release pointer to mapping buffer
          }

        /* unbind the current buffer */
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

      } else {
        glTexSubImage2D(m_textureType, 0,
                        0, 0,				// position
                        m_imagebuf.xsize,
                        m_imagebuf.ysize,
                        m_imagebuf.format,
                        m_imagebuf.type,
                        m_imagebuf.data);
        m_hasMipmap = false;
      }
    }
  } // rebuildlist

  if (m_wantMipmap && canMipmap && !m_hasMipmap) {
    glGenerateMipmap(m_textureType);
    m_hasMipmap = true;
  }
  setTexFilters(m_textureMinQuality != GL_LINEAR_MIPMAP_LINEAR || (m_wantMipmap && canMipmap));

  setTexCoords(m_coords, m_xRatio, m_yRatio, m_upsidedown);

  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, m_env);

  /* cleanup */
  m_rebuildList = false;
  m_didTexture=true;

  state->set(GemState::_GL_TEX_UNITS, m_numTexUnits);

  // if we are using rectangle textures, this is a way to inform the downstream objects
  // (this is important for things like [pix_coordinate]

  // we don't use switch/case as _ARB and _EXT might be the same...
  if(m_textureType==GL_TEXTURE_RECTANGLE_ARB || m_textureType==GL_TEXTURE_RECTANGLE_EXT) {
    state->set(GemState::_GL_TEX_TYPE, 2);
  } else {
    state->set(GemState::_GL_TEX_TYPE, 1);
  }
  
  m_baseCoord.s=m_xRatio;
  m_baseCoord.t=m_yRatio;
  state->set(GemState::_GL_TEX_BASECOORD, m_baseCoord);
  state->set(GemState::_GL_TEX_ORIENTATION, upsidedown);

  sendExtTexture(m_textureObj, m_xRatio, m_yRatio, m_textureType, upsidedown);
}
Ejemplo n.º 18
0
/* Cree un flow d'instruction optimise */
static void gsl_create_fast_iflow(void)
{ /* {{{ */
  int number = currentGoomSL->iflow->number;
  int i;
#ifdef USE_JITC_X86

  /* pour compatibilite avec les MACROS servant a execution */
  int ip = 0;
  GoomSL *gsl = currentGoomSL;

  JitcX86Env *jitc;

  if (currentGoomSL->jitc != NULL)
    jitc_x86_delete(currentGoomSL->jitc);
  jitc = currentGoomSL->jitc = jitc_x86_env_new(0xffff);
  currentGoomSL->jitc_func = jitc_prepare_func(jitc);

#if 0  
#define SRC_STRUCT_ID  instr[ip].data.usrc.var_int[-1]
#define DEST_STRUCT_ID instr[ip].data.udest.var_int[-1]
#define SRC_STRUCT_IBLOCK(i)  gsl->gsl_struct[SRC_STRUCT_ID]->iBlock[i]
#define SRC_STRUCT_FBLOCK(i)  gsl->gsl_struct[SRC_STRUCT_ID]->fBlock[i]
#define DEST_STRUCT_IBLOCK(i) gsl->gsl_struct[DEST_STRUCT_ID]->iBlock[i]
#define DEST_STRUCT_FBLOCK(i) gsl->gsl_struct[DEST_STRUCT_ID]->fBlock[i]
#define DEST_STRUCT_IBLOCK_VAR(i,j) \
  ((int*)((char*)pDEST_VAR   + gsl->gsl_struct[DEST_STRUCT_ID]->iBlock[i].data))[j]
#define DEST_STRUCT_FBLOCK_VAR(i,j) \
  ((float*)((char*)pDEST_VAR + gsl->gsl_struct[DEST_STRUCT_ID]->fBlock[i].data))[j]
#define SRC_STRUCT_IBLOCK_VAR(i,j) \
  ((int*)((char*)pSRC_VAR    + gsl->gsl_struct[SRC_STRUCT_ID]->iBlock[i].data))[j]
#define SRC_STRUCT_FBLOCK_VAR(i,j) \
  ((float*)((char*)pSRC_VAR  + gsl->gsl_struct[SRC_STRUCT_ID]->fBlock[i].data))[j]
#define DEST_STRUCT_SIZE      gsl->gsl_struct[DEST_STRUCT_ID]->size
#endif

  JITC_JUMP_LABEL(jitc, "__very_end__");
  JITC_ADD_LABEL (jitc, "__very_start__");
  
  for (i=0;i<number;++i) {
    Instruction *instr = currentGoomSL->iflow->instr[i];
    switch (instr->id) {
      case INSTR_SETI_VAR_INTEGER     :
        jitc_add(jitc, "mov [$d], $d", instr->data.udest.var_int, instr->data.usrc.value_int);
        break;
      case INSTR_SETI_VAR_VAR         :
        jitc_add(jitc, "mov eax, [$d]", instr->data.usrc.var_int);
        jitc_add(jitc, "mov [$d], eax", instr->data.udest.var_int);
        break;
        /* SET.F */
      case INSTR_SETF_VAR_FLOAT       :
        jitc_add(jitc, "mov [$d], $d", instr->data.udest.var_float, *(int*)(&instr->data.usrc.value_float));
        break;
      case INSTR_SETF_VAR_VAR         :
        jitc_add(jitc, "mov eax, [$d]", instr->data.usrc.var_float);
        jitc_add(jitc, "mov [$d], eax", instr->data.udest.var_float);
        break;
      case INSTR_NOP                  :
        if (instr->nop_label != 0)
          JITC_ADD_LABEL(jitc, instr->nop_label);
        break;
      case INSTR_JUMP                 :
        JITC_JUMP_LABEL(jitc,instr->jump_label);
        break;
      case INSTR_SETP_VAR_PTR         :
        jitc_add(jitc, "mov [$d], $d", instr->data.udest.var_ptr, instr->data.usrc.value_ptr);
        break;
      case INSTR_SETP_VAR_VAR         :
        jitc_add(jitc, "mov eax, [$d]", instr->data.usrc.var_ptr);
        jitc_add(jitc, "mov [$d], eax", instr->data.udest.var_ptr);
        break;
      case INSTR_SUBI_VAR_INTEGER     :
        jitc_add(jitc, "add [$d],  $d", instr->data.udest.var_int, -instr->data.usrc.value_int);
        break;
      case INSTR_SUBI_VAR_VAR         :
        jitc_add(jitc, "mov eax, [$d]", instr->data.udest.var_int);
        jitc_add(jitc, "sub eax, [$d]", instr->data.usrc.var_int);
        jitc_add(jitc, "mov [$d], eax", instr->data.udest.var_int);
        break;
      case INSTR_SUBF_VAR_FLOAT       :
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_SUBF_VAR_VAR         :
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_ISLOWERF_VAR_VAR:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_ISLOWERF_VAR_FLOAT:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_ISLOWERI_VAR_VAR:
        jitc_add(jitc,"mov edx, [$d]", instr->data.udest.var_int);
        jitc_add(jitc,"sub edx, [$d]", instr->data.usrc.var_int);
        jitc_add(jitc,"shr edx, $d",   31);
        break;
      case INSTR_ISLOWERI_VAR_INTEGER:
        jitc_add(jitc,"mov edx, [$d]", instr->data.udest.var_int);
        jitc_add(jitc,"sub edx, $d", instr->data.usrc.value_int);
        jitc_add(jitc,"shr edx, $d",   31);
        break;
      case INSTR_ADDI_VAR_INTEGER:
        jitc_add(jitc, "add [$d],  $d", instr->data.udest.var_int, instr->data.usrc.value_int);
        break;
      case INSTR_ADDI_VAR_VAR:
        jitc_add(jitc, "mov eax, [$d]", instr->data.udest.var_int);
        jitc_add(jitc, "add eax, [$d]", instr->data.usrc.var_int);
        jitc_add(jitc, "mov [$d], eax", instr->data.udest.var_int);
        break;
      case INSTR_ADDF_VAR_FLOAT:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_ADDF_VAR_VAR:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_MULI_VAR_INTEGER:
        if (instr->data.usrc.value_int != 1)
        {
          int po2 = powerOfTwo(instr->data.usrc.value_int);
          if (po2) {
            /* performs (V / 2^n) by doing V >> n */
            jitc_add(jitc, "mov  eax, [$d]",  instr->data.udest.var_int);
            jitc_add(jitc, "sal  eax, $d",    po2);
            jitc_add(jitc, "mov  [$d], eax",  instr->data.udest.var_int);
          }
          else {
            jitc_add(jitc, "mov  eax, [$d]", instr->data.udest.var_int);
            jitc_add(jitc, "imul eax, $d",   instr->data.usrc.value_int);
            jitc_add(jitc, "mov  [$d], eax", instr->data.udest.var_int);
          }
        }
        break;
      case INSTR_MULI_VAR_VAR:
        jitc_add(jitc, "mov  eax,  [$d]", instr->data.udest.var_int);
        jitc_add(jitc, "imul eax,  [$d]", instr->data.usrc.var_int);
        jitc_add(jitc, "mov  [$d], eax",  instr->data.udest.var_int);
        break;
      case INSTR_MULF_VAR_FLOAT:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_MULF_VAR_VAR:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_DIVI_VAR_INTEGER:
        if ((instr->data.usrc.value_int != 1) && (instr->data.usrc.value_int != 0))
        {
          int po2 = powerOfTwo(instr->data.usrc.value_int);
          if (po2) {
            /* performs (V / 2^n) by doing V >> n */
            jitc_add(jitc, "mov  eax, [$d]",  instr->data.udest.var_int);
            jitc_add(jitc, "sar  eax, $d",    po2);
            jitc_add(jitc, "mov  [$d], eax",  instr->data.udest.var_int);
          }
          else {
            /* performs (V/n) by doing (V*(32^2/n)) */
            long   coef;
            double dcoef = (double)4294967296.0 / (double)instr->data.usrc.value_int;
            if (dcoef < 0.0) dcoef = -dcoef;
            coef   = (long)floor(dcoef);
            dcoef -= floor(dcoef);
            if (dcoef < 0.5) coef += 1;
            
            jitc_add(jitc, "mov  eax, [$d]", instr->data.udest.var_int);
            jitc_add(jitc, "mov  edx, $d",   coef);
            jitc_add(jitc, "imul edx");
            if (instr->data.usrc.value_int < 0)
              jitc_add(jitc, "neg edx");
            jitc_add(jitc, "mov [$d], edx", instr->data.udest.var_int);
          }
        }
        break;
      case INSTR_DIVI_VAR_VAR         :
        jitc_add(jitc, "mov  eax, [$d]", instr->data.udest.var_int);
        jitc_add(jitc, "cdq"); /* sign extend eax into edx */
        jitc_add(jitc, "idiv [$d]", instr->data.usrc.var_int);
        jitc_add(jitc, "mov [$d], eax", instr->data.udest.var_int);
        break;
      case INSTR_DIVF_VAR_FLOAT:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_DIVF_VAR_VAR:
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_JZERO:
        jitc_add(jitc, "cmp edx, $d", 0);
        jitc_add(jitc, "je $s", instr->jump_label);
        break;
      case INSTR_ISEQUALP_VAR_VAR     :
        jitc_add(jitc, "mov eax, [$d]", instr->data.udest.var_ptr);
        jitc_add(jitc, "mov edx, $d",   0);
        jitc_add(jitc, "cmp eax, [$d]", instr->data.usrc.var_ptr);
        jitc_add(jitc, "jne $d",        1);
        jitc_add(jitc, "inc edx");
        break;
      case INSTR_ISEQUALP_VAR_PTR     :
        jitc_add(jitc, "mov eax, [$d]", instr->data.udest.var_ptr);
        jitc_add(jitc, "mov edx, $d",   0);
        jitc_add(jitc, "cmp eax, $d",   instr->data.usrc.value_ptr);
        jitc_add(jitc, "jne $d",        1);
        jitc_add(jitc, "inc edx");
        break;
      case INSTR_ISEQUALI_VAR_VAR     :
        jitc_add(jitc, "mov eax, [$d]", instr->data.udest.var_int);
        jitc_add(jitc, "mov edx, $d",   0);
        jitc_add(jitc, "cmp eax, [$d]", instr->data.usrc.var_int);
        jitc_add(jitc, "jne $d",        1);
        jitc_add(jitc, "inc edx");
        break;
      case INSTR_ISEQUALI_VAR_INTEGER :
        jitc_add(jitc, "mov eax, [$d]", instr->data.udest.var_int);
        jitc_add(jitc, "mov edx, $d",   0);
        jitc_add(jitc, "cmp eax, $d", instr->data.usrc.value_int);
        jitc_add(jitc, "jne $d",        1);
        jitc_add(jitc, "inc edx");
        break;
      case INSTR_ISEQUALF_VAR_VAR     :
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_ISEQUALF_VAR_FLOAT   :
        printf("NOT IMPLEMENTED : %d\n", instr->id);
        break;
      case INSTR_CALL:
        jitc_add(jitc, "call $s", instr->jump_label);
        break;
      case INSTR_RET:
        jitc_add(jitc, "ret");
        break;
      case INSTR_EXT_CALL:
        jitc_add(jitc, "mov eax, [$d]", &(instr->data.udest.external_function->vars));
        jitc_add(jitc, "push eax");
        jitc_add(jitc, "mov edx, [$d]", &(currentGoomSL->vars));
        jitc_add(jitc, "push edx");
        jitc_add(jitc, "mov eax, [$d]", &(currentGoomSL));
        jitc_add(jitc, "push eax");

        jitc_add(jitc, "mov eax, [$d]",  &(instr->data.udest.external_function));
        jitc_add(jitc, "mov eax, [eax]");
        jitc_add(jitc, "call [eax]");
        jitc_add(jitc, "add esp, $d", 12);
        break;
      case INSTR_NOT_VAR:
        jitc_add(jitc, "mov eax, edx");
        jitc_add(jitc, "mov edx, $d", 1);
        jitc_add(jitc, "sub edx, eax");
        break;
      case INSTR_JNZERO:
        jitc_add(jitc, "cmp edx, $d", 0);
        jitc_add(jitc, "jne $s", instr->jump_label);
        break;
      case INSTR_SETS_VAR_VAR:
        {
          int loop = DEST_STRUCT_SIZE / sizeof(int);
          int dst  = (int)pDEST_VAR;
          int src  = (int)pSRC_VAR;
        
          while (loop--) {
            jitc_add(jitc,"mov eax, [$d]", src);
            jitc_add(jitc,"mov [$d], eax", dst);
            src += 4;
            dst += 4;
          }
        }
        break;
      case INSTR_ISEQUALS_VAR_VAR:
        break;
      case INSTR_ADDS_VAR_VAR:
        {
        /* process integers */
        int i=0;
        while (DEST_STRUCT_IBLOCK(i).size > 0) {
          int j=DEST_STRUCT_IBLOCK(i).size;
          while (j--) { /* TODO interlace 2 */
            jitc_add(jitc, "mov eax, [$d]", &DEST_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "add eax, [$d]", &SRC_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "mov [$d], eax", &DEST_STRUCT_IBLOCK_VAR(i,j));
          }
          ++i;
        }
        /* process floats */
        i=0;
        while (DEST_STRUCT_FBLOCK(i).size > 0) {
          int j=DEST_STRUCT_FBLOCK(i).size;
          while (j--) {
            /* DEST_STRUCT_FBLOCK_VAR(i,j) += SRC_STRUCT_FBLOCK_VAR(i,j); */
            /* TODO */
          }
          ++i;
        }
        break;
        }
      case INSTR_SUBS_VAR_VAR:
        {
        /* process integers */
        int i=0;
        while (DEST_STRUCT_IBLOCK(i).size > 0) {
          int j=DEST_STRUCT_IBLOCK(i).size;
          while (j--) {
            jitc_add(jitc, "mov eax, [$d]", &DEST_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "sub eax, [$d]", &SRC_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "mov [$d], eax", &DEST_STRUCT_IBLOCK_VAR(i,j));
          }
          ++i;
        }
        break;
        }
      case INSTR_MULS_VAR_VAR:
        {
        /* process integers */
        int i=0;
        while (DEST_STRUCT_IBLOCK(i).size > 0) {
          int j=DEST_STRUCT_IBLOCK(i).size;
          while (j--) {
            jitc_add(jitc, "mov  eax,  [$d]", &DEST_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "imul eax,  [$d]", &SRC_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "mov  [$d], eax",  &DEST_STRUCT_IBLOCK_VAR(i,j));
          }
          ++i;
        }
        break;
        }
      case INSTR_DIVS_VAR_VAR:
        {
        /* process integers */
        int i=0;
        while (DEST_STRUCT_IBLOCK(i).size > 0) {
          int j=DEST_STRUCT_IBLOCK(i).size;
          while (j--) {
            jitc_add(jitc, "mov  eax,  [$d]", &DEST_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "cdq");
            jitc_add(jitc, "idiv [$d]",       &SRC_STRUCT_IBLOCK_VAR(i,j));
            jitc_add(jitc, "mov  [$d], eax",  &DEST_STRUCT_IBLOCK_VAR(i,j));
          }
          ++i;
        }
        break;
        }
    }
  }

  JITC_ADD_LABEL (jitc, "__very_end__");
  jitc_add(jitc, "call $s", "__very_start__");
  jitc_add(jitc, "mov eax, $d", 0);
  jitc_validate_func(jitc);
#else
  InstructionFlow     *iflow     = currentGoomSL->iflow;
  FastInstructionFlow *fastiflow = (FastInstructionFlow*)malloc(sizeof(FastInstructionFlow));
  fastiflow->mallocedInstr = calloc(number*16, sizeof(FastInstruction));
  /* fastiflow->instr = (FastInstruction*)(((int)fastiflow->mallocedInstr) + 16 - (((int)fastiflow->mallocedInstr)%16)); */
  fastiflow->instr = (FastInstruction*)fastiflow->mallocedInstr;
  fastiflow->number = number;
  for(i=0;i<number;++i) {
    fastiflow->instr[i].id    = iflow->instr[i]->id;
    fastiflow->instr[i].data  = iflow->instr[i]->data;
    fastiflow->instr[i].proto = iflow->instr[i];
  }
  currentGoomSL->fastiflow = fastiflow;
#endif
} /* }}} */
Ejemplo n.º 19
0
/////////////////////////////////////////////////////////
// snapMess
//
/////////////////////////////////////////////////////////
void pix_snap2tex :: snapMess(void)
{
 if(getState()==INIT) {
    verbose(0, "not initialized yet with a valid context");
    return;
  }
  if(!GLEW_VERSION_1_1 && !GLEW_EXT_texture_object) return;

  int width  = m_width;
  int height = m_height;

  GemMan::getDimen(((m_width >0)?NULL:&width ),
                   ((m_height>0)?NULL:&height));

  if (width <= 0 || height <= 0)
    {
      error("Illegal size %dx%d", width, height);
      return;
    }

  if(GLEW_VERSION_1_3) {
    glActiveTexture(GL_TEXTURE0_ARB + m_texUnit);
  }

  m_textureType = (m_rectangle?m_canRectangle:GL_TEXTURE_2D);

  glEnable(m_textureType);

  if(GLEW_VERSION_1_1) {
    glBindTexture(m_textureType, m_textureObj);
  } else {
    glBindTextureEXT(m_textureType, m_textureObj);
  }

  if (m_init) {
    m_init=false;
    // if the size changed, then reset the texture
    if(GL_TEXTURE_2D == m_textureType) {
      int x_2 = powerOfTwo(width);
      int y_2 = powerOfTwo(height);
      m_texWidth = x_2;
      m_texHeight = y_2;
      setTexCoords((float)width / (float)x_2, (float)height / (float)y_2);

      glCopyTexImage2D(	m_textureType, 0,
                        GL_RGBA16,
                        m_x, m_y,
                        m_texWidth, m_texHeight,
                        0);
    } else {
      setTexCoords(width, height);
      m_texWidth  = width;
      m_texHeight = height;
      glCopyTexImage2D(	m_textureType, 0,
                        GL_RGBA16,
                        m_x, m_y,
                        m_texWidth, m_texHeight,
                        0);
    }
  } else {
    m_texHeight = height;
    m_texWidth = width;
  }

  glCopyTexSubImage2D(m_textureType, 0,
                      0, 0,
                      m_x, m_y,		// position
                      m_texWidth, m_texHeight);

  glDisable(m_textureType);

  if(GLEW_VERSION_1_3) {
    glActiveTexture(GL_TEXTURE0_ARB);
  }
}
Ejemplo n.º 20
0
    void
    ImageLoader::ensurePowerOfTwo(const std::string & theResizeMode,
                                  unsigned theDepth, const asl::Vector2i * theTile)
    {
        // limit texture size
        int myTextureSizeLimit = 0;
        if (asl::Ptr<ITextureManager> myTextureManager = _myTextureManager.lock()) {
            myTextureSizeLimit = myTextureManager->getMaxTextureSize( theDepth = 1 ? 2 : 3 );
            AC_INFO << "Texture size limit set to " << myTextureSizeLimit;
        } else {
            myTextureSizeLimit = ITextureManager::getTextureSizeLimit();
        }
        AC_DEBUG << "Texture size limit = " << myTextureSizeLimit;

        if (theResizeMode == IMAGE_RESIZE_NONE &&
            (!myTextureSizeLimit || (GetWidth() <= myTextureSizeLimit && GetHeight() <= myTextureSizeLimit))) {
            return;
        }

        if (!powerOfTwo(theDepth)) {
            throw ImageLoaderException(
                string("ensurePowerOfTwo: third dimension (depth) must be power of two for now"),
                    PLUS_FILE_LINE);
        }

        bool myIsCubemapFlag = false;
        if (theTile) {
            unsigned myNumTiles = (*theTile)[0] * (*theTile)[1];
            myIsCubemapFlag = (myNumTiles == 6 ? true : false);
        }
        try {
            int myWidthFactor = 1, myHeightFactor = theDepth;
            if (myIsCubemapFlag) {
                myWidthFactor *= (*theTile)[0];
                myHeightFactor *= (*theTile)[1];
                AC_DEBUG << "tile=" << *theTile << " factor=" << myWidthFactor << "x" << myHeightFactor << " size=" << GetWidth() << "x" << GetHeight();
            }

            unsigned myPreScaleWidth  = GetWidth();
            unsigned myPreScaleHeight = GetHeight();

            if ((myPreScaleWidth % myWidthFactor) != 0) {
                throw ImageLoaderException(
                        string("ensurePowerOfTwo: '" + _myFilename + "' texture strip width must be a multiple of ")+
                        as_string(myWidthFactor), PLUS_FILE_LINE);
            }
            if ((myPreScaleHeight % myHeightFactor) != 0) {
                throw ImageLoaderException(
                        string("ensurePowerOfTwo: '" + _myFilename + "' texture strip height must be a multiple of ")+
                        as_string(myHeightFactor), PLUS_FILE_LINE);
            }

            AC_DEBUG << "GetWidth() = " << GetWidth();
            AC_DEBUG << "GetHeight() = " << GetHeight();
            AC_DEBUG << "myWidthFactor = " << myWidthFactor;
            AC_DEBUG << "myHeightFactor = " << myHeightFactor;

            int myTargetWidth = GetWidth();
            int myTargetHeight = GetHeight();
             if (!powerOfTwo(GetWidth() / myWidthFactor) || !powerOfTwo(GetHeight() / myHeightFactor)) {
                myTargetWidth  = nextPowerOfTwo(GetWidth() / myWidthFactor) * myWidthFactor;
                myTargetHeight = nextPowerOfTwo(GetHeight() / myHeightFactor) * myHeightFactor;
            }
            AC_DEBUG << "myTargetWidth = " << myTargetWidth;
            AC_DEBUG << "myTargetHeight = " << myTargetHeight;

            while (myTextureSizeLimit &&
                ((myTargetWidth / myWidthFactor) > myTextureSizeLimit ||
                 (myTargetHeight / myHeightFactor)  > myTextureSizeLimit) )
            {
                myTargetWidth  = (myTargetWidth / myWidthFactor)/2 * myWidthFactor;
                myTargetHeight = (myTargetHeight / myHeightFactor)/2 * myHeightFactor;
            }
            AC_DEBUG << "GetWidth() = " << myTargetWidth;
            AC_DEBUG << "GetHeight() = " << myTargetHeight;
            AC_DEBUG << "myTargetWidth = " << myTargetWidth;
            AC_DEBUG << "myTargetHeight = " << myTargetHeight;

            if (myTextureSizeLimit &&
                (myTargetWidth != GetWidth() || myTargetHeight != GetHeight())) {
                AC_WARNING << "Texture size exceeds "<<Y60_TEXTURE_SIZE_LIMIT_ENV<<"="<<
                    myTextureSizeLimit<<", resizing to "<<
                    myTargetWidth<<"x"<<myTargetHeight<<endl;
                ApplyFilter(PLFilterResizeBilinear(myTargetWidth, myTargetHeight));
            }

            if (!powerOfTwo(GetWidth() / myWidthFactor) || !powerOfTwo(GetHeight() / myHeightFactor)) {

                unsigned myWidth  = nextPowerOfTwo(GetWidth() / myWidthFactor) * myWidthFactor;
                unsigned myHeight = nextPowerOfTwo(GetHeight() / myHeightFactor) * myHeightFactor;

                if (theResizeMode == IMAGE_RESIZE_SCALE) {
                    AC_INFO << "Resizing bitmap " << _myFilename << " to next power of two: " << myWidth << "x" << myHeight << ".";
                    ApplyFilter(PLFilterResizeBilinear(myWidth, myHeight));
                } else if (theResizeMode == IMAGE_RESIZE_PAD) {
                    //TODO: make padding for for cube maps and 3D texture strips
                    AC_INFO << "Padding bitmap '" << _myFilename << "' to next power of two: " << myWidth << "x" << myHeight << ".";
                    ApplyFilter(PLFilterResizePadded(myWidth, myHeight));
                    _myImageMatrix.scale(Vector3f(float(myPreScaleWidth) / GetWidth(),
                            float(myPreScaleHeight) / GetHeight(), 1.0f));
                } else {
                    throw ImageLoaderException(string("ensurePowerOfTwo: Unknown resize mode: ")
                            + theResizeMode, PLUS_FILE_LINE);
                }
            }

            // convert paletted textures
        } catch (PLTextException & ex) {
            throw ImageLoaderException(std::string("Paintlib exception ")+std::string(ex), PLUS_FILE_LINE);
        }
    }
Ejemplo n.º 21
0
/////////////////////////////////////////////////////////
// snapMess
//
/////////////////////////////////////////////////////////
void pix_snap2tex :: snapMess()
{
  if(!GLEW_VERSION_1_1 && !GLEW_EXT_texture_object) return;
  
  int width  = m_width;
  int height = m_height;

  GemMan::getDimen(((m_width >0)?NULL:&width ),
		   ((m_height>0)?NULL:&height));

  if (width <= 0 || height <= 0)
    {
      error("Illegal size");
      return;
    }

  glEnable(m_textureType);

  if(GLEW_VERSION_1_1) {
    glBindTexture(m_textureType, m_textureObj);
  } else {
    glBindTextureEXT(m_textureType, m_textureObj);
  }

  // if the size changed, then reset the texture
  int x_2 = powerOfTwo(width);
  int y_2 = powerOfTwo(height);

  if (width != m_oldWidth || height != m_oldHeight) 
    {
      m_oldWidth = width;
      m_oldHeight = height;
      
      float m_xRatio = (float)width / (float)x_2;
      float m_yRatio = (float)height / (float)y_2;
		
      m_coords[0].s = 0.f;
      m_coords[0].t = 0.f;
		
      m_coords[1].s = m_xRatio;
      m_coords[1].t = 0.f;
		
      m_coords[2].s = m_xRatio;
      m_coords[2].t = m_yRatio;
		
      m_coords[3].s = 0.f;
      m_coords[3].t = m_yRatio;

      m_texWidth = x_2;
      m_texHeight = y_2;
		
      glCopyTexImage2D(	m_textureType, 0,
			GL_RGBA16,
			m_x, m_y,
			m_texWidth, m_texHeight, 
			0);
      
    } else {
    m_texHeight = m_height;
    m_texWidth = m_width;
  }
  
  glCopyTexSubImage2D(m_textureType, 0,
                      0, 0,
                      m_x, m_y,		// position
                      m_texWidth,
                      m_texHeight);		
  
  glDisable(m_textureType);

}
bool LTexture::loadPixelsFromFile32( std::string path )
{
    //Free texture data if needed
    freeTexture();

    //Texture loading success
    bool pixelsLoaded = false;

    //Generate and set current image ID
    ILuint imgID = 0;
    ilGenImages( 1, &imgID );
    ilBindImage( imgID );

    //Load image
    ILboolean success = ilLoadImage( path.c_str() );

    //Image loaded successfully
    if( success == IL_TRUE )
    {
        //Convert image to RGBA
        success = ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );
        if( success == IL_TRUE )
        {
            //Initialize dimensions
            GLuint imgWidth = (GLuint)ilGetInteger( IL_IMAGE_WIDTH );
            GLuint imgHeight = (GLuint)ilGetInteger( IL_IMAGE_HEIGHT );

            //Calculate required texture dimensions
            GLuint texWidth = powerOfTwo( imgWidth );
            GLuint texHeight = powerOfTwo( imgHeight );

            //Texture is the wrong size
            if( imgWidth != texWidth || imgHeight != texHeight )
            {
                //Place image at upper left
                iluImageParameter( ILU_PLACEMENT, ILU_UPPER_LEFT );

                //Resize image
                iluEnlargeCanvas( (int)texWidth, (int)texHeight, 1 );
            }

            //Allocate memory for texture data
            GLuint size = texWidth * texHeight;
            mPixels32 = new GLuint[ size ];

            //Get image dimensions
            mImageWidth = imgWidth;
            mImageHeight = imgHeight;
            mTextureWidth = texWidth;
            mTextureHeight = texHeight;

            //Copy pixels
            memcpy( mPixels32, ilGetData(), size * 4 );
            pixelsLoaded = true;
        }

        //Delete file from memory
        ilDeleteImages( 1, &imgID );

        //Set pixel format
        mPixelFormat = GL_RGBA;
    }

    //Report error
    if( !pixelsLoaded )
    {
        printf( "Unable to load %s\n", path.c_str() );
    }

    return pixelsLoaded;
}
Ejemplo n.º 23
0
Image *Image::load(SDL_Surface *tmpImage)
{
#ifdef USE_OPENGL
    if (mUseOpenGL)
    {
        // Flush current error flag.
        glGetError();

        int width = tmpImage->w;
        int height = tmpImage->h;
        int realWidth = powerOfTwo(width);
        int realHeight = powerOfTwo(height);

        if (realWidth < width || realHeight < height)
        {
            logger->log("Warning: image too large, cropping to %dx%d texture!",
                    tmpImage->w, tmpImage->h);
        }

        // Make sure the alpha channel is not used, but copied to destination
        SDL_SetAlpha(tmpImage, 0, SDL_ALPHA_OPAQUE);

        // Determine 32-bit masks based on byte order
        Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
        rmask = 0xff000000;
        gmask = 0x00ff0000;
        bmask = 0x0000ff00;
        amask = 0x000000ff;
#else
        rmask = 0x000000ff;
        gmask = 0x0000ff00;
        bmask = 0x00ff0000;
        amask = 0xff000000;
#endif

        SDL_Surface *oldImage = tmpImage;
        tmpImage = SDL_CreateRGBSurface(SDL_SWSURFACE, realWidth, realHeight,
                                        32, rmask, gmask, bmask, amask);

        if (!tmpImage)
        {
            logger->log("Error, image convert failed: out of memory");
            return NULL;
        }

        SDL_BlitSurface(oldImage, NULL, tmpImage, NULL);

        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(mTextureType, texture);

        if (SDL_MUSTLOCK(tmpImage))
            SDL_LockSurface(tmpImage);

        glTexImage2D(mTextureType, 0, 4, tmpImage->w, tmpImage->h,
                     0, GL_RGBA, GL_UNSIGNED_BYTE, tmpImage->pixels);

        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
        glTexParameteri(mTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(mTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        if (SDL_MUSTLOCK(tmpImage))
            SDL_UnlockSurface(tmpImage);

        SDL_FreeSurface(tmpImage);

        GLenum error = glGetError();
        if (error)
        {
            std::string errmsg = "Unknown error";
            switch (error)
            {
                case GL_INVALID_ENUM:
                    errmsg = "GL_INVALID_ENUM";
                    break;
                case GL_INVALID_VALUE:
                    errmsg = "GL_INVALID_VALUE";
                    break;
                case GL_INVALID_OPERATION:
                    errmsg = "GL_INVALID_OPERATION";
                    break;
                case GL_STACK_OVERFLOW:
                    errmsg = "GL_STACK_OVERFLOW";
                    break;
                case GL_STACK_UNDERFLOW:
                    errmsg = "GL_STACK_UNDERFLOW";
                    break;
                case GL_OUT_OF_MEMORY:
                    errmsg = "GL_OUT_OF_MEMORY";
                    break;
            }
            logger->log("Error: Image GL import failed: %s", errmsg.c_str());
            return NULL;
        }

        return new Image(texture, width, height, realWidth, realHeight);
    }
#endif

    bool hasAlpha = false;

    Uint8* imageAlphas = new Uint8[tmpImage->w * tmpImage->h];
    if (tmpImage->format->BitsPerPixel == 32)
    {
        // Figure out whether the image uses its alpha layer
        for (int i = 0; i < tmpImage->w * tmpImage->h; ++i)
        {
            Uint8 r, g, b, a;
            SDL_GetRGBA(((Uint32*) tmpImage->pixels)[i],
                          tmpImage->format, &r, &g, &b, &a);

            imageAlphas[i] = a;

            if (a != 255)
                hasAlpha = true;
        }
    }

    SDL_Surface *image;

    // Convert the surface to the current display format
    if (hasAlpha)
        image = SDL_DisplayFormatAlpha(tmpImage);
    else
        image = SDL_DisplayFormat(tmpImage);

    if (!image)
    {
        logger->log("Error: Image convert failed.");
        return NULL;
    }

    return new Image(image, imageAlphas);
}
Ejemplo n.º 24
0
Texture*
TextureManagerGL::create(SDL_Surface* image)
{
    int texture_w = powerOfTwo(image->w);
    int texture_h = powerOfTwo(image->h);

    //int texture_w = image->w;
    //int texture_h = image->h;
    //LOGD("[Lincity]TextureManagerGL::create() - w=%d h=%d w=%d h=%d pitch=%d\n",texture_w,texture_h,image->w,image->h,image->pitch);

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    SDL_Surface* convert = SDL_CreateRGBSurface(SDL_SWSURFACE,
            texture_w, texture_h, 32,
            0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
#else
    SDL_Surface* convert = SDL_CreateRGBSurface(SDL_SWSURFACE,
        texture_w, texture_h, 32,
        0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
#endif

    if(convert == 0) {
        std::ostringstream msg;
        msg << "Couldn't convert SDL_Surface while creating texture"
            << " (out of memory?): " << SDL_GetError();
        throw std::runtime_error(msg.str());
    }
    SDL_SetAlpha(image, 0, 0);
     SDL_BlitSurface(image, 0, convert, 0);



    GLuint handle;
    glGenTextures(1, &handle);

    SDL_PixelFormat* format = convert->format;

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glBindTexture(GL_TEXTURE_2D, handle);

    //LOGD("[Lincity]TextureManagerGL::create() - Handle %d\n",handle);
    //glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    //glPixelStorei(GL_UNPACK_ROW_LENGTH, convert->pitch/format->BytesPerPixel);
    //assert(convert->pitch == texture_w * convert->format->BytesPerPixel);

       /*
    glTexImage2D(GL_TEXTURE_2D, 0, format->BytesPerPixel,
            convert->w, convert->h, 0, GL_RGBA,
            GL_UNSIGNED_BYTE, convert->pixels);
         */
         

    glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA,
            convert->w, convert->h, 0, GL_RGBA,
             GL_UNSIGNED_BYTE, convert->pixels);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

   /*
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP);
     */
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
    TextureGL* texture = new TextureGL(handle);

    texture->rect = Rect2D(0, 0,
            (float) image->w/(float) texture_w,
            (float) image->h/(float) texture_h);

    /*
    texture->rect = Rect2D(0, 0,
            1.,
            1.);
            */
    texture->width = image->w;
    texture->height = image->h;

    SDL_FreeSurface(image);
    SDL_FreeSurface(convert);

    if (int a = glGetError() != 0)
    {
       LOGD("[Lincity]TextureManagerGL::create() ERROR OCCURED : %d\n",a);

       switch (a) {
        case GL_INVALID_ENUM:
        LOGD("[Lincity]TextureManagerGL::create() GL_INVALID_ENUM\n");
        break;
        case GL_INVALID_VALUE:
        LOGD("[Lincity]TextureManagerGL::create() GL_INVALID_VALUE\n");
        break;
        case GL_INVALID_OPERATION:
        LOGD("[Lincity]TextureManagerGL::create() GL_INVALID_OPERATION\n");
        break;
        case GL_STACK_OVERFLOW:
        LOGD("[Lincity]TextureManagerGL::create() GL_STACK_OVERFLOW\n");;
        break;
        case GL_STACK_UNDERFLOW:
        LOGD("[Lincity]TextureManagerGL::create() GL_STACK_UNDERFLOW\n");
        break;
        case GL_OUT_OF_MEMORY:
        LOGD("[Lincity]TextureManagerGL::create() GL_OUT_OF_MEMORY\n");
        break;
       }
    }
    return texture;
}