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

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