Question

This is from vec3fa.h in Intel's Embree code.

struct __aligned(16) Vec3fa
{
typedef float Scalar;
enum { N = 3 };
union {
  __m128 m128;
  struct { float x,y,z; union { int a; float w; }; };
};

// other stuff in struct

};

What is the outer union doing? The inner union is even more mysterious to me. The a and w variables are never referred to in the code.

It looks like this provides a convenient and clean way of reading and writing to m128, x, y, and z with the appropriate aliases. How does it work?

How did an int get involved??

Was it helpful?

Solution

These are anonymous unions (and a struct). What they do is define anonymous instance of the struct or union inplace and are used to avoid clutter when accessing members. The above code is layout compatible to this one:

struct __aligned(16) Vec3fa
{
  typedef float Scalar;
  enum { N = 3 };
  union {
    __m128 m128;
    struct { float x,y,z; union { int a; float w; } u2; } s;
  } u1;
  // other stuff in struct
};

But now member access is more complicated:

Vec3fa v;      // offset from struct start ((char*)&member - (char*)&v):
v.u1.m128;     // 0
v.u1.s.x;      // 0
v.u1.s.y;      // 4
v.u1.s.z;      // 8
v.u1.s.u2.w;  // 12
v.u1.s.u2.a;  // 12

Instead of the library variant:

Vec3fa v;      // offset from struct start ((char*)&member - (char*)&v):
v.m128;        // 0
v.x;           // 0
v.y;           // 4
v.z;           // 8
v.w;           // 12
v.a;           // 12

OTHER TIPS

How did an int get involved??

Intels Embree is a ray tracing kernel library. In computer graphics, you could imagine the need for sometimes using a 4-element vector for color and alpha, or for representing position using homogeneous coordinates.

https://en.wikipedia.org/wiki/RGBA_color_space https://en.wikipedia.org/wiki/Homogeneous_coordinates

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top