赞
踩
GPU动画实现的最后一步是在shader中重新进行顶点采样。
将动画数据存在一张图片上,每帧动画数据就是一行,因此每个顶点的位置由2个属性确定
1.帧数
2.顶点ID
帧数 = 当前时间 / 动画时间
顶点ID则通过UNITY_VERTEX_INPUT_INSTANCE_ID,Unity会自动将该顶点ID传入
因此,在shade中,进行如下定义,这里直接用最简单的unlit shader示例
- struct appdata
- {
- float4 vertex : POSITION;
- float2 uv : TEXCOORD0;
- uint vid : SV_VERTEXID;
- UNITY_VERTEX_INPUT_INSTANCE_ID
- };
-
- struct v2f
- {
- float2 uv : TEXCOORD0;
- UNITY_FOG_COORDS(1)
- float4 vertex : SV_POSITION;
- UNITY_VERTEX_INPUT_INSTANCE_ID
- };
在顶点着色器中,直接进行顶点位置修改,通过顶点ID和动画时间计算取得顶点的位置。
- v2f vert (appdata v)
- {
- v2f o;
- UNITY_SETUP_INSTANCE_ID(v);
- UNITY_TRANSFER_INSTANCE_ID(v, o);
- float4 uv_anim = float4((v.vid + 0.5) * UNITY_ACCESS_INSTANCED_PROP(Props, _AnimTex_TexelSize).x, _Time.y / UNITY_ACCESS_INSTANCED_PROP(Props, _AnimTime),0.0,0.0);
- v.vertex = float4(tex2Dlod(_AnimTex, uv_anim).xyz,1.0);
- //v.vertex.y = v.vertex.y - 0.5;
- o.vertex = UnityObjectToClipPos(v.vertex);
- o.uv = v.uv * UNITY_ACCESS_INSTANCED_PROP(Props, _MainTex_ST).xy + UNITY_ACCESS_INSTANCED_PROP(Props, _MainTex_ST).zw;
- return o;
- }
片元着色器不用特别处理,直接采样输出即可
着色器源码如下
-
- Properties
- {
- _MainTex ("Texture", 2D) = "white" {}
- _AnimTex ("Texture", 2D) = "white" {}
- _AnimTime ("AnimTime", float) = 1
- }
- SubShader
- {
- Tags { "RenderType"="Opaque" }
- LOD 100
-
- Pass
- {
- CGPROGRAM
- #pragma target 3.5
- #pragma vertex vert
- #pragma fragment frag
- // make fog work
- #pragma multi_compile_instancing
-
- #include "UnityCG.cginc"
-
- struct appdata
- {
- float4 vertex : POSITION;
- float2 uv : TEXCOORD0;
- uint vid : SV_VERTEXID;
- UNITY_VERTEX_INPUT_INSTANCE_ID
- };
-
- struct v2f
- {
- float2 uv : TEXCOORD0;
- UNITY_FOG_COORDS(1)
- float4 vertex : SV_POSITION;
- UNITY_VERTEX_INPUT_INSTANCE_ID
- };
-
- CBUFFER_START(UnityPerMaterial)
- sampler2D _MainTex;
- sampler2D _AnimTex;
- //float4 _MainTex_ST;
-
- UNITY_INSTANCING_BUFFER_START(Props)
- UNITY_DEFINE_INSTANCED_PROP(float4, _AnimTex_TexelSize)
- UNITY_DEFINE_INSTANCED_PROP(float4, _MainTex_ST)
- UNITY_DEFINE_INSTANCED_PROP(float, _AnimTime)
- UNITY_INSTANCING_BUFFER_END(Props)
- CBUFFER_END
-
- v2f vert (appdata v)
- {
- v2f o;
- UNITY_SETUP_INSTANCE_ID(v);
- UNITY_TRANSFER_INSTANCE_ID(v, o);
- float4 uv_anim = float4((v.vid + 0.5) * UNITY_ACCESS_INSTANCED_PROP(Props, _AnimTex_TexelSize).x, _Time.y / UNITY_ACCESS_INSTANCED_PROP(Props, _AnimTime),0.0,0.0);
- v.vertex = float4(tex2Dlod(_AnimTex, uv_anim).xyz,1.0);
- //v.vertex.y = v.vertex.y - 0.5;
- o.vertex = UnityObjectToClipPos(v.vertex);
- o.uv = v.uv * UNITY_ACCESS_INSTANCED_PROP(Props, _MainTex_ST).xy + UNITY_ACCESS_INSTANCED_PROP(Props, _MainTex_ST).zw;
- return o;
- }
-
- fixed4 frag (v2f i) : SV_Target
- {
- UNITY_SETUP_INSTANCE_ID(i);
- fixed4 col = tex2D(_MainTex, i.uv);
- //return float4(1.0,1.0,1.0,1.0) * _Time.y;
- return col;
- }
- ENDCG
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。