#ifndef _ViewCellBsp_H__ #define _ViewCellBsp_H__ #include "Mesh.h" #include "Containers.h" #include class ViewCell; class BspViewCell; class Plane3; class BspTree; class BspInterior; class Polygon3; class AxisAlignedBox3; class Ray; /** Data structure used for optimized ray casting. */ struct BspRayTraversalData { BspNode *mNode; Vector3 mExitPoint; float mMaxT; BspRayTraversalData() {} BspRayTraversalData(BspNode *n, const Vector3 &extp, const float maxt): mNode(n), mExitPoint(extp), mMaxT(maxt) {} }; /** Data used for passing ray data down the tree. */ struct BoundedRay { Ray *mRay; float mMinT; float mMaxT; BoundedRay(): mMinT(0), mMaxT(1e6), mRay(NULL) {} BoundedRay(Ray *r, float minT, float maxT): mRay(r), mMinT(minT), mMaxT(maxT) {} }; typedef vector BoundedRayContainer; class BspTreeStatistics { public: // total number of nodes int nodes; // number of splits int splits; // totals number of rays int rays; // maximal reached depth int maxDepth; // minimal depth int minDepth; // max depth nodes int maxDepthNodes; // max number of rays per node int maxObjectRefs; // accumulated depth (used to compute average) int accumDepth; // number of initial polygons int polys; /// number of view cells different to the view cell representing unbounded space. int viewCells; /// size of the VPS int pvs; /// samples contributing to pvs int contributingSamples; /// sample contributions to pvs int sampleContributions; // Constructor BspTreeStatistics() { Reset(); } int Nodes() const {return nodes;} int Interior() const { return nodes / 2; } int Leaves() const { return (nodes / 2) + 1; } double AvgDepth() const { return accumDepth / (double)Leaves();}; // TODO: computation wrong void Reset() { nodes = 0; splits = 0; maxDepthNodes = 0; maxDepth = 0; minDepth = 99999; polys = 0; accumDepth = 0; viewCells = 0; pvs = 0; contributingSamples = 0; sampleContributions = 0; } void Print(ostream &app) const; friend ostream &operator<<(ostream &s, const BspTreeStatistics &stat) { stat.Print(s); return s; } }; /** BspNode abstract class serving for interior and leaf node implementation */ class BspNode { friend class BspTree; public: BspNode(); virtual ~BspNode(); BspNode(BspInterior *parent); /** Determines whether this node is a leaf or not @return true if leaf */ virtual bool IsLeaf() const = 0; /** Determines whether this node is a root @return true if root */ virtual bool IsRoot() const; /** Returns parent node. */ BspInterior *GetParent(); /** Sets parent node. */ void SetParent(BspInterior *parent); /** Returns pointer to polygons. */ PolygonContainer *GetPolygons(); /** Stores polygons in node or discards them according to storePolys. */ void ProcessPolygons(PolygonContainer *polys, const bool storePolys); static int mailID; int mailbox; void Mail() { mailbox = mailID; } static void NewMail() { mailID++; } bool Mailed() const { return mailbox == mailID; } //int mViewCellIdx; protected: /// parent of this node BspInterior *mParent; /// store polygons created during BSP splits PolygonContainer *mPolygons; }; /** BSP interior node implementation */ class BspInterior : public BspNode { friend class BspTree; public: /** Standard contructor taking split plane as argument. */ BspInterior(const Plane3 &plane); /** @return false since it is an interior node */ bool IsLeaf() const; BspNode *GetBack(); BspNode *GetFront(); Plane3 *GetPlane(); void ReplaceChildLink(BspNode *oldChild, BspNode *newChild); void SetupChildLinks(BspNode *b, BspNode *f); /** Splits polygons with respect to the split plane. @param polys the polygons to be split. the polygons are consumed and distributed to the containers frontPolys, backPolys, coincident. @param frontPolys returns the polygons in the front of the split plane @param backPolys returns the polygons in the back of the split plane @param coincident returns the polygons coincident to the split plane @param storePolys if the polygons should be stored in the node @returns the number of splits */ int SplitPolygons(PolygonContainer &polys, PolygonContainer &frontPolys, PolygonContainer &backPolys, PolygonContainer &coincident, const bool storePolys = false); /** Stores polygon in node or discards them according to storePolys. @param polys the polygons @param storePolys if the polygons should be stored or discarded */ void ProcessPolygon(Polygon3 **poly, const bool storePolys); friend ostream &operator<<(ostream &s, const BspInterior &A) { return s << A.mPlane; } protected: /// Splitting plane corresponding to this node Plane3 mPlane; /// back node BspNode *mBack; /// front node BspNode *mFront; }; /** BSP leaf node implementation. */ class BspLeaf : public BspNode { friend class BspTree; public: BspLeaf(); BspLeaf(BspViewCell *viewCell); BspLeaf(BspInterior *parent); BspLeaf(BspInterior *parent, BspViewCell *viewCell); /** @return true since it is an interior node */ bool IsLeaf() const; /** Returns pointer of view cell. */ BspViewCell *GetViewCell() const; /** Sets pointer to view cell. */ void SetViewCell(BspViewCell *viewCell); /** Generates new view cell and adds rays to the PVS. @param sampleContributions the number contributions of the sampels @param contributingSampels the number of contributing rays */ void GenerateViewCell(const BoundedRayContainer &rays, int &sampleContributions, int &contributingSamples); protected: /// if NULL this does not correspond to feasible viewcell BspViewCell *mViewCell; }; /** Implementation of the view cell BSP tree. */ class BspTree { public: /** Additional data which is passed down the BSP tree during traversal. */ struct BspTraversalData { /// the current node BspNode *mNode; /// polygonal data for splitting PolygonContainer *mPolygons; /// current depth int mDepth; /// the view cell associated with this subdivsion ViewCell *mViewCell; /// rays piercing this node BoundedRayContainer *mRays; BspTraversalData(): mNode(NULL), mPolygons(NULL), mDepth(0), mViewCell(NULL), mRays(NULL) {} BspTraversalData(BspNode *node, PolygonContainer *polys, const int depth, ViewCell *viewCell, BoundedRayContainer *rays): mNode(node), mPolygons(polys), mDepth(depth), mViewCell(viewCell), mRays(rays) {} }; typedef std::stack BspTraversalStack; /** Default constructor creating an empty tree. @param viewCell view cell corresponding to unbounded space */ BspTree(ViewCell *viewCell); ~BspTree(); const BspTreeStatistics &GetStatistics() const; /** Constructs tree using the given list of view cells. For this type of construction we filter all view cells down the tree. If there is no polygon left, the last split plane decides inside or outside of the viewcell. A pointer to the appropriate view cell is stored within each leaf. Many leafs can point to the same viewcell. */ void Construct(const ViewCellContainer &viewCells); /** Constructs tree using the given list of objects. @note the objects are not taken as view cells, but the view cells are constructed from the subdivision: Each leaf is taken as one viewcell. @param objects list of objects */ void Construct(const ObjectContainer &objects); /** Constructs the tree from a given set of rays. @param sampleRays the set of sample rays the construction is based on @param viewCells if not NULL, new view cells are created in the leafs and stored in the conatainer */ void Construct(const RayContainer &sampleRays); /** Returns list of BSP leaves. */ void CollectLeaves(vector &leaves); /** Returns box which bounds the whole tree. */ AxisAlignedBox3 GetBoundingBox()const; /** Returns root of BSP tree. */ BspNode *GetRoot() const; /** Exports Bsp tree to file. */ bool Export(const string filename); /** Collects the leaf view cells of the tree @param viewCells returns the view cells */ void CollectViewCells(ViewCellContainer &viewCells) const; /** A ray is cast possible intersecting the tree. @param the ray that is cast. @returns the number of intersections with objects stored in the tree. */ int CastRay(Ray &ray); /** Set to true if new view cells shall be generated in each leaf. */ void SetGenerateViewCells(int generateViewCells); /// bsp tree construction types enum {FROM_INPUT_VIEW_CELLS, FROM_SCENE_GEOMETRY, FROM_RAYS}; /** Returns statistics. */ BspTreeStatistics &GetStat(); /** finds neighbouring leaves of this tree node. */ int FindNeighbors(BspNode *n, vector &neighbors, const bool onlyUnmailed) const; /** Constructs geometry associated with the half space intersections leading to this node. */ void ConstructGeometry(BspNode *n, PolygonContainer &cell) const; /** Construct geometry of view cell. */ void ConstructGeometry(BspViewCell *vc, PolygonContainer &cell) const; /** Returns random leaf of BSP tree. @param halfspace defines the halfspace from which the leaf is taken. */ BspLeaf *GetRandomLeaf(const Plane3 &halfspace); /** Returns random leaf of BSP tree. @param onlyUnmailed if only unmailed leaves should be returned. */ BspLeaf *GetRandomLeaf(const bool onlyUnmailed = false); /** Adds halfspace to cell definition. @param side indicates which side of halfspace is added */ void AddHalfspace(PolygonContainer &cell, vector &planes, vector &sides, const Plane3 &halfspace, const bool side) const; /** Returns true if merge criteria are reached. */ bool ShouldMerge(BspLeaf *front, BspLeaf *back) const; /** Merges view cells based on some criteria E.g., empty view cells can pe purged, view cells which have a very similar PVS can be merged to one larger view cell. @returns true if merge was successful. */ bool MergeViewCells(BspLeaf *front, BspLeaf *back) const; /** Traverses tree and counts PVS size of all view cells */ int CountViewCellPvs() const; protected: // -------------------------------------------------------------- // For sorting objects // -------------------------------------------------------------- struct SortableEntry { enum {POLY_MIN, POLY_MAX}; int type; float value; Polygon3 *poly; SortableEntry() {} SortableEntry(const int t, const float v, Polygon3 *poly): type(t), value(v), poly(poly) {} bool operator<(const SortableEntry &b) const { return value < b.value; } }; /** Evaluates tree stats in the BSP tree leafs. */ void EvaluateLeafStats(const BspTraversalData &data); /** Subdivides node with respect to the traversal data. @param tStack current traversal stack @param tData traversal data also holding node to be subdivided @returns new root of the subtree */ BspNode *Subdivide(BspTraversalStack &tStack, BspTraversalData &tData); /** Constructs the tree from the given list of polygons and rays. @param polys stores set of polygons on which subdivision may be based @param rays storesset of rays on which subdivision may be based */ void Construct(PolygonContainer *polys, BoundedRayContainer *rays); /** Selects the best possible splitting plane. @param leaf the leaf to be split @param polys the polygon list on which the split decition is based @param rays ray container on which selection may be based @note the polygons can be reordered in the process @returns the split plane */ Plane3 SelectPlane(BspLeaf *leaf, PolygonContainer &polys, const BoundedRayContainer &ray); /** Evaluates the contribution of the candidate split plane. @param canditatePlane the candidate split plane @param polys the polygons the split can be based on @param rays the rays the split can be based on @returns the cost of the candidate split plane */ float SplitPlaneCost(const Plane3 &candidatePlane, const PolygonContainer &polys, const BoundedRayContainer &rays) const; /** Strategies where the effect of the split plane is tested on all input rays. @returns the cost of the candidate split plane */ float SplitPlaneCost(const Plane3 &candidatePlane, const PolygonContainer &polys) const; /** Strategies where the effect of the split plane is tested on all input polygons. @returns the cost of the candidate split plane */ float SplitPlaneCost(const Plane3 &candidatePlane, const BoundedRayContainer &polys) const; /** Filters next view cell down the tree and inserts it into the appropriate leaves (i.e., possibly more than one leaf). */ void InsertViewCell(ViewCell *viewCell); /** Inserts polygons down the tree. The polygons are filtered until a leaf is reached, then further subdivided. */ void InsertPolygons(PolygonContainer *polys); /** Subdivide leaf. @param leaf the leaf to be subdivided @param polys the polygons to be split @param frontPolys returns the polygons in front of the split plane @param backPolys returns the polygons in the back of the split plane @param rays the polygons to be filtered @param frontRays returns the polygons in front of the split plane @param backRays returns the polygons in the back of the split plane @returns the root of the subdivision */ BspInterior *SubdivideNode(BspLeaf *leaf, PolygonContainer &polys, PolygonContainer &frontPolys, PolygonContainer &backPolys, PolygonContainer &coincident, BoundedRayContainer &rays, BoundedRayContainer &frontRays, BoundedRayContainer &backRays); /** Filters polygons down the tree. @param node the current BSP node @param polys the polygons to be filtered @param frontPolys returns the polygons in front of the split plane @param backPolys returns the polygons in the back of the split plane */ void FilterPolygons(BspInterior *node, PolygonContainer *polys, PolygonContainer *frontPolys, PolygonContainer *backPolys); /** Selects the split plane in order to construct a tree with certain characteristics (e.g., balanced tree, least splits, 2.5d aligned) @param polygons container of polygons @param rays bundle of rays on which the split can be based @param maxTests the maximal number of candidate tests */ Plane3 SelectPlaneHeuristics(PolygonContainer &polys, const BoundedRayContainer &rays, const int maxTests); /** Extracts the meshes of the objects and adds them to polygons. Adds object aabb to the aabb of the tree. @param maxPolys the maximal number of objects to be stored as polygons @returns the number of polygons */ int AddToPolygonSoup(const ObjectContainer &objects, PolygonContainer &polys, int maxObjects = 0); /** Extracts the meshes of the view cells and and adds them to polygons. Adds view cell aabb to the aabb of the tree. @param maxPolys the maximal number of objects to be stored as polygons @returns the number of polygons */ int AddToPolygonSoup(const ViewCellContainer &viewCells, PolygonContainer &polys, int maxObjects = 0); /** Extract polygons of this mesh and add to polygon container. @param mesh the mesh that drives the polygon construction @param parent the parent intersectable this polygon is constructed from @returns number of polygons */ int AddMeshToPolygons(Mesh *mesh, PolygonContainer &polys, MeshInstance *parent); /** returns next candidate index and reorders polygons so no candidate is chosen two times @param the current candidate index @param max the range of candidates */ int GetNextCandidateIdx(int currentIdx, PolygonContainer &polys); /** Helper function which extracts a view cell on the front and the back of the split plane. @param backViewCell returns view cell on the back of the split plane @param frontViewCell returns a view cell on the front of the split plane @param coincident container of polygons coincident to the split plane @param splitPlane the split plane which decides about back and front @param extractBack if a back view cell is extracted @param extractFront if a front view cell is extracted */ void ExtractViewCells(ViewCell **backViewCell, ViewCell **frontViewCell, const PolygonContainer &coincident, const Plane3 splitPlane, const bool extractBack, const bool extractFront) const; /** Computes best cost ratio for the suface area heuristics for axis aligned splits. This heuristics minimizes the cost for ray traversal. @param polys the polygons guiding the ratio computation @param box the bounding box of the leaf @param axis the current split axis @param position returns the split position @param objectsBack the number of objects in the back of the split plane @param objectsFront the number of objects in the front of the split plane */ float BestCostRatio(const PolygonContainer &polys, const AxisAlignedBox3 &box, const int axis, float &position, int &objectsBack, int &objectsFront) const; /** Sorts split candidates for surface area heuristics for axis aligned splits. @param polys the input for choosing split candidates @param axis the current split axis @param splitCandidates returns sorted list of split candidates */ void SortSplitCandidates(const PolygonContainer &polys, const int axis, vector &splitCandidates) const; /** Selects an axis aligned split plane. Returns true if split is valied */ bool SelectAxisAlignedPlane(Plane3 &plane, const PolygonContainer &polys) const; /** Bounds ray and returns minT and maxT. @returns true if ray hits BSP tree bounding box */ bool BoundRay(const Ray &ray, float &minT, float &maxT) const; /** Subdivides the rays into front and back rays according to the split plane. @param plane the split plane @param rays contains the rays to be split. The rays are distributed into front and back rays. @param frontRays returns rays on the front side of the plane @param backRays returns rays on the back side of the plane @returns the number of splits */ int SplitRays(const Plane3 &plane, BoundedRayContainer &rays, BoundedRayContainer &frontRays, BoundedRayContainer &backRays); /** Extracts the split planes representing the space bounded by node n. */ void ExtractSplitPlanes(BspNode *n, vector &planes, vector &sides) const; int CountPvs(const BoundedRayContainer &rays) const; float PvsValue(Intersectable &obj, const int cf, const int frontId, const int backId, const int frontAndBackId) const; /// Pointer to the root of the tree BspNode *mRoot; /// Pointer to the root cell of the viewspace // ViewCell *mRootCell; BspTreeStatistics mStat; /// Strategies for choosing next split plane. enum {NO_STRATEGY = 0, RANDOM_POLYGON = 1, AXIS_ALIGNED = 2, LEAST_SPLITS = 4, BALANCED_POLYS = 8, BALANCED_VIEW_CELLS = 16, LARGEST_POLY_AREA = 32, VERTICAL_AXIS = 64, BLOCKED_RAYS = 128, LEAST_RAY_SPLITS = 256, BALANCED_RAYS = 512, PVS = 1024 }; /// box around the whole view domain AxisAlignedBox3 mBox; /// view cell corresponding to unbounded space ViewCell *mRootCell; /// should view cells be stored or generated in the leaves? bool mGenerateViewCells; /// if rays should be stored that are piercing this view cell bool mStorePiercingRays; public: /// Parses the environment and stores the global BSP tree parameters static void ParseEnvironment(); /// maximal number of polygons before subdivision termination static int sTermMaxPolygons; /// maximal number of rays before subdivision termination static int sTermMaxRays; /// maximal possible depth static int sTermMaxDepth; /// strategy to get the best split plane static int sSplitPlaneStrategy; /// number of candidates evaluated for the next split plane static int sMaxCandidates; /// BSP tree construction method static int sConstructionMethod; /// maximal number of polygons for axis aligned split static int sTermMaxPolysForAxisAligned; /// maximal number of rays for axis aligned split static int sTermMaxRaysForAxisAligned; /// maximal number of objects for axis aligned split static int sTermMaxObjectsForAxisAligned; /// axis aligned split criteria static float sCt_div_ci; static float sSplitBorder; static float sMaxCostRatio; // factors guiding the split plane heuristics static float sLeastSplitsFactor; static float sBalancedPolysFactor; static float sBalancedViewCellsFactor; static float sVerticalSplitsFactor; static float sLargestPolyAreaFactor; static float sBlockedRaysFactor; static float sLeastRaySplitsFactor; static float sBalancedRaysFactor; static float sPvsFactor; /// if polygons should be stored in the tree static bool sStoreSplitPolys; /// threshold where view cells are merged static int sMinPvsDif; private: /** Evaluates split plane classification with respect to the plane's contribution for a balanced tree. */ static float sLeastPolySplitsTable[4]; /** Evaluates split plane classification with respect to the plane's contribution for a minimum number splits in the tree. */ static float sBalancedPolysTable[4]; /** Evaluates split plane classification with respect to the plane's contribution for a minimum number of ray splits. */ static float sLeastRaySplitsTable[5]; /** Evaluates split plane classification with respect to the plane's contribution for balanced rays. */ static float sBalancedRaysTable[5]; }; #endif