Unity shader学习之屏幕后期效果之调整屏幕亮度,饱和度,对比度

时间:2025-01-02 22:35:14

Unity的屏幕后期处理效果,使用MonoBehaviour.OnRenderImage来实现。

转载请注明出处:http://www.cnblogs.com/jietian331/p/7228063.html

如代码如下:

基类:

 using UnityEngine;

 [RequireComponent(typeof(Camera))]
public abstract class PostEffectRenderer : GameBehaviour
{
protected abstract string ShaderName { get; } Material m_mat; void Start()
{
if (!SystemInfo.supportsImageEffects)
NotSupport();
} protected virtual void OnRenderImage(RenderTexture src, RenderTexture dest)
{
Graphics.Blit(src, dest, Mat);
} protected void NotSupport()
{
enabled = false;
} protected Material Mat
{
get
{
if (!m_mat)
{
Shader shader = Shader.Find(ShaderName);
if (shader != null && shader.isSupported)
m_mat = new Material(shader);
else
NotSupport();
}
return m_mat;
}
}
}

PostEffectRenderer

子类实现 :

 using UnityEngine;

 public class ScreencolorsAdjuster : PostEffectRenderer
{
[SerializeField]
float m_brightness = ;
[SerializeField]
float m_saturation = ;
[SerializeField]
float m_contrast = ; protected override void OnRenderImage(RenderTexture src, RenderTexture dest)
{
base.Mat.SetFloat("_Brightness", m_brightness);
base.Mat.SetFloat("_Saturation", m_saturation);
base.Mat.SetFloat("_Contrast", m_contrast);
base.OnRenderImage(src, dest);
} protected override string ShaderName
{
get { return "Custom/Screencolors Adjuster"; }
}
}

ScreencolorsAdjuster

shader如下:

 Shader "Custom/Screencolors Adjuster"
{
Properties
{
_MainTex("Main Texture", 2D) = "white" {}
_Brightness("Brightness", Float) =
_Saturation("Saturation", Float) =
_Contrast("Contrast", Float) =
} SubShader
{
Pass
{
ZTest Always
ZWrite Off
Cull Off CGPROGRAM
#pragma vertex vert
#pragma fragment frag sampler2D _MainTex;
float _Brightness;
float _Saturation;
float _Contrast; struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
}; struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
}; v2f vert(appdata v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = v.uv; return o;
} fixed4 frag(v2f i) : SV_TARGET
{
fixed4 tex = tex2D(_MainTex, i.uv); fixed3 finalCol = tex.rgb * _Brightness; fixed luminance = dot(fixed3(0.2125, 0.7154, 0.0721), tex.rgb);
fixed3 luminanceCol = fixed3(luminance, luminance, luminance);
finalCol = lerp(finalCol, luminanceCol, _Saturation); fixed3 avgCol = fixed3(0.5, 0.5, 0.5);
finalCol = lerp(finalCol, avgCol, _Contrast); return fixed4(finalCol, tex.a);
} ENDCG
}
} Fallback Off
}

ScreencolorsAdjuster脚本挂在摄像机上:

Unity shader学习之屏幕后期效果之调整屏幕亮度,饱和度,对比度

调整参数,效果如下:

Unity shader学习之屏幕后期效果之调整屏幕亮度,饱和度,对比度 Unity shader学习之屏幕后期效果之调整屏幕亮度,饱和度,对比度