Skip to content

Commit

Permalink
Change value initialization of vector types
Browse files Browse the repository at this point in the history
Always zero-initialize vectors and quaternions - the performance
tradeoff is worth the security.
Add a missing quaternion exact-equality operator.
  • Loading branch information
sturnclaw committed Oct 11, 2021
1 parent 7754ea8 commit 3e50690
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 7 deletions.
21 changes: 19 additions & 2 deletions src/Quaternion.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ class Quaternion {
axis.z = z / s;
}
}
bool operator==(const Quaternion &a) const
{
return is_equal_exact(a.w, w) && is_equal_exact(a.x, x) && is_equal_exact(a.y, y) && is_equal_exact(a.z, z);
}
bool ExactlyEqual(const Quaternion &a) const
{
return is_equal_exact(a.w, w) && is_equal_exact(a.x, x) && is_equal_exact(a.y, y) && is_equal_exact(a.z, z);
}

// conjugate (inverse)
friend Quaternion operator~(const Quaternion &a)
{
Expand Down Expand Up @@ -234,9 +243,17 @@ class Quaternion {
};

template <>
inline Quaternion<float>::Quaternion() {}
inline Quaternion<float>::Quaternion() :
w(1.f),
x(0.f),
y(0.f),
z(0.f) {}
template <>
inline Quaternion<double>::Quaternion() {}
inline Quaternion<double>::Quaternion() :
w(1.),
x(0.),
y(0.),
z(0.) {}
template <>
inline Quaternion<float>::Quaternion(float w_, float x_, float y_, float z_) :
w(w_),
Expand Down
8 changes: 6 additions & 2 deletions src/vector2.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,13 @@ class vector2 {
};

template <>
inline vector2<float>::vector2() {}
inline vector2<float>::vector2() :
x(0.f),
y(0.f) {}
template <>
inline vector2<double>::vector2() {}
inline vector2<double>::vector2() :
x(0.),
y(0.) {}
template <>
inline vector2<float>::vector2(const vector2<double> &v) :
x(float(v.x)),
Expand Down
15 changes: 12 additions & 3 deletions src/vector3.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
#include <stdio.h>

// Need this pragma due to operator[] implementation.
// #pragma pack(4)
#pragma pack(4)

template <typename T>
class vector3 {
class alignas(sizeof(T)) vector3 {
public:
T x, y, z;

Expand Down Expand Up @@ -280,9 +280,18 @@ inline vector3<double>::vector3(const double vals[3]) :
z(vals[2])
{}

// #pragma pack()
#pragma pack()

typedef vector3<float> vector3f;
typedef vector3<double> vector3d;

// ensure both packing and structure alignment match the constraints we have set
static_assert(alignof(vector3d) == 8);
static_assert(offsetof(vector3d, y) == 8);
static_assert(offsetof(vector3d, z) == 16);

static_assert(alignof(vector3f) == 4);
static_assert(offsetof(vector3f, y) == 4);
static_assert(offsetof(vector3f, z) == 8);

#endif /* _VECTOR3_H */

0 comments on commit 3e50690

Please sign in to comment.