HLSL / Cg Syntax
A quick primer on the HLSL syntax supported in unity.
Data types
- bool - true or false.
- int - 32-bit signed integer.
- uint - 32-bit unsigned integer.
- half - 16-bit floating point value.
- float - 32-bit floating point value.
- double - 64-bit floating point value.
- void - No value.
Variables
Normal variables are definied by type name = value;
.
float depth = _Amount * info;
Vectors
Vectors are arrays of values, in the form typeN
where N is the same.
float3 rgb = tex2D(_MainTex, uv).rgb;
Functions
Functions always take the form return_type name(args, ...) { ... }
.
float calc(float a, float b) { return a * b; }
Notce that unlike C, function overloading is supported in HLSL.
Structs
Structs allow data to be passed around under a single pointer.
The basic syntax for a struct is struct Name { type name1; type name2; ... }
.
struct Input {
float2 uv_MainTex;
};
Notice that unlike C structs in HLSL automatically generate a typedef. That is, an instance of Input is passed as Input foo
not struct Input Foo
.
Unlike C, the naming of fields in structs is highly significant in Unity. In the example above, uv_MainTex
is populated by the uv coordinate of the _MainTex property:
Properties {
_MainTex ("Texture", 2D) = "white" {}
}
If the name is incorrect, the values will not be populated.
#define, macros etc.
As with C, the following statements are generally supported:
#define
#ifdef
#ifndef
#else
#endif
Unity supports all the basic functionality of these operators.
#define FOO 2
#ifdef FOO
#if FOO == 1
#define ADD(x,y) x + y * 2.0
#endif
#if FOO == 2
#define ADD(x,y) x + y * 4.0
#endif
#endif
#ifndef ADD
#define ADD(x, y) x
#endif