Line data Source code
1 : #include "geometry.hpp"
2 :
3 : #include <cmath>
4 :
5 : #include "matrix.hpp"
6 : #include "vector.hpp"
7 :
8 : namespace wren::math {
9 :
10 0 : auto look_at(const Vec3f& eye, const Vec3f& center, const Vec3f& world_up)
11 : -> Mat4f {
12 0 : const Vec3f up = world_up.normalized();
13 0 : const Vec3f f = (center - eye).normalized();
14 0 : const Vec3f s = (up % f).normalized();
15 0 : const Vec3f u = f % s;
16 :
17 0 : Mat4f mat;
18 :
19 0 : mat.at(0, 0) = s.x();
20 0 : mat.at(1, 0) = s.y();
21 0 : mat.at(2, 0) = s.z();
22 0 : mat.at(0, 1) = u.x();
23 0 : mat.at(1, 1) = u.y();
24 0 : mat.at(2, 1) = u.z();
25 0 : mat.at(0, 2) = -f.x();
26 0 : mat.at(1, 2) = -f.y();
27 0 : mat.at(2, 2) = -f.z();
28 0 : mat.at(3, 0) = -(s.dot(eye));
29 0 : mat.at(3, 1) = -(u.dot(eye));
30 0 : mat.at(3, 2) = -(f.dot(eye));
31 0 : return mat;
32 : }
33 :
34 2 : auto translate(Mat4f mat, Vec4f offset) -> Mat4f {
35 2 : auto res = Mat4f::identity();
36 :
37 2 : res.at(3, 0) = offset.data.at(0);
38 2 : res.at(3, 1) = offset.data.at(1);
39 2 : res.at(3, 2) = offset.data.at(2);
40 2 : res.at(3, 3) = offset.data.at(3);
41 :
42 2 : return mat * res; // * res;
43 : }
44 :
45 2 : auto translate(Mat4f mat, Vec3f offset) -> Mat4f {
46 2 : return translate(mat, Vec4f(offset, 1.0));
47 : }
48 :
49 0 : auto scale(const Mat4f& mat, const Vec3f& scale) -> Mat4f {
50 0 : auto res = Mat4f::identity();
51 :
52 0 : res.at(0, 0) = scale.x();
53 0 : res.at(1, 1) = scale.y();
54 0 : res.at(2, 2) = scale.z();
55 :
56 0 : return mat * res;
57 : }
58 :
59 0 : auto rotate(const Mat4f& matrix, float angle, const Vec3f& axis) -> Mat4f {
60 0 : const float sin = std::sin(angle);
61 0 : const float cos = std::cos(angle);
62 0 : const float x2 = axis.x() * axis.x();
63 0 : const float y2 = axis.y() * axis.y();
64 0 : const float z2 = axis.z() * axis.z();
65 0 : const float yx = axis.y() * axis.x();
66 0 : const float yz = axis.y() * axis.z();
67 0 : const float xy = axis.x() * axis.y();
68 0 : const float xz = axis.x() * axis.z();
69 0 : const float zx = axis.z() * axis.x();
70 0 : const float zy = axis.z() * axis.y();
71 0 : const float x = axis.x();
72 0 : const float y = axis.y();
73 0 : const float z = axis.z();
74 :
75 0 : Mat4f mat = matrix;
76 0 : mat.at(0, 0) = cos + x2 * (1 - cos);
77 0 : mat.at(1, 0) = xy * (1 - cos) - z * sin;
78 0 : mat.at(2, 0) = xz * (1 - cos) + y * sin;
79 0 : mat.at(3, 0) = 0;
80 :
81 0 : mat.at(0, 1) = yx * (1 - cos) + z * sin;
82 0 : mat.at(1, 1) = cos + y2 * (1 - cos);
83 0 : mat.at(2, 1) = yz * (1 - cos) - x * sin;
84 0 : mat.at(3, 1) = 0.0F;
85 :
86 0 : mat.at(0, 2) = zx * (1 - cos) - y * sin;
87 0 : mat.at(1, 2) = zy * (1 - cos) + z * sin;
88 0 : mat.at(2, 2) = cos + z2 * (1 - cos);
89 0 : mat.at(3, 0) = 0.0f;
90 :
91 0 : mat.at(0, 3) = 0.0F;
92 0 : mat.at(1, 3) = 0.0f;
93 0 : mat.at(2, 3) = 0.0f;
94 0 : mat.at(3, 3) = 0.0f;
95 :
96 0 : return mat;
97 : }
98 :
99 : } // namespace wren::math
|