libcruft-util/vector.cpp
Danny Robson f6056153e3 rename root namespace from util to cruft
This places, at long last, the core library code into the same namespace
as the extended library code.
2018-08-05 14:42:02 +10:00

116 lines
2.8 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2011 Danny Robson <danny@nerdcruft.net>
*/
#include "vector.hpp"
#include "debug.hpp"
#include <cmath>
using cruft::vector;
using cruft::vector3f;
using cruft::vector3d;
///////////////////////////////////////////////////////////////////////////////
template <typename T>
vector<2,T>
cruft::polar_to_cartesian (vector<2,T> v)
{
return cruft::vector<2,T> {
v[0] * std::cos (v[1]),
v[0] * std::sin (v[1])
};
}
//-----------------------------------------------------------------------------
template <typename T>
vector<2,T>
cruft::cartesian_to_polar (vector<2,T> v)
{
return cruft::vector<2,T> {
std::hypot (v.x, v.y),
std::atan2 (v.y, v.x)
};
}
///////////////////////////////////////////////////////////////////////////////
template <typename T>
vector<3,T>
cruft::from_euler (vector<2,T> euler)
{
return normalised (cruft::vector<3,T> {
std::sin (euler.x) * std::cos (euler.y),
std::cos (euler.x),
-std::sin (euler.x) * std::sin (euler.y),
});
}
template cruft::vector3f cruft::from_euler (cruft::vector2f);
template cruft::vector3d cruft::from_euler (cruft::vector2d);
//-----------------------------------------------------------------------------
template <typename T>
vector<2,T>
cruft::to_euler (vector<3,T> vec)
{
CHECK (is_normalised (vec));
return {
std::acos (vec.y),
-std::atan2 (vec.z, vec.x),
};
}
template cruft::vector2f cruft::to_euler (cruft::vector3f);
template cruft::vector2d cruft::to_euler (cruft::vector3d);
///////////////////////////////////////////////////////////////////////////////
template <size_t S, typename T>
struct cruft::debug::validator<vector<S,T>> {
static bool
is_valid (vector<S,T> const& val)
{
return std::all_of (
std::begin (val.data),
std::end (val.data),
[] (auto v) { return !std::isnan (v); }
);
}
};
///////////////////////////////////////////////////////////////////////////////
#define INSTANTIATE_S_T(S,T) \
template struct cruft::vector<S,T>; \
template struct cruft::debug::validator<vector<S,T>>;
#define INSTANTIATE(T) \
INSTANTIATE_S_T(1,T) \
INSTANTIATE_S_T(2,T) \
INSTANTIATE_S_T(3,T) \
INSTANTIATE_S_T(4,T)
INSTANTIATE(uint32_t)
INSTANTIATE(int32_t)
INSTANTIATE(uint64_t)
INSTANTIATE(int64_t)
INSTANTIATE(float)
INSTANTIATE(double)
//-----------------------------------------------------------------------------
template vector<2,float> cruft::polar_to_cartesian (cruft::vector<2,float>);
template vector<2,float> cruft::cartesian_to_polar (cruft::vector<2,float>);