IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> Unity URP draw mesh屏幕描边 -> 正文阅读

[游戏开发]Unity URP draw mesh屏幕描边

在unity后效中可以创建自定义效果,但是后效中获取不到stencil,这里采用render feature draw mesh的方法,在相机前方绘制一个quad片和场景直接进行blend,这样这个方片是能够拿到stencil的,后续可能会有其他问题。这里作为尝试进行实现。

C#部分

public class ScreenOutlineFeature : ScriptableRendererFeature
{
	private Material _material;
    private const string screenOutline = "path/ScreenOutline";
	private ScreenOutlinePass screenOutlinePass;
	...

	  public override void AddRenderPasses(ScriptableRenderer renderer) 
        {
            if (screenOutlinePass == null)
                screenOutlinePass = new ScreenOutlinePass(Event);//传递或直接在pass中写event
            if (!GetMaterial()) return;

            //set properites...
			
            screenOutlinePass.Setup(_material);
            renderer.EnqueuePass(screenOutlinePass);
        }
        
      Boolean GetMaterial()
        {
            if (_material == null)
            {
                var outLineShader = Shader.Find(screenOutline);
                if (outLineShader == null)
                {
                    Debug.Log($"Check for missing shader {screenOutline}");
                    return false;
                }

                _material = CoreUtils.CreateEngineMaterial(Shader.Find(screenOutline));
            }

            if (_material == null)
            {
                Debug.LogWarning("Missing screenOutline material. effect will not Active. Check for missing shader");
                return false;
            }

            if (!_material.shader.isSupported) return false;
            return true;
        }
}

public class ScreenOutlinePass : ScriptableRenderPass
{
		const string m_ProfilerTag = "Screen Outline";
        private ProfilingSampler m_ProfilingSampler = new ProfilingSampler(m_ProfilerTag);
        public Material _material;
        public ScreenOutlinePass(RenderPassEvent evnt)
        {
            this.renderPassEvent = evnt;
        }
           public void Setup(Material material)
        {
            this._material = material;
        }
        
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (_material == null) return;
            var camera = renderingData.cameraData.camera;
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);
            using (new ProfilingScope(cmd, m_ProfilingSampler))
            {
                cmd.Clear();
                context.ExecuteCommandBuffer(cmd);
                cmd.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
                cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, _material);
                cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix);
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
}

Shader部分

//给stencil值和场景中物体的stencil做比较
Stencil {
		     Ref [_Stencil]
		     Comp Equal 
		     Pass keep
		}
            Blend SrcAlpha OneMinusSrcAlpha
            
            Cull Off
            ZWrite Off
            ZTest Always
//如果想要雾效能够影响描边结果需要在这里根据深度还原世界坐标
float3 ReconstructWorldPos(half2 screenPos, float depth)
{
   #if defined(SHADER_API_GLCORE) || defined (SHADER_API_GLES) || defined (SHADER_API_GLES3)        
   // OpenGL平台 //
        depth = depth * 2 - 1;
   #endif
   #if UNITY_UV_STARTS_AT_TOP
       screenPos.y = 1 - screenPos.y;
   #endif

   float4 raw = mul(UNITY_MATRIX_I_VP, float4(screenPos * 2 - 1, depth, 1));
   float3 worldPos = raw.rgb / raw.a;
   return worldPos;
}
//借用urp10.x后的采样方法,如果有normal这里一并采样
			float3 SampleSceneNormals(float2 uv)
            {
                return UnpackNormalOctRectEncode(SAMPLE_TEXTURE2D_X(_CameraNormalsTexture, sampler_ScreenTextures_linear_clamp, UnityStereoTransformScreenSpaceTex(uv)).xy) * float3(1.0, 1.0, -1.0);
            }

            float SampleScreenDepths(float2 uv)
            {
                return LinearEyeDepth(SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_ScreenTextures_linear_clamp,UnityStereoTransformScreenSpaceTex(uv).xy), _ZBufferParams);
            }

//frag
//拿雾效颜色和outline颜色混合
half4 color = half4(lerp(fogColor.rgb, _OutlineColor.rgb, _OutlineColor.a), saturate(edge));
//outline 具体计算参考自
//https://www.vertexfragment.com/ramblings/unity-postprocessing-sobel-outline/
float GetEdge_D(float edgeSample[5])
{
    float depth_0 = abs(edgeSample[1] - edgeSample[0]);
    depth_0 += abs(edgeSample[2] - edgeSample[0]);
    depth_0 += abs(edgeSample[3] - edgeSample[0]);
    depth_0 += abs(edgeSample[4] - edgeSample[0]);
    float edgeDepth = depth_0 * _OutlineDepthMultiplier;
    return edgeDepth;
}

float GetEdge_N(float3 edgeSample[5])
{
    float normal_0 = 1 - dot(edgeSample[1], edgeSample[0]);
    normal_0 += 1 - dot(edgeSample[2], edgeSample[0]);
    normal_0 += 1 - dot(edgeSample[3], edgeSample[0]);
    normal_0 += 1 - dot(edgeSample[4], edgeSample[0]);
    float edgeNormal = normal_0 * _OutlineNormalMultiplier;
    return  edgeNormal;
}

void Outline_float(float2 UV, float depth, float3 viewDir, out float edge)
{
    float dis   = LinearEyeDepth(depth, _ZBufferParams);
    float depthDis = saturate((_OutlineEnd - dis) / (_OutlineEnd - _OutlineStart));
    //对描边粗细做距离约束
    depthDis = lerp(_OutlineCurveMax, _OutlineCurveMin, depthDis);
    
    float3 offset = float3((1 / _ScreenParams.x), (1 / _ScreenParams.y), 0) * depthDis;

    float2 uvSamples[5];
    float depthSamples[5];
    float3 normalSamples[5];
    
    uvSamples[0] = UV;
    uvSamples[1] = UV - offset.xz;
    uvSamples[2] = UV + offset.xz;
    uvSamples[3] = UV + offset.zy;
    uvSamples[4] = UV - offset.zy;

    for (int i = 0; i < 5; i++)
    {
        depthSamples[i] = SampleScreenDepths(uvSamples[i]);
        normalSamples[i] = SampleSceneNormals(uvSamples[i]);
    }

    // Depth
    float edgeDepth = GetEdge_D(depthSamples);
   
    // Normals
    float edgeNormal = GetEdge_N(normalSamples);
	// 裁剪溢出部分
    float NdotV = 1 - dot(normalSamples[0], -viewDir); // 0 -2
    float normalThreshold01 = saturate((NdotV - 0.1) / (1 - 0.1));//这里0.1数值可以自己调整
    float normalThreshold = normalThreshold01 * _OutlineDepthBevelDamp + 1;
    float depthThreshold = _OutlineDepthDisDamp * depthSamples[0] * normalThreshold;
    edgeDepth = edgeDepth > depthThreshold ? 1 : 0;
   
    edge = max(edgeDepth, edgeNormal);
    //远距离透明,可选
     float minDepth  = _OutlineNear;
     float depthSpan = _OutlineFar;
     float alpha     = lerp(1.0, 0.0, (clamp(dis, minDepth, minDepth + depthSpan) - minDepth) / depthSpan);
     edge = edge * alpha; 
}
  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2021-08-31 15:47:58  更:2021-08-31 15:48:28 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年2日历 -2025/2/5 22:13:07-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码