ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [유니티 쉐이더 스타트업] 색상을 출력해보기
    프로그래밍/Unity Shader 2019. 5. 3. 19:29

    저번 시간에 Properties 영역에서 인터페이스를 어떻게 생성하는지에 대해서 간단하게 알아보았는데요. 오늘은 본격적으로 색상을 출력해보고 연산해보는 시간을 가져보도록 하겠습니다. 그리고 잠깐 다른 이야기를 하자면, 원래 블로그에 글을 적을 때는 "~했다.", "~같다." 식의 말투로 글을 작성했는데 너무 딱딱한 것 같기도 하고, 특히 정보를 제공하는데 있어선 적합하지 않은 듯 해서 좀 바꿔보려고 합니다. 어떤 말투던 간에 익숙해지면 괜찮겠지요.

    https://zerodeg.tistory.com/30

     

    [Unity Shader]Shader Properties 제작해보기

    Unity Ver : 2019.1.0.f2 Personal Shader "Custom/NewSurfaceShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)..

    zerodeg.tistory.com

    먼저 저번 글을 읽지 않으신 분이 있다면 위의 글을 먼저 읽고 오시는 것을 추천해드리겠습니다^^

    Shader "Custom/NewSurfaceShader"
    {
        //1번
        Properties
        {
    
            _Color ("Color", Color) = (1,1,1,1)
            _MainTex ("Albedo (RGB)", 2D) = "white" {}
    		_Glossiness("Smoothness", Range(0,1)) = 0.5
    		_Metallic("Metallic", Range(0,1)) = 0.0
    
        }
        //2번
        SubShader
        {
            Tags { "RenderType"="Opaque" }
            LOD 200
    		
            //3번
            CGPROGRAM
            // Physically based Standard lighting model, and enable shadows on all light types
            #pragma surface surf Standard fullforwardshadows
    
            // Use shader model 3.0 target, to get nicer looking lighting
            #pragma target 3.0
    
            sampler2D _MainTex;
    
            struct Input
            {
                float2 uv_MainTex;
            };
    
            half _Glossiness;
            half _Metallic;
            fixed4 _Color;
    
            // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
            // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
            // #pragma instancing_options assumeuniformscaling
            UNITY_INSTANCING_BUFFER_START(Props)
                // put more per-instance properties here
            UNITY_INSTANCING_BUFFER_END(Props)
    
            void surf (Input IN, inout SurfaceOutputStandard o)
            {
                // Albedo comes from a texture tinted by color
                fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
                o.Albedo = c.rgb;
                // Metallic and smoothness come from slider variables
                o.Metallic = _Metallic;
                o.Smoothness = _Glossiness;
                o.Alpha = c.a;
            }
            ENDCG
        }
        FallBack "Diffuse"
    }
    

    오늘 우리가 해볼 영역은 위 코드에서 주석처리 해놓은 곳중 3번 영역인데요. CGPROGRAM ~ ENDCG 이라고 적혀 있는 곳은 쉐이더 언어로 작성되고 있다는 뜻입니다. 그럼 다시 3번을 3개의 단락으로 쪼개어 정리해보겠습니다.

            // Physically based Standard lighting model, and enable shadows on all light types
            #pragma surface surf Standard fullforwardshadows
    
            // Use shader model 3.0 target, to get nicer looking lighting
            #pragma target 3.0

    먼저 설정 부분입니다. 전처리라고 할수도 있고 스니핏(snippet)이라고 부르기도 한다고 합니다. 쉐이더의 조명계산 설정, 기타 세부적인 분기를 정해주는 부분입니다.

            struct Input
            {
                float2 uv_MainTex;
            };

    Input 이라는 이름을 가진 '구조체(structure)'입니다. 이 구조체 안에는 엔진으로부터 받아와야할 데이터들이 들어간다고 합니다. 

            void surf (Input IN, inout SurfaceOutputStandard o)
            {
                // Albedo comes from a texture tinted by color
                fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
                o.Albedo = c.rgb;
                // Metallic and smoothness come from slider variables
                o.Metallic = _Metallic;
                o.Smoothness = _Glossiness;
                o.Alpha = c.a;
            }

    surf 라는 이름을 가진 함수 영역입니다. 색상이나 이미지가 출력되는 부분을 만들 수 있습니다. surf 함수의 매개변수를 보면 inout SurfaceOutputStandard o 라는 녀석이 있는데, 쉽게 이야기하면 쉐이더의 여러가지 변경할 수 있는 속성들을 모아놓은 구조체라고 생각하면 된다고 합니다. 오늘은 색상을 변경하기 위해서 Albedo와 Emission 만을 사용해보도록 하겠습니다. 먼저 헷갈릴 수 있으니 fixde4 c = ... 이부분 아래에 있는 코드를 아래와 같이 모두 지워주시구요. Albedo 색상을 빨간색으로 변경해보고, 유니티에서 확인해보도록 하겠습니다.

            void surf (Input IN, inout SurfaceOutputStandard o)
            {
                // Albedo comes from a texture tinted by color
                fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
                o.Albedo = float3(1,0,0);
            }

    float3

     

    알베도 색상을 변경하니 빨간색으로 구체가 변경된 것을 확인할 수 있습니다. 그런데 빛의 영향을 받아서 빛을 받는 쪽은 밝고 빛을 받지 않는 쪽은 어둡게 보이네요. 여기서 우리가 신경써줘야 하는 부분은 ambient color와 reflection 입니다. 즉, 반사와 주변광인데요. 빛에 직접 반사되어 생기는 색과, 주변에서 난반사되어 부딫히는 주변광에 의해 물체의 색이 영향을 받고 있는 것이지요. 이번엔 이 반사와 주변광 설정을 꺼보겠습니다. 먼저 쉐이더 스크립트 CGPROGRAM 바로 다음 구문을 다음과 같이 수정해주세요.

     

    CGPROGRAM
            // Physically based Standard lighting model, and enable shadows on all light types
            #pragma surface surf Standard fullforwardshadows noambient
    
            // Use shader model 3.0 target, to get nicer looking lighting
            #pragma target 3.0

    noambient 라는 단어만 추가해주시면 ambient color가 off 됩니다. 다음은 유니티에서 다음과 같이 Lighting Settings에 들어가줍니다.

    Lighting Settings

    그리고 Lighting 설정창에서 다음과 같이 Environment Reflections 에서 Source를 Custom으로 변경해줍니다.

    그리고 마지막으로 스크립트에서 Albedo를 Albedo에서 Emission으로 변경해주고 다시 유니티에서 물체를 확인해보겠습니다.

            void surf (Input IN, inout SurfaceOutputStandard o)
            {
                // Albedo comes from a texture tinted by color
                fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
                o.Emission = float3(1, 0, 0);
                // Metallic and smoothness come from slider variables
                //o.Metallic = _Metallic;
                //o.Smoothness = _Glossiness;
                //o.Alpha = c.a;
            }

    Emission은 조명 연산을 따로 받지 않아서 조명과는 상관 없는 순수한 색상만이 출력되게 해줍니다. 3ds Max를 써본적은 없지만 책에서 본 바로는 셀프 일루미네이션(Self-illumination)이라고 부르는 자기 발광 기능과 동일하다고 합니다. 조명 연산을 받지 않기 때문에 순수한 결과물을 보고 싶을 때는 이 값을 사용하면 된다고 적혀있네요. 오늘은 유니티 쉐이더에서 색상을 어떻게 변경하는지에 대해서 알아보았습니다. 색상을 연산하는 예제는 내용이 길어져서 다음 포스팅으로 미뤄야 할 것 같네요^^

     

     

     

    댓글

Designed by Tistory.