libcruft-util/test/matrix.cpp

110 lines
2.6 KiB
C++
Raw Normal View History

2014-08-19 20:45:28 +10:00
#include "matrix.hpp"
2015-04-13 16:45:56 +10:00
2014-08-19 20:45:28 +10:00
#include "debug.hpp"
2015-04-13 16:45:56 +10:00
#include "tap.hpp"
#include "vector.hpp"
2014-08-19 20:45:28 +10:00
#include <cstdlib>
int
2015-07-13 16:29:01 +10:00
main (void)
{
util::TAP::logger tap;
2014-08-19 20:45:28 +10:00
{
// Identity matrix-vector multiplication
auto v = util::vector<4,float> { 1.f, 2.f, 3.f, 4.f };
2014-08-19 20:45:28 +10:00
auto r = util::matrix<float>::IDENTITY * v;
2015-07-13 16:29:01 +10:00
tap.expect_eq (r, v, "identity matrix-vector multiplication");
2014-08-19 20:45:28 +10:00
}
{
// Simple matrix-vector multiplication
util::matrix<float> m { {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
} };
util::vector<4,float> v { 1.f, 2.f, 3.f, 4.f };
2014-08-19 20:45:28 +10:00
auto r = m * v;
2015-07-13 16:29:01 +10:00
tap.expect (
almost_equal (r.x, 30) &&
almost_equal (r.y, 70) &&
almost_equal (r.z, 110) &&
almost_equal (r.w, 150),
"simple matrix-vector multiplication"
);
2014-08-19 20:45:28 +10:00
}
2014-12-15 13:30:37 +11:00
{
// Simple matrix-matrix multiplication
util::matrix<float> a { {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 },
} };
util::matrix<float> b { {
{ 17, 18, 19, 20 },
{ 21, 22, 23, 24 },
{ -1, -2, -3, -4 },
{ -5, -6, -7, -8 }
} };
util::matrix<float> ab { {
{ 9, 8, 7, 6 },
{ 41, 40, 39, 38 },
{ 73, 72, 71, 70 },
{ 105, 104, 103, 102 },
} };
ab *= 4;
auto res = a * b;
2015-07-13 16:29:01 +10:00
tap.expect_eq (ab, res, "simple matrix-matrix multiplication");
2014-12-15 13:30:37 +11:00
}
2014-08-19 20:45:28 +10:00
{
2015-07-13 16:29:01 +10:00
bool success = true;
2014-08-19 20:45:28 +10:00
// Ensure identity inverts to identity
auto m = util::matrix<float>::IDENTITY.inverse ();
for (size_t r = 0; r < m.rows; ++r)
for (size_t c = 0; c < m.cols; ++c)
if (r == c)
2015-07-13 16:29:01 +10:00
success = success && almost_equal (m.values[r][c], 1);
2014-08-19 20:45:28 +10:00
else
2015-07-13 16:29:01 +10:00
success = success && almost_equal (m.values[r][c], 0);
tap.expect (success, "identity inversion");
2014-08-19 20:45:28 +10:00
}
{
// Simple inversion test
util::matrix<float> m { {
{ 4, 1, 2, 3 },
{ 2, 3, 4, 1 },
{ 3, 4, 1, 2 },
{ 1, 2, 3, 4 }
} };
util::matrix<float> r { {
{ 11, 1, 1, -9 },
{ -9, 1, 11, 1 },
{ 1, 11, -9, 1 },
{ 1, -9, 1, 11 }
} };
2015-07-13 16:29:01 +10:00
tap.expect_eq (m.inverse (), r / 40.f, "simple inversion");
2014-08-19 20:45:28 +10:00
}
2015-07-13 16:29:01 +10:00
return tap.status ();
2014-08-19 20:45:28 +10:00
}