Tour of WGSL

Vector constructors

Vectors have three kinds of constructors:

  1. Zero-value constructor: vecNS() or vecN<T>()

    This constructs a vector with the zero-value for all elements.

    Example

    vec2f() constructs a vec2f with zero-values for each of the elements.

    vec3<bool>() constructs a vec3<bool> with false for each of the elements.

  2. ‘Splat’ constructor: vecNS(value) or vecN<T>(value)

    This constructs a vector with the same value for all elements.

    Example

    vec4i(5) constructs a vec4<i32> with 5 replicated in all 4 elements of the vector.

    vec2<bool>(true) constructs a vec2<bool> with true for both of the elements.

  3. Element-wise constructor: vecNS(x, y, …) or vecN<T>(x, y, …)

    This constructs a vector with the elements assigned the respective argument value.

    Example

    vec3u(1, 2, 3) constructs a vec3<u32> with the .x, .y, and .z elements initialized with 1, 2, and 3, respectively.

    vec2<bool>(true, false) constructs a vec2<bool> with .x, and .y elements initialized with true and false, respectively.

    If an constructor argument is a vector, then the elements of that vector are used as if they were passed separately.

    Example

    vec4f(1, vec2(2, 3), 4) constructs a vec4<f32> with the .x, .y, .z and .w elements initialized with 1, 2, 3, and 4, respectively.

The short-hand vector constructors vecN(value) and vecN(x, y, …) infer the element type from the arguments:

Example

vec4(1i) constructs a vec4<i32> with 1 replicated in all four elements of the vector.

vec2(1, 2) constructs a two-element vector of type abstract-int, with .x and .y elements initialized with 1, 2, respectively.

vec2(1, 2.5) constructs a two-element vector of type abstract-float, with .x and .y elements initialized with 1.0, 2.5, respectively.

Vectors with a different element type but the same number of elements can be element-wise converted, with vecN<T>(vector_expr) .