【Unity Shader】Builtin升级URP学习笔记(一)
一、URP Shader模板Shader "URP/URPShader"
{
Properties
{
_Color ("Color", Color)=(1,1,1,1)
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderPipeline"="UniversalPipeline" "RenderType"="Opaque" }
LOD 100
Pass
{
Tags{"LightMode"="UniversalForward"}
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal : TEXCOORD1;
};
struct v2f
{
float2 uv : TEXCOORD0;
float3 worldPos : TEXCOORD1;
float3 worldNormal : TEXCOORD2;
float fogCoord : TEXCOORD3;
float4 vertex : SV_POSITION;
};
TEXTURE2D(_MainTex);
SAMPLER(sampler_MainTex);
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
float4 _Color;
CBUFFER_END
v2f vert (appdata v)
{
v2f o;
o.vertex = TransformObjectToHClip(v.vertex.xyz);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.worldNormal = TransformObjectToWorldDir(v.normal);
o.worldPos = TransformObjectToWorldDir(v.vertex.xyz);
o.fogCoord = ComputeFogFactor(o.vertex.z);
return o;
}
half4 frag (v2f i) : SV_Target
{
Light light = GetMainLight();
half3 worldNormal = normalize(i.worldNormal);
half3 worldLightDir=normalize(TransformObjectToWorldDir(light.direction));
half4 col = SAMPLE_TEXTURE2D(_MainTex,sampler_MainTex,i.uv)*_Color;
half3 diffuse = LightingLambert(light.color.rgb, worldLightDir, worldNormal);
half3 ambient = _GlossyEnvironmentColor.rgb;
col.rgb=col.rgb*diffuse+ambient;
col.rgb = MixFog(col.rgb,i.fogCoord);
return col;
}
ENDHLSL
}
}
FallBack "Packages/com.unity.render-pipelines.universal/FallbackError"
}其它可参考这个大佬的文章,其中包含了各种URP Shader的编写方式:
二、URP升级指南
详情可参考:
三、补充
接收阴影:
float4 SHADOW_COORDS = TransformWorldToShadowCoord(i.worldPos);
Light mainLight = GetMainLight(SHADOW_COORDS);
half shadow = mainLight.shadowAttenuation;要使上面生效,必须声明
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
#pragma multi_compile _ _SHADOWS_SOFT投射阴影:
URP自带的ShadowCaster:
UsePass "Universal Render Pipeline/Lit/ShadowCaster"经常会打断batcher,需要自己重定义。
获取深度图:
内置管线中
//声明深度图
sampler2D_CameraDepthTexture;
//获取屏幕坐标
o.scrPos = ComputeScreenPos(o.vertex);
//采样深度图
float depth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.scrPos)));
float depthValue = Linear01Depth(depth);URP中
//声明深度图
TEXTURE2D_X_FLOAT(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);
//获取屏幕坐标
o.scrPos = ComputeScreenPos(vertexInput.positionCS);
//采样深度图
float2 screenPos= v.scrPos .xy / v.scrPos .w;
float depth = SAMPLE_TEXTURE2D_X(_CameraDepthTexture, sampler_CameraDepthTexture, screenPos).r;
float depthValue = Linear01Depth(depth, _ZBufferParams);
页:
[1]