benui
benui

Reputation: 6808

Vertex shader for only some vertices

I'm trying to write a vertex shader that only applies to some vertices.

In Unity, text is rendered as a series of disjointed 4-vertex polys. I'm trying to transform/rotate/scale those polys, but separately. So I can move each letter independently.

I don't think it's possible but if each vertex had an ID, I could group them 0-3, 4-7 etc. and move them that way.

Are there any tricks to modifying vertices depending on what they're attached to, or which "number" they are?

Upvotes: 3

Views: 3960

Answers (1)

Jerdak
Jerdak

Reputation: 4056

I don't believe you can do so directly but you could use the second UV channel to store your IDs.

Here is a re-purposed Unity normal shading example using a "vertex ID" to determine when to apply the normal as a color.

Shader "Custom/ColorIdentity" {
Properties {
    //_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
    Pass {  
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct appdata {
                float4 vertex : SV_POSITION;
                float3 normal : NORMAL;
                float4 texCoord2 : TEXCOORD1;
            };
            struct v2f {
                float4 pos : SV_POSITION;
                float3 color : COLOR0;
            };

            v2f vert (appdata v)
            {
                v2f o;

                //here is where I read the vertex id, in texCoord2[0]
                //in this case I'm binning all values > 1 to id 1, else id 0
                //that way they can by multiplied against to the vertex normal
                //to turn color on and off.
                int vID = (v.texCoord2[0]>1)?1:0;   

                o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                o.color = v.normal * vID; //Use normal as color for vertices w/ ids>1
                return o;
            }

            half4 frag (v2f i) : COLOR
            {
                return half4 (i.color, 1);
            }
        ENDCG
    }
}
Fallback "Diffuse"
} 

Also, here is the dummy script I ginned up to assign completely arbitrary IDs. IDs are assigned based on a vertex's position on the y-axis. The bounds were chosen at random based on the mesh I had handy:

public class AssignIdentity : MonoBehaviour {
public GameObject LiveObject;

// Use this for initialization
void Start () {
    Mesh mesh = LiveObject.GetComponent<MeshFilter>().mesh;
    Vector3[] vertices = mesh.vertices;
    Vector2[] uv2s = new Vector2[vertices.Length];

    int i = 0;
    foreach(Vector3 v in vertices){
        if(v.y>9.0f || v.y < 4.0){
            uv2s[i++] = new Vector2(2,0); 
        } else {
            uv2s[i++] = new Vector2(1,0);
        }
    }
    mesh.uv2 = uv2s;
}
}

Upvotes: 2

Related Questions