ThreeJS Uniform

Uniforms are global GLSL variables. They are passed to shader programs.

Code Example

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 types

A value property is required for each uniform. The type of the value must correspond to the type of the uniform variable in the GLSL code, as specified in the table below for the primitive GLSL types. Arrays and uniform structures are also supported. Primitive-type GLSL arrays must be specified as either an array of the corresponding THREE objects or as a flat array containing the data of all the objects. In other words, arrays cannot be used to represent GLSL primitives. This rule does not apply in a transitive sense. An array of vec2 arrays, each of which has a length of five vectors, must be an array of arrays, consisting of either five Vector2 objects or ten numbers.

Structured Uniforms

In your shader code, you may want to organise uniforms as structs at times. So three, the following style must be used. js can handle 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 ];

Constructor

Uniform( value : Object )

value -- An object containing the value to set up the uniform. It's type must be one of the Uniform Types described above.

Properties

.value : Object

Current value of the uniform.

Methods

.clone () : Uniform

Returns a clone of this uniform.

If the uniform's value property is an Object with a clone() method, this is used, otherwise, the value is copied by assignment. Array values are shared between cloned Uniforms.