source: GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h @ 2115

Revision 2115, 26.1 KB checked in by mattausch, 17 years ago (diff)

changed pvs loading: loading objects in a first pass

Line 
1#ifndef _BvHierarchy_H__
2#define _BvHierarchy_H__
3
4#include <stack>
5
6#include "Mesh.h"
7#include "Containers.h"
8#include "Statistics.h"
9#include "VssRay.h"
10#include "RayInfo.h"
11#include "gzstream.h"
12#include "SubdivisionCandidate.h"
13#include "AxisAlignedBox3.h"
14#include "IntersectableWrapper.h"
15#include "HierarchyManager.h"
16
17
18namespace GtpVisibilityPreprocessor {
19
20
21class ViewCellLeaf;
22class Plane3;
23class AxisAlignedBox3;
24class Ray;
25class ViewCellsStatistics;
26class ViewCellsManager;
27class MergeCandidate;
28class Beam;
29class ViewCellsTree;
30class Environment;
31class BvhInterior;
32class BvhLeaf;
33class BvhNode;
34class BvhTree;
35class VspTree;
36class ViewCellsContainer;
37class HierarchyManager;
38
39
40/** View space partition statistics.
41*/
42class BvhStatistics: public StatisticsBase
43{
44public:
45       
46        /// Constructor
47        BvhStatistics()
48        {
49                Reset();
50        }
51
52        int Nodes() const {return nodes;}
53        int Interior() const { return nodes / 2; }
54        int Leaves() const { return (nodes / 2) + 1; }
55       
56        double AvgDepth() const
57        { return accumDepth / (double)Leaves(); }
58
59        double AvgObjectRefs() const
60        { return objectRefs / (double)Leaves(); }
61
62        double AvgRayRefs() const
63        { return rayRefs / (double)Leaves(); }
64
65       
66        void Reset()
67        {
68                nodes = 0;
69                splits = 0;
70                maxDepth = 0;
71
72                minDepth = 99999;
73                accumDepth = 0;
74        maxDepthNodes = 0;
75                minProbabilityNodes = 0;
76                maxCostNodes = 0;
77                ///////////////////
78                minObjectsNodes = 0;
79                maxObjectRefs = 0;
80                minObjectRefs = 999999999;
81                objectRefs = 0;
82                emptyNodes = 0;
83
84                ///////////////////
85                minRaysNodes = 0;
86                maxRayRefs = 0;
87                minRayRefs = 999999999;
88                rayRefs = 0;
89                maxRayContriNodes = 0;
90                mGlobalCostMisses = 0;
91        }
92
93
94public:
95
96        // total number of nodes
97        int nodes;
98        // number of splits
99        int splits;
100        // maximal reached depth
101        int maxDepth;
102        // minimal depth
103        int minDepth;
104        // max depth nodes
105        int maxDepthNodes;
106        // accumulated depth (used to compute average)
107        int accumDepth;
108        // minimum area nodes
109        int minProbabilityNodes;
110        /// nodes termination because of max cost ratio;
111        int maxCostNodes;
112        // global cost ratio violations
113        int mGlobalCostMisses;
114
115        //////////////////
116        // nodes with minimum objects
117        int minObjectsNodes;
118        // max number of rays per node
119        int maxObjectRefs;
120        // min number of rays per node
121        int minObjectRefs;
122        /// object references
123        int objectRefs;
124        // leaves with no objects
125        int emptyNodes;
126
127        //////////////////////////
128        // nodes with minimum rays
129        int minRaysNodes;
130        // max number of rays per node
131        int maxRayRefs;
132        // min number of rays per node
133        int minRayRefs;
134        /// object references
135        int rayRefs;
136        /// nodes with max ray contribution
137        int maxRayContriNodes;
138
139        void Print(ostream &app) const;
140
141        friend ostream &operator<<(ostream &s, const BvhStatistics &stat)
142        {
143                stat.Print(s);
144                return s;
145        }
146};
147
148
149/**
150    VspNode abstract class serving for interior and leaf node implementation
151*/
152class BvhNode: public Intersectable
153{
154public:
155       
156        // types of vsp nodes
157        enum {Interior, Leaf};
158
159        BvhNode();
160        BvhNode(const AxisAlignedBox3 &bbox);
161        BvhNode(const AxisAlignedBox3 &bbox, BvhInterior *parent);
162
163        virtual ~BvhNode(){};
164
165        /** Determines whether this node is a leaf or not
166                @return true if leaf
167        */
168        virtual bool IsLeaf() const = 0;
169
170        /** Determines whether this node is a root
171                @return true if root
172        */
173        virtual bool IsRoot() const;
174
175        /** Returns parent node.
176        */
177        BvhInterior *GetParent();
178
179        /** Sets parent node.
180        */
181        void SetParent(BvhInterior *parent);
182
183        /** collects all objects under this node.
184        */
185        virtual void CollectObjects(ObjectContainer &objects) = 0;
186
187        /** The bounding box specifies the node extent.
188        */
189        inline
190        AxisAlignedBox3 GetBoundingBox() const
191        { return mBoundingBox; }
192
193        /** Sets bouding box of this node.
194        */
195        inline
196        void SetBoundingBox(const AxisAlignedBox3 &boundingBox)
197        { mBoundingBox = boundingBox; }
198
199        /** Cost of mergin this node.
200        */
201        float GetMergeCost() {return (float)-mTimeStamp; }
202
203        virtual int GetRandomEdgePoint(Vector3 &point, Vector3 &normal);
204
205        inline int GetTimeStamp() const { return mTimeStamp; }
206        inline void SetTimeStamp(const int timeStamp) { mTimeStamp = timeStamp; };
207
208
209        ////////////////////////
210        //-- inherited functions from Intersectable
211
212        AxisAlignedBox3 GetBox() const { return mBoundingBox; }
213       
214        int CastRay(Ray &ray) { return 0; }
215       
216        bool IsConvex() const { return true; }
217        bool IsWatertight() const { return true; }
218        float IntersectionComplexity() { return 1; }
219 
220        int NumberOfFaces() const { return 6; };
221       
222        int GetRandomSurfacePoint(GtpVisibilityPreprocessor::Vector3 &point,
223                                                          GtpVisibilityPreprocessor::Vector3 &normal)
224        {
225                // TODO
226                return 0;
227        }
228
229        int GetRandomVisibleSurfacePoint(GtpVisibilityPreprocessor::Vector3 &point,
230                                                                         GtpVisibilityPreprocessor::Vector3 &normal,
231                                                                         const GtpVisibilityPreprocessor::Vector3 &viewpoint,
232                                                                         const int maxTries)
233        {
234                // TODO
235                return 0;
236        }
237 
238        int Type() const
239        {
240                return Intersectable::BVH_INTERSECTABLE;
241        }
242
243        ostream &Describe(ostream &s) { return s; }
244
245        ///////////////////////////////////
246
247        float mRenderCost;
248
249protected:
250       
251        /// the bounding box of the node
252        AxisAlignedBox3 mBoundingBox;
253        /// parent of this node
254        BvhInterior *mParent;
255        int mTimeStamp;
256};
257
258
259/** BSP interior node implementation
260*/
261class BvhInterior: public BvhNode
262{
263public:
264        /** Standard contructor taking a bounding box as argument.
265        */
266        BvhInterior(const AxisAlignedBox3 &bbox);
267        BvhInterior(const AxisAlignedBox3 &bbox, BvhInterior *parent);
268
269        ~BvhInterior();
270        /** @return false since it is an interior node
271        */
272        bool IsLeaf() const;
273       
274        BvhNode *GetBack() { return mBack; }
275        BvhNode *GetFront() { return mFront; }
276
277        /** Replace front or back child with new child.
278        */
279        void ReplaceChildLink(BvhNode *oldChild, BvhNode *newChild);
280
281        /** Replace front and back child.
282        */
283        void SetupChildLinks(BvhNode *front, BvhNode *back);
284
285        friend ostream &operator<<(ostream &s, const BvhInterior &A)
286        {
287                return s << A.mBoundingBox;
288        }
289
290        virtual void CollectObjects(ObjectContainer &objects);
291
292protected:
293
294        /// back node
295        BvhNode *mBack;
296        /// front node
297        BvhNode *mFront;
298};
299
300
301/** BSP leaf node implementation.
302*/
303class BvhLeaf: public BvhNode
304{
305public:
306        /** Standard contructor taking a bounding box as argument.
307        */
308        BvhLeaf(const AxisAlignedBox3 &bbox);
309        BvhLeaf(const AxisAlignedBox3 &bbox, BvhInterior *parent);
310        BvhLeaf(const AxisAlignedBox3 &bbox, BvhInterior *parent, const int numObjects);
311
312        ~BvhLeaf();
313
314        /** @return true since it is an interior node
315        */
316        bool IsLeaf() const;
317       
318        SubdivisionCandidate *GetSubdivisionCandidate()// const
319        {
320                return mSubdivisionCandidate;
321        }
322
323        void SetSubdivisionCandidate(SubdivisionCandidate *candidate)
324        {
325                mSubdivisionCandidate = candidate;
326        }
327       
328        virtual void CollectObjects(ObjectContainer &objects);
329
330        /** Returns level of the hierarchy that is "active" right now.
331        */
332        BvhNode *GetActiveNode()
333        {
334                return mActiveNode;
335        }
336
337        /** Returns level of the hierarchy that is "active" right now.
338        */
339        void SetActiveNode(BvhNode *node)
340        {
341                mActiveNode = node;
342        }
343
344public:
345  // gl list use to store the geometry on the gl server
346  int mGlList;
347 
348  /// objects
349  ObjectContainer mObjects;
350 
351 
352protected:
353 
354  /// pointer to a split plane candidate splitting this leaf
355  SubdivisionCandidate *mSubdivisionCandidate;
356 
357  /// the active node which will be accounted for in the pvs
358  BvhNode *mActiveNode;
359};
360
361
362/** View Space Partitioning tree.
363*/
364class BvHierarchy
365{
366        friend class ViewCellsParseHandlers;
367        friend class HierarchyManager;
368
369protected:
370        struct SortableEntry;
371        typedef vector<SortableEntry> SortableEntryContainer;
372
373public:
374       
375        /** Additional data which is passed down the BSP tree during traversal.
376        */
377        class BvhTraversalData
378        { 
379        public:
380               
381                BvhTraversalData():
382                mNode(NULL),
383                mDepth(0),
384                mMaxCostMisses(0),
385                mAxis(0),
386                mNumRays(0),
387                mCorrectedPvs(0),
388                mPvs(0),
389                mCorrectedVolume(0),
390                mVolume(0)
391                {
392                        for (int i = 0; i < 4; ++ i)
393                                mSortedObjects[i] = NULL;
394                }
395               
396                BvhTraversalData(BvhLeaf *node,
397                                                 const int depth,
398                                                 const float v,
399                                                 const int numRays):
400                mNode(node),
401                mDepth(depth),
402                mMaxCostMisses(0),
403                mAxis(0),
404                mNumRays(numRays),
405                mCorrectedPvs(0),
406                mPvs(0),
407                mCorrectedVolume(0),
408                mVolume(v)
409                {
410                        for (int i = 0; i < 4; ++ i)
411                                mSortedObjects[i] = NULL;
412                }
413
414                /** Deletes contents and sets them to NULL.
415                */
416                void Clear()
417                {
418                        DEL_PTR(mNode);
419                        for (int i = 0; i < 4; ++ i)
420                                DEL_PTR(mSortedObjects[i]);
421                }
422
423                /// the current node
424                BvhLeaf *mNode;
425                /// current depth
426                int mDepth;
427                /// the volume of the node
428                float mVolume;
429                /// the corrected volume
430                float mCorrectedVolume;
431                /// how often this branch has missed the max-cost ratio
432                int mMaxCostMisses;
433                /// current axis
434                int mAxis;
435                /// number of rays
436                int mNumRays;
437                /// parent Pvs;
438                float mPvs;
439                /// parent pvs correction factor
440                float mCorrectedPvs;
441
442                /// the sorted objects for the three dimensions
443                ObjectContainer *mSortedObjects[4];             
444    };
445
446
447        /** Candidate for a object space split.
448        */
449        class BvhSubdivisionCandidate: public SubdivisionCandidate
450        { 
451        public:
452
453        BvhSubdivisionCandidate(const BvhTraversalData &tData): mParentData(tData)
454                {};
455
456                ~BvhSubdivisionCandidate()
457                {
458                        mParentData.Clear();
459                }
460
461                int Type() const { return OBJECT_SPACE; }
462       
463                void EvalCandidate(bool computeSplitplane = true)
464                {
465            mDirty = false;
466                        sBvHierarchy->EvalSubdivisionCandidate(*this, computeSplitplane);
467                }
468
469                bool Apply(SplitQueue &splitQueue, bool terminationCriteriaMet)
470                {
471                        BvhNode *n = sBvHierarchy->Subdivide(splitQueue, this, terminationCriteriaMet);
472
473                        // local or global termination criteria failed
474                        return !n->IsLeaf();           
475                }
476
477                void CollectDirtyCandidates(SubdivisionCandidateContainer &dirtyList,
478                                                                        const bool onlyUnmailed)
479                {
480                        sBvHierarchy->CollectDirtyCandidates(this, dirtyList, onlyUnmailed);
481                }
482
483                bool GlobalTerminationCriteriaMet() const
484                {
485                        return sBvHierarchy->GlobalTerminationCriteriaMet(mParentData);
486                }
487
488                BvhSubdivisionCandidate(const ObjectContainer &frontObjects,
489                                                                const ObjectContainer &backObjects,
490                                                                const BvhTraversalData &tData):
491                mFrontObjects(frontObjects), mBackObjects(backObjects), mParentData(tData)
492                {}
493
494                float GetPriority() const
495                {
496                        return (float)-mParentData.mDepth;
497                        //return mPriority;
498                }
499
500                /////////////////////////////7
501
502                /// pointer to parent tree.
503                static BvHierarchy *sBvHierarchy;
504
505                /// parent data
506                BvhTraversalData mParentData;
507                /// the objects on the front of the potential split
508                ObjectContainer mFrontObjects;
509                /// the objects on the back of the potential split
510                ObjectContainer mBackObjects;
511                       
512                float mCorrectedFrontPvs;
513                float mCorrectedBackPvs;
514
515                float mCorrectedFrontVolume;
516                float mCorrectedBackVolume;
517        };
518
519        /** Struct for traversing line segment.
520        */
521        struct LineTraversalData
522        {
523                BvhNode *mNode;
524                Vector3 mExitPoint;
525               
526                float mMaxT;
527   
528                LineTraversalData () {}
529                LineTraversalData (BvhNode *n, const Vector3 &p, const float maxt):
530                mNode(n), mExitPoint(p), mMaxT(maxt) {}
531        };
532
533
534        /** Default constructor creating an empty tree.
535        */
536        BvHierarchy();
537
538        /** Default destructor.
539        */
540        ~BvHierarchy();
541
542        /** Returns tree statistics.
543        */
544        const BvhStatistics &GetStatistics() const;
545 
546        /** Returns bounding box of the specified node.
547        */
548        AxisAlignedBox3 GetBoundingBox(BvhNode *node) const;
549
550        /** Reads parameters from environment singleton.
551        */
552        void ReadEnvironment();
553
554        /** Evaluates candidate for splitting.
555        */
556        void EvalSubdivisionCandidate(BvhSubdivisionCandidate &splitData,
557                                                                  bool computeSplitPlane = true);
558
559        /** Returns vector of leaves.
560        */
561        void CollectLeaves(BvhNode *root, vector<BvhLeaf *> &leaves) const;
562
563        /** Returns vector of leaves.
564        */
565        void CollectNodes(BvhNode *root, vector<BvhNode *> &nodes) const;
566
567        /** Returns bounding box of the whole tree (= bbox of root node)
568        */
569        AxisAlignedBox3 GetBoundingBox()const;
570
571        /** Returns root of the view space partitioning tree.
572        */
573        BvhNode *GetRoot() const;
574
575        /** finds neighbouring leaves of this tree node.
576        */
577        int FindNeighbors(BvhLeaf *n,
578                                          vector<BvhLeaf *> &neighbors,
579                                          const bool onlyUnmailed) const;
580
581        /** Returns random leaf of BSP tree.
582                @param halfspace defines the halfspace from which the leaf is taken.
583        */
584        BvhLeaf *GetRandomLeaf(const Plane3 &halfspace);
585
586        /** Returns random leaf of BSP tree.
587                @param onlyUnmailed if only unmailed leaves should be returned.
588        */
589        BvhLeaf *GetRandomLeaf(const bool onlyUnmailed = false);
590
591        /** Casts line segment into the tree.
592                @param origin the origin of the line segment
593                @param termination the end point of the line segment
594                @returns view cells intersecting the line segment.
595        */
596    int CastLineSegment(const Vector3 &origin,
597                                                const Vector3 &termination,
598                                                ViewCellContainer &viewcells);
599               
600        /** Sets pointer to view cells manager.
601        */
602        void SetViewCellsManager(ViewCellsManager *vcm);
603
604        float GetViewSpaceVolume() const;
605        /** Writes tree to output stream
606        */
607        bool Export(OUT_STREAM &stream);
608
609        /** Collects rays associated with the objects.
610        */
611        void CollectRays(const ObjectContainer &objects, VssRayContainer &rays) const;
612
613        /** Intersects box with the tree and returns the number of intersected boxes.
614                @returns number of view cells found
615        */
616        int ComputeBoxIntersections(const AxisAlignedBox3 &box,
617                                                                ViewCellContainer &viewCells) const;
618
619        /** Returns leaf the point pt lies in, starting from root.
620        */
621        BvhLeaf *GetLeaf(Intersectable *obj, BvhNode *root = NULL) const;
622
623        /** Sets a pointer to the view cells tree.
624        */
625        ViewCellsTree *GetViewCellsTree() const { return mViewCellsTree; }
626       
627        /** See Get
628        */
629        void SetViewCellsTree(ViewCellsTree *vt) { mViewCellsTree = vt; }
630
631        /** Returns estimated memory usage of tree.
632        */
633        float GetMemUsage() const;
634
635        /** Sets this node to be an active node.
636        */
637        void SetActive(BvhNode *node) const;
638
639
640        ///////////////////////////
641        // hacks in order to provide interleaved heurisitcs
642
643        BvhNode *SubdivideAndCopy(SplitQueue &tQueue, SubdivisionCandidate *splitCandidate);
644
645        /////////////////////////////////
646
647        static float EvalAbsCost(const ObjectContainer &objects);
648
649        float EvalProb(const ObjectContainer &objects) const;
650
651        void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
652
653        float GetRenderCostIncrementially(BvhNode *node) const;
654
655        void Compress();
656        void CreateUniqueObjectIds();
657
658protected:
659
660        /** Returns true if tree can be terminated.
661        */
662        bool LocalTerminationCriteriaMet(const BvhTraversalData &data) const;
663
664        /** Returns true if global tree can be terminated.
665        */
666        bool GlobalTerminationCriteriaMet(const BvhTraversalData &data) const;
667
668        /** For sorting the objects during the heuristics
669        */
670        struct SortableEntry
671        {
672                Intersectable *mObject;
673                float mPos;
674
675                SortableEntry() {}
676
677                SortableEntry(Intersectable *obj, const float pos):
678                mObject(obj), mPos(pos)
679                {}
680
681                bool operator<(const SortableEntry &b) const
682                {
683                        return mPos < b.mPos;
684                }
685        };
686
687        /** Evaluate balanced object partition.
688        */
689        float EvalLocalObjectPartition(const BvhTraversalData &tData,
690                                                                   const int axis,
691                                                                   ObjectContainer &objectsFront,
692                                                                   ObjectContainer &objectsBack);
693
694        /** Evaluate surface area heuristic for the node.
695        */
696        float EvalSah(const BvhTraversalData &tData,
697                                  const int axis,
698                                  ObjectContainer &objectsFront,
699                                  ObjectContainer &objectsBack);
700
701
702        /** Evaluates render cost of the bv induced by these objects
703        */
704        float EvalRenderCost(const ObjectContainer &objects) const;
705
706        /** Evaluates tree stats in the BSP tree leafs.
707        */
708        void EvaluateLeafStats(const BvhTraversalData &data);
709
710        /** Subdivides node using a best split priority queue.
711            @param tQueue the best split priority queue
712                @param splitCandidate the candidate for the next split
713                @param globalCriteriaMet if the global termination criteria were already met
714                @returns new root of the subtree
715        */
716        BvhNode *Subdivide(SplitQueue &tQueue,
717                                           SubdivisionCandidate *splitCandidate,
718                                           const bool globalCriteriaMet);
719       
720        /** Subdivides leaf.
721                @param sc the subdivisionCandidate holding all necessary data for subdivision           
722               
723                @param frontData returns the traversal data for the front node
724                @param backData returns the traversal data for the back node
725
726                @returns the new interior node = the of the subdivision
727        */
728        BvhInterior *SubdivideNode(const BvhSubdivisionCandidate &sc,
729                                                           BvhTraversalData &frontData,
730                                                           BvhTraversalData &backData);
731
732        /** Splits the objects for the next subdivision.
733                @returns cost for this split
734        */
735        float SelectObjectPartition(const BvhTraversalData &tData,
736                                                                ObjectContainer &frontObjects,
737                                                                ObjectContainer &backObjects,
738                                                                bool useVisibilityBasedHeuristics);
739       
740        /** Writes the node to disk
741                @note: should be implemented as visitor.
742        */
743        void ExportNode(BvhNode *node, OUT_STREAM &stream);
744
745        /** Exports objects associated with this leaf.
746        */
747        void ExportObjects(BvhLeaf *leaf, OUT_STREAM &stream);
748
749        /** Associates the objects with their bvh leaves.
750        */
751        static void AssociateObjectsWithLeaf(BvhLeaf *leaf);
752
753
754        /////////////////////////////
755        // Helper functions for local cost heuristics
756       
757        /** Prepare split candidates for cost heuristics using axis aligned splits.
758                @param node the current node
759                @param axis the current split axis
760        */
761        void PrepareLocalSubdivisionCandidates(const BvhTraversalData &tData,
762                                                                                   const int axis);
763
764        static void CreateLocalSubdivisionCandidates(const ObjectContainer &objects,
765                                                                                                 SortableEntryContainer **subdivisionCandidates,
766                                                                                                 const bool sort,
767                                                                                                 const int axis);
768
769        float EvalPriority(const BvhSubdivisionCandidate &splitCandidate,
770                                           const float renderCostDecr,
771                                           const float oldRenderCost) const;
772
773        /** Computes object partition with the best cost according to the heurisics.
774                @param tData the traversal data
775                @param axis the split axis
776                @param objectsFront the objects in the front child bv
777                @param objectsBack the objects in the back child bv
778                @param backObjectsStart the iterator marking the position where the back objects begin
779
780                @returns relative cost (relative to parent cost)
781        */
782        float EvalLocalCostHeuristics(const BvhTraversalData &tData,
783                                                                  const int axis,
784                                                                  ObjectContainer &objectsFront,
785                                                                  ObjectContainer &objectsBack);
786
787        /** Evaluates the contribution to the front and back volume
788                when this object is changing sides in the bvs.
789
790                @param object the object
791                @param volLeft updates the left pvs
792                @param volPvs updates the right pvs
793        */
794        void EvalHeuristicsContribution(Intersectable *obj,
795                                                                        float &volLeft,
796                                                                        float &volRight);
797
798        /** Prepares objects for the cost heuristics.
799                @returns sum of volume of associated view cells
800        */
801        float PrepareHeuristics(const BvhTraversalData &tData, const int axis);
802       
803        /** Evaluates cost for a leaf given the surface area heuristics.
804        */
805        float EvalSahCost(BvhLeaf *leaf) const;
806
807        ////////////////////////////////////////////////
808
809
810        /** Prepares construction for vsp and osp trees.
811        */
812        AxisAlignedBox3 EvalBoundingBox(const ObjectContainer &objects,
813                                                                        const AxisAlignedBox3 *parentBox = NULL) const;
814
815        /** Collects list of invalid candidates. Candidates
816                are invalidated by a view space subdivision step
817                that affects this candidate.
818        */
819        void CollectDirtyCandidates(BvhSubdivisionCandidate *sc,
820                                                                vector<SubdivisionCandidate *> &dirtyList,
821                                                                const bool onlyUnmailed);
822
823        /** Collect view cells which see this bvh leaf.
824        */
825        int CollectViewCells(const ObjectContainer &objects,
826                                                 ViewCellContainer &viewCells,
827                                                 const bool setCounter,
828                                                 const bool onlyUnmailedRays) const;
829
830        /** Collects view cells which see an object.
831                @param useMailBoxing if mailing should be used and
832                only unmailed object should pass
833                @param setCounter counter for the sweep algorithm
834                @param onlyUnmailedRays if only unmailed rays should be considered
835        */
836        int CollectViewCells(Intersectable *object,
837                                                 ViewCellContainer &viewCells,
838                                                 const bool useMailBoxing,
839                                                 const bool setCounter,
840                                                 const bool onlyUnmailedRays) const;
841
842        /** Counts the view cells of this object. note: only
843                counts unmailed objects.
844        */
845        int CountViewCells(Intersectable *obj) const;
846
847        /** Counts the view cells seen by this bvh leaf
848        */
849        int CountViewCells(const ObjectContainer &objects) const;
850
851        /** Evaluates increase in pvs size.
852        */
853        int EvalPvsEntriesIncr(BvhSubdivisionCandidate &splitCandidate, const float avgRayContri) const;
854
855        /** Rays will be clipped to the bounding box.
856        */
857        void PreprocessRays(BvhLeaf *root,
858                                                const VssRayContainer &sampleRays,
859                                                RayInfoContainer &rays);
860
861        /** Print the subdivision stats in the subdivison log.
862        */
863        void PrintSubdivisionStats(const SubdivisionCandidate &tData);
864
865        /** Prints out the stats for this subdivision.
866        */
867        void AddSubdivisionStats(const int viewCells,
868                                                         const float renderCostDecr,
869                                                         const float totalRenderCost);
870
871        /** Stores rays with objects that see the rays.
872        */
873        int AssociateObjectsWithRays(const VssRayContainer &rays) const;
874
875        /** Tests if object is in this leaf.
876                @note: assumes that objects are sorted by their id.
877        */
878        bool IsObjectInLeaf(BvhLeaf *, Intersectable *object) const;
879
880        /** Prepares the construction of the bv hierarchy and returns
881                the first subdivision candidate.
882        */
883        void PrepareConstruction(SplitQueue &tQueue,
884                                                         const VssRayContainer &sampleRays,
885                                                         const ObjectContainer &objects);
886
887        /** Resets bv hierarchy. E.g. deletes root and resets stats.
888        */
889        void Reset(SplitQueue &tQueue,
890                           const VssRayContainer &rays,
891                           const ObjectContainer &objects);
892
893        /** Evaluates volume of view cells that see the objects.
894        */
895        float EvalViewCellsVolume(const ObjectContainer &objects) const;
896
897        /** Assigns or newly creates initial list of sorted objects.
898        */
899        void AssignInitialSortedObjectList(BvhTraversalData &tData,
900                                                                           const ObjectContainer &objects);
901
902        /** Assigns sorted objects to front and back data.
903        */
904        void AssignSortedObjects(const BvhSubdivisionCandidate &sc,
905                                                         BvhTraversalData &frontData,
906                                                         BvhTraversalData &backData);
907       
908        /** Creates new root of hierarchy and computes bounding box.
909                Has to be called before the preparation of the subdivision.
910        */
911        void Initialise(const ObjectContainer &objects);
912
913
914        ////////////////////
915        // initial subdivision
916
917        /** Makes an initial parititon of the object space based on
918                some criteria (size, shader)
919        */
920        void ApplyInitialSubdivision(SubdivisionCandidate *firstCandidate,
921                                                                 vector<SubdivisionCandidate *> &candidateContainer);
922
923        void ApplyInitialSplit(const BvhTraversalData &tData,
924                                                   ObjectContainer &frontObjects,
925                                                   ObjectContainer &backObjects);
926
927        bool InitialTerminationCriteriaMet(const BvhTraversalData &tData) const;
928
929        /** Sets the bvh node ids.
930        */
931        void SetUniqueNodeIds();
932
933protected:
934       
935        /// pre-sorted subdivision candidtes for all three directions.
936        vector<SortableEntry> *mGlobalSubdivisionCandidates[3];
937        /// pointer to the hierarchy of view cells
938        ViewCellsTree *mViewCellsTree;
939        /// The view cells manager
940        ViewCellsManager *mViewCellsManager;
941        /// candidates for placing split planes during cost heuristics
942        vector<SortableEntry> *mSubdivisionCandidates;
943        /// Pointer to the root of the tree
944        BvhNode *mRoot;
945        /// Statistics for the object space partition
946        BvhStatistics mBvhStats;       
947        /// box around the whole view domain
948        AxisAlignedBox3 mBoundingBox;
949        /// the hierarchy manager
950        HierarchyManager *mHierarchyManager;
951
952
953        ////////////////////
954        //-- local termination criteria
955
956        /// maximal possible depth
957        int mTermMaxDepth;
958        /// mininum probability
959        float mTermMinProbability;
960        /// minimal number of objects
961        int mTermMinObjects;
962        /// maximal acceptable cost ratio
963        float mTermMaxCostRatio;
964        /// tolerance value indicating how often the max cost ratio can be failed
965        int mTermMissTolerance;
966        /// minimum number of rays
967        int mTermMinRays;
968
969
970        ////////////////////
971        //-- global termination criteria
972
973        /// the minimal accepted global cost ratio
974        float mTermMinGlobalCostRatio;
975        //// number of accepted misses of the global cost ratio
976        int mTermGlobalCostMissTolerance;
977        /// maximal number of view cells
978        int mTermMaxLeaves;
979        /// maximal tree memory
980        float mMaxMemory;
981        /// the tree is out of memory
982        bool mOutOfMemory;
983
984
985        ////////////////////////////////////////
986        //-- split heuristics based parameters
987       
988        /// if a heuristics should be used for finding a split plane
989    bool mUseCostHeuristics;
990        /// if sah heuristcs should be used for finding a split plane
991        bool mUseSah;
992    /// balancing factor for PVS criterium
993        float mCtDivCi;
994        /// if only driving axis should be used for split
995        bool mOnlyDrivingAxis;
996        /// current time stamp (used for keeping split history)
997        int mTimeStamp;
998        // if rays should be stored in leaves
999        bool mStoreRays;
1000        // subdivision stats output file
1001        ofstream  mSubdivisionStats;
1002        /// keeps track of cost during subdivision
1003        float mTotalCost;
1004        int mPvsEntries;
1005        /// keeps track of overall pvs size during subdivision
1006        int mTotalPvsSize;
1007        /// number of currenly generated view cells
1008        int mCreatedLeaves;
1009        /// represents min and max band for sweep
1010        float mSplitBorder;
1011        /// weight between render cost decrease and node render cost
1012        float mRenderCostDecreaseWeight;
1013
1014        /// if the objects should be sorted in one global step
1015        bool mUseGlobalSorting;
1016
1017        bool mUseBboxAreaForSah;
1018
1019        //SortableEntryContainer *mSortedObjects[4];
1020
1021        int mMinRaysForVisibility;
1022
1023        /// constant value for driving the heuristics
1024        float mMemoryConst;
1025
1026        int mMaxTests;
1027
1028        bool mIsInitialSubdivision;
1029
1030        bool mApplyInitialPartition;
1031       
1032        int mInitialMinObjects;
1033        float mInitialMaxAreaRatio;
1034        float mInitialMinArea;
1035};
1036
1037}
1038
1039#endif
Note: See TracBrowser for help on using the repository browser.