《Unity着色器圣经》3.2.6 | CGPROGRAM/ENDCG

目录索引

译文

在前面几个小节学习到的所有部分都是用 ShaderLab 这种声明式语言编写的,而我们在图形编程语言方面的真正挑战是从 CGPROGRAM 或 HLSLPROGRAM 声明开始的。

默认情况下,我们会发现Unity在新建着色器程序时自动加入了CG语义块。关于这一点,官方文档(2021.2 版)是这样说的:

Unity 最初使用 Cg 语言,因此一些关键词的名称和 .cginc 扩展名也是 Cg 语言,但现在已不再使用这种语言。虽然如此,这些关键词仍然包含在代码内,而且出于兼容性考虑,代码仍可以被编译。

如上所述,在未来的 Unity 版本中,我们的着色器可能会使用 HLSLPROGRAM 而不是 CGPROGRAM 进行声明,因为 HLSL 目前是 Unity 的官方图形编程语言(Shader Graph 就是基于 HLSL的)。

总之,我们只需将着色器中的 CGPROGRAM 替换为 HLSLPROGRAM、将 ENDCG 替换为 ENDHLSL,我们的着色器就可以在内置渲染管线(built-in RP)、通用渲染管线(URP)以及高清渲染管线(HDRP)中编译了。

如果我们想将程序更新为 HLSL,就必须更改一些设置,并修改代码里的一些内容。

// CG version
Pass
{
    CGPROGRAM
   ...
    ENDCG
}

// HLSL version
Pass
{
    HLSLPROGRAM
   ...
    ENDHLSL
}

编译着色器所需的所有函数都将写在 CGPROGRAM 和 ENDCG 字段中间的部分里,在这个范围之外的函数将被 Unity 作为 ShaderLab 属性。如果这些函数与语言不对应(例如在Cg里写HLSL,或存在语法错误),那么我们的程序将无法编译它们。

Shader "InspectorPath/shaderName"
{
    Properties { ... }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        Pass
        {
            CGPROGRAM
            // write all functions here
            ENDCG
        }
    }
}

原文对照

All the sections we have reviewed above are written in the ShaderLab declarative language, our real challenge in the graphics programming language starts here with CGPROGRAM or HLSLPROGRAM declaration.

By default, we can see that Unity has included the word CG in our Program. Regarding this, the official documentation (version 2021.2) says that:

Unity originally used the Cg language, hence the name of some words and .cginc extensions, but the software no longer uses this language, however, the words are still included, and the code is still compiling for compatibility reasons.

As mentioned above, it is likely that in future versions, our shader will appear with the declaration of HLSLPROGRAM instead of CGPROGRAM since HLSL is currently the official graphics programming language (in fact, Shader Graph is based on it).

Anyway, we can update our shader simply by replacing the word CGPROGRAM for HLSLPROGRAM and ENDCG for ENDHLSL, and then our program will compile both in Built-in RP as in Universal RP and High Definition RP.

If we want to update the program to HLSL, we will have to change some settings and add some routes to our shader, which will make this more complex to understand.

// CG version
Pass
{
    CGPROGRAM
   ...
    ENDCG
}

// HLSL version
Pass
{
    HLSLPROGRAM
   ...
    ENDHLSL
}

All the necessary functions for our shader to compile will be written inside the CGPROGRAM and ENDCG field. Those functions outside this fragment will be taken by Unity as ShaderLab properties, and if they do not correspond to this language, then our program will not compile.

Shader "InspectorPath/shaderName"
{
    Properties { ... }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        Pass
        {
            CGPROGRAM
            // write all functions here
            ENDCG
        }
    }
}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容