The date of this post will be upgraded once it updates

A post to record HLSL stuff related to unity shader graph programing.

HLSL Note

Custom Function Node

When coding the HLSL include file, I found the custom function node in the shader graph never stops throwing out errors that I can't understand like this:

Any programmer can never allow any red or yellow stuff in his code, so I tried really hard to locate the error, but find nothing useful at the end. There's little information about how I can get rid of this error, until I accidently folded the preview in the node by referring an unsolved post on unity forum questioning that "why is my custom function node keeps throwing out errors though THE OVERALL SHADER IS WORKING FINE ?" and the error disappears. My feeling was so mixed and in chaos at that moment.

It seems that you cannot call functions or use structs in URP Library directly, that's why SHADERGRAPH_PREVIEW is defined when node tries to draw preview image.

Referring some other shader graph custom functions like the one below, we can see that they hard code the variables that should use functions in URP Library to get (such as GetMainLight()) to get a preview from the node (maybe also for performance in node preview).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void MainLight_float(float3 WorldPos, out float3 Direction, out float3 Color, out float DistanceAtten, out float ShadowAtten)
{
#if SHADERGRAPH_PREVIEW
Direction = float3(-0.5, 0.5, 0);
Color = float3(1, 0.95, 0.8);
DistanceAtten = 1;
ShadowAtten = 1;
#else
#if SHADOWS_SCREEN
float4 clipPos = TransformWorldToHClip(WorldPos);
float4 shadowCoord = ComputeScreenPos(clipPos);
#else
float4 shadowCoord = TransformWorldToShadowCoord(WorldPos);
#endif
Light mainLight = GetMainLight(shadowCoord);
Direction = mainLight.direction;
Color = mainLight.color;
DistanceAtten = mainLight.distanceAttenuation;
ShadowAtten = mainLight.shadowAttenuation;
#endif
}

However, the final preview (usually at right bottom corner) is not the same as the preview in nodes, so when you see errors from your custom node, check the final preview out to see whether your code actually works.

In case you didn't notice, the function name in the custom function node should be the same as the name in your HLSL file. For example, if you put the code above to the node, you should type in MainLight in the function name input box. The _float after the function name is describing the precision of your data, it's either _float or _half in shader graph, and you should also change the precision select box in the graph setting to match your precision in the function.

Static Variable

When I was coding the outline HLSL file, I declared a float parameter outside the main function without marking it static. In HLSL, if you use the variable out of function without marking it static, then:

Official document is good, but sometimes I just don't know if it's a feature of the language or a bug.

Comments

⬆︎TOP