opengl es 2.0 - 优化片段着色器

时间:2013-10-10 14:21:34

标签: opengl-es-2.0 glsl

我正在为Android / iOS开发游戏,需要优化渲染。 游戏使用户能够变形地形,因此我使用地形的灰度图像(地形中的值1表示实地,0表示没有地面)并在其上应用片段着色器(还有背景图像) )。这与60 fps常数非常有效,但问题是我还需要在地形边缘渲染边框。所以要做到这一点我在变形时模糊边缘,在片段着色器中我根据地形密度/透明度绘制边框(边框是1x64纹理)。

问题在于渲染边框时我需要进行动态纹理读取,将帧速率降低到20.有什么方法可以优化它?如果我用一个统一的浮点数组替换边框纹理会有帮助,还是与从2d纹理读取一样?

着色器代码:

 varying mediump vec2 frag_background_texcoord;
 varying mediump vec2 frag_density_texcoord;
 varying mediump vec2 frag_terrain_texcoord;

 uniform sampler2D density_texture;
 uniform sampler2D terrain_texture;
 uniform sampler2D mix_texture;
 uniform sampler2D background_texture;

 void main()
 {
    lowp vec4 background_color = texture2D(background_texture, frag_background_texcoord);
    lowp vec4 terrain_color = texture2D(terrain_texture, frag_terrain_texcoord);

    highp float density = texture2D(density_texture, frag_density_texcoord).a;

    if(density > 0.5)
    {
         lowp vec4 mix_color = texture2D(mix_texture, vec2(density, 1.0)); <- dynamic texture read (FPS drops to 20), would replacing this with a uniform float array help (would also need to calculate the index in the array)?
         gl_FragColor = mix(terrain_color, mix_color, mix_color.a);
    } else
    {
         gl_FragColor =  background_color;
    }
 }

1 个答案:

答案 0 :(得分:0)

想出来。我修复它的方法是删除所有分支。现在运行~60fps。 优化代码:

varying mediump vec2 frag_background_texcoord;
varying mediump vec2 frag_density_texcoord;
varying mediump vec2 frag_terrain_texcoord;

uniform sampler2D density_texture;   
uniform sampler2D terrain_texture;
uniform sampler2D mix_texture;
uniform sampler2D background_texture;

void main()
{
   lowp vec4 background_color = texture2D(background_texture, frag_background_texcoord);
   lowp vec4 terrain_color = texture2D(terrain_texture, frag_terrain_texcoord);

   lowp vec4 mix_color = texture2D(mix_texture, vec2(density, 0.0));
   lowp float density = texture2D(density_texture, frag_density_texcoord).a;

   gl_FragColor = mix(mix(bg_color, terrain_color, mix_color.r), mix_color, mix_color.a);       
}