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

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