Unity3D shader——水的折射与反射
2017-11-27 11:58
711 查看
水的折射与反射原理其实差不多,只是一个用ComputeGrabScreenPos(o.pos)来取得贴图,一个用ComputeScreenPos(o.pos)来取得贴图。另外还需要两个脚本,一个是工具类的脚本,一个是得到反射贴图的脚本。
这里直接放上核心源码:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
效果:
其中:工具类脚本CodeTool.cs
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
得到反射贴图的脚本:ReflectionEffect.cs
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
当然,以上的水的波纹可以按照需求调整。
有一篇博客写得挺好的,那篇博客把波浪和水深的渐变加进去了,效果相当棒。如果用那篇文章的内容加上本篇的内容,基本上就把水的各种技术问题解决了。
http://blog.csdn.net/mobilebbki399/article/details/50493117
最后的效果如下图:有波纹、有反射、折射、有浪花、有水深颜色渐变。
这里直接放上核心源码:
Shader "GameCore/Mobile/Water/Diffuse" { Properties { _BaseColor("BaseColor",color)=(1,1,1,1) _MainTex("Texture",2D)="white"{} _ReflectionTex("ReflectionTex",2D)=""{} _Bias("Bias",range(0,1))=0 _Scale("Scale",range(0,1))=0 _Pow("Pow",range(0,5))=1 } SubShader { Tags {"RenderType"="Opaque" "Queue"="transparent"} LOD 100 grabpass{} Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" #include "Lighting.cginc" float4 _BaseColor; sampler2D _MainTex; float4 _MainTex_ST; sampler2D _GrabTexture; sampler2D _ReflectionTex; float _Bias,_Scale,_Pow; struct v2f { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; float4 proj:TEXCOORD1; float4 refl:TEXCOORD2; float3 L:TEXCOORD3; float3 V:TEXCOORD4; }; v2f vert(appdata_tan v){ v2f o; o.pos=UnityObjectToClipPos(v.vertex); o.uv=TRANSFORM_TEX(v.texcoord.xy,_MainTex); o.proj=ComputeGrabScreenPos(o.pos); o.refl=ComputeScreenPos(o.pos); o.L=ObjSpaceLightDir(v.vertex); o.V=ObjSpaceViewDir(v.vertex); TANGENT_SPACE_ROTATION; o.L=mul(rotation,o.L); o.V=mul(rotation,o.V); return o; } float4 frag(v2f IN):SV_Target{ float4 col1=tex2D(_MainTex,IN.uv+float2(_Time.x,0)); float4 col2=tex2D(_MainTex,float2(1-IN.uv.y,IN.uv.x)+float2(_Time.x,0)); //水的波动 float4 col=(col1+col2)/2; float3 N=normalize(UnpackNormal(col)); //法向量 float off_xy=dot(N,float3(0,1,0)); //法向量和竖直方向向量的点积 IN.proj.xy+=off_xy*0.1; //顶点加上偏移量 float4 gcol=tex2Dproj(_GrabTexture,IN.proj); //折射效果 float diff=max(0,dot(N,normalize(IN.L))); //法线与灯光的点积 float3 H=normalize(normalize(IN.L)+normalize(IN.V)); float spec=pow(max(0,dot(N,H)),128); //高光效果 float4 diffCol=diff*_BaseColor; diffCol.rgb+=spec*_LightColor0.rgb; IN.refl.xy+=off_xy*0.3; float4 reflcol=tex2Dproj(_ReflectionTex,IN.refl); float4 fresnel=_Bias+_Scale*pow(1+dot(N,-normalize(IN.V)),_Pow); float4 finalColor=lerp(gcol,reflcol,fresnel); //fixed4 finalColor=lerp(fresnel,gcol,diffCol); return finalColor; } ENDCG } } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
效果:
其中:工具类脚本CodeTool.cs
using System.Collections; using System; using UnityEngine; /// <summary> /// 工具类 /// </summary> public static class CoreTool { #region Config配置 /// <summary> /// 验证当前文件是否为配置文件 /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static bool IsConfig(string filePath) { return true; } #endregion #region Camera /// <summary> /// 将源摄像机状态克隆到目标相机 /// </summary> /// <param name="src">源相机</param> /// <param name="dest">目标相机</param> public static void CloneCameraModes(Camera src, Camera dest) { if (dest == null) return; // set camera to clear the same way as current camera dest.clearFlags = src.clearFlags; dest.backgroundColor = src.backgroundColor; if (src.clearFlags == CameraClearFlags.Skybox) { Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox; Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox; if (!sky || !sky.material) { mysky.enabled = false; } else { mysky.enabled = true; mysky.material = sky.material; } } // update other values to match current camera. // even if we are supplying custom camera&projection matrices, // some of values are used elsewhere (e.g. skybox uses far plane) dest.depth = src.depth; dest.farClipPlane = src.farClipPlane; dest.nearClipPlane = src.nearClipPlane; dest.orthographic = src.orthographic; dest.fieldOfView = src.fieldOfView; dest.aspect = src.aspect; dest.orthographicSize = src.orthographicSize; } /// <summary> /// 计算反射矩阵 /// </summary> /// <param name="reflectionMat">原始矩阵</param> /// <param name="plane">反射平面</param> /// <returns>反射矩阵</returns> public static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1F - 2F * plane[0] * plane[0]); reflectionMat.m01 = (-2F * plane[0] * plane[1]); reflectionMat.m02 = (-2F * plane[0] * plane[2]); reflectionMat.m03 = (-2F * plane[3] * plane[0]); reflectionMat.m10 = (-2F * plane[1] * plane[0]); reflectionMat.m11 = (1F - 2F * plane[1] * plane[1]); reflectionMat.m12 = (-2F * plane[1] * plane[2]); reflectionMat.m13 = (-2F * plane[3] * plane[1]); reflectionMat.m20 = (-2F * plane[2] * plane[0]); reflectionMat.m21 = (-2F * plane[2] * plane[1]); reflectionMat.m22 = (1F - 2F * plane[2] * plane[2]); reflectionMat.m23 = (-2F * plane[3] * plane[2]); reflectionMat.m30 = 0F; reflectionMat.m31 = 0F; reflectionMat.m32 = 0F; reflectionMat.m33 = 1F; return reflectionMat; } /// <summary> /// 计算指定平面在摄像机中的空间位置 /// </summary> /// <param name="cam">摄像机</param> /// <param name="pos">平面上的点</param> /// <param name="normal">平面法线</param> /// <param name="sideSign">1:平面正面,-1:平面反面</param> /// <param name="clipPlaneOffset">平面法线位置偏移量</param> /// <returns></returns> public static Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign,float clipPlaneOffset) { Vector3 offsetPos = pos + normal * clipPlaneOffset; Matrix4x4 m = cam.worldToCameraMatrix; Vector3 cpos = m.MultiplyPoint(offsetPos); Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign; return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal)); } /// <summary> /// 由剪裁面计算投影倾斜矩阵 /// </summary> /// <param name="projection">投影矩阵</param> /// <param name="clipPlane">剪裁面</param> /// <param name="sideSign">剪裁平面(-1:平面下面,1:平面上面)</param> public static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane,float sideSign) { Vector4 q = projection.inverse * new Vector4( sgn(clipPlane.x), sgn(clipPlane.y), 1.0f, 1.0f ); Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q))); // third row = clip plane - fourth row projection[2] = c.x + Mathf.Sign(sideSign)*projection[3]; projection[6] = c.y + Mathf.Sign(sideSign) * projection[7]; projection[10] = c.z + Mathf.Sign(sideSign) * projection[11]; projection[14] = c.w + Mathf.Sign(sideSign) * projection[15]; return projection; } private static float sgn(float a) { if (a > 0.0f) return 1.0f; if (a < 0.0f) return -1.0f; return 0.0f; } /// <summary> /// 由水平、垂直距离修改倾斜矩阵 /// </summary> /// <param name="projMatrix">倾斜矩阵</param> /// <param name="horizObl">水平方向</param> /// <param name="vertObl">垂直方向</param> /// <returns>修改后的倾斜矩阵</returns> public static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projMatrix, float horizObl, float vertObl) { Matrix4x4 mat = projMatrix; mat[0, 2] = horizObl; mat[1, 2] = vertObl; return mat; } #endregion #region Shader Matrix4x4 /// <summary> /// tex2DProj到tex2D的uv纹理转换矩阵 /// 在shader中, /// vert=>o.posProj = mul(_ProjMatrix, v.vertex); /// frag=>tex2D(_RefractionTex,float2(i.posProj) / i.posProj.w) /// </summary> /// <param name="transform">要显示纹理的对象</param> /// <param name="cam">当前观察的摄像机</param> /// <returns>返回转换矩阵</returns> public static Matrix4x4 UV_Tex2DProj2Tex2D(Transform transform,Camera cam) { Matrix4x4 scaleOffset = Matrix4x4.TRS( new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f)); Vector3 scale = transform.lossyScale; Matrix4x4 _ProjMatrix = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z)); _ProjMatrix = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * _ProjMatrix; return _ProjMatrix; } #endregion }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
得到反射贴图的脚本:ReflectionEffect.cs
using UnityEngine; using System.Collections; using System; /// <summary> /// 反射效果 /// </summary> [AddComponentMenu("GameCore/SpecialEffect/Reflection")] [ExecuteInEditMode] public class ReflectionEffect : MonoBehaviour { public Camera MainCamera; public bool DisablePixelLights = true; public int TextureSize = 512; public float ClipPlaneOffset = 0; public LayerMask ReflectLayers = -1; private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table private RenderTexture m_ReflectionTexture = null; private int m_OldReflectionTextureSize = 0; private static bool s_InsideRendering = false; // This is called when it's known that the object will be rendered by some // camera. We render reflections and do other updates here. // Because the script executes in edit mode, reflections for the scene view // camera will just work! public void OnWillRenderObject() { if (!enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled) return; Camera cam = MainCamera; if (!cam) return; // Safeguard from recursive reflections. if (s_InsideRendering) return; s_InsideRendering = true; Camera reflectionCamera; CreateMirrorObjects(cam, out reflectionCamera); // find out the reflection plane: position and normal in world space Vector3 pos = transform.position; Vector3 normal = transform.up; // Optionally disable pixel lights for reflection int oldPixelLightCount = QualitySettings.pixelLightCount; if (DisablePixelLights) QualitySettings.pixelLightCount = 0; CoreTool.CloneCameraModes(cam, reflectionCamera); // Render reflection // Reflect camera around reflection plane float d = -Vector3.Dot(normal, pos) - ClipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d); Matrix4x4 reflection = CoreTool.CalculateReflectionMatrix(Matrix4x4.zero, reflectionPlane); Vector3 oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint(oldpos); reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CoreTool.CameraSpacePlane(reflectionCamera, pos, normal, 1.0f, ClipPlaneOffset); Matrix4x4 projection = cam.projectionMatrix; projection = CoreTool.CalculateObliqueMatrix(projection, clipPlane,1); reflectionCamera.projectionMatrix = projection; reflectionCamera.cullingMask = ~(1 << 4) & ReflectLayers.value; // never render water layer reflectionCamera.targetTexture = m_ReflectionTexture; GL.SetRevertBackfacing(true); reflectionCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z); reflectionCamera.Render(); reflectionCamera.transform.position = oldpos; GL.SetRevertBackfacing(false); Material[] materials = GetComponent<Renderer>().sharedMaterials; foreach (Material mat in materials) { if (mat.HasProperty("_ReflectionTex")) mat.SetTexture("_ReflectionTex", m_ReflectionTexture); } // Set matrix on the shader that transforms UVs from object space into screen // space. We want to just project reflection texture on screen. Matrix4x4 scaleOffset = Matrix4x4.TRS( new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f)); Vector3 scale = transform.lossyScale; Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z)); mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx; foreach (Material mat in materials) { mat.SetMatrix("_ProjMatrix", mtx); } // Restore pixel light count if (DisablePixelLights) QualitySettings.pixelLightCount = oldPixelLightCount; s_InsideRendering = false; } // Cleanup all the objects we possibly have created void OnDisable() { if (m_ReflectionTexture) { DestroyImmediate(m_ReflectionTexture); m_ReflectionTexture = null; } foreach (DictionaryEntry kvp in m_ReflectionCameras) DestroyImmediate(((Camera)kvp.Value).gameObject); m_ReflectionCameras.Clear(); } // On-demand create any objects we need private void CreateMirrorObjects(Camera currentCamera, out Camera reflectionCamera) { reflectionCamera = null; // Reflection render texture if (!m_ReflectionTexture || m_OldReflectionTextureSize != TextureSize) { if (m_ReflectionTexture) DestroyImmediate(m_ReflectionTexture); m_ReflectionTexture = new RenderTexture(TextureSize, TextureSize,0); m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID(); m_ReflectionTexture.isPowerOfTwo = true; m_ReflectionTexture.hideFlags = HideFlags.DontSave; m_ReflectionTexture.antiAliasing = 4; m_ReflectionTexture.anisoLevel = 0; m_OldReflectionTextureSize = TextureSize; } // Camera for reflection reflectionCamera = m_ReflectionCameras[currentCamera] as Camera; if (!reflectionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO { GameObject go = new GameObject("Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox)); reflectionCamera = go.GetComponent<Camera>(); reflectionCamera.enabled = false; reflectionCamera.transform.position = transform.position; reflectionCamera.transform.rotation = transform.rotation; reflectionCamera.gameObject.AddComponent<FlareLayer>(); go.hideFlags = HideFlags.HideAndDontSave; m_ReflectionCameras[currentCamera] = reflectionCamera; } } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
当然,以上的水的波纹可以按照需求调整。
有一篇博客写得挺好的,那篇博客把波浪和水深的渐变加进去了,效果相当棒。如果用那篇文章的内容加上本篇的内容,基本上就把水的各种技术问题解决了。
http://blog.csdn.net/mobilebbki399/article/details/50493117
最后的效果如下图:有波纹、有反射、折射、有浪花、有水深颜色渐变。
相关文章推荐
- Unity3D shader(18)——水的折射与反射
- Unity3d 实时折射和反射
- OpenGL(十四)环境反射 环境折射 的shader实现
- unity3d Shader镜面高光反射(使用fresenl), bolinPhone是没有物理依据的
- Unity3D Shader(17)——水的折射
- Shader特效——实现“Environment Mapping模拟反射和折射”【基于RenderMonkey】
- 一组自己写的实时折射、镜面反射shader
- Unity Shader 学习笔记(15) 立方体纹理、反射、折射、菲涅尔反射
- 排水管道反射折射 shader
- 分享一组自己写的实时折射、镜面反射shader
- Unity3D - Shader - 高光反射光照模型
- Unity3D Shader——水的折射
- Unity3d 实时折射与反射
- [Unity3d]Shader 着色器 学习前了解知识
- unity3d ulua framwork build打包后shader丢失的问题记录
- Unity3D Shader入门指南(二)
- 猫都能学会的Unity3D Shader入门指南(一
- 【风宇冲】Unity3D教程宝典之Shader篇:目录
- Unity3D Shader 内置函数
- Unity3D 开发之shader教程(实现圆角矩形)