英特尔 Embree 中的这种联合有什么作用?

What does this union in Intel's Embree do?

本文关键字:什么 作用 Embree 英特尔      更新时间:2023-10-16

这是来自英特尔的Embree代码中的vec3fa.h。

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
};

外部联合在做什么?内在的结合对我来说更神秘。a和w变量在代码中从未被引用。

看起来这提供了一种方便和干净的方式,可以使用适当的别名读写m128、x、y和z。它是如何工作的?

int型是怎么进来的??

这是匿名联合(和一个结构体)。它们所做的是就地定义结构体或联合的匿名实例,并用于在访问成员时避免混乱。以上代码的布局与下面的代码兼容:

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
};

但是现在成员访问更复杂了:

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

代替库变量:

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

int型是怎么进来的??

英特尔的Embree是一个光线跟踪内核库。在计算机图形学中,您可以想象有时需要使用4元素向量来表示颜色和alpha,或者使用齐次坐标表示位置。

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