SFML中的2D水着色器

4
我想实现一个二维水面算法,描述在这里这里。但是,我不想使用两个int数组并在CPU上计算,我想使用SFML的sf::RenderTexture(基本上是FBO)和GLSL着色器在GPU上运行所有内容。我想使用SFML,因为它非常简单,而且我之前已经使用过它,所以我对它有一定了解。
到目前为止,我已经取得了一些进展。我能够正确地设置3个sf::RenderTextures并在它们之间进行ping-pong(因为除了int数组之外,您不能同时读写同一个sf::RenderTexture)。我还能够将高度场创建算法从范围-32.767到32.767适应到范围0到1(或更准确地说是-0.5到0.5进行计算)。添加新的涟漪也可以在某种程度上起作用。所以到这一点上,你实际上可以看到一些波浪。

现在出现了我的问题:波浪消失得非常快,即使我还没有施加任何阻尼。根据算法,如果没有施加阻尼,涟漪不会停止。甚至恰恰相反。如果我施加“放大”,波浪看起来接近您期望的样子(但它们仍然会在没有施加任何阻尼的情况下消失)。我的第一个想法是,这是因为我使用的是0-1范围内的浮点数,而不是整数,但我只看到这在使用乘法时会成为问题,但我只使用加法和减法。

以下是我的SFML C++代码:

#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode(1000, 1000), "SFML works!");
    window.setFramerateLimit(12);

    sf::RenderTexture buffers[3];
    buffers[0].create(500, 500);
    buffers[1].create(500, 500);
    buffers[2].create(500, 500);
    sf::RenderTexture* firstBuffer = buffers;
    sf::RenderTexture* secondBuffer = &buffers[1];
    sf::RenderTexture* finalBuffer = &buffers[2];

    firstBuffer->clear(sf::Color(128, 128, 128));
    secondBuffer->clear(sf::Color(128, 128, 128));
    finalBuffer->clear(sf::Color(128, 128, 128));

    sf::Shader waterHeightmapShader;
    waterHeightmapShader.loadFromFile("waterHeightmapShader.glsl", sf::Shader::Fragment);

    sf::Sprite spritefirst;
    spritefirst.setPosition(0, 0);
    spritefirst.setTexture(firstBuffer->getTexture());

    sf::Sprite spritesecond;
    spritesecond.setPosition(500, 0);
    spritesecond.setTexture(secondBuffer->getTexture());

    sf::Sprite spritefinal;
    spritefinal.setPosition(0, 500);
    spritefinal.setTexture(finalBuffer->getTexture());

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
                window.close();

            if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Escape)
                window.close();
        }


        waterHeightmapShader.setParameter("mousePosition", sf::Vector2f(-1.f, -1.f));
        // if mouse button is pressed add new ripples
        if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
        {
            sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
            if(mousePosition.x < 500 && mousePosition.y < 500)
            {
                sf::Vector2f mouse(mousePosition);

                mouse.x /= 500.f;
                mouse.y /= 500.f;

                mouse.y = 1 - mouse.y;


                std::cout << mouse.x << " " << mouse.y << std::endl;

                waterHeightmapShader.setParameter("mousePosition", mouse);
            }
        }


        waterHeightmapShader.setParameter("textureTwoFramesAgo", firstBuffer->getTexture());
        waterHeightmapShader.setParameter("textureOneFrameAgo", secondBuffer->getTexture());

        // create the heightmap
        secondBuffer->display();
        finalBuffer->clear(sf::Color(128, 128, 128));
        finalBuffer->draw(sf::Sprite(secondBuffer->getTexture()), &waterHeightmapShader);
        finalBuffer->display();


        spritefirst.setTexture(firstBuffer->getTexture());
        spritesecond.setTexture(secondBuffer->getTexture());
        spritefinal.setTexture(finalBuffer->getTexture());

        window.clear();
        window.draw(spritefirst);
        window.draw(spritesecond);
        window.draw(spritefinal);
        window.display();

        // swap the buffers around, first becomes second, second becomes third and third becomes first
        sf::RenderTexture* swapper = firstBuffer;
        firstBuffer = secondBuffer;
        secondBuffer = finalBuffer;
        finalBuffer = swapper;
    }

    return 0;
}

这是我的GLSL着色器代码:

uniform sampler2D textureTwoFramesAgo;
uniform sampler2D textureOneFrameAgo;
uniform vec2 mousePosition;

const float textureSize = 500.0;
const float pixelSize = 1.0 / textureSize;

