IronWarrior / UnityOutlineShader

Source code for Outline Shader tutorial for Unity. Detects edges in a scene using the depth and normals buffers.
https://roystan.net/articles/outline-shader
The Unlicense
882 stars 109 forks source link

Draw outlines only with depth buffer #7

Open liuxinjia opened 4 years ago

liuxinjia commented 4 years ago

image @IronWarrior Thank your tutorial first! But I found we can draw outlines only with depth buffer.

float4 Frag(VaryingsDefault i) : SV_Target
{

    float halfScaleFloor = floor(_Scale * .5);
    float halfScaleCeil = ceil(_Scale * .5);
    float2 bottomLeftUV = i.texcoord - float2(_MainTex_TexelSize.x, _MainTex_TexelSize.y) * halfScaleFloor;
    float2 topRightUV = i.texcoord + float2(_MainTex_TexelSize.x , _MainTex_TexelSize.y) * halfScaleCeil;
    float2 bottomRightUV = i.texcoord + float2(_MainTex_TexelSize.x * halfScaleCeil, - _MainTex_TexelSize.y * halfScaleFloor);
    float2 topLeftUV = i.texcoord + float2(-_MainTex_TexelSize.x * halfScaleFloor, _MainTex_TexelSize.y * halfScaleCeil);

    float depth0 = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_CameraDepthTexture, bottomLeftUV).r;
    float depth1 = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_CameraDepthTexture, topRightUV).r;
    float depth2 = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_CameraDepthTexture, bottomRightUV).r;
    float depth3 = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_CameraDepthTexture, topLeftUV).r;

    float depthFiniteDifference0 = depth1 - depth0;
    float depthFiniteDifference1 = depth3 - depth2;
    float edgeDepth = sqrt(pow(depthFiniteDifference0, 2) + pow(depthFiniteDifference1, 2)) * 100;
    // edgeDepth = step( _DepthThreshold, edgeDepth);  // Actullay, it will eliminate the material color

    return edgeDepth;
}

And I'm using unity 2019.3.3f1.