I was looking at vec4
glm's source code implementation, and I was wondering why they represent vector values with a union, instead of primitive data types like float
or int
?
This is the code I found in vec4
implementation:
union { T x, r, s; };
union { T y, g, t; };
union { T z, b, p; };
union { T w, a, q; };
What is the difference if we just write T x
, T y
, T z
, T w
?
Because a vec4
is commonly used for:
x
, y
, z
, w
r
, g
, b
, a
s
, t
, p
, q
(although these are less standardised, and I've also seen r
and u
used in different contexts)Using unions allows use to access the e.g. second data member as either .y
or .g
, depending on your preference & semantics.
GLM is designed to behave like GLSL as much as C++ allows. In GLSL, swizzle operations for vectors can use xyzw
, rgba
, or stpq
, with the corresponding element names referencing the same elements of the vector. Therefore, the union is used to match this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With