# source:trunk/src/matrix.cpp@648Tweet

Last change on this file since 648 was 648, checked in by sam, 11 years ago

Add matrix determinant and inverse methods.

• Property svn:keywords set to Id
File size: 1.7 KB
Line
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2011 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
8//   http://sam.zoy.org/projects/COPYING.WTFPL for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cstdio>
16#include <cstdlib> /* free() */
17#include <cstring> /* strdup() */
18
19#include "core.h"
20
21static inline float det3(float a, float b, float c,
22                         float d, float e, float f,
23                         float g, float h, float i)
24{
25    return a * (e * i - h * f)
26         + b * (f * g - i * d)
27         + c * (d * h - g * e);
28}
29
30static inline float cofact3(float4x4 const &mat, int i, int j)
31{
32    return det3(mat[(i + 1) & 3][(j + 1) & 3],
33                mat[(i + 2) & 3][(j + 1) & 3],
34                mat[(i + 3) & 3][(j + 1) & 3],
35                mat[(i + 1) & 3][(j + 2) & 3],
36                mat[(i + 2) & 3][(j + 2) & 3],
37                mat[(i + 3) & 3][(j + 2) & 3],
38                mat[(i + 1) & 3][(j + 3) & 3],
39                mat[(i + 2) & 3][(j + 3) & 3],
40                mat[(i + 3) & 3][(j + 3) & 3]) * (((i + j) & 1) ? -1.0f : 1.0f);
41}
42
43template<> float float4x4::det() const
44{
45    float ret = 0;
46    for (int n = 0; n < 4; n++)
47        ret += (*this)[n][0] * cofact3(*this, n, 0);
48    return ret;
49}
50
51template<> float4x4 float4x4::invert() const
52{
53    float4x4 ret;
54    float d = det();
55    if (d)
56    {
57        d = 1.0f / d;
58        for (int j = 0; j < 4; j++)
59            for (int i = 0; i < 4; i++)
60                ret[j][i] = cofact3(*this, i, j) * d;
61    }
62    return ret;
63}
64
Note: See TracBrowser for help on using the repository browser.