DreamShaderLang
HLSL / GLSL 背景

HLSL 简介

面向 DreamShaderLang 用户的 HLSL 语法、类型和关键字速览。

HLSL 是 DirectX / Unreal 材质体系中常见的着色语言。DreamShaderLang 的 Function 函数体采用 HLSL 风格代码,因此写 helper 时会经常用到 HLSL 的类型、函数和控制流。

基本形态

float3 ApplyTint(float3 color, float3 tint)
{
    return color * tint;
}

DreamShaderLang 中不会直接写这种返回值函数签名,而是写成显式 out 参数:

Function ApplyTint(in vec3 color, in vec3 tint, out vec3 result) {
    result = color * tint;
}

常用类型

类型说明
float32 位浮点标量。
half半精度浮点,常用于移动端或较低精度计算。
int / uint有符号 / 无符号整数。
bool布尔值。
float2 / float3 / float42/3/4 分量向量。
float3x3 / float4x4矩阵。
Texture2D2D 纹理对象。
SamplerState采样器。

DreamShaderLang 允许在很多地方写 vec2 / vec3 / vec4,生成 helper 时会规范化成 HLSL 风格类型。

变量和表达式

float value = 0.5;
float3 color = float3(1.0, 0.2, 0.1);
float luminance = dot(color, float3(0.2126, 0.7152, 0.0722));

常用运算符:

运算符说明
+ / -加减。
* / /乘除。
> / < / >= / <=比较。
== / !=相等 / 不等。
&& / `

控制流

if (mask > 0.5)
{
    result = a;
}
else
{
    result = b;
}

for (int i = 0; i < 4; ++i)
{
    result += weights[i];
}

在 DreamShaderLang 里,复杂控制流建议放进 FunctionGraph 只支持基础 if / else,不支持 for / while

常用内建函数

函数说明
sin / cos / tan三角函数。
min / max / clamp范围处理。
saturate把值限制到 0..1
lerp线性插值。
dot点积。
cross叉积。
normalize归一化向量。
length向量长度。
pow / sqrt幂和平方根。
abs / floor / ceil / frac数值处理。

常见关键字

分类关键字
类型float, half, int, uint, bool, void
控制流if, else, for, while, do, switch, case, break, continue, return
参数in, out, inout
常量与修饰const, static, uniform
采样相关Texture2D, TextureCube, SamplerState

与 DreamShaderLang 的关系

HLSL 概念DreamShaderLang 中的位置
helper 函数体Function ... { ... }
材质节点连接Graph = { ... }
纹理对象参数PropertiesFunction 参数
复杂循环Function
资产生成Shader / ShaderFunction

On this page