source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h @ 2598

Revision 2598, 38.8 KB checked in by mattausch, 16 years ago (diff)
Line 
1#ifndef _ViewCellsManager_H__
2#define _ViewCellsManager_H__
3
4#include "Ray.h"
5#include "SimpleRay.h"
6#include "VssRay.h"
7#include "Containers.h"
8#include "ViewCell.h"
9#include "RandomViewCellsHandler.h"
10
11
12#define TEST_PACKETS 0
13
14namespace GtpVisibilityPreprocessor {
15
16class ViewCell;
17class Intersectable;
18class RenderSimulator;
19class Renderer;
20class Mesh;
21struct Triangle3;
22class SimulationStatistics;
23class BspTree;
24class KdTree;
25class VspOspTree;
26class VspBspTree;
27class KdNode;
28class KdLeaf;
29class AxisAlignedBox3;
30class BspLeaf;
31class ViewCellsStatistics;
32class Exporter;
33class Beam;
34class Preprocessor;
35class ViewCellsTree;
36class MergeCandidate;
37class BoundingBoxConverter;
38class VspTree;
39class OspTree;
40class VspNode;
41class HierarchyManager;
42class BvHierarchy;
43class ViewCellsTree;
44class ViewCell;
45class MixtureDistribution;
46struct AxisAlignedPlane;
47struct BspRay;
48class BspTree;
49//class RandomViewCellsHandler;
50
51
52struct PvsFilterStatistics
53{
54        PvsFilterStatistics():
55        mAvgFilterRadius(0.0f), mLocalFilterCount(0), mGlobalFilterCount(0) {}
56       
57        float mAvgFilterRadius;
58        int mLocalFilterCount;
59        int mGlobalFilterCount;
60};
61
62/** Probably Visible Set
63*/
64class PrVs
65{
66public:
67        /// root of view cells tree
68        ViewCell *mViewCell;
69        // input parameter is the render budget for the PrVs
70        float mRenderBudget;
71};
72
73
74class LocalMergeNode
75{
76public:
77        virtual ~LocalMergeNode() {};
78        virtual bool IsLeaf() const = 0;
79};
80
81
82struct VizBuffer
83{
84        VizBuffer(): mIndex(0), mMaxSize(10000)
85        {
86        }
87
88        int GetSize() const {return (int)mVizRays.size();}
89
90        void AddRay(VssRay *ray)
91        {
92                if (mVizRays.size() < mMaxSize)
93                        mVizRays.push_back(ray);
94                else
95                        mVizRays[mIndex] = ray;
96               
97                mIndex = (mIndex + 1) % mMaxSize;
98        }
99
100        VssRayContainer &GetRays() { return mVizRays;}
101
102        VssRay *GetRay(int i) { return mVizRays[i % 100];}
103
104protected:
105
106        const int mMaxSize;
107        int mIndex;
108        VssRayContainer mVizRays;
109};
110
111
112/**     Manages different higher order operations on the view cells.
113*/
114class ViewCellsManager
115{
116public:
117
118        struct PerViewCellStat
119        {
120                float pvsSize;
121                float relPvsIncrease;
122        };
123
124        struct SamplesStatistics
125        {
126                int mRays;
127                int mViewCells;
128                int mContributingRays;
129                int mPvsContributions;
130                float mRayLengths;
131
132                void Reset()
133                {
134                        mRayLengths = 0.0f;
135                        mRays = 0;
136                        mViewCells = 0;
137                        mContributingRays = 0;
138                        mPvsContributions = 0;
139                };
140        };
141
142        struct PvsStatistics
143        {
144                float minPvs;
145                float maxPvs;
146                float avgPvs;
147                float renderCost;
148                float avgPvsEntries;
149
150                float avgFilteredPvs;
151                float avgFilteredPvsEntries;
152
153                float avgFilterContribution;
154                float avgFilterRadius;
155                float avgFilterRatio;
156                float avgRelPvsIncrease;
157                float devRelPvsIncrease;
158                int viewcells;
159
160                float mem;
161                float renderCostRatio;
162        };
163 
164        /// view cell container types
165        enum {BSP, KD, VSP_KD, VSP_BSP, VSP_OSP};
166 
167        /// render cost evaluation type
168        enum {PER_OBJECT, PER_TRIANGLE};
169
170        friend class X3dViewCellsParseHandlers;
171
172        /** Default constructor.
173        */
174        ViewCellsManager(ViewCellsTree *viewCellsTree);
175        /** Destructor.
176        */
177        virtual ~ViewCellsManager();
178        /** Constructs view cells container taking a preprocessor
179                @returns the output rays (if not null)
180        */
181        int Construct(Preprocessor *preprocessor, VssRayContainer *outRays = NULL);
182
183        /** Constructs view cell container with a given number of samples.
184        */
185        virtual int ConstructSubdivision(const ObjectContainer &objects,
186                                                                         const VssRayContainer &rays) = 0;
187
188        /** Computes sample contributions of the rays to the view cells PVS.
189       
190                @param rays bundle of rays used to find intersections with view cells and
191                adding the contribution
192                @param addRays true if rays should be added to the PVSs of the viewcells they
193                intersect
194                @param storeViewCells true if view cells should be stored in the ray
195        */
196        virtual float ComputeSampleContributions(const VssRayContainer &rays,
197                                                     const bool addContributions,
198                                                                                         const bool storeViewCells,
199                                                                                         const bool useHitObject = false);
200
201        /** Computes sample contribution of a simgle ray to the view cells PVS.
202                @param ray finds intersections with view cells and holds the contribution
203                @param addSample if sample should be added to the pvs
204                 
205                @returns number of sample contributions
206        */
207        virtual float ComputeSampleContribution(VssRay &ray,
208                                                                                        const bool addContributions,
209                                                                                        const bool storeViewCells,
210                                                                                        const bool useHitObject = false);
211        /** Compute sample contribution only for current view cell.
212        */
213        virtual float ComputeSampleContribution(VssRay &ray,
214                                                                                        const bool addContributions,
215                                                                                        ViewCell *currentViewCell,
216                                                                                        const bool useHitObject = false);
217        /** Prints out statistics of the view cells.
218        */
219        virtual void PrintStatistics(std::ostream &s) const;
220        /** Post processes view cells givemŽa number of rays.
221        */
222        virtual int PostProcess(const ObjectContainer &objects,
223                                                        const VssRayContainer &rays) = 0;
224        /** Show visualization of the view cells.
225        */
226        virtual void Visualize(const ObjectContainer &objects,
227                                                   const VssRayContainer &sampleRays) = 0;
228        /** collect objects intersecting a given spatial box.
229        */
230        virtual void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
231        /** type of the view cell container.
232        */
233        virtual int GetType() const = 0;
234        /** Load the input viewcells. The input viewcells should be given as a collection
235                of meshes. Each mesh is assume to form a bounded polyhedron
236                defining the interior of the viewcell. The view cells manager
237                is responsible for building a hierarchy over these view cells.
238               
239                @param filename file to load
240                @return true on success
241        */
242        virtual bool LoadViewCellsGeometry(const string filename, const bool extrudeBaseTriangle);
243        /** Merges two view cells.
244                @note the piercing rays of the front and back will be ordered   
245                @returns new view cell based on the merging.
246        */
247        ViewCellInterior *MergeViewCells(ViewCell *front, ViewCell *back) const;
248        /** Merges a container of view cells.
249                @returns new view cell based on the merging.
250        */
251        ViewCellInterior *MergeViewCells(ViewCellContainer &children) const;
252        /** Generates view cell of the type specified by this manager
253        */
254        virtual ViewCell *GenerateViewCell(Mesh *mesh = NULL) const = 0;
255        /** Constructs view cell from base triangle.
256                The view cell is extruded along the normal vector.
257                @param the base triangle
258                @param the height of the newly created view cell
259        */
260        ViewCell *ExtrudeViewCell(const Triangle3 &baseTri, const float height) const;
261        /** Returns the intersectable that was hit by the ray.
262        */
263        virtual Intersectable *GetIntersectable(const VssRay &ray, const bool isTermination) const;
264        /** Sets maximal number of samples used for the
265                construction of the view cells.
266        */
267        void SetVisualizationSamples(const int visSamples);
268        /** Sets maximal number of samples used for the construction of the view cells.
269        */
270        void SetConstructionSamples(const int constructionSamples);
271        /** Sets maximal number of samples used for the visualization of the view cells.
272        */
273        void SetInitialSamples(const int initialSamples);
274        /** Sets maximal number of samples used for the post processing of the view cells.
275        */
276        void SetPostProcessSamples(const int postProcessingSamples);
277        /** See set.
278        */
279        int GetVisualizationSamples() const;
280        /** See set.
281        */
282        int GetConstructionSamples() const;
283        /** See set.
284        */
285        int GetPostProcessSamples() const;
286        /** Returns true if view cells are already constructed.
287        */
288        virtual bool ViewCellsConstructed() const = 0;
289        /** cast line segment to get a list of unique viewcells which are intersected
290                by this line segment
291        */
292        virtual int CastLineSegment(const Vector3 &origin,
293                                                            const Vector3 &termination,
294                                                            ViewCellContainer &viewcells) = 0;
295        /** Tests if this line segment intersects a particular view cell.
296        */
297        virtual bool LineSegmentIntersects(const Vector3 &origin,
298                                                                           const Vector3 &termination,
299                                                                           ViewCell *viewCell) = 0;
300        /** Returns a stats about the global pvs.
301        */
302        virtual void GetPvsStatistics(PvsStatistics &stat);
303        /** Returns the probably visible set of the view space filtered pvs.
304        */
305        virtual void GetPrVS(const Vector3 &viewPoint, PrVs &prvs, const float filterWidth);
306        /** Get a viewcell containing the specified view point.
307                @param active if the active or elementary view cell should be returned.
308        */
309        virtual ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const = 0;
310        /** Returns the view cell with the given index (different from the id).
311        */
312        ViewCell *GetViewCell(const int idx) const {return mViewCells[idx];}
313        /** Prints the statistics over the view cell pvss.
314        */
315        virtual void PrintPvsStatistics(std::ostream &s);
316        /** Updates pvs of the view cell hierarchy if necessary.
317        */
318        void UpdatePvs();
319        /** Returns probability that view point lies in one view cell.
320        */
321        virtual float GetProbability(ViewCell *viewCell) = 0;
322        /** Returns render cost of a single view cell given the render cost of an object.
323        */
324        float GetRendercost(ViewCell *viewCell) const;
325        /** Returns reference to container of loaded / generated view cells.
326        */
327        ViewCellContainer &GetViewCells();
328        /** Helper function used to split ray sets uniformly
329                into one that is currently used and the other that
330                is saved for later processing.
331                @param sourceRays the input ray set
332                @param maxSize the maximal number of rays that will be used
333                @param usedRays returns the used ray set
334                @param savedRays if not null, returns the saved ray set
335        */
336        void GetRaySets(const VssRayContainer &sourceRays,
337                                        const int maxSize,
338                                        VssRayContainer &usedRays,
339                                        VssRayContainer *savedRays = NULL) const;
340        /** Returns accumulated area of all view cells.
341        */
342        float GetAccVcArea();
343        /** Returns area of one view cell.
344        */
345        virtual float GetArea(ViewCell *viewCell) const;
346        /** Returns volume of view cell.
347        */
348        virtual float GetVolume(ViewCell *viewCell) const;
349        /** Sets the current renderer mainly for view cells statistics.
350        */
351        void SetRenderer(Renderer *renderer);
352        /** Computes a (random) view point in the valid view space.
353                @returns true if valid view point was found
354        */
355        virtual bool GetViewPoint(Vector3 &viewPoint) const;
356        /** Returns the current view point given a vector for activating the halton sequence.
357        */
358        virtual bool GetViewPoint(Vector3 &viewPoint, const Vector3 &params) const;
359        /** Returns true if this view point is in the valid view space.
360        */
361        virtual bool ViewPointValid(const Vector3 &viewPoint) const;
362        /** Sets a view space boundary.
363        */
364        void SetViewSpaceBox(const AxisAlignedBox3 &box);
365        /** Returns the boundaries of the view space.
366        */
367        AxisAlignedBox3 GetViewSpaceBox() const;
368        /** Creates mesh for this view cell.
369        */
370        virtual void CreateMesh(ViewCell *vc) = 0;
371        /** Writes view cells to disc.
372        */
373        virtual bool ExportViewCells(const string filename,
374                                     const bool exportPvs,
375                                     const ObjectContainer &objects);
376        /** Casts beam to collect view cells.
377        */
378        virtual int CastBeam(Beam &beam);
379        /** Checks if view cell is considered as valid.
380        */
381        virtual bool CheckValidity(ViewCell *vc,
382                                                           int minPvsSize,
383                                                           int maxPvsSize) const;
384        /** Resort pvss after a pass of the algorithm.
385        */
386        void  SortViewCellPvs();
387        /** Map the ray intersection objects from triangles to high level objects.
388        */
389        void DeterminePvsObjects(VssRayContainer &rays,
390                                                         const bool useHitObjects = false);
391        /** Sets validity of view cell
392        */
393        virtual void SetValidity(ViewCell *vc,
394                                                         int minPvsSize,
395                                                         int maxPvsSize) const;
396        /** sets validy of all viewcells
397        */
398        virtual void SetValidity(int minPvsSize, int maxPvsSize) const;
399        /** Set valid viewcells in the range of pvs. sorts the viewcells
400                according to the pvs and then pickups those in the ranges
401        */
402        void SetValidityPercentage(const float minValid, const float maxValid);
403        /** Returns number of valid view cells.
404        */
405    int CountValidViewcells() const;
406        /** Returns maximal allowed pvs size.
407        */
408        int GetMaxPvsSize() const;
409        /** Returns maximal allowed pvs size.
410        */
411        int GetMinPvsSize() const;
412        /** Returns maximal ratio. i.e., currentPVs / maxPvs,
413                where pvs is still considered valid.
414        */
415        float GetMaxPvsRatio() const;
416        /** Exports view cell geometry.
417        */
418        virtual void ExportViewCellGeometry(Exporter *exporter,
419                                                                                ViewCell *vc,
420                                                                                const AxisAlignedBox3 *box,
421                                                                                const AxisAlignedPlane *clipPlane = NULL
422                                                                                ) const = 0;
423        /** Brings the view cells into their final state, computes meshes and volume.
424        */
425        virtual void FinalizeViewCells(const bool createMesh);
426        /** Evaluates statistics values on view cells.
427        */
428        void EvaluateRenderStatistics(float &totalRenderCost,
429                                                                  float &expectedRenderCost,
430                                                                  float &deviation,
431                                                                  float &variance,
432                                                                  float &totalPvs,
433                                                                  float &avgRenderCost);
434        /** Returns hierarchy of the view cells.
435        */
436        ViewCellsTree *GetViewCellsTree();
437        /** Collect candidates for the view cell merge.
438        */
439        virtual void CollectMergeCandidates(const VssRayContainer &rays,
440                                                                                vector<MergeCandidate> &candidates);
441        /** Collects n view cells and stores it as the active view cells.
442        */
443        void CollectViewCells(const int n);
444        /** Sets current view cells set to active,
445                i.e., the sampling is done in this view cell set.
446        */
447        void SetViewCellsActive();
448        /** Evaluates render cost statistics of current view cell hierarchy.
449        */
450        virtual void EvalViewCellPartition();
451        /** Sets maximal size of a view cell filter.
452        */
453        void SetMaxFilterSize(const int size);
454        /** Returns maximal filter size.
455        */
456        int GetMaxFilterSize() const;
457        /** Deletes interior nodes from the tree which have negative
458                merge cost set (local merge).
459        */ 
460        void DeleteLocalMergeTree(ViewCell *vc) const;
461        /** Evaluautes histogram for a given number of view cells.
462        */
463        void EvalViewCellHistogram(const string filename, const int nViewCells);
464        /** Evaluautes histogram for a given number of view cells.
465        */
466        void EvalViewCellHistogramForPvsSize(const string filename,
467                                                                                 const int nViewCells);
468        /** Evaluautes histogram for a given vector of view cells.
469        */
470        void EvalViewCellHistogramForPvsSize(const string filename,
471                                                                                 ViewCellContainer &viewCells);
472        float ComputeRenderCost(const int tri, const int obj); //const
473        /** Sets pvs size of a view cell as a scalar. Used when storing pvs only in the leaves
474                of the hierarchy.
475        */
476        void UpdateScalarPvsSize(ViewCell *vc,
477                                                         const float pvsCost,
478                                                         const int entriesInPvs) const;
479        /** Sets render cost of a view cell as a scalar.
480        */
481        void UpdateScalarPvsCost(ViewCell *vc, const float pvsCost) const;
482
483        /** Returns bounding box of a view cell.
484        */
485        AxisAlignedBox3 GetViewCellBox(ViewCell *vc);
486        /** Exports bounding boxes of objects to file.
487        */
488        bool ExportBoundingBoxes(const string filename,
489                                                         const ObjectContainer &objects) const;
490        /** Load the bounding boxes into the container.
491        */
492        bool LoadBoundingBoxes(const string filename,
493                                                  IndexedBoundingBoxContainer &boxes) const;
494        /** Returns true if pvs should be exported together with the view cells.
495        */
496        bool GetExportPvs() const;
497        /** Efficiently merges the view cells in the container.
498        */
499        void MergeViewCellsRecursivly(ObjectPvs &pvs,
500                                                                  const ViewCellContainer &viewCells) const;
501        /** Compresses the view cells.
502        */
503        virtual void CompressViewCells();
504        /** Returns view cell with the given id.
505        */
506        ViewCell *GetViewCellById(const int id);
507        /** Returns number of view cells.
508        */
509        int GetNumViewCells() const;
510        /** Returns the stored list of view cells and view points.
511        */
512        ViewCellPointsList *GetViewCellPointsList();
513        /** Exports list of random view cells.
514        */
515        bool ExportRandomViewCells(const string &filename);
516        /** Imports list of random view cells and view points.
517        */
518        bool ImportViewCellsList(const string &filename);
519
520
521        //////////////
522        // static members
523       
524        /** Loads view cells from file. The view cells manager is created with
525                respect to the loaded view cells.
526
527                @param filename the filename of the view cells
528                @param objects the scene objects
529                @param finalizeViewCells if the view cells should be post processed, i.e.,
530                           a mesh is created representing the geometry
531                @param bconverter a conversion routine working with the similarities of bounding
532                           boxes: if there is a certain similarity of overlap between
533                           bounding boxes, two tested candidate objects are considered
534                           to be the same objects
535                @returns the view cells manager if loading was successful, false otherwise
536        */
537        static ViewCellsManager *LoadViewCells(const string &filename,
538                                                                                   ObjectContainer &pvsObjects,
539                                                                                   ObjectContainer &preprocessorObjects,
540                                                                                   bool finalizeViewCells = false,
541                                                                                   BoundingBoxConverter *bconverter = NULL);
542
543        /** Convenience function assuming that there are no preprocessor objects.
544        */
545        static ViewCellsManager *LoadViewCells(const string &filename,
546                                                                                   ObjectContainer &pvsObjects,
547                                                                                   bool finalizeViewCells = false,
548                                                                                   BoundingBoxConverter *bconverter = NULL);
549
550
551        ///////////////////////
552        //-- visiblity filter options
553
554        // TODO: write own visibiltiy filter class
555        void ApplyFilter(KdTree *kdTree,
556                                         const float viewSpaceFilterSize,
557                                         const float spatialFilterSize);
558
559        // new adaptive version of the filter
560        PvsFilterStatistics ApplyFilter2(ViewCell *viewCell,
561                                                                         const bool useViewSpaceFilter,
562                                                                         const float filterSize,
563                                                                         ObjectPvs &pvs,
564                                                                         vector<AxisAlignedBox3> *filteredBoxes = NULL,
565                                                                         const bool onlyNewObjects = false);
566
567        void ApplySpatialFilter(KdTree *kdTree,
568                                                        const float spatialFilterSize,
569                                                        ObjectPvs &pvs);
570
571         void ApplyFilter(ViewCell *viewCell,
572                                          KdTree *kdTree,
573                                          const float viewSpaceFilterSize,
574                                          const float spatialFilterSize,
575                                          ObjectPvs &pvs);
576
577        float GetFilterWidth();
578
579        float GetAbsFilterWidth();
580        /** Returns the bounding box of filter width.
581        */
582        AxisAlignedBox3 GetFilterBBox(const Vector3 &viewPoint,
583                                                                  const float width) const;
584
585
586
587        //////////////////////////////////////////////////////////////////
588
589
590        /** If true, the kd nodes are stored instead of the object pvs.
591        */
592        void SetStoreKdPvs(const bool storeKdPvs);
593
594        /** Returns true if the kd nodes are stored instead of the object pvs.
595        **/
596        bool GetStoreKdPVs() const;
597
598        /** Exports single view cells for visualization.
599                @param objects the scene objects
600                @param limit the maximal number of output view cells
601                @param sortViewCells if the view cells should be sorted by pvs size
602                @param exportPvs if the pvs should also be exported
603                @param exportRays if sample rays should be exported as well
604                @param maxRays maximum number of rays to export
605                @param prefix the prefix for the output file
606                @param visRays additional rays
607        */
608        virtual void ExportSingleViewCells(const ObjectContainer &objects,
609                                                                           const int maxViewCells,
610                                                                           const bool sortViewCells,
611                                                                           const bool exportPvs,
612                                                                           const bool exportRays,
613                                                                           const int maxRays,
614                                                                           const string &prefix,
615                                                                           VssRayContainer *visRays = NULL) = 0;
616
617
618        void ResetPvs();
619
620        Preprocessor *GetPreprocessor() const
621        {
622                return mPreprocessor;
623        }
624
625        void SetPreprocessor(Preprocessor *p)
626        {
627                mPreprocessor = p;
628        }
629
630        void UpdatePvsForEvaluation();
631
632
633        VizBuffer mVizBuffer;
634
635
636protected:
637
638        bool ComputeViewCellContribution(ViewCell *viewCell,
639                                                                         VssRay &ray,
640                                                                         Intersectable *obj,
641                                                                         const Vector3 &pt,
642                                                                         const bool addRays);
643
644        void MergeViewCellsRecursivly(ObjectPvs &pvs,
645                                                                  const ViewCellContainer &viewCells,
646                                                                  const int leftIdx,
647                                                                  const int rightIdx) const;
648        /** Intersects box with the tree and returns the number of intersected boxes.
649                @returns number of view cells found
650        */
651        virtual int ComputeBoxIntersections(const AxisAlignedBox3 &box,
652                                                                                ViewCellContainer &viewCells) const;
653        /** Tests the visibility filter functionality.
654        */
655        virtual void TestFilter(const ObjectContainer &objects) {};
656        /** If the view cells tree was already constructed or not.
657        */
658        bool ViewCellsTreeConstructed() const;
659        /** Requests preprocessor to cast samplesPerPass samples of a specific type.
660        */
661        int CastPassSamples(const int samplesPerPass,
662                                                const vector<int> &strategies,
663                                                VssRayContainer &vssRays) const;
664        /** cast samples for the purpose of evaluating the view cells solution
665        */
666        int CastEvaluationSamples(const int samplesPerPass,
667                                                          VssRayContainer &passSamples);// const;
668        /** Parse the options from the environment file.
669        */
670        void ParseEnvironment();
671        /** Creates unique view cell ids.
672        */
673        void CreateUniqueViewCellIds();
674        /** Finalizes, i.e., creates mesh, volume, area etc. for the view cell.
675        */
676        virtual void Finalize(ViewCell *viewCell, const bool createMesh);
677        /** Recollects view cells and resets statistics.
678        */
679        void ResetViewCells();
680        /** Sets this view cell to active.
681        */
682        void SetViewCellActive(ViewCell *vc) const;
683        /** Collects the view cells in the view cell container.
684        */
685        virtual void CollectViewCells() = 0;
686        /** Evaluates view cells statistics and stores it in mViewCellsStatistics.
687        */
688        void EvaluateViewCellsStats();
689       
690
691        void UpdateStatsForViewCell(ViewCell *viewCell, Intersectable *obj);
692
693
694        ///////////////////////
695        //-- helper functions for view cell visualization
696
697        /** Exports the view cell partition.
698        */
699        void ExportViewCellsForViz(Exporter *exporter,
700                                                           const AxisAlignedBox3 *box,
701                                                           const bool colorCode,
702                                                           const AxisAlignedPlane *clipPlane) const;
703        /** Sets exporter color.
704        */
705        virtual void ExportColor(Exporter *exporter,
706                                                         ViewCell *vc,
707                                                         const int colorCode) const;
708        /** Creates meshes from the view cells.
709        */
710        void CreateViewCellMeshes();
711        /** Creates clip plane for visualization.
712        */
713        void CreateClipPlane();
714
715        AxisAlignedPlane *GetClipPlane();
716
717        void ExportMergedViewCells(const ObjectContainer &objects);
718
719
720        ///////////////////////
721
722        /** Returns volume of the view space.
723        */
724        virtual float GetViewSpaceVolume();
725        /** Prepares the view cells for sampling after loading them from disc.
726        */
727        virtual void PrepareLoadedViewCells() {};
728        /** Constructs local view cell merge hierarchy.
729        */
730        ViewCell *ConstructLocalMergeTree(ViewCell *currentViewCell,
731                                          const ViewCellContainer &viewCells);
732        /** Constructs local view cell merge hierarchy based solely on similarity with the
733                current viewcell
734        */
735        ViewCell *ConstructLocalMergeTree2(ViewCell *currentViewCell,
736                                                                           const ViewCellContainer &viewCells);
737        /** Updates pvs of all view cells for statistical evaluation after some more sampling
738        */
739        void UpdatePvsForEvaluation(ViewCell *root, ObjectPvs &pvs);
740        /** Export statistics of the view cells tree.
741        */
742        virtual void ExportStats(const string &mergeStats);
743        /** Loads view cells in binary mode.
744        */
745        static ViewCellsManager *LoadViewCellsBinary(const string &filename,
746                                                                                                 ObjectContainer &pvsObjects,
747                                                                                                 bool finalizeViewCells,
748                                                 BoundingBoxConverter *bconverter);
749        /** This helper function loads the bounding boxes for a binary solution.
750        */
751        static void LoadIndexedBoundingBoxesBinary(IN_STREAM &stream,
752                                                       IndexedBoundingBoxContainer &iboxes);
753
754
755
756        ///////////
757        //-- members
758
759        ofstream mStats;
760        Preprocessor *mPreprocessor;
761        /// if bounding boxes should be exported together with the view cells
762        bool mExportBboxesForPvs;
763        /// the clip plane for visualization
764        AxisAlignedPlane mClipPlaneForViz;
765        /// if the visualization is using the clip plane
766        bool mUseClipPlaneForViz;
767        /// Renders the view cells.
768        Renderer *mRenderer;
769        /// Loaded view cells
770        ViewCellContainer mViewCells;
771        /// the view cell hierarchy (i.e., the logical description of view cells)
772        ViewCellsTree *mViewCellsTree;
773       
774        std::vector<int> mStrategies;
775
776        /** if the values in the view cell leaves and the interiors are up to date
777                this is meant for lazy storing of the pvs, where only a scalar indicating
778                pvs size is stored in interiors and not the pvs itself.
779        */
780        bool mViewCellPvsIsUpdated;
781
782        /// maximum number of samples for the view cell construction
783        int mConstructionSamples;
784        int mSamplesPerPass;
785        int mInitialSamples;
786        int mPostProcessSamples;
787        int mVisualizationSamples;
788
789        int mEvaluationSamples;
790
791        float mTotalAreaValid;
792        float mTotalArea;
793
794        int mMaxPvsSize;
795        int mMinPvsSize;
796        float mMaxPvsRatio;
797
798        int mSamplingType;
799        int mEvaluationSamplingType;
800        int mNumActiveViewCells;
801        bool mCompressViewCells;
802
803        /// Handler for generating and loading random view cells.
804        RandomViewCellsHandler *mRandomViewCellsHandler;
805
806        /// holds the current view cell statistics
807        ViewCellsStatistics mCurrentViewCellsStats;
808
809        /// the scene bounding box
810        AxisAlignedBox3 mViewSpaceBox;
811       
812        /// if view cells should be exported
813        bool mExportViewCells;
814        // if only valid view cells should be considered for processing
815        bool mOnlyValidViewCells;
816        /// if rays should be used to collect merge candidates
817        bool mUseRaysForMerge;
818        /// if there should be an additional merge step after the subdivision
819        bool mMergeViewCells;
820        /// the width of the box filter
821        float mFilterWidth;
822        /// Maximal size of the filter in terms of contributing view cells
823        int mMaxFilterSize;
824        /// only for debugging: stores some rays used during view cell construction
825        VssRayContainer storedRays;
826        /// if kd node based pvs is used for preprocessing
827        bool mUseKdPvs;
828        /// types of distributions used for sampling
829        MixtureDistribution *mMixtureDistribution;
830
831
832
833        //////////////////
834        //-- visualization options
835       
836        /// color code for view cells visualization
837        bool mShowVisualization;
838        int mColorCode;
839        bool mExportGeometry;
840        bool mExportRays;
841        bool mViewCellsFinished;
842        bool mEvaluateViewCells;
843
844        /// if pvs should be exported with view cells
845        bool mExportPvs;
846
847        /// if view cells geometry should be used from other sources
848        bool mUsePredefinedViewCells;
849        /// the weight for one triangle in the heuristics
850        float mTriangleWeight;
851        /// the weight for one object (= one entity issued with one draw call) in the heuristics
852        float mObjectWeight;
853
854        vector<PerViewCellStat> mPerViewCellStat;
855        SamplesStatistics mSamplesStat;
856};
857
858
859/** Manages different higher order operations on the view cells.
860*/
861class BspViewCellsManager: public ViewCellsManager
862{
863
864public:
865        /** Constructor taking the bsp tree and the number of samples
866                used to construct the bsp tree.
867        */
868        BspViewCellsManager(ViewCellsTree *viewCellsTree, BspTree *tree);
869
870        ~BspViewCellsManager();
871
872        int ConstructSubdivision(const ObjectContainer &objects,
873                                  const VssRayContainer &rays);
874
875        int PostProcess(const ObjectContainer &objects,
876                                        const VssRayContainer &rays);
877
878        void Visualize(const ObjectContainer &objects,
879                                   const VssRayContainer &sampleRays);
880
881        int GetType() const;
882       
883        ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
884
885        bool ViewCellsConstructed() const;
886
887        //void PrintStatistics(ostream &s) const;
888
889        int CastLineSegment(const Vector3 &origin,
890                                                const Vector3 &termination,
891                                                ViewCellContainer &viewcells);
892       
893        /** Returns the probability that the view point lies
894                in this view cells.
895        */
896        float GetProbability(ViewCell *viewCell);
897
898        /** Get a viewcell containing the specified point.
899        */
900        ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const;
901
902        /** Creates mesh for this view cell.
903        */
904        void CreateMesh(ViewCell *vc);
905
906        void ExportViewCellGeometry(Exporter *exporter,
907                                                                ViewCell *vc,
908                                                                const AxisAlignedBox3 *box,
909                                                                const AxisAlignedPlane *clipPlane = NULL
910                                                                ) const;
911       
912        void CollectMergeCandidates(const VssRayContainer &rays,
913                                                                vector<MergeCandidate> &candidates);
914
915        void Finalize(ViewCell *viewCell, const bool createMesh);
916
917        bool ExportViewCells(const string filename,
918                                                 const bool exportPvs,
919                                                 const ObjectContainer &objects);
920
921        /** Constructs merge hierarchy which corresponds to the spatial hierarchy.
922        */
923        ViewCell *ConstructSpatialMergeTree(BspNode *root);
924
925        void ExportSingleViewCells(const ObjectContainer &objects,
926                                                           const int maxViewCells,
927                                                           const bool sortViewCells,
928                                                           const bool exportPvs,
929                                                           const bool exportRays,
930                                                           const int maxRays,
931                                                           const string &prefix,
932                                                           VssRayContainer *visRays = NULL);
933
934        bool LineSegmentIntersects(const Vector3 &origin,
935                                                           const Vector3 &termination,
936                                                           ViewCell *viewCell);
937
938protected:
939
940        void CollectViewCells();
941       
942        /// the BSP tree.
943        BspTree *mBspTree;
944        vector<BspRay *> mBspRays;
945
946private:
947
948        /** Constructs a spatial merge tree only 2 levels deep.
949        */
950        ViewCell *ConstructDummyMergeTree(BspNode *root);
951        /** Exports visualization of the BSP splits.
952        */
953        void ExportSplits(const ObjectContainer &objects);
954        /** test if subdivision is valid in terms of volume / area.
955        */
956        void TestSubdivision();
957};
958
959
960/**
961        Manages different higher order operations on the KD type view cells.
962*/
963class KdViewCellsManager: public ViewCellsManager
964{
965
966public:
967
968        KdViewCellsManager(ViewCellsTree *viewCellsTree, KdTree *tree);
969
970        int ConstructSubdivision(const ObjectContainer &objects,
971                                                         const VssRayContainer &rays);
972
973        int CastLineSegment(const Vector3 &origin,
974                                                const Vector3 &termination,
975                                                ViewCellContainer &viewcells);
976
977        int PostProcess(const ObjectContainer &objects,
978                                        const VssRayContainer &rays);
979
980        void Visualize(const ObjectContainer &objects,
981                                   const VssRayContainer &sampleRays);
982
983        int GetType() const;
984
985        bool ViewCellsConstructed() const;
986
987        ViewCell *GenerateViewCell(Mesh *mesh) const;
988
989        /** Prints out statistics of this approach.
990        */
991        //  virtual void PrintStatistics(ostream &s) const;
992        ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const
993        { return NULL; }
994
995        float GetProbability(ViewCell *viewCell);
996       
997        void CreateMesh(ViewCell *vc);
998
999        void ExportViewCellGeometry(Exporter *exporter,
1000                                                                ViewCell *vc,
1001                                                                const AxisAlignedBox3 *box,
1002                                                                const AxisAlignedPlane *clipPlane = NULL) const;
1003
1004
1005        void CollectMergeCandidates(const VssRayContainer &rays,
1006                                                                vector<MergeCandidate> &candidates);
1007
1008        void ExportSingleViewCells(const ObjectContainer &objects,
1009                                                           const int maxViewCells,
1010                                                           const bool sortViewCells,
1011                                                           const bool exportPvs,
1012                                                           const bool exportRays,
1013                                                           const int maxRays,
1014                                                           const string &prefix,
1015                                                           VssRayContainer *visRays = NULL);
1016
1017        bool LineSegmentIntersects(const Vector3 &origin,
1018                                                           const Vector3 &termination,
1019                                                           ViewCell *viewCell);
1020
1021protected:
1022
1023        /** Collects view cells from a hierarchy.
1024        */
1025        void CollectViewCells();
1026
1027        KdNode *GetNodeForPvs(KdLeaf *leaf);
1028
1029        ////////////////////////////////////////
1030
1031        /// the BSP tree.
1032        KdTree *mKdTree;
1033
1034        /// depth of the KD tree nodes with represent the view cells
1035        int mKdPvsDepth;
1036
1037
1038};
1039
1040
1041/** Manages different higher order operations on the view cells.
1042*/
1043class VspBspViewCellsManager: public ViewCellsManager
1044{
1045
1046public:
1047
1048        VspBspViewCellsManager(ViewCellsTree *viewCellsTree, VspBspTree *tree);
1049        ~VspBspViewCellsManager();
1050
1051        int ConstructSubdivision(const ObjectContainer &objects,
1052                                                         const VssRayContainer &rays);
1053
1054        int PostProcess(const ObjectContainer &objects,
1055                                        const VssRayContainer &rays);
1056
1057        void Visualize(const ObjectContainer &objects,
1058                                   const VssRayContainer &sampleRays);
1059
1060        int GetType() const;
1061       
1062        ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
1063
1064        bool ViewCellsConstructed() const;
1065       
1066        int CastLineSegment(const Vector3 &origin,
1067                                                const Vector3 &termination,
1068                                                ViewCellContainer &viewcells);
1069
1070        float GetProbability(ViewCell *viewCell);
1071       
1072        ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const;
1073
1074        bool GetViewPoint(Vector3 &viewPoint) const;
1075
1076        bool ViewPointValid(const Vector3 &viewPoint) const;
1077
1078        void CreateMesh(ViewCell *vc);
1079
1080        bool ExportViewCells(const string filename,
1081                                                 const bool exportPvs,
1082                                                 const ObjectContainer &objects);
1083
1084        int CastBeam(Beam &beam);
1085       
1086        void ExportViewCellGeometry(Exporter *exporter,
1087                                                                ViewCell *vc,
1088                                                                const AxisAlignedBox3 *box,
1089                                                                const AxisAlignedPlane *clipPlane = NULL) const;
1090
1091
1092        void Finalize(ViewCell *viewCell, const bool createMesh);
1093
1094        void CollectMergeCandidates(const VssRayContainer &rays,
1095                                                                vector<MergeCandidate> &candidates);
1096
1097        void ExportSingleViewCells(const ObjectContainer &objects,
1098                                                           const int maxViewCells,
1099                                                           const bool sortViewCells,
1100                                                           const bool exportPvs,
1101                                                           const bool exportRays,               
1102                                                           const int maxRays,
1103                                                           const string &prefix,
1104                                                           VssRayContainer *visRays = NULL);
1105
1106       
1107        bool LineSegmentIntersects(const Vector3 &origin,
1108                                                           const Vector3 &termination,
1109                                                           ViewCell *viewCell);
1110
1111protected:
1112
1113        int ComputeBoxIntersections(const AxisAlignedBox3 &box,
1114                                                                ViewCellContainer &viewCells) const;
1115       
1116        /** Merges view cells according to some criteria
1117        */
1118        void MergeViewCells(const VssRayContainer &rays,
1119                                                const ObjectContainer &objects);
1120       
1121        void RefineViewCells(const VssRayContainer &rays, const ObjectContainer &objects);
1122
1123        void CollectViewCells();
1124
1125        /** Returns maximal depth difference of view cell
1126                leaves in tree.
1127        */
1128        int GetMaxTreeDiff(ViewCell *vc) const;
1129
1130        /** Prepare view cells for use after loading them from disc.
1131        */
1132        void PrepareLoadedViewCells();
1133
1134        /** Constructs merge hierarchy which corresponds to the spatial hierarchy.
1135        */
1136        ViewCell *ConstructSpatialMergeTree(BspNode *root);
1137
1138        /// HACK for testing visibility filter functionality
1139        void TestFilter(const ObjectContainer &objects);
1140
1141        /** Visualization of the pvs difference to exact visubility using
1142                from point queries.
1143        */
1144        void VisualizeWithFromPointQueries();
1145
1146        /** Evaluate from point queries for the current scene.
1147        */
1148        void EvalFromPointQueries();
1149
1150        /** Exports visualization of the BSP splits.
1151        */
1152        void ExportSplits(const ObjectContainer &objects,
1153                                          const VssRayContainer &rays);
1154
1155
1156        /////////////////////////
1157
1158        /// the view space partition BSP tree.
1159        VspBspTree *mVspBspTree;
1160
1161
1162private:
1163
1164        /** test if subdivision is valid in terms of volume / area.
1165        */
1166        void TestSubdivision();
1167};
1168
1169
1170
1171/**     Manages different higher order operations on the view cells.
1172*/
1173class VspOspViewCellsManager: public ViewCellsManager
1174{
1175        friend class ViewCellsParseHandlers;
1176        friend class ViewCellsManager;
1177
1178public:
1179
1180        /** This version takes a view cells tree and a hierarchy
1181                as input.
1182        */
1183        VspOspViewCellsManager(ViewCellsTree *vcTree,
1184                                                   const string &hierarchyType);
1185       
1186        ~VspOspViewCellsManager();
1187
1188        int ConstructSubdivision(const ObjectContainer &objects,
1189                                                         const VssRayContainer &rays);
1190
1191        int PostProcess(const ObjectContainer &objects,
1192                                        const VssRayContainer &rays);
1193
1194        void Visualize(const ObjectContainer &objects,
1195                                   const VssRayContainer &sampleRays);
1196
1197        int GetType() const;
1198       
1199        ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
1200
1201        virtual Intersectable *GetIntersectable(const VssRay &ray,
1202                                                                                        const bool isTermination) const;
1203
1204        bool ViewCellsConstructed() const;
1205
1206        int CastLineSegment(const Vector3 &origin,
1207                                                const Vector3 &termination,
1208                                                ViewCellContainer &viewcells);
1209
1210        bool LineSegmentIntersects(const Vector3 &origin,
1211                                                           const Vector3 &termination,
1212                                                           ViewCell *viewCell);
1213
1214        float GetProbability(ViewCell *viewCell);
1215       
1216        ViewCell *GetViewCell(const Vector3 &point,
1217                                                  const bool active = false) const;
1218
1219        bool GetViewPoint(Vector3 &viewPoint) const;
1220
1221        bool ViewPointValid(const Vector3 &viewPoint) const;
1222
1223        void CreateMesh(ViewCell *vc);
1224
1225        bool ExportViewCells(const string filename,
1226                                                 const bool exportPvs,
1227                                                 const ObjectContainer &objects);
1228
1229        int CastBeam(Beam &beam);
1230
1231        void Finalize(ViewCell *viewCell, const bool createMesh);
1232
1233        void ExportSingleViewCells(const ObjectContainer &objects,
1234                                                           const int maxViewCells,
1235                                                           const bool sortViewCells,
1236                                                           const bool exportPvs,
1237                                                           const bool exportRays,
1238                                                           const int maxRays,
1239                                                           const string &prefix,
1240                                                           VssRayContainer *visRays = NULL);
1241        /** See parent class.
1242        */
1243        virtual void FinalizeViewCells(const bool createMesh);
1244
1245        bool ExportViewCellsBinary(const string filename,
1246                                                           const bool exportPvs,
1247                                                           const ObjectContainer &objects);
1248
1249#if TEST_PACKETS
1250
1251        float ComputeSampleContributions(const VssRayContainer &rays,
1252                                             const bool addContributions,
1253                                                                         const bool storeViewCells,
1254                                                                         const bool useHitObjects = false);
1255#endif
1256
1257
1258protected:
1259
1260        /** View cells manager taking a view cells tree and a hierarchy as input.
1261        */
1262        VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm);
1263       
1264        virtual void EvalViewCellPartition();
1265        /** Exports view cell geometry.
1266        */
1267        void ExportViewCellGeometry(Exporter *exporter,
1268                                                                ViewCell *vc,
1269                                                                const AxisAlignedBox3 *box,
1270                                                                const AxisAlignedPlane *clipPlane = NULL) const;
1271
1272        int ComputeBoxIntersections(const AxisAlignedBox3 &box,
1273                                                                ViewCellContainer &viewCells) const;
1274       
1275        void CollectViewCells();
1276
1277        virtual void CompressViewCells();
1278        /** Prepare view cells for use after loading them from disc.
1279        */
1280        void PrepareLoadedViewCells();
1281        /** Constructs merge hierarchy which corresponds to the spatial hierarchy.
1282        */
1283        ViewCell *ConstructSpatialMergeTree(VspNode *root);
1284        /** Exports visualization of the PVS.
1285        */
1286        void ExportPvs(const ObjectContainer &objects, const VssRayContainer &rays);
1287        /** Returns a hierarchy manager of the given name.
1288        */
1289        static HierarchyManager *CreateHierarchyManager(const string &name);
1290        /** collect objects intersecting a given spatial box
1291        */
1292        virtual void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
1293        /** Update the cost of pvss for hierarchy objects.
1294        */
1295        float UpdateObjectCosts();
1296
1297
1298        ////////////////
1299
1300        /** Fast view cell loader in binary mode.
1301        */
1302        friend ViewCellsManager *ViewCellsManager::
1303                LoadViewCellsBinary(const std::string &filename,
1304                                    ObjectContainer &pvsObjects,
1305                                                        bool finalizeViewCells,
1306                                                        BoundingBoxConverter *bconverter);
1307
1308
1309        /** Print statistics about the view cells compression.
1310        */
1311        static void PrintCompressionStats(HierarchyManager *hm, const int pvsEntries);
1312
1313
1314        ////////////////////
1315
1316        /// if we the objects are compressed after evaluation
1317        /// this makes only sense for testing purpose
1318        bool mCompressObjects;
1319        /// hierarchy manager managing view space / object subdivision.
1320        HierarchyManager *mHierarchyManager;
1321};
1322
1323
1324}
1325
1326#endif
Note: See TracBrowser for help on using the repository browser.