当前位置:网站首页>Unity shader uses rendered texture to achieve glass effect
Unity shader uses rendered texture to achieve glass effect
2022-07-28 17:06:00 【Morita Rinko】
Implementation method :
- adopt cubemap Achieve reflection effect
- adopt GrabPass Get the rendered texture , Match the offset of the upper normal texture , Realize the refraction effect of glass .
Realization effect :

Prepare in advance :
Find the location of the cube cubemap
Code :
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "Custom/Chapter10-GlassRefraction"
{
Properties
{
// The texture of glass
_MainTex("Main Tex",2D)="while"{
}
// Normal texture of glass
_BumpMap("Normal Map",2D)="bump"{
}
// Environment texture used to simulate cube reflection
_CubeMap("Environment Cubemap",Cube)="_Skybox"{
}
// Control the distortion of the image when the glass refracts , Yes GtabPass The degree of distortion treatment
_Distortion("Distortion",Range(0,100))=10
// Used to control the proportion of refraction
_RefractAmount("Refract Amount",Range(0.0,1.0))=1.0
}
SubShader
{
Tags {
"Queue"="Transparent" "RenderType"="Opaque" }
// use GrabPass To get the current screen texture stored in _RefractionTex in , As the refraction texture of the cube
GrabPass{
"_RefractionTex"}
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _BumpMap;
float4 _BumpMap_ST;
samplerCUBE _CubeMap;
float _Distortion;
fixed _RefractAmount;
sampler2D _RefractionTex;
// The size of the texture element that refracts , Later, we need to use
float4 _RefractionTex_TexelSize;
// Vertex shader input structure
struct a2v {
float4 vertex : POSITION;
float3 normal : NORMAL;
// Tangent line
float4 tangent : TANGENT;
// Texture coordinates
float2 texcoord: TEXCOORD0;
};
// Input structure of fragment shader
struct v2f {
float4 pos : SV_POSITION;
// The coordinates of the refracted texture
float4 scrPos : TEXCOORD0;
// Texture coordinates , Normal and reflective
float4 uv : TEXCOORD1;
// Transformation matrix
float4 TtoW0 : TEXCOORD2;
float4 TtoW1 : TEXCOORD3;
float4 TtoW2 : TEXCOORD4;
};
v2f vert(a2v v){
v2f o;
o.pos=UnityObjectToClipPos(v.vertex);
// Get the sampling coordinates of the screen texture
o.scrPos=ComputeGrabScreenPos(o.pos);
// The obtained texture coordinates are stored in uv The four one. float Value
o.uv.xy=TRANSFORM_TEX(v.texcoord,_MainTex);
o.uv.zw=TRANSFORM_TEX(v.texcoord,_BumpMap);
float3 worldPos =mul(unity_ObjectToWorld,v.vertex);
// Normal in world space , Tangent and sub tangent , Used to find the transformation matrix from tangent space to world space
fixed3 worldNormal = UnityObjectToWorldNormal(v.normal);
fixed3 worldTangent =UnityObjectToWorldDir(v.tangent.xyz);
// The sub tangent obtains the direction by cross multiplying the normal and tangent
fixed3 worldBinormal =cross(worldNormal,worldTangent)*v.tangent.w;
// Transform matrix storage , And store the world coordinates in w variable , Save space
o.TtoW0=float4(worldTangent.x,worldBinormal.x,worldNormal.x,worldPos.x);
o.TtoW1=float4(worldTangent.y,worldBinormal.y,worldNormal.x,worldPos.y);
o.TtoW2=float4(worldTangent.z,worldBinormal.z,worldNormal.x,worldPos.z);
return o;
}
fixed4 frag(v2f i):SV_Target{
// World coordinates
float3 worldPos =float3(i.TtoW0.w,i.TtoW1.w,i.TtoW2.w);
// Look in the direction
fixed3 worldViewDir =normalize(UnityWorldSpaceViewDir(worldPos));
// Normal in tangent space
fixed3 bump =UnpackNormal(tex2D(_BumpMap,i.uv.zw));
// Offset of refraction texture coordinates
float2 offset=bump.xy*_Distortion*_RefractionTex_TexelSize;
i.scrPos.xy+=offset;
fixed3 RefrCol=tex2D(_RefractionTex,i.scrPos.xy/i.scrPos.w).rgb;
// normal transformation , matrix multiplication , Transform normals into world space
bump =normalize(half3(dot(i.TtoW0.xyz,bump),dot(i.TtoW1.xyz,bump),dot(i.TtoW2.xyz,bump)));
// Reflect light
fixed3 reflDir =reflect(-worldViewDir,bump);
// Color of glass
fixed4 texColor =tex2D(_MainTex,i.uv.xy);
// The color obtained by sampling the stereo texture is multiplied by the glass color to obtain the reflected color
fixed3 reflCol =texCUBE(_CubeMap,reflDir).rgb*texColor.rgb;
// The final color is reflection and refraction multiplied by their respective weights and added together
fixed3 finalColor =reflDir*(1-_RefractAmount)+RefrCol*_RefractAmount;
return fixed4(finalColor,1.0);
}
ENDCG
}
}
FallBack "Diffuse"
}
边栏推荐
- Create a self-organizing / safe / controllable Lora network! Semtech responded for the first time to the impact of the "new regulations of the Ministry of industry and information technology"
- Alibaba cloud - Wulin headlines - site building expert competition
- asmlinkage的理解
- 2020Q2全球平板市场出货大涨26.1%:华为排名第三,联想增幅最大!
- Global mobile communication base station market in 2019: Ericsson, Huawei and Nokia ranked in the top three
- Summary of kubenertes 1.16 cluster deployment problems
- [deep learning]: day 9 of pytorch introduction to project practice: dropout implementation (including source code)
- 时间复杂度
- Alibaba cloud MSE supports go language traffic protection
- 关于 CMS 垃圾回收器,你真的懂了吗?
猜你喜欢

Ugui learning notes (II) Scrollview related

Re10:读论文 Are we really making much progress? Revisiting, benchmarking, and refining heterogeneous gr

Do you really understand CMS garbage collector?

Alibaba cloud MSE supports go language traffic protection

Re13:读论文 Gender and Racial Stereotype Detection in Legal Opinion Word Embeddings

综合设计一个OPPE主页--页面的售后服务

HTAP是有代价的

Easypoi multi sheet export by template

浏览器解码过程分析

阿里云 MSE 支持 Go 语言流量防护
随机推荐
时间复杂度
go语言慢速入门——流程控制语句
Easypoi multi sheet export by template
记录开发问题
Ruoyi's solution to error reporting after integrating flyway
How to set ticdc synchronization data to only synchronize the specified library?
智慧园区是未来发展的趋势吗?
Re14:读论文 ILLSI Interpretable Low-Resource Legal Decision Making
Re13:读论文 Gender and Racial Stereotype Detection in Legal Opinion Word Embeddings
Outline and principle of structured design -- modularization
打造自组/安全/可控的LoRa网!Semtech首度回应“工信部新规”影响
Record development issues
做题笔记3(二分查找)
SUSE CEPH rapid deployment – storage6
Probability theory and mathematical statistics Chapter 1
Simple addition, deletion, modification and query of commodity information
epoll水平出发何边沿触发
It is said that NVIDIA has held talks with Softbank and will offer more than US $32billion to acquire arm
Ugui learning notes (I) rendering level
Alibaba cloud MSE supports go language traffic protection