Question

I have a problem with trying to make procedural textures in SFML i have this code

sf::Texture* CreateTexture(int w, int h){
   sf::Image tempImage;
   sf::Texture* Tex = new sf::Texture();
   Tex->create(w,h);
   sf::Uint8 *pixelData = GeneratePNoise(w,h);

   tempImage.create(w, h, pixelData);
   Tex->update(tempImage);
   //Tex->loadFromImage(tempImage);
   return Tex;
}
sf::Uint8* GeneratePNoise(int w,int h){
   std::vector<sf::Uint8> data(w*h*4);

   for (int i=0;i<w*h*4;i++){
     data[i]=128;
     if (i+1%4)data[i]=255;
   }

   return data.data();
}
sf::Texture CreateTexturens(int w, int h){
   sf::Image tempImage;
   sf::Texture Tex;
   Tex.create(w,h);
   sf::Uint8 *pixelData = GeneratePNoise(w,h);

   tempImage.create(w, h, pixelData);
   Tex.update(tempImage);
   return Tex;
}

I also have this code which uses the above code

void Star::createStar(){
   sf::CircleShape star(r,30);
   star.setPosition(x,y);
   sf::Texture* t = CreateTexture(256,256);
   star.setTexture(t,false);
   std::cout << "Done!"<<std::endl;
}

This doesn't seem to render anything, I believe it is about the code revolving around creating and applying the texture, all help is appreciated!

Was it helpful?

Solution

In the GeneratePNoise() function, you are returning the data() from a vector that is going to be destroyed upon the returning of that function, and thus the data won't be available anymore.

Instead of a vector, I would recommend creating a unique_ptr and returning that unique_ptr from the function, such as:

unique_ptr<sf::Uint8[]> GeneratePNoise(int w, int h) 
{
    unique_ptr<sf::Uint8[]> data(new sf::Uint8[w * h * 4]);

    for (int i = 0; i  < w * h * 4; i++) {
      data[i] = 128;
      if (i + 1 % 4) 
         data[i] = 255;
    }

    return data;
}

In that case you don't even need to delete the resource that was returned. You should do the same with the CreateTexture() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top