Referencia del Shader
Ejemplos del Surface Shader

Writing Surface Shaders

Escribir sombreadores que interactuén con la iluminación es complejo. Hay diferentes tipos de luces, diferentes opciones de sombras, diferentes Rendering Paths (renderizado forward y deferred), y el sombreador de alguna manera debería manejar toda esa complejidad.

Surface Shaders in Unity is a code generation approach that makes it much easier to write lit shaders than using low level vertex/pixel shader programs. Note that there are no custom languages, magic or ninjas involved in Surface Shaders; it just generates all the repetitive code that would have to be written by hand. You still write shader code in Cg / HLSL.

For some examples, take a look at Surface Shader Examples and Surface Shader Custom Lighting Examples.

How it works

Usted define una “surface function” que toma cualquier UVs o información que necesita como input, y llena en la estructura output SurfaceOutput. El SurfaceOutput básicmaente describe las propiedades de la superficie (su color albedo, normal, emisión, especularidad etc.) Usted escribe este código en Cg / HLSL.

El compilador del Surface Shader luego averigua qué inputs son necesitados, qué outputs son llenados y así, y genera vertex&pixel shaders actuales, al igual que el renderizado pasa a manejar renderizado forward y deferred.

La estructura estándar del output del surface shaders es así:

struct SurfaceOutput
{
    fixed3 Albedo;  // diffuse color
    fixed3 Normal;  // tangent space normal, if written
    fixed3 Emission;
    half Specular;  // specular power in 0..1 range
    fixed Gloss;    // specular intensity
    fixed Alpha;    // alpha for transparencies
};

In Unity 5, surface shaders can also use physically based lighting models. Built-in Standard and StandardSpecular lighting models (see below) use these output structures respectively:

struct SurfaceOutputStandard
{
    fixed3 Albedo;      // base (diffuse or specular) color
    fixed3 Normal;      // tangent space normal, if written
    half3 Emission;
    half Metallic;      // 0=non-metal, 1=metal
    half Smoothness;    // 0=rough, 1=smooth
    half Occlusion;     // occlusion (default 1)
    fixed Alpha;        // alpha for transparencies
};
struct SurfaceOutputStandardSpecular
{
    fixed3 Albedo;      // diffuse color
    fixed3 Specular;    // specular color
    fixed3 Normal;      // tangent space normal, if written
    half3 Emission;
    half Smoothness;    // 0=rough, 1=smooth
    half Occlusion;     // occlusion (default 1)
    fixed Alpha;        // alpha for transparencies
};

Samples

See Surface Shader Examples, Surface Shader Custom Lighting Examples and Surface Shader Tessellation pages.

Surface Shader compile directives

El Surface Shader es colocado dentro del bloque CGPROGRAM..ENDCG, justo como cualquier otro sombreador. Las diferencias son:

  • Debe ser colocado dentro del bloque SubShader, no dentro de Pass. El Surface shader compilará en múltiples pases en sí.
  • Utiliza la directiva #pragma surface ... para indicar su sombreador de superficie.

La directiva del #pragma surface es:

#pragma surface surfaceFunction lightModel [optionalparams]
  • surfaceFunction - qué función Cg tiene el código surface shader. La función debería tener la forma de void surf (Input IN, inout SurfaceOutput o), dónde Input es una estructura que usted tiene definida. Input debería contener cualquier coordenada de textura y variables extras automáticas necesitadas por la función de superficie.
  • lightModel - lighting model to use. Built-in ones are physically based Standard and StandardSpecular, as well as simple non-physically based Lambert (diffuse) and BlinnPhong (specular). See Custom Lighting Models page for how to write your own.
    • Standard lighting model uses SurfaceOutputStandard output struct, and matches the Standard (metallic workflow) shader in Unity.
    • StandardSpecular lighting model uses SurfaceOutputStandardSpecular output struct, and matches the Standard (specular setup) shader in Unity.
    • Lambert and BlinnPhong lighting models are not physically based (coming from Unity 4.x), but the shaders using them can be faster to render on low-end hardware.

Optional parameters

Transparency and alpha testing is controlled by alpha and alphatest directives. Transparency can typically be of two kinds: traditional alpha blending (used for fading objects out) or more physically plausible “premultiplied blending” (which allows semitransparent surfaces to retain proper specular reflections). Enabling semitransparency makes the generated surface shader code contain blending commands; whereas enabling alpha cutout will do a fragment discard in the generated pixel shader, based on the given variable.

  • alpha or alpha:auto - Will pick fade-transparency (same as alpha:fade) for simple lighting functions, and premultiplied transparency (same as alpha:premul) for physically based lighting functions.
  • alpha:blend - Enable alpha blending.
  • alpha:fade - Enable traditional fade-transparency.
  • alpha:premul - Enable premultiplied alpha transparency.
  • alphatest:VariableName - Enable alpha cutout transparency. Cutoff value is in a float variable with VariableName. You’ll likely also want to use addshadow directive to generate proper shadow caster pass.
  • keepalpha - By default opaque surface shaders write 1.0 (white) into alpha channel, no matter what’s output in the Alpha of output struct or what’s returned by the lighting function. Using this option allows keeping lighting function’s alpha value even for opaque surface shaders.
  • decal:add - Additive decal shader (e.g. terrain AddPass). This is meant for objects that lie atop of other surfaces, and use additive blending. See Surface Shader Examples
  • decal:blend - Semitransparent decal shader. This is meant for objects that lie atop of other surfaces, and use alpha blending. See Surface Shader Examples

