source: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h @ 1736

Revision 1736, 17.2 KB checked in by mattausch, 18 years ago (diff)
Line 
1#ifndef _HierarchyManager_H__
2#define _HierarchyManager_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
14
15
16namespace GtpVisibilityPreprocessor {
17
18class ViewCellLeaf;
19class OspTree;
20class VspTree;
21class Plane3;
22class AxisAlignedBox3;
23class Ray;
24class ViewCellsStatistics;
25class ViewCellsManager;
26class MergeCandidate;
27class Beam;
28class ViewCellsTree;
29class Environment;
30class VspInterior;
31class VspLeaf;
32class VspNode;
33class KdNode;
34class KdInterior;
35class KdLeaf;
36class OspTree;
37class KdIntersectable;
38class KdTree;
39class VspTree;
40class KdTreeStatistics;
41class BvHierarchy;
42class Exporter;
43class ViewCellsParseHandlers;
44
45
46#define COUNT_ORIGIN_OBJECTS 1
47
48/** View space / object space hierarchy statistics.
49*/
50class HierarchyStatistics: public StatisticsBase
51{
52public:
53        /// total number of entries in the pvs
54        int mPvsEntries;
55        /// storage cost in MB
56        float mMemory;
57        /// total number of nodes
58        int mNodes;
59        /// maximal reached depth
60        int mMaxDepth;
61        /// accumulated depth
62        int mAccumDepth;
63        /// time spent for queue repair
64        float mRepairTime;
65
66        // global cost ratio violations
67        int mGlobalCostMisses;
68        /// total cost of subdivision
69        float mTotalCost;
70        /// render cost decrease of subdivision
71        float mRenderCostDecrease;
72
73        // Constructor
74        HierarchyStatistics()
75        {
76                Reset();
77        }
78
79        int Nodes() const {return mNodes;}
80        int Interior() const { return mNodes / 2 - 1; }
81        int Leaves() const { return (mNodes / 2) + 1; }
82       
83        // TODO: computation wrong
84        double AvgDepth() const { return mAccumDepth / (double)Leaves();}
85
86        void Reset()
87        {
88                mGlobalCostMisses = 0;
89                mTotalCost = 0;
90                mRenderCostDecrease = 0;
91
92                mNodes = 0;
93                mMaxDepth = 0;
94                mAccumDepth = 0;
95                mRepairTime = 0;
96                mMemory = 0;
97                mPvsEntries = 0;
98        }
99
100        void Print(ostream &app) const;
101
102        friend ostream &operator<<(ostream &s, const HierarchyStatistics &stat)
103        {
104                stat.Print(s);
105                return s;
106        }
107};
108
109
110class HierarchySubdivisionStats
111{
112public:
113           
114        int mNumSplits;
115               
116        float mRenderCostDecrease;
117
118    float mTotalRenderCost;
119   
120        int mEntriesInPvs;
121   
122        float mMemoryCost;
123       
124        float mFullMemory;
125
126        int mViewSpaceSplits;
127
128        int mObjectSpaceSplits;
129
130
131        float VspOspRatio() const { return (float)mViewSpaceSplits / (float)mObjectSpaceSplits; }
132
133        float FpsPerMb() const { return 1.0f / (mTotalRenderCost * mMemoryCost); }
134
135        HierarchySubdivisionStats() { Reset(); }
136
137        void Reset()
138        {
139                mNumSplits = 0;
140                mRenderCostDecrease = 0;
141                mTotalRenderCost = 0;
142                mEntriesInPvs = 0;
143                mMemoryCost = 0;
144                mFullMemory = 0;
145                mViewSpaceSplits = 0;
146                mObjectSpaceSplits = 0;
147        }
148
149
150        void Print(ostream &app) const;
151
152        friend ostream &operator<<(ostream &s, const HierarchySubdivisionStats &stat)
153        {
154                stat.Print(s);
155                return s;
156        }
157};
158
159
160/** This class implements a structure holding two different hierarchies,
161        one for object space partitioning and one for view space partitioning.
162
163        The object space and the view space are subdivided using a cost heuristics.
164        If an object space split or a view space split is chosen is also evaluated
165        based on the heuristics.
166       
167        The view space heuristics is evaluated by weighting and adding the pvss of the back and
168        front node of each specific split. unlike for the standalone method vspbsp tree,
169        the pvs of an object would not be the pvs of single object but that of all objects
170        which are contained in the same leaf of the object subdivision. This could be done
171        by storing the pointer to the object space partition parent, which would allow access to all children.
172        Another possibility is to include traced kd-cells in the ray casing process.
173
174        Accordingly, the object space heuristics is evaluated by storing a pvs of view cells with each object.
175        the contribution to an object to the pvs is the number of view cells it can be seen from.
176
177        @note
178        There is a potential efficiency problem involved in a sense that once a certain type
179        of split is chosen for view space / object space, the candidates for the next split of
180        object space / view space must be reevaluated.
181*/
182class HierarchyManager
183{
184public:
185        /** Constructor with the view space partition tree and
186                the object space hierarchy type as argument.
187        */
188        HierarchyManager(const int objectSpaceHierarchyType);
189        /** Hack: OspTree will copy the content from this kd tree.
190                Only view space hierarchy will be constructed.
191        */
192        HierarchyManager(KdTree *kdTree);
193
194        /** Deletes space partition and view space partition.
195        */
196        ~HierarchyManager();
197
198        /** Constructs the view space and object space subdivision from a given set of rays
199                and a set of objects.
200                @param sampleRays the set of sample rays the construction is based on
201                @param objects the set of objects
202        */
203        void Construct(
204                const VssRayContainer &sampleRays,
205                const ObjectContainer &objects,
206                AxisAlignedBox3 *forcedViewSpace);
207
208        enum
209        {
210                NO_OBJ_SUBDIV,
211                KD_BASED_OBJ_SUBDIV,
212                BV_BASED_OBJ_SUBDIV
213        };
214
215        enum
216        {
217                NO_VIEWSPACE_SUBDIV,
218                KD_BASED_VIEWSPACE_SUBDIV
219        };
220
221        /** The type of object space subdivison
222        */
223        int GetObjectSpaceSubdivisionType() const;     
224        /** The type of view space space subdivison
225        */
226        int GetViewSpaceSubdivisionType() const;
227        /** Sets a pointer to the view cells manager.
228        */             
229        void SetViewCellsManager(ViewCellsManager *vcm);
230        /** Sets a pointer to the view cells tree.
231        */
232        void SetViewCellsTree(ViewCellsTree *vcTree);
233        /** Exports the object hierarchy to disc.
234        */
235        void ExportObjectSpaceHierarchy(OUT_STREAM &stream);
236        /** Adds a sample to the pvs of the specified view cell.
237        */
238        bool AddSampleToPvs(
239                Intersectable *obj,
240                const Vector3 &hitPoint,
241                ViewCell *vc,
242                const float pdf,
243                float &contribution) const;
244
245        /** Print out statistics.
246        */
247        void PrintHierarchyStatistics(ostream &stream) const;
248
249        /** Returns the view space partition tree.
250        */
251        VspTree *GetVspTree();
252
253        /** Returns view space bounding box.
254        */
255        //AxisAlignedBox3 GetViewSpaceBox() const;
256
257        /** Returns object space bounding box.
258        */
259        AxisAlignedBox3 GetObjectSpaceBox() const;
260
261        /** Exports object space hierarchy for visualization.
262        */
263        void ExportObjectSpaceHierarchy(Exporter *exporter,
264                                                                        const ObjectContainer &objects,
265                                                                        const AxisAlignedBox3 *bbox,
266                                                                        const bool exportBounds = true) const;
267
268        /** Returns intersectable pierced by this ray.
269        */
270        Intersectable *GetIntersectable(const VssRay &ray, const bool isTermination) const;
271
272        /** Export object space partition bounding boxes.
273        */
274        void ExportBoundingBoxes(OUT_STREAM &stream, const ObjectContainer &objects);
275
276        friend ostream &operator<<(ostream &s, const HierarchyManager &hm)
277        {
278                hm.PrintHierarchyStatistics(s);
279                return s;
280        }
281
282        HierarchyStatistics &GetHierarchyStats() { return mHierarchyStats; };
283
284        inline bool ConsiderMemory() const { return mConsiderMemory; }
285        //inline float GetMemoryConst() const { return mMemoryConst; }
286
287       
288        void EvaluateSubdivision(const VssRayContainer &sampleRays,                                                                                     
289                                                         const ObjectContainer &objects,
290                                                         const string &filename);
291
292        void EvaluateSubdivision2(ofstream &splitsStats,
293                                                          const int splitsStepSize);
294
295
296        void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
297
298        float mInitialRenderCost;
299
300
301protected:
302
303        /** Returns true if the global termination criteria were met.
304        */
305        bool GlobalTerminationCriteriaMet(SubdivisionCandidate *candidate) const;
306
307        /** Prepare construction of the hierarchies, set parameters, compute
308                first split candidates.
309        */
310        SubdivisionCandidate *PrepareObjectSpaceSubdivision(const VssRayContainer &sampleRays,
311                                                                                                                const ObjectContainer &objects);
312
313
314        /** Create bounding box and root.
315        */
316        void InitialiseObjectSpaceSubdivision(const ObjectContainer &objects);
317
318        /** Returns memory usage of object space hierarchy.
319        */
320        float GetObjectSpaceMemUsage() const;
321
322
323        //////////////////////////////
324        // the main loop
325
326        /** This is for interleaved construction / sequential construction.
327        */
328        void RunConstruction(const bool repairQueue,
329                                                 const VssRayContainer &sampleRays,
330                                                 const ObjectContainer &objects,
331                                                 AxisAlignedBox3 *forcedViewSpace);
332       
333        /** This is for interleaved construction using some objects
334                and some view space splits.
335        */
336        int RunConstruction(SplitQueue &splitQueue,
337                                                SubdivisionCandidateContainer &chosenCandidates,
338                                                //const float minRenderCostDecr,
339                                                SubdivisionCandidate *oldCandidate,
340                                                const int minSteps,
341                                                const int maxSteps);
342
343        /** Default subdivision method.
344        */
345        void RunConstruction(const bool repairQueue);
346               
347        ////////////////////////////////////////////////
348
349        /** Evaluates the subdivision candidate and executes the split.
350        */
351        bool ApplySubdivisionCandidate(SubdivisionCandidate *sc,
352                                                                   SplitQueue &splitQueue,
353                                                                   const bool repairQueue);
354
355        /** Tests if hierarchy construction is finished.
356        */
357        bool FinishedConstruction() const;
358
359        /** Returns next subdivision candidate from the split queue.
360        */
361        SubdivisionCandidate *NextSubdivisionCandidate(SplitQueue &splitQueue);
362
363        /** Repairs the dirty entries of the subdivision candidate queue. The
364                list of entries is given in the dirty list.
365
366                @returns number of repaired candidates
367        */
368        int RepairQueue(const SubdivisionCandidateContainer &dirtyList,
369                                        SplitQueue &splitQueue,
370                                        const bool recomputeSplitPlaneOnRepair);
371
372        /** Collect subdivision candidates which were affected by the splits from the
373                chosenCandidates list.
374        */
375        void CollectDirtyCandidates(const SubdivisionCandidateContainer &chosenCandidates,
376                                                                SubdivisionCandidateContainer &dirtyList);
377
378        /** Evaluate subdivision stats for log.
379        */
380        void EvalSubdivisionStats();
381
382        void AddSubdivisionStats(const int splits,
383                                                         const float renderCostDecr,
384                                                         const float totalRenderCost,
385                                                         const int totalPvsEntries,
386                                                         const float memory,
387                                                         const float renderCostPerStorage,
388                                                         const float vspOspRatio);
389
390        bool AddSampleToPvs(Intersectable *obj,
391                                                const float pdf,
392                                                float &contribution) const;
393
394        /** Collect affected view space candidates.
395        */
396        void CollectViewSpaceDirtyList(SubdivisionCandidate *sc,
397                                                                   SubdivisionCandidateContainer &dirtyList);
398
399        /** Collect affected object space candidates.
400        */
401        void CollectObjectSpaceDirtyList(SubdivisionCandidate *sc,
402                                                                         SubdivisionCandidateContainer &dirtyList);
403               
404        /** Export object space partition tree.
405        */
406        void ExportOspTree(Exporter *exporter,
407                                           const ObjectContainer &objects) const;
408
409        /** Parse the environment variables.
410        */
411        void ParseEnvironment();
412
413        bool StartObjectSpaceSubdivision() const;
414        bool StartViewSpaceSubdivision() const;
415
416
417        ////////////////////////////
418        // Helper function for preparation of subdivision
419
420        /** Prepare bv hierarchy for subdivision
421        */
422        SubdivisionCandidate *PrepareBvHierarchy(const VssRayContainer &sampleRays,
423                                                                           const ObjectContainer &objects);
424
425        /** Prepare object space kd tree for subdivision.
426        */
427        SubdivisionCandidate *PrepareOspTree(const VssRayContainer &sampleRays,
428                                                                   const ObjectContainer &objects);
429
430        /** Prepare view space subdivision and add candidate to queue.
431        */
432        SubdivisionCandidate *PrepareViewSpaceSubdivision(const VssRayContainer &sampleRays,
433                                                                                                          const ObjectContainer &objects);
434
435        /** Was object space subdivision already constructed?
436        */
437        bool ObjectSpaceSubdivisionConstructed() const;
438       
439        /** Was view space subdivision already constructed?
440        */
441        bool ViewSpaceSubdivisionConstructed() const;
442
443        /** Reset the split queue, i.e., reevaluate the split candidates.
444        */
445    void ResetQueue(SplitQueue &splitQueue, const bool recomputeSplitPlane);
446
447        /** After the suddivision has ended, do some final tasks.
448        */
449        void FinishObjectSpaceSubdivision(const ObjectContainer &objects,
450                                                                          const bool removeRayRefs = true) const;
451
452        /** Returns depth of object space subdivision.
453        */
454        int GetObjectSpaceSubdivisionDepth() const;
455
456        /** Returns number of leaves in object space subdivision.
457        */
458        int GetObjectSpaceSubdivisionLeaves() const;
459        int GetObjectSpaceSubdivisionNodes() const;
460
461        /** Construct object space partition interleaved with view space partition.
462                Each time the best object or view space candidate is selected
463                for the next split.
464        */
465        void ConstructInterleaved(const VssRayContainer &sampleRays,
466                                                          const ObjectContainer &objects,
467                                                          AxisAlignedBox3 *forcedViewSpace);
468
469        /** Construct object space partition interleaved with view space partition.
470                The method chooses a number candidates of each type for subdivision.
471                The number is determined by the "gradient", i.e., the render cost decrease.
472                Once this render cost decrease is lower than the render cost decrease
473                for the splits of previous type, the method will stop current subdivision and
474                evaluate if view space or object space would be the beneficial for the
475                next number of split.
476        */
477        void ConstructInterleavedWithGradient(const VssRayContainer &sampleRays,
478                                                                                  const ObjectContainer &objects,
479                                                                                  AxisAlignedBox3 *forcedViewSpace);
480
481        /** Use iteration to construct the object space hierarchy.
482        */
483        void ConstructMultiLevel(const VssRayContainer &sampleRays,
484                                                         const ObjectContainer &objects,
485                                                         AxisAlignedBox3 *forcedViewSpace);
486
487        /** Based on a given subdivision, we try to optimize using an
488                multiple iteration over view and object space.
489        */
490        void OptimizeMultiLevel(const VssRayContainer &sampleRays,                                                                                       
491                                                        const ObjectContainer &objects,
492                                                        AxisAlignedBox3 *forcedViewSpace);
493
494        /** Reset the object space subdivision.
495                E.g., deletes hierarchy and resets stats.
496                so construction can be restarted.
497        */
498        SubdivisionCandidate *ResetObjectSpaceSubdivision(const VssRayContainer &rays,
499                                                                                                          const ObjectContainer &objects);
500
501        SubdivisionCandidate *ResetViewSpaceSubdivision(const VssRayContainer &rays,
502                                                                                                        const ObjectContainer &objects,
503                                                                                                        AxisAlignedBox3 *forcedViewSpace);
504
505
506        ///////////////////////////
507
508        void ExportStats(ofstream &stats, SplitQueue &tQueue, const ObjectContainer &objects);
509
510        void CollectBestSet(const int maxSplits,
511                                                const float maxMemoryCost,
512                                                ViewCellContainer &viewCells,
513                                                vector<BvhNode *> &bvhNodes);
514
515        int ExtractStatistics(const int maxSplits,
516                                                  const float maxMemoryCost,
517                                                  float &renderCost,
518                                                  float &memory,
519                                                  int &pvsEntries,
520                                                  int &viewSpaceSplits,
521                                                  int &objectSpaceSplits);
522
523
524protected:
525
526        /** construction types
527                sequential: construct first view space, then object space
528                interleaved: construct view space and object space fully interleaved
529                gradient: construct view space / object space until a threshold is reached
530                multilevel: iterate until subdivisions converge to the optimum.
531        */
532        enum {SEQUENTIAL, INTERLEAVED, GRADIENT, MULTILEVEL};
533
534        /// type of hierarchy construction
535        int mConstructionType;
536
537        /// Type of object space partition
538        int mObjectSpaceSubdivisionType;
539        /// Type of view space partition
540    int mViewSpaceSubdivisionType;
541
542        /// the traversal queue
543        SplitQueue mTQueue;
544       
545        ////////////
546        //-- helper variables
547       
548        // the original osp type
549        int mSavedObjectSpaceSubdivisionType;
550        // the original vsp type
551        int mSavedViewSpaceSubdivisionType;
552        /// the current subdivision candidate
553        //SubdivisionCandidate *mCurrentCandidate;
554
555
556        ///////////////////
557        // Hierarchies
558
559        /// view space hierarchy
560        VspTree *mVspTree;
561        /// object space partition kd tree
562        OspTree *mOspTree;
563
564        public:
565        /// bounding volume hierarchy
566        BvHierarchy *mBvHierarchy;
567       
568protected:
569
570
571        //////////
572        //-- global termination criteria
573
574        /// the mininal acceptable cost ratio for a split
575        float mTermMinGlobalCostRatio;
576        /// the threshold for global cost miss tolerance
577        int mTermGlobalCostMissTolerance;
578        /// maximum number of leaves
579        int mTermMaxLeaves;
580        /// Maximal allowed memory consumption.
581        float mTermMaxMemory;
582
583
584        ////////////////////
585
586        /// number of minimal steps of the same type
587        int mMinStepsOfSameType;
588        int mMaxStepsOfSameType;
589
590        /// statistics about the hierarchy
591        HierarchyStatistics mHierarchyStats;
592
593        int mMinDepthForObjectSpaceSubdivion;
594        int mMinDepthForViewSpaceSubdivion;
595       
596        //int mMinRenderCostDecrease;
597
598        ofstream mSubdivisionStats;
599
600        /// if the queue should be repaired after a subdivision steps
601        bool mRepairQueue;
602
603        bool mStartWithObjectSpace;
604        /** if multi level construction method should be used
605                where we iterate over both hierarchies until we
606                converge to the optimum.
607        */
608        bool mUseMultiLevelConstruction;
609
610        /// number of iteration steps for multilevel approach   
611        int mNumMultiLevels;
612
613        /** if split plane should be recomputed for the repair.
614                Otherwise only the priority is recomputed, the
615                split plane itself stays the same
616        */
617        bool mRecomputeSplitPlaneOnRepair;
618
619        /** If memory should be considered during choosing
620                of the next split type during gradient method.
621        */
622        bool mConsiderMemory;
623
624        bool mConsiderMemory2;
625
626        int mMaxRepairs;
627
628        int mTimeStamp;
629        friend VspTree;
630        friend OspTree;
631        friend BvHierarchy;
632        friend ViewCellsParseHandlers;
633
634};
635
636}
637
638#endif
Note: See TracBrowser for help on using the repository browser.