Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does glm::vec represent vec values as unions?

Tags:

c++

glm-math

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?

like image 253
pureofpure Avatar asked Feb 24 '17 15:02

pureofpure


2 Answers

Because a vec4 is commonly used for:

  • Space coordinates x, y, z, w
  • Colour components r, g, b, a
  • Texture coordinates 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.

like image 179
Angew is no longer proud of SO Avatar answered Oct 31 '22 20:10

Angew is no longer proud of SO


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.

like image 31
Nicol Bolas Avatar answered Oct 31 '22 20:10

Nicol Bolas