Search Unity

How to create Compute Shader variants?

Discussion in 'Shaders' started by mrtkhosravi, Jan 29, 2017.

  1. mrtkhosravi

    mrtkhosravi

    Joined:
    Nov 9, 2014
    Posts:
    198
    With normal shaders we can create multi compile shaders and enable or disable keywords to activate a certain variant of the shader for a particular draw call. Is there a way to do the same with compute shaders? The ComputeShader class has no EnableKeyword method. HLSL suggests to use interface and concrete classes and through polymorphic behaviour different functions can be run. Without any of these two we need to have an actual if-else block in shader code meaning more instructions and less performance .

    So is there a way to do any of these two approaches with compute shaders?
     
    Last edited: Jan 29, 2017
  2. Michal_

    Michal_

    Joined:
    Jan 14, 2015
    Posts:
    365
    You can't use dynamic shader linking in Unity as far as know but you can compile multiple compute shader variants. The downside is that you have to manually declare every single one. There is no "mluti_compile", "shader_feature" or EnableKeyword. You have to handle everything yourself. Here's how you do it:
    Code (CSharp):
    1. // compute shader
    2. // 1st variant (kernel index 0)
    3. #pragma kernel Main KEYWORD1
    4. // 2nd variant (kernel index 1)
    5. #pragma kernel Main KEYWORD1 KEYWORD2
    6.  
    7. [numthreads]
    8. void Main() { ... }
    9.  
    10. // C#
    11. // use variant 1
    12. shader.Dispatch(0, ...);
    13. // use variant 2
    14. shader.Dispatch(1, ...);
    It gets crazy if you have lot of variants but I didn't find anything better.
     
  3. mrtkhosravi

    mrtkhosravi

    Joined:
    Nov 9, 2014
    Posts:
    198
    At least it's better than nothing when there are two or three keywords. Thank you so much for the help michal.
     
  4. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    862
    mrtkhosravi likes this.
  5. raphick

    raphick

    Joined:
    Nov 15, 2016
    Posts:
    365