-
Notifications
You must be signed in to change notification settings - Fork 78
/
Frustum.cpp
executable file
·100 lines (84 loc) · 2.73 KB
/
Frustum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "Frustum.h"
namespace Planes
{
enum
{
Near = 0,
Far,
Left,
Right,
Top,
Bottom
};
}
float Plane::distanceToPoint(const Vector3& point) const noexcept
{
return glm::dot(point, normal) + distance;
}
//calcuate matrix based on the projection * view matrix.
void Frustum::update(const Matrix4& mat) noexcept
{
// left
m_planes[Planes::Left].normal.x = mat[0][3] + mat[0][0];
m_planes[Planes::Left].normal.y = mat[1][3] + mat[1][0];
m_planes[Planes::Left].normal.z = mat[2][3] + mat[2][0];
m_planes[Planes::Left].distance = mat[3][3] + mat[3][0];
// right
m_planes[Planes::Right].normal.x = mat[0][3] - mat[0][0];
m_planes[Planes::Right].normal.y = mat[1][3] - mat[1][0];
m_planes[Planes::Right].normal.z = mat[2][3] - mat[2][0];
m_planes[Planes::Right].distance = mat[3][3] - mat[3][0];
// bottom
m_planes[Planes::Bottom].normal.x = mat[0][3] + mat[0][1];
m_planes[Planes::Bottom].normal.y = mat[1][3] + mat[1][1];
m_planes[Planes::Bottom].normal.z = mat[2][3] + mat[2][1];
m_planes[Planes::Bottom].distance = mat[3][3] + mat[3][1];
// top
m_planes[Planes::Top].normal.x = mat[0][3] - mat[0][1];
m_planes[Planes::Top].normal.y = mat[1][3] - mat[1][1];
m_planes[Planes::Top].normal.z = mat[2][3] - mat[2][1];
m_planes[Planes::Top].distance = mat[3][3] - mat[3][1];
// near
m_planes[Planes::Near].normal.x = mat[0][3] + mat[0][2];
m_planes[Planes::Near].normal.y = mat[1][3] + mat[1][2];
m_planes[Planes::Near].normal.z = mat[2][3] + mat[2][2];
m_planes[Planes::Near].distance = mat[3][3] + mat[3][2];
// far
m_planes[Planes::Far].normal.x = mat[0][3] - mat[0][2];
m_planes[Planes::Far].normal.y = mat[1][3] - mat[1][2];
m_planes[Planes::Far].normal.z = mat[2][3] - mat[2][2];
m_planes[Planes::Far].distance = mat[3][3] - mat[3][2];
for (auto& plane : m_planes)
{
float length = glm::length(plane.normal);
plane.normal /= length;
plane.distance /= length;
}
}
bool Frustum::pointInFrustum(const Vector3& point) const noexcept
{
for (auto& plane : m_planes)
{
if (plane.distanceToPoint(point) < 0)
{
return false;
}
}
return true;
}
bool Frustum::boxInFrustum(const AABB& box) const noexcept
{
bool result = true;
for (auto& plane : m_planes)
{
if (plane.distanceToPoint(box.getVP(plane.normal)) < 0)
{
return false;
}
else if (plane.distanceToPoint(box.getVN(plane.normal)) < 0)
{
result = true;
}
}
return result;
}