Book Image

Unity 4 Game Development HOTSHOT

By : Jate Wittayabundit
Book Image

Unity 4 Game Development HOTSHOT

By: Jate Wittayabundit

Overview of this book

<p>Immerse yourself in the world of high-end game design by partaking in challenging missions. Start off by working with the Sprite Mode, then learn the basics of creating a UI system for an RPG, and work your way through the game virtually embodying your greatest hero or heroine.</p> <p>Every project is designed to push your Unity skills to the limit and beyond. You will start by creating a 2D platform game with the new 2D sprite feature and move on to the Unity GUI system. Then, you will create a 3D character and make it move. By the end of this book, you will know how to post the player's score to the hi-score board.</p>
Table of Contents (19 chapters)
Unity 4 Game Development HOTSHOT
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Surface shaders


To use the surface shaders, you need to define a surface function (void surf(Input IN, inout SurfaceOutput o)) that takes any UVs or data you need as an input and fills in the output structure, SurfaceOutput. SurfaceOutput, which basically describes the properties of the surface (its albedo color, normal, emission, specularity, and so on). Then, you write this code in Cg/HLSL.

The surface shaders' compiler then figures out what inputs are needed, what outputs are filled, and so on and generates actual vertex and pixel shaders as well as rendering passes to handle forward and deferred rendering.

The surface shaders placed inside the CGPROGRAM...ENDCG block are to be placed inside the SubShader block, and it uses the #pragma surface ... directive to indicate that it's a surface shader. You will see that the surface shaders are placed inside the CGPROGRAM and ENDCG blocks in the following example:

Shader "My Lambert" {
    Properties {
      _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader {
      Tags { "RenderType"="Opaque" }
      LOD 200 //Optional that allows the script to turned the shaderon or off when the player's hardware didn't support your shader.
      CGPROGRAM
      #pragma surface surf Lambert
      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;
      }
      ENDCG
  }
    FallBack "Diffuse"
}

#pragma surface

The #pragma surface directive is used as follows:

#pragma surface surfaceFunction lightModel [optionalparams]

The required parameters to use this directive are as follows:

  • surfaceFunction: This is used to define which Cg function has the surface shader code. The function should have the form of void surf (Input IN, inout SurfaceOutput o), where Input is a structure you have defined. Input should contain any texture coordinates and extra automatic variables needed by surface function.

  • lightModel: This is used to define a lighting model to be used. The built-in models are Lambert (diffuse) and BlinnPhong (specular). You can also write your own lighting model using the following custom lighting models:

    • half4 LightingName (SurfaceOutput s, half3 lightDir, half atten);: This is used in forward rendering the path for light models that are not view-direction dependent (for example, diffuse)

    • half4 LightingName (SurfaceOutput s, half3 lightDir, half3 viewDir, half atten);: This is used in forward rendering path for light models that are view-direction dependent

    • half4 LightingName_PrePass (SurfaceOutput s, half4 light);: This is used in the deferred lighting path.

Tip

Note that you don't need to declare all functions. A lighting model either uses view direction or it does not. Similarly, if the lighting model does not work in deferred lighting, you just do not declare the _PrePass function, and all shaders that use it will compile to forward rendering only, such as the shader that we created in Project 3, Shade Your Hero/Heroine. We don't need the _PrePass function because our shader needs the view direction (viewDir) and the light direction (lightDir) for our custom lighting function to calculate the ramp effect for the cartoon style shader (toon shader / cel shader), which is only available in forward rendering.

Optional parameters [optionalparams] to use #pragma surface are listed in the following table:

Type

Description

alpha

This is the alpha blending mode. This is used for semitransparent shaders.

alphatest:VariableName

This is the alpha testing mode. This is used for transparent-cutout shaders. The cut-off value is in the float variable with VariableName.

vertex:VertexFunction

This is the custom vertex modification function. See tree bark shader, for example.

exclude_path:prepass or exclude_path:forward

This does not generate passes for the given rendering path.

addshadow

This adds shadow caster and collector passes. This is commonly used with custom vertex modification so that shadow casting also gets a procedural vertex animation.

dualforward

This uses dual lightmaps in the forward path.

fullforwardshadows

This supports all shadow types in the forward rendering path.

decal:add

This is an additive decal shader (for example, terrain AddPass).

decal:blend

This is a semitransparent decal shader.

softvegetation

This makes the surface shader render only when soft vegetation is on.

Noambient

This does not apply any ambient lighting or spherical harmonic lights.

novertexlights

This does not apply any spherical harmonics or per-vertex lights in forward rendering.

nolightmap

This disables lightmap support in this shader (makes a shader smaller).

Noforwardadd

This disables forward rendering of an additive pass. This makes the shader support one full directional light, with all other lights computed per vertex/SH. This makes shaders smaller as well.

approxview

This computes normalized view direction per vertex instead of per pixel for shaders that need it. This is faster, but view direction is not entirely correct when the camera gets close to the surface.

halfasview

This passes a half-direction vector into the lighting function instead of view direction. Half direction will be computed and normalized per vertex. This is faster, but not entirely correct.

Additionally, you can write #pragma debug inside the CGPROGRAM block, and then the surface compiler will spit out a lot of comments of the generated code. You can view them using an open compiled shader in the Shader inspector.

Surface shaders input structure

The input structure, Input, generally has any texture coordinates needed by the shader. texture coordinates and must be named uv followed by a texture name (or start it with uv2 to use the second texture coordinate set).

An example of surface shader input structure is as follows:

Properties {
    _MainTex ("Texture", 2D) = "white" {}
}
……
    sampler2D _MainTex;
……
    struct Input {
         float2 uv_MainTex;
    };

We can also have additional values that can be put into the Input structure, as mentioned in the following table:

Type

Description

float3 viewDir

This will contain the view direction to compute Parallax effects, rim lighting, and so on.

float4 with COLOR semantic

This will contain an interpolated per-vertex color.

float4 screenPos

This will contain the screen space position for reflection effects. This is used by the WetStreet shader in Dark Unity, for example.

float3 worldPos

This will contain the world space position.

float3 worldRefl

This will contain the world reflection vector if the surface shader does not write to o.Normal. See the Reflect-Diffuse shader, for example.

float3 worldNormal

This will contain the world normal vector if the surface shader does not write to o.Normal.

float3 worldRefl; INTERNAL_DATA

This will contain the world reflection vector if the surface shader writes to o.Normal. To get the reflection vector based on per-pixel normal map, use WorldReflectionVector (IN, o.Normal). See the Reflect-Bumped shader for example.

float3 worldNormal; INTERNAL_DATA

This will contain the world normal vector if the surface shader writes to o.Normal. To get the normal vector based on per-pixel normal map, use WorldNormalVector (IN, o.Normal).

The SurfaceOutput structure

A standard output structure of surface shaders is as follows:

struct SurfaceOutput {     
    fixed3 Albedo;     
    fixed3 Normal;     
    fixed3 Emission;     
    half Specular;     
    fixed Gloss;     
    fixed Alpha; 
};

You can also find it in the Lighting.cginc file inside Unity (unity install path}/Data/CGIncludes/Lighting.cginc in Windows and /Applications/Unity/Unity.app/Contents/CGIncludes/Lighting.cginc in Mac).