Ray Marching(一)

Ray Marching(一)

Ray Marching(一)_第1张图片

主要内容:实现世界坐标下摄像机发出的射线向量
通过分形的Noise实现云朵

1.在unity做ray marching的射线
2.Noise与FBM
3.依据ray的旋转角实现天空
4.天空的其他部分

1.RayMarching射线

求出根据相机fieldOfView与近裁剪面的距离求出近裁剪面四个顶点相对与摄像机的相对向量;
再将四个向量值赋予 后期处理的全屏四边形 的四个顶点上;
这四个顶点会通过shader中的插值,求出在每个片元上的ray向量;

2.Noise与FBM

详细请看:https://blog.csdn.net/candycat1992/article/details/50346469 【冯乐乐】
这里我用的是value noise

    float Noise(float2 p)
    {
        float2 pi = floor(p);
        float2 pf = p - pi;
        
        float2 w = pf * pf * (3.0 - 2.0 * pf);
        
        return lerp(lerp(Hash12(pi + float2(0.0, 0.0)), Hash12(pi + float2(1.0, 0.0)), w.x),
                lerp(Hash12(pi + float2(0.0, 1.0)), Hash12(pi + float2(1.0, 1.0)), w.x),
                w.y);
    }

FBM(分形后的Noise)这里加了2D的旋转矩阵 ,并加入了时间移动

    float FBM( float2 p ,float time)
    {
        float f = 0.0;
        p+=time;
        f += 0.50000*Noise( p ); p = mul(float2x2(0.8,-0.6,0.6,0.8),p)*2.01; p+=time;
        f += 0.25000*Noise( p  ); p = mul(float2x2(0.8,-0.6,0.6,0.8),p)*2.02; p+=time;
        f += 0.12500*Noise( p ); p = mul(float2x2(0.8,-0.6,0.6,0.8),p)*2.03; p+=time;
        f += 0.06250*Noise( p  ); p = mul(float2x2(0.8,-0.6,0.6,0.8),p)*2.04; p+=time;
        f += 0.03100*Noise( p  ); p = mul(float2x2(0.8,-0.6,0.6,0.8),p)*2.04; p+=time;
        return f/0.984375;
    }
Ray Marching(一)_第2张图片

3.依据ray的旋转角实现天空

先来看一下利用ray向量各个分形,类似2Duv平铺后的情况 frac(ray.xyz)

Ray Marching(一)_第3张图片

来用ps剖切下
Ray Marching(一)_第4张图片

所以在描绘天空时,应用ray的xz坐标读取Noise

但天空编成了球形,这不是我们我们想要的。下面把天空变为一个旋在头顶的平面
Ray Marching(一)_第5张图片

Ray Marching(一)_第6张图片

//cloud
    float cos0 = dot(normalize(rd),float3(0,1,0));
    float cloudNoise = 0;
    float s = 0.5;
    for(int i=0;i<3;i++){
        float height = 2000 + i * 1000;
        float3 pos = height/cos0 * rd;
        float2 worldXZ = ro.xz + pos.xz;
        cloudNoise += s * FBMRTIME(worldXZ/2000 + i * 500 ,(_Time.y / (1+i*2)) /20);
        s*=0.5;
    }
    cloudNoise = smoothstep(0.4, 0.6, cloudNoise);

代码中的循环,是为了制作三层不同高度的云,第一层2000,每向上一层+1000
并且每层云移动速度也有不同

4.天空其他部分

剩下的问题:代码说话


Ray Marching(一)_第7张图片

1.颜色

    //skycolor
    float3 skyColor= float3(0.2,0.5,0.85)*1.1 - rd.y*rd.y*0.5;
    skyColor= lerp( skyColor, 0.85*float3(0.7,0.75,0.85), pow( 1.0-max(rd.y,0.0), 4.0 ) );
    skyColor+=sunColor;

2.太阳

    // sun
    float sundot = clamp(dot(rd,lightDir),0.0,1.0);
    float3 sunColor= 0.25*float3(1.0,0.7,0.4)*pow( sundot,5.0 );
    sunColor += 0.25*float3(1.0,0.8,0.6)*pow( sundot,64.0 );
    sunColor += 0.4*float3(1.0,0.8,0.6)*pow( sundot,512.0 );

3.太密了与地面。太密了:偷懒就用远处的雾来遮住;
方法用ray的y分量的值 lerp 天空/雾/地面的颜色;

//skydown
    float3 sky =lerp(skyColor ,float3(1.0,0.95,1.0) , cloudNoise );
    sky =lerp(skyColor , sky ,smoothstep(-0.1,0.25,rd.y) ) ;
    sky =lerp(float3(0.4,0.4,0.4) , sky ,smoothstep(-0.1,0.1,rd.y) );

图片压缩太厉害出现个大白道

1.ray向量的后期

