TExcelTAD
Home › Shaders & Graphics Programming › Unity: URP HLSL and Shader Graph

Unity: URP HLSL and Shader Graph

Everything in this course so far ran in a browser. In Unity, the same ideas are written in HLSL wrapped in Unity's ShaderLab file format, or built visually in Shader Graph. This lesson writes a real shader for the Universal Render Pipeline (URP), the default pipeline for new Unity 6 projects, and shows where each line of GLSL you know ends up.

Note: Shaders written for the old Built-in Render Pipeline (CGPROGRAM, UnityCG.cginc, #pragma surface) do not work in URP. Most shader code you find online from before about 2020 is Built-in. URP shaders use HLSLPROGRAM and include files from the URP package instead.

The shape of a .shader file

A Unity shader file has three layers:

Layer What it holds GLSL equivalent
Shader "Path/Name" the name shown in the material's shader menu none
Properties { } values the material exposes in the Inspector uniforms the host sets
SubShader { Tags { } Pass { HLSLPROGRAM … ENDHLSL } } the actual GPU code, one block per pass the vertex + fragment shader pair

The smallest URP shader looks like this (create it with Assets > Create > Shader, then replace the contents):

hlsl
Shader "Course/MinimalUnlit"
{
    Properties { }

    SubShader
    {
        Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes                     // vertex input (like GLSL "in" in a vertex shader)
            {
                float4 positionOS : POSITION;     // object-space position
            };

            struct Varyings                       // vertex output = fragment input
            {
                float4 positionHCS : SV_POSITION; // clip-space position (gl_Position)
            };

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
                return OUT;
            }

            half4 frag() : SV_Target              // SV_Target = the color output
            {
                return half4(0.9, 0.3, 0.2, 1.0);
            }
            ENDHLSL
        }
    }
}

The "RenderPipeline" = "UniversalPipeline" tag means "use this SubShader only in URP". Core.hlsl brings in the URP shader library, including the space-transform functions such as TransformObjectToHClip, which does what projectionMatrix * viewMatrix * modelMatrix * position does in a GLSL vertex shader.

HLSL for GLSL writers

HLSL and GLSL are close cousins. The differences you will hit first:

GLSL HLSL
vec2 vec3 vec4, mat4 float2 float3 float4, float4x4 (half4 = lower precision, like mediump)
mix(a, b, t) lerp(a, b, t)
fract(x) frac(x)
mod(x, y) fmod(x, y) (sign follows x, unlike GLSL's mod)
texture(tex, uv) SAMPLE_TEXTURE2D(tex, sampler_tex, uv) in URP (separate texture and sampler objects)
M * v mul(M, v) (* on two matrices is component-wise)
discard; clip(x) discards when x < 0 (discard; also exists)
in/out variables structs with semantics (POSITION, TEXCOORD0, SV_POSITION, SV_Target)
inversesqrt rsqrt
atan(y, x) atan2(y, x)

A textured, lit URP shader

Here is a complete shader with a texture, a tint color, simple Lambert lighting from the main directional light and ambient light from the scene's spherical harmonics. It is the Unity version of the Diffuse Lighting lesson.

hlsl
Shader "Course/SimpleLit"
{
    Properties
    {
        [MainTexture] _BaseMap ("Base Map", 2D) = "white" {}
        [MainColor]   _BaseColor ("Base Color", Color) = (1, 1, 1, 1)
        _Wrap ("Wrap Lighting", Range(0, 1)) = 0
    }

    SubShader
    {
        Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "Queue" = "Geometry" }

        Pass
        {
            Name "ForwardLit"
            Tags { "LightMode" = "UniversalForward" }

            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS   : NORMAL;
                float2 uv         : TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionHCS : SV_POSITION;
                float3 normalWS    : TEXCOORD0;    // any interpolated value uses a TEXCOORDn semantic
                float2 uv          : TEXCOORD1;
            };

            TEXTURE2D(_BaseMap);
            SAMPLER(sampler_BaseMap);

            // Every material property except textures goes in this buffer,
            // so the SRP Batcher can batch draws that use this shader.
            CBUFFER_START(UnityPerMaterial)
                float4 _BaseMap_ST;                // tiling (xy) and offset (zw) from the material
                half4  _BaseColor;
                half   _Wrap;
            CBUFFER_END

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
                OUT.normalWS = TransformObjectToWorldNormal(IN.normalOS);
                OUT.uv = TRANSFORM_TEX(IN.uv, _BaseMap);
                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, IN.uv) * _BaseColor;
                float3 n = normalize(IN.normalWS);          // re-normalize after interpolation

                Light mainLight = GetMainLight();           // direction (toward the light), color, attenuation
                half ndotl = saturate((dot(n, mainLight.direction) + _Wrap) / (1.0 + _Wrap));
                half3 diffuse = mainLight.color * ndotl;
                half3 ambient = SampleSH(n);                // ambient from the Lighting window / light probes

                return half4(albedo.rgb * (diffuse + ambient), albedo.a);
            }
            ENDHLSL
        }
    }
}

