source: GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h @ 1705

Revision 1705, 27.7 KB checked in by mattausch, 18 years ago (diff)
Line 
1#ifndef _VspTree_H__
2#define _VspTree_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 "HierarchyManager.h"
14
15
16namespace GtpVisibilityPreprocessor {
17
18class ViewCellLeaf;
19class Plane3;
20class AxisAlignedBox3;
21class Ray;
22class ViewCellsStatistics;
23class ViewCellsManager;
24class MergeCandidate;
25class Beam;
26class ViewCellsTree;
27class Environment;
28class VspInterior;
29class VspLeaf;
30class VspNode;
31class KdNode;
32class KdInterior;
33class KdLeaf;
34class HierarchyManager;
35class KdIntersectable;
36class KdTree;
37class VspTree;
38class KdTreeStatistics;
39
40
41/** View space partition statistics.
42*/
43class VspTreeStatistics: public StatisticsBase
44{
45public:
46        // total number of nodes
47        int nodes;
48        // number of splits
49        int splits[3];
50       
51        // totals number of rays
52        int rays;
53        // maximal reached depth
54        int maxDepth;
55        // minimal depth
56        int minDepth;
57       
58        // max depth nodes
59        int maxDepthNodes;
60        // minimum depth nodes
61        int minDepthNodes;
62        // max depth nodes
63        int minPvsNodes;
64        // nodes with minimum PVS
65        int minRaysNodes;
66        // max ray contribution nodes
67        int maxRayContribNodes;
68        // minimum area nodes
69        int minProbabilityNodes;
70        /// nodes termination because of max cost ratio;
71        int maxCostNodes;
72        // max number of rays per node
73        int maxObjectRefs;
74        /// samples contributing to pvs
75        int contributingSamples;
76        /// sample contributions to pvs
77        int sampleContributions;
78        /// largest pvs
79        int maxPvs;
80        /// number of invalid leaves
81        int invalidLeaves;
82        /// number of rays refs
83        int rayRefs;
84        /// overall pvs size
85        int pvs;
86        // accumulated depth (used to compute average)
87        int accumDepth;
88        // global cost ratio violations
89        int mGlobalCostMisses;
90
91        // Constructor
92        VspTreeStatistics()
93        {
94                Reset();
95        }
96
97        int Nodes() const {return nodes;}
98        int Interior() const { return nodes / 2; }
99        int Leaves() const { return (nodes / 2) + 1; }
100       
101        // TODO: computation wrong
102        double AvgDepth() const { return accumDepth / (double)Leaves();};
103        double AvgRays() const { return rayRefs / (double)Leaves();};
104
105        void Reset()
106        {
107                nodes = 0;
108                for (int i = 0; i < 3; ++ i)
109                        splits[i] = 0;
110               
111                maxDepth = 0;
112                minDepth = 99999;
113                accumDepth = 0;
114        pvs = 0;
115                maxDepthNodes = 0;
116                minPvsNodes = 0;
117                minRaysNodes = 0;
118                maxRayContribNodes = 0;
119                minProbabilityNodes = 0;
120                maxCostNodes = 0;
121
122                contributingSamples = 0;
123                sampleContributions = 0;
124
125                maxPvs = 0;
126                invalidLeaves = 0;
127                rayRefs = 0;
128                maxObjectRefs = 0;
129                mGlobalCostMisses = 0;
130        }
131
132        void Print(ostream &app) const;
133
134        friend ostream &operator<<(ostream &s, const VspTreeStatistics &stat)
135        {
136                stat.Print(s);
137                return s;
138        }
139};
140
141
142/**
143    VspNode abstract class serving for interior and leaf node implementation
144*/
145class VspNode
146{
147public:
148       
149        /// types of vsp nodes
150        enum {Interior, Leaf};
151
152        VspNode();
153        virtual ~VspNode(){};
154        VspNode(VspInterior *parent);
155
156        /** Determines whether this node is a leaf or not
157                @return true if leaf
158        */
159        virtual bool IsLeaf() const = 0;
160
161        virtual int Type() const = 0;
162
163        /** Determines whether this node is a root
164                @return true if root
165        */
166        virtual bool IsRoot() const;
167       
168        /** Returns parent node.
169        */
170        VspInterior *GetParent();
171       
172        /** Sets parent node.
173        */
174        void SetParent(VspInterior *parent);
175
176        /** Returns true if this node is a sibling of node n.
177        */
178        bool IsSibling(VspNode *n) const;
179       
180        /** returns depth of the node.
181        */
182        int GetDepth() const;
183       
184        /** returns true if the whole subtree is valid
185        */
186        bool TreeValid() const;
187
188        void SetTreeValid(const bool v);
189       
190        /** Cost of mergin this node.
191        */
192        float GetMergeCost() {return (float)-mTimeStamp; }
193
194        /////////
195        //-- mailing options
196
197        void Mail() { mMailbox = sMailId; }
198        static void NewMail() { ++ sMailId; }
199        bool Mailed() const { return mMailbox == sMailId; }
200
201
202        static int sMailId;
203        int mMailbox;
204
205        int mTimeStamp;
206
207        int mPvsEntriesIncr;
208        float mMemoryIncr;
209        float mRenderCostDecr;
210
211protected:
212
213        /// if this sub tree is a completely valid view space region
214        bool mTreeValid;
215       
216        /// parent of this node
217        VspInterior *mParent;
218};
219
220
221/** BSP interior node implementation
222*/
223class VspInterior: public VspNode
224{
225public:
226
227        /** Standard contructor taking split plane as argument.
228        */
229        VspInterior(const AxisAlignedPlane &plane);
230
231        ~VspInterior();
232       
233        /** @return false since it is an interior node
234        */
235        bool IsLeaf() const;
236
237        int Type() const;
238
239        VspNode *GetBack();
240        VspNode *GetFront();
241
242        /** Returns split plane.
243        */
244        AxisAlignedPlane GetPlane() const;
245
246        /** Returns position of split plane.
247        */
248        float GetPosition() const;
249
250        /** Returns split axis.
251        */
252        int GetAxis() const;
253
254        /** Replace front or back child with new child.
255        */
256        void ReplaceChildLink(VspNode *oldChild, VspNode *newChild);
257
258        /** Replace front and back child.
259        */
260        void SetupChildLinks(VspNode *front, VspNode *back);
261
262        friend ostream &operator<<(ostream &s, const VspInterior &A)
263        {
264                return s << A.mPlane.mAxis << " " << A.mPlane.mPosition;
265        }
266
267        AxisAlignedBox3 GetBoundingBox() const;
268        void SetBoundingBox(const AxisAlignedBox3 &box);
269
270        /** Computes intersection of this plane with the ray segment.
271        */
272        int ComputeRayIntersection(const RayInfo &rayData, float &t) const
273        {
274                return rayData.ComputeRayIntersection(mPlane.mAxis, mPlane.mPosition, t);
275        }
276
277
278protected:
279        /// bounding box for this interior node: should we really store this?
280        AxisAlignedBox3 mBoundingBox;
281
282        /// Splitting plane corresponding to this node
283        AxisAlignedPlane mPlane;
284
285        /// back node
286        VspNode *mBack;
287        /// front node
288        VspNode *mFront;
289};
290
291
292/** BSP leaf node implementation.
293*/
294class VspLeaf: public VspNode
295{
296        friend VspTree;
297
298public:
299        VspLeaf();
300        VspLeaf(ViewCellLeaf *viewCell);
301        VspLeaf(VspInterior *parent);
302        VspLeaf(VspInterior *parent, ViewCellLeaf *viewCell);
303
304        ~VspLeaf();
305
306        /** @return true since it is an interior node
307        */
308        bool IsLeaf() const;
309       
310        int Type() const;
311
312        /** Returns pointer of view cell.
313        */
314        ViewCellLeaf *GetViewCell() const;
315        /** Sets pointer to view cell.
316        */
317        void SetViewCell(ViewCellLeaf *viewCell);
318
319        SubdivisionCandidate *GetSubdivisionCandidate()
320        {
321                return mSubdivisionCandidate;
322        }
323
324        void SetSubdivisionCandidate(SubdivisionCandidate *candidate)
325        {
326                mSubdivisionCandidate = candidate;
327        }
328
329
330public:
331
332        /// Rays piercing this leaf.
333        VssRayContainer mVssRays;
334       
335        /// leaf pvs
336        //ObjectPvs *mPvs;
337
338        /// Probability that the view point lies in this leaf
339        float mProbability;
340
341protected:
342
343        /// pointer to a split plane candidate splitting this leaf
344        SubdivisionCandidate *mSubdivisionCandidate;
345       
346        /// if NULL this does not correspond to feasible viewcell
347        ViewCellLeaf *mViewCell;
348};
349
350
351/** View Space Partitioning tree.
352*/
353class VspTree
354{
355        friend class ViewCellsParseHandlers;
356        friend class HierarchyManager;
357
358public:
359       
360        /** Additional data which is passed down the BSP tree during traversal.
361        */
362        class VspTraversalData
363        { 
364        public:
365               
366                /** Returns average ray contribution.
367                */
368                float GetAvgRayContribution() const
369                {
370                        return (float)mPvs / ((float)mRays->size() + Limits::Small);
371                }
372
373
374                VspTraversalData():
375                mNode(NULL),
376                mDepth(0),
377                mRays(NULL),
378                mPvs(0),
379                mProbability(0.0),
380                mMaxCostMisses(0),
381                mPriority(0)
382                {}
383               
384                VspTraversalData(VspLeaf *node,
385                                                 const int depth,
386                                                 RayInfoContainer *rays,
387                                                 const int pvs,
388                                                 const float p,
389                                                 const AxisAlignedBox3 &box):
390                mNode(node),
391                mDepth(depth),
392                mRays(rays),
393                mPvs(pvs),
394                mProbability(p),
395                mBoundingBox(box),
396                mMaxCostMisses(0),
397                mPriority(0)
398                {}
399
400                VspTraversalData(const int depth,
401                                                 RayInfoContainer *rays,
402                                                 const AxisAlignedBox3 &box):
403                mNode(NULL),
404                mDepth(depth),
405                mRays(rays),
406                mPvs(0),
407                mProbability(0),
408                mMaxCostMisses(0),
409                mBoundingBox(box)
410                {}
411
412                /** Returns cost of the traversal data.
413                */
414                float GetCost() const
415                {
416                        return mPriority;
417                }
418
419                /// deletes contents and sets them to NULL
420                void Clear()
421                {
422                        DEL_PTR(mRays);
423
424                        if (mNode)
425                        {
426                                // delete old view cell
427                                delete mNode->GetViewCell();
428                                delete mNode;
429                                mNode = NULL;
430                        }
431                }
432
433                /// the current node
434                VspLeaf *mNode;
435                /// current depth
436                int mDepth;
437                /// rays piercing this node
438                RayInfoContainer *mRays;
439                /// the probability that this node contains view point
440                float mProbability;
441                /// the bounding box of the node
442                AxisAlignedBox3 mBoundingBox;
443                /// pvs size
444                int mPvs;
445                /// how often this branch has missed the max-cost ratio
446                int mMaxCostMisses;
447                // current priority
448                float mPriority;
449
450               
451                friend bool operator<(const VspTraversalData &a, const VspTraversalData &b)
452                {
453                        return a.GetCost() < b.GetCost();
454                }
455    };
456
457        /** Candidate for a view space split.
458        */
459        class VspSubdivisionCandidate: public SubdivisionCandidate
460        { 
461        public:
462
463                static VspTree* sVspTree;
464
465                /// the current split plane
466                AxisAlignedPlane mSplitPlane;
467                /// parent node traversal data
468                VspTraversalData mParentData;
469               
470                VspSubdivisionCandidate(const VspTraversalData &tData): mParentData(tData)
471                {};
472
473                ~VspSubdivisionCandidate()
474                {
475                        mParentData.Clear();
476                }
477
478                int Type() const { return VIEW_SPACE; }
479
480                void EvalCandidate(bool computeSplitplane = true)
481                {
482                        mDirty = false;
483                        sVspTree->EvalSubdivisionCandidate(*this, computeSplitplane);
484                }
485
486                bool GlobalTerminationCriteriaMet() const
487                {
488                        return sVspTree->GlobalTerminationCriteriaMet(mParentData);
489                }
490
491                bool Apply(SplitQueue &splitQueue, bool terminationCriteriaMet)
492                {
493                        VspNode *n = sVspTree->Subdivide(splitQueue, this, terminationCriteriaMet);
494                       
495                        // local or global termination criteria failed
496                        return !n->IsLeaf();           
497                }
498
499                void CollectDirtyCandidates(SubdivisionCandidateContainer &dirtyList,
500                                                                        const bool onlyUnmailed)
501                {
502                        sVspTree->CollectDirtyCandidates(this, dirtyList, onlyUnmailed);
503                }
504
505        VspSubdivisionCandidate(const AxisAlignedPlane &plane, const VspTraversalData &tData):
506                mSplitPlane(plane), mParentData(tData)
507                {}
508
509                float GetPriority() const
510                {
511                        return mPriority;
512                }
513        };
514
515        /** Struct for traversing line segment.
516        */
517        struct LineTraversalData
518        {
519                VspNode *mNode;
520                Vector3 mExitPoint;
521                float mMaxT;
522   
523                LineTraversalData () {}
524                LineTraversalData (VspNode *n, const Vector3 &p, const float maxt):
525                mNode(n), mExitPoint(p), mMaxT(maxt) {}
526        };
527
528        /** Default constructor creating an empty tree.
529        */
530        VspTree();
531        /** Default destructor.
532        */
533        ~VspTree();
534
535        /** Returns BSP Tree statistics.
536        */
537        const VspTreeStatistics &GetStatistics() const;
538 
539        /** Returns bounding box of the specified node.
540        */
541        AxisAlignedBox3 GetBoundingBox(VspNode *node) const;
542
543        /** Returns list of BSP leaves with pvs smaller than
544                a certain threshold.
545                @param onlyUnmailed if only the unmailed leaves should be considered
546                @param maxPvs the maximal pvs of a leaf to be added (-1 means unlimited)
547        */
548        void CollectLeaves(vector<VspLeaf *> &leaves,
549                                           const bool onlyUnmailed = false,
550                                           const int maxPvs = -1) const;
551
552        /** Returns box which bounds the whole tree.
553        */
554        AxisAlignedBox3 GetBoundingBox() const;
555
556        /** Returns root of the view space partitioning tree.
557        */
558        VspNode *GetRoot() const;
559
560        /** Collects the leaf view cells of the tree
561                @param viewCells returns the view cells
562        */
563        void CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const;
564
565        /** A ray is cast possible intersecting the tree.
566                @param the ray that is cast.
567                @returns the number of intersections with objects stored in the tree.
568        */
569        int CastRay(Ray &ray);
570
571
572        /** finds neighbouring leaves of this tree node.
573        */
574        int FindNeighbors(VspLeaf *n,
575                                          vector<VspLeaf *> &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        VspLeaf *GetRandomLeaf(const Plane3 &halfspace);
582
583        /** Returns random leaf of BSP tree.
584                @param onlyUnmailed if only unmailed leaves should be returned.
585        */
586        VspLeaf *GetRandomLeaf(const bool onlyUnmailed = false);
587
588        /** Returns epsilon of this tree.
589        */
590        float GetEpsilon() const;
591
592        /** Casts line segment into the tree.
593                @param origin the origin of the line segment
594                @param termination the end point of the line segment
595                @returns view cells intersecting the line segment.
596        */
597    int CastLineSegment(const Vector3 &origin,
598                                                const Vector3 &termination,
599                                                ViewCellContainer &viewcells,
600                                                const bool useMailboxing = true);
601
602               
603        /** Sets pointer to view cells manager.
604        */
605        void SetViewCellsManager(ViewCellsManager *vcm);
606
607        /** Returns view cell the current point is located in.
608                @param point the current view point
609                @param active if currently active view cells should be returned or
610                elementary view cell
611        */
612        ViewCell *GetViewCell(const Vector3 &point, const bool active = false);
613
614
615        /** Returns true if this view point is in a valid view space,
616                false otherwise.
617        */
618        bool ViewPointValid(const Vector3 &viewPoint) const;
619
620        /** Returns view cell corresponding to
621                the invalid view space.
622        */
623        VspViewCell *GetOutOfBoundsCell();
624
625        /** Writes tree to output stream
626        */
627        bool Export(OUT_STREAM &stream);
628
629        /** Casts beam, i.e. a 5D frustum of rays, into tree.
630                Tests conservative using the bounding box of the nodes.
631                @returns number of view cells it intersected
632        */
633        int CastBeam(Beam &beam);
634
635        /** Checks if tree validity-flags are right
636                with respect to view cell valitiy.
637                If not, marks subtree as invalid.
638        */
639        void ValidateTree();
640
641        /** Invalid view cells are added to the unbounded space
642        */
643        void CollapseViewCells();
644
645        /** Collects rays stored in the leaves.
646        */
647        void CollectRays(VssRayContainer &rays);
648
649        /** Intersects box with the tree and returns the number of intersected boxes.
650                @returns number of view cells found
651        */
652        int ComputeBoxIntersections(const AxisAlignedBox3 &box,
653                                                                ViewCellContainer &viewCells) const;
654
655        /** Returns view cells of this ray, either taking precomputed cells
656                or by recomputation.
657        */
658        void GetViewCells(const VssRay &ray, ViewCellContainer &viewCells);
659
660        /** Returns view cells tree.
661        */
662        ViewCellsTree *GetViewCellsTree() const { return mViewCellsTree; }
663
664        /** Sets the view cells tree.
665        */
666        void SetViewCellsTree(ViewCellsTree *vt) { mViewCellsTree = vt; }
667
668#if WORK_WITH_VIEWCELLS
669        /** Remove the references of the parent view cell from the kd nodes associated with
670                the objects.
671        */
672        void RemoveParentViewCellReferences(ViewCell *parent) const;
673
674        /** Adds references to the view cell to the kd nodes associated with the objects.
675        */
676        void AddViewCellReferences(ViewCell *vc) const;
677#endif
678
679        VspNode *SubdivideAndCopy(SplitQueue &tQueue, SubdivisionCandidate *splitCandidate);
680
681protected:
682
683        // --------------------------------------------------------------
684        // For sorting objects
685        // --------------------------------------------------------------
686        struct SortableEntry
687        {
688                enum EType
689                {
690                        ERayMin,
691                        ERayMax
692                };
693
694                int type;
695                float value;
696                VssRay *ray;
697 
698                SortableEntry() {}
699                SortableEntry(const int t, const float v, VssRay *r):
700                type(t), value(v), ray(r)
701                {
702                }
703               
704                friend inline bool operator<(const SortableEntry &a, const SortableEntry &b)
705                {       // prefer max event
706                        //if (EpsilonEqual(a.value, b.value, 0.0001f))
707                        //      return (a.type == ERayMax);
708
709                        return (a.value < b.value);
710                }
711        };
712
713        /** faster evaluation of split plane cost for kd axis aligned cells.
714        */
715        float EvalLocalSplitCost(const VspTraversalData &data,
716                                                         const AxisAlignedBox3 &box,
717                                                         const int axis,
718                                                         const float &position,
719                                                         float &pFront,
720                                                         float &pBack) const;
721
722        void ComputeBoundingBox(const VssRayContainer &rays,
723                                                        AxisAlignedBox3 *forcedBoundingBox);
724
725        /** Evaluates candidate for splitting.
726        */
727        void EvalSubdivisionCandidate(VspSubdivisionCandidate &splitData,
728                                                                  bool computeSplitPlane = true);
729
730        /** Evaluates render cost decrease of next split.
731        */
732        float EvalRenderCostDecrease(const AxisAlignedPlane &candidatePlane,
733                                                                 const VspTraversalData &data,
734                                                                 float &normalizedOldRenderCost) const;
735
736        /** Collects view cells in the subtree under root.
737        */
738        void CollectViewCells(VspNode *root,
739                                                  bool onlyValid,
740                                                  ViewCellContainer &viewCells,
741                                                  bool onlyUnmailed = false) const;
742
743        /** Returns view cell corresponding to
744                the invalid view space. If it does not exist, it is created.
745        */
746        VspViewCell *GetOrCreateOutOfBoundsCell();
747
748        /** Collapses the tree with respect to the view cell partition,
749                i.e. leaves having the same view cell are collapsed.
750                @param node the root of the subtree to be collapsed
751                @param collapsed returns the number of collapsed nodes
752                @returns node of type leaf if the node could be collapsed,
753                this node otherwise
754        */
755        VspNode *CollapseTree(VspNode *node, int &collapsed);
756
757        /** Helper function revalidating the view cell leaf list after merge.
758        */
759        void RepairViewCellsLeafLists();
760
761        /** Evaluates tree stats in the BSP tree leafs.
762        */
763        void EvaluateLeafStats(const VspTraversalData &data);
764
765        /** Subdivides node using a best split priority queue.
766            @param tQueue the best split priority queue
767                @param splitCandidate the candidate for the next split
768                @param globalCriteriaMet if the global termination criteria were already met
769                @returns new root of the subtree
770        */
771        VspNode *Subdivide(SplitQueue &tQueue,
772                                           SubdivisionCandidate *splitCandidate,
773                                           const bool globalCriteriaMet);
774
775        /** Adds stats to subdivision log file.
776        */
777        void AddSubdivisionStats(const int viewCells,
778                                                         const float renderCostDecr,
779                                                         const float totalRenderCost,
780                                                         const float avgRenderCost);
781       
782        /** Subdivides leaf.
783                       
784                @param tData data object holding, e.g., a pointer to the leaf
785                @param frontData returns the data (e.g.,  pointer to the leaf) in front of the split plane
786                @param backData returns the data (e.g.,  pointer to the leaf) in the back of the split plane
787               
788                @param rays the polygons to be filtered
789                @param frontRays returns the polygons in front of the split plane
790       
791                @returns the root of the subdivision
792        */
793        VspInterior *SubdivideNode(const AxisAlignedPlane &splitPlane,
794                                                           VspTraversalData &tData,
795                                                           VspTraversalData &frontData,
796                               VspTraversalData &backData);
797
798        /** Selects an axis aligned for the next split.
799                @returns cost for this split
800        */
801        float SelectSplitPlane(const VspTraversalData &tData,
802                                                   AxisAlignedPlane &plane,
803                                                   float &pFront,
804                                                   float &pBack);
805
806        /** Sorts split candidates along the specified axis.
807                The split candidates are generated on possible visibility
808                events (i.e., where ray segments intersect the ray boundaries).
809                The sorted candidates are needed to compute the heuristics.
810
811                @param polys the input for choosing split candidates
812                @param axis the current split axis
813                @param splitCandidates returns sorted list of split candidates
814        */
815        void SortSubdivisionCandidates(const RayInfoContainer &rays,
816                                                         const int axis,
817                                                         float minBand,
818                                                         float maxBand);
819
820        /** Evaluate pvs size as induced by the samples.
821        */
822        int EvalPvsSize(const RayInfoContainer &rays) const;
823
824        int EvalPvsEntriesIncr(VspSubdivisionCandidate &splitCandidate) const;
825
826        /** Returns number of effective entries in the pvs.
827        */
828        int EvalPvsEntriesSize(const RayInfoContainer &rays) const;
829        int EvalPvsEntriesContribution(const VssRay &ray, const bool isTermination) const;
830        /** Computes best cost for axis aligned planes.
831        */
832        float EvalLocalCostHeuristics(const VspTraversalData &tData,
833                                                                  const AxisAlignedBox3 &box,
834                                                                  const int axis,
835                                                                  float &position);
836
837
838        //////////////////////////////////////////
839        // Helper function for computing heuristics
840
841        /** Evaluates the contribution to left and right pvs at a visibility event ve.
842                @param ve the visibility event
843                @param pvsLeft updates the left pvs
844                @param rightPvs updates the right pvs
845        */
846        void EvalHeuristics(const SortableEntry &ve, int &pvsLeft, int &pvsRight) const;
847
848        /** Evaluates contribution of min event to pvs
849        */
850        int EvalMinEventContribution(
851                const VssRay &ray, const bool isTermination) const;
852
853        /** Evaluates contribution of max event to pvs
854        */
855        int EvalMaxEventContribution(
856                const VssRay &ray, const bool isTermination) const;
857
858        /** Evaluates contribution of kd leaf when encountering a min event
859        */
860        int EvalMinEventContribution(KdLeaf *leaf) const;
861        /**  Evaluates contribution of kd leaf when encountering a max event
862        */
863        int EvalMaxEventContribution(KdLeaf *leaf) const;
864
865        /** Prepares objects for the heuristics.
866                @returns pvs size as seen by the rays.
867        */
868        int PrepareHeuristics(const RayInfoContainer &rays);
869       
870        /** Prepare a single ray for heuristics.
871        */
872        int PrepareHeuristics(const VssRay &ray, const bool isTermination);
873        /** Prepare a single kd leaf for heuristics.
874        */
875        int PrepareHeuristics(KdLeaf *leaf);
876
877       
878        /////////////////////////////////////////////////////////////////////////////
879
880
881        /** Subdivides the rays into front and back rays according to the split plane.
882               
883                @param plane the split plane
884                @param rays contains the rays to be split. The rays are
885                           distributed into front and back rays.
886                @param frontRays returns rays on the front side of the plane
887                @param backRays returns rays on the back side of the plane
888               
889                @returns the number of splits
890        */
891        int SplitRays(const AxisAlignedPlane &plane,
892                                  RayInfoContainer &rays,
893                              RayInfoContainer &frontRays,
894                                  RayInfoContainer &backRays) const;
895
896        void UpdatePvsEntriesContribution(
897                const VssRay &ray,
898                const bool isTermination,
899                const int cf,
900                float &frontPvs,
901                float &backPvs,
902                float &totalPvs) const;
903
904        /** Classfifies the object with respect to the
905                pvs of the front and back leaf and updates pvs size
906                accordingly.
907
908                @param obj the object to be added
909                @param cf the ray classification regarding the split plane
910                @param frontPvs returns the PVS of the front partition
911                @param backPvs returns the PVS of the back partition
912       
913        */
914        void UpdateContributionsToPvs(
915                const VssRay &ray,
916                const bool isTermination,
917                const int cf,
918                float &frontPvs,
919                float &backPvs,
920                float &totalPvs) const;
921
922        /** Evaluates the contribution for objects.
923        */
924        void UpdateContributionsToPvs(
925                Intersectable *obj,
926                const int cf,
927                float &frontPvs,
928                float &backPvs,
929                float &totalPvs) const;
930
931        /** Evaluates the contribution for bounding volume leaves.
932        */
933        void UpdateContributionsToPvs(
934                BvhLeaf *leaf,
935                const int cf,
936                float &frontPvs,
937                float &backPvs,
938                float &totalPvsm,
939                const bool countEntries = false) const;
940
941        /** Evaluates the contribution for kd leaves.
942        */
943        void UpdateContributionsToPvs(
944                KdLeaf *leaf,
945                const int cf,
946                float &frontPvs,
947                float &backPvs,
948                float &totalPvs) const;
949
950        /** Returns true if tree can be terminated.
951        */
952        bool LocalTerminationCriteriaMet(const VspTraversalData &data) const;
953
954        /** Returns true if global tree can be terminated.
955        */
956        bool GlobalTerminationCriteriaMet(const VspTraversalData &data) const;
957
958        /** Adds ray sample contributions to the PVS.
959                @param sampleContributions the number contributions of the samples
960                @param contributingSampels the number of contributing rays
961               
962        */
963        void AddSamplesToPvs(VspLeaf *leaf,
964                                                 const RayInfoContainer &rays,
965                                                 float &sampleContributions,
966                                                 int &contributingSamples);
967
968        /** Propagates valid flag up the tree.
969        */
970        void PropagateUpValidity(VspNode *node);
971
972        /** Writes the node to disk
973                @note: should be implemented as visitor.
974        */
975        void ExportNode(VspNode *node, OUT_STREAM &stream);
976
977        /** Returns estimated memory usage of tree.
978        */
979        float GetMemUsage() const;
980
981        /** Updates view cell pvs of objects.
982        */
983        void ProcessViewCellObjects(ViewCell *parent,
984                                                                ViewCell *front,
985                                                                ViewCell *back) const;
986
987        void CreateViewCell(VspTraversalData &tData, const bool updatePvs);
988
989        /** Collect split candidates which are affected by the last split
990                and must be reevaluated.
991        */
992        void CollectDirtyCandidates(VspSubdivisionCandidate *sc,
993                                                                vector<SubdivisionCandidate *> &dirtyList,
994                                                                const bool onlyUnmailed);
995
996        void CollectDirtyCandidate(const VssRay &ray,
997                                                           const bool isTermination,
998                                                           vector<SubdivisionCandidate *> &dirtyList,
999                                                           const bool onlyUnmailed) const;
1000
1001        /** Rays will be clipped to the bounding box.
1002        */
1003        void PreprocessRays(const VssRayContainer &sampleRays, RayInfoContainer &rays);
1004
1005        /** Evaluate subdivision statistics.
1006        */
1007        void EvalSubdivisionStats(const SubdivisionCandidate &tData);
1008
1009        SubdivisionCandidate *PrepareConstruction(
1010                const VssRayContainer &sampleRays,
1011                RayInfoContainer &rays);
1012
1013        /** Evaluates pvs contribution of this ray.
1014        */
1015        int EvalContributionToPvs(const VssRay &ray, const bool isTermination) const;
1016
1017        /** Evaluates pvs contribution of a kd node.
1018        */
1019        int EvalContributionToPvs(KdLeaf *leaf) const;
1020
1021        /** Creates new root of hierarchy and computes bounding box.
1022                Has to be called before the preparation of the subdivision.
1023        */
1024        void Initialise(const VssRayContainer &rays,
1025                                        AxisAlignedBox3 *forcedBoundingBox);
1026
1027protected:
1028
1029        /// pointer to the hierarchy of view cells
1030        ViewCellsTree *mViewCellsTree;
1031
1032        HierarchyManager *mHierarchyManager;
1033        //OspTree *mOspTree;
1034        //bool mUseKdPvsForHeuristics;
1035       
1036        ViewCellsManager *mViewCellsManager;
1037       
1038        vector<SortableEntry> *mLocalSubdivisionCandidates;
1039
1040        /// Pointer to the root of the tree
1041        VspNode *mRoot;
1042               
1043        VspTreeStatistics mVspStats;
1044       
1045        /// View cell corresponding to the space outside the valid view space
1046        VspViewCell *mOutOfBoundsCell;
1047
1048        /// box around the whole view domain
1049        AxisAlignedBox3 mBoundingBox;
1050
1051
1052        //-- local termination
1053
1054        /// minimal number of rays before subdivision termination
1055        int mTermMinRays;
1056        /// maximal possible depth
1057        int mTermMaxDepth;
1058        /// mininum probability
1059        float mTermMinProbability;
1060        /// mininum PVS
1061        int mTermMinPvs;
1062        /// maximal contribution per ray
1063        float mTermMaxRayContribution;
1064        /// maximal acceptable cost ratio
1065        float mTermMaxCostRatio;
1066        /// tolerance value indicating how often the max cost ratio can be failed
1067        int mTermMissTolerance;
1068
1069
1070        //-- global criteria
1071        float mTermMinGlobalCostRatio;
1072        int mTermGlobalCostMissTolerance;
1073       
1074
1075        /// maximal number of view cells
1076        int mMaxViewCells;
1077        /// maximal tree memory
1078        float mMaxMemory;
1079        /// the tree is out of memory
1080        bool mOutOfMemory;
1081
1082        ////////////
1083        //-- split heuristics based parameters
1084       
1085        bool mUseCostHeuristics;
1086        /// balancing factor for PVS criterium
1087        float mCtDivCi;
1088        /// if only driving axis should be used for split
1089        bool mOnlyDrivingAxis;
1090        /// if random split axis should be used
1091        bool mUseRandomAxis;
1092        /// if vsp bsp tree should simulate octree
1093        bool mCirculatingAxis;
1094        /// minimal relative position where the split axis can be placed
1095        float mMinBand;
1096        /// maximal relative position where the split axis can be placed
1097        float mMaxBand;
1098
1099
1100        /// current time stamp (used for keeping split history)
1101        int mTimeStamp;
1102        // if rays should be stored in leaves
1103        bool mStoreRays;
1104
1105        /// epsilon for geometric comparisons
1106        float mEpsilon;
1107
1108        /// subdivision stats output file
1109        ofstream  mSubdivisionStats;
1110        /// keeps track of cost during subdivision
1111        float mTotalCost;
1112        int mPvsEntries;
1113        /// keeps track of overall pvs size during subdivision
1114        int mTotalPvsSize;
1115        /// number of currenly generated view cells
1116        int mCreatedViewCells;
1117
1118        /// weight between render cost decrease and node render cost
1119        float mRenderCostDecreaseWeight;
1120
1121        int mMaxTests;
1122};
1123
1124
1125}
1126
1127#endif
Note: See TracBrowser for help on using the repository browser.