unity 之 Shader语法一

Shader Reference

在Unity中内置的渲染管道中的着色器是这样写的:

  • 表面着色器
  • 顶点和片段着色器
  • 固定功能着色器
     

无论何种类型,着色器代码总是由ShaderLab语言包装,它组织着色器结构. 下面是一个用shaderLab写的框架

Shader "MyShader" {
    Properties {
        _MyTexture ("My Texture", 2D) = "white" { }
        // place other properties here, such as colors or vectors.
    }
    __SubShader__ {
        // place the shader code here for your:
        // - surface shader,
        // - vertex and program shader, or
        // - fixed function shader
    }
    SubShader {
        // a simpler version of the subshader above goes here.
        // this version is for supporting older graphics cards.
    }
}

To learn about shader basics and fixed function shaders, consult the ShaderLab syntax section. For other supported shader types, see either Writing Surface Shaders or Writing vertex and fragment shaders. You can also use post-processing effects with shaders to create full-screen filters and other interesting effects.

See Also

Writing Surface Shaders

编写与灯光交互的着色器是复杂的.它们有不同的 light types, 不同的hadow options, 不同的rendering
paths (forward and deferred rendering), 着色器应该以某种方式处理所有的复杂性。

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

How it works

你定义一个“surface function”,它接受你需要的任何uv或数据作为输入,输出到 SurfaceOutput.

标准的着色器结构如下:

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
};

物理着色器模型,包括metallic 和smoothness

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:表面着色器编译指令

Surface shader 被放在CGPROGRAM..ENDCG 命令块之间,就像其它着色器一样,他们的不同在于:

  • 必须在 SubShader之间, 不在 Pass. 表面着色器将自己编译成多个Pass
  • 它使用#pragma surface…指示它是一个表面着色器。

The #pragma surface directive is:

#pragma surface surfaceFunction lightModel [optionalparams]

Required parameters

  • surfaceFunction - Cg 函数含有的表面着色器代码,这个方法由 void surf (Input IN, inout SurfaceOutput o)组成,  Input 是你自定义的结构体构成,输入应包含任何纹理坐标和额外的自动变量所需的表面函数。
  • lightModel - 使用光照模板,基于Standard and StandardSpecular, 简单的基于Lambert (diffuse) and BlinnPhong (specular). See Custom Lighting Models page for how to write your own.
    • Standard 光照模型使用 SurfaceOutputStandard 结构体, and 匹配 Standard (metallic )属性
    • StandardSpecular光照模型使用SurfaceOutputStandardSpecular 匹配 Standard (specular setup)属性.
    • Lambert and BlinnPhong 不基于物理模型,是unity4.0以前的版本,但是不耗性能

Optional parameters

Transparency and alpha testing 通过 alpha and alphatest 指令控制. 透明度通常有两种: 传统的alpha混合(用于淡出物体) or 更合理的物理“预乘混合”(允许半透明表面保留适当的镜面反射)启用半透明使生成的表面着色器代码包含混合命令;启用alpha cutout将在生成的基于给定变量的像素着色器中执行片段丢弃。

  • alpha or alpha:auto - 简单的光照将选择fade-transparency (和 alpha:fade) , 预乘的透明度(与alpha:premul相同)用于基于物理的照明功能。
  • alpha:blend - 启用 alpha blending.
  • alpha:fade - 启用 traditional fade-transparency.
  • alpha:premul - Enable premultiplied alpha transparency.
  • alphatest:VariableName - 启用alpha剪切透明度. 把裁剪到的值和变量名一起放到一个float里面,你可能还想使用addshadow指令来生成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 - Custom final color modification function. See 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 - use DX11 GPU tessellation; the function computes tessellation factors. See Surface Shader Tessellation for details.

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 - Disables Forward rendering additive pass. This makes the shader support one full directional light, with all other lights computed per-vertex/SH. Makes shaders smaller as well.
  • nolppv - Disables Light Probe Proxy Volume
    support in this shader.
  • noshadowmask - Disables Shadowmask support for this shader (both Shadowmask
    and Distance Shadowmask
    ).

Miscellaneous options

  • softvegetation - Makes the surface shader only be rendered when Soft Vegetation is on.
  • 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 - Pass 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.
  • approxview - Removed in Unity 5.0. Use interpolateview instead.
  • dualforward - Use dual lightmaps in forward rendering path.
  • dithercrossfade - Makes the surface shader support dithering effects. You can then apply this shader to GameObjects
    that use an LOD Group
    component configured for cross-fade transition mode.

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

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

Additional values that can be put into Input structure:

  • float3 viewDir - contains view direction, for computing Parallax effects, rim lighting etc.
  • float4 with COLOR semantic - contains interpolated per-vertex color.
  • float4 screenPos - contains screen space position for reflection or screenspace effects. Note that this is not suitable for GrabPass; you need to compute custom UV yourself using ComputeGrabScreenPos function.
  • float3 worldPos - contains world space position.
  • float3 worldRefl - contains world reflection vector if surface shader does not write to o.Normal. See Reflect-Diffuse shader for example.
  • float3 worldNormal - contains world normal vector if surface shader does not write to o.Normal.
  • float3 worldRefl; INTERNAL_DATA - contains world reflection vector if surface shader writes to o.Normal. To get the reflection vector based on per-pixel normal map
    , use WorldReflectionVector (IN, o.Normal). See Reflect-Bumped shader for example.
  • float3 worldNormal; INTERNAL_DATA - contains world normal vector if surface shader writes to o.Normal. To get the normal vector based on per-pixel normal map, use 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TO_ZRG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值