Up to date

This page is up to date for Godot `4.2`. If you still find outdated information, please open an issue.

# 着色语言¶

## 前言¶

Godot 使用类似于 GLSL ES 3.0 的着色语言。支持大多数数据类型和函数，并且可能会随着时间的推移添加剩余的几种类型和函数。

## 数据类型¶

void

Void数据类型, 只对不返回任何内容的函数有用.

bool

bvec2

bvec3

bvec4

int

ivec2

ivec3

ivec4

uint

uvec2

uvec3

uvec4

float

vec2

vec3

vec4

mat2

2x2矩阵, 按主要顺序排列.

mat3

3x3矩阵, 在列的主要顺序.

mat4

4x4矩阵, 按主要顺序排列.

sampler2D

isampler2D

usampler2D

sampler2DArray

isampler2DArray

usampler2DArray

sampler3D

isampler3D

usampler3D

samplerCube

samplerCubeArray

### 类型转换¶

```float a = 2; // invalid
float a = 2.0; // valid
float a = float(2); // valid
```

```int a = 2; // valid
uint a = 2; // invalid
uint a = uint(2); // valid
```

### 构建¶

```// The required amount of scalars
vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
// Complementary vectors and/or scalars
vec4 a = vec4(vec2(0.0, 1.0), vec2(2.0, 3.0));
vec4 a = vec4(vec3(0.0, 1.0, 2.0), 3.0);
// A single scalar for the whole vector
vec4 a = vec4(0.0);
```

```mat2 m2 = mat2(vec2(1.0, 0.0), vec2(0.0, 1.0));
mat3 m3 = mat3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
mat4 identity = mat4(1.0);
```

Matrices can also be built from a matrix of another dimension. There are two rules:

1. If a larger matrix is constructed from a smaller matrix, the additional rows and columns are set to the values they would have in an identity matrix. 2. If a smaller matrix is constructed from a larger matrix, the top, left submatrix of the larger matrix is used.

```mat3 basis = mat3(MODEL_MATRIX);
mat4 m4 = mat4(basis);
mat2 m2 = mat2(m4);
```

### 混写Swizzling¶

```vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
vec3 b = a.rgb; // Creates a vec3 with vec4 components.
vec3 b = a.ggg; // Also valid; creates a vec3 and fills it with a single vec4 component.
vec3 b = a.bgr; // "b" will be vec3(2.0, 1.0, 0.0).
vec3 b = a.xyz; // Also rgba, xyzw are equivalent.
vec3 b = a.stp; // And stpq (for texture coordinates).
float c = b.w; // Invalid, because "w" is not present in vec3 b.
vec3 c = b.xrt; // Invalid, mixing different styles is forbidden.
b.rrr = a.rgb; // Invalid, assignment with duplication.
b.bgr = a.rgb; // Valid assignment. "b"'s "blue" component will be "a"'s "red" and vice versa.
```

### 精度¶

```lowp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // low precision, usually 8 bits per component mapped to 0-1
mediump vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // medium precision, usually 16 bits or half float
highp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // high precision, uses full float or integer range (default)
```

## 数组¶

Arrays are containers for multiple variables of a similar type.

### 局部数组¶

```void fragment() {
float arr[3];
}
```

```float float_arr[3] = float[3] (1.0, 0.5, 0.0); // first constructor

int int_arr[3] = int[] (2, 1, 0); // second constructor

vec2 vec2_arr[3] = { vec2(1.0, 1.0), vec2(0.5, 0.5), vec2(0.0```