c#脚本

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

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class RayMarch : MonoBehaviour
{
    public float MountainHeight;
    
    public Material material;
    //public Transform DirLightTransform;
    public Vector3 LightDir;
    private Camera MyCamera;

    private Transform MyCameraTransform;

    //如果不支持material就取消勾选
    private void Start(){
        if(material==null||material.shader==null||!material.shader.isSupported){
            enabled=false;
            return;
        }else{
            MyCamera=GetComponent();
        }
    }
    void OnEnalbe(){
        //让摄像机产生深度纹理
        MyCamera.depthTextureMode |=DepthTextureMode.Depth;
    }

    [ImageEffectOpaque]
    void OnRenderImage(RenderTexture src,RenderTexture dest){
        if(material!=null){
            SetRay();
            Graphics.Blit(src,dest,material);
        }else{
            Graphics.Blit(src,dest);
        }
    }

    private  void SetRay(){
        Matrix4x4 fourPoint=Matrix4x4.identity; //角度与弧度的转换 Π 与 0
        float fov = MyCamera.fieldOfView;
        float near =MyCamera.nearClipPlane;
        float aspect=MyCamera.aspect;

        float halfHeight = near* Mathf.Tan(fov*0.5f*Mathf.Deg2Rad);
        float halfRight = halfHeight * aspect;
        Vector3 toHeight = MyCamera.transform.up * halfHeight;
        Vector3 toRight = MyCamera.transform.right * halfRight;

        Vector3 topLeft = MyCamera.transform.forward*near + toHeight - toRight;
        float scale= topLeft.magnitude/near;
        topLeft*= scale;

        Vector3 topRight=MyCamera.transform.forward*near +toHeight +toRight;
        topRight*=scale;

        Vector3 bottomLeft=MyCamera.transform.forward*near - toHeight -toRight;
        bottomLeft*=scale;

        Vector3 bottomRight=MyCamera.transform.forward*near -toHeight +toRight;
        bottomRight*=scale;

        fourPoint.SetRow(0,bottomLeft);
        fourPoint.SetRow(1,bottomRight);
        fourPoint.SetRow(2,topRight);
        fourPoint.SetRow(3,topLeft);
        
        
        //Vector4 DirLight=DirLightTransform.eulerAngles;
        Vector4 DirLight=LightDir;
        material.SetMatrix("_FourRay",fourPoint);
        material.SetFloat("_MountainHeight",MountainHeight);
        material.SetVector("_LightDir",DirLight);
    }

}

shader 天空代码写在ProcessRayMarch()里

Shader "Hidden/RayMarching"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _MountainHeight("MountainHeight",float)=100
        _LightDir("LightDir",vector)=(0,1,0,0)
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"
            #include "RayTemp.cginc" 

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                float4 Ray:TEXCOORD1;
            };

            sampler2D _MainTex;
            float2 _MainTex_TexelSize;

            float4x4 _FourRay;
            
            

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                int index=0;
                if( o.uv.x<0.5 && o.uv.y<0.5){
                    index = 0 ;
                }else if( o.uv.x>0.5 && o.uv.y<0.5){
                    index = 1;
                }else if( o.uv.x>0.5 && o.uv.y>0.5){
                    index = 2;
                }else if( o.uv.x<0.5 && o.uv.y>0.5){
                    index = 3;
                }

                #if UNITY_UV_STARTS_AT_TOP
                    if (_MainTex_TexelSize.y < 0)
                        index = 3 - index;
                #endif

                o.Ray = _FourRay[index];
                return o;
            }


            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 sceneCol=tex2D(_MainTex,i.uv);
                float3 ro = _WorldSpaceCameraPos;
                float3 rd = normalize(i.Ray.xyz);
                
                return ProcessRayMarch(ro,rd,sceneCol);
            }
            ENDCG
        }
    }
}

2.天空shader

float4 ProcessRayMarch(float3 ro,float3 rd,float4 sceneCol){
    //data
    float3 lightDir=normalize( _LightDir.xyz);
    float4 finalColor=float4(0,0,0,1);

    //sky-------------------------------------------------------------------------------
    //cloud
    float cos0 = dot(normalize(rd),float3(0,1,0));
    float cloudNoise = 0;
    float s = 0.5;
    for(int i=0;i<3;i++){
        float height = 2000 + i * 1000;
        float3 pos = height/cos0 * rd;
        float2 worldXZ = ro.xz + pos.xz;
        cloudNoise += s * FBMRTIME(worldXZ/2000 + i * 500 ,(_Time.y / (1+i*2))/5 );
        s*=0.5;
    }
    cloudNoise = smoothstep(0.4, 0.6, cloudNoise);
    // sun
    float sundot = clamp(dot(rd,lightDir),0.0,1.0);
    float3 sunColor= 0.25*float3(1.0,0.7,0.4)*pow( sundot,5.0 );
    sunColor += 0.25*float3(1.0,0.8,0.6)*pow( sundot,64.0 );
    sunColor += 0.4*float3(1.0,0.8,0.6)*pow( sundot,512.0 );
    //skycolor
    float3 skyColor= float3(0.2,0.5,0.85)*1.1 - rd.y*rd.y*0.5;
    skyColor= lerp( skyColor, 0.85*float3(0.7,0.75,0.85), pow( 1.0-max(rd.y,0.0), 4.0 ) );
    skyColor+=sunColor;
    //skydown
    float3 sky =lerp(skyColor ,float3(1.0,0.95,1.0) , cloudNoise );
    sky =lerp(skyColor , sky ,smoothstep(-0.1,0.25,rd.y) ) ;
    sky =lerp(float3(0.4,0.4,0.4) , sky ,smoothstep(-0.1,0.1,rd.y) );



    return float4(sky,1.);
}

你可能感兴趣的:(Ray Marching(一))