在Unity上渲染出Depth與Normal圖,網路上可用的資源實在有夠舊的,連官方範例都無法使用
參考此篇
http://williamchyr.com/2013/11/unity-shaders-depth-and-normal-textures-part-3/comment-page-1/#comment-202908
修改一些段落變成Unity5可用的
Script--
float4 depth = float4(depthValue);
改成
float4 depth = float4(depthValue,depthValue,depthValue,1.0);
Shader--
camera.depthTextureMode = DepthTextureMode.DepthNormals;
改成
GetComponent().depthTextureMode = DepthTextureMode.DepthNormals;
o.scrPos.y = 1 - o.scrPos.y; //刪除此行
Fixed Code 直接可以套用
RenderCamera.cs
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class RenderCamera : MonoBehaviour {
bool showNormalColors = true;
public Material mat;
void Start()
{
GetComponent<Camera>().depthTextureMode = DepthTextureMode.DepthNormals;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
showNormalColors = !showNormalColors;
}
if (showNormalColors)
{
mat.SetFloat("_showNormalColors", 1.0f);
}
else
{
mat.SetFloat("_showNormalColors", 0.0f);
}
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source, destination, mat);
//mat is the material which contains the shader
//we are passing the destination RenderTexture to
}
}
DepthNormalShader.shader
Shader "Custom/DepthNormalShader" {
Properties {
_MainTex ("", 2D) = "white" {}
_HighlightDirection ("Highlight Direction", Vector) = (1, 0,0)
}
SubShader {
Tags { "RenderType"="Opaque" }
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _CameraDepthNormalsTexture;
float _StartingTime;
float _showNormalColors = 1; //when this is 1, show normal values as colors. when 0, show depth values as colors.
struct v2f {
float4 pos : SV_POSITION;
float4 scrPos: TEXCOORD1;
};
//Our Vertex Shader
v2f vert (appdata_base v){
v2f o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.scrPos=ComputeScreenPos(o.pos);
return o;
}
sampler2D _MainTex;
float4 _HighlightDirection;
//Our Fragment Shader
half4 frag (v2f i) : COLOR{
float3 normalValues;
float depthValue;
//extract depth value and normal values
DecodeDepthNormal(tex2D(_CameraDepthNormalsTexture, i.scrPos.xy), depthValue, normalValues);
if (_showNormalColors == 1){
float4 normalColor = float4(normalValues, 1);
return normalColor;
} else {
float4 depth = float4(depthValue,depthValue,depthValue,1.0);
return depth;
}
}
ENDCG
}
}
FallBack "Diffuse"
}
沒有留言:
張貼留言