Unity 2018 Shaders and Effects Cookbook
eBook - ePub

Unity 2018 Shaders and Effects Cookbook

Transform your game into a visually stunning masterpiece with over 70 recipes, 3rd Edition

John P. Doran, Alan Zucconi

Compartir libro
  1. 392 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Unity 2018 Shaders and Effects Cookbook

Transform your game into a visually stunning masterpiece with over 70 recipes, 3rd Edition

John P. Doran, Alan Zucconi

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Bring realism to your games by mastering post-processing effects and advanced shading techniques in Unity 2018

Key Features

  • Learn the secrets of creating AAA quality shaders without writing long algorithms
  • Master shader programming through easy-to-follow examples
  • Create stunning visual effects that can be used in 3D games

Book Description

Since their introduction to Unity, shaders have been seen as notoriously difficult to understand and implement in games. Complex mathematics has always stood in the way of creating your own shaders and attaining the level of realism you crave.

Unity 2018 Shaders and Effects Cookbook changes that by giving you a recipe-based guide to creating shaders using Unity. It will show you everything you need to know about vectors, how lighting is constructed with them, and how textures are used to create complex effects without the heavy math.

This book starts by teaching you how to use shaders without writing code with the post-processing stack. Then, you'll learn how to write shaders from scratch, build up essential lighting, and finish by creating stunning screen effects just like those in high-quality 3D and mobile games. You'll discover techniques, such as normal mapping, image-based lighting, and animating your models inside a shader. We'll explore how to use physically based rendering to treat light the way it behaves in the real world. At the end, we'll even look at Unity 2018's new Shader Graph system.

With this book, what seems like a dark art today will be second nature by tomorrow.

What you will learn

  • Understand physically based rendering to fit the aesthetic of your game
  • Write shaders from scratch in ShaderLab and HLSL/Cg
  • Combine shader programming with interactive scripts to add life to your materials
  • Design efficient shaders for mobile platforms without sacrificing their realism
  • Use state-of-the-art techniques, such as volumetric explosions and fur shading
  • Master the math and algorithms behind the most used lighting models
  • Understand how shader models have evolved and how you can create your own

Who this book is for

Unity Shaders and Effects Cookbook is for developers who want to create their first shaders in Unity 2018 or wish to take their game to a whole new level by adding professional post-processing effects. A solid understanding of Unity is required to get the most from this book.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Unity 2018 Shaders and Effects Cookbook un PDF/ePUB en línea?
Sí, puedes acceder a Unity 2018 Shaders and Effects Cookbook de John P. Doran, Alan Zucconi en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming Games. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781788390958
Edición
3

Surface Shaders and Texture Mapping

In this chapter, we will explore the topic of Surface Shaders in greater detail than in the previous chapter. We will start from building a very simple matte material and end with holographic projections and the advanced blending of terrains. We will also see how you can use textures to animate, blend, and drive any other property that they like.
In this chapter, you will learn about the following methods:
  • Diffuse shading
  • Accessing and modifying packed arrays
  • Adding a texture to a shader
  • Scrolling textures by modifying UV values
  • Creating a shader with normal mapping
  • Creating a transparent material
  • Creating a Holographic Shader
  • Packing and blending textures
  • Creating a circle around your terrain

Introduction

Surface Shaders were introduced in Chapter 2, Creating Your First Shader, as the main type of shader that's used in Unity. This chapter will show you in detail what these actually are and how they work. Generally speaking, there are two essential steps in every Surface Shader. First, you have to specify certain physical properties of the material that you want to describe, such as its diffuse color, smoothness, and transparency. These properties are initialized in a function called the surface function and are stored in a structure called the SurfaceOutput. Secondly, the SurfaceOutput is passed to a lighting model. This is a special function that will also take information about the nearby lights in the scene. Both of these parameters are then used to calculate the final color for each pixel of your model. The lighting function is where the real calculations of a shader take place as it's the piece of code that determines how light should behave when it touches a material.
The following diagram loosely summarizes how a Surface Shader works. Custom lighting models will be explored in Chapter 4, Understanding Lighting Models, while Chapter 6, Vertex Functions, will focus on vertex modifiers:

Diffuse shading

Before starting our journey into texture mapping, it is important to understand how diffuse materials work. Certain objects might have a uniform color and smooth surface, but are not smooth enough to shine in reflected light. These matte materials are best represented with a Diffuse Shader. While, in the real world pure diffuse materials do not exist, Diffuse Shaders are relatively cheap to implement and are largely applied in games with low-poly aesthetics, so they're worth learning about.
There are several ways in which you can create your own Diffuse Shader. A quick way is to start with Unity's Standard Surface Shader and edit it to remove any additional texture information.

Getting ready

Before starting this recipe, you should have created a Standard Surface Shader with the name SimpleDiffuse. For instructions on creating a Standard Surface Shader, look at the Creating a basic Standard Surface Shader recipe located in Chapter 2, Creating Your First Shader, if you haven't done so already.

How to do it...

Open up the SimpleDiffuse shader you've created and make the following changes:
  1. In the Properties section, remove all of the variables except for _Color:
 Properties 
{
_Color ("Color", Color) = (1,1,1,1)
}
  1. From the SubShader{} section, remove the _MainTex, _Glossiness, and _Metallic variables. You should not remove the reference to uv_MainTex as Cg does not allow the Input struct to be empty. The value will simply be ignored.
  2. Also, remove the UNITY_INSTANCING_BUFFER_START/END macros and the comments used with them.
  1. Remove the content of the surf() function and replace it with the following:
void surf (Input IN, inout SurfaceOutputStandard o) 
{
o.Albedo = _Color.rgb;
}
  1. Your shader should look as follows:
Shader "CookbookShaders/Chapter03/SimpleDiffuse" {
Properties
{
_Color ("Color", Color) = (1,1,1,1)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200

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


struct Input
{
float2 uv_MainTex;
};

fixed4 _Color;

void surf (Input IN, inout SurfaceOutputStandard o)
{
o.Albedo = _Color.rgb;
}

ENDCG
}
FallBack "Diffuse"
}
The two lines below CGPROGRAM is actually one line and is cut off due to the size of the book.
  1. As this shader has been refitted with a Standard Shader, it will use physically-based rendering to simulate how light behaves on your models.
If you are trying to achieve a non-photorealistic look, you can change the first #pragma directive so that it uses Lambert rather than Standard. If you do so, you should also replace the SurfaceOutputStandard parameter of the surf function with SurfaceOutput. For more information on this and the other lighting models that Unity supports, Jordan Stevens put together a very nice article about it, which you can see here: http://www.jordanstevenstechart.com/lighting-models
  1. Save the shader and dive back into Unity. Using the same instructions as in the Creating a basic Standard Surface Shader recipe located in Chapter 2, Creating Your First Shader, create a new material called SimpleDiffuseMat and apply our newly created shader to it. Change the color to something different, such as red, by clicking on the window next to the Color property in the Inspector window while selected.
  2. Then, go into the Models folder of this book's example code and bring the bunny object into our scene by dragging and dropping it from the Project window into the Hierarchy window. From there, assign the SimpleDiffuseMat material to the object:
  1. You can double-click on an object in the Hierarchy tab in order to center the camera on the object that's been selected.

How it works...

The way shaders allow you to communicate the rendering properties of your material to their lighting model is via their SurfaceOutput. It is basically a wrapper around all the parameters that the cur...

Índice