Download

Do Material Functions treat & optimize "Constant" Inputs as actual constants (precompute)?

Assume we have a material function F, which takes a Input scalar X.

Function F performs some more complex/slow arithmetic on it, eg Y= sin(1/X).

It then returns Y.

My question is: if we call material function F and pass a Constant node for function input X (eg 0.4) to it, will this result be precomputed since shader compiler/unreal material system knows that it is a constant so it can precompute Y =sin(1/0.4) upfront and thus make the expression sin(1/X) free in this case?

I’m asking because I see my instruction count jumping a lot between these two cases:

case 1) I define a Constant node and pass it via function Inputs down ~3 levels (so the constant it passed 3 times to a function inside a function inside a funtion… as a Input:

  • in this case I have a instruction count of 70.

case 2) But if I hardcode the constant in the very “deepest”/last function instead of passing it all the way I get a instruction count of 30.

So now I’ wondering what is happening?
a) is unreal/compiler not detecting that it is a constant and is thus not optimizing it?
b) the instruction counter has a bug?

So tl/dr: are constants optimized across function inputs/outputs?

Instruction count is reported by compile worker, so that should be more or less accurate and potential warning sign that constants in question are not folded. If you are having doubts, the best bet would be to check ASM of the shader in a packed game.

It would help, if you would re-create the node network, that gives the issue in a separate material and share it with the community so we can productively discuss it.

Shader compiler should optimize all constant math and addition to that UE4 material editor also optimize math done by per draw call constants.(scalar/vector parameters)