hx3d  1
2D/3D Simple Game Framework
vector_utils.cpp
1 /*
2  Vector helper methods.
3  Copyright (C) 2015 Denis BOURGE
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Lesser General Public
7  License as published by the Free Software Foundation; either
8  version 2.1 of the License, or (at your option) any later version.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public
16  License along with this library; if not, write to the Free Software
17  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
18  USA
19 */
20 
21 #include "hx3d/math/vector_utils.hpp"
22 
23 #include <glm/gtx/rotate_vector.hpp>
24 
25 namespace hx3d {
26 namespace math {
27 
28 glm::vec3 rotate(glm::vec3 vector, float angle, glm::vec3 axis) {
29  glm::vec3 ret(vector);
30 
31  if (axis.x != 0)
32  ret = glm::rotateX(ret, angle);
33  if (axis.y != 0)
34  ret = glm::rotateY(ret, angle);
35  if (axis.z != 0)
36  ret = glm::rotateZ(ret, angle);
37 
38  return ret;
39 }
40 
41 glm::vec2 cross(float v, glm::vec2 vec) {
42  return glm::vec2(-v * vec.y, v * vec.x);
43 }
44 glm::vec2 cross(glm::vec2 vec, float v) {
45  return glm::vec2(v * vec.y, -v * vec.x);
46 }
47 float cross(glm::vec2 vec1, glm::vec2 vec2) {
48  return vec1.x * vec2.y - vec1.y * vec2.x;
49 }
50 
51 glm::vec2 normalize(glm::vec2 vec) {
52  float length = glm::length(vec);
53  if (length > kEpsilon) {
54  float inv = 1.f / length;
55  return {vec.x * inv, vec.y * inv};
56  }
57 
58  return vec;
59 }
60 
61 float squareLength(glm::vec2 vec) {
62  return vec.x * vec.x + vec.y * vec.y;
63 }
64 
65 float angleBetweenVecs(const glm::vec2 vec1, const glm::vec2 vec2) {
66  float angle = 0.f;
67  float a = glm::dot(vec1, vec2);
68 
69  if (vec2.x < 0) {
70  angle = -std::acos(a);
71  } else {
72  angle = std::acos(a);
73  }
74 
75  return angle;
76 }
77 
78 } /* math */
79 } /* hx3d */
hx3d framework namespace
Definition: audio.hpp:26
float squareLength(glm::vec2 vec)
Compute the square length of a 2D vector.
glm::vec3 rotate(glm::vec3 vector, float angle, glm::vec3 axis)
Rotate a vector of an angle on one/multiple axis.
const float kEpsilon
Float epsilon.
Definition: constants.hpp:36
float angleBetweenVecs(const glm::vec2 vec1, const glm::vec2 vec2)
Compute the angle between two 2D vectors.
glm::vec2 normalize(glm::vec2 vec)
Normalize a 2D vector.
glm::vec2 cross(glm::vec2 vec, float v)
Calculate the cross product vector between a 2D vector and a scalar.