src/kdtree.h
author Radek Brich <radek.brich@devl.cz>
Sun, 25 Nov 2007 15:50:01 +0100
branchpyrit
changeset 14 fc18ac4833f2
parent 12 f4fcabf05785
child 15 a0a3e334744f
permissions -rw-r--r--
replace Plane with axis-aligned Box (because infinite Plane is not usable with kd-tree) fix memory leak in KdTree::nearest_intersection rename BBox::R to BBox::H new file: common.h (Eps and Inf constants)

#ifndef KDTREE_H
#define KDTREE_H

#include <vector>
#include <iostream>
#include <fstream>

#include "scene.h"

using namespace std;

class ShapeList: public vector<Shape*>
{
};

class Container
{
protected:
	BBox bbox;
public:
	ShapeList shapes;
	Container(): bbox(), shapes() {};
	virtual ~Container() {};
	virtual void addShape(Shape* aShape);
	//void addShapeNoExtend(Shape* aShape) { shapes.push_back(aShape); };
	virtual Shape *nearest_intersection(const Shape *origin_shape, const Ray &ray,
		float &nearest_distance);
	virtual void optimize() {};
};

class KdNode
{
	float split;
	bool leaf; /* is this node a leaf? */
	short axis; /* 0,1,2 => x,y,z */
	KdNode *children;
public:
	ShapeList shapes;

	KdNode() : leaf(true), axis(0), shapes() {};

	void setAxis(short aAxis) { axis = aAxis; };
	short getAxis() { return axis; };

	void setSplit(float aSplit) { split = aSplit; };
	float getSplit() { return split; };

	void setLeaf(bool aLeaf) { leaf = aLeaf; };
	bool isLeaf() { return leaf; };

	KdNode *getLeftChild() { return children; };
	KdNode *getRightChild() { return children+1; };

	void addShape(Shape* aShape) { shapes.push_back(aShape); };

	void subdivide(BBox bbox, int depth);
};

class KdTree: public Container
{
	KdNode *root;
	bool built;
public:
	KdTree() : Container(), built(false) {};
	void addShape(Shape* aShape) { Container::addShape(aShape); built = false; };
	Shape *nearest_intersection(const Shape *origin_shape, const Ray &ray,
		float &nearest_distance);
	void optimize() { build(); };
	void build();
	void save(ostream &str, KdNode *node = NULL);
	void load(istream &str, KdNode *node = NULL);
};

#endif