欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

why we use _MainText_ST and what does the mean of TRANSFORM_TEX

程序员文章站 2022-06-02 22:14:04
...

this is the same question.
i thank the website:
https://answers.unity.com/questions/33404/accessing-uv-offset-in-cg-shader.html

just post the following code to your shader file:

Shader "Course/MainTextureST" 
{
    Properties 
    {
        _MainTex ("Texture", 2D) = "white" { }
    }

    SubShader
    {
        pass    
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;

            struct v2f 
            {
                float4  pos : SV_POSITION;
                float2  uv : TEXCOORD0;
            };

            v2f vert (appdata_base v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = v.texcoord.xy;
                //o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
                return o;
            }

            float4 frag (v2f i) : COLOR
            {
                float4 texCol = tex2D(_MainTex,i.uv);
                float4 outp = texCol;
                return outp;
            }
            ENDCG
        }
    }
}

and change the value of the tiling and offset of the shader.
why we use _MainText_ST and what does the mean of TRANSFORM_TEX

you find that the tiling/offset value can not affect the rendering effect.

and then ,you just comment the o.uv = v.texcoord.xy; and uncomment the next line.

//o.uv = v.texcoord.xy;
o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;

you will find, the tiling and offset value is valid. they can affect the rendering effect.
why we use _MainText_ST and what does the mean of TRANSFORM_TEX

so, now, you can clearly understand why we using _MainText_ST and how to translate vertex’s original uv value when tiling and offset value of texture change.

you can also use a macro to replace the line:
o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
that is :

//o.uv = v.texcoord.xy;
//o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);

you can find the macro defined in the UnityCG.cginc file.

// Transforms 2D UV by scale/bias property
#define TRANSFORM_TEX(tex,name) (tex.xy * name##_ST.xy + name##_ST.zw)

so so , the ending comes.