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

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