Components can be accessed via dot notation (swizzling) or array subscripting.
Swizzling (Dot Notation)
Vectors support component selection using names from these sets:
- Spatial:
x, y, z, w - Color:
r, g, b, a - Texture:
s, t, p, q
Components are synonyms (e.g., x, r, and s all refer to the first component). You can select multiple components in any order to create a new vector (swizzling).
Rules:
- You cannot select more than 4 components.
- You cannot use duplicate components when assigning to an l-value (e.g.,
pos.xx = ... is illegal). - Swizzling can be used on both r-values (to read) and l-values (to write).
Array Subscripting
Vectors support numeric indexing (e.g., pos[2] is equivalent to pos.z).
- Indexing starts at 0.
- For non-constant indices, behavior is undefined if the index is out of bounds.
Matrix Access
Matrices are treated as arrays of column vectors.
m[1] selects the second column (a vector).m[0][0] selects the element at column 0, row 0.
Length Method
vector.length() returns the number of components in the vector (as an int).matrix.length() returns the number of columns in the matrix (as an int).
vec4 pos = vec4(1.0, 2.0, 3.0, 4.0);
vec4 swiz = pos.wzyx; // (4.0, 3.0, 2.0, 1.0)
vec4 dup = pos.xxyy; // (1.0, 1.0, 2.0, 2.0)
pos.xw = vec2(5.0, 6.0); // writes to components
mat4 m;
m[1] = vec4(2.0); // sets second column to 2.0
m[0][0] = 1.0; // sets upper left element