From 2fb0370f94d74981f1a486edee37348adbf5e84e Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Wed, 11 Sep 2013 11:02:43 +0300 Subject: [PATCH] Add a frustum culler class --- source/frustumculler.cpp | 53 ++++++++++++++++++++++++++++++++++++++++ source/frustumculler.h | 24 ++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 source/frustumculler.cpp create mode 100644 source/frustumculler.h diff --git a/source/frustumculler.cpp b/source/frustumculler.cpp new file mode 100644 index 00000000..5401d845 --- /dev/null +++ b/source/frustumculler.cpp @@ -0,0 +1,53 @@ +#include "camera.h" +#include "frustumculler.h" +#include "renderable.h" +#include "renderer.h" + +#include + +namespace Msp { +namespace GL { + +void FrustumCuller::setup_frame(const Renderer &renderer) +{ + const Camera *camera = renderer.get_camera(); + if(!camera) + return; + + float y = tan(camera->get_field_of_view()/2.0f); + float s = sqrt(y*y+1); + edges[0] = Vector3(0, 1/s, y/s); + edges[1] = Vector3(0, -1/s, y/s); + + float x = y*camera->get_aspect(); + s = sqrt(x*x+1); + edges[2] = Vector3(1/s, 0, x/s); + edges[3] = Vector3(-1/s, 0, x/s); +} + +bool FrustumCuller::cull(const Renderer &renderer, const Renderable &renderable) const +{ + const Matrix *matrix = renderable.get_matrix(); + const Geometry::BoundingSphere *bsphere = renderable.get_bounding_sphere(); + const Camera *camera = renderer.get_camera(); + if(!matrix || !bsphere || !camera) + return false; + + Matrix mvm = camera->get_matrix()**matrix; + float n = camera->get_near_clip(); + float f = camera->get_far_clip(); + + Vector3 center = mvm*bsphere->get_center(); + float radius = bsphere->get_radius(); + + if(center.z-radius>-n || center.z+radius<-f) + return true; + for(unsigned i=0; i<4; ++i) + if(dot(center, edges[i])>radius) + return true; + + return false; +} + +} // namespace GL +} // namespace Msp diff --git a/source/frustumculler.h b/source/frustumculler.h new file mode 100644 index 00000000..d6f07486 --- /dev/null +++ b/source/frustumculler.h @@ -0,0 +1,24 @@ +#ifndef MSP_GL_FRUSTUMCULLER_H_ +#define MSP_GL_FRUSTUMCULLER_H_ + +#include "culler.h" +#include "vector.h" + +namespace Msp { +namespace GL { + +class FrustumCuller: public Culler +{ +private: + Vector3 edges[4]; + +public: + virtual void setup_frame(const Renderer &); + + virtual bool cull(const Renderer &, const Renderable &) const; +}; + +} // namespace GL +} // namespace Msp + +#endif -- 2.43.0