High-Level Shading Language (HLSL) Reference
The High-Level Shading Language (HLSL) is a proprietary language developed by Microsoft for writing shader programs that run on the GPU. It provides a C-like syntax that makes it easier to write complex shader logic compared to assembly-level shading languages.
Overview
HLSL is used to define the behavior of graphics pipelines, controlling how vertices are transformed, how pixels are colored, and how other graphical effects are rendered. It's an integral part of the DirectX graphics API.
Key Concepts
- Shader Stages: HLSL code is organized into different shader types, each corresponding to a stage in the graphics pipeline (e.g., Vertex Shader, Pixel Shader, Geometry Shader, Compute Shader).
- Data Types: HLSL supports various data types, including basic types (
float,int,bool) and vector/matrix types (e.g.,float2,float3x3). - Functions: Built-in functions are provided for common mathematical operations, texture sampling, and manipulating shader data.
- Variables and Semantics: Variables are used to pass data into and out of shaders. Semantics are attached to variables to define their meaning within the graphics pipeline (e.g.,
POSITION,COLOR,NORMAL). - Resources: Shaders can access various resources, including textures, samplers, constant buffers, and structured buffers.
Syntax Examples
Basic Vertex Shader
This example demonstrates a simple vertex shader that passes vertex position and color to the next stage.
struct VS_INPUT {
float4 pos : POSITION;
float4 color : COLOR;
};
struct VS_OUTPUT {
float4 pos : SV_POSITION;
float4 color : COLOR;
};
VS_OUTPUT main(VS_INPUT input) {
VS_OUTPUT output;
output.pos = input.pos; // Pass position through
output.color = input.color; // Pass color through
return output;
}
Basic Pixel Shader
This example demonstrates a simple pixel shader that outputs a solid color.
float4 main() : SV_TARGET {
return float4(1.0f, 0.0f, 0.0f, 1.0f); // Output red color
}
Built-in Functions
HLSL provides a rich set of built-in functions for:
- Mathematical Operations:
sin,cos,pow,dot,cross,normalize, etc. - Vector Operations:
lerp,saturate,clip, etc. - Texture Sampling:
tex2D,tex2Dlod,sample, etc. - Bitwise Operations:
asfloat,asint,asuint.
Resources and Bindings
- Constant Buffers: Used to pass constant data (e.g., transformation matrices, lighting parameters) to shaders.
- Shader Resources (SRVs): Textures and other data structures that shaders can read from.
- Unordered Access Views (UAVs): Resources that shaders can read from and write to.
- Samplers: Control how textures are sampled (e.g., filtering, addressing modes).