void main()
{
    // pixels position
    vec2 position = gl_TexCoord[0].st;

    vec4 finalColor = ((texture2D(textureOneFrameAgo, vec2(position.x - pixelSize, position.y)) +
                        texture2D(textureOneFrameAgo, vec2(position.x + pixelSize, position.y)) +
                        texture2D(textureOneFrameAgo, vec2(position.x, position.y + pixelSize)) +
                        texture2D(textureOneFrameAgo, vec2(position.x, position.y - pixelSize)) - 2.0) / 2) -
                       (texture2D(textureTwoFramesAgo, position) - 0.5);

    // damping
//    finalColor.rgb *= 1.9;  // <---- uncomment this for the "amplifiction" ie. to see the waves better
    finalColor.rgb += 0.5;

    // add new ripples
    if(mousePosition.x > 0.0)
    {
        if(distance(position, mousePosition) < pixelSize * 5)
        {
            finalColor = vec4(0.9, 0.9, 0.9, 1.0);
        }
    }

    gl_FragColor = finalColor;

}

请记住,这一切只涉及高度场的创建。目前还没有对水进行着色。
你知道为什么波浪会自动消失而不衰减吗?

1
很抱歉,这些算法在以下两个页面中进行了解释:http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/the-water-effect-explained-r915 http://freespace.virgin.net/hugo.elias/graphics/x_water.htm(由于我是新用户,无法发布超过两个链接)。 - Foaly
你找到解决方案了吗? - Prizoff
2个回答

2
如果我正确理解了代码,你会从前一帧中取样纹理的颜色/高度,并使用四个相邻的像素/纹素来确定当前像素的颜色/高度。
在计算(缩放)这些相邻像素时,你可能会错过包含所寻找颜色/高度的纹素。它可能不是最高的纹素,只是比它低一点点的旁边一个,导致意外的阻尼。
这就是你不仅仅使用加法和减法的地方:
const float pixelSize = 1.0 / textureSize;

通过使用该值,您可以忽略您正在寻找的纹素。
编辑:
另外,由于您正在对样本进行平均,因此结果始终小于样本的最大值。因此,您可以选择最大值而不是平均值。这可能会产生奇怪的结果,但也能提供额外的见解。

有一件事情你应该做:使用位图手动计算几个像素,看看结果是否符合算法预期。如果符合,那么算法就是错误的。如果不符合,则算法的实现可能存在问题。 - Emond
我在网格纸上手算了一下,看起来和我发布的位图有点不同,所以我认为实现可能有误。我仍然认为你最初的想法可能是对的,即有时步骤1.0 /textureSize无法获得邻近的纹理元素,从而产生意外的衰减。但我不知道其他方法,也没有找到其他方法……您能告诉我正确的做法吗? - Foaly
不,现在你调整了像素大小。你应该调整样本坐标的偏移量。 - Emond
好的,但是像素大小(pixelSize)是我用作偏移量的。或者我在这里理解错了什么? - Foaly
谢谢您提供这篇有趣的文章!但是在开头就说它不适用于OpenGL。我尝试了position.xy += pixelSize * 0.5;,但是没有任何变化... - Foaly
显示剩余8条评论

2
这里有一些“Processing”代码,实现了你上面发布的同样的算法,并且它的阻尼是正确的。希望你能从中获得一些启示:
// codes begin

int Width = 800;
int Height = 600;
int FullSize = 0;
//int Spacing = 10;

int[] source, dest;
PImage bg;

void setup()
{
  // if you want to run these codes by "Processing"
  // please make a picture named "HelloWorld.png"
  bg = loadImage("HelloWorld.png");
  Width = bg.width;
  Height = bg.height;
  FullSize = Width * Height;
  size(Width, Height);
  source = new int[FullSize];
  dest = new int[FullSize];
  for (int i=0; i< FullSize; i++)
    source[i] = dest[i] = 0;
}

void draw()
{
  for (int i=Width; i< FullSize-Width; i++)
  {
    // check for bounds
    int xi = i % Width;
    if ((xi==0) || (xi==Width-1)) continue;

    dest[i] = (
    ((source[i-1]+
      source[i+1]+
      source[i-Width]+
      source[i+Width]) >>1) ) -dest[i];

    int dampFactor = 1000;
    dest[i] -= (dest[i] >> dampFactor); // Damping - Quick divde by 32 (5 bits)
  }

  //image(bg, 0, 0);
  loadPixels();
  for (int i=Width; i< FullSize-Width; i++)
  {
    // check for bounds
    int xi = i % Width;
    if ((xi==0) || (xi==Width-1)) continue;

    int xoffset = dest[i-1] - dest[i+1];
    int yoffset = dest[i-Width] - dest[i+Width];

    int offset = i+xoffset+yoffset*Width;
    if (offset>0 && offset<FullSize)
    {
      // TODO: make better map
      pixels[i] = bg.pixels[offset];
    }
  }
  //bg.updatePixels();
  updatePixels();

  //swap
  int[] temp = source;
  source = dest;
  dest = temp;
}

void mouseDragged() 
{
    if (mouseX > 0 && mouseX < Width && mouseY > 0 && mouseY < Height)
      source[mouseY*Width+mouseX] = (int)random(50, 100); 
}

void mousePressed()
{
   // TODO: make a area pulse value, like a radius circle
   if (mouseX > 0 && mouseX < Width && mouseY > 0 && mouseY < Height)
      source[mouseY*Width+mouseX] = (int)random(50, 100); 
}

// codes end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接