source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp @ 2615

Revision 2615, 180.0 KB checked in by mattausch, 16 years ago (diff)

did some stuff for the visualization

Line 
1#include "ViewCellsManager.h"
2#include "RenderSimulator.h"
3#include "Mesh.h"
4#include "Triangle3.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "X3dParser.h"
8#include "ViewCellBsp.h"
9#include "KdTree.h"
10#include "HierarchyManager.h"
11#include "Exporter.h"
12#include "VspBspTree.h"
13#include "ViewCellsParser.h"
14#include "Beam.h"
15#include "VssPreprocessor.h"
16#include "RssPreprocessor.h"
17#include "BoundingBoxConverter.h"
18#include "GlRenderer.h"
19#include "ResourceManager.h"
20#include "IntersectableWrapper.h"
21#include "VspTree.h"
22#include "OspTree.h"
23#include "BvHierarchy.h"
24#include "SamplingStrategy.h"
25#include "SceneGraph.h"
26
27#ifdef USE_PERFTIMER 
28#include "Timer/PerfTimer.h"
29#endif // USE_PERFTIMER
30
31#define USE_RAY_LENGTH_AS_CONTRIBUTION 0
32#define DIST_WEIGHTED_CONTRIBUTION 0
33#define SUM_RAY_CONTRIBUTIONS 1
34#define AVG_RAY_CONTRIBUTIONS 0
35#define CONTRIBUTION_RELATIVE_TO_PVS_SIZE 0
36#define PVS_ADD_DIRTY 1
37
38
39#define MYSTATS 1
40
41
42namespace GtpVisibilityPreprocessor {
43
44
45#ifdef USE_PERFTIMER 
46PerfTimer viewCellCastTimer;
47PerfTimer pvsTimer;
48PerfTimer objTimer;
49#endif
50 
51// HACK
52const static bool SAMPLE_AFTER_SUBDIVISION = true;
53//const static bool CLAMP_TO_BOX = false;
54const static bool CLAMP_TO_BOX = true;
55
56
57
58inline static bool ilt(Intersectable *obj1, Intersectable *obj2)
59{
60        return obj1->mId < obj2->mId;
61}
62
63
64template <typename T> class myless
65{
66public:
67        //bool operator() (HierarchyNode *v1, HierarchyNode *v2) const
68        bool operator() (T v1, T v2) const
69        {
70                return (v1->GetMergeCost() < v2->GetMergeCost());
71        }
72};
73
74
75
76struct SortableViewCellEntry {
77
78        SortableViewCellEntry() {}
79        SortableViewCellEntry(const float v, ViewCell *cell):mValue(v), mViewCell(cell) {}
80
81        float mValue;
82        ViewCell *mViewCell;
83
84  friend bool operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b);
85};
86
87
88inline bool
89operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b) {
90  return a.mValue < b.mValue;
91}
92
93ViewCellsManager::ViewCellsManager(ViewCellsTree *viewCellsTree):
94mRenderer(NULL),
95mInitialSamples(0),
96mConstructionSamples(0),
97mPostProcessSamples(0),
98mVisualizationSamples(0),
99mTotalAreaValid(false),
100mTotalArea(0.0f),
101mViewCellsFinished(false),
102mMaxPvsSize(9999999),
103mMinPvsSize(0),
104mMaxPvsRatio(1.0),
105mViewCellPvsIsUpdated(false),
106mPreprocessor(NULL),
107mViewCellsTree(viewCellsTree),
108mUsePredefinedViewCells(false),
109mMixtureDistribution(NULL),
110mEvaluationSamples(0)
111{
112        mViewSpaceBox.Initialize();
113        ParseEnvironment();
114
115        mViewCellsTree->SetViewCellsManager(this);
116        mSamplesStat.Reset();
117        //mStats.open("mystats.log");
118
119        mRandomViewCellsHandler = new RandomViewCellsHandler(this);
120}
121
122
123int ViewCellsManager::CastEvaluationSamples(const int samplesPerPass,
124                                                                                        VssRayContainer &passSamples)
125{
126        static int pass = 0;
127        static int totalRays = 0;
128
129        SimpleRayContainer rays;
130        rays.reserve(samplesPerPass);
131        //passSamples.reserve(samplesPerPass * 2);
132 
133        long startTime = GetTime();
134
135        cout<<"Progress :"<<totalRays / 1e6f << " M rays, " << (100.0f * totalRays) / (mEvaluationSamples + 1) << "%" << endl;
136       
137        //rays.clear();
138        //passSamples.clear();
139       
140        mMixtureDistribution->GenerateSamples(samplesPerPass, rays);
141       
142        const bool doubleRays = true;
143        const bool pruneInvalidRays = true;
144        mPreprocessor->CastRays(rays, passSamples, doubleRays, pruneInvalidRays);
145
146        mMixtureDistribution->ComputeContributions(passSamples);
147        mMixtureDistribution->UpdateDistributions(passSamples);
148       
149        Real time = TimeDiff(startTime, GetTime());
150        PrintPvsStatistics(mStats);
151       
152        /*mStats <<
153                "#Pass\n" << pass ++ <<endl<<
154                "#Time\n" << time <<endl<<
155                "#TotalSamples\n" << totalRays << endl;
156        */     
157
158        totalRays += samplesPerPass;
159
160        return (int)passSamples.size();
161}
162
163
164ViewCellsManager::~ViewCellsManager()
165{
166        // HACK: if view cells tree does not
167        // handle view cells, we have to do it here
168        // question: rather create view cells resource manager?
169        if (!ViewCellsTreeConstructed())
170        {
171                CLEAR_CONTAINER(mViewCells);
172        }
173        else
174        {
175                DEL_PTR(mViewCellsTree);
176        }
177
178        DEL_PTR(mMixtureDistribution);
179        DEL_PTR(mRandomViewCellsHandler);
180}
181
182
183void ViewCellsManager::ParseEnvironment()
184{
185        // visualization stuff
186        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportRays", mExportRays);
187        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportGeometry", mExportGeometry);
188        Environment::GetSingleton()->GetFloatValue("ViewCells.maxPvsRatio", mMaxPvsRatio);
189       
190        Environment::GetSingleton()->GetBoolValue("ViewCells.processOnlyValidViewCells", mOnlyValidViewCells);
191
192        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samples", mConstructionSamples);
193        Environment::GetSingleton()->GetIntValue("ViewCells.PostProcess.samples", mPostProcessSamples);
194        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.useRaysForMerge", mUseRaysForMerge);
195
196        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.samples", mVisualizationSamples);
197
198        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samplesPerPass", mSamplesPerPass);
199        Environment::GetSingleton()->GetBoolValue("ViewCells.exportToFile", mExportViewCells);
200       
201        Environment::GetSingleton()->GetIntValue("ViewCells.active", mNumActiveViewCells);
202        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.compress", mCompressViewCells);
203        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.useClipPlane", mUseClipPlaneForViz);
204        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.merge", mMergeViewCells);
205        Environment::GetSingleton()->GetBoolValue("ViewCells.evaluateViewCells", mEvaluateViewCells);
206        Environment::GetSingleton()->GetBoolValue("ViewCells.showVisualization", mShowVisualization);
207        Environment::GetSingleton()->GetIntValue("ViewCells.Filter.maxSize", mMaxFilterSize);
208        Environment::GetSingleton()->GetFloatValue("ViewCells.Filter.width", mFilterWidth);
209
210        Environment::GetSingleton()->GetBoolValue("ViewCells.exportBboxesForPvs", mExportBboxesForPvs);
211        Environment::GetSingleton()->GetBoolValue("ViewCells.exportPvs", mExportPvs);
212
213        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
214
215        char buf[100];
216        Environment::GetSingleton()->GetStringValue("ViewCells.samplingType", buf);
217
218        Environment::GetSingleton()->GetFloatValue("ViewCells.triangleWeight", mTriangleWeight);
219        Environment::GetSingleton()->GetFloatValue("ViewCells.objectWeight", mObjectWeight);
220
221        // choose mix of sampling strategies
222        if (0)
223        {
224                mStrategies.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
225                //mStrategies.push_back(SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION);
226        }
227        else
228        {
229                mStrategies.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
230                mStrategies.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
231                       
232                mStrategies.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
233                //mStrategies.push_back(SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION);
234        }
235               
236    Debug << "casting strategies: ";
237        for (int i = 0; i < (int)mStrategies.size(); ++ i)
238                Debug << mStrategies[i] << " ";
239        Debug << endl;
240
241        // sampling type for view cells construction samples
242        if (strcmp(buf, "object") == 0)
243        {
244                mSamplingType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
245        }
246        else if (strcmp(buf, "box") == 0)
247        {
248                mSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
249        }
250        else if (strcmp(buf, "directional") == 0)
251        {
252                mSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
253        }
254        else if (strcmp(buf, "object_directional") == 0)
255        {
256                mSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
257        }
258        else if (strcmp(buf, "reverse_object") == 0)
259        {
260                mSamplingType = SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION;
261        }
262        /*else if (strcmp(buf, "interior") == 0)
263        {
264                mSamplingType = Preprocessor::OBJECTS_INTERIOR_DISTRIBUTION;
265        }*/
266        else
267        {
268                Debug << "error! wrong sampling type" << endl;
269                exit(0);
270        }
271
272        // sampling type for evaluation samples
273        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.samplingType", buf);
274       
275        if (strcmp(buf, "object") == 0)
276        {
277                mEvaluationSamplingType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
278        }
279        else if (strcmp(buf, "box") == 0)
280        {
281                mEvaluationSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
282        }
283        else if (strcmp(buf, "directional") == 0)
284        {
285                mEvaluationSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
286        }
287        else if (strcmp(buf, "object_directional") == 0)
288        {
289                mEvaluationSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
290        }
291        else if (strcmp(buf, "reverse_object") == 0)
292        {
293                mEvaluationSamplingType = SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION;
294        }
295        else
296        {
297                mEvaluationSamplingType = -1;
298                Debug << "error! wrong sampling type" << endl;
299                exit(0);
300        }
301
302
303        /** The color code used during visualization.
304        */
305        Environment::GetSingleton()->GetStringValue("ViewCells.Visualization.colorCode", buf);
306
307        if (strcmp(buf, "PVS") == 0)
308                mColorCode = 1;
309        else if (strcmp(buf, "MergedLeaves") == 0)
310                mColorCode = 2;
311        else if (strcmp(buf, "MergedTreeDiff") == 0)
312                mColorCode = 3;
313        else
314                mColorCode = 0;
315
316
317        Debug << "************ View Cells Manager options ***************" << endl;
318        Debug << "color code: " << mColorCode << endl;
319
320        Debug << "export rays: " << mExportRays << endl;
321        Debug << "export geometry: " << mExportGeometry << endl;
322        Debug << "max pvs ratio: " << mMaxPvsRatio << endl;
323       
324        Debug << "process only valid view cells: " << mOnlyValidViewCells << endl;
325        Debug << "construction samples: " << mConstructionSamples << endl;
326        Debug << "post process samples: " << mPostProcessSamples << endl;
327        Debug << "post process use rays for merge: " << mUseRaysForMerge << endl;
328        Debug << "visualization samples: " << mVisualizationSamples << endl;
329        Debug << "construction samples per pass: " << mSamplesPerPass << endl;
330        Debug << "export to file: " << mExportViewCells << endl;
331       
332        Debug << "active view cells: " << mNumActiveViewCells << endl;
333        Debug << "post process compress: " << mCompressViewCells << endl;
334        Debug << "visualization use clipPlane: " << mUseClipPlaneForViz << endl;
335        Debug << "post process merge: " << mMergeViewCells << endl;
336        Debug << "evaluate view cells: " << mEvaluateViewCells << endl;
337        Debug << "sampling type: " << mSamplingType << endl;
338        Debug << "evaluation sampling type: " << mEvaluationSamplingType << endl;
339        Debug << "show visualization: " << mShowVisualization << endl;
340        Debug << "filter width: " << mFilterWidth << endl;
341        Debug << "sample after subdivision: " << SAMPLE_AFTER_SUBDIVISION << endl;
342
343        Debug << "export bounding boxes: " << mExportBboxesForPvs << endl;
344        Debug << "export pvs for view cells: " << mExportPvs << endl;
345        Debug << "use kd pvs " << mUseKdPvs << endl;
346
347        Debug << "triangle weight: " << mTriangleWeight << endl;
348        Debug << "object weight: " << mObjectWeight << endl;
349
350        Debug << endl;
351}
352
353
354ViewCell *ViewCellsManager::GetViewCellById(const int id)
355{
356        ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
357
358        for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
359        {
360                if ((*vit)->GetId() == id)
361                        return (*vit);
362        }
363        return NULL;
364}
365
366
367Intersectable *ViewCellsManager::GetIntersectable(const VssRay &ray,
368                                                                                                  const bool isTermination) const
369{
370#if DYNAMIC_OBJECTS_HACK
371
372#if USE_TRANSFORMED_MESH_INSTANCE_HACK
373        if (ray.mTerminationObject->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
374                return ray.mTerminationObject;
375#else
376        if (ray.mTerminationObject->Type() == Intersectable::SCENEGRAPHLEAF_INTERSECTABLE)
377                return ray.mTerminationObject;
378#endif
379
380#endif
381        if (mUseKdPvs)
382        {
383                KdNode *node = GetPreprocessor()->
384                        mKdTree->GetPvsNode(isTermination ?     ray.mTermination : ray.mOrigin);
385
386                return GetPreprocessor()->mKdTree->GetOrCreateKdIntersectable(node);
387        }
388        else
389        {
390                return isTermination ? ray.mTerminationObject : ray.mOriginObject;
391        }
392}
393
394
395void ViewCellsManager::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
396{
397        GetPreprocessor()->mKdTree->CollectObjects(box, objects);
398}
399
400
401AxisAlignedBox3 ViewCellsManager::GetViewCellBox(ViewCell *vc)
402{
403        Mesh *m = vc->GetMesh();
404
405        if (m)
406        {
407                m->ComputeBoundingBox();
408                return m->mBox;
409        }
410
411        AxisAlignedBox3 box;
412        box.Initialize();
413
414        if (!vc->IsLeaf())
415        {
416                ViewCellInterior *vci = (ViewCellInterior *) vc;
417
418                ViewCellContainer::iterator it = vci->mChildren.begin();
419                for (; it != vci->mChildren.end(); ++it)
420                {
421                        box.Include(GetViewCellBox(*it));
422                }
423        }
424
425        return box;
426}
427
428
429int ViewCellsManager::CastPassSamples(const int samplesPerPass,
430                                                                          const vector<int> &strategies,
431                                                                          VssRayContainer &passSamples
432                                                                          ) const
433{
434        long startTime = GetTime();
435       
436        SimpleRayContainer simpleRays;
437       
438        simpleRays.reserve(samplesPerPass);
439        // reserve 2 times the size because always creates double rays
440        passSamples.reserve(samplesPerPass * 2);
441
442        // create one third of each type
443        int castRays = 0;
444       
445        const int numRaysPerPass = samplesPerPass / (int)strategies.size();
446        vector<int>::const_iterator iit, iit_end = strategies.end();
447
448        for (iit = strategies.begin(); iit != iit_end; ++ iit)
449        {
450                const int stype = *iit;
451                const int newRays =
452                        mPreprocessor->GenerateRays(numRaysPerPass, stype, simpleRays);
453
454                cout << "cast " << newRays << " rays of strategy " << stype << endl;
455                castRays += newRays;
456        }
457
458        cout << "generated " << samplesPerPass << " samples in "
459                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
460
461        startTime = GetTime();
462
463        // shoot simple ray and add it to importance samples
464        mPreprocessor->CastRays(simpleRays, passSamples, true);
465       
466        cout << "cast " <<  samplesPerPass << " samples in "
467                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
468
469        return (int)passSamples.size();
470}
471
472
473/// helper function which destroys rays or copies them into the output ray container
474inline void disposeRays(VssRayContainer &rays, VssRayContainer *outRays)
475{
476        cout << "disposing samples ... ";
477        long startTime = GetTime();
478        int n = (int)rays.size();
479
480        if (outRays)
481        {
482                VssRayContainer::const_iterator it, it_end = rays.end();
483                for (it = rays.begin(); it != it_end; ++ it)
484                {
485                        outRays->push_back(*it);
486                }
487        }
488        else
489        {
490                VssRayContainer::const_iterator it, it_end = rays.end();
491                for (it = rays.begin(); it != it_end; ++ it)
492                {
493                        if (!(*it)->IsActive())
494                                delete (*it);
495                }
496        }
497
498        cout << "finished" << endl;
499        Debug << "disposed " << n << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
500}
501
502
503int ViewCellsManager::Construct(Preprocessor *preprocessor, VssRayContainer *outRays)
504{
505        int numSamples = 0;
506
507        SimpleRayContainer simpleRays;
508        VssRayContainer initialSamples;
509
510        // store pointer to preprocessor for further use during construction
511        mPreprocessor = preprocessor;
512       
513        // now decode distribution string
514        char mix[1024];
515        Environment::GetSingleton()->GetStringValue("RssPreprocessor.distributions", mix);
516        Debug << "using mixture distributions: " << mix << endl;
517
518        mMixtureDistribution = new MixtureDistribution(*mPreprocessor);
519        mMixtureDistribution->Construct(mix);
520
521        ///////////////////////////////////////////////////////
522        //-- Initial sampling for the construction of the view cell hierarchy.
523        //-- We use uniform sampling / box based sampling.
524       
525        long startTime = GetTime();
526        cout << "view cell construction: casting " << mInitialSamples << " initial samples ... " << endl;
527
528        // cast initial samples
529       
530        // mix of sampling strategies
531#if 0
532        vector<int>dummy;
533        dummy.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
534        dummy.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
535        dummy.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
536#endif
537        CastPassSamples(mInitialSamples, mStrategies, initialSamples);
538
539        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
540
541        // construct view cells
542        ConstructSubdivision(preprocessor->mObjects, initialSamples);
543
544        // initial samples count for overall samples ...
545        numSamples += mInitialSamples;
546
547        // rays can be passed or deleted
548        disposeRays(initialSamples, outRays);
549
550        cout << "time needed for initial construction: "
551                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
552
553        Debug << "time needed for initial construction: "
554                  << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
555
556        // collect view cells and compute statistics
557        ResetViewCells();
558
559
560        ///////////////////
561        //-- Initial hierarchy construction finished.
562        //-- We can do some stats and visualization
563       
564        if (0)
565        {
566                //-- export initial view cell partition
567                Debug << "\nView cells after initial sampling:\n" << mCurrentViewCellsStats << endl;
568
569                const string filename("viewcells.wrl");
570                Exporter *exporter = Exporter::GetExporter(filename.c_str());
571       
572                if (exporter)
573                {
574                        cout << "exporting initial view cells (=leaves) to " << filename.c_str() << " ... ";
575
576                        if (mExportGeometry)
577                        {
578                                exporter->ExportGeometry(preprocessor->mObjects);
579                        }
580
581                        exporter->SetWireframe();
582                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
583
584                        delete exporter;
585                        cout << "finished" << endl;
586                }
587        }
588
589
590        //////////////////////
591        //-- Cast some more sampling after initial construction.
592        //-- The additional rays can be used to gain
593        //-- some more information before the bottom-up merge
594        //-- note: guided rays could be used for this task
595
596        // time spent after construction of the initial partition
597        startTime = GetTime();
598        const int n = mConstructionSamples; //+initialSamples;
599
600        while (numSamples < n)
601        {
602                cout << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
603                Debug << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
604
605                VssRayContainer constructionSamples;
606
607                // cast new samples
608                numSamples += CastPassSamples(mSamplesPerPass,
609                                                                          mStrategies,
610                                                                          constructionSamples);
611
612                cout << "finished" << endl;
613                cout << "computing sample contribution for " << (int)constructionSamples.size() << " samples ... ";
614
615                // computes sample contribution of cast rays
616                if (SAMPLE_AFTER_SUBDIVISION)
617                        ComputeSampleContributions(constructionSamples, true, false);
618
619                cout << "finished" << endl;
620
621                disposeRays(constructionSamples, outRays);
622                cout << "total samples: " << numSamples << endl;
623        }
624
625        if (0)
626        {
627                ///////////////
628                //-- Get stats after the additional sampling step
629                //-- and before the bottom-up merge step
630
631                EvaluateViewCellsStats();
632                Debug << "\noriginal view cell partition before post process:\n"
633                          << mCurrentViewCellsStats << endl;
634       
635                mRenderer->RenderScene();
636                SimulationStatistics ss;
637                static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
638
639                Debug << ss << endl;
640        }
641
642        ////////////////////
643        //-- post processing of the initial construction
644        //-- We can bottom-up merge the view cells in this step
645        //-- We can additionally cast some post processing sample rays.
646        //-- These rays can be used to store the view cells with the rays
647
648        VssRayContainer postProcessSamples;
649        cout << "casting " << mPostProcessSamples << " post process samples ..." << endl;
650       
651        CastPassSamples(mPostProcessSamples, mStrategies, postProcessSamples);
652
653        cout << "finished post process sampling" << endl;
654        cout << "starting post processing and visualization" << endl;
655
656        // store view cells with rays for post processing?
657        const bool storeViewCells = true;
658
659        if (SAMPLE_AFTER_SUBDIVISION)
660                ComputeSampleContributions(postProcessSamples, true, storeViewCells);
661
662        PostProcess(preprocessor->mObjects, postProcessSamples);
663
664        const float secs = TimeDiff(startTime, GetTime()) * 1e-3f;
665        cout << "post processing (=merge) finished in " << secs << " secs" << endl;
666
667        Debug << "post processing time: " << secs << endl;
668        disposeRays(postProcessSamples, outRays);
669
670
671        ////////////////
672        //-- Evaluation of the resulting view cell partition.
673        //-- We cast a number of new samples and measure the render cost
674
675        if (mEvaluateViewCells)
676        {
677                EvalViewCellPartition();
678        }
679       
680        /////////////////
681        //-- Show some visualizations
682
683        if (mShowVisualization)
684        {
685                ///////////////
686                //-- visualization rays, e.g., to show some samples in the scene
687               
688                VssRayContainer visSamples;
689                int numSamples = CastPassSamples(mVisualizationSamples,
690                                                                                 mStrategies,
691                                                                                 visSamples);
692
693                if (SAMPLE_AFTER_SUBDIVISION)
694                        ComputeSampleContributions(visSamples, true, storeViewCells);
695
696                // various visualizations
697                Visualize(preprocessor->mObjects, visSamples);
698
699                disposeRays(visSamples, outRays);
700        }
701
702        // recalculate view cells
703        EvaluateViewCellsStats();
704
705        // compress the final solution
706        if (0) CompressViewCells();
707
708        // write view cells to disc
709        if (mExportViewCells)
710        {
711                char filename[100];
712
713                Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
714                ExportViewCells(filename, mExportPvs, mPreprocessor->mObjects);
715        }
716
717        return numSamples;
718}
719
720
721AxisAlignedPlane *ViewCellsManager::GetClipPlane()
722{
723        return mUseClipPlaneForViz ? &mClipPlaneForViz : NULL;
724}
725
726
727ViewCellsManager *ViewCellsManager::LoadViewCells(const string &filename,
728                                                                                                  ObjectContainer &pvsObjects,
729                                                                                                  bool finalizeViewCells,
730                                                                                                  BoundingBoxConverter *bconverter)
731                                                                                                 
732{
733        if (!Debug.is_open()) Debug.open("debug.log");
734
735
736        if (strstr(filename.c_str(), ".bn"))
737        {
738                Debug << "binary view cells format detected" << endl;
739
740                return LoadViewCellsBinary(filename,
741                                               pvsObjects,
742                                                                   finalizeViewCells,
743                                                                   bconverter);
744        }
745        else
746        {
747                Debug << "xml view cells format detected" << endl;
748
749                // give just an empty container as parameter:
750                // this loading function is used in the engine, thus it
751                // does not need to load the entities the preprocessor works on
752                ObjectContainer preprocessorObjects;
753
754                return LoadViewCells(filename,
755                                         pvsObjects,
756                                                         preprocessorObjects,
757                                                         finalizeViewCells,
758                                                         bconverter);
759        }
760}
761
762void ViewCellsManager::LoadIndexedBoundingBoxesBinary(IN_STREAM &stream, IndexedBoundingBoxContainer &iboxes)
763{
764        int numBoxes;
765        stream.read(reinterpret_cast<char *>(&numBoxes), sizeof(int));
766
767        iboxes.reserve(numBoxes);
768
769        Vector3 bmin;
770        Vector3 bmax;
771        int id;
772
773#ifdef USE_PERFTIMER 
774        PerfTimer boxTimer;
775
776        boxTimer.Start();
777        boxTimer.Entry();
778#endif 
779        for (int i = 0; i < numBoxes; ++ i)
780        {
781                stream.read(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
782                stream.read(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
783                stream.read(reinterpret_cast<char *>(&id), sizeof(int));
784
785                iboxes.push_back(IndexedBoundingBox(id, AxisAlignedBox3(bmin, bmax)));
786        }
787
788
789#ifdef USE_PERFTIMER 
790        boxTimer.Exit();
791
792        Debug << numBoxes << " boxes loaded in " << boxTimer.TotalTime() << " secs" << endl;
793#endif
794}
795
796
797ViewCellsManager *ViewCellsManager::LoadViewCells(const string &filename,
798                                                                                                  ObjectContainer &pvsObjects,
799                                                                                                  ObjectContainer &preprocessorObjects,
800                                                                                                  bool finalizeViewCells,
801                                                                                                  BoundingBoxConverter *bconverter)                                                                                             
802{
803        ViewCellsParser parser;
804        ViewCellsManager *vm = NULL;
805
806        const long startTime = GetTime();
807        const bool success = parser.ParseViewCellsFile(filename,
808                                                                                                   &vm,
809                                                                                                   pvsObjects,
810                                                                                                   preprocessorObjects,
811                                                                                                   bconverter);
812
813        if (!success)
814        {
815                Debug << "Error: loading view cells failed!" << endl;
816                DEL_PTR(vm);
817
818                return NULL;
819        }
820       
821        if (0) //hack: reset function should work, but something is wrong ..
822        {
823                vm->ResetViewCells();
824        }
825        else
826        {
827                ViewCellContainer leaves;
828
829                vm->mViewCells.clear();
830                vm->mViewCellsTree->CollectLeaves(vm->mViewCellsTree->GetRoot(), leaves);
831               
832                ViewCellContainer::const_iterator it, it_end = leaves.end();
833
834                for (it = leaves.begin(); it != it_end; ++ it)
835                {
836                        vm->mViewCells.push_back(*it);
837                }
838        }
839
840        vm->mViewCellsFinished = true;
841        vm->mMaxPvsSize = (int)pvsObjects.size();
842
843        if (finalizeViewCells)
844        {
845                // do some final computations, e.g.,
846                // create the meshes and compute view cell volumes
847                const bool createMeshes = true;
848                vm->FinalizeViewCells(createMeshes);
849        }
850
851        cout << (int)vm->mViewCells.size() << " view cells loaded in "
852                 << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
853
854        Debug << (int)vm->mViewCells.size() << " view cells loaded in "
855                  << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
856       
857        return vm;
858}
859
860
861bool VspBspViewCellsManager::ExportViewCells(const string filename,
862                                                                                         const bool exportPvs,
863                                                                                         const ObjectContainer &objects)
864{
865        // no view cells constructed yet
866        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
867                return false;
868
869        cout << "exporting view cells to xml ... ";
870
871        OUT_STREAM stream(filename.c_str());
872
873        // we need unique ids for each view cell
874        CreateUniqueViewCellIds();
875
876        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
877        stream << "<VisibilitySolution>" << endl;
878
879        if (exportPvs)
880        {
881                //-- export bounding boxes
882                stream << "<BoundingBoxes>" << endl;
883
884                if (mUseKdPvs)
885                {
886                        vector<KdIntersectable *>::iterator kit, kit_end = GetPreprocessor()->mKdTree->mKdIntersectables.end();
887
888                        int id = 0;
889                        for (kit = GetPreprocessor()->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
890                        {
891                                Intersectable *obj = *kit;
892                                const AxisAlignedBox3 box = obj->GetBox();
893                 
894                                obj->SetId(id);
895       
896                                stream << "<BoundingBox" << " id=\"" << id << "\""
897                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
898                                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
899                        }
900                }
901                else
902                {
903                        ObjectContainer::const_iterator oit, oit_end = objects.end();
904               
905                        for (oit = objects.begin(); oit != oit_end; ++ oit)
906                        {
907                                const AxisAlignedBox3 box = (*oit)->GetBox();
908
909                                ////////////
910                                //-- the bounding boxes
911
912                                stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
913                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
914                                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
915                        }
916                }
917
918                stream << "</BoundingBoxes>" << endl;
919        }
920
921       
922        /////////////
923        //-- export the view cells and the pvs
924
925        const int numViewCells = mCurrentViewCellsStats.viewCells;
926        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
927
928        mViewCellsTree->Export(stream, exportPvs);
929
930        stream << "</ViewCells>" << endl;
931
932
933        //////////
934        //-- export the view space hierarchy
935       
936        stream << "<ViewSpaceHierarchy type=\"bsp\""
937                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
938                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
939
940        mVspBspTree->Export(stream);
941        stream << "</ViewSpaceHierarchy>" << endl;
942
943        stream << "</VisibilitySolution>" << endl;
944
945        stream.close();
946        cout << "finished" << endl;
947
948        return true;
949}
950
951
952void ViewCellsManager::EvalViewCellHistogram(const string filename,
953                                                                                         const int nViewCells)
954{
955        std::ofstream outstream;
956        outstream.open(filename.c_str());
957
958        ViewCellContainer viewCells;
959       
960        // the collect best viewcells does not work?
961        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
962
963        float maxRenderCost, minRenderCost;
964
965        // sort by render cost
966        sort(viewCells.begin(), viewCells.end(), SmallerRenderCost);
967
968        minRenderCost = viewCells.front()->GetRenderCost();
969        maxRenderCost = viewCells.back()->GetRenderCost();
970
971        Debug << "histogram min rc: " << minRenderCost << " max rc: " << maxRenderCost << endl;
972
973    int histoIntervals;
974        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
975        const int intervals = min(histoIntervals, (int)viewCells.size());
976
977        int histoMaxVal;
978        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
979        maxRenderCost = min((float)histoMaxVal, maxRenderCost);
980
981       
982        const float range = maxRenderCost - minRenderCost;
983        const float stepSize = range / (float)intervals;
984
985        float currentRenderCost = minRenderCost;//(int)ceil(minRenderCost);
986
987        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
988        const float totalVol = GetViewSpaceBox().GetVolume();
989        //const float totalVol = mViewCellsTree->GetRoot()->GetVolume();
990
991        int j = 0;
992        int i = 0;
993       
994        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();             
995
996        // count for integral
997        float volSum = 0;
998        int smallerCostSum = 0;
999       
1000        // note can skip computations for view cells already
1001        // evaluated and delete them from vector ...
1002    while (1)
1003        {
1004                // count for histogram value
1005                float volDif = 0;
1006                int smallerCostDif = 0;
1007
1008                while ((i < (int)viewCells.size()) && (viewCells[i]->GetRenderCost() < currentRenderCost))
1009                {
1010                        volSum += viewCells[i]->GetVolume();
1011                        volDif += viewCells[i]->GetVolume();
1012
1013                        ++ i;
1014                        ++ smallerCostSum;
1015                        ++ smallerCostDif;
1016                }
1017               
1018                if ((i >= (int)viewCells.size()) || (currentRenderCost >= maxRenderCost))
1019                        break;
1020               
1021                const float rcRatio = currentRenderCost / maxRenderCost;
1022                const float volRatioSum = volSum / totalVol;
1023                const float volRatioDif = volDif / totalVol;
1024
1025                outstream << "#Pass\n" << j ++ << endl;
1026                outstream << "#RenderCostRatio\n" << rcRatio << endl;
1027                outstream << "#WeightedCost\n" << currentRenderCost / totalVol << endl;
1028                outstream << "#ViewCellsDif\n" << smallerCostDif << endl;
1029                outstream << "#ViewCellsSum\n" << smallerCostSum << endl;       
1030                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1031                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1032
1033                // increase current render cost
1034                currentRenderCost += stepSize;
1035        }
1036
1037        outstream.close();
1038}
1039
1040void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
1041                                                                                                           const int nViewCells)
1042{
1043        std::ofstream outstream;
1044        outstream.open(filename.c_str());
1045
1046        ViewCellContainer viewCells;
1047
1048#ifdef USE_BIT_PVS
1049        cout << "objects size: " << (int)ObjectPvsIterator::sObjects.size() << endl;
1050        cout << "pvs size: " <<  ObjectPvs::sPvsSize << endl;
1051#endif
1052
1053        // $$ JB hack - the collect best viewcells does not work?
1054#if 0
1055        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
1056#else
1057        viewCells = mViewCells;
1058#endif
1059
1060        ViewCellContainer::iterator it = viewCells.begin(), it_end = viewCells.end();           
1061       
1062        for (; it != it_end; ++it)
1063        {
1064                (*it)->UpdatePvsCost();
1065        }
1066
1067        float maxPvs, maxVal, minVal;
1068       
1069        // sort by pvs size
1070        sort(viewCells.begin(), viewCells.end(), SmallerPvs);
1071
1072        maxPvs = viewCells.back()->GetTrianglesInPvs();
1073        minVal = 0;
1074
1075        // hack: normalize pvs size
1076        int histoMaxVal;
1077        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
1078        maxVal = max((float)histoMaxVal, maxPvs);
1079               
1080        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
1081                << " real maxpvs " << maxPvs << endl;
1082
1083        int histoIntervals;
1084        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
1085        const int intervals = min(histoIntervals, (int)viewCells.size());
1086
1087        const float range = maxVal - minVal;
1088        int stepSize = (int)(range / intervals);
1089
1090        // set step size to avoid endless loop
1091        if (!stepSize) stepSize = 1;
1092       
1093        Debug << "intervals " << histoIntervals << endl;
1094        Debug << "stepsize: " << stepSize << endl;
1095        cout << "intervals " << histoIntervals << endl;
1096        cout << "stepsize: " << stepSize << endl;
1097
1098        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
1099        const float totalVol = GetViewSpaceBox().GetVolume();
1100
1101        float currentPvs = minVal;
1102       
1103        int i = 0;
1104        int j = 0;
1105        float volSum = 0;
1106        int smallerSum = 0;
1107
1108        it = viewCells.begin();
1109       
1110        for (int j = 0; j < intervals; ++ j)
1111        {
1112                float volDif = 0;
1113                int smallerDif = 0;
1114
1115                while ((i < (int)viewCells.size()) &&
1116                           (viewCells[i]->GetTrianglesInPvs() < currentPvs))
1117                {
1118                        volDif += viewCells[i]->GetVolume();
1119                        volSum += viewCells[i]->GetVolume();
1120
1121                        ++ i;
1122                        ++ smallerDif;
1123                        ++ smallerSum;
1124                }
1125               
1126                const float volRatioDif = volDif / totalVol;
1127                const float volRatioSum = volSum / totalVol;
1128
1129                outstream << "#Pass\n" << j << endl;
1130                outstream << "#Pvs\n" << currentPvs << endl;
1131                outstream << "#ViewCellsDif\n" << smallerDif << endl;
1132                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
1133                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1134                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1135       
1136                //-- increase current pvs size to define next interval
1137                currentPvs += stepSize;
1138        }
1139
1140        outstream.close();
1141}
1142
1143
1144void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
1145                                                                                                           ViewCellContainer &viewCells)
1146{
1147        std::ofstream outstream;
1148        outstream.open(filename.c_str());
1149
1150        float maxPvs, maxVal, minVal;
1151       
1152        // sort by pvs size
1153        sort(viewCells.begin(), viewCells.end(), SmallerPvs);
1154
1155        maxPvs = viewCells.back()->GetTrianglesInPvs();
1156        minVal = 0;
1157
1158        // hack: normalize pvs size
1159        int histoMaxVal;
1160        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
1161        maxVal = max((float)histoMaxVal, maxPvs);
1162               
1163        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
1164                << " real maxpvs " << maxPvs << endl;
1165
1166        int histoIntervals;
1167        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
1168        const int intervals = min(histoIntervals, (int)viewCells.size());
1169
1170        const float range = maxVal - minVal;
1171        int stepSize = (int)(range / intervals);
1172
1173        // set step size to avoid endless loop
1174        if (!stepSize) stepSize = 1;
1175       
1176        Debug << "intervals " << histoIntervals << endl;
1177        Debug << "stepsize: " << stepSize << endl;
1178        cout << "intervals " << histoIntervals << endl;
1179        cout << "stepsize: " << stepSize << endl;
1180
1181        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
1182        const float totalVol = GetViewSpaceBox().GetVolume();
1183
1184        float currentPvs = minVal;
1185       
1186        int i = 0;
1187        int j = 0;
1188        float volSum = 0;
1189        int smallerSum = 0;
1190
1191        //ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();   
1192       
1193        for (int j = 0; j < intervals; ++ j)
1194        {
1195                float volDif = 0;
1196                int smallerDif = 0;
1197
1198                while ((i < (int)viewCells.size()) &&
1199                           (viewCells[i]->GetTrianglesInPvs() < currentPvs))
1200                {
1201                        volDif += viewCells[i]->GetVolume();
1202                        volSum += viewCells[i]->GetVolume();
1203
1204                        ++ i;
1205                        ++ smallerDif;
1206                        ++ smallerSum;
1207                }
1208               
1209                //              if (0 && (i < (int)viewCells.size()))
1210                //                Debug << "new pvs cost increase: " << mViewCellsTree->GetTrianglesInPvs(viewCells[i])
1211                //                              << " " << currentPvs << endl;
1212               
1213                const float volRatioDif = volDif / totalVol;
1214                const float volRatioSum = volSum / totalVol;
1215
1216                outstream << "#Pass\n" << j << endl;
1217                outstream << "#Pvs\n" << currentPvs << endl;
1218                outstream << "#ViewCellsDif\n" << smallerDif << endl;
1219                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
1220                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1221                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1222       
1223                //-- increase current pvs size to define next interval
1224                currentPvs += stepSize;
1225        }
1226
1227        outstream.close();
1228}
1229
1230
1231bool ViewCellsManager::GetExportPvs() const
1232{
1233        return mExportPvs;
1234}
1235
1236
1237void ViewCellsManager::ResetPvs()
1238{
1239        if (ViewCellsTreeConstructed())
1240        {
1241                mViewCellsTree->ResetPvs();
1242        }
1243        else
1244        {
1245                cout << "view cells tree not constructed" << endl;
1246        }
1247}
1248
1249
1250void ViewCellsManager::ExportStats(const string &fileName)
1251{
1252        mViewCellsTree->ExportStats(fileName);
1253}
1254
1255
1256void ViewCellsManager::EvalViewCellPartition()
1257{
1258        int samplesPerPass;
1259        int numSamples;
1260        int castSamples = 0;
1261        char str[64];
1262        int oldSamples = 0;
1263
1264        int samplesForStats;
1265
1266        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
1267        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesForStats", samplesForStats);
1268        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", numSamples);
1269
1270        char statsPrefix[100];
1271        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
1272
1273        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
1274        Debug << "view cell evaluation samples: " << numSamples << endl;
1275        Debug << "view cell stats prefix: " << statsPrefix << endl;
1276
1277        cout << "reseting pvs ... ";
1278               
1279        const bool startFromZero = true;
1280
1281        // reset pvs and start over from zero
1282        if (startFromZero)
1283        {
1284                mViewCellsTree->ResetPvs();
1285        }
1286        else // start from current sampless
1287        {
1288                // statistics before casting more samples
1289                cout << "compute new statistics ... ";
1290                sprintf(str, "-%09d-eval.log", castSamples);
1291                string fName = string(statsPrefix) + string(str);
1292
1293                mViewCellsTree->ExportStats(fName);
1294                cout << "finished" << endl;
1295        }
1296
1297        cout << "finished" << endl;
1298    cout << "Evaluating view cell partition ... " << endl;
1299
1300        while (castSamples < numSamples)
1301        {               
1302                ///////////////
1303                //-- we have to use uniform sampling strategy for construction rays
1304
1305                VssRayContainer evaluationSamples;
1306                const int samplingType = mEvaluationSamplingType;
1307
1308                long startTime = GetTime();
1309
1310                cout << "casting " << samplesPerPass << " samples ... ";
1311                Debug << "casting " << samplesPerPass << " samples ... ";
1312
1313                CastPassSamples(samplesPerPass, mStrategies, evaluationSamples);
1314               
1315                castSamples += samplesPerPass;
1316
1317                Real timeDiff = TimeDiff(startTime, GetTime());
1318               
1319                cout << "finished in " << timeDiff * 1e-3f << " secs" << endl;
1320                cout << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
1321               
1322                Debug << "finished in " << timeDiff * 1e-3f << " secs" << endl;
1323                Debug << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
1324
1325                startTime = GetTime();
1326
1327                ComputeSampleContributions(evaluationSamples, true, false);
1328
1329                timeDiff = TimeDiff(startTime, GetTime());
1330                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1331                Debug << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1332
1333                if ((castSamples >= samplesForStats + oldSamples) || (castSamples >= numSamples))
1334                {
1335                        oldSamples += samplesForStats;
1336
1337                        ///////////
1338                        //-- output stats
1339
1340                        sprintf(str, "-%09d-eval.log", castSamples);
1341                        string fileName = string(statsPrefix) + string(str);
1342
1343                        ///////////////
1344                        //-- propagate pvs or pvs size information
1345
1346                        startTime = GetTime();
1347                        ObjectPvs pvs;
1348
1349                        cout << "updating pvs for evaluation ... " << endl;
1350
1351                        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), pvs);
1352
1353                        timeDiff = TimeDiff(startTime, GetTime());
1354                        cout << "finished updating the pvs in " << timeDiff * 1e-3 << " secs" << endl;
1355                        Debug << "pvs evaluated in " << timeDiff * 1e-3 << " secs" << endl;
1356               
1357                        startTime = GetTime();
1358                        cout << "compute new statistics ... " << endl;
1359
1360                        ExportStats(fileName);
1361
1362                        timeDiff = TimeDiff(startTime, GetTime());
1363                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1364                        Debug << "statistis computed in " << timeDiff * 1e-3 << " secs" << endl;
1365                }
1366
1367                disposeRays(evaluationSamples, NULL);
1368        }
1369       
1370
1371        ////////////
1372        //-- histogram
1373
1374        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
1375        bool useHisto;
1376        int histoStepSize;
1377
1378        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
1379        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
1380
1381        if (useHisto)
1382        {
1383                // evaluate view cells in a histogram           
1384                char s[64];
1385
1386                for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
1387                {
1388                        string filename;
1389
1390                        cout << "computing histogram for " << pass << " view cells" << endl;
1391#if 0
1392                        //-- evaluate histogram for render cost
1393                        sprintf(s, "-%09d-histo.log", pass);
1394                        filename = string(statsPrefix) + string(s);
1395
1396                        EvalViewCellHistogram(filename, pass);
1397
1398#endif
1399                        //////////////////////////////////////////
1400            //-- evaluate histogram for pvs size
1401
1402                        cout << "computing pvs histogram for " << pass << " view cells" << endl;
1403
1404                        sprintf(s, "-%09d-histo-pvs.log", pass);
1405                        filename = string(statsPrefix) + string(s);
1406
1407                        EvalViewCellHistogram(filename, pass);
1408                        //                      EvalViewCellHistogramForPvsSize(filename, pass);
1409                }
1410        }
1411}
1412
1413
1414inline float EvalMergeCost(ViewCell *root, ViewCell *candidate)
1415{
1416  return root->GetPvs().GetPvsHomogenity(candidate->GetPvs());
1417}
1418
1419
1420/// Returns index of the best view cells of the neighborhood
1421static int GetBestViewCellIdx(ViewCell *root, const ViewCellContainer &neighborhood)
1422{
1423        int bestViewCellIdx = 0;
1424
1425        float mergeCost = Limits::Infinity;
1426        int i = 0;
1427
1428        ViewCellContainer::const_iterator vit, vit_end = neighborhood.end();
1429
1430        for (vit = neighborhood.begin(); vit != vit_end; ++ vit, ++ i)
1431        {
1432                const float mc = EvalMergeCost(root, *vit);
1433               
1434                if (mc < mergeCost)
1435                {
1436                        mergeCost = mc;
1437                        bestViewCellIdx = i;
1438                }
1439        }
1440
1441        return bestViewCellIdx;
1442}
1443
1444
1445void ViewCellsManager::SetMaxFilterSize(const int size)
1446{
1447        mMaxFilterSize = size;
1448}
1449
1450
1451float ViewCellsManager::ComputeRenderCost(const int tri, const int obj) //const
1452{
1453        return max((float)tri * mTriangleWeight, (float)obj * mObjectWeight);
1454}
1455
1456
1457ViewCell *ViewCellsManager::ConstructLocalMergeTree(ViewCell *currentViewCell,
1458                                                                                                        const ViewCellContainer &viewCells)
1459{
1460        ViewCell *root = currentViewCell;
1461        ViewCellContainer neighborhood = viewCells;
1462
1463        ViewCellContainer::const_iterator it, it_end = neighborhood.end();
1464
1465        const int n = min(mMaxFilterSize, (int)neighborhood.size());
1466       
1467        /////////////////
1468        //-- use priority queue to merge leaf pairs
1469       
1470        for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1471        {
1472                const int bestViewCellIdx = GetBestViewCellIdx(root, neighborhood);
1473               
1474                ViewCell *bestViewCell = neighborhood[bestViewCellIdx];
1475       
1476                // remove from vector
1477                swap(neighborhood[bestViewCellIdx], neighborhood.back());
1478                neighborhood.pop_back();
1479       
1480                if (!bestViewCell || !root)
1481            cout << "warning!!" << endl;
1482               
1483                // create new root of the hierarchy
1484                root = MergeViewCells(root, bestViewCell);
1485        }
1486
1487        return root;   
1488}
1489
1490
1491
1492ViewCell * ViewCellsManager::ConstructLocalMergeTree2(ViewCell *currentViewCell,
1493                                                                                                          const ViewCellContainer &viewCells)
1494{
1495 
1496  vector<SortableViewCellEntry> neighborhood(viewCells.size());
1497  int i, j;
1498  for (i = 0, j = 0; i < viewCells.size(); i++) {
1499        if (viewCells[i] != currentViewCell)
1500          neighborhood[j++] = SortableViewCellEntry(
1501                                                                                                EvalMergeCost(currentViewCell, viewCells[i]),
1502                                                                                                viewCells[i]);
1503  }
1504  neighborhood.resize(j);
1505 
1506  sort(neighborhood.begin(), neighborhood.end());
1507 
1508  ViewCell *root = currentViewCell;
1509 
1510  vector<SortableViewCellEntry>::const_iterator it, it_end = neighborhood.end();
1511 
1512  const int n = min(mMaxFilterSize, (int)neighborhood.size());
1513  //-- use priority queue to merge leaf pairs
1514 
1515  //cout << "neighborhood: " << neighborhood.size() << endl;
1516  for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1517  {
1518          ViewCell *bestViewCell = neighborhood[nMergedViewCells].mViewCell;
1519          //cout <<nMergedViewCells<<":"<<"homogenity=" <<neighborhood[nMergedViewCells].mValue<<endl;
1520          // create new root of the hierarchy
1521          root = MergeViewCells(root, bestViewCell);
1522          // set negative cost so that this view cell gets deleted
1523          root->SetMergeCost(-1.0f);
1524  }
1525 
1526  return root; 
1527}
1528
1529void
1530ViewCellsManager::DeleteLocalMergeTree(ViewCell *vc
1531                                                                           ) const
1532{
1533        if (!vc->IsLeaf() && vc->GetMergeCost() < 0.0f)
1534        {       
1535                ViewCellInterior *vci = (ViewCellInterior *) vc;
1536                ViewCellContainer::const_iterator it, it_end = vci->mChildren.end();
1537
1538        for (it = vci->mChildren.begin(); it != it_end; ++ it)
1539                        DeleteLocalMergeTree(*it);
1540               
1541                vci->mChildren.clear();
1542               
1543                delete vci;
1544  }
1545}
1546
1547
1548bool ViewCellsManager::CheckValidity(ViewCell *vc,
1549                                                                         int minPvsSize,
1550                                                                         int maxPvsSize) const
1551{
1552
1553        const float pvsCost = vc->GetPvs().EvalPvsCost();
1554
1555        if ((pvsCost > maxPvsSize) || (pvsCost < minPvsSize))
1556        {
1557                cout << "err: " << pvsCost << " " << minPvsSize << " " << maxPvsSize << endl;
1558                return false;
1559        }
1560
1561        return true;
1562}
1563
1564
1565int ViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
1566                                                                                          ViewCellContainer &viewCells) const
1567{
1568        return 0;
1569};
1570
1571
1572AxisAlignedBox3 ViewCellsManager::GetFilterBBox(const Vector3 &viewPoint,
1573                                                                                                const float width) const
1574{
1575  float w = Magnitude(mViewSpaceBox.Size())*width;
1576  Vector3 min = viewPoint - w * 0.5f;
1577  Vector3 max = viewPoint + w * 0.5f;
1578 
1579  return AxisAlignedBox3(min, max);
1580}
1581
1582
1583void ViewCellsManager::GetPrVS(const Vector3 &viewPoint,
1584                                                           PrVs &prvs,
1585                                                           const float filterWidth)
1586{
1587        ViewCell *currentViewCell = GetViewCell(viewPoint);
1588
1589        if (mMaxFilterSize < 1) {
1590                prvs.mViewCell = currentViewCell;
1591                return;
1592        }
1593
1594        const AxisAlignedBox3 box = GetFilterBBox(viewPoint, filterWidth);
1595
1596        if (currentViewCell)
1597        {
1598                ViewCellContainer viewCells;
1599                ComputeBoxIntersections(box, viewCells);
1600
1601                ViewCell *root = ConstructLocalMergeTree2(currentViewCell, viewCells);
1602                prvs.mViewCell = root;
1603
1604        }
1605        else
1606        {
1607                prvs.mViewCell = NULL;
1608                //prvs.mPvs = root->GetPvs();
1609        }
1610}
1611
1612
1613bool ViewCellsManager::ViewCellsTreeConstructed() const
1614{
1615    return (mViewCellsTree && mViewCellsTree->GetRoot());
1616}
1617
1618
1619void ViewCellsManager::SetValidity(ViewCell *vc,
1620                                                                   int minPvs,
1621                                                                   int maxPvs) const
1622{
1623        vc->SetValid(CheckValidity(vc, minPvs, maxPvs));
1624}
1625
1626
1627void
1628ViewCellsManager::SetValidity(
1629                                                          int minPvsSize,
1630                                                          int maxPvsSize) const
1631{
1632        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1633
1634
1635        for (it = mViewCells.begin(); it != it_end; ++ it)
1636        {
1637                SetValidity(*it, minPvsSize, maxPvsSize);
1638        }
1639}
1640
1641void
1642ViewCellsManager::SetValidityPercentage(
1643                                                                                const float minValid,
1644                                                                                const float maxValid
1645                                                                                )
1646{
1647  ObjectPvs dummyPvs;
1648  // update pvs sizes
1649  for (int i = 0; i < (int)mViewCells.size(); ++ i) {
1650        UpdatePvsForEvaluation(mViewCells[i], dummyPvs);
1651  }
1652 
1653  sort(mViewCells.begin(), mViewCells.end(), SmallerPvs);
1654 
1655  int start = (int)(mViewCells.size() * minValid);
1656  int end = (int)(mViewCells.size() * maxValid);
1657 
1658  for (int i = 0; i < (int)mViewCells.size(); ++ i)
1659        {
1660          //      cout<<"pvs:"<<mViewCells[i]->GetCachedPvsCost()<<endl;
1661          mViewCells[i]->SetValid(i >= start && i <= end);
1662        }
1663}
1664
1665
1666int ViewCellsManager::CountValidViewcells() const
1667{
1668        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1669        int valid = 0;
1670
1671        for (it = mViewCells.begin(); it != it_end; ++ it)
1672        {       
1673                if ((*it)->GetValid())
1674                        ++ valid;
1675        }
1676
1677        return valid;
1678}
1679
1680
1681bool ViewCellsManager::LoadViewCellsGeometry(const string filename,
1682                                                                                         const bool extrudeBaseTriangles)
1683{
1684        /// we use predefined view cells from now on
1685        mUsePredefinedViewCells = true;
1686        X3dParser parser;
1687       
1688        if (extrudeBaseTriangles)
1689        {
1690                Environment::GetSingleton()->GetFloatValue("ViewCells.height", parser.mViewCellHeight);
1691                const bool success = parser.ParseFile(filename, *this);
1692
1693                if (!success)
1694                        return false;
1695        }
1696        else
1697        {
1698                // hack: use standard mesh loading
1699                // create temporary scene graph for loading the view cells geometry
1700                // note: delete the meshes as they are created two times for transformed mesh instances.
1701                SceneGraphLeaf *root = new SceneGraphLeaf();
1702                const bool success = parser.ParseFile(filename, root, true);
1703               
1704                if (!success)
1705                {
1706                        DEL_PTR(root);
1707                        return false;
1708                }
1709
1710                ObjectContainer::const_iterator oit, oit_end = root->mGeometry.end();
1711               
1712                for (oit = root->mGeometry.begin(); oit != oit_end; ++ oit)
1713                {
1714                        Mesh *mesh;
1715                        if ((*oit)->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
1716                        {
1717                                TransformedMeshInstance *mit = static_cast<TransformedMeshInstance *>(*oit);
1718                                mesh = MeshManager::GetSingleton()->CreateResource();
1719                                mit->GetTransformedMesh(*mesh);
1720                        }
1721                        else if ((*oit)->Type() == Intersectable::MESH_INSTANCE)
1722                        {
1723                                MeshInstance *mit = static_cast<MeshInstance *>(*oit);
1724                                mesh = mit->GetMesh();
1725                        }
1726                        mesh->ComputeBoundingBox();
1727                        mViewCells.push_back(GenerateViewCell(mesh));
1728                }
1729
1730                DEL_PTR(root);
1731        }
1732
1733        // set view space box to bounding box of the view cells
1734        AxisAlignedBox3 bbox;
1735        bbox.Initialize();
1736        ViewCellContainer::iterator it = mViewCells.begin(), it_end = mViewCells.end();
1737
1738        for (; it != it_end; ++ it)
1739        {
1740                bbox.Include((*it)->GetMesh()->mBox);
1741        }
1742
1743        SetViewSpaceBox(bbox);
1744        cout << "view space box: " << bbox << endl;
1745        cout << "generated " << (int)mViewCells.size() << " view cells using the geometry " << filename << endl;
1746
1747        return true;
1748}
1749
1750
1751bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
1752{
1753  viewPoint = mViewSpaceBox.GetRandomPoint();
1754  return true;
1755}
1756
1757bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint, const Vector3 &params) const
1758{
1759  viewPoint = mViewSpaceBox.GetRandomPoint(params);
1760  return true;
1761}
1762
1763
1764float ViewCellsManager::GetViewSpaceVolume()
1765{
1766        return mViewSpaceBox.GetVolume() * (2.0f * sqr((float)M_PI));
1767}
1768
1769
1770bool ViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
1771{
1772        if (!ViewCellsConstructed())
1773        {
1774                return mViewSpaceBox.IsInside(viewPoint);
1775        }
1776        else
1777        {
1778                if (!mViewSpaceBox.IsInside(viewPoint))
1779                        return false;
1780
1781                ViewCell *viewcell = GetViewCell(viewPoint);
1782
1783                if (!viewcell || !viewcell->GetValid())
1784                        return false;
1785        }
1786
1787        return true;
1788}
1789
1790
1791float
1792ViewCellsManager::ComputeSampleContributions(const VssRayContainer &rays,
1793                                                                                         const bool addContributions,
1794                                                                                         const bool storeViewCells,
1795                                                                                         const bool useHitObjects)
1796{
1797        float sum = 0.0f;
1798
1799        VssRayContainer::const_iterator it, it_end = rays.end();
1800
1801        for (it = rays.begin(); it != it_end; ++ it)
1802        {
1803                if (!ViewCellsConstructed())
1804                {
1805                        // view cells not constructed yet =>
1806                        // just take the lenghts of the rays as contributions
1807                        if ((*it)->mTerminationObject)
1808                        {
1809                                sum += (*it)->Length();
1810                        }
1811                }
1812                else
1813                {
1814                        sum += ComputeSampleContribution(*(*it), addContributions, storeViewCells, useHitObjects);
1815                }
1816        }
1817
1818#ifdef USE_PERFTIMER 
1819        cout << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
1820        Debug << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
1821
1822        cout << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
1823        Debug << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
1824#endif 
1825        return sum;
1826}
1827
1828
1829void ViewCellsManager::EvaluateViewCellsStats()
1830{
1831        mCurrentViewCellsStats.Reset();
1832        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1833
1834        for (it = mViewCells.begin(); it != it_end; ++ it)
1835        {
1836                mViewCellsTree->UpdateViewCellsStats(*it, mCurrentViewCellsStats);
1837        }
1838}
1839
1840
1841void ViewCellsManager::EvaluateRenderStatistics(float &totalRenderCost,
1842                                                                                                float &expectedRenderCost,
1843                                                                                                float &deviation,
1844                                                                                                float &variance,
1845                                                                                                float &totalCost,
1846                                                                                                float &avgRenderCost)
1847{
1848        ////////////
1849        //-- compute expected value
1850
1851        totalRenderCost = 0;
1852        totalCost = 0;
1853
1854        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1855
1856        for (it = mViewCells.begin(); it != it_end; ++ it)
1857        {
1858                ViewCell *vc = *it;
1859                totalRenderCost += vc->GetPvs().EvalPvsCost() * vc->GetVolume();
1860                totalCost += (int)vc->GetPvs().EvalPvsCost();
1861        }
1862
1863        // normalize with view space box
1864        totalRenderCost /= mViewSpaceBox.GetVolume();
1865        expectedRenderCost = totalRenderCost / (float)mViewCells.size();
1866        avgRenderCost = totalCost / (float)mViewCells.size();
1867
1868
1869        ///////////
1870        //-- compute standard defiation
1871
1872        variance = 0;
1873        deviation = 0;
1874
1875        for (it = mViewCells.begin(); it != it_end; ++ it)
1876        {
1877                ViewCell *vc = *it;
1878
1879                float renderCost = vc->GetPvs().EvalPvsCost() * vc->GetVolume();
1880                float dev;
1881
1882                if (1)
1883                        dev = fabs(avgRenderCost - (float)vc->GetPvs().EvalPvsCost());
1884                else
1885                        dev = fabs(expectedRenderCost - renderCost);
1886
1887                deviation += dev;
1888                variance += dev * dev;
1889        }
1890
1891        variance /= (float)mViewCells.size();
1892        deviation /= (float)mViewCells.size();
1893}
1894
1895
1896float ViewCellsManager::GetArea(ViewCell *viewCell) const
1897{
1898        return viewCell->GetArea();
1899}
1900
1901
1902float ViewCellsManager::GetVolume(ViewCell *viewCell) const
1903{
1904        return viewCell->GetVolume();
1905}
1906
1907
1908void ViewCellsManager::CompressViewCells()
1909{
1910        if (!(ViewCellsTreeConstructed() && mCompressViewCells))
1911                return;
1912
1913        ////////////
1914        //-- compression
1915       
1916        int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
1917
1918        cout << "number of entries before compress: " << pvsEntries << endl;
1919        Debug << "number of entries before compress: " << pvsEntries << endl;
1920
1921        mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
1922
1923        pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
1924
1925        Debug << "number of entries after compress: " << pvsEntries << endl;
1926        cout << "number of entries after compress: " << pvsEntries << endl;
1927}
1928
1929
1930ViewCell *ViewCellsManager::ExtrudeViewCell(const Triangle3 &baseTri,
1931                                                                                        const float height) const
1932{
1933        // one mesh per view cell
1934        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
1935//ootl::hash_map<int, Intersectable *> hmap(-2, NULL);
1936        ////////////
1937        //-- construct prism
1938
1939        // bottom
1940        mesh->mFaces.push_back(new Face(2,1,0));
1941        // top
1942    mesh->mFaces.push_back(new Face(3,4,5));
1943        // sides
1944        mesh->mFaces.push_back(new Face(1, 4, 3, 0));
1945        mesh->mFaces.push_back(new Face(2, 5, 4, 1));
1946        mesh->mFaces.push_back(new Face(3, 5, 2, 0));
1947
1948
1949        /////////////
1950        //-- extrude new vertices for top of prism
1951
1952        const Vector3 triNorm = baseTri.GetNormal();
1953        Triangle3 topTri;
1954
1955        // add base vertices and calculate top vertices
1956        for (int i = 0; i < 3; ++ i)
1957        {
1958                mesh->mVertices.push_back(baseTri.mVertices[i]);
1959        }
1960
1961        // add top vertices
1962        for (int i = 0; i < 3; ++ i)
1963        {
1964                mesh->mVertices.push_back(baseTri.mVertices[i] + height * triNorm);
1965        }
1966
1967        // do we have to preprocess this mesh (we don't want to trace view cells!)?
1968        mesh->ComputeBoundingBox();
1969       
1970        return GenerateViewCell(mesh);
1971}
1972
1973
1974void ViewCellsManager::FinalizeViewCells(const bool createMesh)
1975{
1976        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1977
1978        // volume and area of the view cells are recomputed
1979        // a view cell mesh is created
1980        for (it = mViewCells.begin(); it != it_end; ++ it)
1981        {
1982                Finalize(*it, createMesh);
1983        }
1984
1985        mViewCellsTree->AssignRandomColors();
1986
1987        mTotalAreaValid = false;
1988}
1989
1990
1991void ViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
1992{
1993        // implemented in subclasses
1994}
1995
1996
1997/** fast way of merging 2 view cells.
1998*/
1999ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCell *left, ViewCell *right) const
2000{
2001        // generate parent view cell
2002        ViewCellInterior *vc = new ViewCellInterior();
2003
2004        vc->GetPvs().Clear();
2005        ObjectPvs::Merge(vc->GetPvs(), left->GetPvs(), right->GetPvs());
2006
2007        // set only links to child (not from child to parent, maybe not wished!!)
2008        vc->mChildren.push_back(left);
2009        vc->mChildren.push_back(right);
2010
2011        // update pvs size
2012        UpdateScalarPvsSize(vc, vc->GetPvs().EvalPvsCost(), vc->GetPvs().GetSize());
2013
2014        return vc;
2015}
2016
2017
2018ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCellContainer &children) const
2019{
2020        ViewCellInterior *vc = new ViewCellInterior();
2021        ViewCellContainer::const_iterator it, it_end = children.end();
2022
2023        for (it = children.begin(); it != it_end; ++ it)
2024        {
2025                vc->GetPvs().MergeInPlace((*it)->GetPvs());
2026       
2027                vc->mChildren.push_back(*it);
2028        }
2029
2030        return vc;
2031}
2032
2033
2034void ViewCellsManager::SetRenderer(Renderer *renderer)
2035{
2036        mRenderer = renderer;
2037}
2038
2039
2040ViewCellsTree *ViewCellsManager::GetViewCellsTree()
2041{
2042        return mViewCellsTree;
2043}
2044
2045
2046void ViewCellsManager::SetVisualizationSamples(const int visSamples)
2047{
2048        mVisualizationSamples = visSamples;
2049}
2050
2051
2052void ViewCellsManager::SetConstructionSamples(const int constructionSamples)
2053{
2054        mConstructionSamples = constructionSamples;
2055}
2056
2057
2058void ViewCellsManager::SetInitialSamples(const int initialSamples)
2059{
2060        mInitialSamples = initialSamples;
2061}
2062
2063
2064void ViewCellsManager::SetPostProcessSamples(const int postProcessSamples)
2065{
2066        mPostProcessSamples = postProcessSamples;
2067}
2068
2069
2070int ViewCellsManager::GetVisualizationSamples() const
2071{
2072        return mVisualizationSamples;
2073}
2074
2075
2076int ViewCellsManager::GetConstructionSamples() const
2077{
2078        return mConstructionSamples;
2079}
2080
2081
2082int ViewCellsManager::GetPostProcessSamples() const
2083{
2084        return mPostProcessSamples;
2085}
2086
2087
2088void ViewCellsManager::UpdatePvs()
2089{
2090        if (mViewCellPvsIsUpdated || !ViewCellsTreeConstructed())
2091                return;
2092
2093        mViewCellPvsIsUpdated = true;
2094
2095        ViewCellContainer leaves;
2096        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
2097
2098        ViewCellContainer::const_iterator it, it_end = leaves.end();
2099
2100        for (it = leaves.begin(); it != it_end; ++ it)
2101        {
2102                mViewCellsTree->PropagatePvs(*it);
2103        }
2104}
2105
2106
2107void ViewCellsManager::GetPvsStatistics(PvsStatistics &stat)
2108{
2109  // update pvs of view cells tree if necessary
2110  if (0) UpdatePvs();
2111 
2112  ViewCellContainer::const_iterator it = mViewCells.begin();
2113 
2114  stat.viewcells = 0;
2115  stat.minPvs = 100000000;
2116  stat.maxPvs = 0;
2117  stat.avgPvs = 0.0f;
2118  stat.avgPvsEntries = 0.0f;
2119  stat.avgFilteredPvs = 0.0f;
2120  stat.avgFilteredPvsEntries = 0.0f;
2121  stat.avgFilterContribution = 0.0f;
2122  stat.avgFilterRadius = 0;
2123  stat.avgFilterRatio = 0;
2124  stat.avgRelPvsIncrease = 0.0f;
2125  stat.devRelPvsIncrease = 0.0f;
2126  stat.renderCost = 0.0f;
2127  stat.mem = 0.0f;
2128
2129  if (mPerViewCellStat.size() != mViewCells.size()) {
2130        // reset the pvs size array after the first call to this routine
2131        mPerViewCellStat.resize(mViewCells.size());
2132        for (int i=0; i < mPerViewCellStat.size(); i++) {
2133          mPerViewCellStat[i].pvsSize = 0.0f;
2134          mPerViewCellStat[i].relPvsIncrease = 0.0f;
2135        }
2136  }
2137  int i;
2138  bool evaluateFilter;
2139  Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluateFilter", evaluateFilter);
2140
2141  const float vol = mViewSpaceBox.GetVolume();
2142
2143  for (i = 0; it != mViewCells.end(); ++ it, ++ i)
2144  {
2145          ViewCell *viewcell = *it;
2146          if (viewcell->GetValid()) {
2147                  const float pvsCost = mViewCellsTree->GetTrianglesInPvs(viewcell);
2148                  const float renderCost = pvsCost * viewcell->GetVolume() / vol;
2149
2150                  if (pvsCost < stat.minPvs)
2151                          stat.minPvs = pvsCost;
2152                  if (pvsCost > stat.maxPvs)
2153                          stat.maxPvs = pvsCost;
2154
2155                  stat.avgPvs += pvsCost;
2156                  stat.renderCost += renderCost;
2157
2158                  const float pvsEntries = (float)mViewCellsTree->GetPvsEntries(viewcell);
2159                  stat.avgPvsEntries += pvsEntries;
2160
2161                  if (mPerViewCellStat[i].pvsSize > 0.0f)
2162                          mPerViewCellStat[i].relPvsIncrease = (pvsCost - mPerViewCellStat[i].pvsSize) / mPerViewCellStat[i].pvsSize;
2163
2164                  stat.avgRelPvsIncrease += mPerViewCellStat[i].relPvsIncrease;
2165
2166                  // update the pvs size
2167                  mPerViewCellStat[i].pvsSize = pvsCost;
2168
2169
2170                  if (evaluateFilter)
2171                  {
2172                          ObjectPvs filteredPvs;
2173
2174                          PvsFilterStatistics fstat = ApplyFilter2(viewcell, false, mFilterWidth, filteredPvs);
2175
2176                          const float filteredCost = filteredPvs.EvalPvsCost();
2177
2178                          stat.avgFilteredPvs += filteredCost;
2179                          stat.avgFilteredPvsEntries += filteredPvs.GetSize();
2180
2181                          stat.avgFilterContribution += filteredCost - pvsCost;
2182
2183                          stat.avgFilterRadius += fstat.mAvgFilterRadius;
2184                          int sum = fstat.mGlobalFilterCount + fstat.mLocalFilterCount;
2185                          if (sum) {
2186                                  stat.avgFilterRatio += fstat.mLocalFilterCount /
2187                                          (float) sum;
2188                          }
2189
2190                  } else {
2191                          stat.avgFilteredPvs += pvsCost;
2192                          stat.avgFilterContribution += 0;
2193                  }
2194
2195                  ++ stat.viewcells;
2196          }
2197  }
2198
2199
2200
2201  if (stat.viewcells) {
2202          stat.mem = (float)(ObjectPvs::GetEntrySizeByte() * stat.avgPvsEntries + stat.viewcells * 16) / float(1024 * 1024);
2203
2204          stat.avgPvs/=stat.viewcells;
2205          stat.avgPvsEntries/=stat.viewcells;
2206          stat.avgFilteredPvsEntries/=stat.viewcells;
2207          stat.avgFilteredPvs/=stat.viewcells;
2208          stat.avgFilterContribution/=stat.viewcells;
2209          stat.avgFilterRadius/=stat.viewcells;
2210          stat.avgFilterRatio/=stat.viewcells;
2211          stat.avgRelPvsIncrease/=stat.viewcells;
2212          stat.renderCostRatio=stat.renderCost / stat.mem;
2213
2214          // evaluate std deviation of relPvsIncrease
2215          float sum=0.0f;
2216          for (i=0; i < stat.viewcells; i++) {
2217                  sum += sqr(mPerViewCellStat[i].relPvsIncrease - stat.avgRelPvsIncrease);
2218          }
2219          stat.devRelPvsIncrease = sqrt(sum/stat.viewcells);
2220  }
2221
2222}
2223
2224
2225void ViewCellsManager::PrintPvsStatistics(ostream &s)
2226{
2227  s<<"############# Viewcell PVS STAT ##################\n";
2228  PvsStatistics pvsStat;
2229  GetPvsStatistics(pvsStat);
2230  s<<"#AVG_PVS\n"<<pvsStat.avgPvs<<endl;
2231  s<<"#AVG_ENTRIES_PVS\n"<<pvsStat.avgPvsEntries<<endl;
2232  s<<"#RENDERCOST\n"<<pvsStat.renderCost<<endl;
2233  s<<"#AVG_FILTERED_PVS\n"<<pvsStat.avgFilteredPvs<<endl;
2234  s<<"#AVG_FILTERED_ENTRIES_PVS\n"<<pvsStat.avgFilteredPvsEntries<<endl;
2235  s<<"#AVG_FILTER_CONTRIBUTION\n"<<pvsStat.avgFilterContribution<<endl;
2236  s<<"#AVG_FILTER_RADIUS\n"<<pvsStat.avgFilterRadius<<endl;
2237  s<<"#AVG_FILTER_RATIO\n"<<pvsStat.avgFilterRatio<<endl;
2238  s<<"#MAX_PVS\n"<<pvsStat.maxPvs<<endl;
2239  s<<"#MIN_PVS\n"<<pvsStat.minPvs<<endl;
2240  s<<"#AVG_REL_PVS_INCREASE\n"<<pvsStat.avgRelPvsIncrease<<endl;
2241  s<<"#DEV_REL_PVS_INCREASE\n"<<pvsStat.devRelPvsIncrease<<endl;
2242  s<<"#MEMORY\n"<<pvsStat.mem<<endl;
2243  s<<"#RATIO\n"<<pvsStat.renderCost / (pvsStat.mem + Limits::Small)<<endl;
2244  s<<"#CONTRIBUTING_RAYS\n"<<mSamplesStat.mContributingRays<<endl;
2245 
2246  if (mSamplesStat.mRays) {
2247        s<<"#AVG_VIEWCELLS_PER_RAY\n"<<mSamplesStat.mViewCells/(float)mSamplesStat.mRays<<endl;
2248    s<<"#AVG_RAY_LENGTHS\n"<<mSamplesStat.mRayLengths << endl;
2249
2250  } else {
2251        s<<"#AVG_VIEWCELLS_PER_RAY\n 1 \n";
2252        s<<"#AVG_RAY_LENGTHS\n 1 \n";
2253  }
2254  mSamplesStat.Reset();
2255}
2256
2257
2258int ViewCellsManager::CastBeam(Beam &beam)
2259{
2260        return 0;
2261}
2262
2263
2264ViewCellContainer &ViewCellsManager::GetViewCells()
2265{
2266        return mViewCells;
2267}
2268
2269
2270void ViewCellsManager::SetViewSpaceBox(const AxisAlignedBox3 &box)
2271{
2272        mViewSpaceBox = box;
2273       
2274        // hack: create clip plane relative to new view space box
2275        CreateClipPlane();
2276        // the total area of the view space has changed
2277        mTotalAreaValid = false;
2278}
2279
2280
2281void ViewCellsManager::CreateClipPlane()
2282{
2283        int axis = 0;
2284        float pos;
2285        bool orientation;
2286        Vector3 absPos;
2287
2288        Environment::GetSingleton()->GetFloatValue("ViewCells.Visualization.clipPlanePos", pos);
2289        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.clipPlaneAxis", axis);
2290
2291        if (axis < 0)
2292        {
2293                axis = -axis;
2294                orientation = false;
2295                absPos = mViewSpaceBox.Max() -  mViewSpaceBox.Size() * pos;
2296        }
2297        else
2298        {
2299                orientation = true;
2300                absPos = mViewSpaceBox.Min() +  mViewSpaceBox.Size() * pos;
2301        }
2302
2303        mClipPlaneForViz = AxisAlignedPlane(axis, absPos[axis]);
2304        mClipPlaneForViz.mOrientation = orientation;
2305}
2306
2307
2308AxisAlignedBox3 ViewCellsManager::GetViewSpaceBox() const
2309{
2310        return mViewSpaceBox;
2311}
2312
2313
2314void ViewCellsManager::ResetViewCells()
2315{
2316        // recollect view cells
2317        mViewCells.clear();
2318        CollectViewCells();
2319       
2320        // stats are computed once more
2321        EvaluateViewCellsStats();
2322
2323        // has to be recomputed
2324        mTotalAreaValid = false;
2325}
2326
2327
2328int ViewCellsManager::GetMaxPvsSize() const
2329{
2330        return mMaxPvsSize;
2331}
2332
2333
2334int ViewCellsManager::GetMinPvsSize() const
2335{
2336        return mMinPvsSize;
2337}
2338
2339
2340
2341float ViewCellsManager::GetMaxPvsRatio() const
2342{
2343        return mMaxPvsRatio;
2344}
2345
2346
2347inline static void AddSampleToPvs(ObjectPvs &pvs,
2348                                                                  Intersectable *obj,
2349                                                                  const float pdf)
2350{
2351#if PVS_ADD_DIRTY
2352        pvs.AddSampleDirtyCheck(obj, pdf);
2353
2354        if (pvs.RequiresResort())
2355        {
2356                pvs.SimpleSort();
2357        }
2358#else
2359        pvs.AddSample(obj, pdf);
2360#endif
2361}
2362
2363
2364void ViewCellsManager::SortViewCellPvs()
2365{
2366        ViewCellContainer::iterator it, it_end = mViewCells.end();
2367       
2368        for (it = mViewCells.begin(); it != it_end; ++ it)
2369        {
2370                ObjectPvs &pvs = (*it)->GetPvs();
2371                if (pvs.RequiresResortLog())
2372                        pvs.SimpleSort();
2373        }
2374}
2375
2376
2377void ViewCellsManager::UpdateStatsForViewCell(ViewCell *vc, Intersectable *obj)
2378{
2379        KdIntersectable *kdObj = static_cast<KdIntersectable *>(obj);
2380
2381        const AxisAlignedBox3 box = kdObj->GetBox();
2382        const float dist = Distance(vc->GetBox().Center(), box.Center());
2383
2384        float f;
2385
2386        const float radius = box.Radius();
2387        const float fullRadius = max(0.2f * mViewSpaceBox.Radius(), radius);
2388
2389        const float minVal = 0.01f;
2390        const float maxVal = 1.0f;
2391
2392        if (dist <= radius)
2393                f = maxVal;
2394        else if (dist >= fullRadius)
2395                f = minVal;
2396        else // linear blending
2397        {
2398                f = minVal * (dist - radius) / (fullRadius - radius) +
2399                        maxVal * (fullRadius - radius - dist) / (fullRadius - radius);
2400        }
2401
2402        //cout << "x " << radius << " " << dist << " " << fullRadius << " " << f << " " << f * f << endl;
2403
2404        const int numTriangles = kdObj->ComputeNumTriangles();
2405
2406        vc->GetPvs().mStats.mDistanceWeightedTriangles += f * numTriangles;
2407        vc->GetPvs().mStats.mDistanceWeightedPvs += f ;
2408        vc->GetPvs().mStats.mWeightedTriangles += numTriangles;
2409}
2410
2411
2412bool ViewCellsManager::ComputeViewCellContribution(ViewCell *viewCell,
2413                                                                                                   VssRay &ray,
2414                                                                                                   Intersectable *obj,
2415                                                                                                   const Vector3 &pt,
2416                                                                                                   bool addSamplesToPvs)
2417{
2418        // check if we are outside of view space
2419        // $$JB tmp commented to speedup up computations
2420#if 0
2421        if (!obj || !viewCell->GetValid())
2422                return false;
2423#endif
2424
2425        // if ray not outside of view space
2426        float relContribution = 0.0f;
2427        float absContribution = 0.0f;
2428        bool hasAbsContribution;
2429
2430        // todo: maybe not correct for kd node pvs
2431        if (addSamplesToPvs)
2432        {
2433                //if (obj->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)cout << "here12 " << endl;
2434
2435                hasAbsContribution = viewCell->GetPvs().AddSampleDirtyCheck(obj, ray.mPdf);
2436                //hasAbsContribution = viewCell->GetPvs().AddSample(obj,ray.mPdf);
2437               
2438                if (hasAbsContribution)
2439                {
2440                        UpdateStatsForViewCell(viewCell, obj);
2441                }
2442        }
2443        else
2444        {
2445                hasAbsContribution =
2446                        viewCell->GetPvs().GetSampleContribution(obj, ray.mPdf, relContribution);
2447        }
2448
2449        // $$ clear the relative contribution as it is currently not correct anyway
2450        //  relContribution = 0.0f;
2451
2452        if (hasAbsContribution) 
2453        {
2454                ++ ray.mPvsContribution;
2455                absContribution = relContribution = 1.0f;
2456
2457                if (viewCell->GetPvs().RequiresResort())
2458                        viewCell->GetPvs().SimpleSort();
2459
2460#if CONTRIBUTION_RELATIVE_TO_PVS_SIZE
2461                relContribution /= viewcell->GetPvs().GetSize();
2462#endif
2463
2464#if DIST_WEIGHTED_CONTRIBUTION
2465                // recalculate the contribution - weight the 1.0f contribution by the sqr distance to the
2466                // object-> a new contribution in the proximity of the viewcell has a larger weight!
2467                relContribution /=
2468                        SqrDistance(GetViewCellBox(viewcell).Center(), ray.mTermination);
2469
2470#endif
2471        }
2472
2473#if SUM_RAY_CONTRIBUTIONS || AVG_RAY_CONTRIBUTIONS
2474        ray.mRelativePvsContribution += relContribution;
2475#else
2476        // recalculate relative contribution - use max of Rel Contribution
2477        if (ray.mRelativePvsContribution < relContribution)
2478                ray.mRelativePvsContribution = relContribution;
2479#endif
2480
2481        return hasAbsContribution;
2482}
2483
2484
2485int ViewCellsManager::GetNumViewCells() const
2486{
2487  return (int)mViewCells.size();
2488}
2489
2490
2491void
2492ViewCellsManager::DeterminePvsObjects(VssRayContainer &rays,
2493                                                                          bool useHitObjects)
2494{
2495        if (!useHitObjects)
2496        {
2497                // store higher order object (e.g., bvh node) instead of object itself
2498                VssRayContainer::const_iterator it, it_end = rays.end();
2499
2500                for (it = rays.begin(); it != it_end; ++ it)
2501                {
2502                        VssRay *vssRay = *it;
2503
2504                        // set only the termination object
2505                        vssRay->mTerminationObject = GetIntersectable(*vssRay, true);
2506                       
2507                        if (vssRay->mTerminationObject->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)     
2508                                cout << "r";
2509
2510#if 0
2511                  if (vssRay->mTerminationObject == NULL)
2512                          cerr<<"Error in DeterminePvsObjects - termination object maps to NULL!"<<endl;
2513#endif
2514                }
2515        }
2516}
2517
2518
2519float ViewCellsManager::ComputeSampleContribution(VssRay &ray,
2520                                                                                                  const bool addRays,
2521                                                                                                  ViewCell *currentViewCell,
2522                                                                                                  const bool useHitObjects)
2523{
2524        ray.mPvsContribution = 0;
2525        ray.mRelativePvsContribution = 0.0f;
2526
2527        if (!ray.mTerminationObject)
2528                return 0.0f;
2529
2530        // optain pvs entry (can be different from hit object)
2531        Intersectable *terminationObj;
2532
2533        terminationObj = ray.mTerminationObject;
2534        //cout << "rayd: " << ray.GetDir() << " ";
2535        ComputeViewCellContribution(currentViewCell,
2536                                                                ray,
2537                                                                terminationObj,
2538                                                                ray.mTermination,
2539                                                                addRays);
2540       
2541#if USE_RAY_LENGTH_AS_CONTRIBUTION
2542        float c = 0.0f;
2543        if (terminationObj)
2544                c = ray.Length();
2545
2546        ray.mRelativePvsContribution = ray.mPvsContribution = c;
2547        return c;
2548#else
2549        return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
2550          (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
2551#endif
2552}
2553
2554
2555float
2556ViewCellsManager::ComputeSampleContribution(VssRay &ray,
2557                                                                                        bool addRays,
2558                                                                                        bool storeViewCells,
2559                                                                                        bool useHitObjects)
2560{
2561        ray.mPvsContribution = 0;
2562        ray.mRelativePvsContribution = 0.0f;
2563
2564        ++ mSamplesStat.mRays;
2565
2566#if MYSTATS
2567        mSamplesStat.mRayLengths += ray.Length();
2568#endif
2569        if (!ray.mTerminationObject)
2570                return 0.0f;
2571
2572        static Ray hray;
2573        hray.Init(ray);
2574
2575        float tmin = 0, tmax = 1.0;
2576
2577        if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
2578        {
2579                // cerr<<"ray outside view space box\n";
2580                return 0;
2581        }
2582
2583        Vector3 origin = hray.Extrap(tmin);
2584        Vector3 termination = hray.Extrap(tmax);
2585
2586        ViewCell::NewMail();
2587
2588#ifdef USE_PERFTIMER 
2589        viewCellCastTimer.Entry();
2590#endif
2591        static ViewCellContainer viewCells;
2592        static VssRay *lastVssRay = NULL;
2593
2594        // check if last ray was not same ray with reverse direction
2595        if (1)
2596                // tmp matt: don't use when origin objects are not accounted for, currently the second ray is lost!!
2597                //!lastVssRay ||
2598                //!(ray.mOrigin == lastVssRay->mTermination) ||
2599                //!(ray.mTermination == lastVssRay->mOrigin))
2600        {
2601                viewCells.clear();
2602
2603                // traverse the view space subdivision
2604                CastLineSegment(origin, termination, viewCells);
2605                lastVssRay = &ray;
2606        }
2607
2608#ifdef USE_PERFTIMER 
2609        viewCellCastTimer.Exit();
2610#endif
2611
2612        mSamplesStat.mViewCells += (int)viewCells.size();
2613
2614        if (storeViewCells)
2615        {       
2616                // cerr << "Store viewcells should not be used in the test!" << endl;
2617                // copy viewcells memory efficiently
2618#if VSS_STORE_VIEWCELLS
2619                ray.mViewCells.reserve(viewCells.size());
2620                ray.mViewCells = viewCells;
2621#else
2622                cerr << "Vss store viewcells not supported." << endl;
2623                exit(1);
2624#endif
2625        }
2626
2627        Intersectable *terminationObj;
2628
2629#ifdef USE_PERFTIMER 
2630        objTimer.Entry();
2631#endif
2632        // obtain pvs entry (can be different from hit object)
2633        terminationObj = ray.mTerminationObject;
2634
2635#ifdef USE_PERFTIMER 
2636        objTimer.Exit();
2637
2638        pvsTimer.Entry();
2639#endif
2640        //if (terminationObj->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
2641        //      cout << "found tmi: " << Intersectable::GetTypeName(terminationObj) << " " << viewCells.size() << endl;
2642        bool contri = false;
2643        ViewCellContainer::const_iterator it = viewCells.begin();
2644//cout << "rayd: " << ray.GetDir() << " ";
2645        for (; it != viewCells.end(); ++ it)
2646        {
2647                if (ComputeViewCellContribution(*it,
2648                                                    ray,
2649                                                                                terminationObj,
2650                                                                                ray.mTermination,
2651                                                                                addRays))
2652                {
2653                        contri = true;
2654                }       
2655
2656                (*it)->IncNumPiercingRays();
2657               
2658        }
2659
2660#if MYSTATS
2661        if (contri)
2662        {
2663                if (rand() < (RAND_MAX / 10))
2664                  //                    cout << "rayd: " /*<< ray.GetOrigin() << " " << ray.GetTermination() << " "*/ << Normalize(ray.GetDir()) << " " << endl;
2665                mVizBuffer.AddRay(&ray);
2666        }
2667#endif
2668#ifdef USE_PERFTIMER 
2669        pvsTimer.Exit();
2670#endif
2671       
2672        mSamplesStat.mPvsContributions += ray.mPvsContribution;
2673        if (ray.mPvsContribution)
2674                ++ mSamplesStat.mContributingRays;
2675
2676#if AVG_RAY_CONTRIBUTIONS
2677        ray.mRelativePvsContribution /= (float)viewCells.size();
2678#endif
2679
2680#if USE_RAY_LENGTH_AS_CONTRIBUTION
2681        float c = 0.0f;
2682        if (terminationObj)
2683                c = ray.Length();
2684        ray.mRelativePvsContribution = ray.mPvsContribution = c;
2685        return c;
2686#else
2687        return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
2688                (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
2689#endif
2690}
2691
2692
2693void ViewCellsManager::GetRaySets(const VssRayContainer &sourceRays,
2694                                                                  const int maxSize,
2695                                                                  VssRayContainer &usedRays,
2696                                                                  VssRayContainer *savedRays) const
2697{
2698        const int limit = min(maxSize, (int)sourceRays.size());
2699        const float prop = (float)limit / ((float)sourceRays.size() + Limits::Small);
2700
2701        VssRayContainer::const_iterator it, it_end = sourceRays.end();
2702        for (it = sourceRays.begin(); it != it_end; ++ it)
2703        {
2704                if (Random(1.0f) < prop)
2705                        usedRays.push_back(*it);
2706                else if (savedRays)
2707                        savedRays->push_back(*it);
2708        }
2709}
2710
2711
2712float ViewCellsManager::GetRendercost(ViewCell *viewCell) const
2713{
2714        return (float)mViewCellsTree->GetTrianglesInPvs(viewCell);
2715}
2716
2717
2718float ViewCellsManager::GetAccVcArea()
2719{
2720        // if already computed
2721        if (mTotalAreaValid)
2722        {
2723                return mTotalArea;
2724        }
2725
2726        mTotalArea = 0;
2727        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2728
2729        for (it = mViewCells.begin(); it != it_end; ++ it)
2730        {
2731                //Debug << "area: " << GetArea(*it);
2732        mTotalArea += GetArea(*it);
2733        }
2734
2735        mTotalAreaValid = true;
2736
2737        return mTotalArea;
2738}
2739
2740
2741void ViewCellsManager::PrintStatistics(ostream &s) const
2742{
2743        s << mCurrentViewCellsStats << endl;
2744}
2745
2746
2747void ViewCellsManager::CreateUniqueViewCellIds()
2748{
2749        if (ViewCellsTreeConstructed())
2750        {
2751                mViewCellsTree->CreateUniqueViewCellsIds();
2752        }
2753        else // no view cells tree, handle view cells "myself"
2754        {
2755                int i = 0;
2756                ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
2757                for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
2758                {
2759                        if ((*vit)->GetId() != OUT_OF_BOUNDS_ID)
2760                        {
2761                                mViewCells[i]->SetId(i ++);
2762                        }
2763                }
2764        }
2765}
2766
2767
2768void ViewCellsManager::ExportViewCellsForViz(Exporter *exporter,
2769                                                                                         const AxisAlignedBox3 *sceneBox,
2770                                                                                         const bool colorCode,
2771                                                                                         const AxisAlignedPlane *clipPlane
2772                                                                                         ) const
2773{
2774        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2775
2776        for (it = mViewCells.begin(); it != it_end; ++ it)
2777        {
2778                if (!mOnlyValidViewCells || (*it)->GetValid())
2779                {
2780                        ExportColor(exporter, *it, colorCode); 
2781                        ExportViewCellGeometry(exporter, *it, sceneBox, clipPlane);
2782                }
2783        }
2784}
2785
2786
2787void ViewCellsManager::CreateViewCellMeshes()
2788{
2789        // convert to meshes
2790        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2791
2792        for (it = mViewCells.begin(); it != it_end; ++ it)
2793        {
2794                if (!(*it)->GetMesh())
2795                {
2796                        CreateMesh(*it);
2797                }
2798        }
2799}
2800
2801
2802bool ViewCellsManager::ExportViewCells(const string filename,
2803                                                                           const bool exportPvs,
2804                                                                           const ObjectContainer &objects)
2805{
2806        return false;
2807}
2808
2809
2810void ViewCellsManager::CollectViewCells(const int n)
2811{
2812        mNumActiveViewCells = n;
2813        mViewCells.clear();
2814        // implemented in subclasses
2815        CollectViewCells();
2816}
2817
2818
2819void ViewCellsManager::SetViewCellActive(ViewCell *vc) const
2820{
2821        ViewCellContainer leaves;
2822        // sets the pointers to the currently active view cells
2823        mViewCellsTree->CollectLeaves(vc, leaves);
2824
2825        ViewCellContainer::const_iterator lit, lit_end = leaves.end();
2826        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2827        {
2828                static_cast<ViewCellLeaf *>(*lit)->SetActiveViewCell(vc);
2829        }
2830}
2831
2832
2833void ViewCellsManager::SetViewCellsActive()
2834{
2835        // collect leaf view cells and set the pointers to
2836        // the currently active view cells
2837        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2838
2839        for (it = mViewCells.begin(); it != it_end; ++ it)
2840        {
2841                SetViewCellActive(*it);
2842        }
2843}
2844
2845
2846int ViewCellsManager::GetMaxFilterSize() const
2847{
2848        return mMaxFilterSize; 
2849}
2850
2851
2852static const bool USE_ASCII = true;
2853
2854
2855bool ViewCellsManager::ExportBoundingBoxes(const string filename,
2856                                                                                   const ObjectContainer &objects) const
2857{
2858        ObjectContainer::const_iterator it, it_end = objects.end();
2859       
2860        if (USE_ASCII)
2861        {
2862                ofstream boxesOut(filename.c_str());
2863                if (!boxesOut.is_open())
2864                        return false;
2865
2866                for (it = objects.begin(); it != it_end; ++ it)
2867                {
2868                        MeshInstance *mi = static_cast<MeshInstance *>(*it);
2869                        const AxisAlignedBox3 box = mi->GetBox();
2870
2871                        boxesOut << mi->GetId() << " "
2872                                         << box.Min().x << " "
2873                                         << box.Min().y << " "
2874                                         << box.Min().z << " "
2875                                         << box.Max().x << " "
2876                                         << box.Max().y << " "
2877                     << box.Max().z << endl;   
2878                }
2879
2880                boxesOut.close();
2881        }
2882        else
2883        {
2884                ofstream boxesOut(filename.c_str(), ios::binary);
2885
2886                if (!boxesOut.is_open())
2887                        return false;
2888
2889                for (it = objects.begin(); it != it_end; ++ it)
2890                {       
2891                        MeshInstance *mi = static_cast<MeshInstance *>(*it);
2892                        const AxisAlignedBox3 box = mi->GetBox();
2893                       
2894                        Vector3 bmin = box.Min();
2895                        Vector3 bmax = box.Max();
2896                       
2897                        int id = mi->GetId();
2898
2899                        boxesOut.write(reinterpret_cast<char *>(&id), sizeof(int));
2900                        boxesOut.write(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
2901                        boxesOut.write(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
2902                }
2903               
2904                boxesOut.close();
2905        }
2906
2907        return true;
2908}
2909
2910
2911bool ViewCellsManager::LoadBoundingBoxes(const string filename,
2912                                                                                 IndexedBoundingBoxContainer &boxes) const
2913{
2914        Vector3 bmin, bmax;
2915        int id;
2916
2917        if (USE_ASCII)
2918        {
2919                ifstream boxesIn(filename.c_str());
2920               
2921                if (!boxesIn.is_open())
2922                {
2923                        cout << "failed to open file " << filename << endl;
2924                        return false;
2925                }
2926
2927                string buf;
2928                while (!(getline(boxesIn, buf)).eof())
2929                {
2930                        sscanf(buf.c_str(), "%d %f %f %f %f %f %f",
2931                                   &id, &bmin.x, &bmin.y, &bmin.z,
2932                                   &bmax.x, &bmax.y, &bmax.z);
2933               
2934                        AxisAlignedBox3 box(bmin, bmax);
2935                        //      MeshInstance *mi = new MeshInstance();
2936                        // HACK: set bounding box to new box
2937                        //mi->mBox = box;
2938
2939                        boxes.push_back(IndexedBoundingBox(id, box));
2940                }
2941
2942                boxesIn.close();
2943        }
2944        else
2945        {
2946                ifstream boxesIn(filename.c_str(), ios::binary);
2947
2948                if (!boxesIn.is_open())
2949                        return false;
2950
2951                while (1)
2952                {
2953                        boxesIn.read(reinterpret_cast<char *>(&id), sizeof(Vector3));
2954                        boxesIn.read(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
2955                        boxesIn.read(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
2956                       
2957                        if (boxesIn.eof())
2958                                break;
2959                       
2960                        AxisAlignedBox3 box(bmin, bmax);
2961                        MeshInstance *mi = new MeshInstance(NULL);
2962
2963                        boxes.push_back(IndexedBoundingBox(id, box));
2964                }
2965
2966                boxesIn.close();
2967        }
2968
2969        return true;
2970}
2971
2972
2973float ViewCellsManager::GetFilterWidth()
2974{
2975        return mFilterWidth;
2976}
2977
2978
2979float ViewCellsManager::GetAbsFilterWidth()
2980{
2981        return Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
2982}
2983
2984
2985void ViewCellsManager::UpdateScalarPvsSize(ViewCell *vc,
2986                                                                                   const float pvsCost,
2987                                                                                   const int entriesInPvs) const
2988{
2989        vc->mPvsCost = pvsCost;
2990        vc->mEntriesInPvs = entriesInPvs;
2991
2992        vc->mPvsSizeValid = true;
2993}
2994
2995
2996void ViewCellsManager::UpdateScalarPvsCost(ViewCell *vc, const float pvsCost) const
2997{
2998        vc->mPvsCost = pvsCost;
2999}
3000
3001
3002void
3003ViewCellsManager::ApplyFilter(ViewCell *viewCell,
3004                                                          KdTree *kdTree,
3005                                                          const float viewSpaceFilterSize,
3006                                                          const float spatialFilterSize,
3007                                                          ObjectPvs &pvs
3008                                                          )
3009{
3010  // extend the pvs of the viewcell by pvs of its neighbors
3011  // and apply spatial filter by including all neighbors of the objects
3012  // in the pvs
3013
3014  // get all viewcells intersecting the viewSpaceFilterBox
3015  // and compute the pvs union
3016 
3017  //Vector3 center = viewCell->GetBox().Center();
3018  //  Vector3 center = m->mBox.Center();
3019
3020        //  AxisAlignedBox3 box(center - Vector3(viewSpaceFilterSize/2),
3021        //                                        center + Vector3(viewSpaceFilterSize/2));
3022        if (!ViewCellsConstructed())
3023                return;
3024
3025        if (viewSpaceFilterSize >= 0.0f)
3026        {
3027                const bool usePrVS = false;
3028
3029                if (!usePrVS)
3030                {
3031                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
3032                        box.Enlarge(Vector3(viewSpaceFilterSize/2));
3033
3034                        ViewCellContainer viewCells;
3035                        ComputeBoxIntersections(box, viewCells);
3036
3037                        //  cout<<"box="<<box<<endl;
3038                        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();
3039
3040                        for (; it != it_end; ++ it)
3041                        {
3042                                ObjectPvs interPvs;
3043                                //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
3044                                ObjectPvs::Merge(interPvs, pvs, (*it)->GetPvs());
3045
3046                                pvs = interPvs;
3047                        }
3048                }
3049                else
3050                {
3051                        PrVs prvs;
3052                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
3053
3054                        //  mViewCellsManager->SetMaxFilterSize(1);
3055                        GetPrVS(box.Center(), prvs, viewSpaceFilterSize);
3056                        pvs = prvs.mViewCell->GetPvs();
3057                        DeleteLocalMergeTree(prvs.mViewCell);
3058                }
3059        }
3060        else
3061        {
3062                pvs = viewCell->GetPvs();
3063        }
3064
3065        if (spatialFilterSize >=0.0f)
3066                ApplySpatialFilter(kdTree, spatialFilterSize, pvs);
3067
3068}
3069
3070
3071
3072void
3073ViewCellsManager::ApplyFilter(KdTree *kdTree,
3074                                                          const float relViewSpaceFilterSize,
3075                                                          const float relSpatialFilterSize
3076                                                          )
3077{
3078
3079        if (!ViewCellsConstructed())
3080                return;
3081
3082        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
3083
3084        ObjectPvs *newPvs;
3085        newPvs = new ObjectPvs[mViewCells.size()];
3086
3087        float viewSpaceFilterSize = Magnitude(mViewSpaceBox.Size())*relViewSpaceFilterSize;
3088        float spatialFilterSize = Magnitude(kdTree->GetBox().Size())*relSpatialFilterSize;
3089       
3090        int i;
3091        for (i=0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
3092          ApplyFilter(*it,
3093                                  kdTree,
3094                                  viewSpaceFilterSize,
3095                                  spatialFilterSize,
3096                                  newPvs[i]
3097                                  );
3098        }
3099       
3100        // now replace all pvss
3101        for (i = 0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
3102         
3103          ObjectPvs &pvs = (*it)->GetPvs();
3104          pvs.Clear();
3105          pvs = newPvs[i];
3106          newPvs[i].Clear();
3107        }
3108
3109        delete [] newPvs;
3110}
3111
3112
3113void
3114ViewCellsManager::ApplySpatialFilter(
3115                                                                         KdTree *kdTree,
3116                                                                         const float spatialFilterSize,
3117                                                                         ObjectPvs &pvs
3118                                                                         )
3119{
3120        // now compute a new Pvs by including also objects intersecting the
3121        // extended boxes of visible objects
3122        Intersectable::NewMail();
3123
3124        ObjectPvsIterator pit = pvs.GetIterator();
3125
3126        while (pit.HasMoreEntries())
3127                pit.Next()->Mail();
3128
3129        ObjectPvs nPvs;
3130        int nPvsSize = 0;
3131
3132        ObjectPvsIterator pit2 = pvs.GetIterator();
3133
3134        while (pit2.HasMoreEntries())
3135        {               
3136                // now go through the pvs again
3137                Intersectable *object = pit2.Next();
3138
3139                //      Vector3 center = object->GetBox().Center();
3140                //      AxisAlignedBox3 box(center - Vector3(spatialFilterSize/2),
3141                //                                              center + Vector3(spatialFilterSize/2));
3142
3143                AxisAlignedBox3 box = object->GetBox();
3144                box.Enlarge(Vector3(spatialFilterSize/2));
3145
3146                ObjectContainer objects;
3147
3148                // $$ warning collect objects takes only unmailed ones!
3149                kdTree->CollectObjects(box, objects);
3150                //      cout<<"collected objects="<<objects.size()<<endl;
3151                ObjectContainer::const_iterator noi = objects.begin();
3152                for (; noi != objects.end(); ++ noi)
3153                {
3154                        Intersectable *o = *noi;
3155                        cout<<"w";
3156                        // $$ JB warning: pdfs are not correct at this point!     
3157                        nPvs.AddSample(o, Limits::Small);
3158                        nPvsSize ++;
3159                }
3160        }
3161
3162        // cout<<"nPvs size = "<<nPvsSize<<endl;
3163        pvs.MergeInPlace(nPvs);
3164}
3165
3166
3167void ViewCellsManager::MergeViewCellsRecursivly(ObjectPvs &pvs,
3168                                                                                                const ViewCellContainer &viewCells) const
3169{
3170        MergeViewCellsRecursivly(pvs, viewCells, 0, (int)viewCells.size() - 1);
3171}
3172
3173
3174void ViewCellsManager::MergeViewCellsRecursivly(ObjectPvs &pvs,
3175                                                                                                const ViewCellContainer &viewCells,
3176                                                                                                int leftIdx,
3177                                                                                                int rightIdx) const
3178{
3179        if (leftIdx == rightIdx)
3180        {
3181                pvs = viewCells[leftIdx]->GetPvs();
3182        }
3183        else
3184        {
3185                const int midSplit = (leftIdx + rightIdx) / 2;
3186       
3187                ObjectPvs leftPvs, rightPvs;
3188                MergeViewCellsRecursivly(leftPvs, viewCells, leftIdx, midSplit);
3189                MergeViewCellsRecursivly(rightPvs, viewCells, midSplit, rightIdx);
3190
3191        ObjectPvs::Merge(pvs, leftPvs, rightPvs);
3192        }
3193}
3194
3195
3196PvsFilterStatistics
3197ViewCellsManager::ApplyFilter2(ViewCell *viewCell,
3198                                                           const bool useViewSpaceFilter,
3199                                                           const float filterSize,
3200                                                           ObjectPvs &pvs,
3201                                                           vector<AxisAlignedBox3> *filteredBoxes,
3202                                                           const bool onlyNewObjects
3203                                                           )
3204{
3205        pvs.Reserve(viewCell->GetFilteredPvsSize());
3206
3207        PvsFilterStatistics stats;
3208
3209        AxisAlignedBox3 vbox = GetViewCellBox(viewCell);
3210        const Vector3 center = vbox.Center();
3211       
3212        // copy the PVS
3213        if (!mUseKdPvs)
3214                Intersectable::NewMail();
3215        else
3216                KdNode::NewMail();
3217
3218        ObjectPvs basePvs = viewCell->GetPvs();
3219        ObjectPvsIterator pit = basePvs.GetIterator();
3220
3221        if (!mUseKdPvs)
3222        {
3223          // first mark all objects from this pvs
3224          while (pit.HasMoreEntries()) 
3225                pit.Next()->Mail();
3226        }
3227       
3228        int pvsSize = 0;
3229        int nPvsSize = 0;
3230       
3231        //Debug<<"f #s="<<samples<<"  pvs size = "<<basePvs.GetSize();
3232        //  cout<<"Filter size = "<<filterSize<<endl;
3233        //  cout<<"vbox = "<<vbox<<endl;
3234        //  cout<<"center = "<<center<<endl;
3235
3236
3237        // Minimal number of local samples to take into account
3238        // the local sampling density.
3239        // The size of the filter is a minimum of the conservative
3240        // local sampling density estimate (#rays intersecting teh viewcell and
3241        // the object)
3242        // and gobal estimate for the view cell
3243        // (total #rays intersecting the viewcell)
3244        const int minLocalSamples = 2;
3245        const float viewCellRadius = 0.5f * Magnitude(vbox.Diagonal());
3246
3247        float samples = (float)basePvs.GetSamples();
3248
3249
3250        //////////
3251        //-- now compute the filter box around the current viewCell
3252
3253        if (useViewSpaceFilter)
3254        {
3255                // float radius = Max(viewCellRadius/100.0f, avgRadius - viewCellRadius);
3256                float radius = viewCellRadius / 100.0f;
3257                vbox.Enlarge(radius);
3258                cout<<"vbox = "<<vbox<<endl;
3259
3260                ViewCellContainer viewCells;
3261                ComputeBoxIntersections(vbox, viewCells);
3262
3263                ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();
3264
3265                for (int i = 0; it != it_end; ++ it, ++ i)
3266                {
3267                  if ((*it) != viewCell)
3268                        {
3269                          //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
3270                          basePvs.MergeInPlace((*it)->GetPvs());
3271                        }
3272                 
3273                  // update samples and globalC
3274                  samples = (float)pvs.GetSamples();
3275                  //    cout<<"neighboring viewcells = "<<i-1<<endl;
3276                  //    cout<<"Samples' = "<<samples<<endl;
3277                }
3278        }
3279
3280        // Minimal number of samples so that filtering takes place
3281        const float MIN_SAMPLES = 50;
3282
3283        if (samples > MIN_SAMPLES)
3284        {
3285                float globalC = 2.0f * filterSize / sqrt(samples);
3286
3287                ObjectContainer objects;
3288                PvsData pvsData;
3289
3290                pit = basePvs.GetIterator();
3291               
3292                if (onlyNewObjects) {
3293                  while (pit.HasMoreEntries()) {
3294                        // mail all objects from the original not to include them in the
3295                        // resulting pvs
3296                        Intersectable *obj = pit.Next(pvsData);
3297                        obj->Mail();
3298                  }
3299                  pit = basePvs.GetIterator();
3300                }
3301               
3302                while (pit.HasMoreEntries())
3303                {               
3304                        Intersectable *object = pit.Next(pvsData);
3305
3306                        // compute filter size based on the distance and the numebr of samples
3307                        AxisAlignedBox3 box = object->GetBox();
3308
3309                        float distance = Distance(center, box.Center());
3310                        float globalRadius = distance*globalC;
3311
3312                        int objectSamples = (int)pvsData.mSumPdf;
3313                        float localRadius = MAX_FLOAT;
3314
3315                        localRadius = filterSize*0.5f*Magnitude(box.Diagonal())/
3316                                sqrt((float)objectSamples);
3317
3318                        // cout<<"os="<<objectSamples<<" lr="<<localRadius<<" gr="<<globalRadius<<endl;
3319
3320                        // now compute the filter size
3321                        float radius;
3322
3323#if 0
3324                        if (objectSamples <= 1)
3325                        {
3326                                if (localRadius > globalRadius)
3327                                {
3328                                        radius = 0.5flRadius;
3329                                        stats.mLocalFilterCount++;
3330                                }
3331                                else
3332                                {
3333                                        radius = globalRadius;
3334                                        stats.mGlobalFilterCount++;
3335                                }
3336                        }
3337                        else
3338                        {
3339                                radius = localRadius;
3340                                stats.mLocalFilterCount++;
3341                        }
3342#else
3343
3344                        // radius = 0.5f*globalRadius + 0.5f*localRadius;
3345                        radius = Min(globalRadius, localRadius);
3346
3347                        if (localRadius > globalRadius)
3348                                ++ stats.mLocalFilterCount;
3349                        else
3350                                ++ stats.mGlobalFilterCount;
3351#endif
3352
3353                        stats.mAvgFilterRadius += radius;
3354
3355                        // cout<<"box = "<<box<<endl;
3356                        //      cout<<"distance = "<<distance<<endl;
3357                        //      cout<<"radiues = "<<radius<<endl;
3358
3359                        box.Enlarge(Vector3(radius));
3360
3361                        if (filteredBoxes)
3362                          filteredBoxes->push_back(box);
3363                       
3364                        objects.clear();
3365
3366                        // $$ warning collect objects takes only unmailed ones!
3367                        if (mUseKdPvs) {
3368                                                  GetPreprocessor()->mKdTree->CollectKdObjects(box, objects);
3369                          //GetPreprocessor()->mKdTree->CollectSmallKdObjects(box, objects, 0.1f);
3370
3371                        } else
3372                          CollectObjects(box, objects);
3373                       
3374                        //      cout<<"collected objects="<<objects.size()<<endl;
3375                        ObjectContainer::const_iterator noi = objects.begin();
3376                        for (; noi != objects.end(); ++ noi)
3377                          {
3378                                Intersectable *o = *noi;
3379                               
3380                                // $$ JB warning: pdfs are not correct at this point!     
3381                                pvs.AddSampleDirty(o, Limits::Small);
3382                        }
3383                }
3384               
3385                stats.mAvgFilterRadius /= (stats.mLocalFilterCount + stats.mGlobalFilterCount);
3386        }
3387       
3388        //Debug << " nPvs size = " << pvs.GetSize() << endl;
3389
3390        if (!mUseKdPvs && !onlyNewObjects)
3391        {
3392                PvsData pvsData;
3393
3394                // copy the base pvs to the new pvs
3395                pit = basePvs.GetIterator();
3396                while (pit.HasMoreEntries())
3397                {               
3398                        Intersectable *obj = pit.Next(pvsData);
3399                        pvs.AddSampleDirty(obj, pvsData.mSumPdf);
3400                }
3401        }
3402
3403        pvs.SimpleSort();
3404        viewCell->SetFilteredPvsSize(pvs.GetSize());
3405
3406        // warning: not thread-safe!
3407        if (!mUseKdPvs)
3408                Intersectable::NewMail();
3409
3410        return stats;
3411}
3412
3413
3414
3415void ViewCellsManager::ExportColor(Exporter *exporter,
3416                                                                   ViewCell *vc,
3417                                                                   int colorCode) const
3418{
3419        const bool vcValid = CheckValidity(vc, mMinPvsSize, mMaxPvsSize);
3420
3421        float importance = 0;
3422        static Material m;
3423        //cout << "color code: " << colorCode << endl;
3424               
3425        switch (colorCode)
3426        {
3427        case 0: // Random
3428                {
3429                        if (vcValid)
3430                        {
3431                                m.mDiffuseColor.r = 0.2f + RandomValue(0.0f, 0.8f);
3432                                m.mDiffuseColor.g = 0.2f + RandomValue(0.0f, 0.8f);
3433                                m.mDiffuseColor.b = 0.2f + RandomValue(0.0f, 0.8f);
3434                        }
3435                        else
3436                        {
3437                                m.mDiffuseColor.r = 0.0f;
3438                                m.mDiffuseColor.g = 1.0f;
3439                                m.mDiffuseColor.b = 0.0f;
3440                        }
3441
3442                        exporter->SetForcedMaterial(m);
3443                        return;
3444                }
3445               
3446        case 1: // pvs
3447                {
3448                        if (mCurrentViewCellsStats.maxPvs)
3449                        {
3450                                importance = //(float)mViewCellsTree->GetTrianglesInPvs(vc) / 700;
3451                                                         (float)mCurrentViewCellsStats.maxPvs;
3452                        }
3453                }
3454                break;
3455        case 2: // merges
3456                {
3457            const int lSize = mViewCellsTree->GetNumInitialViewCells(vc);
3458                        importance = (float)lSize / (float)mCurrentViewCellsStats.maxLeaves;
3459                }
3460                break;
3461        default:
3462                break;
3463        }
3464
3465        // special color code for invalid view cells
3466        m.mDiffuseColor.r = importance;
3467        m.mDiffuseColor.b = 1.0f;//vcValid ? 0.0f : 1.0f;
3468        m.mDiffuseColor.g = 1.0f - importance;
3469
3470        //Debug << "importance: " << importance << endl;
3471        exporter->SetForcedMaterial(m);
3472}
3473
3474
3475void ViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3476                                                                                          vector<MergeCandidate> &candidates)
3477{
3478        // implemented in subclasses
3479}
3480
3481
3482void ViewCellsManager::UpdatePvsForEvaluation()
3483{
3484        ObjectPvs objPvs;
3485        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), objPvs);
3486}
3487
3488
3489void ViewCellsManager::UpdatePvsForEvaluation(ViewCell *root, ObjectPvs &pvs)
3490{
3491        // terminate traversal
3492        if (root->IsLeaf())
3493        {
3494                // we assume that pvs is explicitly stored in leaves
3495                pvs = root->GetPvs();
3496                UpdateScalarPvsSize(root, pvs.EvalPvsCost(), pvs.GetSize());
3497
3498                return;
3499        }
3500
3501        ////////////////
3502        //-- interior node => propagate pvs up the tree
3503
3504        ViewCellInterior *interior = static_cast<ViewCellInterior *>(root);
3505
3506        // reset interior pvs
3507        interior->GetPvs().Clear();
3508
3509        // reset recursive pvs
3510        pvs.Clear();
3511
3512        // pvss of child nodes
3513        vector<ObjectPvs> pvsList;
3514        pvsList.resize((int)interior->mChildren.size());
3515
3516        ViewCellContainer::const_iterator vit, vit_end = interior->mChildren.end();
3517       
3518        int i = 0;
3519
3520        ////////
3521        //-- recursivly compute child pvss
3522
3523        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ i)
3524        {
3525                UpdatePvsForEvaluation(*vit, pvsList[i]);
3526        }
3527
3528#if 1
3529        Intersectable::NewMail();
3530
3531
3532        ///////////
3533        //-- merge pvss
3534
3535        PvsData pvsData;
3536
3537        vector<ObjectPvs>::iterator oit = pvsList.begin();
3538
3539        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ oit)
3540        {
3541                ObjectPvsIterator pit = (*oit).GetIterator();
3542               
3543                // add pvss to new pvs: use mailing to avoid adding entries two times.
3544                while (pit.HasMoreEntries())
3545                {               
3546                        Intersectable *intersect = pit.Next(pvsData);
3547
3548                        if (!intersect->Mailed())
3549                        {
3550                                intersect->Mail();
3551                                pvs.AddSampleDirty(intersect, pvsData.mSumPdf);
3552                        }
3553                }
3554        }
3555
3556        // store pvs in this node
3557        if (mViewCellsTree->ViewCellsStorage() == ViewCellsTree::PVS_IN_INTERIORS)
3558        {
3559                interior->SetPvs(pvs);
3560        }
3561       
3562        // set new pvs size
3563        UpdateScalarPvsSize(interior, pvs.EvalPvsCost(), pvs.GetSize());
3564       
3565#else
3566        // really merge cells: slow but sumPdf is correct
3567        viewCellInterior->GetPvs().Merge(backVc->GetPvs());
3568        viewCellInterior->GetPvs().Merge(frontVc->GetPvs());
3569#endif
3570}
3571
3572
3573
3574/*******************************************************************/
3575/*               BspViewCellsManager implementation                */
3576/*******************************************************************/
3577
3578
3579BspViewCellsManager::BspViewCellsManager(ViewCellsTree *vcTree, BspTree *bspTree):
3580ViewCellsManager(vcTree), mBspTree(bspTree)
3581{
3582        Environment::GetSingleton()->GetIntValue("BspTree.Construction.samples", mInitialSamples);
3583
3584        mBspTree->SetViewCellsManager(this);
3585        mBspTree->SetViewCellsTree(mViewCellsTree);
3586}
3587
3588
3589bool BspViewCellsManager::ViewCellsConstructed() const
3590{
3591        return mBspTree->GetRoot() != NULL;
3592}
3593
3594
3595ViewCell *BspViewCellsManager::GenerateViewCell(Mesh *mesh) const
3596{
3597        return new BspViewCell(mesh);
3598}
3599
3600
3601int BspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
3602                                                                                          const VssRayContainer &rays)
3603{
3604        // if view cells were already constructed, we can finish
3605        if (ViewCellsConstructed())
3606                return 0;
3607
3608        int sampleContributions = 0;
3609
3610        // construct view cells using the collected samples
3611        RayContainer constructionRays;
3612        VssRayContainer savedRays;
3613
3614        // choose a a number of rays based on the ratio of cast rays / requested rays
3615        const int limit = min(mInitialSamples, (int)rays.size());
3616        VssRayContainer::const_iterator it, it_end = rays.end();
3617
3618        const float prop = (float)limit / ((float)rays.size() + Limits::Small);
3619
3620        for (it = rays.begin(); it != it_end; ++ it)
3621        {
3622                if (Random(1.0f) < prop)
3623                        constructionRays.push_back(new Ray(*(*it)));
3624                else
3625                        savedRays.push_back(*it);
3626        }
3627
3628    if (!mUsePredefinedViewCells)
3629        {
3630                // no view cells loaded
3631                mBspTree->Construct(objects, constructionRays, &mViewSpaceBox);
3632                // collect final view cells
3633                mBspTree->CollectViewCells(mViewCells);
3634        }
3635        else
3636        {       
3637                // use predefined view cells geometry =>
3638                // contruct bsp hierarchy over them
3639                mBspTree->Construct(mViewCells);
3640        }
3641
3642        // destroy rays created only for construction
3643        CLEAR_CONTAINER(constructionRays);
3644
3645        Debug << mBspTree->GetStatistics() << endl;
3646        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
3647
3648        // recast rest of the rays
3649        if (SAMPLE_AFTER_SUBDIVISION)
3650                ComputeSampleContributions(savedRays, true, false);
3651
3652        // real meshes are contructed at this stage
3653        if (0)
3654        {
3655                cout << "finalizing view cells ... ";
3656                FinalizeViewCells(true);
3657                cout << "finished" << endl;     
3658        }
3659
3660        return sampleContributions;
3661}
3662
3663
3664void BspViewCellsManager::CollectViewCells()
3665{       
3666        if (!ViewCellsTreeConstructed())
3667        {       // view cells tree constructed 
3668                mBspTree->CollectViewCells(mViewCells);
3669        }
3670        else
3671        {       // we can use the view cells tree hierarchy to get the right set
3672                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
3673        }
3674}
3675
3676
3677float BspViewCellsManager::GetProbability(ViewCell *viewCell)
3678{
3679        if (1)
3680                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
3681        else
3682                // compute view cell area as subsititute for probability
3683                return GetArea(viewCell) / GetAccVcArea();
3684}
3685
3686
3687
3688int BspViewCellsManager::CastLineSegment(const Vector3 &origin,
3689                                                                                 const Vector3 &termination,
3690                                                                                 ViewCellContainer &viewcells)
3691{
3692        return mBspTree->CastLineSegment(origin, termination, viewcells);
3693}
3694
3695
3696bool BspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
3697                                                                                                const Vector3 &termination,
3698                                                                                                ViewCell *viewCell)
3699{
3700        return false;
3701}
3702
3703
3704void ViewCellsManager::ExportMergedViewCells(const ObjectContainer &objects)
3705{
3706        // save color code
3707        const int savedColorCode = mColorCode;
3708
3709        Exporter *exporter;
3710
3711        // export merged view cells using pvs color coding
3712        exporter = Exporter::GetExporter("merged_view_cells_pvs.wrl");
3713        cout << "exporting view cells after merge (pvs size) ... ";     
3714
3715        if (exporter)
3716        {
3717                if (mExportGeometry)
3718                {
3719                        exporter->ExportGeometry(objects);
3720                }
3721
3722                exporter->SetFilled();
3723                mColorCode = 1;
3724
3725                ExportViewCellsForViz(exporter, NULL,  mColorCode, GetClipPlane());
3726
3727                delete exporter;
3728        }
3729        cout << "finished" << endl;
3730       
3731        mColorCode = savedColorCode;
3732}
3733
3734
3735int BspViewCellsManager::PostProcess(const ObjectContainer &objects,
3736                                                                         const VssRayContainer &rays)
3737{
3738        if (!ViewCellsConstructed())
3739        {
3740                Debug << "view cells not constructed" << endl;
3741                return 0;
3742        }
3743       
3744        // view cells already finished before post processing step,
3745        // i.e., because they were loaded from disc
3746        if (mViewCellsFinished)
3747        {
3748                FinalizeViewCells(true);
3749                EvaluateViewCellsStats();
3750
3751                return 0;
3752        }
3753
3754        //////////////////
3755        //-- merge leaves of the view cell hierarchy   
3756       
3757        cout << "starting post processing using " << mPostProcessSamples << " samples ... ";
3758        long startTime = GetTime();
3759       
3760        VssRayContainer postProcessRays;
3761        GetRaySets(rays, mPostProcessSamples, postProcessRays);
3762
3763        if (mMergeViewCells)
3764        {
3765                cout << "constructing visibility based merge tree" << endl;
3766                mViewCellsTree->ConstructMergeTree(rays, objects);
3767        }
3768        else
3769        {
3770                cout << "constructing spatial merge tree" << endl;
3771                ViewCell *root;
3772                // the spatial merge tree is difficult to build for
3773                // this type of construction, as view cells cover several
3774                // leaves => create dummy tree which is only 2 levels deep
3775                if (mUsePredefinedViewCells)
3776                {
3777                        root = ConstructDummyMergeTree(mBspTree->GetRoot());
3778                }
3779                else
3780                {
3781                        // create spatial merge hierarchy
3782                        root = ConstructSpatialMergeTree(mBspTree->GetRoot());
3783                }
3784               
3785                mViewCellsTree->SetRoot(root);
3786
3787                // recompute pvs in the whole hierarchy
3788                ObjectPvs pvs;
3789                UpdatePvsForEvaluation(root, pvs);
3790        }
3791
3792        cout << "finished" << endl;
3793        cout << "merged view cells in "
3794                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
3795
3796        Debug << "Postprocessing: Merged view cells in "
3797                << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl << endl;
3798
3799       
3800        ////////////////////////
3801        //-- visualization and statistics after merge
3802
3803        if (1)
3804        {
3805                char mstats[100];
3806                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
3807                mViewCellsTree->ExportStats(mstats);
3808        }
3809
3810        // recompute view cells and stats
3811        ResetViewCells();
3812        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
3813
3814        //  visualization of the view cells
3815        if (1) ExportMergedViewCells(objects);
3816
3817        // compute final meshes and volume / area
3818        if (1) FinalizeViewCells(true);
3819       
3820        return 0;
3821}
3822
3823
3824BspViewCellsManager::~BspViewCellsManager()
3825{
3826}
3827
3828
3829int BspViewCellsManager::GetType() const
3830{
3831        return BSP;
3832}
3833
3834
3835void BspViewCellsManager::Visualize(const ObjectContainer &objects,
3836                                                                        const VssRayContainer &sampleRays)
3837{
3838        if (!ViewCellsConstructed())
3839                return;
3840       
3841        const int savedColorCode = mColorCode;
3842       
3843        if (1) // export final view cells
3844        {
3845                mColorCode = 1; // 0 = pvs, 1 = random
3846                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
3847       
3848                cout << "exporting view cells after merge (pvs size) ... ";     
3849
3850                if (exporter)
3851                {
3852                        if (mExportGeometry)
3853                        {
3854                                exporter->ExportGeometry(objects);
3855                        }
3856
3857                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
3858                        delete exporter;
3859                }
3860                cout << "finished" << endl;
3861        }
3862
3863        // reset color code
3864        mColorCode = savedColorCode;
3865
3866
3867        //////////////////
3868        //-- visualization of the BSP splits
3869
3870        bool exportSplits = false;
3871        Environment::GetSingleton()->GetBoolValue("BspTree.Visualization.exportSplits", exportSplits);
3872
3873        if (exportSplits)
3874        {
3875                cout << "exporting splits ... ";
3876                ExportSplits(objects);
3877                cout << "finished" << endl;
3878        }
3879
3880        int leafOut;
3881        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
3882        const int raysOut = 100;
3883        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
3884}
3885
3886
3887void BspViewCellsManager::ExportSplits(const ObjectContainer &objects)
3888{
3889        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
3890
3891        if (exporter)
3892        {
3893                //exporter->SetFilled();
3894                if (mExportGeometry)
3895                {
3896                        exporter->ExportGeometry(objects);
3897                }
3898
3899                Material m;
3900                m.mDiffuseColor = RgbColor(1, 0, 0);
3901                exporter->SetForcedMaterial(m);
3902                exporter->SetWireframe();
3903
3904                exporter->ExportBspSplits(*mBspTree, true);
3905
3906                // NOTE: take forced material, else big scenes cannot be viewed
3907                m.mDiffuseColor = RgbColor(0, 1, 0);
3908                exporter->SetForcedMaterial(m);
3909                //exporter->ResetForcedMaterial();
3910
3911                delete exporter;
3912        }
3913}
3914
3915
3916void BspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
3917                                                                                                const int maxViewCells,
3918                                                                                                const bool sortViewCells,
3919                                                                                                const bool exportPvs,
3920                                                                                                const bool exportRays,
3921                                                                                                const int maxRays,
3922                                                                                                const string &prefix,
3923                                                                                                VssRayContainer *visRays)
3924{
3925        if (sortViewCells)
3926        {       // sort view cells to visualize the largest view cells
3927                sort(mViewCells.begin(), mViewCells.end(), LargerRenderCost);
3928        }
3929
3930        //////////
3931        //-- export visualizations of some view cells
3932
3933        ViewCell::NewMail();
3934        const int limit = min(maxViewCells, (int)mViewCells.size());
3935       
3936        for (int i = 0; i < limit; ++ i)
3937        {
3938                const int idx = sortViewCells ? (int)RandomValue(0, (float)mViewCells.size() - 0.5f) : i;
3939                ViewCell *vc = mViewCells[idx];
3940
3941                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
3942                        continue;
3943
3944                vc->Mail();
3945
3946                ObjectPvs pvs;
3947                mViewCellsTree->GetPvs(vc, pvs);
3948
3949                char s[64]; sprintf(s, "%sviewcell-%04d.wrl", prefix.c_str(), i);
3950                Exporter *exporter = Exporter::GetExporter(s);
3951               
3952                cout << "view cell " << idx << ": pvs cost=" << (int)mViewCellsTree->GetTrianglesInPvs(vc) << endl;
3953
3954                if (exportRays)
3955                {
3956                        ////////////
3957                        //-- export rays piercing this view cell
3958
3959                        // use rays stored with the view cells
3960                        VssRayContainer vcRays, vcRays2, vcRays3;
3961            VssRayContainer collectRays;
3962
3963                        // collect initial view cells
3964                        ViewCellContainer leaves;
3965                        mViewCellsTree->CollectLeaves(vc, leaves);
3966
3967                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
3968                for (vit = leaves.begin(); vit != vit_end; ++ vit)
3969                        {       
3970                                // prepare some rays for visualization
3971                                VssRayContainer::const_iterator rit, rit_end = (*vit)->GetOrCreateRays()->end();
3972                                for (rit = (*vit)->GetOrCreateRays()->begin(); rit != rit_end; ++ rit)
3973                                {
3974                                        collectRays.push_back(*rit);
3975                                }
3976                        }
3977
3978                        const int raysOut = min((int)collectRays.size(), maxRays);
3979
3980                        // prepare some rays for visualization
3981                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
3982                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
3983                        {
3984                                const float p = RandomValue(0.0f, (float)collectRays.size());
3985                                if (p < raysOut)
3986                                {
3987                                        if ((*rit)->mFlags & VssRay::BorderSample)
3988                                        {
3989                                                vcRays.push_back(*rit);
3990                                        }
3991                                        else if ((*rit)->mFlags & VssRay::ReverseSample)
3992                                        {
3993                                                vcRays2.push_back(*rit);
3994                                        }
3995                                        else
3996                                        {
3997                                                vcRays3.push_back(*rit);
3998                                        }       
3999                                }
4000                        }
4001
4002                        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
4003                        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
4004                        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
4005                }
4006               
4007                ////////////////
4008                //-- export view cell geometry
4009
4010                exporter->SetWireframe();
4011
4012                Material m;//= RandomMaterial();
4013                m.mDiffuseColor = RgbColor(0, 1, 0);
4014                exporter->SetForcedMaterial(m);
4015
4016                ExportViewCellGeometry(exporter, vc, NULL, NULL);
4017                exporter->SetFilled();
4018
4019                if (exportPvs)
4020                {
4021                        Intersectable::NewMail();
4022                        ObjectPvsIterator pit = pvs.GetIterator();
4023
4024                        while (pit.HasMoreEntries())
4025                        {               
4026                                Intersectable *intersect = pit.Next();
4027
4028                // output PVS of view cell
4029                                if (!intersect->Mailed())
4030                                {
4031                                        intersect->Mail();
4032
4033                                        m = RandomMaterial();
4034                                        exporter->SetForcedMaterial(m);
4035                                        exporter->ExportIntersectable(intersect);
4036                                }
4037                        }
4038                        cout << endl;
4039                }
4040               
4041                DEL_PTR(exporter);
4042                cout << "finished" << endl;
4043        }
4044}
4045
4046
4047void BspViewCellsManager::TestSubdivision()
4048{
4049        ViewCellContainer leaves;
4050        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
4051
4052        ViewCellContainer::const_iterator it, it_end = leaves.end();
4053
4054        const float vol = mViewSpaceBox.GetVolume();
4055        float subdivVol = 0;
4056        float newVol = 0;
4057
4058        for (it = leaves.begin(); it != it_end; ++ it)
4059        {
4060                BspNodeGeometry geom;
4061                mBspTree->ConstructGeometry(*it, geom);
4062
4063                const float lVol = geom.GetVolume();
4064                newVol += lVol;
4065                subdivVol += (*it)->GetVolume();
4066
4067                const float thres = 0.9f;
4068                if ((lVol < ((*it)->GetVolume() * thres)) ||
4069                        (lVol * thres > ((*it)->GetVolume())))
4070                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
4071        }
4072       
4073        Debug << "exact volume: " << vol << endl;
4074        Debug << "subdivision volume: " << subdivVol << endl;
4075        Debug << "new volume: " << newVol << endl;
4076}
4077
4078
4079void BspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
4080                                                                                                 ViewCell *vc,
4081                                                                                                 const AxisAlignedBox3 *sceneBox,
4082                                                                                                 const AxisAlignedPlane *clipPlane
4083                                                                                                 ) const
4084{
4085        if (clipPlane)
4086        {
4087                const Plane3 plane = clipPlane->GetPlane();
4088
4089                ViewCellContainer leaves;
4090                mViewCellsTree->CollectLeaves(vc, leaves);
4091                ViewCellContainer::const_iterator it, it_end = leaves.end();
4092
4093                for (it = leaves.begin(); it != it_end; ++ it)
4094                {
4095                        BspNodeGeometry geom;
4096                        BspNodeGeometry front;
4097                        BspNodeGeometry back;
4098
4099                        mBspTree->ConstructGeometry(*it, geom);
4100
4101                        const float eps = 0.0001f;
4102                        const int cf = geom.Side(plane, eps);
4103
4104                        if (cf == -1)
4105                        {
4106                                exporter->ExportPolygons(geom.GetPolys());
4107                        }
4108                        else if (cf == 0)
4109                        {
4110                                geom.SplitGeometry(front,
4111                                                                   back,
4112                                                                   plane,
4113                                                                   mViewSpaceBox,
4114                                                                   eps);
4115
4116                                if (back.Valid())
4117                                {
4118                                        exporter->ExportPolygons(back.GetPolys());
4119                                }                       
4120                        }
4121                }
4122        }
4123        else
4124        {
4125                // export mesh if available
4126                // TODO: some bug here?
4127                if (1 && vc->GetMesh())
4128                {
4129                        exporter->ExportMesh(vc->GetMesh());
4130                }
4131                else
4132                {
4133                        BspNodeGeometry geom;
4134                        mBspTree->ConstructGeometry(vc, geom);
4135                        exporter->ExportPolygons(geom.GetPolys());
4136                }
4137        }
4138}
4139
4140
4141void BspViewCellsManager::CreateMesh(ViewCell *vc)
4142{
4143        // note: should previous mesh be deleted (via mesh manager?)
4144        BspNodeGeometry geom;
4145        mBspTree->ConstructGeometry(vc, geom);
4146
4147        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
4148       
4149        IncludeNodeGeomInMesh(geom, *mesh);
4150        mesh->ComputeBoundingBox();
4151
4152        vc->SetMesh(mesh);
4153}
4154
4155
4156void BspViewCellsManager::Finalize(ViewCell *viewCell,
4157                                                                   const bool createMesh)
4158{
4159        float area = 0;
4160        float volume = 0;
4161
4162        ViewCellContainer leaves;
4163        mViewCellsTree->CollectLeaves(viewCell, leaves);
4164
4165        ViewCellContainer::const_iterator it, it_end = leaves.end();
4166
4167    for (it = leaves.begin(); it != it_end; ++ it)
4168        {
4169                BspNodeGeometry geom;
4170
4171                mBspTree->ConstructGeometry(*it, geom);
4172
4173                const float lVol = geom.GetVolume();
4174                const float lArea = geom.GetArea();
4175
4176                area += lArea;
4177                volume += lVol;
4178       
4179                CreateMesh(*it);
4180        }
4181
4182        viewCell->SetVolume(volume);
4183        viewCell->SetArea(area);
4184}
4185
4186
4187ViewCell *BspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
4188{
4189        if (!ViewCellsConstructed())
4190        {
4191                return NULL;
4192        }
4193        if (!mViewSpaceBox.IsInside(point))
4194        {
4195                return NULL;
4196        }
4197        return mBspTree->GetViewCell(point);
4198}
4199
4200
4201void BspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4202                                                                                                 vector<MergeCandidate> &candidates)
4203{
4204        cout << "collecting merge candidates ... " << endl;
4205
4206        if (mUseRaysForMerge)
4207        {
4208                mBspTree->CollectMergeCandidates(rays, candidates);
4209        }
4210        else
4211        {
4212                vector<BspLeaf *> leaves;
4213                mBspTree->CollectLeaves(leaves);
4214                mBspTree->CollectMergeCandidates(leaves, candidates);
4215        }
4216
4217        cout << "fininshed collecting candidates" << endl;
4218}
4219
4220
4221
4222bool BspViewCellsManager::ExportViewCells(const string filename,
4223                                                                                  const bool exportPvs,
4224                                                                                  const ObjectContainer &objects)
4225{
4226        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
4227        {
4228                return false;
4229        }
4230
4231        cout << "exporting view cells to xml ... ";
4232
4233        OUT_STREAM stream(filename.c_str());
4234
4235        // we need unique ids for each view cell
4236        CreateUniqueViewCellIds();
4237
4238        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
4239        stream << "<VisibilitySolution>" << endl;
4240
4241        if (exportPvs)
4242        {
4243                //////////
4244                //-- export bounding boxes: they are used to identify the objects from the pvs and
4245                //-- assign them to the entities in the rendering engine
4246
4247                stream << "<BoundingBoxes>" << endl;
4248                ObjectContainer::const_iterator oit, oit_end = objects.end();
4249
4250                for (oit = objects.begin(); oit != oit_end; ++ oit)
4251                {
4252                        const AxisAlignedBox3 box = (*oit)->GetBox();
4253                       
4254                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
4255                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
4256                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
4257                }
4258
4259                stream << "</BoundingBoxes>" << endl;
4260        }
4261
4262        ///////////
4263        //-- export the view cells and the pvs
4264
4265        const int numViewCells = mCurrentViewCellsStats.viewCells;
4266        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
4267
4268        mViewCellsTree->Export(stream, exportPvs);
4269       
4270        stream << "</ViewCells>" << endl;
4271
4272        /////////////
4273        //-- export the view space hierarchy
4274        stream << "<ViewSpaceHierarchy type=\"bsp\""
4275                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
4276                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
4277
4278        mBspTree->Export(stream);
4279
4280        // end tags
4281        stream << "</ViewSpaceHierarchy>" << endl;
4282        stream << "</VisibilitySolution>" << endl;
4283
4284        stream.close();
4285        cout << "finished" << endl;
4286
4287        return true;
4288}
4289
4290
4291ViewCell *BspViewCellsManager::ConstructDummyMergeTree(BspNode *root)
4292{
4293        ViewCellInterior *vcRoot = new ViewCellInterior();
4294               
4295        // evaluate merge cost for priority traversal
4296        const float mergeCost =  -(float)root->mTimeStamp;
4297        vcRoot->SetMergeCost(mergeCost);
4298
4299        float volume = 0;
4300        vector<BspLeaf *> leaves;
4301        mBspTree->CollectLeaves(leaves);
4302        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
4303        ViewCell::NewMail();
4304
4305        for (lit = leaves.begin(); lit != lit_end; ++ lit)
4306        {
4307                BspLeaf *leaf = *lit;
4308                ViewCell *vc = leaf->GetViewCell();
4309
4310                if (!vc->Mailed())
4311                {
4312                        vc->Mail();
4313                        vc->SetMergeCost(0.0f);
4314                        vcRoot->SetupChildLink(vc);
4315
4316                        volume += vc->GetVolume();
4317                        volume += vc->GetVolume();     
4318                        vcRoot->SetVolume(volume);
4319                }
4320        }
4321       
4322        return vcRoot;
4323}
4324
4325
4326ViewCell *BspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
4327{
4328        // terminate recursion
4329        if (root->IsLeaf())
4330        {
4331                BspLeaf *leaf = static_cast<BspLeaf *>(root);
4332                leaf->GetViewCell()->SetMergeCost(0.0f);
4333                return leaf->GetViewCell();
4334        }
4335       
4336        BspInterior *interior = static_cast<BspInterior *>(root);
4337        ViewCellInterior *viewCellInterior = new ViewCellInterior();
4338               
4339        // evaluate merge cost for priority traversal
4340        const float mergeCost = -(float)root->mTimeStamp;
4341        viewCellInterior->SetMergeCost(mergeCost);
4342
4343        float volume = 0;
4344       
4345        BspNode *front = interior->GetFront();
4346        BspNode *back = interior->GetBack();
4347
4348
4349        ////////////
4350        //-- recursivly compute child hierarchies
4351
4352        ViewCell *backVc = ConstructSpatialMergeTree(back);
4353        ViewCell *frontVc = ConstructSpatialMergeTree(front);
4354
4355        viewCellInterior->SetupChildLink(backVc);
4356        viewCellInterior->SetupChildLink(frontVc);
4357
4358        volume += backVc->GetVolume();
4359        volume += frontVc->GetVolume();
4360
4361        viewCellInterior->SetVolume(volume);
4362
4363        return viewCellInterior;
4364}
4365
4366
4367/************************************************************************/
4368/*                   KdViewCellsManager implementation                  */
4369/************************************************************************/
4370
4371
4372
4373KdViewCellsManager::KdViewCellsManager(ViewCellsTree *vcTree, KdTree *kdTree):
4374ViewCellsManager(vcTree), mKdTree(kdTree), mKdPvsDepth(100)
4375{
4376}
4377
4378
4379float KdViewCellsManager::GetProbability(ViewCell *viewCell)
4380{
4381        // compute view cell area / volume as subsititute for probability
4382        if (0)
4383                return GetArea(viewCell) / GetViewSpaceBox().SurfaceArea();
4384        else
4385                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
4386}
4387
4388
4389
4390
4391void KdViewCellsManager::CollectViewCells()
4392{
4393        //mKdTree->CollectViewCells(mViewCells); TODO
4394}
4395
4396
4397int KdViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4398                                                                  const VssRayContainer &rays)
4399{
4400        // if view cells already constructed
4401        if (ViewCellsConstructed())
4402                return 0;
4403
4404        mKdTree->Construct();
4405
4406        mTotalAreaValid = false;
4407        // create the view cells
4408        mKdTree->CreateAndCollectViewCells(mViewCells);
4409        // cast rays
4410        ComputeSampleContributions(rays, true, false);
4411
4412        EvaluateViewCellsStats();
4413        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4414
4415        return 0;
4416}
4417
4418
4419bool KdViewCellsManager::ViewCellsConstructed() const
4420{
4421        return mKdTree->GetRoot() != NULL;
4422}
4423
4424
4425int KdViewCellsManager::PostProcess(const ObjectContainer &objects,
4426                                                                        const VssRayContainer &rays)
4427{
4428        return 0;
4429}
4430
4431
4432void KdViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
4433                                                                                           const int maxViewCells,
4434                                                                                           const bool sortViewCells,
4435                                                                                           const bool exportPvs,
4436                                                                                           const bool exportRays,
4437                                                                                           const int maxRays,
4438                                                                                           const string &prefix,
4439                                                                                           VssRayContainer *visRays)
4440{
4441        // TODO
4442}
4443
4444
4445void KdViewCellsManager::Visualize(const ObjectContainer &objects,
4446                                                                   const VssRayContainer &sampleRays)
4447{
4448        if (!ViewCellsConstructed())
4449                return;
4450
4451        // using view cells instead of the kd PVS of objects
4452        const bool useViewCells = true;
4453        bool exportRays = false;
4454
4455        int limit = min(mVisualizationSamples, (int)sampleRays.size());
4456        const int pvsOut = min((int)objects.size(), 10);
4457        VssRayContainer *rays = new VssRayContainer[pvsOut];
4458
4459        if (useViewCells)
4460        {
4461                const int leafOut = 10;
4462
4463                ViewCell::NewMail();
4464
4465                //-- some rays for visualization
4466                const int raysOut = min((int)sampleRays.size(), mVisualizationSamples);
4467                Debug << "visualization using " << raysOut << " samples" << endl;
4468
4469                //-- some random view cells and rays for visualization
4470                vector<KdLeaf *> kdLeaves;
4471
4472                for (int i = 0; i < leafOut; ++ i)
4473                        kdLeaves.push_back(static_cast<KdLeaf *>(mKdTree->GetRandomLeaf()));
4474
4475                for (int i = 0; i < kdLeaves.size(); ++ i)
4476                {
4477                        KdLeaf *leaf = kdLeaves[i];
4478                        RayContainer vcRays;
4479
4480                        cout << "creating output for view cell " << i << " ... ";
4481#if 0
4482                        // check whether we can add the current ray to the output rays
4483                        for (int k = 0; k < raysOut; ++ k)
4484                        {
4485                                Ray *ray = sampleRays[k];
4486
4487                                for (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
4488                                {
4489                                        BspLeaf *leaf2 = ray->bspIntersections[j].mLeaf;
4490
4491                                        if (leaf->GetViewCell() == leaf2->GetViewCell())
4492                                        {
4493                                                vcRays.push_back(ray);
4494                                        }
4495                                }
4496                        }
4497#endif
4498                        Intersectable::NewMail();
4499
4500                        ViewCell *vc = leaf->mViewCell;
4501                        char str[64]; sprintf(str, "viewcell%04d.wrl", i);
4502
4503                        Exporter *exporter = Exporter::GetExporter(str);
4504                        exporter->SetFilled();
4505
4506                        exporter->SetWireframe();
4507                        //exporter->SetFilled();
4508
4509                        Material m;//= RandomMaterial();
4510                        m.mDiffuseColor = RgbColor(1, 1, 0);
4511                        exporter->SetForcedMaterial(m);
4512
4513                        AxisAlignedBox3 box = mKdTree->GetBox(leaf);
4514                        exporter->ExportBox(box);
4515
4516                        // export rays piercing this view cell
4517                        exporter->ExportRays(vcRays, 1000, RgbColor(0, 1, 0));
4518
4519                        m.mDiffuseColor = RgbColor(1, 0, 0);
4520                        exporter->SetForcedMaterial(m);
4521
4522                        // exporter->SetWireframe();
4523                        exporter->SetFilled();
4524
4525                        ObjectPvsIterator pit = vc->GetPvs().GetIterator();
4526                       
4527                        while (pit.HasMoreEntries())
4528                        {               
4529                                //-- output PVS of view cell
4530                                Intersectable *intersect = pit.Next();
4531
4532                                if (!intersect->Mailed())
4533                                {
4534                                        exporter->ExportIntersectable(intersect);
4535                                        intersect->Mail();
4536                                }
4537                        }
4538
4539                        DEL_PTR(exporter);
4540                        cout << "finished" << endl;
4541                }
4542
4543                DEL_PTR(rays);
4544        }
4545        else // using kd PVS of objects
4546        {
4547                for (int i = 0; i < limit; ++ i)
4548                {
4549                        VssRay *ray = sampleRays[i];
4550
4551                        // check whether we can add this to the rays
4552                        for (int j = 0; j < pvsOut; j++)
4553                        {
4554                                if (objects[j] == ray->mTerminationObject)
4555                                {
4556                                        rays[j].push_back(ray);
4557                                }
4558                        }
4559                }
4560
4561                if (exportRays)
4562                {
4563                        Exporter *exporter = NULL;
4564                        exporter = Exporter::GetExporter("sample-rays.x3d");
4565                        exporter->SetWireframe();
4566                        exporter->ExportKdTree(*mKdTree);
4567
4568                        for (int i = 0; i < pvsOut; i++)
4569                                exporter->ExportRays(rays[i], RgbColor(1, 0, 0));
4570
4571                        exporter->SetFilled();
4572                        delete exporter;
4573                }
4574
4575                for (int k=0; k < pvsOut; k++)
4576                {
4577                        Intersectable *object = objects[k];
4578                        char str[64]; sprintf(str, "viewcell%04d.wrl", k);
4579
4580                        Exporter *exporter = Exporter::GetExporter(str);
4581                        exporter->SetWireframe();
4582
4583                        // matt: we do not use kd pvs
4584#if 0
4585                        KdPvsMap::iterator kit = object->mKdPvs.mEntries.begin();
4586                        Intersectable::NewMail();
4587
4588                        // avoid adding the object to the list
4589                        object->Mail();
4590                        ObjectContainer visibleObjects;
4591
4592                        for (; kit != object->mKdPvs.mEntries.end(); i++)
4593                        {
4594                                KdNode *node = (*kit).first;
4595                                exporter->ExportBox(mKdTree->GetBox(node));
4596
4597                                mKdTree->CollectObjects(node, visibleObjects);
4598                        }
4599
4600                        exporter->ExportRays(rays[k],  RgbColor(0, 1, 0));
4601                        exporter->SetFilled();
4602
4603                        for (int j = 0; j < visibleObjects.size(); j++)
4604                                exporter->ExportIntersectable(visibleObjects[j]);
4605
4606                        Material m;
4607                        m.mDiffuseColor = RgbColor(1, 0, 0);
4608                        exporter->SetForcedMaterial(m);
4609                        exporter->ExportIntersectable(object);
4610#endif
4611                        delete exporter;
4612                }
4613        }
4614}
4615
4616
4617ViewCell *KdViewCellsManager::GenerateViewCell(Mesh *mesh) const
4618{
4619        return new KdViewCell(mesh);
4620}
4621
4622
4623void KdViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
4624                                                                                                ViewCell *vc,
4625                                                                                                const AxisAlignedBox3 *sceneBox,
4626                                                                                                const AxisAlignedPlane *clipPlane
4627                                                                                                ) const
4628{
4629        ViewCellContainer leaves;
4630        mViewCellsTree->CollectLeaves(vc, leaves);
4631        ViewCellContainer::const_iterator it, it_end = leaves.end();
4632
4633        for (it = leaves.begin(); it != it_end; ++ it)
4634        {
4635                KdViewCell *kdVc = static_cast<KdViewCell *>(*it);
4636                exporter->ExportBox(mKdTree->GetBox(kdVc->mLeaves[0]));
4637        }
4638}
4639
4640
4641int KdViewCellsManager::GetType() const
4642{
4643        return ViewCellsManager::KD;
4644}
4645
4646
4647
4648KdNode *KdViewCellsManager::GetNodeForPvs(KdLeaf *leaf)
4649{
4650        KdNode *node = leaf;
4651
4652        while (node->mParent && node->mDepth > mKdPvsDepth)
4653                node = node->mParent;
4654
4655        return node;
4656}
4657
4658int KdViewCellsManager::CastLineSegment(const Vector3 &origin,
4659                                                                                const Vector3 &termination,
4660                                                                                ViewCellContainer &viewcells)
4661{
4662        return mKdTree->CastLineSegment(origin, termination, viewcells);
4663}
4664
4665
4666bool KdViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
4667                                                                                           const Vector3 &termination,
4668                                                                                           ViewCell *viewCell)
4669{
4670        return false;
4671}
4672
4673
4674void KdViewCellsManager::CreateMesh(ViewCell *vc)
4675{
4676        // TODO
4677}
4678
4679
4680
4681void KdViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4682                                                                                                vector<MergeCandidate> &candidates)
4683{
4684        // TODO
4685}
4686
4687
4688
4689/**************************************************************************/
4690/*                   VspBspViewCellsManager implementation                */
4691/**************************************************************************/
4692
4693
4694VspBspViewCellsManager::VspBspViewCellsManager(ViewCellsTree *vcTree, VspBspTree *vspBspTree):
4695ViewCellsManager(vcTree), mVspBspTree(vspBspTree)
4696{
4697        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", mInitialSamples);
4698        mVspBspTree->SetViewCellsManager(this);
4699        mVspBspTree->mViewCellsTree = mViewCellsTree;
4700}
4701
4702
4703VspBspViewCellsManager::~VspBspViewCellsManager()
4704{
4705}
4706
4707
4708float VspBspViewCellsManager::GetProbability(ViewCell *viewCell)
4709{
4710        if (0 && mVspBspTree->mUseAreaForPvs)
4711                return GetArea(viewCell) / GetAccVcArea();
4712        else
4713                return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
4714}
4715
4716
4717void VspBspViewCellsManager::CollectViewCells()
4718{
4719        // view cells tree constructed?
4720        if (!ViewCellsTreeConstructed())
4721        {
4722                mVspBspTree->CollectViewCells(mViewCells, false);
4723        }
4724        else
4725        {       
4726                // we can use the view cells tree hierarchy to get the right set
4727                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
4728        }
4729}
4730
4731
4732void VspBspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4733                                                                                                        vector<MergeCandidate> &candidates)
4734{       
4735        cout << "collecting merge candidates ... " << endl;
4736
4737        if (mUseRaysForMerge)
4738        {
4739                mVspBspTree->CollectMergeCandidates(rays, candidates);
4740        }
4741        else
4742        {
4743                vector<BspLeaf *> leaves;
4744                mVspBspTree->CollectLeaves(leaves);
4745       
4746                mVspBspTree->CollectMergeCandidates(leaves, candidates);
4747        }
4748
4749        cout << "fininshed collecting candidates" << endl;
4750}
4751
4752
4753bool VspBspViewCellsManager::ViewCellsConstructed() const
4754{
4755        return mVspBspTree->GetRoot() != NULL;
4756}
4757
4758
4759ViewCell *VspBspViewCellsManager::GenerateViewCell(Mesh *mesh) const
4760{
4761        return new BspViewCell(mesh);
4762}
4763
4764
4765int VspBspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4766                                                                                                 const VssRayContainer &rays)
4767{
4768        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
4769
4770        // if view cells were already constructed
4771        if (ViewCellsConstructed())
4772        {
4773                return 0;
4774        }
4775
4776        int sampleContributions = 0;
4777        VssRayContainer sampleRays;
4778
4779        const int limit = min(mInitialSamples, (int)rays.size());
4780
4781        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
4782                  << ", actual rays: " << (int)rays.size() << endl;
4783
4784        VssRayContainer savedRays;
4785
4786        if (SAMPLE_AFTER_SUBDIVISION)
4787        {
4788                VssRayContainer constructionRays;
4789               
4790                GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
4791
4792                Debug << "rays used for initial construction: " << (int)constructionRays.size() << endl;
4793                Debug << "rays saved for later use: " << (int)savedRays.size() << endl;
4794       
4795                mVspBspTree->Construct(constructionRays, &mViewSpaceBox);
4796        }
4797        else
4798        {
4799                Debug << "rays used for initial construction: " << (int)rays.size() << endl;
4800                mVspBspTree->Construct(rays, &mViewSpaceBox);
4801        }
4802
4803        // collapse invalid regions
4804        cout << "collapsing invalid tree regions ... ";
4805        long startTime = GetTime();
4806
4807        const int collapsedLeaves = mVspBspTree->CollapseTree();
4808        Debug << "collapsed in " << TimeDiff(startTime, GetTime()) * 1e-3
4809                  << " seconds" << endl;
4810
4811    cout << "finished" << endl;
4812
4813        /////////////////
4814        //-- stats after construction
4815
4816        Debug << mVspBspTree->GetStatistics() << endl;
4817
4818        ResetViewCells();
4819        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4820
4821
4822        //////////////////////
4823        //-- recast the rest of the rays
4824
4825        startTime = GetTime();
4826
4827        cout << "Computing remaining ray contributions ... ";
4828
4829        if (SAMPLE_AFTER_SUBDIVISION)
4830                ComputeSampleContributions(savedRays, true, false);
4831
4832        cout << "finished" << endl;
4833
4834        Debug << "Computed remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
4835                  << " secs" << endl;
4836
4837        cout << "construction finished" << endl;
4838
4839        if (0)
4840        {       ////////
4841                //-- real meshes are contructed at this stage
4842
4843                cout << "finalizing view cells ... ";
4844                FinalizeViewCells(true);
4845                cout << "finished" << endl;
4846        }
4847
4848        return sampleContributions;
4849}
4850
4851
4852void VspBspViewCellsManager::MergeViewCells(const VssRayContainer &rays,
4853                                                                                        const ObjectContainer &objects)
4854{
4855    int vcSize = 0;
4856        int pvsSize = 0;
4857
4858        //-- merge view cells
4859        cout << "starting merge using " << mPostProcessSamples << " samples ... " << endl;
4860        long startTime = GetTime();
4861
4862
4863        if (mMergeViewCells)
4864        {
4865                // TODO: should be done BEFORE the ray casting
4866                // compute tree by merging the nodes based on cost heuristics
4867                mViewCellsTree->ConstructMergeTree(rays, objects);
4868        }
4869        else
4870        {
4871                // compute tree by merging the nodes of the spatial hierarchy
4872                ViewCell *root = ConstructSpatialMergeTree(mVspBspTree->GetRoot());
4873                mViewCellsTree->SetRoot(root);
4874
4875                // compute pvs
4876                ObjectPvs pvs;
4877                UpdatePvsForEvaluation(root, pvs);
4878        }
4879
4880        if (1)
4881        {
4882                char mstats[100];
4883                ObjectPvs pvs;
4884
4885                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
4886                mViewCellsTree->ExportStats(mstats);
4887        }
4888
4889        cout << "merged view cells in "
4890                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
4891
4892        Debug << "Postprocessing: Merged view cells in "
4893                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
4894       
4895
4896        //////////////////
4897        //-- stats and visualizations
4898
4899        int savedColorCode = mColorCode;
4900       
4901        // get currently active view cell set
4902        ResetViewCells();
4903        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
4904       
4905        if (mShowVisualization) // export merged view cells
4906        {
4907                mColorCode = 0;
4908                Exporter *exporter = Exporter::GetExporter("merged_view_cells.wrl");
4909               
4910                cout << "exporting view cells after merge ... ";
4911
4912                if (exporter)
4913                {
4914                        if (0)
4915                                exporter->SetWireframe();
4916                        else
4917                                exporter->SetFilled();
4918
4919                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
4920
4921                        if (mExportGeometry)
4922                        {
4923                                Material m;
4924                                m.mDiffuseColor = RgbColor(0, 1, 0);
4925                                exporter->SetForcedMaterial(m);
4926                                exporter->SetFilled();
4927
4928                                exporter->ExportGeometry(objects);
4929                        }
4930
4931                        delete exporter;
4932                }
4933                cout << "finished" << endl;
4934        }
4935
4936        mColorCode = savedColorCode;
4937}
4938
4939
4940void VspBspViewCellsManager::RefineViewCells(const VssRayContainer &rays,
4941                                                                                         const ObjectContainer &objects)
4942{
4943        mRenderer->RenderScene();
4944
4945        SimulationStatistics ss;
4946        static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
4947    Debug << "render time before refine\n\n" << ss << endl;
4948
4949        const long startTime = GetTime();
4950        cout << "Refining the merged view cells ... ";
4951
4952        // refining the merged view cells
4953        const int refined = mViewCellsTree->RefineViewCells(rays, objects);
4954
4955        //-- stats and visualizations
4956        cout << "finished" << endl;
4957        cout << "refined " << refined << " view cells in "
4958                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
4959
4960        Debug << "Postprocessing: refined " << refined << " view cells in "
4961                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
4962}
4963
4964
4965int VspBspViewCellsManager::PostProcess(const ObjectContainer &objects,
4966                                                                                const VssRayContainer &rays)
4967{
4968        if (!ViewCellsConstructed())
4969        {
4970                Debug << "postprocess error: no view cells constructed" << endl;
4971                return 0;
4972        }
4973
4974        // view cells already finished before post processing step
4975        // (i.e. because they were loaded)
4976        if (mViewCellsFinished)
4977        {
4978                FinalizeViewCells(true);
4979                EvaluateViewCellsStats();
4980
4981                return 0;
4982        }
4983
4984        // check if new view cells turned invalid
4985        int minPvs, maxPvs;
4986
4987        if (0)
4988        {
4989                minPvs = mMinPvsSize;
4990                maxPvs = mMaxPvsSize;
4991        }
4992        else
4993        {
4994                // problem matt: why did I start here from zero?
4995                minPvs = 0;
4996                maxPvs = mMaxPvsSize;
4997        }
4998
4999        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5000        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5001       
5002        SetValidity(minPvs, maxPvs);
5003
5004        // update valid view space according to valid view cells
5005        if (0) mVspBspTree->ValidateTree();
5006
5007        // area has to be recomputed
5008        mTotalAreaValid = false;
5009        VssRayContainer postProcessRays;
5010        GetRaySets(rays, mPostProcessSamples, postProcessRays);
5011
5012        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
5013
5014        //////////
5015        //-- merge neighbouring view cells
5016        MergeViewCells(postProcessRays, objects);
5017       
5018        // refines the merged view cells
5019        if (0) RefineViewCells(postProcessRays, objects);
5020
5021
5022        ///////////
5023        //-- render simulation after merge + refine
5024
5025        cout << "\nview cells partition render time before compress" << endl << endl;;
5026        static_cast<RenderSimulator *>(mRenderer)->RenderScene();
5027        SimulationStatistics ss;
5028        static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
5029        cout << ss << endl;
5030       
5031        if (0) CompressViewCells();
5032       
5033        // collapse sibling leaves that share the same view cell
5034        if (0) mVspBspTree->CollapseTree();
5035
5036        // recompute view cell list and statistics
5037        ResetViewCells();
5038
5039        // compute final meshes and volume / area
5040        if (1) FinalizeViewCells(true);
5041
5042        return 0;
5043}
5044
5045
5046int VspBspViewCellsManager::GetType() const
5047{
5048        return VSP_BSP;
5049}
5050
5051
5052ViewCell *VspBspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
5053{
5054        // terminate recursion
5055        if (root->IsLeaf())
5056        {
5057                BspLeaf *leaf = static_cast<BspLeaf *>(root);
5058                leaf->GetViewCell()->SetMergeCost(0.0f);
5059                return leaf->GetViewCell();
5060        }
5061       
5062       
5063        BspInterior *interior = static_cast<BspInterior *>(root);
5064        ViewCellInterior *viewCellInterior = new ViewCellInterior();
5065               
5066        // evaluate merge cost for priority traversal
5067        float mergeCost = 1.0f / (float)root->mTimeStamp;
5068        viewCellInterior->SetMergeCost(mergeCost);
5069
5070        float volume = 0;
5071       
5072        BspNode *front = interior->GetFront();
5073        BspNode *back = interior->GetBack();
5074
5075
5076        ObjectPvs frontPvs, backPvs;
5077
5078        //-- recursivly compute child hierarchies
5079        ViewCell *backVc = ConstructSpatialMergeTree(back);
5080        ViewCell *frontVc = ConstructSpatialMergeTree(front);
5081
5082
5083        viewCellInterior->SetupChildLink(backVc);
5084        viewCellInterior->SetupChildLink(frontVc);
5085
5086        volume += backVc->GetVolume();
5087        volume += frontVc->GetVolume();
5088
5089        viewCellInterior->SetVolume(volume);
5090
5091        return viewCellInterior;
5092}
5093
5094
5095bool VspBspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
5096{
5097        if (!ViewCellsConstructed())
5098                return ViewCellsManager::GetViewPoint(viewPoint);
5099
5100        // TODO: set reasonable limit
5101        const int limit = 20;
5102
5103        for (int i = 0; i < limit; ++ i)
5104        {
5105                viewPoint = mViewSpaceBox.GetRandomPoint();
5106                if (mVspBspTree->ViewPointValid(viewPoint))
5107                {
5108                        return true;
5109                }
5110        }
5111
5112        Debug << "failed to find valid view point, taking " << viewPoint << endl;
5113        return false;
5114}
5115
5116
5117bool VspBspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
5118{
5119        // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
5120        // validy update in preprocessor for all managers)
5121        return ViewCellsManager::ViewPointValid(viewPoint);
5122
5123        //      return mViewSpaceBox.IsInside(viewPoint) &&
5124        //                 mVspBspTree->ViewPointValid(viewPoint);
5125}
5126
5127
5128void VspBspViewCellsManager::Visualize(const ObjectContainer &objects,
5129                                                                           const VssRayContainer &sampleRays)
5130{
5131        if (!ViewCellsConstructed())
5132                return;
5133
5134        VssRayContainer visRays;
5135        GetRaySets(sampleRays, mVisualizationSamples, visRays);
5136       
5137        if (1)
5138        {       
5139                //////////////////
5140                //-- export final view cell partition
5141
5142                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
5143               
5144                if (exporter)
5145                {
5146                        cout << "exporting view cells after post process ... ";
5147
5148                        if (0)
5149                        {       // export view space box
5150                                exporter->SetWireframe();
5151                                exporter->ExportBox(mViewSpaceBox);
5152                                exporter->SetFilled();
5153                        }
5154
5155                        Material m;
5156                        m.mDiffuseColor.r = 0.0f;
5157                        m.mDiffuseColor.g = 0.5f;
5158                        m.mDiffuseColor.b = 0.5f;
5159
5160            exporter->SetForcedMaterial(m);
5161
5162                        if (1 && mExportGeometry)
5163                        {
5164                                exporter->ExportGeometry(objects);
5165                        }
5166
5167                        if (0 && mExportRays)
5168                        {
5169                                exporter->ExportRays(visRays, RgbColor(1, 0, 0));
5170                        }
5171                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
5172
5173                        delete exporter;
5174                        cout << "finished" << endl;
5175                }
5176        }
5177
5178        ////////////////
5179        //-- visualization of the BSP splits
5180
5181        bool exportSplits = false;
5182        Environment::GetSingleton()->GetBoolValue("VspBspTree.Visualization.exportSplits", exportSplits);
5183
5184        if (exportSplits)
5185        {
5186                cout << "exporting splits ... ";
5187                ExportSplits(objects, visRays);
5188                cout << "finished" << endl;
5189        }
5190
5191        ////////
5192        //-- export single view cells
5193       
5194        int leafOut;
5195        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
5196        const int raysOut = 100;
5197       
5198        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
5199}
5200
5201
5202void VspBspViewCellsManager::ExportSplits(const ObjectContainer &objects,
5203                                                                                  const VssRayContainer &rays)
5204{
5205        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
5206
5207        if (exporter)
5208        {
5209                Material m;
5210                m.mDiffuseColor = RgbColor(1, 0, 0);
5211                exporter->SetForcedMaterial(m);
5212                exporter->SetWireframe();
5213
5214                exporter->ExportBspSplits(*mVspBspTree, true);
5215
5216                // take forced material, else big scenes cannot be viewed
5217                m.mDiffuseColor = RgbColor(0, 1, 0);
5218                exporter->SetForcedMaterial(m);
5219                exporter->SetFilled();
5220
5221                exporter->ResetForcedMaterial();
5222
5223                // export rays
5224                if (mExportRays)
5225                {
5226                        exporter->ExportRays(rays, RgbColor(1, 1, 0));
5227                }
5228
5229                if (mExportGeometry)
5230                {
5231                        exporter->ExportGeometry(objects);
5232                }
5233                delete exporter;
5234        }
5235}
5236
5237
5238void VspBspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
5239                                                                                                   const int maxViewCells,
5240                                                                                                   const bool sortViewCells,
5241                                                                                                   const bool exportPvs,
5242                                                                                                   const bool exportRays,
5243                                                                                                   const int maxRays,
5244                                                                                                   const string &prefix,
5245                                                                                                   VssRayContainer *visRays)
5246{       
5247        if (sortViewCells)
5248        {
5249                // sort view cells to visualize the largest view cells
5250                sort(mViewCells.begin(), mViewCells.end(), LargerRenderCost);
5251        }
5252
5253        //////////
5254        //-- export some view cells for visualization
5255
5256        ViewCell::NewMail();
5257        const int limit = min(maxViewCells, (int)mViewCells.size());
5258       
5259        for (int i = 0; i < limit; ++ i)
5260        {
5261                cout << "creating output for view cell " << i << " ... ";
5262
5263                ViewCell *vc = sortViewCells ? // largest view cell pvs first?
5264                        mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 0.5f)] : mViewCells[i];
5265
5266                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
5267                        continue;
5268
5269                vc->Mail();
5270
5271                ObjectPvs pvs;
5272                mViewCellsTree->GetPvs(vc, pvs);
5273
5274                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
5275                Exporter *exporter = Exporter::GetExporter(s);
5276               
5277                const float pvsCost = mViewCellsTree->GetTrianglesInPvs(vc);
5278                cout << "view cell " << vc->GetId() << ": pvs cost=" << pvsCost << endl;
5279
5280                if (exportRays)
5281                {
5282                        ////////////
5283                        //-- export rays piercing this view cell
5284
5285                        // take rays stored with the view cells during subdivision
5286                        VssRayContainer vcRays;
5287            VssRayContainer collectRays;
5288
5289                        // collect initial view cells
5290                        ViewCellContainer leaves;
5291                        mViewCellsTree->CollectLeaves(vc, leaves);
5292
5293                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
5294                for (vit = leaves.begin(); vit != vit_end; ++ vit)
5295                        {       
5296                                BspLeaf *vcLeaf = static_cast<BspViewCell *>(*vit)->mLeaves[0];
5297                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
5298
5299                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
5300                                {
5301                                        collectRays.push_back(*rit);
5302                                }
5303                        }
5304
5305                        const int raysOut = min((int)collectRays.size(), maxRays);
5306               
5307                        // prepare some rays for visualization
5308                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
5309                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
5310                        {
5311                                const float p = RandomValue(0.0f, (float)collectRays.size());
5312                       
5313                                if (p < raysOut)
5314                                {
5315                                        vcRays.push_back(*rit);
5316                                }
5317                        }
5318
5319                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
5320                }
5321               
5322                ////////////////
5323                //-- export view cell geometry
5324
5325                exporter->SetWireframe();
5326
5327                Material m;//= RandomMaterial();
5328                m.mDiffuseColor = RgbColor(0, 1, 0);
5329                exporter->SetForcedMaterial(m);
5330
5331                ExportViewCellGeometry(exporter, vc, NULL, NULL);
5332                exporter->SetFilled();
5333
5334                if (exportPvs)
5335                {
5336                        Intersectable::NewMail();
5337                        ObjectPvsIterator pit = pvs.GetIterator();
5338
5339                        cout << endl;
5340
5341                        // output PVS of view cell
5342                        while (pit.HasMoreEntries())
5343                        {
5344                                Intersectable *intersect = pit.Next();         
5345                               
5346                                if (!intersect->Mailed())
5347                                {
5348                                        intersect->Mail();
5349
5350                                        m = RandomMaterial();
5351                                        exporter->SetForcedMaterial(m);
5352                                        exporter->ExportIntersectable(intersect);
5353                                }
5354                        }
5355                        cout << endl;
5356                }
5357               
5358                DEL_PTR(exporter);
5359                cout << "finished" << endl;
5360        }
5361}
5362
5363
5364void VspBspViewCellsManager::TestFilter(const ObjectContainer &objects)
5365{
5366        Exporter *exporter = Exporter::GetExporter("filter.x3d");
5367
5368        Vector3 bsize = mViewSpaceBox.Size();
5369        const Vector3 viewPoint(mViewSpaceBox.Center());
5370        float w = Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
5371        const Vector3 width = Vector3(w);
5372       
5373        PrVs testPrVs;
5374       
5375        if (exporter)
5376        {
5377                ViewCellContainer viewCells;
5378       
5379        const AxisAlignedBox3 tbox = GetFilterBBox(viewPoint, mFilterWidth);
5380
5381                GetPrVS(viewPoint, testPrVs, GetFilterWidth());
5382
5383                exporter->SetWireframe();
5384
5385                exporter->SetForcedMaterial(RgbColor(1,1,1));
5386                exporter->ExportBox(tbox);
5387               
5388                exporter->SetFilled();
5389
5390                exporter->SetForcedMaterial(RgbColor(0,1,0));
5391                ExportViewCellGeometry(exporter, GetViewCell(viewPoint), NULL, NULL);
5392
5393                //exporter->ResetForcedMaterial();
5394                exporter->SetForcedMaterial(RgbColor(0,0,1));
5395                ExportViewCellGeometry(exporter, testPrVs.mViewCell, NULL, NULL);
5396
5397        exporter->SetForcedMaterial(RgbColor(1,0,0));
5398                exporter->ExportGeometry(objects);
5399
5400                delete exporter;
5401        }
5402}
5403
5404
5405int VspBspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
5406                                                                                                        ViewCellContainer &viewCells) const
5407{
5408        return mVspBspTree->ComputeBoxIntersections(box, viewCells);
5409}
5410
5411
5412int VspBspViewCellsManager::CastLineSegment(const Vector3 &origin,
5413                                                                                        const Vector3 &termination,
5414                                                                                        ViewCellContainer &viewcells)
5415{
5416        return mVspBspTree->CastLineSegment(origin, termination, viewcells);
5417}
5418
5419
5420bool VspBspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
5421                                                                                                   const Vector3 &termination,
5422                                                                                                   ViewCell *viewCell)
5423{
5424        return false;
5425}
5426
5427
5428void VspBspViewCellsManager::VisualizeWithFromPointQueries()
5429{
5430        int numSamples;
5431       
5432        Environment::GetSingleton()->GetIntValue("RenderSampler.samples", numSamples);
5433        cout << "samples" << numSamples << endl;
5434
5435        vector<RenderCostSample> samples;
5436 
5437        if (!mPreprocessor->GetRenderer())
5438                return;
5439
5440        //start the view point queries
5441        long startTime = GetTime();
5442        cout << "starting sampling of render cost ... ";
5443       
5444        mPreprocessor->GetRenderer()->SampleRenderCost(numSamples, samples, true);
5445
5446        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
5447
5448
5449        // for each sample:
5450        //    find view cells associated with the samples
5451        //    store the sample pvs with the pvs associated with the view cell
5452        //
5453        // for each view cell:
5454        //    compute difference point sampled pvs - view cell pvs
5455        //    export geometry with color coded pvs difference
5456       
5457    std::map<ViewCell *, ObjectPvs> sampleMap;
5458
5459        vector<RenderCostSample>::const_iterator rit, rit_end = samples.end();
5460
5461        for (rit = samples.begin(); rit != rit_end; ++ rit)
5462        {
5463                RenderCostSample sample = *rit;
5464       
5465                ViewCell *vc = GetViewCell(sample.mPosition);
5466
5467                std::map<ViewCell *, ObjectPvs>::iterator it = sampleMap.find(vc);
5468
5469                if (it == sampleMap.end())
5470                {
5471                        sampleMap[vc] = sample.mPvs;
5472                }
5473                else
5474                {
5475                        (*it).second.MergeInPlace(sample.mPvs);
5476                }
5477        }
5478
5479        // visualize the view cells
5480        std::map<ViewCell *, ObjectPvs>::const_iterator vit, vit_end = sampleMap.end();
5481
5482        Material m;//= RandomMaterial();
5483
5484        for (vit = sampleMap.begin(); vit != vit_end; ++ vit)
5485        {
5486                ViewCell *vc = (*vit).first;
5487               
5488                const int pvsVc = mViewCellsTree->GetPvsEntries(vc);
5489                const int pvsPtSamples = (*vit).second.GetSize();
5490
5491        m.mDiffuseColor.r = (float) (pvsVc - pvsPtSamples);
5492                m.mDiffuseColor.b = 1.0f;
5493                //exporter->SetForcedMaterial(m);
5494                //ExportViewCellGeometry(exporter, vc, mClipPlaneForViz);
5495
5496                /*      // counting the pvss
5497                for (rit = samples.begin(); rit != rit_end; ++ rit)
5498                {
5499                        RenderCostSample sample = *rit;
5500                        ViewCell *vc = GetViewCell(sample.mPosition);
5501
5502                        AxisAlignedBox3 box(sample.mPosition - Vector3(1, 1, 1), sample.mPosition + Vector3(1, 1, 1));
5503                        Mesh *hMesh = CreateMeshFromBox(box);
5504
5505                        DEL_PTR(hMesh);
5506                }
5507                */
5508        }
5509}
5510
5511
5512void VspBspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
5513                                                                                                        ViewCell *vc,
5514                                                                                                        const AxisAlignedBox3 *sceneBox,
5515                                                                                                        const AxisAlignedPlane *clipPlane
5516                                                                                                        ) const
5517{
5518        if (clipPlane)
5519        {
5520                const Plane3 plane = clipPlane->GetPlane();
5521
5522                ViewCellContainer leaves;
5523                mViewCellsTree->CollectLeaves(vc, leaves);
5524                ViewCellContainer::const_iterator it, it_end = leaves.end();
5525
5526                for (it = leaves.begin(); it != it_end; ++ it)
5527                {
5528                        BspNodeGeometry geom;
5529                        BspNodeGeometry front;
5530                        BspNodeGeometry back;
5531
5532                        mVspBspTree->ConstructGeometry(*it, geom);
5533
5534                        const float eps = 0.0001f;
5535                        const int cf = geom.Side(plane, eps);
5536
5537                        if (cf == -1)
5538                        {
5539                                exporter->ExportPolygons(geom.GetPolys());
5540                        }
5541                        else if (cf == 0)
5542                        {
5543                                geom.SplitGeometry(front,
5544                                                                   back,
5545                                                                   plane,
5546                                                                   mViewSpaceBox,
5547                                                                   eps);
5548
5549                                if (back.Valid())
5550                                {
5551                                        exporter->ExportPolygons(back.GetPolys());
5552                                }                       
5553                        }
5554                }
5555        }
5556        else
5557        {
5558                // export mesh if available
5559                // TODO: some bug here?
5560                if (1 && vc->GetMesh())
5561                {
5562                        exporter->ExportMesh(vc->GetMesh());
5563                }
5564                else
5565                {
5566                        BspNodeGeometry geom;
5567                        mVspBspTree->ConstructGeometry(vc, geom);
5568                        exporter->ExportPolygons(geom.GetPolys());
5569                }
5570        }
5571}
5572
5573
5574int VspBspViewCellsManager::GetMaxTreeDiff(ViewCell *vc) const
5575{
5576        ViewCellContainer leaves;
5577        mViewCellsTree->CollectLeaves(vc, leaves);
5578
5579        int maxDist = 0;
5580       
5581        // compute max height difference
5582        for (int i = 0; i < (int)leaves.size(); ++ i)
5583        {
5584                for (int j = 0; j < (int)leaves.size(); ++ j)
5585                {
5586                        BspLeaf *leaf = static_cast<BspViewCell *>(leaves[i])->mLeaves[0];
5587
5588                        if (i != j)
5589                        {
5590                                BspLeaf *leaf2 =static_cast<BspViewCell *>(leaves[j])->mLeaves[0];
5591                                const int dist = mVspBspTree->TreeDistance(leaf, leaf2);
5592                               
5593                                if (dist > maxDist)
5594                                        maxDist = dist;
5595                        }
5596                }
5597        }
5598
5599        return maxDist;
5600}
5601
5602
5603ViewCell *VspBspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
5604{
5605        if (!ViewCellsConstructed())
5606                return NULL;
5607
5608        if (!mViewSpaceBox.IsInside(point))
5609          return NULL;
5610
5611        return mVspBspTree->GetViewCell(point, active);
5612}
5613
5614
5615void VspBspViewCellsManager::CreateMesh(ViewCell *vc)
5616{
5617        BspNodeGeometry geom;
5618        mVspBspTree->ConstructGeometry(vc, geom);
5619       
5620        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
5621       
5622        IncludeNodeGeomInMesh(geom, *mesh);
5623        mesh->ComputeBoundingBox();
5624
5625        vc->SetMesh(mesh);
5626}
5627
5628
5629int VspBspViewCellsManager::CastBeam(Beam &beam)
5630{
5631        return mVspBspTree->CastBeam(beam);
5632}
5633
5634
5635void VspBspViewCellsManager::Finalize(ViewCell *viewCell,
5636                                                                          const bool createMesh)
5637{
5638        float area = 0;
5639        float volume = 0;
5640
5641        ViewCellContainer leaves;
5642        mViewCellsTree->CollectLeaves(viewCell, leaves);
5643
5644        ViewCellContainer::const_iterator it, it_end = leaves.end();
5645
5646    for (it = leaves.begin(); it != it_end; ++ it)
5647        {
5648                BspNodeGeometry geom;
5649                mVspBspTree->ConstructGeometry(*it, geom);
5650
5651                const float lVol = geom.GetVolume();
5652                const float lArea = geom.GetArea();
5653
5654                area += lArea;
5655                volume += lVol;
5656
5657                if (createMesh)
5658                        CreateMesh(*it);
5659        }
5660
5661        viewCell->SetVolume(volume);
5662        viewCell->SetArea(area);
5663}
5664
5665
5666void VspBspViewCellsManager::TestSubdivision()
5667{
5668        ViewCellContainer leaves;
5669        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
5670
5671        ViewCellContainer::const_iterator it, it_end = leaves.end();
5672
5673        const float vol = mViewSpaceBox.GetVolume();
5674        float subdivVol = 0;
5675        float newVol = 0;
5676
5677        for (it = leaves.begin(); it != it_end; ++ it)
5678        {
5679                BspNodeGeometry geom;
5680                mVspBspTree->ConstructGeometry(*it, geom);
5681
5682                const float lVol = geom.GetVolume();
5683               
5684                newVol += lVol;
5685                subdivVol += (*it)->GetVolume();
5686               
5687                float thres = 0.9f;
5688                if ((lVol < ((*it)->GetVolume() * thres)) || (lVol * thres > ((*it)->GetVolume())))
5689                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
5690        }
5691       
5692        Debug << "exact volume: " << vol << endl;
5693        Debug << "subdivision volume: " << subdivVol << endl;
5694        Debug << "new volume: " << newVol << endl;
5695}
5696
5697
5698void VspBspViewCellsManager::PrepareLoadedViewCells()
5699{
5700        // TODO: do I still need this here?
5701        if (0) mVspBspTree->RepairViewCellsLeafLists();
5702}
5703
5704
5705
5706/************************************************************************/
5707/*                 VspOspViewCellsManager implementation                */
5708/************************************************************************/
5709
5710
5711VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree,
5712                                                                                           const string &hierarchyType)
5713: ViewCellsManager(vcTree)
5714{
5715        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
5716        Environment::GetSingleton()->GetBoolValue("ViewCells.compressObjects", mCompressObjects);
5717
5718        Debug << "compressing objects: " << mCompressObjects << endl;
5719        cout << "compressing objects: " << mCompressObjects << endl;
5720
5721        mHierarchyManager = CreateHierarchyManager(hierarchyType);
5722
5723        mHierarchyManager->SetViewCellsManager(this);
5724        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
5725}
5726
5727
5728VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm)
5729: ViewCellsManager(vcTree), mHierarchyManager(hm)
5730{
5731        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
5732        Environment::GetSingleton()->GetBoolValue("ViewCells.compressObjects", mCompressObjects);
5733
5734        Debug << "compressing objects: " << mCompressObjects << endl;
5735        cout << "compressing objects: " << mCompressObjects << endl;
5736
5737        mHierarchyManager->SetViewCellsManager(this);
5738        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
5739}
5740
5741
5742Intersectable *VspOspViewCellsManager::GetIntersectable(const VssRay &ray,
5743                                                                                                                const bool isTermination) const
5744{
5745        if (mUseKdPvs)
5746          return ViewCellsManager::GetIntersectable(ray, isTermination);
5747        else
5748          return mHierarchyManager->GetIntersectable(ray, isTermination);
5749}
5750
5751
5752HierarchyManager *VspOspViewCellsManager::CreateHierarchyManager(const string &hierarchyType)
5753{
5754        HierarchyManager *hierarchyManager;
5755
5756        if (strcmp(hierarchyType.c_str(), "osp") == 0)
5757        {
5758                Debug << "hierarchy manager: osp" << endl;
5759                hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
5760        }
5761        else if (strcmp(hierarchyType.c_str(), "bvh") == 0)
5762        {
5763                Debug << "hierarchy manager: bvh" << endl;
5764                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
5765        }
5766        else // only view space partition
5767        {
5768                Debug << "hierarchy manager: obj" << endl;
5769                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
5770        }
5771
5772        return hierarchyManager;
5773}
5774
5775
5776VspOspViewCellsManager::~VspOspViewCellsManager()
5777{
5778        DEL_PTR(mHierarchyManager);
5779}
5780
5781
5782float VspOspViewCellsManager::GetProbability(ViewCell *viewCell)
5783{
5784        return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
5785}
5786
5787
5788void VspOspViewCellsManager::CollectViewCells()
5789{
5790        // view cells tree constructed
5791        if (!ViewCellsTreeConstructed())
5792        {
5793                mHierarchyManager->GetVspTree()->CollectViewCells(mViewCells, false);
5794        }
5795        else
5796        {       // we can use the view cells tree hierarchy to get the right set
5797                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
5798        }
5799}
5800
5801
5802bool VspOspViewCellsManager::ViewCellsConstructed() const
5803{
5804        return mHierarchyManager->GetVspTree()->GetRoot() != NULL;
5805}
5806
5807
5808ViewCell *VspOspViewCellsManager::GenerateViewCell(Mesh *mesh) const
5809{
5810        return new VspViewCell(mesh);
5811}
5812
5813
5814int VspOspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
5815                                                                                                 const VssRayContainer &rays)
5816{
5817        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
5818
5819        // skip rest if view cells were already constructed
5820        if (ViewCellsConstructed())
5821                return 0;
5822
5823        int sampleContributions = 0;
5824        VssRayContainer sampleRays;
5825
5826        int limit = min (mInitialSamples, (int)rays.size());
5827
5828        VssRayContainer constructionRays;
5829        VssRayContainer savedRays;
5830
5831        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
5832                  << ", actual rays: " << (int)rays.size() << endl;
5833
5834        GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
5835
5836        Debug << "initial rays used for construction: " << (int)constructionRays.size() << endl;
5837        Debug << "saved rays: " << (int)savedRays.size() << endl;
5838
5839        mHierarchyManager->Construct(constructionRays, objects, &mViewSpaceBox);
5840
5841#if TEST_EVALUATION
5842        VssRayContainer::const_iterator tit, tit_end = constructionRays.end();
5843        for (tit = constructionRays.begin(); tit != tit_end; ++ tit)
5844        {
5845                storedRays.push_back(new VssRay(*(*tit)));
5846        }
5847#endif
5848
5849        /////////////////////////
5850        //-- print satistics for subdivision and view cells
5851
5852        Debug << endl << endl << *mHierarchyManager << endl;
5853
5854        ResetViewCells();
5855        //Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
5856
5857        //////////////
5858        //-- recast rest of rays
5859       
5860        const long startTime = GetTime();
5861        cout << "Computing remaining ray contributions ... ";
5862
5863        if (SAMPLE_AFTER_SUBDIVISION)
5864                ComputeSampleContributions(savedRays, true, false);
5865
5866        Debug << "finished computing remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
5867                  << " secs" << endl;
5868
5869        if (0)
5870        {       
5871                // real meshes are constructed at this stage
5872                cout << "finalizing view cells ... ";
5873        FinalizeViewCells(true);
5874                cout << "finished" << endl;
5875        }
5876
5877        return sampleContributions;
5878}
5879
5880
5881int VspOspViewCellsManager::PostProcess(const ObjectContainer &objects,
5882                                                                                const VssRayContainer &rays)
5883{
5884        if (!ViewCellsConstructed())
5885        {
5886                Debug << "post process error: no view cells constructed" << endl;
5887                return 0;
5888        }
5889
5890        // if view cells were already constructed before post processing step
5891        // (e.g., because they were loaded), we are finished
5892        if (mViewCellsFinished)
5893        {
5894                FinalizeViewCells(true);
5895                EvaluateViewCellsStats();
5896
5897                return 0;
5898        }
5899
5900        // check if new view cells turned invalid
5901        int minPvs, maxPvs;
5902
5903        if (0)
5904        {
5905                minPvs = mMinPvsSize;
5906                maxPvs = mMaxPvsSize;
5907        }
5908        else
5909        {
5910                // problem matt: why did I start here from zero?
5911                minPvs = 0;
5912                maxPvs = mMaxPvsSize;
5913        }
5914
5915        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5916        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5917       
5918        SetValidity(minPvs, maxPvs);
5919
5920       
5921        // area is not up to date, has to be recomputed
5922        mTotalAreaValid = false;
5923        VssRayContainer postProcessRays;
5924        GetRaySets(rays, mPostProcessSamples, postProcessRays);
5925
5926        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
5927
5928
5929        // compute tree by merging the nodes of the spatial hierarchy
5930        ViewCell *root = ConstructSpatialMergeTree(mHierarchyManager->GetVspTree()->GetRoot());
5931        mViewCellsTree->SetRoot(root);
5932
5933        //////////////////////////
5934        //-- update pvs up to the root of the hierarchy
5935
5936        ObjectPvs pvs;
5937        UpdatePvsForEvaluation(root, pvs);
5938
5939
5940        //////////////////////
5941        //-- render simulation after merge + refine
5942
5943        cout << "\nview cells partition render time before compress" << endl << endl;
5944        static_cast<RenderSimulator *>(mRenderer)->RenderScene();
5945        SimulationStatistics ss;
5946        static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
5947        cout << ss << endl;
5948       
5949
5950        mHierarchyManager->CreateUniqueObjectIds();
5951
5952        ///////////
5953        //-- compression
5954
5955        if (0) CompressViewCells();
5956
5957        /////////////
5958        //-- some tasks still to do on the view cells:
5959        //-- Compute meshes from view cell geometry, evaluate volume and / or area
5960
5961        if (1) FinalizeViewCells(true);
5962
5963        return 0;
5964}
5965
5966
5967int VspOspViewCellsManager::GetType() const
5968{
5969        return VSP_OSP;
5970}
5971
5972
5973ViewCell *VspOspViewCellsManager::ConstructSpatialMergeTree(VspNode *root)
5974{
5975        // terminate recursion
5976        if (root->IsLeaf())
5977        {
5978                VspLeaf *leaf = static_cast<VspLeaf *>(root);
5979                leaf->GetViewCell()->SetMergeCost(0.0f);
5980                return leaf->GetViewCell();
5981        }
5982       
5983        VspInterior *interior = static_cast<VspInterior *>(root);
5984        ViewCellInterior *viewCellInterior = new ViewCellInterior();
5985               
5986        // evaluate merge cost for priority traversal
5987        const float mergeCost = -(float)root->mTimeStamp;
5988        viewCellInterior->SetMergeCost(mergeCost);
5989
5990        float volume = 0;
5991       
5992        VspNode *front = interior->GetFront();
5993        VspNode *back = interior->GetBack();
5994
5995        ObjectPvs frontPvs, backPvs;
5996
5997        /////////
5998        //-- recursivly compute child hierarchies
5999
6000        ViewCell *backVc = ConstructSpatialMergeTree(back);
6001        ViewCell *frontVc = ConstructSpatialMergeTree(front);
6002
6003        viewCellInterior->SetupChildLink(backVc);
6004        viewCellInterior->SetupChildLink(frontVc);
6005
6006        volume += backVc->GetVolume();
6007        volume += frontVc->GetVolume();
6008
6009        viewCellInterior->SetVolume(volume);
6010
6011        return viewCellInterior;
6012}
6013
6014
6015bool VspOspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
6016{
6017        if (!ViewCellsConstructed())
6018                return ViewCellsManager::GetViewPoint(viewPoint);
6019
6020        // TODO: set reasonable limit
6021        const int limit = 20;
6022
6023        for (int i = 0; i < limit; ++ i)
6024        {
6025                viewPoint = mViewSpaceBox.GetRandomPoint();
6026
6027                if (mHierarchyManager->GetVspTree()->ViewPointValid(viewPoint))
6028                {
6029                        return true;
6030                }
6031        }
6032
6033        Debug << "failed to find valid view point, taking " << viewPoint << endl;
6034        return false;
6035}
6036
6037
6038void VspOspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
6039                                                                                                        ViewCell *vc,
6040                                                                                                        const AxisAlignedBox3 *sceneBox,
6041                                                                                                        const AxisAlignedPlane *clipPlane
6042                                                                                                        ) const
6043{
6044        Plane3 plane;
6045        if (clipPlane)
6046        {
6047                // arbitrary plane definition
6048                plane = clipPlane->GetPlane();
6049        }
6050
6051        ViewCellContainer leaves;
6052        mViewCellsTree->CollectLeaves(vc, leaves);
6053
6054        ViewCellContainer::const_iterator it, it_end = leaves.end();
6055
6056        for (it = leaves.begin(); it != it_end; ++ it)
6057        {
6058                VspViewCell *vspVc = static_cast<VspViewCell *>(*it);
6059                VspLeaf *l = vspVc->mLeaves[0];
6060
6061                const AxisAlignedBox3 box =
6062                        mHierarchyManager->GetVspTree()->GetBoundingBox(vspVc->mLeaves[0]);
6063               
6064                if (sceneBox && !Overlap(*sceneBox, box))
6065                        continue;
6066
6067                if (clipPlane)
6068                {
6069                        if (box.Side(plane) == -1)
6070                        {
6071                                exporter->ExportBox(box);
6072                        }
6073                        else if (box.Side(plane) == 0)
6074                        {
6075                                // intersection
6076                                AxisAlignedBox3 fbox, bbox;
6077                                box.Split(clipPlane->mAxis, clipPlane->mPosition, fbox, bbox);
6078                                exporter->ExportBox(bbox);
6079                        }
6080                }
6081                else
6082                {
6083                        exporter->ExportBox(box);
6084                }
6085        }
6086}
6087
6088
6089bool VspOspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
6090{
6091  // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
6092  // validy update in preprocessor for all managers)
6093  return ViewCellsManager::ViewPointValid(viewPoint);
6094
6095  //    return mViewSpaceBox.IsInside(viewPoint) &&
6096  //               mVspTree->ViewPointValid(viewPoint);
6097}
6098
6099
6100float VspOspViewCellsManager::UpdateObjectCosts()
6101{
6102        float maxRenderCost = 0;
6103
6104        cout << "updating object pvs cost ... ";
6105        const long startTime = GetTime();
6106
6107        ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
6108
6109        Intersectable::NewMail();
6110
6111        const float invViewSpaceVol = 1.0f / GetViewSpaceBox().GetVolume();
6112
6113        for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
6114        {
6115                ViewCell *vc = *vit;
6116
6117                ObjectPvsIterator pit = vc->GetPvs().GetIterator();
6118
6119                // output PVS of view cell
6120                while (pit.HasMoreEntries())
6121                {               
6122                        Intersectable *obj = pit.Next();
6123                               
6124                        BvhNode *node = static_cast<BvhNode *>(obj);
6125                       
6126                        // hack!!
6127                        if (!node->IsLeaf())
6128                        {
6129                                cout << "error, can only process leaves" << endl;
6130                                return 0;
6131                        }
6132       
6133                        if (!node->Mailed())
6134                        {
6135                                node->Mail();
6136                                node->mRenderCost = 0;
6137                        }
6138
6139                        const float rc = (float)((BvhLeaf *)node)->mObjects.size();
6140
6141                        node->mRenderCost += rc * vc->GetVolume() * invViewSpaceVol;
6142
6143                        if (node->mRenderCost > maxRenderCost)
6144                                maxRenderCost = node->mRenderCost;
6145                }
6146        }
6147
6148        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
6149
6150        return maxRenderCost;
6151}
6152
6153
6154void VspOspViewCellsManager::Visualize(const ObjectContainer &objects,
6155                                                                           const VssRayContainer &sampleRays)
6156{
6157        if (!ViewCellsConstructed())
6158                return;
6159
6160        VssRayContainer visRays;
6161        GetRaySets(sampleRays, mVisualizationSamples, visRays);
6162
6163        ////////////
6164        //-- export final view cells
6165
6166        Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
6167
6168        Vector3 scale(0.9f, 0.9f, 0.9f);
6169        //Vector3 scale(1.0f, 1.0f, 1.0f);
6170
6171        if (exporter)
6172        {
6173                // clamp to a scene boudning box
6174                if (CLAMP_TO_BOX)
6175                        exporter->mClampToBox = true;   
6176               
6177                const long starttime = GetTime();
6178                cout << "exporting final view cells (after initial construction + post process) ... " << endl;
6179
6180                // matt: hack for clamping scene
6181                AxisAlignedBox3 bbox = mViewSpaceBox;
6182                bbox.Scale(scale);
6183
6184                if (1 && mExportRays)
6185                {       
6186                        exporter->ExportRays(visRays, RgbColor(0, 1, 0));
6187                }
6188
6189                // hack color code
6190                const int savedColorCode = mColorCode;
6191
6192                EvaluateViewCellsStats();
6193                const int colorCode = 0;
6194
6195                const float maxRenderCost = -1;//UpdateObjectCosts();
6196                const bool exportBounds = false;
6197
6198                //cout << "maxRenderCost: " << maxRenderCost << endl;
6199                if (1)
6200                mHierarchyManager->ExportObjectSpaceHierarchy(exporter,
6201                                                                                                          objects,
6202                                                                                                          CLAMP_TO_BOX ? &bbox : NULL,
6203                                                                                                          maxRenderCost,
6204                                                                                                          exportBounds);
6205               
6206                //ExportViewCellsForViz(exporter, CLAMP_TO_BOX ? &bbox : NULL, mColorCode, GetClipPlane());
6207                ExportViewCellsForViz(exporter, NULL, colorCode, GetClipPlane());
6208               
6209                delete exporter;
6210
6211                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
6212        }
6213
6214        if (1)
6215        {
6216                exporter = Exporter::GetExporter("final_object_partition.wrl");
6217
6218                if (exporter)
6219                {
6220                        if (CLAMP_TO_BOX)
6221                        {       
6222                                exporter->mClampToBox = true;   
6223                        }
6224
6225                        const long starttime = GetTime();
6226                        cout << "exporting final objects (after initial construction + post process) ... ";
6227
6228                        // matt: hack for clamping scene
6229                        AxisAlignedBox3 bbox = mViewSpaceBox;
6230                        bbox.Scale(scale);
6231
6232                        // hack color code (show pvs size)
6233                        const int savedColorCode = mColorCode;
6234
6235                        EvaluateViewCellsStats();
6236                        mColorCode = 1; // 0 = random, 1 = export pvs
6237
6238                        // don't visualize render cost
6239                        const float maxRenderCost = -1;
6240                        //const bool exportBounds = true;
6241                        const bool exportBounds = false;
6242
6243                        mHierarchyManager->ExportObjectSpaceHierarchy(exporter,
6244                                                                      objects,
6245                                                                                                                  CLAMP_TO_BOX ? &bbox : NULL,
6246                                                                                                                  maxRenderCost,
6247                                                                                                                  exportBounds);
6248
6249
6250                        delete exporter;
6251
6252                        cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
6253                        mColorCode = savedColorCode;
6254                }
6255        }
6256
6257        // export some view cells
6258        int leafOut;
6259        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
6260
6261        const bool sortViewCells = false;
6262        const bool exportPvs = true;
6263        const bool exportRays = true;
6264        const int raysOut = 100;
6265
6266        ExportSingleViewCells(objects,
6267                                                  leafOut,
6268                                                  sortViewCells,
6269                                                  exportPvs,
6270                                                  exportRays,
6271                                                  raysOut,
6272                                                  "");
6273}
6274
6275
6276void VspOspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
6277                                                                                                   const int maxViewCells,
6278                                                                                                   const bool sortViewCells,
6279                                                                                                   const bool exportPvs,
6280                                                                                                   const bool exportRays,
6281                                                                                                   const int maxRays,
6282                                                                                                   const string &prefix,
6283                                                                                                   VssRayContainer *visRays)
6284{
6285        if (sortViewCells)
6286        {
6287                // sort view cells to visualize the view cells with highest render cost
6288                sort(mViewCells.begin(), mViewCells.end(), LargerRenderCost);
6289        }
6290
6291        ViewCell::NewMail();
6292        const int limit = min(maxViewCells, (int)mViewCells.size());
6293       
6294        cout << "\nExporting " << limit << " single view cells: " << endl;
6295       
6296        for (int i = 0; i < limit; ++ i)
6297        {
6298                cout << "creating output for view cell " << i << " ... ";
6299               
6300                // largest view cell pvs first of random view cell
6301                ViewCell *vc = sortViewCells ?
6302                        mViewCells[i] : mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 1)];
6303               
6304                if (vc->Mailed()) // view cell already processed
6305                        continue;
6306
6307                vc->Mail();
6308
6309                ObjectPvs pvs;
6310                mViewCellsTree->GetPvs(vc, pvs);
6311
6312                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
6313                Exporter *exporter = Exporter::GetExporter(s);
6314               
6315                cout << "view cell " << vc->GetId() << ": pvs cost=" << mViewCellsTree->GetTrianglesInPvs(vc) << endl;
6316
6317                if (exportPvs)
6318                {
6319                        Material m;
6320                        Intersectable::NewMail();
6321                       
6322                        ObjectPvsIterator pit = pvs.GetIterator();
6323
6324                        // output PVS of view cell
6325                        while (pit.HasMoreEntries())
6326                        {               
6327                                Intersectable *intersect = pit.Next();
6328                               
6329                                if (!intersect->Mailed())
6330                                {
6331                                        m = RandomMaterial();
6332                                        exporter->SetForcedMaterial(m);
6333
6334                                        exporter->ExportIntersectable(intersect);
6335                                        intersect->Mail();
6336                                }
6337                        }
6338                }
6339
6340                if (exportRays)
6341                {
6342                        ////////////
6343                        //-- export the sample rays
6344
6345                        // output rays stored with the view cells during subdivision
6346                        VssRayContainer vcRays;
6347                        VssRayContainer collectRays;
6348
6349                        // collect intial view cells
6350                        ViewCellContainer leaves;
6351                        mViewCellsTree->CollectLeaves(vc, leaves);
6352
6353                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
6354
6355                        for (vit = leaves.begin(); vit != vit_end; ++ vit)
6356                        {
6357                                VspLeaf *vcLeaf = static_cast<VspViewCell *>(*vit)->mLeaves[0];
6358                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
6359
6360                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
6361                                {
6362                                        collectRays.push_back(*rit);
6363                                }
6364                        }
6365
6366                        const int raysOut = min((int)collectRays.size(), maxRays);
6367
6368                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
6369
6370                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
6371                        {
6372                                const float p = RandomValue(0.0f, (float)collectRays.size());
6373
6374                                if (p < raysOut)
6375                                        vcRays.push_back(*rit);
6376                        }
6377
6378                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
6379                }
6380               
6381       
6382                /////////////////
6383                //-- export view cell geometry
6384
6385                exporter->SetWireframe();
6386
6387                Material m;
6388                m.mDiffuseColor = RgbColor(0, 1, 0);
6389                exporter->SetForcedMaterial(m);
6390
6391                ExportViewCellGeometry(exporter, vc, NULL, NULL);
6392                exporter->SetFilled();
6393
6394                DEL_PTR(exporter);
6395                cout << "finished" << endl;
6396        }
6397
6398        cout << endl;
6399}
6400
6401
6402int VspOspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
6403                                                                                                        ViewCellContainer &viewCells) const
6404{
6405        return mHierarchyManager->GetVspTree()->ComputeBoxIntersections(box, viewCells);
6406}
6407
6408
6409int VspOspViewCellsManager::CastLineSegment(const Vector3 &origin,
6410                                                                                        const Vector3 &termination,
6411                                                                                        ViewCellContainer &viewcells)
6412{
6413        return mHierarchyManager->CastLineSegment(origin, termination, viewcells);
6414}
6415
6416
6417bool VspOspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
6418                                                                                                   const Vector3 &termination,
6419                                                                                                   ViewCell *viewCell)
6420{
6421        return false;
6422}
6423
6424
6425bool VspOspViewCellsManager::ExportViewCells(const string filename,
6426                                                                                         const bool exportPvs,
6427                                                                                         const ObjectContainer &objects)
6428{
6429        // no view cells were computed
6430        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
6431                return false;
6432
6433        if (strstr(filename.c_str(), ".bn"))
6434        {
6435                return ExportViewCellsBinary(filename, exportPvs, objects);
6436        }
6437
6438        //cout << "exporting binary" << endl; string fname("test.vc"); return ExportViewCellsBinary(fname, exportPvs, objects);
6439
6440        const long starttime = GetTime();
6441        cout << "exporting view cells to xml ... ";
6442       
6443        OUT_STREAM stream(filename.c_str());
6444
6445        // we need unique ids for each view cell
6446        CreateUniqueViewCellIds();
6447
6448        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
6449        stream << "<VisibilitySolution>" << endl;
6450
6451        if (exportPvs)
6452        {
6453        ///////////////
6454                //-- export bounding boxes
6455                //-- we need the boxes to identify objects in the target engine
6456
6457                if (mUseKdPvs)
6458                {
6459                        stream << "<BoundingBoxes>" << endl;
6460
6461                        int id = 0;
6462                        vector<KdIntersectable *>::const_iterator kit, kit_end = mPreprocessor->mKdTree->mKdIntersectables.end();
6463                       
6464                        for (kit = mPreprocessor->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
6465                        {
6466                                Intersectable *obj = (*kit);
6467                                const AxisAlignedBox3 box = obj->GetBox();
6468
6469                                // set kd node id
6470                                obj->SetId(id);
6471
6472                                stream << "<BoundingBox" << " id=\"" << id << "\""
6473                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
6474                                       << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
6475                        }
6476
6477                        stream << "</BoundingBoxes>" << endl;
6478                }
6479                else
6480                {
6481                        mHierarchyManager->ExportBoundingBoxes(stream, objects);
6482                }
6483        }
6484
6485
6486        //////////////////////////
6487        //-- export the view cells and the pvs
6488
6489        const int numViewCells = mCurrentViewCellsStats.viewCells;
6490
6491        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
6492        mViewCellsTree->Export(stream, exportPvs);
6493        stream << "</ViewCells>" << endl;
6494
6495
6496        /////////////////
6497        //-- export the view space hierarchy
6498       
6499        stream << "<ViewSpaceHierarchy type=\"vsp\""
6500                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
6501                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
6502
6503        mHierarchyManager->GetVspTree()->Export(stream);
6504        stream << "</ViewSpaceHierarchy>" << endl;
6505
6506        /////////////////
6507        //-- export the object space hierarchy
6508       
6509        mHierarchyManager->ExportObjectSpaceHierarchy(stream);
6510       
6511        stream << "</VisibilitySolution>" << endl;
6512        stream.close();
6513       
6514        cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3 << " secs" << endl;
6515        return true;
6516}
6517
6518
6519bool VspOspViewCellsManager::ExportViewCellsBinary(const string filename,
6520                                                                                                   const bool exportPvs,
6521                                                                                                   const ObjectContainer &objects)
6522{
6523        // no view cells constructed yet
6524        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
6525                return false;
6526
6527        const long starttime = GetTime();
6528        cout << "exporting view cells to binary format ... ";
6529       
6530        OUT_STREAM stream(filename.c_str());
6531
6532        // we need unique ids for each view cell
6533        CreateUniqueViewCellIds();
6534
6535        int numBoxes = mPreprocessor->mKdTree->mKdIntersectables.size();
6536        stream.write(reinterpret_cast<char *>(&numBoxes), sizeof(int));
6537
6538
6539    ///////////////
6540        //-- export bounding boxes
6541
6542        // we use bounding box intersection to identify pvs objects in the target engine
6543        vector<KdIntersectable *>::const_iterator kit, kit_end = mPreprocessor->mKdTree->mKdIntersectables.end();
6544
6545        int id = 0;
6546
6547        for (kit = mPreprocessor->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
6548        {
6549                Intersectable *obj = (*kit);
6550                // set the kd node id to identify the kd node as a pvs entry
6551                obj->SetId(id);
6552
6553                const AxisAlignedBox3 &box = obj->GetBox();
6554                Vector3 bmin = box.Min();
6555                Vector3 bmax = box.Max();
6556
6557                stream.write(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
6558                stream.write(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
6559                stream.write(reinterpret_cast<char *>(&id), sizeof(int));
6560        }
6561
6562        cout << "written " << numBoxes << " kd nodes" << endl;
6563
6564        ///////////////
6565        //-- export the view cells and the pvs
6566
6567        int numViewCells = mViewCells.size();
6568        stream.write(reinterpret_cast<char *>(&numViewCells), sizeof(int));
6569
6570        Vector3 vmin = mViewSpaceBox.Min();
6571        Vector3 vmax = mViewSpaceBox.Max();
6572
6573        stream.write(reinterpret_cast<char *>(&vmin), sizeof(Vector3));
6574        stream.write(reinterpret_cast<char *>(&vmax), sizeof(Vector3));
6575
6576
6577        //////////
6578        //-- export binary view cells
6579
6580        mViewCellsTree->ExportBinary(stream);
6581
6582
6583        /////////
6584        //-- export the view space hierarchy
6585       
6586        mHierarchyManager->GetVspTree()->ExportBinary(stream);
6587       
6588
6589        ////////
6590        //-- export the object space hierarchy
6591
6592        //mHierarchyManager->ExportObjectSpaceHierarchyBinary();
6593   
6594        stream.close();
6595       
6596        //mHierarchyManager->GetVspTree()->TestOutput("output.txt");
6597
6598        cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3 << " secs" << endl;
6599        return true;
6600}
6601
6602
6603ViewCell *VspOspViewCellsManager::GetViewCell(const Vector3 &point,
6604                                                                                          const bool active) const
6605{
6606        if (!ViewCellsConstructed())
6607                return NULL;
6608
6609        if (!mViewSpaceBox.IsInside(point))
6610                return NULL;
6611
6612        return mHierarchyManager->GetVspTree()->GetViewCell(point, active);
6613}
6614
6615
6616void VspOspViewCellsManager::CreateMesh(ViewCell *vc)
6617{
6618        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
6619       
6620        ViewCellContainer leaves;
6621        mViewCellsTree->CollectLeaves(vc, leaves);
6622
6623        ViewCellContainer::const_iterator it, it_end = leaves.end();
6624
6625    for (it = leaves.begin(); it != it_end; ++ it)
6626        {
6627                VspLeaf *leaf = static_cast<VspViewCell *>(*it)->mLeaves[0];
6628                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
6629        IncludeBoxInMesh(box, *mesh);
6630        }
6631
6632        mesh->ComputeBoundingBox();
6633
6634        vc->SetMesh(mesh);
6635}
6636
6637
6638int VspOspViewCellsManager::CastBeam(Beam &beam)
6639{
6640        // matt: TODO
6641        return 0;
6642}
6643
6644
6645void VspOspViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
6646{
6647        float area = 0;
6648        float volume = 0;
6649
6650        ViewCellContainer leaves;
6651        mViewCellsTree->CollectLeaves(viewCell, leaves);
6652
6653        ViewCellContainer::const_iterator it, it_end = leaves.end();
6654
6655    for (it = leaves.begin(); it != it_end; ++ it)
6656        {
6657                VspLeaf *leaf = static_cast<VspViewCell *>(*it)->mLeaves[0];
6658               
6659                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
6660
6661                const float lVol = box.GetVolume();
6662                const float lArea = box.SurfaceArea();
6663
6664                area += lArea;
6665                volume += lVol;
6666
6667        CreateMesh(*it);
6668        }
6669
6670        viewCell->SetVolume(volume);
6671        viewCell->SetArea(area);
6672}
6673
6674
6675void VspOspViewCellsManager::PrepareLoadedViewCells()
6676{
6677        // TODO
6678}
6679
6680
6681void VspOspViewCellsManager::PrintCompressionStats(HierarchyManager *hm, const int pvsEntries)
6682{
6683        const float mem = (float)pvsEntries * ObjectPvs::GetEntrySize();
6684               
6685        float fullmem = mem +
6686                        (hm->GetVspTree()->GetStatistics().Leaves() * 16 +
6687                         hm->mBvHierarchy->GetStatistics().Leaves() * 16) / float(1024 * 1024);
6688
6689        cout << "entries: " << pvsEntries << ", mem=" << mem << ", fullmem=" << fullmem <<endl;
6690        Debug << "entries: " << pvsEntries << ", mem=" << mem << ", fullmem=" << fullmem <<endl;
6691}
6692
6693
6694void VspOspViewCellsManager::CompressViewCells()
6695{
6696        if (!(ViewCellsTreeConstructed() && mCompressViewCells))
6697                return;
6698
6699
6700        ////////////
6701        //-- compression
6702
6703        int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
6704
6705        cout << "before compression: " << endl;
6706        Debug << "before compression: " << endl;
6707       
6708        PrintCompressionStats(mHierarchyManager, pvsEntries);
6709
6710        if (mCompressObjects)
6711        {
6712                cout << "compressing in the objects: " << endl;
6713                Debug << "compressing in the objects: " << endl;
6714
6715                pvsEntries = mHierarchyManager->CompressObjectSpace();
6716        }
6717        else
6718        {
6719                cout << "compressing in the view space: " << endl;
6720                Debug << "compressing in the view space: " << endl;
6721
6722                mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
6723                pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
6724        }
6725
6726        PrintCompressionStats(mHierarchyManager, pvsEntries);
6727}
6728
6729
6730void VspOspViewCellsManager::CollectObjects(const AxisAlignedBox3 &box,
6731                                                                                        ObjectContainer &objects)
6732{
6733        mHierarchyManager->CollectObjects(box, objects);
6734}
6735
6736
6737void VspOspViewCellsManager::EvalViewCellPartition()
6738{
6739        int samplesPerPass;
6740        int castSamples = 0;
6741        int oldSamples = 0;
6742        int samplesForStats;
6743        char statsPrefix[100];
6744        char suffix[100];
6745        int splitsStepSize;
6746
6747        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
6748        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesForStats", samplesForStats);
6749        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", mEvaluationSamples);
6750        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
6751        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.stepSize", splitsStepSize);
6752       
6753        bool useHisto;
6754        int histoMem;
6755
6756        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
6757        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoMem", histoMem);
6758
6759        Debug << "step size: " << splitsStepSize << endl;
6760        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
6761        Debug << "view cell evaluation samples: " << mEvaluationSamples << endl;
6762        Debug << "view cell stats prefix: " << statsPrefix << endl;
6763
6764    cout << "reseting pvs ... ";
6765               
6766        // reset pvs and start over from zero
6767        mViewCellsTree->ResetPvs();
6768       
6769        cout << "finished" << endl;
6770    cout << "Evaluating view cell partition ... " << endl;
6771
6772        int pass = 0;
6773
6774        while (castSamples < mEvaluationSamples)
6775        {               
6776                ///////////////
6777                //-- we have to use uniform sampling strategy for construction rays
6778
6779                VssRayContainer evaluationSamples;
6780                const int samplingType = mEvaluationSamplingType;
6781
6782                long startTime = GetTime();
6783                Real timeDiff;
6784
6785                cout << "casting " << samplesPerPass << " samples ... ";
6786                Debug << "casting " << samplesPerPass << " samples ... ";
6787       
6788                // use mixed distributions
6789                CastEvaluationSamples(samplesPerPass, evaluationSamples);
6790
6791                timeDiff = TimeDiff(startTime, GetTime());
6792                cout << "finished in " << timeDiff * 1e-3f << " secs" << endl;
6793                Debug << "finished in " << timeDiff * 1e-3f << " secs" << endl;
6794               
6795                // don't computed sample contributions
6796                // because already accounted for inside the mixture distribution!
6797               
6798                castSamples += samplesPerPass;
6799
6800                if ((castSamples >= samplesForStats + oldSamples) ||
6801                        (castSamples >= mEvaluationSamples))
6802                {
6803                        oldSamples += samplesForStats;
6804
6805                        ///////////
6806                        //-- output stats
6807
6808                        sprintf(suffix, "-%09d-eval.log", castSamples);
6809                        const string filename = string(statsPrefix) + string(suffix);
6810
6811                        startTime = GetTime();
6812                       
6813                        cout << "compute new statistics ... " << endl;
6814
6815                        ofstream ofstr(filename.c_str());
6816                        mHierarchyManager->EvaluateSubdivision(ofstr, splitsStepSize, false, useHisto, histoMem, pass);
6817
6818                        timeDiff = TimeDiff(startTime, GetTime());
6819                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6820                        cout << "*************************************" << endl;
6821
6822                        Debug << "statistics computed in " << timeDiff * 1e-3 << " secs" << endl;
6823
6824                        ++ pass;
6825                }
6826
6827                disposeRays(evaluationSamples, NULL);
6828        }
6829
6830        ////////////
6831        //-- histogram
6832
6833        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
6834        int histoStepSize;
6835
6836        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
6837        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
6838
6839        if (useHisto)
6840        {
6841                // evaluate view cells in a histogram           
6842                char str[64];
6843
6844                // hack: just show final view cells
6845                const int pass = (int)mViewCells.size();
6846
6847                //for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
6848
6849                string filename;
6850
6851                cout << "computing histogram for " << pass << " view cells" << endl;
6852
6853                ///////////////////
6854                //-- evaluate histogram for pvs size
6855
6856                cout << "computing pvs histogram for " << pass << " view cells" << endl;
6857
6858                sprintf(str, "-%09d-histo-pvs2.log", pass);
6859                filename = string(statsPrefix) + string(str);
6860
6861                EvalViewCellHistogramForPvsSize(filename, pass);
6862        }
6863}
6864
6865
6866void VspOspViewCellsManager::FinalizeViewCells(const bool createMesh)
6867{       
6868        ViewCellsManager::FinalizeViewCells(createMesh);
6869
6870        if (mHierarchyManager->mUseTraversalTree)
6871        {       // create a traversal tree for optimal view cell casting
6872                mHierarchyManager->CreateTraversalTree();
6873        }
6874}
6875
6876
6877#if TEST_PACKETS
6878
6879float VspOspViewCellsManager::ComputeSampleContributions(const VssRayContainer &rays,
6880                                                                                                                 const bool addContributions,
6881                                                                                                                 const bool storeViewCells,
6882                                                                                                                 const bool useHitObjects)
6883{
6884        if (!ViewCellsConstructed())
6885                return 0;
6886       
6887        float sum = 0.0f;
6888        VssRayContainer::const_iterator it, it_end = rays.end();
6889
6890        VssRayContainer tmpRays;       
6891
6892        for (it = rays.begin(); it != it_end; ++ it)
6893        {
6894                sum += ComputeSampleContribution(*(*it), addContributions, storeViewCells, useHitObjects);
6895
6896                tmpRays.push_back(new VssRay(*(*it)));
6897               
6898                if (tmpRays.size() == 4)
6899                {
6900                        // cast packets of 4 rays
6901                        RayPacket packet(tmpRays);
6902                        mHierarchyManager->CastLineSegment(packet);
6903               
6904                        for (int i = 0; i < 4; ++ i)
6905                        {
6906                                ComputeSampleContribution(*tmpRays[i], addContributions, true, useHitObjects);
6907                                // compare results
6908                                cout << "ray " << i << ": " << (int)tmpRays[i]->mViewCells.size() << " "
6909                                         << (int)packet.mViewCells[i].size() << endl;
6910                        }
6911                       
6912                        CLEAR_CONTAINER(tmpRays);
6913                }
6914        }
6915       
6916        CLEAR_CONTAINER(tmpRays);
6917
6918#ifdef USE_PERFTIMER 
6919        cout << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
6920        Debug << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
6921        cout << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
6922        Debug << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
6923#endif
6924       
6925        return sum;
6926}
6927
6928#endif
6929
6930
6931ViewCellsManager *
6932ViewCellsManager::LoadViewCellsBinary(const string &filename,
6933                                                                          ObjectContainer &pvsObjects,
6934                                                                          bool finalizeViewCells,
6935                                                                          BoundingBoxConverter *bconverter)                                                                                             
6936{
6937  IN_STREAM stream(filename.c_str());
6938 
6939  if (!stream.is_open())
6940        {
6941                Debug << "View cells loading failed: could not open file" << endl;
6942                return NULL;
6943        }
6944
6945        Debug << "loading boxes" << endl;
6946
6947        const long startTime = GetTime();
6948
6949        // load all the bounding boxes
6950        IndexedBoundingBoxContainer iboxes;
6951        ViewCellsManager::LoadIndexedBoundingBoxesBinary(stream, iboxes);
6952
6953        pvsObjects.reserve(iboxes.size());
6954
6955        if (bconverter)
6956        {
6957                // associate object ids with bounding boxes
6958                bconverter->IdentifyObjects(iboxes, pvsObjects);
6959        }
6960
6961
6962        ObjectContainer pvsLookup;
6963        pvsLookup.resize(iboxes.size());
6964
6965        for (size_t i = 0; i < pvsLookup.size(); ++ i)
6966        {
6967                pvsLookup[i] = NULL;
6968        }
6969
6970        for (size_t i = 0; i < pvsObjects.size(); ++ i)
6971        {
6972                pvsLookup[pvsObjects[i]->GetId()] = pvsObjects[i];
6973        }
6974
6975
6976        /////////////
6977        //-- load the view cells
6978       
6979        int numViewCells;
6980        stream.read(reinterpret_cast<char *>(&numViewCells), sizeof(int));
6981
6982        Debug << "loading " << numViewCells << " view cells " << endl;
6983
6984        Vector3 vmin, vmax;
6985
6986        stream.read(reinterpret_cast<char *>(&vmin), sizeof(Vector3));
6987        stream.read(reinterpret_cast<char *>(&vmax), sizeof(Vector3));
6988
6989        AxisAlignedBox3 viewSpaceBox(vmin, vmax);
6990
6991        Debug << "view space box: " << viewSpaceBox << endl;
6992
6993    ViewCellsTree *vcTree = new ViewCellsTree();
6994
6995        if (!vcTree->ImportBinary(stream, pvsLookup))
6996        {
6997                Debug << "Error: loading view cells tree failed!" << endl;
6998                delete vcTree;
6999       
7000                return NULL;
7001        }
7002
7003        Debug << "loading the view space partition tree" << endl;
7004        VspTree *vspTree = new VspTree(viewSpaceBox);
7005
7006        if (!vspTree->ImportBinary(stream))
7007        {
7008                Debug << "Error: loading vsp tree failed!" << endl;
7009                delete vcTree; delete vspTree;
7010
7011                return NULL;
7012        }
7013
7014
7015        HierarchyManager * hm =
7016                new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
7017
7018        hm->SetVspTree(vspTree);
7019
7020
7021        /////////
7022        //-- create view cells manager
7023       
7024        VspOspViewCellsManager *vm = new VspOspViewCellsManager(vcTree, hm);
7025
7026
7027        //////////////
7028        //-- do some more preparation
7029
7030        vm->mViewSpaceBox = viewSpaceBox;
7031        vm->mViewCells.clear();
7032
7033        ViewCellContainer viewCells;
7034        vcTree->CollectLeaves(vcTree->GetRoot(), viewCells);
7035
7036        ViewCellContainer::const_iterator cit, cit_end = viewCells.end();
7037
7038        for (cit = viewCells.begin(); cit != cit_end; ++ cit)
7039        {
7040                vm->mViewCells.push_back(*cit);
7041        }
7042
7043
7044        //////////////
7045        //-- associate view cells with vsp leaves
7046
7047        vector<VspLeaf *> vspLeaves;
7048        vspTree->CollectLeaves(vspLeaves);
7049
7050        vector<VspLeaf *>::const_iterator vit, vit_end = vspLeaves.end();
7051        cit = viewCells.begin();
7052
7053        for (vit = vspLeaves.begin(); vit != vit_end; ++ vit, ++ cit)
7054        {
7055                VspLeaf *leaf = *vit;
7056                VspViewCell *vc = static_cast<VspViewCell *>(*cit);
7057
7058                leaf->SetViewCell(vc);
7059                vc->mLeaves.push_back(leaf);
7060        }
7061
7062       
7063        /*for (cit = viewCells.begin(); cit != cit_end; ++ cit)
7064        {
7065                Debug << "pvssize: " << (*cit)->GetPvs().GetSize();
7066        }*/
7067
7068
7069        vm->mViewCellsFinished = true;
7070        vm->mMaxPvsSize = (int)pvsObjects.size();
7071
7072        if (finalizeViewCells)
7073        {
7074                // create the meshes and compute view cell volumes
7075                const bool createMeshes = true;
7076                vm->FinalizeViewCells(createMeshes);
7077        }
7078
7079        Debug << (int)vm->mViewCells.size() << " view cells loaded in "
7080                  << TimeDiff(startTime, GetTime()) * 1e-6f << " secs" << endl;
7081
7082        //vspTree->TestOutput("input.txt");
7083
7084        return vm;
7085}
7086
7087
7088ViewCellPointsList *ViewCellsManager::GetViewCellPointsList()
7089{
7090        return mRandomViewCellsHandler->GetViewCellPointsList();
7091}
7092
7093
7094bool ViewCellsManager::ExportRandomViewCells(const string &filename)
7095{
7096        // export ten view cells with 100 random view points inside each
7097        const int numViewCells = 100;
7098        const int numViewPoints = 10;
7099
7100        //cout << "exporting random view cells" << endl;
7101        return mRandomViewCellsHandler->ExportRandomViewCells(filename);
7102}
7103
7104
7105bool ViewCellsManager::ImportViewCellsList(const string &filename)
7106{
7107        return mRandomViewCellsHandler->ImportViewCellsList(filename);
7108}
7109
7110
7111}
Note: See TracBrowser for help on using the repository browser.