Built-in shaders in Unity have their LODs set up this way:
Returns a value between the x and y components of input Out Min Max based on the linear interpolation of the value of input In between the x and y components of input In Min Max.
Tags { "TagName1" ="Value1" "TagName2" = "Value2" }
· Always: Always rendered; no lighting is applied.
· ForwardBase: Used in Forwardrendering, ambient, main directional light, vertex/SH lights andlightmaps are applied.
· ForwardAdd: Used in Forwardrendering; additive per-pixel lights are applied, one pass perlight.
· Deferred: Used in DeferredShading; renders g-buffer.
· ShadowCaster: Renders object depth into the shadowmap or a depth texture.
· MotionVectors: Used to calculate per-object motion vectors.
· PrepassBase: Used in legacyDeferred Lighting, renders normals and specular exponent.
· PrepassFinal: Used in legacyDeferred Lighting, renders final color by combining textures,lighting and emission.
· Vertex: Used in legacy VertexLit rendering whenobject is not lightmapped; all vertex lights are applied.
· VertexLMRGBM: Used in legacy VertexLit rendering whenobject is lightmapped; on platforms where lightmap is RGBM encoded (PC &console).
· VertexLM: Used in legacy VertexLit rendering whenobject is lightmapped; on platforms where lightmap is double-LDR encoded(mobile platforms).
· OnlyDirectional: When used in ForwardBase pass type, this flag makes it so thatonly the main directional light and ambient/lightprobe data is passed into theshader. This means that data of non-important lights is not passed into vertex-light or sphericalharmonics shader variables. See Forwardrendering for details.
· SoftVegetation: Render this pass only if Soft Vegetation is on in QualitySettings.
Pass { [Name and Tags] [RenderSetup] }
Cull Back | Front | Off
ZTest (Less | Greater | LEqual | GEqual | Equal| NotEqual | Always)
ZWrite On | Off
Offset OffsetFactor, OffsetUnits
Blend sourceBlendModedestBlendMode
Blend sourceBlendModedestBlendMode, alphaSourceBlendMode alphaDestBlendMode
BlendOp colorOp
BlendOp colorOp,alphaOp
AlphaToMask On | Off
ColorMask RGB | A | 0 | any combination of R,G, B, A
Fixed-function Lighting and Material
Lighting On | Off
Material { MaterialBlock }
SeparateSpecular On |Off
Color Color-value
ColorMaterial AmbientAndDiffuse | Emission
Fixed-function Fog
Fog { Fog Block }
Fixed-function AlphaTest
AlphaTest (Less | Greater | LEqual | GEqual |Equal | NotEqual | Always) CutoffValue
Fixed-function Texture combiners
SetTexture textureProperty { combine options }
· In ForwardRendering, ForwardBase
and ForwardAdd
passes are used.
· In DeferredShading, Deferred
pass is used.
· In legacyDeferred Lighting, PrepassBase
and PrepassFinal
passes are used.
· In legacy VertexLit, Vertex
, VertexLMRGBM
and VertexLM
passes are used.
· In any of the above, to render Shadows or a depth texture, ShadowCaster
pass is used.
ForwardBase
passrenders ambient, lightmaps, main directional light and not important(vertex/SH) lights at once. ForwardAdd
passis used for any additive per-pixel lights; one invocation per objectilluminated by such light is done. See ForwardRendering for details.
If forward rendering is used, but a shader does not have forward-suitablepasses (i.e. neither ForwardBase
nor ForwardAdd
passtypes are present), then that object is rendered just like it would in VertexLit path, see below.
Deferred
passrenders all information needed for lighting (in built-in shaders: diffusecolor, specular color, smoothness, world space normal, emission). It also addslightmaps, reflection probes and ambient lighting into the emission channel.See DeferredShading for details.
PrepassBase
passrenders normals & specular exponent; PrepassFinal
passrenders final color by combining textures, lighting & emissive materialproperties. All regular in-scene lighting is done separately in screen-space.See DeferredLighting for details.
·
· Vertex
pass is used for non-lightmapped objects. All lights arerendered at once, using a fixed function OpenGL/Direct3D lighting model (Blinn-Phong)
· VertexLMRGBM
pass is used for lightmapped objects, when lightmaps are RGBMencoded (PC and consoles). No realtime lighting is applied; pass is expected tocombine textures with a lightmap.
· VertexLMM
pass is used for lightmapped objects, when lightmaps aredouble-LDR encoded (mobile platforms). No realtime lighting is applied; pass isexpected to combine textures with a lightmap.
Deferred Shading isthe rendering path with the most lighting and shadow fidelity, and is bestsuited if you have many realtime lights. It requires a certain level ofhardware support.
Forward is the traditional rendering path. It supports all thetypical Unity graphics features (normal maps, per-pixel lights, shadows etc.).However under default settings, only a small number of the brightest lights arerendered in per-pixel lighting mode. The rest of the lights are calculated atobject vertices or per-object.
Legacy Deferred (light prepass) issimilar to Deferred Shading, just using a different technique with differenttrade-offs. It does not support the Unity 5 physically based standard shader.
Legacy Vertex Lit isthe rendering path with the lowest lighting fidelity and no support forrealtime shadows. It is a subset of Forward rendering path.
Deferred |
Forward |
Legacy Deferred |
Vertex Lit |
|
Features |
||||
Per-pixel lighting (normal maps, light cookies) |
Yes |
Yes |
Yes |
- |
Realtime shadows |
Yes |
With caveats |
Yes |
- |
Reflection Probes |
Yes |
Yes |
- |
- |
Depth&Normals Buffers |
Yes |
Additional render passes |
Yes |
- |
Soft Particles |
Yes |
- |
Yes |
- |
Semitransparent objects |
- |
Yes |
- |
Yes |
Anti-Aliasing |
- |
Yes |
- |
Yes |
Light Culling Masks |
Limited |
Yes |
Limited |
Yes |
Lighting Fidelity |
All per-pixel |
Some per-pixel |
All per-pixel |
All per-vertex |
Performance |
||||
Cost of a per-pixel Light |
Number of pixels it illuminates |
Number of pixels * Number of objects it illuminates |
Number of pixels it illuminates |
- |
Number of times objects are normally rendered |
1 |
Number of per-pixel lights |
2 |
1 |
Overhead for simple scenes |
High |
None |
Medium |
None |
Platform Support |
||||
PC (Windows/Mac) |
Shader Model 3.0+ & MRT |
All |
Shader Model 3.0+ |
All |
Mobile (iOS/Android) |
OpenGL ES 3.0 & MRT, Metal (on devices with A8 or later SoC) |
All |
OpenGL ES 2.0 |
All |
Consoles |
XB1, PS4 |
All |
XB1, PS4, 360 |
- |
RenderType
tagcategorizes shaders into several predefined groups, e.g. is is an opaqueshader, or an alpha-tested shader etc. This is used by ShaderReplacement andin some cases used to produce camera’sdepth texture.
Some shaders (mostly ones that do object-space vertexdeformations) do not work when Draw CallBatching isused – that’s because batching transforms all geometry into world space, so“object space” is lost.
DisableBatching
tagcan be used to incidate that. There are three possible values: “True” (alwaysdisables batching for this shader), “False” (does not disable batching; this isdefault) and “LODFading” (disable batching when LOD fading is active; mostlyused on trees).
If ForceNoShadowCasting
tagis given and has a value of “True”, then an object that is rendered using thissubshader will never cast shadows. This is mostly useful when you are usingshader replacement on transparent objects and you do not wont to inherit ashadow pass from another subshader.
If IgnoreProjector
tagis given and has a value of “True”, then an object that uses this shader willnot be affected by Projectors.This is mostly useful on semitransparent objects, because there is no good wayfor Projectors to affect them.
Set CanUseSpriteAtlas
tagto “False” if the shader is meant for sprites, and will not work when they arepacked into atlases (see SpritePacker).
PreviewType
indicateshow the material inspector preview should display the material. By defaultmaterials are displayed as spheres, but PreviewType can also be set to “Plane”(will display as 2D) or “Skybox” (will display as skybox).
Blend Off
: Turn off blending (this is thedefault)
Blend SrcFactor DstFactor
:Configure and enable blending. The generated color is multiplied by the SrcFactor.The color already on screen is multiplied by DstFactorand the two areadded together.
Blend SrcFactor DstFactor, SrcFactorA DstFactorA
:Same as above, but use different factors for blending the alpha channel.
BlendOp Op
: Instead of adding blendedcolors together, carry out a different operation on them.
BlendOp OpColor, OpAlpha
: Same asabove, but use different blend operation for color (RGB) and alpha (A)channels.
Additionally, you can set upper-rendertarget blending modes.When using multiple render target (MRT) rendering, the regular syntax abovesets up the same blending modes for all render targets. The following syntaxcan set up different blending modes for individual render targets, where N
isthe render target index (0..7). This feature works on most modern APIs/GPUs(DX11/12, GLCore, Metal, PS4):
· Blend N SrcFactorDstFactor
· Blend N SrcFactorDstFactor, SrcFactorA DstFactorA
· BlendOp N Op
· BlendOp N OpColor,OpAlpha
AlphaToMask On
: Turns on alpha-to-coverage.When MSAA is used, alpha-to-coverage modifies multisample coverage maskproportionally to the pixel Shader result alpha value. This is typically usedfor less aliased outlines than regular alpha test; useful for vegetation andother alpha-tested Shaders.
Add |
Add source and destination together. |
Sub |
Subtract destination from source. |
RevSub |
Subtract source from destination. |
Min |
Use the smaller of source and destination. |
Max |
Use the larger of source and destination. |
LogicalClear |
Logical operation: Clear (0) DX11.1 only. |
LogicalSet |
Logical operation: Set (1) DX11.1 only. |
LogicalCopy |
Logical operation: Copy (s) DX11.1 only. |
LogicalCopyInverted |
Logical operation: Copy inverted (!s) DX11.1 only. |
LogicalNoop |
Logical operation: Noop (d) DX11.1 only. |
LogicalInvert |
Logical operation: Invert (!d) DX11.1 only. |
LogicalAnd |
Logical operation: And (s & d) DX11.1 only. |
LogicalNand |
Logical operation: Nand !(s & d) DX11.1 only. |
LogicalOr |
Logical operation: Or (s | d) DX11.1 only. |
LogicalNor |
Logical operation: Nor !(s | d) DX11.1 only. |
LogicalXor |
Logical operation: Xor (s ^ d) DX11.1 only. |
LogicalEquiv |
Logical operation: Equivalence !(s ^ d) DX11.1 only. |
LogicalAndReverse |
Logical operation: Reverse And (s & !d) DX11.1 only. |
LogicalAndInverted |
Logical operation: Inverted And (!s & d) DX11.1 only. |
LogicalOrReverse |
Logical operation: Reverse Or (s | !d) DX11.1 only. |
LogicalOrInverted |
Logical operation: Inverted Or (!s | d) DX11.1 only. |
All following properties are valid for both SrcFactor &DstFactor in the Blend command. Source refers to the calculated color, Destination is the color already on the screen.The blend factors are ignored if BlendOp is using logical operations.
One |
The value of one - use this to let either the source or the destination color come through fully. |
Zero |
The value zero - use this to remove either the source or the destination values. |
SrcColor |
The value of this stage is multiplied by the source color value. |
SrcAlpha |
The value of this stage is multiplied by the source alpha value. |
DstColor |
The value of this stage is multiplied by frame buffer source color value. |
DstAlpha |
The value of this stage is multiplied by frame buffer source alpha value. |
OneMinusSrcColor |
The value of this stage is multiplied by (1 - source color). |
OneMinusSrcAlpha |
The value of this stage is multiplied by (1 - source alpha). |
OneMinusDstColor |
The value of this stage is multiplied by (1 - destination color). |
OneMinusDstAlpha |
The value of this stage is multiplied by (1 - destination alpha). |
Numbers and Sliders
name ("displayname", Range (min, max)) = number
name ("displayname", Float) = number
name ("displayname", Int) = number
Colors and Vectors
name ("displayname", Color) = (number,number,number,number)
name ("displayname", Vector) =(number,number,number,number)
Cg/HLSL can also accept uniform keyword, but it is not necessary:
uniform float4 _MyColor;
Property types in ShaderLab map to Cg/HLSL variable typesthis way:
· Color and Vector properties map to float4, half4 or fixed4 variables.
· Range and Float properties map to float, half or fixed variables.
· Texture properties map to sampler2D variablesfor regular (2D) textures; Cubemaps map to samplerCUBE; and 3Dtextures map to sampler3D.
Texture tiling & offset
Materials oftenhave Tiling and Offset fields for their texture properties. This information ispassed into shaders in a float4 {TextureName}_ST
property:
· x
contains X tiling value
· y
contains Y tiling value
· z
contains X offset value
· w
contains Y offset value
For example, if a shader contains texture named _MainTex
, the tiling information will bein a _MainTex_ST
vector.
Texture size
{TextureName}_TexelSize - a float4property contains texture size information:
· x contains 1.0/width
· y contains 1.0/height
· z contains width
· w contains height
Texture HDR parameters
{TextureName}_HDR
-a float4 property with information on how to decode a potentially HDR (e.g. RGBM-encoded)texture depending on the colorspace used.SeeDecodeHDR
functionin UnityCG.cginc shaderinclude file.
When using Linearcolor space, all material color propertiesare supplied as sRGB colors, but are converted into linear values when passedinto shaders.
For example, if your Properties shaderblock contains a Color
propertycalled “MyColor“, then thecorresponding ”MyColor” HLSL variable will get the linear colorvalue.
For properties that are marked as Float
or Vector
type,no color space conversions are done by default; it is assumed that they containnon-color data. It is possible to add [Gamma]
attributefor float/vector properties to indicate that they are specified in sRGB space,just like colors (see Properties).
Textures
name ("displayname", 2D) = "defaulttexture" {}
name ("displayname", Cube) = "defaulttexture" {}
name ("displayname", 3D) = "defaulttexture" {}
· For Range and Float propertiesit’s just a single number, for example “13.37”.
· For Color and Vector propertiesit’s four numbers in parentheses, for example “(1,0.5,0.2,1)”.
· For 2D Textures, the default value is either an empty string,or one of the built-in default Textures: “white” (RGBA: 1,1,1,1), “black”(RGBA: 0,0,0,0), “gray” (RGBA: 0.5,0.5,0.5,0.5), “bump” (RGBA: 0.5,0.5,1,0.5)or “red” (RGBA: 1,0,0,0).
· For non–2D Textures (Cube, 3D, 2DArray) the default valueis an empty string. When a Material does not have a Cubemap/3D/Array Textureassigned, a gray one (RGBA: 0.5,0.5,0.5,0.5) is used.
· [HideInInspector]
- does not show the property value in the material inspector.
· [NoScaleOffset]
- material inspector will not show texture tiling/offset fieldsfor texture properties with this attribute.
· [Normal]
- indicates that a texture property expects a normal-map.
· [HDR]
- indicates that a texture property expects a high-dynamic range(HDR) texture.
· [Gamma]
- indicates that a float/vector property is specified as sRGBvalue in the UI (just like colors are), and possibly needs conversion accordingto color space used. SeePropertiesin Shader Programs.
· [PerRendererData]
- indicates that a texture property will be coming fromper-renderer data in the form of a MaterialPropertyBlock. Material inspector changes the texture slot UI for theseproperties.
In Unity this can be achieved by adding a #pragma multi_compile
or #pragma shader_feature
directive to a shadersnippet. This works in surfaceshaders too.
#pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON
Will produce two shader variants, one with FANCY_STUFF_OFF
defined, and another with FANCY_STUFF_ON
. At runtime, one of themwill be activated based on the Material or global shader keywords. If neitherof these two keywords are enabled then the first one (“off”) will be used.
There can be more than two keywords on a multi_compile line, forexample this will produce four shader variants:
#pragma multi_compile SIMPLE_SHADING BETTER_SHADINGGOOD_SHADING BEST_SHADING
When any of the names are all underscores, then a shader variantwill be produced, with no preprocessor macro defined. This is commonly used forshaders features, to avoid using up two keywords (see notes on keywork limitbelow). For example, the directive below will produce two shader variants;first one with nothing defined, and second one with FOO_ON
defined:
#pragma multi_compile __ FOO_ON
#pragma shader_feature
isvery similar to #pragmamulti_compile
, the only difference is that unused variantsof shader_feature shaders will not be included into game build. Soshader_feature makes most sense for keywords that will be set on the materials,while multi_compile for keywords that will be set from code globally.
Additionally, it has a shorthand notation with just one keyword:
#pragma shader_feature FANCY_STUFF
Which is just a shortcut for #pragma shader_feature _ FANCY_STUFF
, i.e. it expands into two shader variants (first one withoutthe define; second one with it).
Several multi_compile lines can be provided, and the resultingshader will be compiled for all possible combinations of the lines:
#pragma multi_compile AB C
#pragma multi_compile DE
When using Shader variants, remember that there is a limit of256 keywords in Unity, and around 60 of them are used internally (thereforelowering the available limit). Also, the keywords are enabled globallythroughout a particular Unity project, so be careful not to exceed the limitwhen multiple keywords are defined in several different Shaders.
· multi_compile_fwdbase compiles all variants neededby ForwardBase (forward rendering base) pass type. The variantsdeal with different lightmap types and main directional light having shadows onor off.
· multi_compile_fwdadd compiles variants for ForwardAdd (forwardrendering additive) pass type. This compiles variants to handle directional,spot or point light types, and their variants with cookie textures.
· multi_compile_fwdadd_fullshadows - same as above, but also includesability for the lights to have realtime shadows.
· multi_compile_fog expands to several variants tohandle different fog types (off/linear/exp/exp2).
Most of the built-in shortcuts result in many shader variants.It is possible to skip compiling some of them if you know they are not needed,by using #pragma skip_variants
.For example:
#pragmamulti_compile_fwdadd
// will make allvariants containing
// "POINT" or"POINT_COOKIE" be skipped
#pragma skip_variantsPOINT POINT_COOKIE
UNITY_HARDWARE_TIER1
UNITY_HARDWARE_TIER2
UNITY_HARDWARE_TIER3
The majority of calculations inshaders are carried out on floating-point numbers (which would be float
in regular programming languages like C#). Several variants offloating point types are present: float
, half
and fixed
(as well as vector/matrixvariants of them, such as half3
and float4x4
). These types differ inprecision (and, consequently, performance or power usage):
High precision: float
Highest precision floating point value; generally 32 bits (justlike float
fromregular programming languages).
Full float
precisionis generally used for world space positions, texture coordinates, or scalarcomputations involving complex functions such as trigonometry orpower/exponentiation.
Medium precision: half
Medium precision floating point value; generally 16 bits (rangeof –60000 to +60000, with about 3 decimal digits of precision).
Half precision is useful for short vectors, directions, objectspace positions, high dynamic range colors.
Low precision: fixed
Lowest precision fixed point value. Generally 11 bits, with arange of –2.0 to +2.0 and 1/256th precision.
Fixed precision is useful for regular colors (as typicallystored in regular textures) and performing simple operations on them.
Integer data types
Integers (int
datatype) are often used as loop counters or array indices. For this purpose, theygenerally work fine across various platforms.
Depending on the platform, integer types might not be supportedby the GPU. For example, Direct3D 9 and OpenGL ES 2.0 GPUs only operate onfloating point data, and simple-looking integer expressions (involving bit orlogical operations) might be emulated using fairly complicated floating pointmath instructions.
Direct3D 11, OpenGL ES 3, Metal and other modern platforms haveproper support for integer data types, so using bit shifts and bit maskingworks as expected.
HLSL has built-in vector and matrix types that are created fromthe basic types. For example, float3
isa 3D vector with .x, .y, .z components, and half4
isa medium precision 4D vector with .x, .y, .z, .w components. Alternatively,vectors can be indexed using .r, .g, .b, .a components, which is useful whenworking on colors.
Matrix types are built in a similar way; for example float4x4
isa 4x4 transformation matrix. Note that some platforms only support squarematrices, most notably OpenGL ES 2.0.
Typically you declare textures in your HLSL code as follows:
sampler2D _MainTex;
samplerCUBE _Cubemap;
For mobile platforms, these translate into “low precisionsamplers”, i.e. the textures are expected to have low precision data in them.If you know your texture contains HDR colors, you might want to use halfprecision sampler:
sampler2D_half_MainTex;
samplerCUBE_half_Cubemap;
Or if your texture contains full float precision data (e.g. depthtexture), use a full precision sampler:
sampler2D_float_MainTex;
samplerCUBE_float_Cubemap;
GPU Family |
float |
half |
fixed |
PowerVR Series 6/7 |
32 |
16 |
|
PowerVR SGX 5xx |
32 |
16 |
11 |
Qualcomm Adreno 4xx/3xx |
32 |
16 |
|
Qualcomm Adreno 2xx |
32 vertex 24 fragment |
||
ARM Mali T6xx/7xx |
32 |
16 |
|
ARM Mali 400/450 |
32 vertex 16 fragment |
||
NVIDIA X1 |
32 |
16 |
|
NVIDIA K1 |
32 |
||
NVIDIA Tegra 3/4 |
32 |
16 |
· Direct3D-like: The coordinate is 0 at the top andincreases downward. This applies to Direct3D, Metal and consoles.
· OpenGL-like: The coordinate is 0 at the bottom and increases upward.This applies to OpenGL and OpenGL ES.
· Just GrabPass { } grabs the current screen contents into a texture.The texture can be accessed in further passes by _GrabTexture name.Note: this form of grab pass will do the time-consuming screen grabbingoperation for each object that uses it.
· GrabPass { "TextureName" } grabs thecurrent screen contents into a texture, but will only do that once per framefor the first object that uses the given texture name. The texture can beaccessed in further passes by the given texture name. This is a more performantmethod when you have multiple objects using GrabPass in the scene.
This is approximate "shader capability" level of thegraphics device, expressed in DirectX shader model terms. Possible values are:
50 Shader Model 5.0 (DX11.0)
46 OpenGL 4.1 capabilities (Shader Model4.0 + tessellation)
45 Metal / OpenGL ES 3.1 capabilities(Shader Model 3.5 + compute shaders)
40 Shader Model 4.0 (DX10.0)
35 OpenGL ES 3.0 capabilities (ShaderModel 3.0 + integers, texture arrays, instancing)
30 Shader Model 3.0
25 Shader Model 2.5 (DX11 feature level9.3 feature set)
20 Shader Model 2.0.
· DepthTextureMode.Depth: a depthtexture.
· DepthTextureMode.DepthNormals: depth and view space normals packed into one texture.*
· DepthTextureMode.MotionVectors: per-pixel screen space motion of each screen texel for thecurrent frame. Packed into a RG16 texture.
· Using a geometry shader (#pragma geometry) setcompilation target to 4.0.
· Using tessellation shaders (#pragma hull or #pragma domain) setscompilation target to 4.6.
#pragma target 2.0
· Works on all platforms supported by Unity. DX9 shadermodel 2.0.
· Limited amount of arithmetic & texture instructions;8 interpolators; no vertex texture sampling; no derivatives in fragmentshaders; no explicit LOD texture sampling.
#pragma target 2.5 (default)
· Almost the same as 3.0 target (see below), except stillonly has 8 interpolators, and does not have explicit LOD texture sampling.
· Compiles into SM3.0 on DX9, and DX11 feature level 9.3 onWindows Phone.
#pragma target 3.0
· DX9 shader model 3.0: derivative instructions, textureLOD sampling, 10 interpolators, more math/texture instructions allowed.
· Not supported on DX11 feature level 9.x GPUs (e.g. mostWindows Phone devices).
· Might not be fully supported by some OpenGL ES 2.0 devices,depending on driver extensions present and features used.
#pragma target 3.5 (or es3.0)
· OpenGL ES 3.0 capabilities (DX10 SM4.0 on D3D platforms,just without geometry shaders).
· Not supported on DX9, DX11 9.x (WinPhone), OpenGL ES 2.0.
· Supported on DX11+, OpenGL 3.2+, OpenGL ES 3+, Metal,Vulkan, PS4/XB1 consoles.
· Native integer operations in shaders, texture arrays,etc.
#pragma target 4.0
· DX11 shader model 4.0.
· Not supported on DX9, DX11 9.x (WinPhone), OpenGL ES2.0/3.0/3.1, Metal.
· Supported on DX11+, OpenGL 3.2+, OpenGL ES 3.1+AEP,Vulkan, PS4/XB1 consoles.
· Has geometry shaders and everything that es3.0 targethas.
#pragma target 4.5 (or es3.1)
· OpenGL ES 3.1 capabilities (DX11 SM5.0 on D3D platforms,just without tessellation shaders).
· Not supported on DX9, DX11 before SM5.0, OpenGL before4.3 (i.e. Mac), OpenGL ES 2.0/3.0.
· Supported on DX11+ SM5.0, OpenGL 4.3+, OpenGL ES 3.1,Metal, Vulkan, PS4/XB1 consoles.
· Has compute shaders, random access texture writes,atomics etc. No geometry or tessellation shaders.
#pragma target 4.6 (or gl4.1)
· OpenGL 4.1 capabilities (DX11 SM5.0 on D3D platforms,just without compute shaders). This is basically the highest OpenGL levelsupported by Macs.
· Not supported on DX9, DX11 before SM5.0, OpenGL before4.1, OpenGL ES 2.0/3.0/3.1, Metal.
· Supported on DX11+ SM5.0, OpenGL 4.1+, OpenGL ES 3.1+AEP,PS4/XB1 consoles.
#pragma target 5.0
· DX11 shader model 5.0.
· Not supported on DX9, DX11 before SM5.0, OpenGL before4.3 (i.e. Mac), OpenGL ES 2.0/3.0/3.1, Metal.
· Supported on DX11+ SM5.0, OpenGL 4.3+, OpenGL ES 3.1+AEP,Vulkan, PS4/XB1 consoles.
Property |
Function |
UnityStereoScreenSpaceUVAdjust(uv, sb) |
Parameters: |
UnityStereoTransformScreenSpaceTex(uv) |
Parameters: |
UnityStereoClamp(uv, sb) |
Parameters: |
Additionally, the constant unity_StereoEyeIndex is exposedin Shaders, so eye-dependent calculations can be performed. The value of unity_StereoEyeIndex is 0 forrendering of the left eye, and 1 for rendering of the right eye.
· UNITY_TRANSFER_DEPTH(o): computes eye space depth of the vertexand outputs it in o (which must be a float2). Use it in avertex program when rendering into a depth texture. On platforms with nativedepth textures this macro does nothing at all, because Z buffer value isrendered implicitly.
· UNITY_OUTPUT_DEPTH(i): returns eye space depth from i (whichmust be a float2). Use it in a fragment program when rendering into a depthtexture. On platforms with native depth textures this macro always returnszero, because Z buffer value is rendered implicitly.
· COMPUTE_EYEDEPTH(i): computes eye space depth of the vertexand outputs it in o. Use it in a vertex program when not renderinginto a depth texture.
· DECODE_EYEDEPTH(i)/LinearEyeDepth(i): given highprecision value from depth texture i, returns corresponding eyespace depth.
· Linear01Depth(i): given high precision value from depthtexture i, returns corresponding linear depth in range between 0and 1.
Cg has six basic data types. Some of them arethe same as in C, while others are especially added for GPU programming. Thesetypes are:
· float - a 32bit floating point number
· half - a 16bit floating point number
· int - a 32bit integer
· fixed - a 12bit fixed point number
· bool - a boolean variable
· sampler* - represents a textureobject
SV_TargetN: Multiple render targets
SV_Target1
, SV_Target2
,etc.: These are additional colors written by the shader. This is used whenrendering into more than one render target at once (known as the MultipleRender Targets rendering technique, or MRT). SV_Target0
isthe same as SV_Target
.
SV_Depth: Pixel shader depth output
Usually the fragment shader does not override the Z buffervalue, and a default value is used from the regular triangle rasterization.However, for some effects it is useful to output custom Z buffer depth valuesper pixel.
· TEXCOORD0, TEXCOORD1 etc are used to indicate arbitrary high precisiondata such as texture coordinates and positions.
· COLOR0 and COLOR1 semantics on vertex outputs and fragment inputs arefor low-precision, 0–1 range data (like simple color values).
Interpolator count limits
· Up to 8 interpolators: OpenGL ES 2.0 (iOS/Android), Direct3D11 9.x level (Windows Phone) and Direct3 9 shader model 2.0 (old PCs). Sincethe interpolator count is limited, but each interpolator can be a 4-componentvector, some shaders pack things together to stay within limits. For example,two texture coordinates can be passed in one float4 variable(.xy for one coordinate, .zw for the second coordinate).
· Up to 10 interpolators: Direct3D 9 shader model 3.0 (#pragma target 3.0).
· Up to 16 interpolators: OpenGL ES 3.0 (iOS/Android), Metal(iOS).
· Up to 32 interpolators: Direct3D 10 shader model 4.0 (#pragma target 4.0).
Vertex transformation functions inUnityCG.cginc
float4 UnityObjectToClipPos(float3 pos) |
Transforms a point from object space to the camera’s clip space in homogeneous coordinates. This is the equivalent of mul(UNITY_MATRIX_MVP, float4(pos, 1.0)), and should be used in its place. |
float3 UnityObjectToViewPos(float3 pos) |
Transforms a point from object space to view space. This is the equivalent of mul(UNITY_MATRIX_MV, float4(pos, 1.0)).xyz, and should be used in its place. |
Generic helper functions in UnityCG.cginc
float3 WorldSpaceViewDir (float4 v) |
Returns world space direction (not normalized) from given object space vertex position towards the camera. |
float3 ObjSpaceViewDir (float4 v) |
Returns object space direction (not normalized) from given object space vertex position towards the camera. |
float2 ParallaxOffset (half h, half height, half3 viewDir) |
calculates UV offset for parallax normal mapping. |
fixed Luminance (fixed3 c) |
Converts color to luminance (grayscale). |
fixed3 DecodeLightmap (fixed4 color) |
Decodes color from Unity lightmap (RGBM or dLDR depending on platform). |
float4 EncodeFloatRGBA (float v) |
Encodes [0..1) range float into RGBA color, for storage in low precision render target. |
float DecodeFloatRGBA (float4 enc) |
Decodes RGBA color into a float. |
float2 EncodeFloatRG (float v) |
Encodes [0..1) range float into a float2. |
float DecodeFloatRG (float2 enc) |
Decodes a previously-encoded RG float. |
float2 EncodeViewNormalStereo (float3 n) |
Encodes view space normal into two numbers in 0..1 range. |
float3 DecodeViewNormalStereo (float4 enc4) |
Decodes view space normal from enc4.xy. |
Forward rendering helper functions in UnityCG.cginc
float3 WorldSpaceLightDir (float4 v) |
Computes world space direction (not normalized) to light, given object space vertex position. |
float3 ObjSpaceLightDir (float4 v) |
Computes object space direction (not normalized) to light, given object space vertex position. |
float3 Shade4PointLights (...) |
Computes illumination from four point lights, with light data tightly packed into vectors. Forward rendering uses this to compute per-vertex lighting. |
Screen-space helper functions in UnityCG.cginc
float4 ComputeScreenPos (float4 clipPos) |
Computes texture coordinate for doing a screenspace-mapped texture sample. Input is clip space position. |
float4 ComputeGrabScreenPos (float4 clipPos) |
Computes texture coordinate for sampling a GrabPass texure. Input is clip space position. |
Vertex-lit helper functions in UnityCG.cginc
float3 ShadeVertexLights (float4 vertex, float3 normal)
Computesillumination from four per-vertex lights and ambient, given object spaceposition & normal.
· HLSLSupport.cginc - (automatically included) Helpermacros and definitions for cross-platform shader compilation.
· UnityShaderVariables.cginc - (automatically included) Commonlyused global variables.
· UnityCG.cginc - commonly used helper functions.
· AutoLight.cginc - lighting & shadowing functionality, e.g. surface shaders use this file internally.
· Lighting.cginc - standard surface shader lighting models;automatically included when you’re writing surface shaders.
· TerrainEngine.cginc - helper functions for Terrain& Vegetation shaders.
Data structures in UnityCG.cginc
At the start of the snippet compilation directives can begiven as #pragma statements. Directives indicating whichshader functions to compile:
· #pragma vertex name - compilefunction name as the vertex shader.
· #pragma fragment name - compilefunction name as the fragment shader.
· #pragma geometry name - compilefunction name as DX10 geometry shader. Having this optionautomatically turns on #pragma target 4.0, described below.
· #pragma hull name - compile function name asDX11 hull shader. Having this option automatically turns on #pragmatarget 5.0, described below.
· #pragma domain name - compilefunction name as DX11 domain shader. Having this optionautomatically turns on #pragma target 5.0, described below.
Other compilation directives:
· #pragma target name - which shadertarget to compile to. See Shader Compilation Targets page fordetails.
· #pragma only_renderers space separated names -compile shader only for given renderers. By default shaders are compiled forall renderers. See Renderers below for details.
· #pragma exclude_renderers space separated names -do not compile shader for given renderers. By default shaders are compiled forall renderers. See Renderers below for details.
· #pragma multi_compile … - for working with multiple shader variants.
· #pragma enable_d3d11_debug_symbols - generatedebug information for shaders compiled for DirectX 11, this will allow you todebug shaders via Visual Studio 2012 (or higher) Graphics debugger.
· #pragma hardware_tier_variants renderername - generate multiple shader hardware variants of eachcompiled shader, for each hardware tier that could run the selected renderer.See Renderers below for details.
Each snippet must contain at least a vertex program and afragment program. Thus #pragma vertex and #pragmafragment directives are required.
Compilation directives that don’t do anything startingwith Unity 5.0 and can be safely removed: #pragma glsl, #pragmaglsl_no_auto_normalization, #pragma profileoption, #pragma fragmentoption.
using #pragmaonly_renderers or #pragma exclude_renderers directives.
· d3d9 - Direct3D 9
· d3d11 - Direct3D 11/12
· glcore - OpenGL 3.x/4.x
· gles - OpenGL ES 2.0
· gles3 - OpenGL ES 3.x
· metal - iOS/Mac Metal
· vulkan - Vulkan
· d3d11_9x - Direct3D 11 9.x feature level, as commonly usedon WSA platforms
· xboxone - Xbox One
· ps4 - PlayStation 4
· psp2 - PlayStation Vita
· n3ds - Nintendo 3DS
· wiiu - Nintendo Wii U
#pragma only_renderers d3d9
SHADER_API_D3D9 |
Direct3D 9 |
SHADER_API_D3D11 |
Direct3D 11 |
SHADER_API_GLCORE |
Desktop OpenGL “core” (GL 3/4) |
SHADER_API_GLES |
OpenGL ES 2.0 |
SHADER_API_GLES3 |
OpenGL ES 3.0/3.1 |
SHADER_API_METAL |
iOS/Mac Metal |
SHADER_API_VULKAN |
Vulkan |
SHADER_API_D3D11_9X |
Direct3D 11 “feature level 9.x” target for Universal Windows Platform |
SHADER_API_PS4 |
PlayStation 4. SHADER_API_PSSL is also defined. |
SHADER_API_XBOXONE |
Xbox One |
SHADER_API_PSP2 |
PlayStation Vita |
SHADER_API_WIIU |
Nintendo Wii U |
#if SHADER_TARGET <30
// less than Shader model 3.0:
// very limited Shader capabilities, dosome approximation
#else
// decent capabilities, do a better thing
#endif
#if UNITY_VERSION>= 500
preprocessor check onlypasses on versions 5.0.0 or later.
Preprocessor macros SHADER_STAGE_VERTEX
, SHADER_STAGE_FRAGMENT
, SHADER_STAGE_DOMAIN
, SHADER_STAGE_HULL
, SHADER_STAGE_GEOMETRY
, SHADER_STAGE_COMPUTE
aredefined when compiling each Shader stage. Typically they are useful whensharing Shader code between pixel Shaders and compute Shaders, to handle caseswhere some things have to be done slightly differently.
UNITY_BRANCH |
Add this before conditional statements to tell the compiler that this should be compiled into an actual branch. Expands to [branch] when on HLSL platforms. |
UNITY_FLATTEN |
Add this before conditional statements to tell the compiler that this should be flattened to avoid an actual branch instruction. Expands to [flatten] when on HLSL platforms. |
UNITY_NO_SCREENSPACE_SHADOWS |
Defined on platforms that do not use cascaded screenspace shadowmaps (mobile platforms). |
UNITY_NO_LINEAR_COLORSPACE |
Defined on platforms that do not support Linear color space (mobile platforms). |
UNITY_NO_RGBM |
Defined on platforms where RGBM compression for lightmaps is not used (mobile platforms). |
UNITY_NO_DXT5nm |
Defined on platforms that do not use DXT5nm normal-map compression (mobile platforms). |
UNITY_FRAMEBUFFER_FETCH_AVAILABLE |
Defined on platforms where “framebuffer color fetch” functionality can be available (generally iOS platforms - OpenGL ES 2.0, 3.0 and Metal). |
UNITY_USE_RGBA_FOR_POINT_SHADOWS |
Defined on platforms where point light shadowmaps use RGBA Textures with encoded depth (other platforms use single-channel floating point Textures). |
UNITY_ATTEN_CHANNEL |
Defines which channel of light attenuation Texture contains the data; used in per-pixel lighting code. Defined to either ‘r’ or ‘a’. |
UNITY_HALF_TEXEL_OFFSET |
Defined on platforms that need a half-texel offset adjustment in mapping texels to pixels (e.g. Direct3D 9). |
UNITY_UV_STARTS_AT_TOP |
Always defined with value of 1 or 0. A value of 1 is on platforms where Texture V coordinate is 0 at the “top” of the Texture. Direct3D-like platforms use value of 1; OpenGL-like platforms use value of 0. |
UNITY_MIGHT_NOT_HAVE_DEPTH_Texture |
Defined if a platform might emulate shadow maps or depth Textures by manually rendering depth into a Texture. |
UNITY_PROJ_COORD(a) |
Given a 4-component vector, this returns a Texture coordinate suitable for projected Texture reads. On most platforms this returns the given value directly. |
UNITY_NEAR_CLIP_VALUE |
Defined to the value of near clipping plane. Direct3D-like platforms use 0.0 while OpenGL-like platforms use –1.0. |
UNITY_VPOS_TYPE |
Defines the data type required for pixel position input (VPOS): float2 on D3D9, float4 elsewhere. |
UNITY_CAN_COMPILE_TESSELLATION |
Defined when the Shader compiler “understands” the tessellation Shader HLSL syntax (currently only D3D11). |
UNITY_INITIALIZE_OUTPUT(type,name) |
Initializes the variable name of given type to zero. |
UNITY_COMPILER_HLSL,UNITY_COMPILER_HLSL2GLSL,UNITY_COMPILER_CG |
Indicates which Shader compiler is being used to compile Shaders - respectively: Microsoft’s HLSL, HLSL to GLSL translator, and NVIDIA’s Cg. See documentation on Shading Languages for more details. Use this if you run into very specific Shader syntax handling differences between the compilers, and want to write different code for each compiler. |
· UNITY_REVERSED_Z - defined on plaftorms using reverse Z buffer.Stored Z values are in the range 1..0 instead of 0..1.
UNITY_DECLARE_SHADOWMAP(tex) |
Declares a shadowmap Texture variable with name “tex”. |
UNITY_SAMPLE_SHADOW(tex,uv) |
Samples shadowmap Texture “tex” at given “uv” coordinate (XY components are Texture location, Z component is depth to compare with). Returns single float value with the shadow term in 0..1 range. |
UNITY_SAMPLE_SHADOW_PROJ(tex,uv) |
Similar to above, but does a projective shadowmap read. “uv” is a float4, all other components are divided by .w for doing the lookup. |
Use CBUFFER_START(name) and CBUFFER_END macros forthat:
CBUFFER_START(MyRarelyUpdatedVariables)
float4_SomeGlobalValue;
CBUFFER_END
Macro: |
Use: |
UNITY_DECLARE_TEX2D(name) |
Declares a Texture and Sampler pair. |
UNITY_DECLARE_TEX2D_NOSAMPLER(name) |
Declares a Texture without a Sampler. |
UNITY_DECLARE_TEX2DARRAY(name) |
Declares a Texture array Sampler variable. |
UNITY_SAMPLE_TEX2D(name,uv) |
Sample from a Texture and Sampler pair, using given Texture coordinate. |
UNITY_SAMPLE_TEX2D_SAMPLER( name,samplername,uv) |
Sample from Texture (name), using a Sampler from another Texture (samplername). |
UNITY_SAMPLE_TEX2DARRAY(name,uv) |
Sample from a Texture array with a float3 UV; the z component of the coordinate is array element index. |
UNITY_SAMPLE_TEX2DARRAY_LOD(name,uv,lod) |
Sample from a Texture array with an explicit mipmap level. |
Macro: |
Use: |
UNITY_PASS_FORWARDBASE |
Forward rendering base pass (main directional light, lightmaps, SH). |
UNITY_PASS_FORWARDADD |
Forward rendering additive pass (one light per pass). |
UNITY_PASS_DEFERRED |
Deferred shading pass (renders g buffer). |
UNITY_PASS_SHADOWCASTER |
Shadow caster and depth Texture rendering pass. |
UNITY_PASS_PREPASSBASE |
Legacy deferred lighting base pass (renders normals and specular exponent). |
UNITY_PASS_PREPASSFINAL |
Legacy deferred lighting final pass (applies lighting and Textures). |
Name |
Value |
UNITY_MATRIX_MVP |
Current model * view * projection matrix. |
UNITY_MATRIX_MV |
Current model * view matrix. |
UNITY_MATRIX_V |
Current view matrix. |
UNITY_MATRIX_P |
Current projection matrix. |
UNITY_MATRIX_VP |
Current view * projection matrix. |
UNITY_MATRIX_T_MV |
Transpose of model * view matrix. |
UNITY_MATRIX_IT_MV |
Inverse transpose of model * view matrix. |
_Object2World |
Current model matrix. |
_World2Object |
Inverse of current world matrix. |
Name |
Type |
Value |
_WorldSpaceCameraPos |
float3 |
World space position of the camera. |
_ProjectionParams |
float4 |
x is 1.0 (or –1.0 if currently rendering with a flipped projection matrix), y is the camera’s near plane, z is the camera’s far plane and w is 1/FarPlane. |
_ScreenParams |
float4 |
x is the camera’s render target width in pixels, y is the camera’s render target height in pixels, z is 1.0 + 1.0/width and w is 1.0 + 1.0/height. |
_ZBufferParams |
float4 |
Used to linearize Z buffer values. x is (1-far/near), y is (far/near), z is (x/far) and w is (y/far). |
unity_OrthoParams |
float4 |
x is orthographic camera’s width, y is orthographic camera’s height, z is unused and w is 1.0 when camera is orthographic, 0.0 when perspective. |
unity_CameraProjection |
float4x4 |
Camera’s projection matrix. |
unity_CameraInvProjection |
float4x4 |
Inverse of camera’s projection matrix. |
unity_CameraWorldClipPlanes[6] |
float4 |
Camera frustum plane world space equations, in this order: left, right, bottom, top, near, far. |
Name |
Type |
Value |
_Time |
float4 |
Time since level load (t/20, t, t*2, t*3), use to animate things inside the shaders. |
_SinTime |
float4 |
Sine of time: (t/8, t/4, t/2, t). |
_CosTime |
float4 |
Cosine of time: (t/8, t/4, t/2, t). |
unity_DeltaTime |
float4 |
Delta time: (dt, 1/dt, smoothDt, 1/smoothDt). |
Forwardrendering (ForwardBase
and ForwardAdd
passtypes):
Name |
Type |
Value |
_LightColor0 (declared in Lighting.cginc) |
fixed4 |
Light color. |
_WorldSpaceLightPos0 |
float4 |
Directional lights: (world space direction, 0). Other lights: (world space position, 1). |
_LightMatrix0 (declared in AutoLight.cginc) |
float4x4 |
World-to-light matrix. Used to sample cookie & attenuation textures. |
unity_4LightPosX0, unity_4LightPosY0, unity_4LightPosZ0 |
float4 |
(ForwardBase pass only) world space positions of first four non-important point lights. |
unity_4LightAtten0 |
float4 |
(ForwardBase pass only) attenuation factors of first four non-important point lights. |
unity_LightColor |
half4[4] |
(ForwardBase pass only) colors of of first four non-important point lights. |
Deferred shading and deferredlighting, used in the lighting pass shader (all declared inUnityDeferredLibrary.cginc):
Name |
Type |
Value |
_LightColor |
float4 |
Light color. |
_LightMatrix0 |
float4x4 |
World-to-light matrix. Used to sample cookie & attenuation textures. |
Up to 8 lights are set up for a Vertex
passtype; always sorted starting from the brightest one. So if you want to renderobjects affected by two lights at once, you can just take first two entries inthe arrays. If there are less lights affecting the object than 8, the rest willhave their color set to black.
Name |
Type |
Value |
unity_LightColor |
half4[8] |
Light colors. |
unity_LightPosition |
float4[8] |
View-space light positions. (-direction,0) for directional lights; (position,1) for point/spot lights. |
unity_LightAtten |
half4[8] |
Light attenuation factors. x is cos(spotAngle/2) or –1 for non-spot lights; y is 1/cos(spotAngle/4) or 1 for non-spot lights; z is quadratic attenuation; w is squared light range. |
unity_SpotDirection |
float4[8] |
View-space spot light positions; (0,0,1,0) for non-spot lights. |
Name |
Type |
Value |
unity_AmbientSky |
fixed4 |
Sky ambient lighting color in gradient ambient lighting case. |
unity_AmbientEquator |
fixed4 |
Equator ambient lighting color in gradient ambient lighting case. |
unity_AmbientGround |
fixed4 |
Ground ambient lighting color in gradient ambient lighting case. |
UNITY_LIGHTMODEL_AMBIENT |
fixed4 |
Ambient lighting color (sky color in gradient ambient case). Legacy variable. |
unity_FogColor |
fixed4 |
Fog color. |
unity_FogParams |
float4 |
Parameters for fog calculation: (density / sqrt(ln(2)), density / ln(2), –1/(end-start), end/(end-start)). x is useful for Exp2 fog mode, y for Exp mode, z and w for Linear mode. |
Name |
Type |
Value |
unity_LODFade |
float4 |
Level-of-detail fade when using LODGroup. x is fade (0..1), y is fade quantized to 16 levels, z and w unused. |
clip(color.a-_CutOff); // is equal to the following code //if(color.a <_CutOff) //{ // discard; //}
· Background - this render queue is rendered before any others.You’d typically use this for things that really need to be in the background.
· Geometry (default) - this is used for mostobjects. Opaque geometry uses this queue.
· AlphaTest - alpha tested geometry uses this queue. It’s aseparate queue from Geometry one since it’s more efficient to renderalpha-tested objects after all solid ones are drawn.
· Transparent - this render queue is rendered after Geometry and AlphaTest, inback-to-front order. Anything alpha-blended (i.e. shaders that don’t write todepth buffer) should go here (glass, particle effects).
· Overlay - this render queue is meant for overlay effects.Anything rendered last should go here (e.g. lens flares).
For special uses in-betweenqueues can be used. Internally each queue is represented by integer index; Background
is1000, Geometry
is2000, AlphaTest
is2450,Transparent
is3000 and Overlay
is4000. If a shader uses a queue like this:Tags { "Queue" = "Geometry+1" }
· Opaque: most of the shaders (Normal, Self Illuminated, Reflective, terrain shaders).
· Transparent: most semitransparent shaders (Transparent, Particle, Font, terrain additivepass shaders).
· TransparentCutout: masked transparency shaders (Transparent Cutout, two pass vegetationshaders).
· Background: Skybox shaders.
· Overlay: GUITexture, Halo, Flare shaders.
· TreeOpaque: terrain engine tree bark.
· TreeTransparentCutout: terrain engine tree leaves.
· TreeBillboard: terrain engine billboarded trees.
· Grass: terrain engine grass.
· GrassBillboard: terrain engine billboarded grass.
检查读取显示贴图的环境与制作贴图环境UV坐标系是否一致。
如:Directx左上角(0,0),右下角(1,1)
unity 左下角(0,0),右上角(1,1)
两者互转需要垂直镜像。