好吧,我自己仅使用 C++ 标准找到了解决方案。
No 命令行既不使用编译器特定的 code.
所以这是我新的简单的实现
template<unsigned int I>
struct scalar_swizzle
{
float v[1];
float &operator=(const float x)
{
v[I] = x;
return v[I];
}
operator float() const
{
return v[I];
}
float operator++(int)
{
return v[I]++;
}
float operator++()
{
return ++v[I];
}
float operator--(int)
{
return v[I]--;
}
float operator--()
{
return --v[I];
}
};
// We use a vec_type in a template instead of forward declartions to prevent erros in some compilers.
template<typename vec_type, unsigned int A, unsigned int B>
struct vec2_swizzle
{
float d[2];
vec_type operator=(const vec_type& vec)
{
return vec_type(d[A] = vec.x, d[B] = vec.y);
}
operator vec_type()
{
return vec_type(d[A], d[B]);
}
};
struct vec2
{
union
{
float d[2];
scalar_swizzle<0> x, r, s;
scalar_swizzle<1> y, g, t;
vec2_swizzle<vec2, 0, 0> xx;
vec2_swizzle<vec2, 1, 1> yy;
};
vec2() {}
vec2(float all)
{
x = y = all;
}
vec2(float a, float b)
{
x = a;
y = b;
}
};
/* Debugging */
inline std::ostream& operator<<(std::ostream &os, vec2 vec)
{
os << "(" << vec.x << ", " << vec.y << ")";
return os;
}
template<typename vec_type, unsigned int A, unsigned int B, unsigned int C>
struct vec3_swizzle
{
float d[3];
vec_type operator=(const vec_type& vec)
{
return vec_type(d[A] = vec.x, d[B] = vec.y, d[C] = vec.z);
}
operator vec_type()
{
return vec_type(d[A], d[B], d[C]);
}
};
struct vec3
{
union
{
float d[3];
scalar_swizzle<0> x, r, s;
scalar_swizzle<1> y, g, t;
scalar_swizzle<2> z, b, p;
vec2_swizzle<vec2, 0, 1> xy;
vec2_swizzle<vec2, 1, 2> yz;
vec3_swizzle<vec3, 0, 1, 2> xyz;
vec3_swizzle<vec3, 2, 1, 0> zyx;
};
vec3() {}
vec3(float all)
{
x = y = z = all;
}
vec3(float a, float b, float c)
{
x = a;
y = b;
z = c;
}
};
/* Debugging */
inline std::ostream& operator<<(std::ostream &os, vec3 vec)
{
os << "(" << vec.x << ", " << vec.y << ", " << vec.z << ")";
return os;
}
当然,您可以添加/创建更多的混合。现在进行一个小测试。
int main()
{
vec3 v0(10, 20, 30);
std::cout << v0.zyx << std::endl;
vec2 c(-5, -5);
v0.xy = c;
vec2 v1(v0.yz);
std::cout << v0 << std::endl;
std::cout << v1 << std::endl;
vec3 v(50, 60, 70);
vec2 d = v.yz;
std::cout << d << std::endl;
float f = d.x * d.y;
std::cout << f << std::endl;
return 0;
}
Out:
(30, 20, 10)
(-5, -5, 30)
(-5, 30)
(60, 70)
4200
您可以打印向量以进行调试std::cout
如果你没有使用IDE正如我在海湾合作委员会所做的那样。