What each piece does:

  • Properties declares what the material Inspector shows. The names (_BaseMap, _BaseColor) must match the HLSL variables. [MainTexture] and [MainColor] tell Unity which properties Material.mainTexture and Material.color refer to.
  • "LightMode" = "UniversalForward" marks the pass that URP's forward renderer draws for lit opaque objects.
  • TEXTURE2D / SAMPLER / SAMPLE_TEXTURE2D are URP macros that expand to the right texture syntax on every graphics API Unity targets (D3D, Vulkan, Metal, OpenGL ES).
  • CBUFFER_START(UnityPerMaterial) is the important one for performance. When all non-texture properties are in this constant buffer, the shader is SRP Batcher compatible: Unity can draw many objects with this shader without re-uploading material data per draw. The Inspector of a shader asset tells you whether it is compatible.
  • _BaseMap_ST is filled in automatically with the material's Tiling and Offset; TRANSFORM_TEX applies it.
  • GetMainLight() comes from Lighting.hlsl. It returns a Light struct with direction, color, distanceAttenuation and shadowAttenuation.

What this shader does not do yet, compared with URP's own Lit shader: receive shadows (needs #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE and a shadow coordinate), cast shadows (needs a ShadowCaster pass), additional lights, fog and the depth passes (DepthOnly, DepthNormals) that features such as SSAO and the depth prepass read. A custom shader without those passes still draws, but the object will not cast shadows or appear in the depth texture. For a full PBR surface, copying URP's Lit features by hand is a big job; that is where Shader Graph shines.

The same shader in Shader Graph

Shader Graph is Unity's node editor for shaders. It generates all the passes (shadows, depth, motion vectors) for you, so most game teams use it for surface materials and write HLSL by hand only for special cases.

To rebuild the shader above:

  1. In the Project window, Create > Shader Graph > URP > Lit Shader Graph and open it.
  2. In the Blackboard, add a Texture2D property (Base Map) and a Color property (Base Color). Drag them into the graph.
  3. Add a Sample Texture 2D node, connect Base Map to its Texture input, and multiply its RGBA output by Base Color with a Multiply node.
  4. Connect the result to Base Color in the Fragment block of the Master Stack. The Lit target does the lighting (full PBR, shadows, all lights) itself.
  5. For custom lighting (like the wrap term above), use an Unlit Shader Graph and compute the light yourself, or put HLSL in a Custom Function node, which calls a function from an .hlsl file or inline code.
  6. Save, then create a material from the graph (right-click the graph asset, Create > Material).

Rough mapping between the two:

HLSL Shader Graph
Properties + CBUFFER Blackboard properties (Shader Graph builds the CBUFFER for you)
SAMPLE_TEXTURE2D Sample Texture 2D node
lerp, saturate, dot Lerp, Saturate, Dot Product nodes
_Time.y Time node
clip(alpha - threshold) Graph Settings: Alpha Clipping, plus the Alpha and Alpha Clip Threshold outputs
a helper function Sub Graph, or a Custom Function node

Tip: Even if you only use Shader Graph, you can read the HLSL it generates: select the graph asset and use View Generated Shader in the Inspector. It is the fastest way to learn how URP's real passes are structured.

Unity-specific gotchas

  • Time is _Time in HLSL: _Time.y is seconds (like iTime), _Time.x is seconds / 20, _Time.z seconds × 2, _Time.w seconds × 3.
  • Color properties are converted to linear when the project uses Linear color space (the default for new projects), so the value you read in HLSL is not the sRGB number you typed. See Field Notes.
  • Shader variants multiply: every multi_compile keyword doubles (or more) the number of compiled versions. Prefer shader_feature for material toggles; it only keeps the variants that materials actually use in a build.
  • Unity's clip space follows the platform (D3D-style 0..1 depth on most platforms, reversed Z). Use the Transform… functions and the UNITY_REVERSED_Z macro instead of assuming OpenGL conventions.

Unity's course covers the editor side of materials, and One Dissolve, Three Engines builds a full effect in this style.

Test yourself

Why put material properties inside CBUFFER_START(UnityPerMaterial) in a URP shader?

  1. It is required for textures to work
  2. It makes the shader compatible with the SRP Batcher
  3. It enables shadows
  4. It converts colors to linear space

Which HLSL function corresponds to GLSL's mix?

  1. blend
  2. lerp
  3. mad
  4. smoothstep

Your hand-written URP shader draws fine but the object casts no shadow. What is missing?

  1. A ShadowCaster pass
  2. The RenderType tag
  3. A Properties block
  4. The SV_Target semantic