]> git.tdb.fi Git - libs/gl.git/commitdiff
Add a frustum culler class
authorMikko Rasa <tdb@tdb.fi>
Wed, 11 Sep 2013 08:02:43 +0000 (11:02 +0300)
committerMikko Rasa <tdb@tdb.fi>
Wed, 11 Sep 2013 08:02:43 +0000 (11:02 +0300)
source/frustumculler.cpp [new file with mode: 0644]
source/frustumculler.h [new file with mode: 0644]

diff --git a/source/frustumculler.cpp b/source/frustumculler.cpp
new file mode 100644 (file)
index 0000000..5401d84
--- /dev/null
@@ -0,0 +1,53 @@
+#include "camera.h"
+#include "frustumculler.h"
+#include "renderable.h"
+#include "renderer.h"
+
+#include <msp/io/print.h>
+
+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<float, 3> *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 (file)
index 0000000..d6f0748
--- /dev/null
@@ -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