Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Increase specific color without utilizing if statement

Discussion in 'Shaders' started by Je.Klaster, Feb 19, 2016.

  1. Je.Klaster

    Je.Klaster

    Joined:
    Feb 19, 2016
    Posts:
    3
    Hello,

    I have simple post process shader where I increasing intensity of specific color.
    My current implementation is using simple if statement, but as far as I know it is not good idea to use if in shaders, so I like to ask you - is there any way how to write this code without if?

    Code (Shader):
    1. //pseudo code
    2. if(col.r > 0.5) {
    3.   col.r += 0.5;
    4. }
    Thank you.
     
  2. Michal_

    Michal_

    Joined:
    Jan 14, 2015
    Posts:
    365
    Not every if is slow. This particular if statement will be compiled as conditional move on any decent hardware. That means there will be no branching. It will compile into two instructions and it will be blazing fast.

    Assigning a value based on a condition is generally very fast in shaders. You can always look at the compiled shader if you want to be sure.
     
  3. PixelMind

    PixelMind

    Joined:
    Aug 16, 2013
    Posts:
    101
    Something like
    Code (CSharp):
    1. col.r += step(0.5, col.r) * 0.5;
    should do the same (but I didn't try and I'm tired :))
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,248
    col.r += round(col.r) * 0.5;

    That should work too, not sure if any of these will be any faster than the original though for the reasons @Michal_ already mentioned.
     
  5. mholub

    mholub

    Joined:
    Oct 3, 2012
    Posts:
    123
    I could be wrong but as far as I know from CUDA course GPU hardware runs code in groups of 32 threads (called warps). You pay "double" price for if only if in one warp some threads execute "if branch" and some "else branch".

    I suppose on most hardware threads in one warp process pixels which are close to each other (like 4x2 rects of pixels). So for example if you have fullscreen shader which looks for red color and you have big red circle which occupy most of your image, you will pay more only near circle borders. So don't be afraid of ifs, especially constant ones %)