Uniform

优质
小牛编辑
114浏览
2023-12-01

Uniforms 是 GLSL 着色器中的全局变量。

代码示例

When declaring a uniform of a ShaderMaterial, it is declared by value or by object.

uniforms: {
  time: { value: 1.0 },
  resolution: new Uniform( new Vector2() )
};

Uniform 种类

每个 Uniform 必须包括一个 value 属性。value 的类型必须和下表中 GLSL 的基本类型相对应。同样,Uniform 的结构体和队列 也是支持的。 GLSL基本类型队列必须要么被显示声明为一个 THREE 对象的队列,要么被声明为一个包含所有对象数据的队列。这就是说, 队列中的 GLSL 基础类型不能再是一个队列。举例,一个有 5 个 vec2 元素的队列,必须是一个包含 5 个 Vector2 的队列数组, 或包含 10 个 number 的队列。

Uniform 类型
GLSL 类型JavaScript 类型
intNumber
uint (WebGL 2)Number
floatNumber
boolBoolean
boolNumber
vec2THREE.Vector2
vec2Float32Array (*)
vec2Array (*)
vec3THREE.Vector3
vec3THREE.Color
vec3Float32Array (*)
vec3Array (*)
vec4THREE.Vector4
vec4THREE.Quaternion
vec4Float32Array (*)
vec4Array (*)
mat2Float32Array (*)
mat2Array (*)
mat3THREE.Matrix3
mat3Float32Array (*)
mat3Array (*)
mat4THREE.Matrix4
mat4Float32Array (*)
mat4Array (*)
ivec2, bvec2Float32Array (*)
ivec2, bvec2Array (*)
ivec3, bvec3Int32Array (*)
ivec3, bvec3Array (*)
ivec4, bvec4Int32Array (*)
ivec4, bvec4Array (*)
sampler2DTHREE.Texture
samplerCubeTHREE.CubeTexture

(*) 与最内层队列中 GSLS 的类型保持一致。包含队列中所有矢量的元素或矩阵中的元素。

Structured Uniforms

Sometimes you want to organize uniforms as structs in your shader code. The following style must be used so three.js is able to process structured uniform data.

uniforms = {
  data: {
    value: {
      position: new Vector3(),
      direction: new Vector3( 0, 0, 1 )
     }
  }
};
This definition can be mapped on the following GLSL code:
struct Data {
  vec3 position;
  vec3 direction;
};
uniform Data data;

Structured Uniforms with Arrays

It's also possible to manage structs in arrays. The syntax for this use case looks like so:

const entry1 = {
  position: new Vector3(),
  direction: new Vector3( 0, 0, 1 )
};
const entry2 = {
  position: new Vector3( 1, 1, 1 ),
  direction: new Vector3( 0, 1, 0 )
};
uniforms = {
  data: {
    value: [ entry1, entry2 ]
  }
};
This definition can be mapped on the following GLSL code:
struct Data {
  vec3 position;
  vec3 direction;
};
uniform Data data[ 2 ];

构造函数

Uniform( value : Object )

value -- 包含需要设置 Uniform 数据的对象。 数据类型必须是上述类型中的一种。

属性

.value : Object

当前 uniform 的值。

方法

.clone () : Uniform

返回该 Uniform 的克隆。
如果 Uniform 的 value 属性是一个带 clone() 方法的 Object,则克隆该对象时,value 的 clone() 方法也会被调用,否则克隆时只会使用赋值语句。 队列中的值会在该 Uniform 和 被克隆对象间共享。

源代码

src/core/Uniform.js