c++ - SFML 中的程序纹理

标签 c++ textures sfml procedural

我在尝试在 SFML 中制作程序纹理时遇到问题我有这段代码

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;
}

我也有使用上述代码的代码

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;
}

这似乎没有渲染任何东西,我相信这是关于围绕创建和应用纹理的代码,感谢所有帮助!

最佳答案

在 GeneratePNoise() 函数中,您从一个 vector 返回 data(),该 vector 将在该函数返回时被销毁,因此数据将不再可用。

我建议创建一个 unique_ptr 并从函数返回该 unique_ptr,而不是 vector ,例如:

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;
}

在这种情况下,您甚至不需要删除返回的资源。您应该对 CreateTexture() 函数执行相同的操作。

关于c++ - SFML 中的程序纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17303976/

相关文章:

ios - 在 Sprite Kit 中使用纹理图集有什么好处?

c++ - SFML window.clear() 不清除屏幕?

c++ - std::vector在push_back和insert(end(),x)之间不一致崩溃

java.lang 在 JNI 中调用 BluetoothAdapter.getDefaultAdapter() 时抛出 UNsatisfiedLinkError

c++ - qt,信号槽没有连接?

c++ - fgetws 无法从 FILE* 中获取准确的宽字符字符串

c++ - OpenGL - 不显示简单的 2D 纹理

matlab - 从照片中去除纸张纹理图案

GTK 和 SFML 2 模糊 Sprite

c++ - 如何在 C++ 中使用带有 SFML 的 http 请求从 node.js 服务器获取数据?