GLSL in ShaderLab

Syntaxhtml

  However, use of raw GLSL is only recommended for testing, or when you know you will only target Mac OS X or OpenGL ES 2.0 compatible mobile devices. In majority of normal cases, Unity will cross-compile Cg/HLSL into optimized GLSL (this is done by default for mobile platforms, and can be optionally turned on for desktop platforms via #pragma glsl).app

  GLSL program snippets are written between GLSLPROGRAM and ENDGLSL keywords.編輯器

  In GLSL, all shader function entry points have to be called main(). When Unity loads the GLSL shader, it loads the source once for the vertex program, with VERTEX preprocessor define, and once more for the fragment program, with FRAGMENT preprocessor define. So the way to separate vertex and fragment program parts in GLSL snippet is to surround them with #ifdef VERTEX.. #endif and #ifdef FRAGMENT .. #endif. Each GLSL snippet must contain both a vertex program and a fragment program.ide

  Standard include files match those provided for Cg shaders; they just have .glslinc extension: UnityCG.glslinc.this

  Vertex shader inputs come from predefined GLSL variables (gl_Vertex, gl_MultiTexCoord0, ...) or are user defined attributes. Usually only the tangent vector needs a user defined attribute:spa

    attribute vec4 Tangent;

  Data from vertex to fragment programs is passed through varying variables, for example:code

    varying vec3 lightDir; // vertex shader computes this, fragment shader uses this

Examplesorm

  爲了使用ShaderLab中的Property,需像下面這樣搞:htm

Properties
{
    //能夠從編輯器中選擇顏色
    _Color ("Main Color", Color) = (1,0.5,0.5,1)
}

#ifdef FRAGMENT
//這就是從Unity編輯器給GLSL shader傳遞數據的方法,定義uniforms類型變量
uniform vec4 _Color ;
void main()
{
    gl_FragColor = _Color;
}
#endif 

  完整代碼以下所示:blog

Shader "simple_Color_Shader"
        {
            Properties
            {
                   //能夠從編輯器中選擇顏色
                   _Color ("Main Color", Color) = (1,0.5,0.5,1)
            }
            SubShader
            {
            Tags { "Queue" = "Geometry" }
            Pass
            {
            GLSLPROGRAM
            #ifdef VERTEX
            void main()
            {
               gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
            }
            #endif  
        
            #ifdef FRAGMENT
            //這就是從Unity編輯器給GLSL shader傳遞數據的方法,定義uniforms類型變量
            uniform vec4 _Color ;
            void main()
            {
               gl_FragColor = _Color;
            }
            #endif
            ENDGLSL
            }
            }
        }
View Code

參考:

一、http://www.58player.com/blog-2532-69127.html

二、file://localhost/Applications/Unity/Unity.app/Contents/Documentation/Documentation/Components/SL-GLSLShaderPrograms.html

相關文章
相關標籤/搜索