How to declare function in material custom node?

I want to store some codes in a function that update some of my variable that can be called from main function,i turned on shaderdeveloopment in coonfiguration but it didnt give much information
float3 tex;
float rh=1;
float prh;
float th;
float pth;
float ri=0;
float hs;
float ph;
float uvd;

void update(float ho)
{prh=rh;
pth=th;
rh-=ho;
UV-={ho*Tanx,ho*Tany};
uvd=ho/Tan;
return;}

for(int i=0;i<MaxSteps;i++)
{tex=Texture.SampleLevel(TextureSampler,UV,0);
th=tex[HeightChannel];
if(rh<=th){ri=(th-rh)/(prh-pth+th-rh);UV+=uvd*ri;break;}
if(rh<tex[ProbeDepthChannel])
{if(hs=StepSize*Tan<rh){update(hs);continue;}
 update(rh);break;}
ph=rh-tex[ProbeDepthChannel];
if(hs=tex[ProbeRadius]*Tan<ph){update(hs);continue;}
if(ph/Tan>StepSize){update(ph);continue;}
if(hs=StepSize*Tan<rh){update(hs);continue;}
update(rh);break;}

float4 ouput={UV,ri,rh};
return ouput;

119091-提问+-+ue4+answerhubl.png

You cannot declare a function in a custom node, yet you can do so with ease in UE4 shader files, located in Engine/Shaders.

Make your own USF file with your functions, and include it to Common.USF

Then you can call it from custom node.

1 Like

That sounds too hard for me,I just inlined the function manually,also my function is to update variable inside my custom node,can this do that?thanks for the information.

Sorry for necroposting, but…
Yes! You actually can declare multiple functions in a Custom Material Node!
I stumbled on this a few months ago looking for the same information.

struct Functions
{
  float3 OrangeBright(float3 c)
  {
      return c * float3(1, .7, 0);
  }
  float3 Out()
  {
    return OrangeBright(InColor);
  }
};
Functions f;
return f.Out();

I found the info here, for which I am eternally grateful:

6 Likes

Thank you! This is much cleaner. I love it.

1 Like

For anyone that’s having trouble with this in 5.1, saying that the inner functions don’t have access to variables. You can pass in the variables like this:

struct Functions
{
  float3 OrangeBright(float3 c)
  {
      return c * float3(1, .7, 0);
  }
  float3 Out(float3 InColor)
  {
    return OrangeBright(InColor);
  }
};
Functions f;
return f.Out(InColor);
4 Likes