CG/HLSL Data Types in Shader

· 2 min read
CG/HLSL Data Types in Shader
Cg/HLSL data types in Shader

In the article Introduction to Shader in Unity 2023, we already saw how to define a variable in Properties, and which provides a way we can adjust values on the Materials' inspector. However, if we want to use those variables in Cg/HLSL, we must declare them again (with the SAME name). Let have a look at the common data types in Cg/HLSL:

Common Cg/HLSL data types

float: High precision type, 32-bit, is usually used for positions in world coordinates, texture UV coordinates, or scalar calculations involving complex functions, such as trigonometric functions and power operations.

half: Medium precision type, 16 bits, with a value range of [-60000, +60000]. It is usually used for position, direction vector, HDR color, etc. in local coordinates.

fixed: Low precision type, 11 bits, with a value range of [-2, +2]. It is usually used for regular colors and textures, as well as some computation variables with low precision.

Notice that: On the PC platform, no matter of half or fixed in the Shader, they are all treated as float. half and fixed are only effective on some mobile devices. A common rule is to use float for position and coordinates, and use half for everything else. The main reason is that most modern GPUs only support 32-bit and 16-bit precision, which means they only support float and half, not fixed.

integer: integer number, normally used on index for in a loop.

float4: represents a 4-component vector of floating-point values, used to represent colors, positions, normals, and other data that can be expressed as a four-component vector.

sampler2D, sampler3D and samplerCUBE: Those three are used to define textures:

  • sampler2D is used for 2D textures, such as images and photos.
  • sampler3D is used for 3D textures, such as volumes of voxels.
  • samplerCUBE is used for cube maps, which are 6 2D textures arranged in a cube shape and used to create environment maps.

A texture sampler is used to access and sample the values of a texture. The sampler type specifies how to interpret the texture coordinates when sampling the texture. It also specifies how to filter the texture when the texture is magnified or minified, and how to wrap the texture when the texture coordinates fall outside of the texture boundaries.

Mapping Cg/HLSL data types to Shader data types

Now we have two sets of data types, the Cg/HLSL data types and Shader data types(Link). It is our job to map them correctly in the Shader program unfornately.

  • Int can be presented in integer or float
  • Float can be presented in float, half or fixed
  • Vector or Color can be presented in float4
  • 2D can be presented in sampler2D
  • 3D can be presented in sampler3D
  • CUBE can be presented in samplerCUBE