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

Revision 2575, 39.2 KB checked in by bittner, 17 years ago (diff)

big merge: preparation for havran ray caster, check if everything works

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) = 0;
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                                                                         const bool onlyNewObjects = false);
579
580        void ApplySpatialFilter(KdTree *kdTree,
581                                                        const float spatialFilterSize,
582                                                        ObjectPvs &pvs);
583
584         void ApplyFilter(ViewCell *viewCell,
585                                          KdTree *kdTree,
586                                          const float viewSpaceFilterSize,
587                                          const float spatialFilterSize,
588                                          ObjectPvs &pvs);
589
590        float GetFilterWidth();
591
592        float GetAbsFilterWidth();
593        /** Returns the bounding box of filter width.
594        */
595        AxisAlignedBox3 GetFilterBBox(const Vector3 &viewPoint,
596                                                                  const float width) const;
597
598
599
600        //////////////////////////////////////////////////////////////////
601
602
603        /** If true, the kd nodes are stored instead of the object pvs.
604        */
605        void SetStoreKdPvs(const bool storeKdPvs);
606
607        /** Returns true if the kd nodes are stored instead of the object pvs.
608        **/
609        bool GetStoreKdPVs() const;
610
611        /** Exports single view cells for visualization.
612                @param objects the scene objects
613                @param limit the maximal number of output view cells
614                @param sortViewCells if the view cells should be sorted by pvs size
615                @param exportPvs if the pvs should also be exported
616                @param exportRays if sample rays should be exported as well
617                @param maxRays maximum number of rays to export
618                @param prefix the prefix for the output file
619                @param visRays additional rays
620        */
621        virtual void ExportSingleViewCells(const ObjectContainer &objects,
622                                                                           const int maxViewCells,
623                                                                           const bool sortViewCells,
624                                                                           const bool exportPvs,
625                                                                           const bool exportRays,
626                                                                           const int maxRays,
627                                                                           const string &prefix,
628                                                                           VssRayContainer *visRays = NULL) = 0;
629
630
631        void ResetPvs();
632
633        Preprocessor *GetPreprocessor() const
634        {
635                return mPreprocessor;
636        }
637
638        void SetPreprocessor(Preprocessor *p)
639        {
640                mPreprocessor = p;
641        }
642
643        vector<ViewCellPoints *> *GetViewCellPoints()
644        {
645                return &mViewCellPoints;
646        }
647
648        void UpdatePvsForEvaluation();
649
650
651        VizBuffer mVizBuffer;
652
653
654protected:
655
656        void ComputeViewCellContribution(ViewCell *viewCell,
657                                                                         VssRay &ray,
658                                                                         Intersectable *obj,
659                                                                         const Vector3 &pt,
660                                                                         const bool addRays);
661
662        void MergeViewCellsRecursivly(ObjectPvs &pvs,
663                                                                  const ViewCellContainer &viewCells,
664                                                                  const int leftIdx,
665                                                                  const int rightIdx) const;
666        /** Intersects box with the tree and returns the number of intersected boxes.
667                @returns number of view cells found
668        */
669        virtual int ComputeBoxIntersections(const AxisAlignedBox3 &box,
670                                                                                ViewCellContainer &viewCells) const;
671        /** Tests the visibility filter functionality.
672        */
673        virtual void TestFilter(const ObjectContainer &objects) {};
674        /** If the view cells tree was already constructed or not.
675        */
676        bool ViewCellsTreeConstructed() const;
677        /** Requests preprocessor to cast samplesPerPass samples of a specific type.
678        */
679        int CastPassSamples(const int samplesPerPass,
680                                                const vector<int> &strategies,
681                                                VssRayContainer &vssRays) const;
682        /** cast samples for the purpose of evaluating the view cells solution
683        */
684        int CastEvaluationSamples(const int samplesPerPass,
685                                                          VssRayContainer &passSamples);// const;
686        /** Parse the options from the environment file.
687        */
688        void ParseEnvironment();
689        /** Creates unique view cell ids.
690        */
691        void CreateUniqueViewCellIds();
692        /** Finalizes, i.e., creates mesh, volume, area etc. for the view cell.
693        */
694        virtual void Finalize(ViewCell *viewCell, const bool createMesh);
695        /** Recollects view cells and resets statistics.
696        */
697        void ResetViewCells();
698        /** Sets this view cell to active.
699        */
700        void SetViewCellActive(ViewCell *vc) const;
701        /** Collects the view cells in the view cell container.
702        */
703        virtual void CollectViewCells() = 0;
704        /** Evaluates view cells statistics and stores it in mViewCellsStatistics.
705        */
706        void EvaluateViewCellsStats();
707       
708
709        void UpdateStatsForViewCell(ViewCell *viewCell, Intersectable *obj);
710
711
712        ///////////////////////
713        //-- helper functions for view cell visualization
714
715        /** Exports the view cell partition.
716        */
717        void ExportViewCellsForViz(Exporter *exporter,
718                                                           const AxisAlignedBox3 *box,
719                                                           const bool colorCode,
720                                                           const AxisAlignedPlane *clipPlane) const;
721        /** Sets exporter color.
722        */
723        virtual void ExportColor(Exporter *exporter,
724                                                         ViewCell *vc,
725                                                         const int colorCode) const;
726        /** Creates meshes from the view cells.
727        */
728        void CreateViewCellMeshes();
729        /** Creates clip plane for visualization.
730        */
731        void CreateClipPlane();
732
733        AxisAlignedPlane *GetClipPlane();
734
735        void ExportMergedViewCells(const ObjectContainer &objects);
736
737
738        ///////////////////////
739
740        /** Returns volume of the view space.
741        */
742        virtual float GetViewSpaceVolume();
743        /** Prepares the view cells for sampling after loading them from disc.
744        */
745        virtual void PrepareLoadedViewCells() {};
746        /** Constructs local view cell merge hierarchy.
747        */
748        ViewCell *ConstructLocalMergeTree(ViewCell *currentViewCell,
749                                          const ViewCellContainer &viewCells);
750        /** Constructs local view cell merge hierarchy based solely on similarity with the
751                current viewcell
752        */
753        ViewCell *ConstructLocalMergeTree2(ViewCell *currentViewCell,
754                                                                           const ViewCellContainer &viewCells);
755        /** Updates pvs of all view cells for statistical evaluation after some more sampling
756        */
757        void UpdatePvsForEvaluation(ViewCell *root, ObjectPvs &pvs);
758        /** Export statistics of the view cells tree.
759        */
760        virtual void ExportStats(const string &mergeStats);
761        /** Loads view cells in binary mode.
762        */
763        static ViewCellsManager *LoadViewCellsBinary(const string &filename,
764                                                                                                 ObjectContainer &pvsObjects,
765                                                                                                 bool finalizeViewCells,
766                                                 BoundingBoxConverter *bconverter);
767        /** This helper function loads the bounding boxes for a binary solution.
768        */
769        static void LoadIndexedBoundingBoxesBinary(IN_STREAM &stream,
770                                                       IndexedBoundingBoxContainer &iboxes);
771
772
773
774        ///////////
775        //-- members
776
777        ofstream mStats;
778        Preprocessor *mPreprocessor;
779        /// if bounding boxes should be exported together with the view cells
780        bool mExportBboxesForPvs;
781        /// the clip plane for visualization
782        AxisAlignedPlane mClipPlaneForViz;
783        /// if the visualization is using the clip plane
784        bool mUseClipPlaneForViz;
785        /// Renders the view cells.
786        Renderer *mRenderer;
787        /// Loaded view cells
788        ViewCellContainer mViewCells;
789        /// the view cell hierarchy (i.e., the logical description of view cells)
790        ViewCellsTree *mViewCellsTree;
791       
792        std::vector<int> mStrategies;
793
794        /** if the values in the view cell leaves and the interiors are up to date
795                this is meant for lazy storing of the pvs, where only a scalar indicating
796                pvs size is stored in interiors and not the pvs itself.
797        */
798        bool mViewCellPvsIsUpdated;
799
800        /// maximum number of samples for the view cell construction
801        int mConstructionSamples;
802        int mSamplesPerPass;
803        int mInitialSamples;
804        int mPostProcessSamples;
805        int mVisualizationSamples;
806
807        int mEvaluationSamples;
808
809        float mTotalAreaValid;
810        float mTotalArea;
811
812        int mMaxPvsSize;
813        int mMinPvsSize;
814        float mMaxPvsRatio;
815
816        int mSamplingType;
817        int mEvaluationSamplingType;
818        int mNumActiveViewCells;
819        bool mCompressViewCells;
820
821        vector<ViewCellPoints *> mViewCellPoints;
822
823        /// holds the current view cell statistics
824        ViewCellsStatistics mCurrentViewCellsStats;
825
826        /// the scene bounding box
827        AxisAlignedBox3 mViewSpaceBox;
828       
829        /// if view cells should be exported
830        bool mExportViewCells;
831        // if only valid view cells should be considered for processing
832        bool mOnlyValidViewCells;
833        /// if rays should be used to collect merge candidates
834        bool mUseRaysForMerge;
835        /// if there should be an additional merge step after the subdivision
836        bool mMergeViewCells;
837        /// the width of the box filter
838        float mFilterWidth;
839        /// Maximal size of the filter in terms of contributing view cells
840        int mMaxFilterSize;
841        /// only for debugging: stores some rays used during view cell construction
842        VssRayContainer storedRays;
843        /// if kd node based pvs is used for preprocessing
844        bool mUseKdPvs;
845        /// types of distributions used for sampling
846        MixtureDistribution *mMixtureDistribution;
847
848
849
850        //////////////////
851        //-- visualization options
852       
853        /// color code for view cells visualization
854        bool mShowVisualization;
855        int mColorCode;
856        bool mExportGeometry;
857        bool mExportRays;
858        bool mViewCellsFinished;
859        bool mEvaluateViewCells;
860
861        /// if pvs should be exported with view cells
862        bool mExportPvs;
863
864        /// if view cells geometry should be used from other sources
865        bool mUsePredefinedViewCells;
866        /// the weight for one triangle in the heuristics
867        float mTriangleWeight;
868        /// the weight for one object (= one entity issued with one draw call) in the heuristics
869        float mObjectWeight;
870
871        vector<PerViewCellStat> mPerViewCellStat;
872        SamplesStatistics mSamplesStat;
873};
874
875
876/** Manages different higher order operations on the view cells.
877*/
878class BspViewCellsManager: public ViewCellsManager
879{
880
881public:
882        /** Constructor taking the bsp tree and the number of samples
883                used to construct the bsp tree.
884        */
885        BspViewCellsManager(ViewCellsTree *viewCellsTree, BspTree *tree);
886
887        ~BspViewCellsManager();
888
889        int ConstructSubdivision(const ObjectContainer &objects,
890                                  const VssRayContainer &rays);
891
892        int PostProcess(const ObjectContainer &objects,
893                                        const VssRayContainer &rays);
894
895        void Visualize(const ObjectContainer &objects,
896                                   const VssRayContainer &sampleRays);
897
898        int GetType() const;
899       
900        ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
901
902        bool ViewCellsConstructed() const;
903
904        //void PrintStatistics(ostream &s) const;
905
906        int CastLineSegment(const Vector3 &origin,
907                                                const Vector3 &termination,
908                                                ViewCellContainer &viewcells);
909       
910        /** Returns the probability that the view point lies
911                in this view cells.
912        */
913        float GetProbability(ViewCell *viewCell);
914
915        /** Get a viewcell containing the specified point.
916        */
917        ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const;
918
919        /** Creates mesh for this view cell.
920        */
921        void CreateMesh(ViewCell *vc);
922
923        void ExportViewCellGeometry(Exporter *exporter,
924                                                                ViewCell *vc,
925                                                                const AxisAlignedBox3 *box,
926                                                                const AxisAlignedPlane *clipPlane = NULL
927                                                                ) const;
928       
929        void CollectMergeCandidates(const VssRayContainer &rays,
930                                                                vector<MergeCandidate> &candidates);
931
932        void Finalize(ViewCell *viewCell, const bool createMesh);
933
934        bool ExportViewCells(const string filename,
935                                                 const bool exportPvs,
936                                                 const ObjectContainer &objects);
937
938        /** Constructs merge hierarchy which corresponds to the spatial hierarchy.
939        */
940        ViewCell *ConstructSpatialMergeTree(BspNode *root);
941
942        void ExportSingleViewCells(const ObjectContainer &objects,
943                                                           const int maxViewCells,
944                                                           const bool sortViewCells,
945                                                           const bool exportPvs,
946                                                           const bool exportRays,
947                                                           const int maxRays,
948                                                           const string &prefix,
949                                                           VssRayContainer *visRays = NULL);
950
951        bool LineSegmentIntersects(const Vector3 &origin,
952                                                           const Vector3 &termination,
953                                                           ViewCell *viewCell);
954
955protected:
956
957        void CollectViewCells();
958       
959        /// the BSP tree.
960        BspTree *mBspTree;
961        vector<BspRay *> mBspRays;
962
963private:
964
965        /** Constructs a spatial merge tree only 2 levels deep.
966        */
967        ViewCell *ConstructDummyMergeTree(BspNode *root);
968        /** Exports visualization of the BSP splits.
969        */
970        void ExportSplits(const ObjectContainer &objects);
971        /** test if subdivision is valid in terms of volume / area.
972        */
973        void TestSubdivision();
974};
975
976
977/**
978        Manages different higher order operations on the KD type view cells.
979*/
980class KdViewCellsManager: public ViewCellsManager
981{
982
983public:
984
985        KdViewCellsManager(ViewCellsTree *viewCellsTree, KdTree *tree);
986
987        int ConstructSubdivision(const ObjectContainer &objects,
988                                                         const VssRayContainer &rays);
989
990        int CastLineSegment(const Vector3 &origin,
991                                                const Vector3 &termination,
992                                                ViewCellContainer &viewcells);
993
994        int PostProcess(const ObjectContainer &objects,
995                                        const VssRayContainer &rays);
996
997        void Visualize(const ObjectContainer &objects,
998                                   const VssRayContainer &sampleRays);
999
1000        int GetType() const;
1001
1002        bool ViewCellsConstructed() const;
1003
1004        ViewCell *GenerateViewCell(Mesh *mesh) const;
1005
1006        /** Prints out statistics of this approach.
1007        */
1008        //  virtual void PrintStatistics(ostream &s) const;
1009        ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const
1010        { return NULL; }
1011
1012        float GetProbability(ViewCell *viewCell);
1013       
1014        void CreateMesh(ViewCell *vc);
1015
1016        void ExportViewCellGeometry(Exporter *exporter,
1017                                                                ViewCell *vc,
1018                                                                const AxisAlignedBox3 *box,
1019                                                                const AxisAlignedPlane *clipPlane = NULL) const;
1020
1021
1022        void CollectMergeCandidates(const VssRayContainer &rays,
1023                                                                vector<MergeCandidate> &candidates);
1024
1025        void ExportSingleViewCells(const ObjectContainer &objects,
1026                                                           const int maxViewCells,
1027                                                           const bool sortViewCells,
1028                                                           const bool exportPvs,
1029                                                           const bool exportRays,
1030                                                           const int maxRays,
1031                                                           const string &prefix,
1032                                                           VssRayContainer *visRays = NULL);
1033
1034        bool LineSegmentIntersects(const Vector3 &origin,
1035                                                           const Vector3 &termination,
1036                                                           ViewCell *viewCell);
1037
1038protected:
1039
1040        /** Collects view cells from a hierarchy.
1041        */
1042        void CollectViewCells();
1043
1044        KdNode *GetNodeForPvs(KdLeaf *leaf);
1045
1046        ////////////////////////////////////////
1047
1048        /// the BSP tree.
1049        KdTree *mKdTree;
1050
1051        /// depth of the KD tree nodes with represent the view cells
1052        int mKdPvsDepth;
1053
1054
1055};
1056
1057
1058/** Manages different higher order operations on the view cells.
1059*/
1060class VspBspViewCellsManager: public ViewCellsManager
1061{
1062
1063public:
1064
1065        VspBspViewCellsManager(ViewCellsTree *viewCellsTree, VspBspTree *tree);
1066        ~VspBspViewCellsManager();
1067
1068        int ConstructSubdivision(const ObjectContainer &objects,
1069                                                         const VssRayContainer &rays);
1070
1071        int PostProcess(const ObjectContainer &objects,
1072                                        const VssRayContainer &rays);
1073
1074        void Visualize(const ObjectContainer &objects,
1075                                   const VssRayContainer &sampleRays);
1076
1077        int GetType() const;
1078       
1079        ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
1080
1081        bool ViewCellsConstructed() const;
1082       
1083        int CastLineSegment(const Vector3 &origin,
1084                                                const Vector3 &termination,
1085                                                ViewCellContainer &viewcells);
1086
1087        float GetProbability(ViewCell *viewCell);
1088       
1089        ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const;
1090
1091        bool GetViewPoint(Vector3 &viewPoint) const;
1092
1093        bool ViewPointValid(const Vector3 &viewPoint) const;
1094
1095        void CreateMesh(ViewCell *vc);
1096
1097        bool ExportViewCells(const string filename,
1098                                                 const bool exportPvs,
1099                                                 const ObjectContainer &objects);
1100
1101        int CastBeam(Beam &beam);
1102       
1103        void ExportViewCellGeometry(Exporter *exporter,
1104                                                                ViewCell *vc,
1105                                                                const AxisAlignedBox3 *box,
1106                                                                const AxisAlignedPlane *clipPlane = NULL) const;
1107
1108
1109        void Finalize(ViewCell *viewCell, const bool createMesh);
1110
1111        void CollectMergeCandidates(const VssRayContainer &rays,
1112                                                                vector<MergeCandidate> &candidates);
1113
1114        void ExportSingleViewCells(const ObjectContainer &objects,
1115                                                           const int maxViewCells,
1116                                                           const bool sortViewCells,
1117                                                           const bool exportPvs,
1118                                                           const bool exportRays,               
1119                                                           const int maxRays,
1120                                                           const string &prefix,
1121                                                           VssRayContainer *visRays = NULL);
1122
1123       
1124        bool LineSegmentIntersects(const Vector3 &origin,
1125                                                           const Vector3 &termination,
1126                                                           ViewCell *viewCell);
1127
1128protected:
1129
1130        int ComputeBoxIntersections(const AxisAlignedBox3 &box,
1131                                                                ViewCellContainer &viewCells) const;
1132       
1133        /** Merges view cells according to some criteria
1134        */
1135        void MergeViewCells(const VssRayContainer &rays,
1136                                                const ObjectContainer &objects);
1137       
1138        void RefineViewCells(const VssRayContainer &rays, const ObjectContainer &objects);
1139
1140        void CollectViewCells();
1141
1142        /** Returns maximal depth difference of view cell
1143                leaves in tree.
1144        */
1145        int GetMaxTreeDiff(ViewCell *vc) const;
1146
1147        /** Prepare view cells for use after loading them from disc.
1148        */
1149        void PrepareLoadedViewCells();
1150
1151        /** Constructs merge hierarchy which corresponds to the spatial hierarchy.
1152        */
1153        ViewCell *ConstructSpatialMergeTree(BspNode *root);
1154
1155        /// HACK for testing visibility filter functionality
1156        void TestFilter(const ObjectContainer &objects);
1157
1158        /** Visualization of the pvs difference to exact visubility using
1159                from point queries.
1160        */
1161        void VisualizeWithFromPointQueries();
1162
1163        /** Evaluate from point queries for the current scene.
1164        */
1165        void EvalFromPointQueries();
1166
1167        /** Exports visualization of the BSP splits.
1168        */
1169        void ExportSplits(const ObjectContainer &objects,
1170                                          const VssRayContainer &rays);
1171
1172
1173        /////////////////////////
1174
1175        /// the view space partition BSP tree.
1176        VspBspTree *mVspBspTree;
1177
1178
1179private:
1180
1181        /** test if subdivision is valid in terms of volume / area.
1182        */
1183        void TestSubdivision();
1184};
1185
1186
1187
1188/**     Manages different higher order operations on the view cells.
1189*/
1190class VspOspViewCellsManager: public ViewCellsManager
1191{
1192        friend class ViewCellsParseHandlers;
1193        friend class ViewCellsManager;
1194
1195public:
1196
1197        /** This version takes a view cells tree and a hierarchy
1198                as input.
1199        */
1200        VspOspViewCellsManager(ViewCellsTree *vcTree,
1201                                                   const string &hierarchyType);
1202       
1203        ~VspOspViewCellsManager();
1204
1205        int ConstructSubdivision(const ObjectContainer &objects,
1206                                                         const VssRayContainer &rays);
1207
1208        int PostProcess(const ObjectContainer &objects,
1209                                        const VssRayContainer &rays);
1210
1211        void Visualize(const ObjectContainer &objects,
1212                                   const VssRayContainer &sampleRays);
1213
1214        int GetType() const;
1215       
1216        ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
1217
1218        virtual Intersectable *GetIntersectable(const VssRay &ray,
1219                                                                                        const bool isTermination) const;
1220
1221        bool ViewCellsConstructed() const;
1222
1223        int CastLineSegment(const Vector3 &origin,
1224                                                const Vector3 &termination,
1225                                                ViewCellContainer &viewcells);
1226
1227        bool LineSegmentIntersects(const Vector3 &origin,
1228                                                           const Vector3 &termination,
1229                                                           ViewCell *viewCell);
1230
1231        float GetProbability(ViewCell *viewCell);
1232       
1233        ViewCell *GetViewCell(const Vector3 &point,
1234                                                  const bool active = false) const;
1235
1236        bool GetViewPoint(Vector3 &viewPoint) const;
1237
1238        bool ViewPointValid(const Vector3 &viewPoint) const;
1239
1240        void CreateMesh(ViewCell *vc);
1241
1242        bool ExportViewCells(const string filename,
1243                                                 const bool exportPvs,
1244                                                 const ObjectContainer &objects);
1245
1246        int CastBeam(Beam &beam);
1247
1248        void Finalize(ViewCell *viewCell, const bool createMesh);
1249
1250        void ExportSingleViewCells(const ObjectContainer &objects,
1251                                                           const int maxViewCells,
1252                                                           const bool sortViewCells,
1253                                                           const bool exportPvs,
1254                                                           const bool exportRays,
1255                                                           const int maxRays,
1256                                                           const string &prefix,
1257                                                           VssRayContainer *visRays = NULL);
1258        /** See parent class.
1259        */
1260        virtual void FinalizeViewCells(const bool createMesh);
1261
1262        bool ExportViewCellsBinary(const string filename,
1263                                                           const bool exportPvs,
1264                                                           const ObjectContainer &objects);
1265
1266#if TEST_PACKETS
1267
1268        float ComputeSampleContributions(const VssRayContainer &rays,
1269                                             const bool addContributions,
1270                                                                         const bool storeViewCells,
1271                                                                         const bool useHitObjects = false);
1272#endif
1273
1274
1275protected:
1276
1277        /** View cells manager taking a view cells tree and a hierarchy as input.
1278        */
1279        VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm);
1280       
1281        virtual void EvalViewCellPartition();
1282        /** Exports view cell geometry.
1283        */
1284        void ExportViewCellGeometry(Exporter *exporter,
1285                                                                ViewCell *vc,
1286                                                                const AxisAlignedBox3 *box,
1287                                                                const AxisAlignedPlane *clipPlane = NULL) const;
1288
1289        int ComputeBoxIntersections(const AxisAlignedBox3 &box,
1290                                                                ViewCellContainer &viewCells) const;
1291       
1292        void CollectViewCells();
1293
1294        virtual void CompressViewCells();
1295        /** Prepare view cells for use after loading them from disc.
1296        */
1297        void PrepareLoadedViewCells();
1298        /** Constructs merge hierarchy which corresponds to the spatial hierarchy.
1299        */
1300        ViewCell *ConstructSpatialMergeTree(VspNode *root);
1301        /** Exports visualization of the PVS.
1302        */
1303        void ExportPvs(const ObjectContainer &objects, const VssRayContainer &rays);
1304        /** Returns a hierarchy manager of the given name.
1305        */
1306        static HierarchyManager *CreateHierarchyManager(const string &name);
1307        /** collect objects intersecting a given spatial box
1308        */
1309        virtual void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
1310        /** Update the cost of pvss for hierarchy objects.
1311        */
1312        float UpdateObjectCosts();
1313
1314
1315        ////////////////
1316
1317        /** Fast view cell loader in binary mode.
1318        */
1319        friend ViewCellsManager *ViewCellsManager::
1320                LoadViewCellsBinary(const std::string &filename,
1321                                    ObjectContainer &pvsObjects,
1322                                                        bool finalizeViewCells,
1323                                                        BoundingBoxConverter *bconverter);
1324
1325
1326        /** Print statistics about the view cells compression.
1327        */
1328        static void PrintCompressionStats(HierarchyManager *hm, const int pvsEntries);
1329
1330
1331        ////////////////////
1332
1333        /// if we the objects are compressed after evaluation
1334        /// this makes only sense for testing purpose
1335        bool mCompressObjects;
1336        /// hierarchy manager managing view space / object subdivision.
1337        HierarchyManager *mHierarchyManager;
1338};
1339
1340
1341}
1342
1343#endif
Note: See TracBrowser for help on using the repository browser.