Search Unity

Conditions in a Shader

Discussion in 'Shaders' started by ToshoDaimos, May 8, 2017.

  1. ToshoDaimos

    ToshoDaimos

    Joined:
    Jan 30, 2013
    Posts:
    679
    I know that branching in a shader slows it down. How about running a loop with some IFs? I need to pick a texture based on face normal angle. I will compute vector angle and then I need to pick a texture based on its value. This will require "for" loop and some "ifs". The code will not branch into some "else" statement. Is this fast?
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    You should prepare for the worst case scenario in that all code in the if conditions is executed. Then again, this allows for almost free blending between the textures. For example:
    Code (csharp):
    1.  
    2. float4 score = 0.0;
    3. score.x = dot(normal, angle1);
    4. score.y = dot(normal, angle2);
    5. score.z = dot(normal, angle3);
    6. score.w = dot(normal, angle4);
    7. score = saturate(3.0 * score - 2.0); // For example, other weighting options can be done here of course
    8. float totalScore = dot(score, float4(1.0, 1.0, 1.0, 1.0));
    9. score /= totalScore;
    10. float4 result = score.x * tex2D(texture1, uv1);
    11. result = score.y * tex2D(texture2, uv2) + result; // MAD order instead of +=
    12. result = score.z * tex2D(texture3, uv3) + result; // MAD order instead of +=
    13. result = score.w * tex2D(texture4, uv4) + result; // MAD order instead of +=
    14. return result;
    15.  
    Pretty close to blended triplanar mapping like this. It depends on the number of textures and the platform whether this is feasible of course.
     
  3. ToshoDaimos

    ToshoDaimos

    Joined:
    Jan 30, 2013
    Posts:
    679
    I found a way to do it without conditions and loops. Its quite easy. Thanks for input.