Unity Shader 获取场景深度图

获取场景深度图,需要明白场景中的物体是否是透明物体,透明物体和不透明物体的获取方式不一样。

一、获取场景中不透明物体深度图

1、创建Render Texture

2、创建Shader脚本

Shader "Custom/Depth" 
{  
	SubShader {  
		
		Pass{  
			CGPROGRAM  
			#pragma vertex vert  
			#pragma fragment frag  
			#include "UnityCG.cginc"  

			sampler2D _CameraDepthTexture;  
			struct v2f 
			{  
			   float4 pos : SV_POSITION;  
			   float4 scrPos:TEXCOORD1;  
			};  

			v2f vert (appdata_base v)
			{  
			   v2f f;  		  
			   f.pos = UnityObjectToClipPos (v.vertex);  
			   f.scrPos=ComputeScreenPos(f.pos);  
			   return f;  
			}  
			  
			half4 frag (v2f f) : COLOR
			{  
			   float depthValue =Linear01Depth (tex2Dproj(_CameraDepthTexture,UNITY_PROJ_COORD(f.scrPos)).r);
			   return half4(depthValue,depthValue,depthValue,1);  
			}  
			ENDCG  
		}  
	}  
	FallBack "Diffuse"  
}  

3、创建材质,修改shader为上面的shader

4、创建相机,创建c#脚本,保存深度图

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class depth : MonoBehaviour
{
    // Start is called before the first frame update
    private Camera m_Camera;
    public Material Mat;
    public RenderTexture DepthRenderTexture;
    string m_DepthMapName;
    void Start()
    {
        m_Camera = gameObject.GetComponent();
        m_Camera.depthTextureMode = DepthTextureMode.Depth;
        m_DepthMapName = "depth.png";
    }
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (null != Mat)
        {
            Graphics.Blit(source, DepthRenderTexture, Mat);
            saveDepthMap();
        }
    }

    private void saveDepthMap()
    {
        int Width = DepthRenderTexture.width;
        int Height = DepthRenderTexture.height;
        Texture2D texture2D = new Texture2D(Width, Height);
        var previous = RenderTexture.active;
        RenderTexture.active = DepthRenderTexture;
        texture2D.ReadPixels(new Rect(0, 0, Width, Height), 0, 0);
        RenderTexture.active = previous;
        texture2D.Apply();
        byte[] Data = texture2D.EncodeToPNG();
        FileStream file = File.Open(m_DepthMapName, FileMode.Create, FileAccess.Write);
        BinaryWriter writer = new BinaryWriter(file);
        writer.Write(Data);
        file.Close();
    }
}

在工程目录下面可以看到深度图

Unity Shader 获取场景深度图_第1张图片

参考文章:https://www.jianshu.com/p/72c07b0bbaa5

 

二、场景中透明物体深度图获取

待写

 

 

 

你可能感兴趣的:(unity,unity)