source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.h @ 2342

Revision 2342, 19.8 KB checked in by mattausch, 18 years ago (diff)
Line 
1#ifndef _ViewCell_H__
2#define _ViewCell_H__
3
4#include "Mesh.h"
5#include "Containers.h"
6#include "Ray.h"
7#include "Statistics.h"
8#include "Material.h"
9#include "gzstream.h"
10#include "ObjectPvs.h"
11
12namespace GtpVisibilityPreprocessor {
13
14struct Triangle3;
15
16class BspInterior;
17class BspPvs;
18class BspLeaf;
19class VspLeaf;
20class KdLeaf;
21class ViewCellInterior;
22class MergeCandidate;
23class ViewCellsManager;
24class ViewCellLeaf;
25
26
27//class ObjectPvs;
28
29
30/** Statistics for a view cell partition.
31*/
32
33class ViewCellsStatistics: public StatisticsBase
34{
35public:
36
37        /// number of view cells
38        int viewCells;
39        /// cost of the PVS
40        float pvsCost;
41        /// largest PVS of all view cells
42        float maxPvs;
43        /// smallest PVS of all view cells
44        float minPvs;
45        /// view cells with empty PVS
46        int emptyPvs;
47        /// number of leaves covering the view space
48        int leaves;
49        /// largest number of leaves covered by one view cell
50        int maxLeaves;
51        /// number of invalid view cells
52        int invalid;
53
54    // Constructor
55        ViewCellsStatistics()
56        {
57                Reset();
58        }
59
60        double AvgLeaves() const {return (double)leaves / (double)viewCells;};
61        double AvgPvs() const {return (double)pvsCost / (double)viewCells;};
62
63        void Reset()
64        {
65                viewCells = 0;
66                pvsCost = 0;
67                maxPvs = 0;
68
69                minPvs = 999999;
70                emptyPvs = 0;
71                leaves = 0;
72                maxLeaves = 0;
73                invalid = 0;
74        }
75
76        void Print(std::ostream &app) const;
77
78        friend std::ostream &operator<<(std::ostream &s, const ViewCellsStatistics &stat)
79        {
80                stat.Print(s);
81                return s;
82        }
83};
84
85
86class ViewCellsTreeStats
87{
88public:
89        int mPass;
90   
91        int mNumViewCells;
92               
93        float mRenderCostDecrease;
94
95    float mTotalRenderCost;
96   
97        float mCurrentPvsCost;
98                                                       
99        float mExpectedCost;
100   
101        float mAvgRenderCost;
102       
103        float mDeviation;
104                       
105        float mTotalPvsCost;
106       
107        int mEntriesInPvs;
108   
109        float mMemoryCost;
110       
111        int mPvsSizeDecr;
112 
113        float mVolume;
114
115
116        void Reset()
117        {
118                mPass = 0;
119                mNumViewCells = 0;
120                mRenderCostDecrease = 0;
121                mTotalRenderCost = 0;
122                mCurrentPvsCost = 0;
123                mExpectedCost = 0;
124                mAvgRenderCost = 0;
125                mDeviation = 0;
126                mTotalPvsCost = 0;
127                mEntriesInPvs = 0;
128                mMemoryCost = 0;
129                mPvsSizeDecr = 0;
130                mVolume = 0;
131        }
132
133
134        void Print(std::ostream &app) const;
135
136        friend std::ostream &operator<<(std::ostream &s, const ViewCellsTreeStats &stat)
137        {
138                stat.Print(s);
139                return s;
140        }
141};
142
143
144/**
145        A view cell. View cells are regions in space. The visibility informations,
146        i.e., the primitives seen by the view cell are stored in a PVs.
147        A view cell can be represented in many different ways, e.g.,
148        a mesh representation.
149*/
150class ViewCell: public MeshInstance
151{
152        friend class ViewCellsTree;
153        friend class ViewCellsManager;
154
155public:
156
157        ViewCell();
158
159        /** Constructor taking a mesh representing the shape of the viewcell.
160        */
161        ViewCell(Mesh *mesh);
162
163        /** Default destructor.
164        */
165        virtual ~ViewCell();
166        /** Returns Pvs.
167        */
168        const ObjectPvs &GetPvs() const;
169        /** Returns pvs.
170        */
171        ObjectPvs &GetPvs();
172        /** Completely substitutes the pvs.
173        */
174        void SetPvs(const ObjectPvs &pvs);
175        /** Type of view cell.
176        */
177        int Type() const;
178        /** Adds a passing ray to the passing ray container.
179        */
180        void AddPassingRay(const Ray &ray, const int contributions);
181        /** Returns volume of the view cell.
182        */
183        inline float GetVolume() const
184        {
185                return mVolume;
186        }
187        /** Sets the volume of the view cell.
188        */
189        inline void SetVolume(float volume)
190        {
191                mVolume = volume;
192        }
193        /** Returns area of the view cell.
194        */
195        inline float GetArea() const
196        {
197                return mArea;
198        }
199        /** Sets the area of the view cell.
200        */
201        void SetArea(float area)
202        {
203                mArea = area;
204        }
205        /** if this view cell is the root of a view cell hierarchy
206        */
207        bool IsRoot() const;
208        /** Returns parent view cell.
209        */
210        ViewCellInterior *GetParent() const;
211        /** Sets parent of this view cell.
212        */
213        void SetParent(ViewCellInterior *parent);
214        /** Sets the mesh for this view cell.
215        */
216        void SetMesh(Mesh *mesh);
217        /** Sets this view cell to be a valid view cell according to some criteria.
218        */
219        void SetValid(const bool valid);
220        /** Returns true if this view cell is considered to be valid according to
221                some criteria.
222        */
223        bool GetValid() const;
224
225        /** Returns estimated render cost of this view cell.
226        */
227        float GetRenderCost() const;
228
229        /** set color for visiualizations.
230        */
231        void SetColor(const RgbColor &color);
232
233        /** get color for visualuzations.
234        */
235    RgbColor GetColor() const;
236
237        /** Adds a sample to the pvs.
238                @param sample the sample to be added
239                @param pdf a continuos measure of visibility
240                @param contribution returns the contribution of this sample to the pvs
241        */
242        bool AddPvsSample(Intersectable *sample, const float pdf, float &contribution);
243
244        /** if this is a view cell correspending to a leaf in a hierarchy.
245        */
246        virtual bool IsLeaf() const = 0;
247
248        static bool SmallerPvs(const ViewCell *a, const ViewCell *b)
249        {
250                // HACK: take scalar value because pvs may not have been stored properly
251#if 1
252                return a->mPvsCost < b->mPvsCost;
253#else
254                return a->GetPvs().EvalPvsCost() < b->GetPvs().EvalPvsCost();
255#endif
256        }
257
258        static bool GreaterOrEqualPvs(const ViewCell *a, const ViewCell *b)
259        {
260                return !SmallerPvs(a, b);
261        }
262
263        static bool SmallerRenderCost(const ViewCell *a, const ViewCell *b)
264        {
265                return a->GetRenderCost() < b->GetRenderCost();
266        }
267
268        static bool LargerRenderCost(const ViewCell *a, const ViewCell *b)
269        {
270                return a->GetRenderCost() > b->GetRenderCost();
271        }
272
273        /** Sets merge cost used for merging this view cell from other cells.
274                @hack The function is available for leaves also to have a common interface,
275                but it should be less than zero for leaves.
276        */
277        void SetMergeCost(const float mergeCost);
278
279        /** Returns merge cost needed to merge this leaf from other cells.
280                @hack The function is available for leaves also to have a common interface,
281                but it should be less than zero for leaves.
282        */
283        float GetMergeCost() const;
284
285        void UpdatePvsCost() {
286                mPvsCost = GetPvs().EvalPvsCost();
287        }
288
289        void SetTrianglesInPvs(const float c) {
290                mPvsCost = c;
291        }
292
293        void SetEntriesInPvs(const int e) {
294                mEntriesInPvs = e;
295        }
296
297        float GetTrianglesInPvs() const {
298                return mPvsCost;
299        }
300
301        int GetEntriesInPvs() const {
302                return mEntriesInPvs;
303        }
304
305        int GetFilteredPvsSize() const
306        {
307                return mFilteredPvsSize;
308        }
309
310        void SetFilteredPvsSize(const int s) {
311                mFilteredPvsSize = s;
312        }
313
314        //virtual int ViewCellType;
315
316protected:
317
318        /// parent view cell in the view cell hierarchy
319        ViewCellInterior *mParent;
320        /// the potentially visible objects
321        ObjectPvs mPvs;
322        /// the volume of this view cell
323        float mVolume;
324        /// the area of this view cell
325        float mArea;
326        /// the cost that were paid for merging this view cells from two others.
327        float mMergeCost;
328        /// if the view cell is valid view space
329        bool mValid;
330        /// color used for consistent visualization
331        RgbColor mColor;
332        /// store pvs size, used for evaluation purpose when pvss are stored only in the leaves
333        float mPvsCost;
334        /// stores number of entries in pvs
335        int mEntriesInPvs;
336        /** if the pvs size scalar (+ entries into pvs)
337                is up to date and corresponding to the real pvs size
338        */
339        bool mPvsSizeValid;
340
341        /// Filter cost of the pvs
342        int mFilteredPvsSize;
343
344};
345
346
347class ViewCellInterior: public ViewCell
348{
349        friend class ViewCellsManager;
350
351public:
352        ViewCellInterior();
353        ~ViewCellInterior();
354
355        ViewCellInterior(Mesh *mesh);
356
357        /** Sets pointer from parent to child and vice versa.
358        */
359        void SetupChildLink(ViewCell *l);
360        void ReplaceChildLink(ViewCell *prev, ViewCell *cur);
361
362        void RemoveChildLink(ViewCell *l);
363        bool IsLeaf() const;
364
365        void SetCost(const float c) {
366                mCost = c;
367        }
368
369        float GetCost() const {
370                return mCost;
371        }
372
373        ViewCellContainer mChildren;
374
375protected:
376
377        /// Pverall cost resulting from the merge.
378        float mCost;
379};
380
381
382/**
383        Leaf of the view cell.
384*/
385class ViewCellLeaf: public ViewCell
386{
387public:
388        ViewCellLeaf()  {  mActiveViewCell = this; }
389        ViewCellLeaf(Mesh *mesh):
390        ViewCell(mesh) { mActiveViewCell = this; }
391
392        bool IsLeaf() const
393        {
394                return true;
395        }
396
397        /** Returns active view cell, i.e. this view cell or
398                a parent view cell which is set as active view cell.
399        */
400        ViewCell *GetActiveViewCell() const
401        { return mActiveViewCell; }
402
403        /** Sets this view cell to be an active view cell.
404        */
405        void SetActiveViewCell(ViewCell *vc)
406        { mActiveViewCell = vc;}
407       
408        /** points to the currently active view cell. This is the
409                view cell representing the current brach.
410        */
411        ViewCell *mActiveViewCell;
412};
413
414
415/** Leaf of the view cell hierarchy corresponding
416        to a leaf in a spatial hierarchy.
417*/
418template<typename T>
419class HierarchyLeafViewCell: public ViewCellLeaf
420{
421public:
422
423        HierarchyLeafViewCell<T>(): ViewCellLeaf() {  }
424        HierarchyLeafViewCell<T>(Mesh *mesh):
425        ViewCellLeaf(mesh) {  }
426               
427        bool IsLeaf() const
428        {
429                return true;
430        }
431
432        /// Leaves of some hierarchy which contains this view cell.
433        vector<T> mLeaves;
434};
435
436
437typedef HierarchyLeafViewCell<VspLeaf *> VspViewCell;
438typedef HierarchyLeafViewCell<BspLeaf *> BspViewCell;
439typedef HierarchyLeafViewCell<KdLeaf *> KdViewCell;
440
441
442
443
444class ViewCellsTree
445{
446        friend class ViewCellsManager;
447        friend class ViewCellsParseHandlers;
448
449public:
450
451        ViewCellsTree();
452
453        /** View cells tree constructor taking a view cell mnanager as parameter
454        */
455        ViewCellsTree(ViewCellsManager *vcm);
456        ~ViewCellsTree();
457
458        /** Returns number of leaves this view cell consists of.
459        */
460        int GetNumInitialViewCells(ViewCell *vc) const;
461
462        /** Collects leaves corresponding to a view cell.
463        */
464        void CollectLeaves(ViewCell *vc, ViewCellContainer &leaves) const;
465
466        /** Merges view cells according to some cost heuristics.
467        */
468        int ConstructMergeTree(const VssRayContainer &rays, const ObjectContainer &objects);
469       
470        /** Refines view cells using shuffling, i.e., border leaves
471                of two view cells are exchanged if the resulting view cells
472                are tested to be "better" than the old ones.
473                @returns number of refined view cells
474        */
475        int RefineViewCells(const VssRayContainer &rays, const ObjectContainer &objects);
476       
477        /** Assign colors to the viewcells so that they can be renderered interactively without
478            color flickering. 
479        */
480        void AssignRandomColors();
481
482        /** Updates view cell stats for this particular view cell.
483        */
484        void UpdateViewCellsStats(ViewCell *vc, ViewCellsStatistics &vcStat);
485
486        /** Get costs resulting from each merge step.
487        */
488        void GetCostFunction(vector<float> &costFunction);
489       
490        /** Returns storage cost resulting from each merge step.
491        */
492        void GetStorageFunction(vector<int> &storageCost);
493
494        /** Returns optimal set of view cells for a given number of view cells.
495        */
496        void CollectBestViewCellSet(ViewCellContainer &viewCells, const int numViewCells);
497
498        /** Root of view cells tree.
499        */
500        ViewCell *GetRoot() const;
501
502        /** Returns pvs of view cell.
503                @note pvs is returned per reference if tree is not compressed,
504                per copy else.
505        */
506        void GetPvs(ViewCell *vc, ObjectPvs &pvs) const;
507
508        /** Returns pvs size (i.e. the render cost of the stored objects)
509        */
510        float GetTrianglesInPvs(ViewCell *vc) const;
511 
512        /** Returns number of entries associated with this view cell.
513
514                This returns the same value as the "GetPvsSize" function for object pvs
515                but most likely different values if we use object space grouping.
516                E.g., using bounding volumes.
517        */
518        int GetPvsEntries(ViewCell *vc) const;
519
520        /** Returns the number of physically stored entries in the view cells sub tree.
521                This can vary based on the current storage method
522        */
523        int CountStoredPvsEntries(ViewCell *root) const;
524
525        /** Returns memory cost of this view cell.
526        */
527        float GetMemoryCost(ViewCell *vc) const;
528
529        /** Sets method of storage for view cells.
530        */
531        void SetViewCellsStorage(int type);
532
533        /** pvs storage methods
534        */
535        enum {PVS_IN_INTERIORS, COMPRESSED, PVS_IN_LEAVES};
536
537        /** If view cells in this tree have compressed pvs.
538        */
539        int ViewCellsStorage() const;
540
541        /** Returns active view cell that is in the path of this view cell.
542        */
543        ViewCell *GetActiveViewCell(ViewCellLeaf *vc) const;
544
545        /** Sets the leaves to be the currently active view cells.
546        */
547    void SetActiveSetToLeaves();
548
549        /** Propagates pvs up the tree to the root and downwards the tree.
550        */
551        void PropagatePvs(ViewCell *vc);
552
553        /** Exports view cells to file.
554        */
555        bool Export(OUT_STREAM &stream, const bool exportPvs = false);
556
557        /** Export statistics of this view cell tree.
558        */
559        void ExportStats(const std::string &mergeStats);
560
561        /** Sets root of hierarchy.
562        */
563        void SetRoot(ViewCell *root);
564
565        /** Assignes unique ids to view cells.
566        */
567        void CreateUniqueViewCellsIds();
568
569        /** Resets pvs of whole tree.
570        */
571        void ResetPvs();
572
573        /** Counts pvs of the view cell taking the kd cells into account.
574        */
575        int CountKdPvs(const ViewCellLeaf *vc) const;
576
577        /** Sets pointer to view cells manager.
578        */
579        void SetViewCellsManager(ViewCellsManager *vcm);
580
581        void Update();
582
583protected:
584
585        /** Reads the environment and sets member variables.
586        */
587        void ReadEnvironment();
588
589
590        //////////////////////////////////////////////////////////////
591        //                    merge related stuff                   //
592        //////////////////////////////////////////////////////////////
593
594
595        /** Computes render cost of the merged pvs.
596        */
597        float ComputeMergedPvsCost(const ObjectPvs &pvs1, const ObjectPvs &pvs2) const;
598
599        /** Returns cost of this leaf according to current heuristics.
600        */
601        float GetCostHeuristics(ViewCell *vc) const;
602
603        /** Returns cost of leaf.
604        */
605        float GetRenderCost(ViewCell *vc) const;
606
607        /** Evaluates the merge cost of this merge candidate pair.
608        */
609        void EvalMergeCost(MergeCandidate &mc) const;
610
611        /** Variance of leaf.
612        */
613        float GetVariance(ViewCell *vc) const;
614
615        /** Standard deviation of leaf.
616        */
617        float GetDeviation(ViewCell *vc) const;
618
619        /** Tries to set this merge candidate to valid.
620                @returns false if both view cells are the same
621        */
622        bool ValidateMergeCandidate(MergeCandidate &mc) const;
623
624        /** Merge view cells of leaves l1 and l2.
625                @returns difference in pvs size
626        */
627        ViewCellInterior *MergeViewCells(ViewCell *l, ViewCell *r, float &pvsDiff);
628
629        /** Shuffles, i.e. takes border leaf from view cell 1 and adds it
630                to view cell 2.
631        */
632        void ShuffleLeaf(ViewCell *leaf, ViewCellInterior *vc1, ViewCellInterior *vc2) const;   
633               
634        /** Shuffles the leaves, i.e., tests if exchanging
635                the leaves helps in improving the view cells.
636        */
637        bool ShuffleLeaves(MergeCandidate &mc) const;
638
639        /** Calculates cost for merge of view cell 1 and 2.
640        */
641        float EvalShuffleCost(ViewCell *leaf,
642                                                  ViewCellInterior *vc1,
643                                                  ViewCellInterior *vc2) const;
644
645        /** Exports a snapshot of the merged view cells to disc.
646        */
647        void ExportMergedViewCells(ViewCellContainer &viewCells,
648                                                           const ObjectContainer &objects,
649                                                           const int numNewViewCells);
650
651        /** Merge queue must be reset after some time because expected value
652                may not be valid.
653        */
654        void ResetMergeQueue();
655
656        /** Updates the current cut of view cells.
657                @returns number of newly merged view cells
658        */
659        int UpdateActiveViewCells(ViewCellContainer &viewCells);
660
661        /** Helper function pullling pvs as high up in the tree as possible.
662        */
663        void PullUpVisibility(ViewCellInterior *interior);
664
665        /** Compress pvs of view cell and children.
666        */
667        void CompressViewCellsPvs(ViewCell *root);
668
669        /** Returns memory usage of view cells.
670        */
671        float GetMemUsage() const;
672
673        /**     Exports single view cell.
674                NOTE: should be in exporter!!
675        */
676        void ExportViewCell(ViewCell *viewCell, OUT_STREAM &stream, const bool exportPvs);     
677
678        /** Exports pvs of a view cell.
679        */
680        void ExportPvs(ViewCell *viewCell, OUT_STREAM &stream);
681
682        /** Counts the logical number of entries in the pvs this view cell.
683                The pvs is assumed to be stored using lossless compression.
684        */
685        int GetEntriesInPvsForCompressedStorage(ViewCell *vc) const;
686
687        /** Computes pvs size of this view cell.
688                The pvs is assumed to be stored using lossless compression.
689        */
690        float GetPvsCostForCompressedStorage(ViewCell *vc) const;
691       
692        /** Computes pvs size of this view cell.
693                The pvs is assumed to be stored in the leaves.
694        */
695        float GetPvsCostForLeafStorage(ViewCell *vc) const;
696
697        /** Counts the logical number of entries in the pvs this view cell.
698                The pvs is assumed to be stored using the leaves.
699        */
700        int GetEntriesInPvsForLeafStorage(ViewCell *vc) const;
701
702        /** Update stats for the log.
703        */
704        void UpdateStats(std::ofstream &stats,
705                                         const ViewCellsTreeStats &vcStats);
706
707       
708
709        //////////////////////////////////////
710
711        /// if the view cell tree hold compressed pvs
712        int mViewCellsStorage;
713        /// pointer to the view cells manager
714        ViewCellsManager *mViewCellsManager;
715        /// the root of the view cells hierarchy
716        ViewCell *mRoot;
717
718        /// if merge visualization should be shown
719        bool mExportMergedViewCells;
720        /// intermediate container of merged view cells.
721        ViewCellContainer mMergedViewCells;
722        /// if merged view cells are refined.
723        bool mRefineViewCells;
724        /// weights between variance and render cost increase in the range [0 .. 1].
725        float mRenderCostWeight;
726
727        /// overall cost used to normalize cost ratio
728        float mOverallCost;
729        float mExpectedCost;
730    float mDeviation;
731        float mAvgRenderCost;
732       
733        /// the area is used for pvs heuristics
734        int mUseAreaForPvs;
735        /// number of currently active view cells (=current cut)
736        int mNumActiveViewCells;
737        /// minimal number of view cells
738        int mMergeMinViewCells;
739        /// maximal cost ratio for the merge
740        float mMergeMaxCostRatio;
741
742        typedef std::priority_queue<MergeCandidate> MergeQueue;
743
744        MergeQueue mMergeQueue;
745
746        float mMaxMemory;
747
748        int mMaxMergesPerPass;
749        float mAvgCostMaxDeviation;
750};
751
752
753/**
754        Candidate for leaf merging based on priority.
755*/
756class MergeCandidate
757
758        friend class ViewCellsTree;
759
760public:
761
762        MergeCandidate(ViewCell *l, ViewCell *r);
763
764        /** If this merge pair is still valid.
765        */
766        bool IsValid() const;
767
768       
769        friend bool operator<(const MergeCandidate &leafa, const MergeCandidate &leafb)
770        {
771                return leafb.GetMergeCost() < leafa.GetMergeCost();
772        }
773
774        void SetLeftViewCell(ViewCell *l);
775        void SetRightViewCell(ViewCell *l);
776
777        ViewCell *GetLeftViewCell() const;
778        ViewCell *GetRightViewCell() const;
779
780        /** Returns leaf view cell initially associated with this merge candidate.
781        */
782        ViewCell *GetInitialLeftViewCell() const;
783        /** Returns leaf view cell initially associated with this merge candidate.
784        */
785        ViewCell *GetInitialRightViewCell() const;
786
787        /** Returns the increase of the standard deviation of this merge candidate.
788        */
789        float GetDeviationIncr() const;
790
791        /** Merge cost of this candidate pair.
792        */
793        float GetMergeCost() const;
794
795        /** Render cost of this candidate.
796        */
797        float GetRenderCost() const;
798       
799        static float sRenderCostWeight;
800
801protected:
802
803        /// render cost increase by this merge
804        float mRenderCost;
805        /// increase / decrease of standard deviation
806        float mDeviationIncr;
807
808        ViewCell *mLeftViewCell;
809        ViewCell *mRightViewCell;
810
811        ViewCell *mInitialLeftViewCell;
812        ViewCell *mInitialRightViewCell;
813};
814
815
816class MergeStatistics: public StatisticsBase
817{
818public:
819       
820        int merged;
821        int siblings;
822        int candidates;
823        int nodes;
824
825        int accTreeDist;
826        int maxTreeDist;
827       
828        Real collectTime;
829        Real mergeTime;
830
831        Real overallCost;
832
833        Real expectedRenderCost;
834        Real deviation;
835        Real heuristics;
836
837        // Constructor
838        MergeStatistics()
839        {
840                Reset();
841        }
842       
843        double AvgTreeDist() const {return (double)accTreeDist / (double)merged;};
844
845        void Reset()
846        {
847                nodes = 0;
848                merged = 0;
849                siblings = 0;
850                candidates = 0;
851       
852                accTreeDist = 0;
853                maxTreeDist = 0;
854
855                collectTime = 0;
856                mergeTime = 0;
857                overallCost = 0;
858
859                expectedRenderCost = 0;
860                deviation = 0;
861                heuristics = 0;
862
863        }
864
865        void Print(std::ostream &app) const;
866
867        friend std::ostream &operator<<(std::ostream &s, const MergeStatistics &stat)
868        {
869                stat.Print(s);
870                return s;
871        }
872};
873
874}
875
876#endif
Note: See TracBrowser for help on using the repository browser.