스토리지

[5.6] Lightening 계산 본문

Unity/Shader

[5.6] Lightening 계산

ljw4104 2021. 5. 6. 11:23

 

왼쪽의 그림은 구의 위쪽에서 조명이 비추고 있는 모습이다.

빛이 들어오는 벡터와 표면벡터 (Normal Vector) 의 Dot(내적)이 -1인 부분이 제일 밝다.

그리고 빛으로부터의 각도가 커지면 커질수록 빛이 들어오는 양이 줄어든다. 즉 어두워진다.

90도가 되는 지점을 기점으로 아예 검정색이다.

그래도 아직 밝게 보이는 이유는 환경광 (Ambient) 때문이다.

그래서 환경광을 제거해주어야 조명을 우리가 조종할 수 있다.

 

 

조명 계산

● CG Function - dot ( 내적계산 )

developer.download.nvidia.com/cg/dot.html

 

dot

Name dot - returns the scalar dot product of two vectors Synopsis float dot(float a, float b); float dot(float1 a, float1 b); float dot(float2 a, float2 b); float dot(float3 a, float3 b); float dot(float4 a, float4 b); half dot(half a, half b); half dot(ha

developer.download.nvidia.com

Shader "Custom/Test"
{
    Properties
    {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Test noambient
        //Unity의 내장 함수대신에 함수를 커스텀함 이름 : Test

        sampler2D _MainTex;

        struct Input
        {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o)
        {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }

        //surf가 출력한 값을 바탕으로 계산하기에 밑에서 선언하는 편이 좋음.
        //★ 위에 정의한 것 앞에 Lighting을 꼭 붙인 다음에 선언해야한다. ★       ex) Lighting + Test.
        float4 LightingTest(SurfaceOutput s, float3 lightDir, float atten)  
        //s: 위에서 저장된 구조체, lightDir: 조명 (단위)벡터, atten: 감쇠(attenuation, 가까우면 밝아지고, 멀어지면 어두워진다.)
        {
            //조명이 가장 밝을때가 -1이기때문에 조명벡터가 뒤집혀서 들어온다.
            float ndotl = dot(s.Normal, lightDir);      //normal벡터와 light벡터를 내적한 값.
            return ndotl;
        }

        ENDCG
    }
    FallBack "Diffuse"
}

결과값

  • 임의의 조명함수 선언 시, float4 Lighting + 이름 형식으로 무조건 선언하여야 한다.
  • 두 벡터를 내적하면 float 값 하나가 나오지만 반환할 수 있다.

'Unity > Shader' 카테고리의 다른 글

[5.6] Light 연산 정리  (0) 2021.05.06
[5.6] Light 연산 (Lambert, Half-Lambert)  (0) 2021.05.06
[5.4] Shader Lightening  (0) 2021.05.04
[5.4] Shader 2  (0) 2021.05.04
[5.4] Ambient Occlusion  (0) 2021.05.04
Comments