Custom modifier functions can be used to alter or compute incoming vertex data, or to alter final computed fragment color.

  • vertex:VertexFunction - Custom vertex modification function. This function is invoked at start of generated vertex shader, and can modify or compute per-vertex data. See Surface Shader Examples.
  • finalcolor:ColorFunction - Función final color modification personalizada. Vea Surface Shader Examples.
  • finalgbuffer:ColorFunction - Custom deferred path for altering gbuffer content.
  • finalprepass:ColorFunction - Custom prepass base path.

Shadows and Tessellation - additional directives can be given to control how shadows and tessellation is handled.

  • addshadow - Generate a shadow caster pass. Commonly used with custom vertex modification, so that shadow casting also gets any procedural vertex animation. Often shaders don’t need any special shadows handling, as they can just use shadow caster pass from their fallback.
  • fullforwardshadows - Support all light shadow types in Forward rendering path. By default shaders only support shadows from one directional light in forward rendering (to save on internal shader variant count). If you need point or spot light shadows in forward rendering, use this directive.
  • tessellate:TessFunction - utiliza teselación DX11 GPU; la función computa factores de teselación. Vea Surface Shader Tessellation para más detalles.

Code generation options - by default generated surface shader code tries to handle all possible lighting/shadowing/lightmap scenarios. However in some cases you know you won’t need some of them, and it is possible to adjust generated code to skip them. This can result in smaller shaders that are faster to load.

  • exclude_path:deferred, exclude_path:forward, exclude_path:prepass - Do not generate passes for given rendering path (Deferred Shading, Forward and Legacy Deferred respectively).
  • noshadow - Disables all shadow receiving support in this shader.
  • noambient - Do not apply any ambient lighting or light probes.
  • novertexlights - Do not apply any light probes or per-vertex lights in Forward rendering.
  • nolightmap - Disables all lightmapping support in this shader.
  • nodynlightmap - Disables runtime dynamic global illumination support in this shader.
  • nodirlightmap - Disables directional lightmaps support in this shader.
  • nofog - Disables all built-in Fog support.
  • nometa - Does not generate a “meta” pass (that’s used by lightmapping & dynamic global illumination to extract surface information).
  • noforwardadd - Deshabilita Forward rendering additive pass. Esto hace que sombreador soporte una completa directional light, con todas las otras luces computadas per-vertex/SH. Hace el sombreador más pequeño también.

Miscellaneous options

  • softvegetation - Hace que el surface shader solo se renderize cuándo Soft Vegetation está prendido.
  • interpolateview - Compute view direction in the vertex shader and interpolate it; instead of computing it in the pixel shader. This can make the pixel shader faster, but uses up one more texture interpolator.
  • halfasview - Pasa el vector half-direction a la función de iluminación en vez de view-direction. Half-direction va a ser computada y normalizada por vértice. Esto es más rápido pero no enteramente correcto.
  • approxview - Removed in Unity 5.0. Use interpolateview instead.
  • dualforward - Use dual lightmaps in forward rendering path.

To see what exactly is different from using different options above, it can be helpful to use “Show Generated Code” button in the Shader Inspector.

Surface Shader input structure

La estructura de input Input generalmente tiene las coordenadas de textura necesitadas por este sombreador. Las coordenadas de textura deben ser nombradas “uv” seguido por el nombre de una textura (o comenzar con “uv2” para usar el segundo conjunto de coordenadas de textura).

Valores adicionales que pueden ser colocados en la estructura Input:

  • float3 viewDir - va a contener view direction, para computar efectos Parallax, la iluminación de los bordes etc.
  • float4 con semántica COLOR - va a contener el color interpolado por vértice.
  • float4 screenPos - will contain screen space position for reflection or screenspace effects.
  • float3 worldPos - va a contener la posición del espacio del mundo.
  • float3 worldRefl - va a contener el vector de reflexión del mundo si el surface shader no escribe a o.Normal. Vea el sombreador Reflect-Diffuse para ejemplo.
  • float3 worldNormal - va a contener el vector normal del mundo(world normal vector) si el surface shader no escribe a o.Normal.
  • float3 worldRefl; INTERNAL_DATA - va a contener el vector de reflexión del mundo(world reflection vector) si el surface shader escribe a o.Normal. Para obtener el vector de reflexión (reflection vector) basado en un normal map por-píxel, utilice WorldReflectionVector (IN, o.Normal). Vea el sombreador Reflect-Bumped para el ejemplo.
  • float3 worldNormal; INTERNAL_DATA - va a contener el vector normal del mundo (world normal vector) si el surface shader escribe a o.Normal. Para obtener el vector de la normal (normal vector) basado en un normal map por-píxel, utilice WorldNormalVector (IN, o.Normal).

Surface shaders and DirectX 11 HLSL syntax

Currently some parts of surface shader compilation pipeline do not understand DirectX 11-specific HLSL syntax, so if you’re using HLSL features like StructuredBuffers, RWTextures and other non-DX9 syntax, you have to wrap it into a DX11-only preprocessor macro.

See Platform Specific Differences and Shading Language pages for details.

Required parameters

Referencia del Shader
Ejemplos del Surface Shader