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

Revision 1680, 142.6 KB checked in by mattausch, 18 years ago (diff)
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
28// warning: Should not count origin object for sampling because it disturbs heuristics
29#define SAMPLE_ORIGIN_OBJECTS 1  // matt temp
30
31// $$JB HACK
32#define USE_KD_PVS 0
33#define KD_PVS_AREA 1e-3f
34
35namespace GtpVisibilityPreprocessor {
36
37
38// HACK
39const static bool SAMPLE_AFTER_SUBDIVISION = true;
40const static bool CLAMP_TO_BOX = true;
41
42template <typename T> class myless
43{
44public:
45        //bool operator() (HierarchyNode *v1, HierarchyNode *v2) const
46        bool operator() (T v1, T v2) const
47        {
48                return (v1->GetMergeCost() < v2->GetMergeCost());
49        }
50};
51
52
53ViewCellsManager::ViewCellsManager(ViewCellsTree *viewCellsTree):
54mRenderer(NULL),
55mInitialSamples(0),
56mConstructionSamples(0),
57mPostProcessSamples(0),
58mVisualizationSamples(0),
59mTotalAreaValid(false),
60mTotalArea(0.0f),
61mViewCellsFinished(false),
62mMaxPvsSize(9999999),
63mMinPvsSize(0), // one means only empty view cells are invalid
64mMaxPvsRatio(1.0),
65mViewCellPvsIsUpdated(false),
66mPreprocessor(NULL),
67mViewCellsTree(viewCellsTree),
68mUsePredefinedViewCells(false)
69{
70        mViewSpaceBox.Initialize();
71        ParseEnvironment();
72
73        mViewCellsTree->SetViewCellsManager(this);
74        //mViewCellsTree = new ViewCellsTree(this);
75}
76
77
78void ViewCellsManager::ParseEnvironment()
79{
80        // visualization stuff
81        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportRays", mExportRays);
82        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportGeometry", mExportGeometry);
83        Environment::GetSingleton()->GetFloatValue("ViewCells.maxPvsRatio", mMaxPvsRatio);
84       
85        Environment::GetSingleton()->GetBoolValue("ViewCells.processOnlyValidViewCells", mOnlyValidViewCells);
86
87        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samples", mConstructionSamples);
88        Environment::GetSingleton()->GetIntValue("ViewCells.PostProcess.samples", mPostProcessSamples);
89        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.useRaysForMerge", mUseRaysForMerge);
90
91        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.samples", mVisualizationSamples);
92
93        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samplesPerPass", mSamplesPerPass);
94        Environment::GetSingleton()->GetBoolValue("ViewCells.exportToFile", mExportViewCells);
95       
96        Environment::GetSingleton()->GetIntValue("ViewCells.active", mNumActiveViewCells);
97        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.compress", mCompressViewCells);
98        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.useClipPlane", mUseClipPlaneForViz);
99        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.merge", mMergeViewCells);
100        Environment::GetSingleton()->GetBoolValue("ViewCells.evaluateViewCells", mEvaluateViewCells);
101        Environment::GetSingleton()->GetBoolValue("ViewCells.showVisualization", mShowVisualization);
102        Environment::GetSingleton()->GetIntValue("ViewCells.Filter.maxSize", mMaxFilterSize);
103        Environment::GetSingleton()->GetFloatValue("ViewCells.Filter.width", mFilterWidth);
104        Environment::GetSingleton()->GetIntValue("ViewCells.renderCostEvaluationType", mRenderCostEvaluationType);
105
106        Environment::GetSingleton()->GetBoolValue("ViewCells.exportBboxesForPvs", mExportBboxesForPvs);
107        Environment::GetSingleton()->GetBoolValue("ViewCells.exportPvs", mExportPvs);
108       
109        char buf[100];
110        Environment::GetSingleton()->GetStringValue("ViewCells.samplingType", buf);
111
112       
113        // sampling type for view cells construction samples
114        if (strcmp(buf, "box") == 0)
115        {
116                mSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
117        }
118        else if (strcmp(buf, "directional") == 0)
119        {
120                mSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
121        }
122        else if (strcmp(buf, "object_directional") == 0)
123        {
124                mSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
125        }
126        /*else if (strcmp(buf, "interior") == 0)
127        {
128                mSamplingType = Preprocessor::OBJECTS_INTERIOR_DISTRIBUTION;
129        }*/
130        else
131        {
132                Debug << "error! wrong sampling type" << endl;
133                exit(0);
134        }
135
136        // sampling type for evaluation samples
137        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.samplingType", buf);
138       
139        if (strcmp(buf, "box") == 0)
140        {
141                mEvaluationSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
142        }
143        else if (strcmp(buf, "directional") == 0)
144        {
145                mEvaluationSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
146        }
147        else if (strcmp(buf, "object_directional") == 0)
148        {
149                mEvaluationSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
150        }
151        /*else if (strcmp(buf, "interior") == 0)
152        {
153                mEvaluationSamplingType = SamplingStrategy::OBJECTS_INTERIOR_DISTRIBUTION;
154        }*/
155        else
156        {
157                Debug << "error! wrong sampling type" << endl;
158                exit(0);
159        }
160
161        Environment::GetSingleton()->GetStringValue("ViewCells.renderCostEvaluationType", buf);
162       
163        if (strcmp(buf, "perobject") == 0)
164        {
165                mRenderCostEvaluationType = ViewCellsManager::PER_OBJECT;
166        }
167        else if (strcmp(buf, "directional") == 0)
168        {
169                mRenderCostEvaluationType = ViewCellsManager::PER_TRIANGLE;
170        }
171        else
172        {
173                Debug << "error! wrong sampling type" << endl;
174                exit(0);
175        }
176
177    Environment::GetSingleton()->GetStringValue("ViewCells.Visualization.colorCode", buf);
178
179        if (strcmp(buf, "PVS") == 0)
180                mColorCode = 1;
181        else if (strcmp(buf, "MergedLeaves") == 0)
182                mColorCode = 2;
183        else if (strcmp(buf, "MergedTreeDiff") == 0)
184                mColorCode = 3;
185        else
186                mColorCode = 0;
187
188
189        Debug << "************ View Cells Manager options ***************" << endl;
190        Debug << "color code: " << mColorCode << endl;
191
192        Debug << "export rays: " << mExportRays << endl;
193        Debug << "export geometry: " << mExportGeometry << endl;
194        Debug << "max pvs ratio: " << mMaxPvsRatio << endl;
195       
196        Debug << "process only valid view cells: " << mOnlyValidViewCells << endl;
197        Debug << "construction samples: " << mConstructionSamples << endl;
198        Debug << "post process samples: " << mPostProcessSamples << endl;
199        Debug << "post process use rays for merge: " << mUseRaysForMerge << endl;
200        Debug << "visualization samples: " << mVisualizationSamples << endl;
201        Debug << "construction samples per pass: " << mSamplesPerPass << endl;
202        Debug << "export to file: " << mExportViewCells << endl;
203       
204        Debug << "active view cells: " << mNumActiveViewCells << endl;
205        Debug << "post process compress: " << mCompressViewCells << endl;
206        Debug << "visualization use clipPlane: " << mUseClipPlaneForViz << endl;
207        Debug << "post process merge: " << mMergeViewCells << endl;
208        Debug << "evaluate view cells: " << mEvaluateViewCells << endl;
209        Debug << "sampling type: " << mSamplingType << endl;
210        Debug << "render cost evaluation type: " << mRenderCostEvaluationType << endl;
211        Debug << "evaluation sampling type: " << mEvaluationSamplingType << endl;
212        Debug << "show visualization: " << mShowVisualization << endl;
213        Debug << "filter width: " << mFilterWidth << endl;
214        Debug << "sample after subdivision: " << SAMPLE_AFTER_SUBDIVISION << endl;
215
216        Debug << "export bounding boxes: " << mExportBboxesForPvs << endl;
217        Debug << "export pvs for view cells: " << mExportPvs << endl;
218        Debug << endl;
219}
220
221
222ViewCellsManager::~ViewCellsManager()
223{
224        // HACK: if view cells tree does not
225        // handle view cells, we have to do it here
226        // question: rather create view cells resource manager?
227        if (!ViewCellsTreeConstructed())
228        {
229                CLEAR_CONTAINER(mViewCells);
230        }
231}
232
233
234
235AxisAlignedBox3 ViewCellsManager::GetViewCellBox(ViewCell *vc)
236{
237  Mesh *m = vc->GetMesh();
238 
239  if (m)
240  {
241          m->ComputeBoundingBox();
242          return m->mBox;
243  }
244
245  AxisAlignedBox3 box;
246  box.Initialize();
247 
248  if (!vc->IsLeaf()) {
249        ViewCellInterior *vci = (ViewCellInterior *) vc;
250       
251        ViewCellContainer::iterator it = vci->mChildren.begin();
252        for (; it != vci->mChildren.end(); ++it) {
253          box.Include(GetViewCellBox(*it));
254        }
255  }
256 
257  return box;
258}
259
260
261int ViewCellsManager::CastPassSamples(const int samplesPerPass,
262                                                                          const int sampleType,
263                                                                          VssRayContainer &passSamples) const
264{
265        SimpleRayContainer simpleRays;
266        long startTime = GetTime();
267
268        mPreprocessor->GenerateRays(samplesPerPass, sampleType, simpleRays);
269        cout << "generated " << samplesPerPass << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
270
271        startTime = GetTime();
272        // shoot simple ray and add it to importance samples
273        mPreprocessor->CastRays(simpleRays, passSamples, true);
274        cout << "cast " <<  samplesPerPass << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
275
276        return (int)passSamples.size();
277}
278
279
280/// helper function which destroys rays or copies them into the output ray container
281inline void disposeRays(VssRayContainer &rays, VssRayContainer *outRays)
282{
283        cout << "disposing samples ... ";
284        long startTime = GetTime();
285        int n = (int)rays.size();
286
287        if (outRays)
288        {
289                VssRayContainer::const_iterator it, it_end = rays.end();
290                for (it = rays.begin(); it != it_end; ++ it)
291                {
292                        outRays->push_back(*it);
293                }
294        }
295        else
296        {
297                VssRayContainer::const_iterator it, it_end = rays.end();
298                for (it = rays.begin(); it != it_end; ++ it)
299                {
300                        if (!(*it)->IsActive())
301                                delete (*it);
302                }
303        }
304
305        cout << "finished" << endl;
306        Debug << "disposed " << n << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
307}
308
309
310int ViewCellsManager::Construct(Preprocessor *preprocessor, VssRayContainer *outRays)
311{
312        int numSamples = 0;
313
314        SimpleRayContainer simpleRays;
315        VssRayContainer initialSamples;
316
317        // store pointer to preprocessor for further use during construction
318        mPreprocessor = preprocessor;
319       
320
321        ///////////////////////////////////////////////////////
322        //-- Initial sampling for the construction of the view cell hierarchy.
323        //-- We use uniform sampling / box based sampling.
324       
325        long startTime = GetTime();
326        cout << "view cell construction: casting " << mInitialSamples << " initial samples ... " << endl;
327
328        // cast initial samples
329        CastPassSamples(mInitialSamples, mSamplingType, initialSamples);
330
331        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
332
333        // construct view cells
334        ConstructSubdivision(preprocessor->mObjects, initialSamples);
335
336        // initial samples count for overall samples ...
337        numSamples += mInitialSamples;
338
339        // rays can be passed or deleted
340        disposeRays(initialSamples, outRays);
341
342        cout << "time needed for initial construction: "
343                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
344
345        Debug << "time needed for initial construction: "
346                  << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
347
348        // collect view cells and compute statistics
349        ResetViewCells();
350
351
352        ///////////////////
353        //-- Initial hierarchy construction finished.
354        //-- We can do some stats and visualization
355       
356        if (0)
357        {
358                //-- export initial view cell partition
359                Debug << "\nView cells after initial sampling:\n" << mCurrentViewCellsStats << endl;
360
361                const string filename("viewcells.wrl");
362                Exporter *exporter = Exporter::GetExporter(filename.c_str());
363       
364                if (exporter)
365                {
366                        cout << "exporting initial view cells (=leaves) to " << filename.c_str() << " ... ";
367
368                        if (mExportGeometry)
369                        {
370                                exporter->ExportGeometry(preprocessor->mObjects);
371                        }
372
373                        exporter->SetWireframe();
374                        ExportViewCellsForViz(exporter, NULL, GetClipPlane());
375
376                        delete exporter;
377                        cout << "finished" << endl;
378                }
379        }
380
381
382        //////////////////////
383        //-- Cast some more sampling after initial construction.
384        //-- The additional rays can be used to gain
385        //-- some more information before the bottom-up merge
386        //-- note: guided rays could be used for this task
387
388        // time spent after construction of the initial partition
389        startTime = GetTime();
390        const int n = mConstructionSamples; //+initialSamples;
391        // should we use directional samples?
392        bool dirSamples = (mSamplingType == SamplingStrategy::DIRECTION_BASED_DISTRIBUTION);
393
394        while (numSamples < n)
395        {
396                cout << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
397                Debug << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
398
399                VssRayContainer constructionSamples;
400
401                const int samplingType = mSamplingType;
402                        //dirSamples ? Preprocessor::DIRECTION_BASED_DISTRIBUTION :     Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION;
403
404                if (0) dirSamples = !dirSamples; // toggle sampling method
405
406                // cast new samples
407                numSamples += CastPassSamples(mSamplesPerPass,
408                                                                          samplingType,
409                                                                          constructionSamples);
410
411                cout << "finished" << endl;
412                cout << "computing sample contribution for " << (int)constructionSamples.size() << " samples ... ";
413
414                // computes sample contribution of cast rays TODO: leak?
415                if (SAMPLE_AFTER_SUBDIVISION)
416                        ComputeSampleContributions(constructionSamples, true, false);
417
418                cout << "finished" << endl;
419
420                disposeRays(constructionSamples, outRays);
421                cout << "total samples: " << numSamples << endl;
422        }
423
424       
425        if (0)
426        {
427                ///////////////
428                //-- Get stats after the additional sampling step
429                //-- and before the bottom-up merge step
430
431                EvaluateViewCellsStats();
432                Debug << "\noriginal view cell partition before post process:\n"
433                          << mCurrentViewCellsStats << endl;
434       
435                mRenderer->RenderScene();
436                SimulationStatistics ss;
437                dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
438
439                Debug << ss << endl;
440        }
441
442        ////////////////////
443        //-- post processing of the initial construction
444        //-- We can bottom-up merge the view cells in this step
445        //-- We can additionally cast some post processing sample rays.
446        //-- These rays can be used to store the view cells with the rays
447
448        VssRayContainer postProcessSamples;
449        cout << "casting " << mPostProcessSamples << " post processing samples ... ";
450       
451        CastPassSamples(mPostProcessSamples, mSamplingType, postProcessSamples);
452
453        cout << "finished" << endl;
454        cout << "starting post processing and visualization" << endl;
455
456        // store view cells with rays for post processing?
457        const bool storeViewCells = true;
458
459        if (SAMPLE_AFTER_SUBDIVISION)
460                ComputeSampleContributions(postProcessSamples, true, storeViewCells);
461
462        PostProcess(preprocessor->mObjects, postProcessSamples);
463
464        const float secs = TimeDiff(startTime, GetTime()) * 1e-3f;
465        cout << "post processing (=merge) finished in " << secs << " secs" << endl;
466
467        Debug << "post processing time: " << secs << endl;
468        disposeRays(postProcessSamples, outRays);
469
470       
471        ////////////////
472        //-- Evaluation of the resulting view cell partition.
473        //-- We cast a number of new samples and measure the render cost
474
475        if (mEvaluateViewCells)
476        {
477                EvalViewCellPartition();
478        }
479       
480        /////////////////
481        //-- Finally, we do some visualization
482
483        if (mShowVisualization)
484        {
485                ///////////////
486                //-- visualization rays, e.g., to show some samples in the scene
487               
488                VssRayContainer visSamples;
489                int numSamples = CastPassSamples(mVisualizationSamples,
490                                                                                 mSamplingType,
491                                                                                 visSamples);
492
493                if (SAMPLE_AFTER_SUBDIVISION)
494                        ComputeSampleContributions(visSamples, true, storeViewCells);
495
496                // various visualizations
497                Visualize(preprocessor->mObjects, visSamples);
498
499                disposeRays(visSamples, outRays);
500        }
501
502        // recalculate view cells
503        EvaluateViewCellsStats();
504
505        return numSamples;
506}
507
508
509AxisAlignedPlane *ViewCellsManager::GetClipPlane()
510{
511        return mUseClipPlaneForViz ? &mClipPlaneForViz : NULL;
512}
513
514
515void ViewCellsManager::EvalViewCellHistogram(const string filename,
516                                                                                         const int nViewCells)
517{
518        std::ofstream outstream;
519        outstream.open(filename.c_str());
520
521        ViewCellContainer viewCells;
522        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
523
524        float maxRenderCost, minRenderCost;
525
526        // sort by render cost
527        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerRenderCost);
528
529        minRenderCost = viewCells.front()->GetRenderCost();
530        maxRenderCost = viewCells.back()->GetRenderCost();
531
532        Debug << "histogram min rc: " << minRenderCost << " max rc: " << maxRenderCost << endl;
533
534    int histoIntervals;
535        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
536        const int intervals = min(histoIntervals, (int)viewCells.size());
537
538        int histoMaxVal;
539        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
540        maxRenderCost = max((float)histoMaxVal, maxRenderCost);
541
542       
543        const float range = maxRenderCost - minRenderCost;
544        const float stepSize = range / (float)intervals;
545
546        float currentRenderCost = minRenderCost;//(int)ceil(minRenderCost);
547
548        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
549        const float totalVol = GetViewSpaceBox().GetVolume();
550        //const float totalVol = mViewCellsTree->GetRoot()->GetVolume();
551
552        int j = 0;
553        int i = 0;
554       
555        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();             
556
557        // count for integral
558        float volSum = 0;
559        int smallerCostSum = 0;
560       
561        // note can skip computations for view cells already evaluated and delete them from vector ...
562    while (1)
563        {
564                // count for histogram value
565                float volDif = 0;
566                int smallerCostDif = 0;
567
568                while ((i < (int)viewCells.size()) && (viewCells[i]->GetRenderCost() < currentRenderCost))
569                {
570                        volSum += viewCells[i]->GetVolume();
571                        volDif += viewCells[i]->GetVolume();
572
573                        ++ i;
574                        ++ smallerCostSum;
575                        ++ smallerCostDif;
576                }
577               
578                if ((i >= (int)viewCells.size()) || (currentRenderCost >= maxRenderCost))
579                        break;
580               
581                const float rcRatio = currentRenderCost / maxRenderCost;
582                const float volRatioSum = volSum / totalVol;
583                const float volRatioDif = volDif / totalVol;
584
585                outstream << "#Pass\n" << j ++ << endl;
586                outstream << "#RenderCostRatio\n" << rcRatio << endl;
587                outstream << "#WeightedCost\n" << currentRenderCost / totalVol << endl;
588                outstream << "#ViewCellsDif\n" << smallerCostDif << endl;
589                outstream << "#ViewCellsSum\n" << smallerCostSum << endl;       
590                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
591                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
592
593                // increase current render cost
594                currentRenderCost += stepSize;
595        }
596
597        outstream.close();
598}
599
600
601
602ViewCellsManager *ViewCellsManager::LoadViewCells(const string &filename,
603                                                                                                  ObjectContainer *objects,
604                                                                                                  bool finalizeViewCells,
605                                                                                                  BoundingBoxConverter *bconverter)
606                                                                                                 
607{
608        ViewCellsParser parser;
609        ViewCellsManager *vm = NULL;
610
611        const long startTime = GetTime();
612        bool success = parser.ParseViewCellsFile(filename, &vm, objects, bconverter);
613
614        if (success)
615        {
616                //vm->ResetViewCells();
617                //hack
618                vm->mViewCells.clear();
619                ViewCellContainer leaves;
620                vm->mViewCellsTree->CollectLeaves(vm->mViewCellsTree->GetRoot(), leaves);
621
622                ViewCellContainer::const_iterator it, it_end = leaves.end();
623
624                for (it = leaves.begin(); it != it_end; ++ it)
625                {
626                        vm->mViewCells.push_back(*it);
627                }
628                vm->mViewCellsFinished = true;
629                vm->mMaxPvsSize = (int)objects->size();
630
631                if (finalizeViewCells)
632                {
633                        // create the meshes and compute volumes
634                        vm->FinalizeViewCells(true);
635                        // vm->mViewCellsTree->AssignRandomColors();
636                }
637
638                Debug << (int)vm->mViewCells.size() << " view cells loaded in "
639                          << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
640        }
641        else
642        {
643                Debug << "Error: loading view cells failed!" << endl;
644                DEL_PTR(vm);
645        }
646
647        return vm;
648}
649
650
651bool VspBspViewCellsManager::ExportViewCells(const string filename,
652                                                                                         const bool exportPvs,
653                                                                                         const ObjectContainer &objects)
654{
655        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
656        {
657                return false;
658        }
659
660        cout << "exporting view cells to xml ... ";
661
662        OUT_STREAM stream(filename.c_str());
663
664        // for output we need unique ids for each view cell
665        CreateUniqueViewCellIds();
666
667        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
668        stream << "<VisibilitySolution>" << endl;
669
670        if (exportPvs)
671        {
672                //-- export bounding boxes
673                stream << "<BoundingBoxes>" << endl;
674#if USE_KD_PVS
675        KdIntersectableMap::const_iterator kit, kit_end = GetPreprocessor()->mKdTree->mKdIntersectables.end();
676
677                int id = 0;
678                for (kit = GetPreprocessor()->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
679                {
680                        Intersectable *obj = (*kit).second;
681                        const AxisAlignedBox3 box = obj->GetBox();
682               
683                        obj->SetId(id);
684
685                        stream << "<BoundingBox" << " id=\"" << id << "\""
686                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
687                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
688                }
689#else
690        ObjectContainer::const_iterator oit, oit_end = objects.end();
691
692                for (oit = objects.begin(); oit != oit_end; ++ oit)
693                {
694                        const AxisAlignedBox3 box = (*oit)->GetBox();
695
696                        ////////////
697                        //-- the bounding boxes
698                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
699                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
700                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
701                }
702#endif
703                stream << "</BoundingBoxes>" << endl;
704        }
705
706       
707        /////////////
708        //-- export the view cells and the pvs
709
710        const int numViewCells = mCurrentViewCellsStats.viewCells;
711        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
712
713        mViewCellsTree->Export(stream, exportPvs);
714
715        stream << "</ViewCells>" << endl;
716
717
718        //////////
719        //-- export the view space hierarchy
720       
721        stream << "<ViewSpaceHierarchy type=\"bsp\""
722                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
723                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
724
725        mVspBspTree->Export(stream);
726        stream << "</ViewSpaceHierarchy>" << endl;
727
728        stream << "</VisibilitySolution>" << endl;
729
730        stream.close();
731        cout << "finished" << endl;
732
733        return true;
734}
735
736
737void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
738                                                                                                           const int nViewCells)
739{
740        std::ofstream outstream;
741        outstream.open(filename.c_str());
742
743        ViewCellContainer viewCells;
744        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
745
746        int maxPvs, maxVal, minVal;
747
748        // sort by pvs size
749        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerPvs);
750
751        maxPvs = mViewCellsTree->GetPvsSize(viewCells.back());
752        minVal = 0;
753
754        // hack: normalize pvs size
755        int histoMaxVal;
756        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
757        maxVal = max(histoMaxVal, maxPvs);
758               
759        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
760                << " real maxpvs " << maxPvs << endl;
761
762        int histoIntervals;
763        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
764        const int intervals = min(histoIntervals, (int)viewCells.size());
765
766        const int range = maxVal - minVal;
767        int stepSize = range / intervals;
768
769        // set step size to avoid endless loop
770        if (!stepSize) stepSize = 1;
771       
772        Debug << "stepsize: " << stepSize << endl;
773       
774        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
775        const float totalVol = GetViewSpaceBox().GetVolume();
776
777        int currentPvs = minVal;//(int)ceil(minRenderCost);
778       
779        int i = 0;
780        int j = 0;
781        float volSum = 0;
782        int smallerSum = 0;
783
784        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();             
785       
786        for (int j = 0; j < intervals; ++ j)
787        {
788                float volDif = 0;
789                int smallerDif = 0;
790
791                while ((i < (int)viewCells.size()) &&
792                           (mViewCellsTree->GetPvsSize(viewCells[i]) < currentPvs))
793                {
794                        volDif += viewCells[i]->GetVolume();
795                        volSum += viewCells[i]->GetVolume();
796
797                        ++ i;
798                        ++ smallerDif;
799                        ++ smallerSum;
800                }
801               
802                if (0 && (i < (int)viewCells.size()))
803                        Debug << "new pvs size increase: " << mViewCellsTree->GetPvsSize(viewCells[i])
804                        << " " << currentPvs << endl;
805       
806                const float volRatioDif = volDif / totalVol;
807                const float volRatioSum = volSum / totalVol;
808
809                outstream << "#Pass\n" << j << endl;
810                outstream << "#Pvs\n" << currentPvs << endl;
811                outstream << "#ViewCellsDif\n" << smallerDif << endl;
812                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
813                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
814                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
815       
816                //if ((i >= (int)viewCells.size()) || (currentPvs >= maxPvs))   break;
817
818                //-- increase current pvs size to define next interval
819                currentPvs += stepSize;
820        }
821
822        outstream.close();
823}
824
825
826bool ViewCellsManager::GetExportPvs() const
827{
828        return mExportPvs;
829}
830
831
832bool ViewCellsManager::AddSampleToPvs(Intersectable *obj,
833                                                                          const Vector3 &hitPoint,
834                                                                          ViewCell *vc,
835                                                                          const float pdf,
836                                                                          float &contribution) const
837{
838        if (!obj) return false;
839
840        // potentially visible objects
841        return vc->AddPvsSample(obj, pdf, contribution);
842}
843
844
845void ViewCellsManager::ResetPvs()
846{
847        if (ViewCellsTreeConstructed())
848        {
849                mViewCellsTree->ResetPvs();
850        }
851        else
852        {
853                cout << "view cells tree not constructed" << endl;
854        }
855}
856
857
858void ViewCellsManager::ExportStats(const string &fileName)
859{
860        mViewCellsTree->ExportStats(fileName);
861}
862
863
864void ViewCellsManager::EvalViewCellPartition()
865{
866        int samplesPerPass;
867        int numSamples;
868        int castSamples = 0;
869        char str[64];
870
871        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
872        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", numSamples);
873
874        char statsPrefix[100];
875        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
876
877        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
878        Debug << "view cell evaluation samples: " << numSamples << endl;
879        Debug << "view cell stats prefix: " << statsPrefix << endl;
880
881        // should directional sampling be used?
882        bool dirSamples =
883                (mEvaluationSamplingType == SamplingStrategy::DIRECTION_BASED_DISTRIBUTION);
884
885        cout << "reseting pvs ... ";
886               
887        const bool startFromZero = true;
888
889        // reset pvs and start over from zero
890        if (startFromZero)
891        {
892                mViewCellsTree->ResetPvs();
893        }
894        else // start from current sampless
895        {
896                // statistics before casting more samples
897                cout << "compute new statistics ... ";
898                sprintf(str, "-%09d-eval.log", castSamples);
899                string fName = string(statsPrefix) + string(str);
900
901                mViewCellsTree->ExportStats(fName);
902                cout << "finished" << endl;
903        }
904
905        cout << "finished" << endl;
906    cout << "Evaluating view cell partition ... " << endl;
907
908        while (castSamples < numSamples)
909        {
910                VssRayContainer evaluationSamples;
911
912                const int samplingType = mEvaluationSamplingType;
913                /*      dirSamples ?
914                                                Preprocessor::DIRECTION_BASED_DISTRIBUTION :
915                                                Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION;
916                */
917                long startTime = GetTime();
918
919                //-- construction rays => we use uniform samples for this
920
921                cout << "casting " << samplesPerPass << " samples ... ";
922                Debug << "casting " << samplesPerPass << " samples ... ";
923
924                CastPassSamples(samplesPerPass, samplingType, evaluationSamples);
925               
926                castSamples += samplesPerPass;
927
928                Real timeDiff = TimeDiff(startTime, GetTime());
929                Debug << "finished in " << timeDiff * 1e-3 << " secs" << endl;
930                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
931
932                cout << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
933                Debug << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
934
935                startTime = GetTime();
936
937                ComputeSampleContributions(evaluationSamples, true, false);
938
939                timeDiff = TimeDiff(startTime, GetTime());
940                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
941                Debug << "finished in " << timeDiff * 1e-3 << " secs" << endl;
942
943                startTime = GetTime();
944                cout << "compute new statistics ... " << endl;
945       
946                ///////////////
947                //-- propagate pvs or pvs size information
948
949                ObjectPvs pvs;
950                UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), pvs);
951
952                ///////////
953                //-- output stats
954                sprintf(str, "-%09d-eval.log", castSamples);
955                string fileName = string(statsPrefix) + string(str);
956
957                ExportStats(fileName);
958
959                timeDiff = TimeDiff(startTime, GetTime());
960                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
961                Debug << "statistis compted in " << timeDiff * 1e-3 << " secs" << endl;
962       
963                disposeRays(evaluationSamples, NULL);
964        }
965       
966
967        ////////////
968        //-- histogram
969
970        bool useHisto;
971        int histoStepSize;
972
973        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
974        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
975
976        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
977
978
979        if (useHisto)
980        {
981                // evaluate view cells in a histogram           
982                char s[64];
983
984                for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
985                {
986                        string filename;
987
988                        cout << "computing histogram for " << pass << " view cells" << endl;
989#if 0
990                        //-- evaluate histogram for render cost
991                        sprintf(s, "-%09d-histo.log", pass);
992                        filename = string(statsPrefix) + string(s);
993
994                        EvalViewCellHistogram(filename, pass);
995
996#endif
997                        //////////////////////////////////////////
998            //-- evaluate histogram for pvs size
999
1000                        cout << "computing pvs histogram for " << pass << " view cells" << endl;
1001
1002                        sprintf(s, "-%09d-histo-pvs.log", pass);
1003                        filename = string(statsPrefix) + string(s);
1004
1005                        EvalViewCellHistogramForPvsSize(filename, pass);
1006                }
1007        }
1008}
1009
1010
1011inline float EvalMergeCost(ViewCell *root, ViewCell *candidate)
1012{
1013        return root->GetPvs().GetPvsHomogenity(candidate->GetPvs());
1014}
1015
1016
1017/// Returns index of the best view cells of the neighborhood
1018int GetBestViewCellIdx(ViewCell *root, const ViewCellContainer &neighborhood)
1019{
1020        int bestViewCellIdx = 0;
1021
1022        float mergeCost = Limits::Infinity;
1023        int i = 0;
1024
1025        ViewCellContainer::const_iterator vit, vit_end = neighborhood.end();
1026
1027        for (vit = neighborhood.begin(); vit != vit_end; ++ vit, ++ i)
1028        {
1029                const float mc = EvalMergeCost(root, *vit);
1030               
1031                if (mc < mergeCost)
1032                {
1033                        mergeCost = mc;
1034                        bestViewCellIdx = i;
1035                }
1036        }
1037
1038        return bestViewCellIdx;
1039}
1040
1041
1042void ViewCellsManager::SetMaxFilterSize(const int size)
1043{
1044        mMaxFilterSize = size;
1045}
1046
1047
1048float ViewCellsManager::EvalRenderCost(Intersectable *obj) const
1049{
1050        switch (mRenderCostEvaluationType)
1051        {
1052        case PER_OBJECT:
1053                //cout << "perobject" << endl;
1054                return 1.0f;
1055       
1056        case PER_TRIANGLE:
1057                {//cout << "pertriangle" << endl;
1058                        // HACK
1059                        MeshInstance *mi = dynamic_cast<MeshInstance *>(obj);
1060
1061                        // HACK: assume meshes are triangles
1062                        if (mi->GetMesh())
1063                        {
1064                                return (float)mi->GetMesh()->mFaces.size();
1065                        }
1066                }
1067        default:
1068                cout << "default" << endl;
1069                return 1.0f;
1070        }
1071
1072        // should not come here
1073        return 0.0f;
1074}
1075
1076
1077ViewCell *ViewCellsManager::ConstructLocalMergeTree(ViewCell *currentViewCell,
1078                                                                                                        const ViewCellContainer &viewCells)
1079{
1080        ViewCell *root = currentViewCell;
1081        ViewCellContainer neighborhood = viewCells;
1082
1083        ViewCellContainer::const_iterator it, it_end = neighborhood.end();
1084
1085        const int n = min(mMaxFilterSize, (int)neighborhood.size());
1086       
1087        /////////////////
1088        //-- use priority queue to merge leaf pairs
1089       
1090        for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1091        {
1092                const int bestViewCellIdx = GetBestViewCellIdx(root, neighborhood);
1093               
1094                ViewCell *bestViewCell = neighborhood[bestViewCellIdx];
1095       
1096                // remove from vector
1097                swap(neighborhood[bestViewCellIdx], neighborhood.back());
1098                neighborhood.pop_back();
1099       
1100                if (!bestViewCell || !root)
1101            cout << "warning!!" << endl;
1102               
1103                // create new root of the hierarchy
1104                root = MergeViewCells(root, bestViewCell);
1105        }
1106
1107        return root;   
1108}
1109
1110
1111struct SortableViewCellEntry {
1112
1113        SortableViewCellEntry() {}
1114        SortableViewCellEntry(const float v, ViewCell *cell):mValue(v), mViewCell(cell) {}
1115
1116        float mValue;
1117        ViewCell *mViewCell;
1118
1119        friend bool operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b) {
1120                return a.mValue < b.mValue;
1121        }
1122};
1123
1124
1125ViewCell * ViewCellsManager::ConstructLocalMergeTree2(ViewCell *currentViewCell,
1126                                                                                                          const ViewCellContainer &viewCells)
1127{
1128 
1129  vector<SortableViewCellEntry> neighborhood(viewCells.size());
1130  int i, j;
1131  for (i = 0, j = 0; i < viewCells.size(); i++) {
1132        if (viewCells[i] != currentViewCell)
1133          neighborhood[j++] = SortableViewCellEntry(
1134                                                                                                EvalMergeCost(currentViewCell, viewCells[i]),
1135                                                                                                viewCells[i]);
1136  }
1137  neighborhood.resize(j);
1138 
1139  sort(neighborhood.begin(), neighborhood.end());
1140 
1141  ViewCell *root = currentViewCell;
1142 
1143  vector<SortableViewCellEntry>::const_iterator it, it_end = neighborhood.end();
1144 
1145  const int n = min(mMaxFilterSize, (int)neighborhood.size());
1146  //-- use priority queue to merge leaf pairs
1147 
1148  //cout << "neighborhood: " << neighborhood.size() << endl;
1149  for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1150  {
1151          ViewCell *bestViewCell = neighborhood[nMergedViewCells].mViewCell;
1152          //cout <<nMergedViewCells<<":"<<"homogenity=" <<neighborhood[nMergedViewCells].mValue<<endl;
1153          // create new root of the hierarchy
1154          root = MergeViewCells(root, bestViewCell);
1155          // set negative cost so that this view cell gets deleted
1156          root->SetMergeCost(-1.0f);
1157  }
1158 
1159  return root; 
1160}
1161
1162void
1163ViewCellsManager::DeleteLocalMergeTree(ViewCell *vc
1164                                                                           ) const
1165{
1166        if (!vc->IsLeaf() && vc->GetMergeCost() < 0.0f)
1167        {       
1168                ViewCellInterior *vci = (ViewCellInterior *) vc;
1169                ViewCellContainer::const_iterator it, it_end = vci->mChildren.end();
1170
1171        for (it = vci->mChildren.begin(); it != it_end; ++ it)
1172                        DeleteLocalMergeTree(*it);
1173               
1174                vci->mChildren.clear();
1175               
1176                delete vci;
1177  }
1178}
1179
1180
1181bool ViewCellsManager::CheckValidity(ViewCell *vc,
1182                                                                         int minPvsSize,
1183                                                                         int maxPvsSize) const
1184{
1185
1186        if ((vc->GetPvs().CountObjectsInPvs() > maxPvsSize) ||
1187                (vc->GetPvs().CountObjectsInPvs() < minPvsSize))
1188        {
1189                return false;
1190        }
1191
1192        return true;
1193}
1194
1195
1196int ViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
1197                                                                                          ViewCellContainer &viewCells) const
1198{
1199        return 0;
1200};
1201
1202
1203AxisAlignedBox3 ViewCellsManager::GetFilterBBox(const Vector3 &viewPoint,
1204                                                                                                const float width) const
1205{
1206  float w = Magnitude(mViewSpaceBox.Size())*width;
1207  Vector3 min = viewPoint - w * 0.5f;
1208  Vector3 max = viewPoint + w * 0.5f;
1209 
1210  return AxisAlignedBox3(min, max);
1211}
1212
1213
1214void ViewCellsManager::GetPrVS(const Vector3 &viewPoint,
1215                                                           PrVs &prvs,
1216                                                           const float filterWidth)
1217{
1218  ViewCell *currentViewCell = GetViewCell(viewPoint);
1219
1220  if (mMaxFilterSize < 1) {
1221        prvs.mViewCell = currentViewCell;
1222        return;
1223  }
1224 
1225  const AxisAlignedBox3 box = GetFilterBBox(viewPoint, filterWidth);
1226 
1227  if (currentViewCell)
1228        {
1229          ViewCellContainer viewCells;
1230          ComputeBoxIntersections(box, viewCells);
1231         
1232          ViewCell *root = ConstructLocalMergeTree2(currentViewCell, viewCells);
1233          prvs.mViewCell = root;
1234         
1235        }
1236  else
1237        {
1238          prvs.mViewCell = NULL;
1239          //prvs.mPvs = root->GetPvs();
1240        }
1241}
1242
1243
1244bool ViewCellsManager::ViewCellsTreeConstructed() const
1245{
1246    return (mViewCellsTree && mViewCellsTree->GetRoot());
1247}
1248
1249
1250void ViewCellsManager::SetValidity(ViewCell *vc,
1251                                                                   int minPvs,
1252                                                                   int maxPvs) const
1253{
1254        vc->SetValid(CheckValidity(vc, minPvs, maxPvs));
1255}
1256
1257
1258void
1259ViewCellsManager::SetValidity(
1260                                                          int minPvsSize,
1261                                                          int maxPvsSize) const
1262{
1263        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1264
1265
1266        for (it = mViewCells.begin(); it != it_end; ++ it)
1267        {
1268                SetValidity(*it, minPvsSize, maxPvsSize);
1269        }
1270}
1271
1272void
1273ViewCellsManager::SetValidityPercentage(
1274                                                                                const float minValid,
1275                                                                                const float maxValid
1276                                                                                )
1277{
1278        sort(mViewCells.begin(), mViewCells.end(), ViewCell::SmallerPvs);
1279
1280        int start = (int)(mViewCells.size() * minValid);
1281        int end = (int)(mViewCells.size() * maxValid);
1282
1283        for (int i = 0; i < (int)mViewCells.size(); ++ i)
1284        {
1285                mViewCells[i]->SetValid(i >= start && i <= end);
1286        }
1287}
1288
1289
1290int ViewCellsManager::CountValidViewcells() const
1291{
1292        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1293        int valid = 0;
1294
1295        for (it = mViewCells.begin(); it != it_end; ++ it)
1296        {       
1297                if ((*it)->GetValid())
1298                        ++ valid;
1299        }
1300
1301        return valid;
1302}
1303
1304
1305bool ViewCellsManager::LoadViewCellsGeometry(const string filename,
1306                                                                                         const bool extrudeBaseTriangles)
1307{
1308        /// we use predefined view cells from now on
1309        mUsePredefinedViewCells = true;
1310        X3dParser parser;
1311       
1312        if (extrudeBaseTriangles)
1313        {
1314                Environment::GetSingleton()->GetFloatValue("ViewCells.height", parser.mViewCellHeight);
1315                const bool success = parser.ParseFile(filename, *this);
1316
1317                if (!success)
1318                        return false;
1319        }
1320        else
1321        {
1322                // hack: use standard mesh loading
1323                // create temporary scene graph for loading the view cells geometry
1324                // note: delete the meshes as they are created two times for transformed mesh instances.
1325                SceneGraphNode *root = new SceneGraphNode();
1326                const bool success = parser.ParseFile(filename, root, true);
1327               
1328                if (!success)
1329                {
1330                        DEL_PTR(root);
1331                        return false;
1332                }
1333
1334                ObjectContainer::const_iterator oit, oit_end = root->mGeometry.end();
1335               
1336                for (oit = root->mGeometry.begin(); oit != oit_end; ++ oit)
1337                {
1338                        Mesh *mesh;
1339                        if ((*oit)->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
1340                        {
1341                                TransformedMeshInstance *mit = dynamic_cast<TransformedMeshInstance *>(*oit);
1342                                mesh = MeshManager::GetSingleton()->CreateResource();
1343                                mit->GetTransformedMesh(*mesh);
1344                        }
1345                        else if ((*oit)->Type() == Intersectable::MESH_INSTANCE)
1346                        {
1347                                MeshInstance *mit = dynamic_cast<MeshInstance *>(*oit);
1348                                mesh = mit->GetMesh();
1349                        }
1350                        mesh->ComputeBoundingBox();
1351                        mViewCells.push_back(GenerateViewCell(mesh));
1352                }
1353
1354                DEL_PTR(root);
1355        }
1356
1357        // set view space box to bounding box of the view cells
1358        AxisAlignedBox3 bbox;
1359        bbox.Initialize();
1360        ViewCellContainer::iterator it = mViewCells.begin(), it_end = mViewCells.end();
1361
1362        for (; it != it_end; ++ it)
1363        {
1364                bbox.Include((*it)->GetMesh()->mBox);
1365        }
1366
1367        SetViewSpaceBox(bbox);
1368        cout << "view space box: " << bbox << endl;
1369        cout << "generated " << (int)mViewCells.size() << " view cells using the geometry " << filename << endl;
1370
1371        return true;
1372}
1373
1374
1375bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
1376{
1377        viewPoint = mViewSpaceBox.GetRandomPoint();
1378        return true;
1379}
1380
1381
1382float ViewCellsManager::GetViewSpaceVolume()
1383{
1384        return mViewSpaceBox.GetVolume() * (2.0f * sqr((float)M_PI));
1385}
1386
1387
1388bool ViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
1389{
1390        if (!ViewCellsConstructed())
1391        {
1392                return mViewSpaceBox.IsInside(viewPoint);
1393        }
1394        else
1395        {
1396                if (!mViewSpaceBox.IsInside(viewPoint))
1397                        return false;
1398
1399                ViewCell *viewcell = GetViewCell(viewPoint);
1400
1401                if (!viewcell || !viewcell->GetValid())
1402                        return false;
1403        }
1404
1405        return true;
1406}
1407
1408
1409float ViewCellsManager::ComputeSampleContributions(const VssRayContainer &rays,
1410                                                                                                   const bool addRays,                                                                 
1411                                                                                                   const bool storeViewCells)
1412{
1413        // view cells not yet constructed
1414        if (!ViewCellsConstructed())
1415                return 0.0f;
1416       
1417        float sum = 0.0f;
1418        VssRayContainer::const_iterator it, it_end = rays.end();
1419       
1420        for (it = rays.begin(); it != it_end; ++ it)
1421        {
1422                sum += ComputeSampleContribution(*(*it), addRays, storeViewCells);
1423        }
1424
1425        return sum;
1426}
1427
1428
1429void ViewCellsManager::EvaluateViewCellsStats()
1430{
1431        mCurrentViewCellsStats.Reset();
1432        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1433
1434        for (it = mViewCells.begin(); it != it_end; ++ it)
1435        {
1436                mViewCellsTree->UpdateViewCellsStats(*it, mCurrentViewCellsStats);
1437        }
1438}
1439
1440
1441void ViewCellsManager::EvaluateRenderStatistics(float &totalRenderCost,
1442                                                                                                float &expectedRenderCost,
1443                                                                                                float &deviation,
1444                                                                                                float &variance,
1445                                                                                                int &totalPvs,
1446                                                                                                float &avgRenderCost)
1447{
1448        ////////////
1449        //-- compute expected value
1450
1451        totalRenderCost = 0;
1452        totalPvs = 0;
1453
1454        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1455
1456        for (it = mViewCells.begin(); it != it_end; ++ it)
1457        {
1458                ViewCell *vc = *it;
1459                totalRenderCost += vc->GetPvs().CountObjectsInPvs() * vc->GetVolume();
1460                totalPvs += (int)vc->GetPvs().CountObjectsInPvs();
1461        }
1462
1463        // normalize with view space box
1464        totalRenderCost /= mViewSpaceBox.GetVolume();
1465        expectedRenderCost = totalRenderCost / (float)mViewCells.size();
1466        avgRenderCost = totalPvs / (float)mViewCells.size();
1467
1468
1469        ///////////
1470        //-- compute standard defiation
1471
1472        variance = 0;
1473        deviation = 0;
1474
1475        for (it = mViewCells.begin(); it != it_end; ++ it)
1476        {
1477                ViewCell *vc = *it;
1478
1479                float renderCost = vc->GetPvs().CountObjectsInPvs() * vc->GetVolume();
1480                float dev;
1481
1482                if (1)
1483                        dev = fabs(avgRenderCost - (float)vc->GetPvs().CountObjectsInPvs());
1484                else
1485                        dev = fabs(expectedRenderCost - renderCost);
1486
1487                deviation += dev;
1488                variance += dev * dev;
1489        }
1490
1491        variance /= (float)mViewCells.size();
1492        deviation /= (float)mViewCells.size();
1493}
1494
1495
1496float ViewCellsManager::GetArea(ViewCell *viewCell) const
1497{
1498        return viewCell->GetArea();
1499}
1500
1501
1502float ViewCellsManager::GetVolume(ViewCell *viewCell) const
1503{
1504        return viewCell->GetVolume();
1505}
1506
1507
1508ViewCell *ViewCellsManager::ExtrudeViewCell(const Triangle3 &baseTri,
1509                                                                                        const float height) const
1510{
1511        // one mesh per view cell
1512        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
1513
1514        ////////////
1515        //-- construct prism
1516
1517        // bottom
1518        mesh->mFaces.push_back(new Face(2,1,0));
1519        // top
1520    mesh->mFaces.push_back(new Face(3,4,5));
1521        // sides
1522        mesh->mFaces.push_back(new Face(1, 4, 3, 0));
1523        mesh->mFaces.push_back(new Face(2, 5, 4, 1));
1524        mesh->mFaces.push_back(new Face(3, 5, 2, 0));
1525
1526
1527        /////////////
1528        //-- extrude new vertices for top of prism
1529
1530        const Vector3 triNorm = baseTri.GetNormal();
1531        Triangle3 topTri;
1532
1533        // add base vertices and calculate top vertices
1534        for (int i = 0; i < 3; ++ i)
1535        {
1536                mesh->mVertices.push_back(baseTri.mVertices[i]);
1537        }
1538
1539        // add top vertices
1540        for (int i = 0; i < 3; ++ i)
1541        {
1542                mesh->mVertices.push_back(baseTri.mVertices[i] + height * triNorm);
1543        }
1544
1545        // do we have to preprocess this mesh (we don't want to trace view cells!)?
1546        mesh->ComputeBoundingBox();
1547       
1548        return GenerateViewCell(mesh);
1549}
1550
1551
1552void ViewCellsManager::FinalizeViewCells(const bool createMesh)
1553{
1554        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1555
1556        // volume and area of the view cells are recomputed and a view cell mesh is created
1557        for (it = mViewCells.begin(); it != it_end; ++ it)
1558        {
1559                Finalize(*it, createMesh);
1560        }
1561
1562        mViewCellsTree->AssignRandomColors();
1563
1564        mTotalAreaValid = false;
1565}
1566
1567
1568void ViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
1569{
1570        // implemented in subclasses
1571}
1572
1573
1574/** fast way of merging 2 view cells.
1575*/
1576ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCell *left, ViewCell *right) const
1577{
1578        // generate parent view cell
1579        ViewCellInterior *vc = new ViewCellInterior();
1580
1581        vc->GetPvs().Clear();
1582        vc->GetPvs() = left->GetPvs();
1583
1584        // merge pvs of right cell
1585        vc->GetPvs().Merge(right->GetPvs());
1586
1587        // set only links to child (not from child to parent, maybe not wished!!)
1588        vc->mChildren.push_back(left);
1589        vc->mChildren.push_back(right);
1590
1591        // update pvs size
1592        UpdateScalarPvsSize(vc, vc->GetPvs().CountObjectsInPvs(), vc->GetPvs().GetSize());
1593
1594        return vc;
1595}
1596
1597
1598ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCellContainer &children) const
1599{
1600        ViewCellInterior *vc = new ViewCellInterior();
1601
1602        ViewCellContainer::const_iterator it, it_end = children.end();
1603
1604        for (it = children.begin(); it != it_end; ++ it)
1605        {
1606                // merge pvs
1607                vc->GetPvs().Merge((*it)->GetPvs());
1608                vc->mChildren.push_back(*it);
1609        }
1610
1611        return vc;
1612}
1613
1614
1615void ViewCellsManager::SetRenderer(Renderer *renderer)
1616{
1617        mRenderer = renderer;
1618}
1619
1620
1621ViewCellsTree *ViewCellsManager::GetViewCellsTree()
1622{
1623        return mViewCellsTree;
1624}
1625
1626
1627void ViewCellsManager::SetVisualizationSamples(const int visSamples)
1628{
1629        mVisualizationSamples = visSamples;
1630}
1631
1632
1633void ViewCellsManager::SetConstructionSamples(const int constructionSamples)
1634{
1635        mConstructionSamples = constructionSamples;
1636}
1637
1638
1639void ViewCellsManager::SetInitialSamples(const int initialSamples)
1640{
1641        mInitialSamples = initialSamples;
1642}
1643
1644
1645void ViewCellsManager::SetPostProcessSamples(const int postProcessSamples)
1646{
1647        mPostProcessSamples = postProcessSamples;
1648}
1649
1650
1651int ViewCellsManager::GetVisualizationSamples() const
1652{
1653        return mVisualizationSamples;
1654}
1655
1656
1657int ViewCellsManager::GetConstructionSamples() const
1658{
1659        return mConstructionSamples;
1660}
1661
1662
1663int ViewCellsManager::GetPostProcessSamples() const
1664{
1665        return mPostProcessSamples;
1666}
1667
1668
1669void ViewCellsManager::UpdatePvs()
1670{
1671        if (mViewCellPvsIsUpdated || !ViewCellsTreeConstructed())
1672                return;
1673
1674        mViewCellPvsIsUpdated = true;
1675
1676        ViewCellContainer leaves;
1677        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
1678
1679        ViewCellContainer::const_iterator it, it_end = leaves.end();
1680
1681        for (it = leaves.begin(); it != it_end; ++ it)
1682        {
1683                mViewCellsTree->PropagatePvs(*it);
1684        }
1685}
1686
1687
1688void ViewCellsManager::GetPvsStatistics(PvsStatistics &stat)
1689{
1690  // update pvs of view cells tree if necessary
1691  UpdatePvs();
1692 
1693  ViewCellContainer::const_iterator it = mViewCells.begin();
1694 
1695  stat.viewcells = 0;
1696  stat.minPvs = 100000000;
1697  stat.maxPvs = 0;
1698  stat.avgPvs = 0.0f;
1699 
1700  for (; it != mViewCells.end(); ++ it)
1701        {
1702          ViewCell *viewcell = *it;
1703
1704          //      bool mCountKdPvs = false;
1705          const int pvsSize = mViewCellsTree->GetPvsSize(viewcell);
1706
1707
1708          if (pvsSize < stat.minPvs)
1709                stat.minPvs = pvsSize;
1710          if (pvsSize > stat.maxPvs)
1711                stat.maxPvs = pvsSize;
1712         
1713          stat.avgPvs += pvsSize;
1714         
1715          ++ stat.viewcells;
1716        }
1717 
1718  if (stat.viewcells)
1719        stat.avgPvs/=stat.viewcells;
1720}
1721
1722
1723void ViewCellsManager::PrintPvsStatistics(ostream &s)
1724{
1725  s<<"############# Viewcell PVS STAT ##################\n";
1726  PvsStatistics pvsStat;
1727  GetPvsStatistics(pvsStat);
1728  s<<"#AVG_PVS\n"<<pvsStat.avgPvs<<endl;
1729  s<<"#MAX_PVS\n"<<pvsStat.maxPvs<<endl;
1730  s<<"#MIN_PVS\n"<<pvsStat.minPvs<<endl;
1731}
1732
1733
1734int ViewCellsManager::CastBeam(Beam &beam)
1735{
1736        return 0;
1737}
1738
1739
1740ViewCellContainer &ViewCellsManager::GetViewCells()
1741{
1742        return mViewCells;
1743}
1744
1745
1746void ViewCellsManager::SetViewSpaceBox(const AxisAlignedBox3 &box)
1747{
1748        mViewSpaceBox = box;
1749       
1750        // hack: create clip plane relative to new view space box
1751        CreateClipPlane();
1752        // the total area of the view space has changed
1753        mTotalAreaValid = false;
1754}
1755
1756
1757void ViewCellsManager::CreateClipPlane()
1758{
1759        int axis = 0;
1760        float pos;
1761        bool orientation;
1762        Vector3 absPos;
1763
1764        Environment::GetSingleton()->GetFloatValue("ViewCells.Visualization.clipPlanePos", pos);
1765        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.clipPlaneAxis", axis);
1766
1767        if (axis < 0)
1768        {
1769                axis = -axis;
1770                orientation = false;
1771                absPos = mViewSpaceBox.Max() -  mViewSpaceBox.Size() * pos;
1772        }
1773        else
1774        {
1775                orientation = true;
1776                absPos = mViewSpaceBox.Min() +  mViewSpaceBox.Size() * pos;
1777        }
1778
1779        mClipPlaneForViz = AxisAlignedPlane(axis, absPos[axis]);
1780        mClipPlaneForViz.mOrientation = orientation;
1781}
1782
1783
1784AxisAlignedBox3 ViewCellsManager::GetViewSpaceBox() const
1785{
1786        return mViewSpaceBox;
1787}
1788
1789
1790void ViewCellsManager::ResetViewCells()
1791{
1792        // recollect view cells
1793        mViewCells.clear();
1794        CollectViewCells();
1795       
1796        // stats are computed once more
1797        EvaluateViewCellsStats();
1798
1799        // has to be recomputed
1800        mTotalAreaValid = false;
1801}
1802
1803
1804int ViewCellsManager::GetMaxPvsSize() const
1805{
1806        return mMaxPvsSize;
1807}
1808
1809
1810void
1811ViewCellsManager::AddSampleContributions(const VssRayContainer &rays)
1812{
1813  if (!ViewCellsConstructed())
1814        return;
1815
1816  VssRayContainer::const_iterator it, it_end = rays.end();
1817
1818  for (it = rays.begin(); it != it_end; ++ it) {
1819        AddSampleContributions(*(*it));
1820  }
1821}
1822
1823
1824int ViewCellsManager::GetMinPvsSize() const
1825{
1826        return mMinPvsSize;
1827}
1828
1829
1830
1831float ViewCellsManager::GetMaxPvsRatio() const
1832{
1833        return mMaxPvsRatio;
1834}
1835
1836
1837void
1838ViewCellsManager::AddSampleContributions(VssRay &ray)
1839{
1840  // assumes viewcells have been stored...
1841  ViewCellContainer *viewcells = &ray.mViewCells;
1842  ViewCellContainer::const_iterator it;
1843
1844  if (!ray.mTerminationObject)
1845        return;
1846 
1847#if USE_KD_PVS
1848  float area = GetPreprocessor()->mKdTree->GetBox().SurfaceArea()*KD_PVS_AREA;
1849  KdNode *node = GetPreprocessor()->mKdTree->GetNode(ray.mTermination, area);
1850  Intersectable *obj =
1851        GetPreprocessor()->mKdTree->
1852        GetOrCreateKdIntersectable(node);
1853#else
1854  Intersectable *obj = ray.mTerminationObject;
1855#endif
1856 
1857  for (it = viewcells->begin(); it != viewcells->end(); ++it) {
1858        ViewCell *viewcell = *it;
1859        if (viewcell->GetValid()) {
1860          // if ray not outside of view space
1861          viewcell->GetPvs().AddSample(obj, ray.mPdf);
1862        }
1863  }
1864}
1865
1866
1867float ViewCellsManager::ComputeSampleContribution(VssRay &ray,
1868                                                                                                  const bool addRays,
1869                                                                                                  const bool storeViewCells)
1870{
1871        ViewCellContainer viewcells;
1872
1873        ray.mPvsContribution = 0;
1874        ray.mRelativePvsContribution = 0.0f;
1875
1876        static Ray hray;
1877        hray.Init(ray);
1878        //hray.mFlags |= Ray::CULL_BACKFACES;
1879        //Ray hray(ray);
1880
1881        float tmin = 0, tmax = 1.0;
1882
1883        if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
1884                return 0;
1885
1886        Vector3 origin = hray.Extrap(tmin);
1887        Vector3 termination = hray.Extrap(tmax);
1888
1889        ViewCell::NewMail();
1890
1891        // traverse the view space subdivision
1892        CastLineSegment(origin, termination, viewcells);
1893
1894        if (storeViewCells)
1895        {       // copy viewcells memory efficiently
1896                ray.mViewCells.reserve(viewcells.size());
1897                ray.mViewCells = viewcells;
1898        }
1899
1900#if USE_KD_PVS
1901        float area = GetPreprocessor()->mKdTree->GetBox().SurfaceArea()*KD_PVS_AREA;
1902        KdNode *node = GetPreprocessor()->mKdTree->GetNode(ray.mTermination, area);
1903        Intersectable *obj =
1904          GetPreprocessor()->mKdTree->
1905          GetOrCreateKdIntersectable(node);
1906#else
1907        Intersectable *obj = ray.mTerminationObject;
1908#endif
1909       
1910       
1911        ViewCellContainer::const_iterator it = viewcells.begin();
1912       
1913        for (; it != viewcells.end(); ++ it)
1914        {
1915                ViewCell *viewcell = *it;
1916               
1917                if (viewcell->GetValid()) // tests if view cell is in valid view space
1918                {
1919                        float contribution;
1920
1921                        if (ray.mTerminationObject)
1922                        {                       
1923                                if (viewcell->GetPvs().GetSampleContribution(obj,
1924                                        ray.mPdf,
1925                                        contribution))
1926                                {
1927                                        ++ ray.mPvsContribution;
1928                                        ray.mRelativePvsContribution += contribution;
1929                                }
1930                        }
1931                       
1932#if SAMPLE_ORIGIN_OBJECTS
1933
1934                        // for directional sampling it is important to count only contributions
1935                        // made in one direction!!!
1936                        // the other contributions of this sample will be counted for the oposite ray!
1937
1938                        if (ray.mOriginObject &&
1939                                viewcell->GetPvs().GetSampleContribution(ray.mOriginObject,
1940                                                                                                                 ray.mPdf,
1941                                                                                                                 contribution))
1942                        {
1943                                ++ ray.mPvsContribution;
1944                                ray.mRelativePvsContribution += contribution;
1945                        }
1946#endif
1947                }
1948        }
1949
1950        // if true, the sampled entities are stored in the pvs
1951        if (addRays)
1952        {
1953                for (it = viewcells.begin(); it != viewcells.end(); ++ it)
1954                {
1955                        ViewCell *viewcell = *it;
1956           
1957                        if (viewcell->GetValid())
1958                        {
1959                                // if view point is valid, add new object to the pvs
1960                                if (ray.mTerminationObject)
1961                                {
1962                                        viewcell->GetPvs().AddSample(obj, ray.mPdf);
1963                                }                               
1964#if SAMPLE_ORIGIN_OBJECTS
1965                                 if (ray.mOriginObject)
1966                                 {
1967                                         viewcell->GetPvs().AddSample(ray.mOriginObject, ray.mPdf);
1968                                 }
1969#endif
1970                        }
1971                }
1972        }
1973
1974        return ray.mRelativePvsContribution;
1975}
1976
1977
1978void ViewCellsManager::GetRaySets(const VssRayContainer &sourceRays,
1979                                                                  const int maxSize,
1980                                                                  VssRayContainer &usedRays,
1981                                                                  VssRayContainer *savedRays) const
1982{
1983        const int limit = min(maxSize, (int)sourceRays.size());
1984        const float prop = (float)limit / ((float)sourceRays.size() + Limits::Small);
1985
1986        VssRayContainer::const_iterator it, it_end = sourceRays.end();
1987        for (it = sourceRays.begin(); it != it_end; ++ it)
1988        {
1989                if (Random(1.0f) < prop)
1990                        usedRays.push_back(*it);
1991                else if (savedRays)
1992                        savedRays->push_back(*it);
1993        }
1994}
1995
1996
1997float ViewCellsManager::GetRendercost(ViewCell *viewCell) const
1998{
1999        return (float)mViewCellsTree->GetPvsSize(viewCell);
2000}
2001
2002
2003float ViewCellsManager::GetAccVcArea()
2004{
2005        // if already computed
2006        if (mTotalAreaValid)
2007        {
2008                return mTotalArea;
2009        }
2010
2011        mTotalArea = 0;
2012        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2013
2014        for (it = mViewCells.begin(); it != it_end; ++ it)
2015        {
2016                //Debug << "area: " << GetArea(*it);
2017        mTotalArea += GetArea(*it);
2018        }
2019
2020        mTotalAreaValid = true;
2021
2022        return mTotalArea;
2023}
2024
2025
2026void ViewCellsManager::PrintStatistics(ostream &s) const
2027{
2028        s << mCurrentViewCellsStats << endl;
2029}
2030
2031
2032void ViewCellsManager::CreateUniqueViewCellIds()
2033{
2034        if (ViewCellsTreeConstructed())
2035        {
2036                mViewCellsTree->CreateUniqueViewCellsIds();
2037        }
2038        else // no view cells tree, handle view cells "myself"
2039        {
2040                int i = 0;
2041                ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
2042                for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
2043                {
2044                        if ((*vit)->GetId() != OUT_OF_BOUNDS_ID)
2045                        {
2046                                mViewCells[i]->SetId(i ++);
2047                        }
2048                }
2049        }
2050}
2051
2052
2053void ViewCellsManager::ExportViewCellsForViz(Exporter *exporter,
2054                                                                                         const AxisAlignedBox3 *sceneBox,
2055                                                                                         const AxisAlignedPlane *clipPlane,
2056                                                                                         const bool colorCode
2057                                                                                         ) const
2058{
2059        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2060
2061        for (it = mViewCells.begin(); it != it_end; ++ it)
2062        {
2063                if (!mOnlyValidViewCells || (*it)->GetValid())
2064                {
2065                        ExportColor(exporter, *it, colorCode); 
2066                        ExportViewCellGeometry(exporter, *it, sceneBox, clipPlane);
2067                }
2068        }
2069}
2070
2071
2072void ViewCellsManager::CreateViewCellMeshes()
2073{
2074        // convert to meshes
2075        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2076
2077        for (it = mViewCells.begin(); it != it_end; ++ it)
2078        {
2079                if (!(*it)->GetMesh())
2080                {
2081                        CreateMesh(*it);
2082                }
2083        }
2084}
2085
2086
2087bool ViewCellsManager::ExportViewCells(const string filename,
2088                                                                           const bool exportPvs,
2089                                                                           const ObjectContainer &objects)
2090{
2091        return false;
2092}
2093
2094
2095void ViewCellsManager::CollectViewCells(const int n)
2096{
2097        mNumActiveViewCells = n;
2098        mViewCells.clear();
2099        // implemented in subclasses
2100        CollectViewCells();
2101}
2102
2103
2104void ViewCellsManager::SetViewCellsActive()
2105{
2106        // collect leaf view cells and set the pointers to the currently
2107        // active view cells
2108        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2109
2110        for (it = mViewCells.begin(); it != it_end; ++ it)
2111        {
2112                ViewCellContainer leaves;
2113                mViewCellsTree->CollectLeaves(*it, leaves);
2114
2115                ViewCellContainer::const_iterator lit, lit_end = leaves.end();
2116                for (lit = mViewCells.begin(); lit != lit_end; ++ lit)
2117                {
2118                        dynamic_cast<ViewCellLeaf *>(*lit)->SetActiveViewCell(*it);
2119                }
2120        }
2121}
2122
2123
2124int ViewCellsManager::GetMaxFilterSize() const
2125{
2126        return mMaxFilterSize; 
2127}
2128
2129
2130static const bool USE_ASCII = true;
2131
2132
2133bool ViewCellsManager::ExportBoundingBoxes(const string filename,
2134                                                                                   const ObjectContainer &objects) const
2135{
2136        ObjectContainer::const_iterator it, it_end = objects.end();
2137       
2138        if (USE_ASCII)
2139        {
2140                ofstream boxesOut(filename.c_str());
2141                if (!boxesOut.is_open())
2142                        return false;
2143
2144                for (it = objects.begin(); it != it_end; ++ it)
2145                {
2146                        MeshInstance *mi = dynamic_cast<MeshInstance *>(*it);
2147                        const AxisAlignedBox3 box = mi->GetBox();
2148
2149                        boxesOut << mi->GetId() << " "
2150                                         << box.Min().x << " "
2151                                         << box.Min().y << " "
2152                                         << box.Min().z << " "
2153                                         << box.Max().x << " "
2154                                         << box.Max().y << " "
2155                     << box.Max().z << endl;   
2156                }
2157
2158                boxesOut.close();
2159        }
2160        else
2161        {
2162                ofstream boxesOut(filename.c_str(), ios::binary);
2163
2164                if (!boxesOut.is_open())
2165                        return false;
2166
2167                for (it = objects.begin(); it != it_end; ++ it)
2168                {       
2169                        MeshInstance *mi = dynamic_cast<MeshInstance *>(*it);
2170                        const AxisAlignedBox3 box = mi->GetBox();
2171                        Vector3 bmin = box.Min();
2172                        Vector3 bmax = box.Max();
2173                        int id = mi->GetId();
2174
2175                        boxesOut.write(reinterpret_cast<char *>(&id), sizeof(int));
2176                        boxesOut.write(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
2177                        boxesOut.write(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
2178                }
2179               
2180                boxesOut.close();
2181        }
2182
2183        return true;
2184}
2185
2186
2187bool ViewCellsManager::LoadBoundingBoxes(const string filename,
2188                                                                                 IndexedBoundingBoxContainer &boxes) const
2189{
2190        Vector3 bmin, bmax;
2191        int id;
2192
2193        if (USE_ASCII)
2194        {
2195                ifstream boxesIn(filename.c_str());
2196               
2197                if (!boxesIn.is_open())
2198                {
2199                        cout << "failed to open file " << filename << endl;
2200                        return false;
2201                }
2202
2203                string buf;
2204                while (!(getline(boxesIn, buf)).eof())
2205                {
2206                        sscanf(buf.c_str(), "%d %f %f %f %f %f %f",
2207                                   &id, &bmin.x, &bmin.y, &bmin.z,
2208                                   &bmax.x, &bmax.y, &bmax.z);
2209               
2210                        AxisAlignedBox3 box(bmin, bmax);
2211                        //      MeshInstance *mi = new MeshInstance();
2212                        // HACK: set bounding box to new box
2213                        //mi->mBox = box;
2214
2215                        boxes.push_back(IndexedBoundingBox(id, box));
2216                }
2217
2218                boxesIn.close();
2219        }
2220        else
2221        {
2222                ifstream boxesIn(filename.c_str(), ios::binary);
2223
2224                if (!boxesIn.is_open())
2225                        return false;
2226
2227                while (1)
2228                {
2229                        boxesIn.read(reinterpret_cast<char *>(&id), sizeof(Vector3));
2230                        boxesIn.read(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
2231                        boxesIn.read(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
2232                       
2233                        if (boxesIn.eof())
2234                                break;
2235
2236                       
2237                        AxisAlignedBox3 box(bmin, bmax);
2238                        MeshInstance *mi = new MeshInstance(NULL);
2239
2240                        // HACK: set bounding box to new box
2241                        //mi->mBox = box;
2242                        //boxes.push_back(mi);
2243                        boxes.push_back(IndexedBoundingBox(id, box));
2244                }
2245
2246                boxesIn.close();
2247        }
2248
2249        return true;
2250}
2251
2252
2253float ViewCellsManager::GetFilterWidth()
2254{
2255        return mFilterWidth;
2256}
2257
2258
2259float ViewCellsManager::GetAbsFilterWidth()
2260{
2261        return Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
2262}
2263
2264
2265void ViewCellsManager::UpdateScalarPvsSize(ViewCell *vc,
2266                                                                                   const int pvsSize,
2267                                                                                   const int entriesInPvs) const
2268{
2269        vc->mPvsSize = pvsSize;
2270        vc->mEntriesInPvs = entriesInPvs;
2271
2272        vc->mPvsSizeValid = true;
2273}
2274
2275
2276void
2277ViewCellsManager::ApplyFilter(ViewCell *viewCell,
2278                                                          KdTree *kdTree,
2279                                                          const float viewSpaceFilterSize,
2280                                                          const float spatialFilterSize,
2281                                                          ObjectPvs &pvs
2282                                                          )
2283{
2284  // extend the pvs of the viewcell by pvs of its neighbors
2285  // and apply spatial filter by including all neighbors of the objects
2286  // in the pvs
2287
2288  // get all viewcells intersecting the viewSpaceFilterBox
2289  // and compute the pvs union
2290 
2291  //Vector3 center = viewCell->GetBox().Center();
2292  //  Vector3 center = m->mBox.Center();
2293
2294        //  AxisAlignedBox3 box(center - Vector3(viewSpaceFilterSize/2),
2295        //                                        center + Vector3(viewSpaceFilterSize/2));
2296        if (!ViewCellsConstructed())
2297                return;
2298
2299        if (viewSpaceFilterSize >= 0.0f) {
2300
2301                const bool usePrVS = false;
2302
2303                if (!usePrVS) {
2304                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
2305                        box.Enlarge(Vector3(viewSpaceFilterSize/2));
2306
2307                        ViewCellContainer viewCells;
2308                        ComputeBoxIntersections(box, viewCells);
2309
2310                        //  cout<<"box="<<box<<endl;
2311                        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();
2312
2313                        int i;
2314                        for (i=0; it != it_end; ++ it, ++ i) {
2315                                //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
2316                                pvs.Merge((*it)->GetPvs());
2317                        }
2318                } else {
2319                        PrVs prvs;
2320                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
2321
2322                        //  mViewCellsManager->SetMaxFilterSize(1);
2323                        GetPrVS(box.Center(), prvs, viewSpaceFilterSize);
2324                        pvs = prvs.mViewCell->GetPvs();
2325                        DeleteLocalMergeTree(prvs.mViewCell);
2326                }
2327        } else
2328                pvs = viewCell->GetPvs();
2329
2330        if (spatialFilterSize >=0.0f)
2331                ApplySpatialFilter(kdTree, spatialFilterSize, pvs);
2332
2333}
2334
2335
2336
2337void
2338ViewCellsManager::ApplyFilter(KdTree *kdTree,
2339                                                          const float relViewSpaceFilterSize,
2340                                                          const float relSpatialFilterSize
2341                                                          )
2342{
2343
2344        if (!ViewCellsConstructed())
2345                return;
2346
2347        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2348
2349        ObjectPvs *newPvs;
2350        newPvs = new ObjectPvs[mViewCells.size()];
2351
2352        float viewSpaceFilterSize = Magnitude(mViewSpaceBox.Size())*relViewSpaceFilterSize;
2353        float spatialFilterSize = Magnitude(kdTree->GetBox().Size())*relSpatialFilterSize;
2354
2355        int i;
2356        for (i=0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
2357                ApplyFilter(*it,
2358                        kdTree,
2359                        viewSpaceFilterSize,
2360                        spatialFilterSize,
2361                        newPvs[i]
2362                        );
2363        }
2364
2365        // now replace all pvss
2366        for (i = 0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
2367
2368                ObjectPvs &pvs = (*it)->GetPvs();
2369                pvs.Clear();
2370                pvs = newPvs[i];
2371                newPvs[i].Clear();
2372        }
2373
2374        delete [] newPvs;
2375}
2376
2377
2378void
2379ViewCellsManager::ApplySpatialFilter(
2380                                                                         KdTree *kdTree,
2381                                                                         const float spatialFilterSize,
2382                                                                         ObjectPvs &pvs
2383                                                                         )
2384{
2385        // now compute a new Pvs by including also objects intersecting the
2386        // extended boxes of visible objects
2387        Intersectable::NewMail();
2388
2389        ObjectPvsMap::const_iterator oi;
2390
2391  for (oi = pvs.mEntries.begin(); oi != pvs.mEntries.end(); ++ oi)
2392  {
2393          Intersectable *object = (*oi).first;
2394      object->Mail();
2395  }
2396
2397  ObjectPvs nPvs;
2398  int nPvsSize = 0;
2399  // now go through the pvs again
2400  for (oi = pvs.mEntries.begin(); oi != pvs.mEntries.end(); ++oi) {
2401        Intersectable *object = (*oi).first;
2402
2403        //      Vector3 center = object->GetBox().Center();
2404        //      AxisAlignedBox3 box(center - Vector3(spatialFilterSize/2),
2405        //                                              center + Vector3(spatialFilterSize/2));
2406
2407        AxisAlignedBox3 box = object->GetBox();
2408        box.Enlarge(Vector3(spatialFilterSize/2));
2409
2410        ObjectContainer objects;
2411
2412        // $$ warning collect objects takes only unmailed ones!
2413        kdTree->CollectObjects(box, objects);
2414        //      cout<<"collected objects="<<objects.size()<<endl;
2415        ObjectContainer::const_iterator noi = objects.begin();
2416        for (; noi != objects.end(); ++ noi)
2417        {
2418                Intersectable *o = *noi;
2419                // $$ JB warning: pdfs are not correct at this point!     
2420                nPvs.AddSample(o, Limits::Small);
2421                nPvsSize ++;
2422        }
2423  }
2424  //  cout<<"nPvs size = "<<nPvsSize<<endl;
2425  pvs.Merge(nPvs);
2426}
2427
2428
2429void ViewCellsManager::ExportColor(Exporter *exporter,
2430                                                                   ViewCell *vc,
2431                                                                   bool colorCode) const
2432{
2433        const bool vcValid = CheckValidity(vc, mMinPvsSize, mMaxPvsSize);
2434
2435        float importance = 0;
2436        static Material m;
2437
2438        switch (mColorCode)
2439        {
2440        case 0: // Random
2441                {
2442                        if (vcValid)
2443                        {
2444                                m.mDiffuseColor.r = 0.5f + RandomValue(0.0f, 0.5f);
2445                                m.mDiffuseColor.g = 0.5f + RandomValue(0.0f, 0.5f);
2446                                m.mDiffuseColor.b = 0.5f + RandomValue(0.f, 0.5f);
2447                        }
2448                        else
2449                        {
2450                                m.mDiffuseColor.r = 0.0f;
2451                                m.mDiffuseColor.g = 1.0f;
2452                                m.mDiffuseColor.b = 0.0f;
2453                        }
2454
2455                        exporter->SetForcedMaterial(m);
2456                        return;
2457                }
2458               
2459        case 1: // pvs
2460                {
2461                        if (mCurrentViewCellsStats.maxPvs)
2462                        {
2463                                importance =
2464                                        (float)mViewCellsTree->GetPvsSize(vc) /
2465                                        (float)mCurrentViewCellsStats.maxPvs;
2466                        }
2467                }
2468                break;
2469        case 2: // merges
2470                {
2471            const int lSize = mViewCellsTree->GetNumInitialViewCells(vc);
2472                        importance = (float)lSize / (float)mCurrentViewCellsStats.maxLeaves;
2473                }
2474                break;
2475#if 0
2476        case 3: // merge tree differene
2477                {
2478                        importance = (float)GetMaxTreeDiff(vc) /
2479                                (float)(mVspBspTree->GetStatistics().maxDepth * 2);
2480
2481                }
2482                break;
2483#endif
2484        default:
2485                break;
2486        }
2487
2488        // special color code for invalid view cells
2489        m.mDiffuseColor.r = importance;
2490        m.mDiffuseColor.g = 1.0f - m.mDiffuseColor.r;
2491        m.mDiffuseColor.b = vcValid ? 1.0f : 0.0f;
2492
2493        //Debug << "importance: " << importance << endl;
2494        exporter->SetForcedMaterial(m);
2495}
2496
2497
2498void ViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
2499                                                                                          vector<MergeCandidate> &candidates)
2500{
2501        // implemented in subclasses
2502}
2503
2504
2505void
2506ViewCellsManager::UpdatePvsForEvaluation()
2507{
2508  ObjectPvs objPvs;
2509  UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), objPvs);
2510}
2511
2512void ViewCellsManager::UpdatePvsForEvaluation(ViewCell *root, ObjectPvs &pvs)
2513{
2514        // terminate traversal
2515        if (root->IsLeaf())
2516        {
2517                // we assume that pvs is explicitly stored in leaves
2518                pvs = root->GetPvs();
2519                UpdateScalarPvsSize(root, pvs.CountObjectsInPvs(), pvs.GetSize());
2520               
2521                return;
2522        }
2523       
2524        ////////////////
2525        //-- interior node => propagate pvs up the tree
2526
2527        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(root);
2528
2529        // reset interior pvs
2530        interior->GetPvs().Clear();
2531        // reset recursive pvs
2532        pvs.Clear();
2533        vector<ObjectPvs> pvsList;
2534
2535        ViewCellContainer::const_iterator vit, vit_end = interior->mChildren.end();
2536
2537        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit)
2538        {
2539                ObjectPvs objPvs;
2540               
2541                //////////////////
2542                //-- recursivly compute child pvss
2543
2544                UpdatePvsForEvaluation(*vit, objPvs);
2545
2546                // store pvs in vector
2547                pvsList.push_back(objPvs);
2548        }
2549
2550#if 1
2551        Intersectable::NewMail();
2552
2553        //-- faster way of computing pvs:
2554        //-- construct merged pvs by adding
2555        //-- and only those of the next pvs which were not mailed.
2556        //-- note: sumpdf is not correct!!
2557
2558        vector<ObjectPvs>::iterator oit = pvsList.begin();
2559
2560        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ oit)
2561        {
2562            ObjectPvsMap::iterator pit, pit_end = (*oit).mEntries.end();
2563       
2564                for (pit = (*oit).mEntries.begin(); pit != pit_end; ++ pit)
2565                {
2566                        Intersectable *intersect = (*pit).first;
2567
2568                        if (!intersect->Mailed())
2569                        {
2570                                pvs.AddSample(intersect, (*pit).second.mSumPdf);
2571                                intersect->Mail();
2572                        }
2573                }
2574        }
2575
2576        // store pvs in this node
2577        if (mViewCellsTree->ViewCellsStorage() == ViewCellsTree::PVS_IN_INTERIORS)
2578        {
2579                interior->SetPvs(pvs);
2580        }
2581       
2582        // set new pvs size
2583        UpdateScalarPvsSize(interior, pvs.CountObjectsInPvs(), pvs.GetSize());
2584       
2585#else
2586        // really merge cells: slow put sumPdf is correct
2587        viewCellInterior->GetPvs().Merge(backVc->GetPvs());
2588        viewCellInterior->GetPvs().Merge(frontVc->GetPvs());
2589#endif
2590}
2591
2592
2593
2594/*******************************************************************/
2595/*               BspViewCellsManager implementation                */
2596/*******************************************************************/
2597
2598
2599BspViewCellsManager::BspViewCellsManager(ViewCellsTree *vcTree, BspTree *bspTree):
2600ViewCellsManager(vcTree), mBspTree(bspTree)
2601{
2602        Environment::GetSingleton()->GetIntValue("BspTree.Construction.samples", mInitialSamples);
2603
2604        mBspTree->SetViewCellsManager(this);
2605        mBspTree->SetViewCellsTree(mViewCellsTree);
2606}
2607
2608
2609bool BspViewCellsManager::ViewCellsConstructed() const
2610{
2611        return mBspTree->GetRoot() != NULL;
2612}
2613
2614
2615ViewCell *BspViewCellsManager::GenerateViewCell(Mesh *mesh) const
2616{
2617        return new BspViewCell(mesh);
2618}
2619
2620
2621int BspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
2622                                                                                          const VssRayContainer &rays)
2623{
2624        // if view cells were already constructed, we can finish
2625        if (ViewCellsConstructed())
2626                return 0;
2627
2628        int sampleContributions = 0;
2629
2630        // construct view cells using the collected samples
2631        RayContainer constructionRays;
2632        VssRayContainer savedRays;
2633
2634        // choose a a number of rays based on the ratio of cast rays / requested rays
2635        const int limit = min(mInitialSamples, (int)rays.size());
2636        VssRayContainer::const_iterator it, it_end = rays.end();
2637
2638        const float prop = (float)limit / ((float)rays.size() + Limits::Small);
2639
2640        for (it = rays.begin(); it != it_end; ++ it)
2641        {
2642                if (Random(1.0f) < prop)
2643                        constructionRays.push_back(new Ray(*(*it)));
2644                else
2645                        savedRays.push_back(*it);
2646        }
2647
2648    if (!mUsePredefinedViewCells)
2649        {
2650                // no view cells loaded
2651                mBspTree->Construct(objects, constructionRays, &mViewSpaceBox);
2652                // collect final view cells
2653                mBspTree->CollectViewCells(mViewCells);
2654        }
2655        else
2656        {       
2657                // use predefined view cells geometry =>
2658                // contruct bsp hierarchy over them
2659                mBspTree->Construct(mViewCells);
2660        }
2661
2662        // destroy rays created only for construction
2663        CLEAR_CONTAINER(constructionRays);
2664
2665        Debug << mBspTree->GetStatistics() << endl;
2666        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
2667
2668        // recast rest of the rays
2669        if (SAMPLE_AFTER_SUBDIVISION)
2670                ComputeSampleContributions(savedRays, true, false);
2671
2672        // real meshes are contructed at this stage
2673        if (0)
2674        {
2675                cout << "finalizing view cells ... ";
2676                FinalizeViewCells(true);
2677                cout << "finished" << endl;     
2678        }
2679
2680        return sampleContributions;
2681}
2682
2683
2684void BspViewCellsManager::CollectViewCells()
2685{       
2686        if (!ViewCellsTreeConstructed())
2687        {       // view cells tree constructed 
2688                mBspTree->CollectViewCells(mViewCells);
2689        }
2690        else
2691        {       // we can use the view cells tree hierarchy to get the right set
2692                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
2693        }
2694}
2695
2696
2697float BspViewCellsManager::GetProbability(ViewCell *viewCell)
2698{
2699        if (1)
2700                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
2701        else
2702                // compute view cell area as subsititute for probability
2703                return GetArea(viewCell) / GetAccVcArea();
2704}
2705
2706
2707
2708int BspViewCellsManager::CastLineSegment(const Vector3 &origin,
2709                                                                                 const Vector3 &termination,
2710                                                                                 ViewCellContainer &viewcells)
2711{
2712        return mBspTree->CastLineSegment(origin, termination, viewcells);
2713}
2714
2715
2716void ViewCellsManager::ExportMergedViewCells(const ObjectContainer &objects)
2717{
2718        // save color code
2719        const int savedColorCode = mColorCode;
2720
2721        // export merged view cells
2722        mColorCode = 0; // use random colors
2723
2724        Exporter *exporter = Exporter::GetExporter("merged_view_cells.wrl");
2725
2726        cout << "exporting view cells after merge ... ";
2727
2728        if (exporter)
2729        {
2730                if (mExportGeometry)
2731                {
2732                        exporter->ExportGeometry(objects);
2733                }
2734
2735                exporter->SetFilled();
2736                ExportViewCellsForViz(exporter, NULL, GetClipPlane());
2737
2738                delete exporter;
2739        }
2740        cout << "finished" << endl;
2741
2742        // export merged view cells using pvs color coding
2743        mColorCode = 1;
2744
2745        exporter = Exporter::GetExporter("merged_view_cells_pvs.wrl");
2746        cout << "exporting view cells after merge (pvs size) ... ";     
2747
2748        if (exporter)
2749        {
2750                if (mExportGeometry)
2751                {
2752                        exporter->ExportGeometry(objects);
2753                }
2754
2755                exporter->SetFilled();
2756                ExportViewCellsForViz(exporter, NULL, GetClipPlane());
2757
2758                delete exporter;
2759        }
2760        cout << "finished" << endl;
2761       
2762        mColorCode = savedColorCode;
2763}
2764
2765
2766int BspViewCellsManager::PostProcess(const ObjectContainer &objects,
2767                                                                         const VssRayContainer &rays)
2768{
2769        if (!ViewCellsConstructed())
2770        {
2771                Debug << "view cells not constructed" << endl;
2772                return 0;
2773        }
2774       
2775        // view cells already finished before post processing step,
2776        // i.e., because they were loaded from disc
2777        if (mViewCellsFinished)
2778        {
2779                FinalizeViewCells(true);
2780                EvaluateViewCellsStats();
2781
2782                return 0;
2783        }
2784
2785        //////////////////
2786        //-- merge leaves of the view cell hierarchy   
2787       
2788        cout << "starting post processing using " << mPostProcessSamples << " samples ... ";
2789        long startTime = GetTime();
2790       
2791        VssRayContainer postProcessRays;
2792        GetRaySets(rays, mPostProcessSamples, postProcessRays);
2793
2794        if (mMergeViewCells)
2795        {
2796                cout << "constructing visibility based merge tree" << endl;
2797                mViewCellsTree->ConstructMergeTree(rays, objects);
2798        }
2799        else
2800        {
2801                cout << "constructing spatial merge tree" << endl;
2802                ViewCell *root;
2803                // the spatial merge tree is difficult to build for
2804                // this type of construction, as view cells cover several
2805                // leaves => create dummy tree which is only 2 levels deep
2806                if (mUsePredefinedViewCells)
2807                {
2808                        root = ConstructDummyMergeTree(mBspTree->GetRoot());
2809                }
2810                else
2811                {
2812                        // create spatial merge hierarchy
2813                        root = ConstructSpatialMergeTree(mBspTree->GetRoot());
2814                }
2815               
2816                mViewCellsTree->SetRoot(root);
2817
2818                // recompute pvs in the whole hierarchy
2819                ObjectPvs pvs;
2820                UpdatePvsForEvaluation(root, pvs);
2821        }
2822
2823        cout << "finished" << endl;
2824        cout << "merged view cells in "
2825                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
2826
2827        Debug << "Postprocessing: Merged view cells in "
2828                << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl << endl;
2829
2830       
2831        ////////////////////////
2832        //-- visualization and statistics after merge
2833
2834        if (1)
2835        {
2836                char mstats[100];
2837                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
2838                mViewCellsTree->ExportStats(mstats);
2839        }
2840
2841        // recompute view cells and stats
2842        ResetViewCells();
2843        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
2844
2845        //  visualization of the view cells
2846        if (1) ExportMergedViewCells(objects);
2847
2848        // compute final meshes and volume / area
2849        if (1) FinalizeViewCells(true);
2850
2851        // write view cells to disc
2852        if (1 && mExportViewCells)
2853        {
2854                char filename[100];
2855                Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
2856                ExportViewCells(filename, mExportPvs, objects);
2857        }
2858       
2859        return 0;
2860}
2861
2862
2863BspViewCellsManager::~BspViewCellsManager()
2864{
2865}
2866
2867
2868int BspViewCellsManager::GetType() const
2869{
2870        return BSP;
2871}
2872
2873
2874void BspViewCellsManager::Visualize(const ObjectContainer &objects,
2875                                                                        const VssRayContainer &sampleRays)
2876{
2877        if (!ViewCellsConstructed())
2878                return;
2879       
2880        const int savedColorCode = mColorCode;
2881       
2882        if (1) // export final view cells
2883        {
2884                mColorCode = 1; // hack color code
2885                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
2886       
2887                cout << "exporting view cells after merge (pvs size) ... ";     
2888
2889                if (exporter)
2890                {
2891                        if (mExportGeometry)
2892                        {
2893                                exporter->ExportGeometry(objects);
2894                        }
2895
2896                        ExportViewCellsForViz(exporter, NULL, GetClipPlane());
2897                        delete exporter;
2898                }
2899                cout << "finished" << endl;
2900        }
2901
2902        // reset color code
2903        mColorCode = savedColorCode;
2904
2905
2906        //////////////////
2907        //-- visualization of the BSP splits
2908
2909        bool exportSplits = false;
2910        Environment::GetSingleton()->GetBoolValue("BspTree.Visualization.exportSplits", exportSplits);
2911
2912        if (exportSplits)
2913        {
2914                cout << "exporting splits ... ";
2915                ExportSplits(objects);
2916                cout << "finished" << endl;
2917        }
2918
2919        int leafOut;
2920        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
2921        const int raysOut = 100;
2922        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
2923}
2924
2925
2926void BspViewCellsManager::ExportSplits(const ObjectContainer &objects)
2927{
2928        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
2929
2930        if (exporter)
2931        {
2932                //exporter->SetFilled();
2933                if (mExportGeometry)
2934                {
2935                        exporter->ExportGeometry(objects);
2936                }
2937
2938                Material m;
2939                m.mDiffuseColor = RgbColor(1, 0, 0);
2940                exporter->SetForcedMaterial(m);
2941                exporter->SetWireframe();
2942
2943                exporter->ExportBspSplits(*mBspTree, true);
2944
2945                // NOTE: take forced material, else big scenes cannot be viewed
2946                m.mDiffuseColor = RgbColor(0, 1, 0);
2947                exporter->SetForcedMaterial(m);
2948                //exporter->ResetForcedMaterial();
2949
2950                delete exporter;
2951        }
2952}
2953
2954
2955void BspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
2956                                                                                                const int maxViewCells,
2957                                                                                                const bool sortViewCells,
2958                                                                                                const bool exportPvs,
2959                                                                                                const bool exportRays,
2960                                                                                                const int maxRays,
2961                                                                                                const string prefix,
2962                                                                                                VssRayContainer *visRays)
2963{
2964        if (sortViewCells)
2965        {       // sort view cells to visualize the largest view cells
2966                stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
2967        }
2968
2969        //////////
2970        //-- some view cells for output
2971
2972        ViewCell::NewMail();
2973        const int limit = min(maxViewCells, (int)mViewCells.size());
2974       
2975        for (int i = 0; i < limit; ++ i)
2976        {
2977                const int idx = sortViewCells ? (int)RandomValue(0, (float)mViewCells.size() - 0.5f) : i;
2978                ViewCell *vc = mViewCells[idx];
2979
2980                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
2981                        continue;
2982
2983                vc->Mail();
2984
2985                ObjectPvs pvs;
2986                mViewCellsTree->GetPvs(vc, pvs);
2987
2988                char s[64]; sprintf(s, "%sviewcell-%04d.wrl", prefix.c_str(), i);
2989                Exporter *exporter = Exporter::GetExporter(s);
2990               
2991                cout << "view cell " << idx << ": pvs size=" << (int)mViewCellsTree->GetPvsSize(vc) << endl;
2992
2993                if (exportRays)
2994                {
2995                        ////////////
2996                        //-- export rays piercing this view cell
2997
2998                        // use rays stored with the view cells
2999                        VssRayContainer vcRays, vcRays2, vcRays3;
3000            VssRayContainer collectRays;
3001
3002                        // collect initial view cells
3003                        ViewCellContainer leaves;
3004                        mViewCellsTree->CollectLeaves(vc, leaves);
3005
3006                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
3007                for (vit = leaves.begin(); vit != vit_end; ++ vit)
3008                        {       
3009                                // prepare some rays for output
3010                                VssRayContainer::const_iterator rit, rit_end = (*vit)->mVssRays.end();
3011                                for (rit = (*vit)->mVssRays.begin(); rit != rit_end; ++ rit)
3012                                {
3013                                        collectRays.push_back(*rit);
3014                                }
3015                        }
3016
3017                        const int raysOut = min((int)collectRays.size(), maxRays);
3018
3019                        // prepare some rays for output
3020                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
3021                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
3022                        {
3023                                const float p = RandomValue(0.0f, (float)collectRays.size());
3024                                if (p < raysOut)
3025                                {
3026                                        if ((*rit)->mFlags & VssRay::BorderSample)
3027                                        {
3028                                                vcRays.push_back(*rit);
3029                                        }
3030                                        else if ((*rit)->mFlags & VssRay::ReverseSample)
3031                                                vcRays2.push_back(*rit);
3032                                        else
3033                                                vcRays3.push_back(*rit);
3034                                               
3035                                }
3036                        }
3037
3038                        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
3039                        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
3040                        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
3041                }
3042               
3043                ////////////////
3044                //-- export view cell geometry
3045
3046                exporter->SetWireframe();
3047
3048                Material m;//= RandomMaterial();
3049                m.mDiffuseColor = RgbColor(0, 1, 0);
3050                exporter->SetForcedMaterial(m);
3051
3052                ExportViewCellGeometry(exporter, vc, NULL, NULL);
3053                exporter->SetFilled();
3054
3055                if (exportPvs)
3056                {
3057                        Intersectable::NewMail();
3058                        ObjectPvsMap::const_iterator oit, oit_end = pvs.mEntries.end();
3059                       
3060                        // output PVS of view cell
3061                        for (oit = pvs.mEntries.begin(); oit != oit_end; ++ oit)
3062                        {               
3063                                Intersectable *intersect = (*oit).first;
3064                               
3065                                if (!intersect->Mailed())
3066                                {
3067                                        intersect->Mail();
3068
3069                                        m = RandomMaterial();
3070                                        exporter->SetForcedMaterial(m);
3071                                        exporter->ExportIntersectable(intersect);
3072                                }
3073                        }
3074                        cout << endl;
3075                }
3076               
3077                DEL_PTR(exporter);
3078                cout << "finished" << endl;
3079        }
3080}
3081
3082
3083void BspViewCellsManager::TestSubdivision()
3084{
3085        ViewCellContainer leaves;
3086        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
3087
3088        ViewCellContainer::const_iterator it, it_end = leaves.end();
3089
3090        const float vol = mViewSpaceBox.GetVolume();
3091        float subdivVol = 0;
3092        float newVol = 0;
3093
3094        for (it = leaves.begin(); it != it_end; ++ it)
3095        {
3096                BspNodeGeometry geom;
3097                mBspTree->ConstructGeometry(*it, geom);
3098
3099                const float lVol = geom.GetVolume();
3100                newVol += lVol;
3101                subdivVol += (*it)->GetVolume();
3102
3103                const float thres = 0.9f;
3104                if ((lVol < ((*it)->GetVolume() * thres)) ||
3105                        (lVol * thres > ((*it)->GetVolume())))
3106                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
3107        }
3108       
3109        Debug << "exact volume: " << vol << endl;
3110        Debug << "subdivision volume: " << subdivVol << endl;
3111        Debug << "new volume: " << newVol << endl;
3112}
3113
3114
3115void BspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
3116                                                                                                 ViewCell *vc,
3117                                                                                                 const AxisAlignedBox3 *sceneBox,
3118                                                                                                 const AxisAlignedPlane *clipPlane
3119                                                                                                 ) const
3120{
3121        if (clipPlane)
3122        {
3123                const Plane3 plane = clipPlane->GetPlane();
3124
3125                ViewCellContainer leaves;
3126                mViewCellsTree->CollectLeaves(vc, leaves);
3127                ViewCellContainer::const_iterator it, it_end = leaves.end();
3128
3129                for (it = leaves.begin(); it != it_end; ++ it)
3130                {
3131                        BspNodeGeometry geom;
3132                        BspNodeGeometry front;
3133                        BspNodeGeometry back;
3134
3135                        mBspTree->ConstructGeometry(*it, geom);
3136
3137                        const float eps = 0.0001f;
3138                        const int cf = geom.Side(plane, eps);
3139
3140                        if (cf == -1)
3141                        {
3142                                exporter->ExportPolygons(geom.GetPolys());
3143                        }
3144                        else if (cf == 0)
3145                        {
3146                                geom.SplitGeometry(front,
3147                                                                   back,
3148                                                                   plane,
3149                                                                   mViewSpaceBox,
3150                                                                   eps);
3151
3152                                if (back.Valid())
3153                                {
3154                                        exporter->ExportPolygons(back.GetPolys());
3155                                }                       
3156                        }
3157                }
3158        }
3159        else
3160        {
3161                // export mesh if available
3162                // TODO: some bug here?
3163                if (1 && vc->GetMesh())
3164                {
3165                        exporter->ExportMesh(vc->GetMesh());
3166                }
3167                else
3168                {
3169                        BspNodeGeometry geom;
3170                        mBspTree->ConstructGeometry(vc, geom);
3171                        exporter->ExportPolygons(geom.GetPolys());
3172                }
3173        }
3174}
3175
3176
3177void BspViewCellsManager::CreateMesh(ViewCell *vc)
3178{
3179        // note: should previous mesh be deleted (via mesh manager?)
3180        BspNodeGeometry geom;
3181        mBspTree->ConstructGeometry(vc, geom);
3182
3183        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
3184
3185        IncludeNodeGeomInMesh(geom, *mesh);
3186        vc->SetMesh(mesh);
3187}
3188
3189
3190void BspViewCellsManager::Finalize(ViewCell *viewCell,
3191                                                                   const bool createMesh)
3192{
3193        float area = 0;
3194        float volume = 0;
3195
3196        ViewCellContainer leaves;
3197        mViewCellsTree->CollectLeaves(viewCell, leaves);
3198
3199        ViewCellContainer::const_iterator it, it_end = leaves.end();
3200
3201    for (it = leaves.begin(); it != it_end; ++ it)
3202        {
3203                BspNodeGeometry geom;
3204
3205                mBspTree->ConstructGeometry(*it, geom);
3206
3207                const float lVol = geom.GetVolume();
3208                const float lArea = geom.GetArea();
3209
3210                area += lArea;
3211                volume += lVol;
3212       
3213                CreateMesh(*it);
3214        }
3215
3216        viewCell->SetVolume(volume);
3217        viewCell->SetArea(area);
3218}
3219
3220
3221ViewCell *BspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
3222{
3223        if (!ViewCellsConstructed())
3224        {
3225                return NULL;
3226        }
3227        if (!mViewSpaceBox.IsInside(point))
3228        {
3229                return NULL;
3230        }
3231        return mBspTree->GetViewCell(point);
3232}
3233
3234
3235void BspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3236                                                                                                 vector<MergeCandidate> &candidates)
3237{
3238        cout << "collecting merge candidates ... " << endl;
3239
3240        if (mUseRaysForMerge)
3241        {
3242                mBspTree->CollectMergeCandidates(rays, candidates);
3243        }
3244        else
3245        {
3246                vector<BspLeaf *> leaves;
3247                mBspTree->CollectLeaves(leaves);
3248                mBspTree->CollectMergeCandidates(leaves, candidates);
3249        }
3250
3251        cout << "fininshed collecting candidates" << endl;
3252}
3253
3254
3255
3256bool BspViewCellsManager::ExportViewCells(const string filename,
3257                                                                                  const bool exportPvs,
3258                                                                                  const ObjectContainer &objects)
3259{
3260        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
3261        {
3262                return false;
3263        }
3264
3265        cout << "exporting view cells to xml ... ";
3266
3267        OUT_STREAM stream(filename.c_str());
3268
3269        // for output we need unique ids for each view cell
3270        CreateUniqueViewCellIds();
3271
3272        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
3273        stream << "<VisibilitySolution>" << endl;
3274
3275        if (exportPvs)
3276        {
3277                //////////
3278                //-- export bounding boxes: they are used to identify the objects from the pvs and
3279                //-- assign them to the entities in the rendering engine
3280
3281                stream << "<BoundingBoxes>" << endl;
3282                ObjectContainer::const_iterator oit, oit_end = objects.end();
3283
3284                for (oit = objects.begin(); oit != oit_end; ++ oit)
3285                {
3286                        const AxisAlignedBox3 box = (*oit)->GetBox();
3287                       
3288                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
3289                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
3290                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
3291                }
3292
3293                stream << "</BoundingBoxes>" << endl;
3294        }
3295
3296        ///////////
3297        //-- export the view cells and the pvs
3298
3299        const int numViewCells = mCurrentViewCellsStats.viewCells;
3300        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
3301
3302        mViewCellsTree->Export(stream, exportPvs);
3303       
3304        stream << "</ViewCells>" << endl;
3305
3306        /////////////
3307        //-- export the view space hierarchy
3308        stream << "<ViewSpaceHierarchy type=\"bsp\""
3309                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
3310                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
3311
3312        mBspTree->Export(stream);
3313
3314        // end tags
3315        stream << "</ViewSpaceHierarchy>" << endl;
3316        stream << "</VisibilitySolution>" << endl;
3317
3318        stream.close();
3319        cout << "finished" << endl;
3320
3321        return true;
3322}
3323
3324
3325ViewCell *BspViewCellsManager::ConstructDummyMergeTree(BspNode *root)
3326{
3327        ViewCellInterior *vcRoot = new ViewCellInterior();
3328               
3329        // evaluate merge cost for priority traversal
3330        const float mergeCost = 1.0f / (float)root->mTimeStamp;
3331        vcRoot->SetMergeCost(mergeCost);
3332
3333        float volume = 0;
3334        vector<BspLeaf *> leaves;
3335        mBspTree->CollectLeaves(leaves);
3336        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
3337        ViewCell::NewMail();
3338
3339        for (lit = leaves.begin(); lit != lit_end; ++ lit)
3340        {
3341                BspLeaf *leaf = *lit;
3342                ViewCell *vc = leaf->GetViewCell();
3343
3344                if (!vc->Mailed())
3345                {
3346                        vc->Mail();
3347                        vc->SetMergeCost(0.0f);
3348                        vcRoot->SetupChildLink(vc);
3349
3350                        volume += vc->GetVolume();
3351                        volume += vc->GetVolume();     
3352                        vcRoot->SetVolume(volume);
3353                }
3354        }
3355       
3356        return vcRoot;
3357}
3358
3359
3360ViewCell *BspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
3361{
3362        // terminate recursion
3363        if (root->IsLeaf())
3364        {
3365                BspLeaf *leaf = dynamic_cast<BspLeaf *>(root);
3366                leaf->GetViewCell()->SetMergeCost(0.0f);
3367                return leaf->GetViewCell();
3368        }
3369       
3370        BspInterior *interior = dynamic_cast<BspInterior *>(root);
3371        ViewCellInterior *viewCellInterior = new ViewCellInterior();
3372               
3373        // evaluate merge cost for priority traversal
3374        float mergeCost = 1.0f / (float)root->mTimeStamp;
3375        viewCellInterior->SetMergeCost(mergeCost);
3376
3377        float volume = 0;
3378       
3379        BspNode *front = interior->GetFront();
3380        BspNode *back = interior->GetBack();
3381
3382
3383        ////////////
3384        //-- recursivly compute child hierarchies
3385
3386        ViewCell *backVc = ConstructSpatialMergeTree(back);
3387        ViewCell *frontVc = ConstructSpatialMergeTree(front);
3388
3389        viewCellInterior->SetupChildLink(backVc);
3390        viewCellInterior->SetupChildLink(frontVc);
3391
3392        volume += backVc->GetVolume();
3393        volume += frontVc->GetVolume();
3394
3395        viewCellInterior->SetVolume(volume);
3396
3397        return viewCellInterior;
3398}
3399
3400
3401/************************************************************************/
3402/*                   KdViewCellsManager implementation                  */
3403/************************************************************************/
3404
3405
3406
3407KdViewCellsManager::KdViewCellsManager(ViewCellsTree *vcTree, KdTree *kdTree):
3408ViewCellsManager(vcTree), mKdTree(kdTree), mKdPvsDepth(100)
3409{
3410}
3411
3412
3413float KdViewCellsManager::GetProbability(ViewCell *viewCell)
3414{
3415        // compute view cell area / volume as subsititute for probability
3416        if (0)
3417                return GetArea(viewCell) / GetViewSpaceBox().SurfaceArea();
3418        else
3419                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
3420}
3421
3422
3423
3424
3425void KdViewCellsManager::CollectViewCells()
3426{
3427        //mKdTree->CollectViewCells(mViewCells); TODO
3428}
3429
3430
3431int KdViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
3432                                                                  const VssRayContainer &rays)
3433{
3434        // if view cells already constructed
3435        if (ViewCellsConstructed())
3436                return 0;
3437
3438        mKdTree->Construct();
3439
3440        mTotalAreaValid = false;
3441        // create the view cells
3442        mKdTree->CreateAndCollectViewCells(mViewCells);
3443        // cast rays
3444        ComputeSampleContributions(rays, true, false);
3445
3446        EvaluateViewCellsStats();
3447        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
3448
3449        return 0;
3450}
3451
3452
3453bool KdViewCellsManager::ViewCellsConstructed() const
3454{
3455        return mKdTree->GetRoot() != NULL;
3456}
3457
3458
3459int KdViewCellsManager::PostProcess(const ObjectContainer &objects,
3460                                                                        const VssRayContainer &rays)
3461{
3462        return 0;
3463}
3464
3465
3466void KdViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
3467                                                                                           const int maxViewCells,
3468                                                                                           const bool sortViewCells,
3469                                                                                           const bool exportPvs,
3470                                                                                           const bool exportRays,
3471                                                                                           const int maxRays,
3472                                                                                           const string prefix,
3473                                                                                           VssRayContainer *visRays)
3474{
3475        // TODO
3476}
3477
3478
3479void KdViewCellsManager::Visualize(const ObjectContainer &objects,
3480                                                                   const VssRayContainer &sampleRays)
3481{
3482        if (!ViewCellsConstructed())
3483                return;
3484
3485        // using view cells instead of the kd PVS of objects
3486        const bool useViewCells = true;
3487        bool exportRays = false;
3488
3489        int limit = min(mVisualizationSamples, (int)sampleRays.size());
3490        const int pvsOut = min((int)objects.size(), 10);
3491        VssRayContainer *rays = new VssRayContainer[pvsOut];
3492
3493        if (useViewCells)
3494        {
3495                const int leafOut = 10;
3496
3497                ViewCell::NewMail();
3498
3499                //-- some rays for output
3500                const int raysOut = min((int)sampleRays.size(), mVisualizationSamples);
3501                Debug << "visualization using " << raysOut << " samples" << endl;
3502
3503                //-- some random view cells and rays for output
3504                vector<KdLeaf *> kdLeaves;
3505
3506                for (int i = 0; i < leafOut; ++ i)
3507                        kdLeaves.push_back(dynamic_cast<KdLeaf *>(mKdTree->GetRandomLeaf()));
3508
3509                for (int i = 0; i < kdLeaves.size(); ++ i)
3510                {
3511                        KdLeaf *leaf = kdLeaves[i];
3512                        RayContainer vcRays;
3513
3514                        cout << "creating output for view cell " << i << " ... ";
3515#if 0
3516                        // check whether we can add the current ray to the output rays
3517                        for (int k = 0; k < raysOut; ++ k)
3518                        {
3519                                Ray *ray = sampleRays[k];
3520
3521                                for (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
3522                                {
3523                                        BspLeaf *leaf2 = ray->bspIntersections[j].mLeaf;
3524
3525                                        if (leaf->GetViewCell() == leaf2->GetViewCell())
3526                                        {
3527                                                vcRays.push_back(ray);
3528                                        }
3529                                }
3530                        }
3531#endif
3532                        Intersectable::NewMail();
3533
3534                        ViewCell *vc = leaf->mViewCell;
3535                        char str[64]; sprintf(str, "viewcell%04d.wrl", i);
3536
3537                        Exporter *exporter = Exporter::GetExporter(str);
3538                        exporter->SetFilled();
3539
3540                        exporter->SetWireframe();
3541                        //exporter->SetFilled();
3542
3543                        Material m;//= RandomMaterial();
3544                        m.mDiffuseColor = RgbColor(1, 1, 0);
3545                        exporter->SetForcedMaterial(m);
3546
3547                        AxisAlignedBox3 box = mKdTree->GetBox(leaf);
3548                        exporter->ExportBox(box);
3549
3550                        // export rays piercing this view cell
3551                        exporter->ExportRays(vcRays, 1000, RgbColor(0, 1, 0));
3552
3553                        m.mDiffuseColor = RgbColor(1, 0, 0);
3554                        exporter->SetForcedMaterial(m);
3555
3556                        // exporter->SetWireframe();
3557                        exporter->SetFilled();
3558
3559                        ObjectPvsMap::iterator it, it_end = vc->GetPvs().mEntries.end();
3560                        // -- output PVS of view cell
3561                        for (it = vc->GetPvs().mEntries.begin(); it != it_end; ++ it)
3562                        {
3563                                Intersectable *intersect = (*it).first;
3564                                if (!intersect->Mailed())
3565                                {
3566                                        exporter->ExportIntersectable(intersect);
3567                                        intersect->Mail();
3568                                }
3569                        }
3570
3571                        DEL_PTR(exporter);
3572                        cout << "finished" << endl;
3573                }
3574
3575                DEL_PTR(rays);
3576        }
3577        else // using kd PVS of objects
3578        {
3579                for (int i = 0; i < limit; ++ i)
3580                {
3581                        VssRay *ray = sampleRays[i];
3582
3583                        // check whether we can add this to the rays
3584                        for (int j = 0; j < pvsOut; j++)
3585                        {
3586                                if (objects[j] == ray->mTerminationObject)
3587                                {
3588                                        rays[j].push_back(ray);
3589                                }
3590                        }
3591                }
3592
3593                if (exportRays)
3594                {
3595                        Exporter *exporter = NULL;
3596                        exporter = Exporter::GetExporter("sample-rays.x3d");
3597                        exporter->SetWireframe();
3598                        exporter->ExportKdTree(*mKdTree);
3599
3600                        for (i = 0; i < pvsOut; i++)
3601                                exporter->ExportRays(rays[i], RgbColor(1, 0, 0));
3602
3603                        exporter->SetFilled();
3604                        delete exporter;
3605                }
3606
3607                for (int k=0; k < pvsOut; k++)
3608                {
3609                        Intersectable *object = objects[k];
3610                        char str[64]; sprintf(str, "viewcell%04d.wrl", i);
3611
3612                        Exporter *exporter = Exporter::GetExporter(str);
3613                        exporter->SetWireframe();
3614
3615                        KdPvsMap::iterator kit = object->mKdPvs.mEntries.begin();
3616                        Intersectable::NewMail();
3617
3618                        // avoid adding the object to the list
3619                        object->Mail();
3620                        ObjectContainer visibleObjects;
3621
3622                        for (; kit != object->mKdPvs.mEntries.end(); i++)
3623                        {
3624                                KdNode *node = (*kit).first;
3625                                exporter->ExportBox(mKdTree->GetBox(node));
3626
3627                                mKdTree->CollectObjects(node, visibleObjects);
3628                        }
3629
3630                        exporter->ExportRays(rays[k],  RgbColor(0, 1, 0));
3631                        exporter->SetFilled();
3632
3633                        for (int j = 0; j < visibleObjects.size(); j++)
3634                                exporter->ExportIntersectable(visibleObjects[j]);
3635
3636                        Material m;
3637                        m.mDiffuseColor = RgbColor(1, 0, 0);
3638                        exporter->SetForcedMaterial(m);
3639                        exporter->ExportIntersectable(object);
3640
3641                        delete exporter;
3642                }
3643        }
3644}
3645
3646
3647ViewCell *KdViewCellsManager::GenerateViewCell(Mesh *mesh) const
3648{
3649        return new KdViewCell(mesh);
3650}
3651
3652
3653void KdViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
3654                                                                                                ViewCell *vc,
3655                                                                                                const AxisAlignedBox3 *sceneBox,
3656                                                                                                const AxisAlignedPlane *clipPlane
3657                                                                                                ) const
3658{
3659        ViewCellContainer leaves;
3660        mViewCellsTree->CollectLeaves(vc, leaves);
3661        ViewCellContainer::const_iterator it, it_end = leaves.end();
3662
3663        for (it = leaves.begin(); it != it_end; ++ it)
3664        {
3665                KdViewCell *kdVc = dynamic_cast<KdViewCell *>(*it);
3666                exporter->ExportBox(mKdTree->GetBox(kdVc->mLeaves[0]));
3667        }
3668}
3669
3670
3671int KdViewCellsManager::GetType() const
3672{
3673        return ViewCellsManager::KD;
3674}
3675
3676
3677
3678KdNode *KdViewCellsManager::GetNodeForPvs(KdLeaf *leaf)
3679{
3680        KdNode *node = leaf;
3681
3682        while (node->mParent && node->mDepth > mKdPvsDepth)
3683                node = node->mParent;
3684
3685        return node;
3686}
3687
3688int KdViewCellsManager::CastLineSegment(const Vector3 &origin,
3689                                                                                const Vector3 &termination,
3690                                                                                ViewCellContainer &viewcells)
3691{
3692        return mKdTree->CastLineSegment(origin, termination, viewcells);
3693}
3694
3695
3696void KdViewCellsManager::CreateMesh(ViewCell *vc)
3697{
3698        // TODO
3699}
3700
3701
3702
3703void KdViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3704                                                                                                vector<MergeCandidate> &candidates)
3705{
3706        // TODO
3707}
3708
3709
3710
3711/**************************************************************************/
3712/*                   VspBspViewCellsManager implementation                */
3713/**************************************************************************/
3714
3715
3716VspBspViewCellsManager::VspBspViewCellsManager(ViewCellsTree *vcTree, VspBspTree *vspBspTree):
3717ViewCellsManager(vcTree), mVspBspTree(vspBspTree)
3718{
3719        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", mInitialSamples);
3720        mVspBspTree->SetViewCellsManager(this);
3721        mVspBspTree->mViewCellsTree = mViewCellsTree;
3722}
3723
3724
3725VspBspViewCellsManager::~VspBspViewCellsManager()
3726{
3727}
3728
3729
3730float VspBspViewCellsManager::GetProbability(ViewCell *viewCell)
3731{
3732        if (0 && mVspBspTree->mUseAreaForPvs)
3733                return GetArea(viewCell) / GetAccVcArea();
3734        else
3735                return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
3736}
3737
3738
3739void VspBspViewCellsManager::CollectViewCells()
3740{
3741        // view cells tree constructed?
3742        if (!ViewCellsTreeConstructed())
3743        {
3744                mVspBspTree->CollectViewCells(mViewCells, false);
3745        }
3746        else
3747        {       
3748                // we can use the view cells tree hierarchy to get the right set
3749                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
3750        }
3751}
3752
3753
3754void VspBspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3755                                                                                                        vector<MergeCandidate> &candidates)
3756{       
3757        cout << "collecting merge candidates ... " << endl;
3758
3759        if (mUseRaysForMerge)
3760        {
3761                mVspBspTree->CollectMergeCandidates(rays, candidates);
3762        }
3763        else
3764        {
3765                vector<BspLeaf *> leaves;
3766                mVspBspTree->CollectLeaves(leaves);
3767       
3768                mVspBspTree->CollectMergeCandidates(leaves, candidates);
3769        }
3770
3771        cout << "fininshed collecting candidates" << endl;
3772}
3773
3774
3775bool VspBspViewCellsManager::ViewCellsConstructed() const
3776{
3777        return mVspBspTree->GetRoot() != NULL;
3778}
3779
3780
3781ViewCell *VspBspViewCellsManager::GenerateViewCell(Mesh *mesh) const
3782{
3783        return new BspViewCell(mesh);
3784}
3785
3786
3787int VspBspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
3788                                                                                                 const VssRayContainer &rays)
3789{
3790        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
3791
3792        // if view cells were already constructed
3793        if (ViewCellsConstructed())
3794        {
3795                return 0;
3796        }
3797
3798        int sampleContributions = 0;
3799        VssRayContainer sampleRays;
3800
3801        const int limit = min(mInitialSamples, (int)rays.size());
3802
3803        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
3804                  << ", actual rays: " << (int)rays.size() << endl;
3805
3806        VssRayContainer savedRays;
3807
3808        if (SAMPLE_AFTER_SUBDIVISION)
3809        {
3810                VssRayContainer constructionRays;
3811               
3812                GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
3813
3814                Debug << "rays used for initial construction: " << (int)constructionRays.size() << endl;
3815                Debug << "rays saved for later use: " << (int)savedRays.size() << endl;
3816       
3817                mVspBspTree->Construct(constructionRays, &mViewSpaceBox);
3818        }
3819        else
3820        {
3821                Debug << "rays used for initial construction: " << (int)rays.size() << endl;
3822                mVspBspTree->Construct(rays, &mViewSpaceBox);
3823        }
3824
3825        // collapse invalid regions
3826        cout << "collapsing invalid tree regions ... ";
3827        long startTime = GetTime();
3828
3829        const int collapsedLeaves = mVspBspTree->CollapseTree();
3830        Debug << "collapsed in " << TimeDiff(startTime, GetTime()) * 1e-3
3831                  << " seconds" << endl;
3832
3833    cout << "finished" << endl;
3834
3835        /////////////////
3836        //-- stats after construction
3837
3838        Debug << mVspBspTree->GetStatistics() << endl;
3839
3840        ResetViewCells();
3841        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
3842
3843
3844        //////////////////////
3845        //-- recast the rest of the rays
3846
3847        startTime = GetTime();
3848
3849        cout << "Computing remaining ray contributions ... ";
3850
3851        if (SAMPLE_AFTER_SUBDIVISION)
3852                ComputeSampleContributions(savedRays, true, false);
3853
3854        cout << "finished" << endl;
3855
3856        Debug << "Computed remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
3857                  << " secs" << endl;
3858
3859        cout << "construction finished" << endl;
3860
3861        if (0)
3862        {       ////////
3863                //-- real meshes are contructed at this stage
3864                cout << "finalizing view cells ... ";
3865                FinalizeViewCells(true);
3866                cout << "finished" << endl;
3867        }
3868
3869        return sampleContributions;
3870}
3871
3872
3873void VspBspViewCellsManager::MergeViewCells(const VssRayContainer &rays,
3874                                                                                        const ObjectContainer &objects)
3875{
3876    int vcSize = 0;
3877        int pvsSize = 0;
3878
3879        //-- merge view cells
3880        cout << "starting merge using " << mPostProcessSamples << " samples ... " << endl;
3881        long startTime = GetTime();
3882
3883
3884        if (mMergeViewCells)
3885        {
3886                // TODO: should be done BEFORE the ray casting
3887                // compute tree by merging the nodes based on cost heuristics
3888                mViewCellsTree->ConstructMergeTree(rays, objects);
3889        }
3890        else
3891        {
3892                // compute tree by merging the nodes of the spatial hierarchy
3893                ViewCell *root = ConstructSpatialMergeTree(mVspBspTree->GetRoot());
3894                mViewCellsTree->SetRoot(root);
3895
3896                // compute pvs
3897                ObjectPvs pvs;
3898                UpdatePvsForEvaluation(root, pvs);
3899        }
3900
3901        if (1)
3902        {
3903                char mstats[100];
3904                ObjectPvs pvs;
3905
3906                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
3907                mViewCellsTree->ExportStats(mstats);
3908        }
3909
3910        cout << "merged view cells in "
3911                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
3912
3913        Debug << "Postprocessing: Merged view cells in "
3914                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
3915       
3916
3917        //////////////////
3918        //-- stats and visualizations
3919
3920        int savedColorCode = mColorCode;
3921       
3922        // get currently active view cell set
3923        ResetViewCells();
3924        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
3925       
3926        if (mShowVisualization) // export merged view cells
3927        {
3928                mColorCode = 0;
3929                Exporter *exporter = Exporter::GetExporter("merged_view_cells.wrl");
3930               
3931                cout << "exporting view cells after merge ... ";
3932
3933                if (exporter)
3934                {
3935                        if (0)
3936                                exporter->SetWireframe();
3937                        else
3938                                exporter->SetFilled();
3939
3940                        ExportViewCellsForViz(exporter, NULL, GetClipPlane());
3941
3942                        if (mExportGeometry)
3943                        {
3944                                Material m;
3945                                m.mDiffuseColor = RgbColor(0, 1, 0);
3946                                exporter->SetForcedMaterial(m);
3947                                exporter->SetFilled();
3948
3949                                exporter->ExportGeometry(objects);
3950                        }
3951
3952                        delete exporter;
3953                }
3954                cout << "finished" << endl;
3955        }
3956
3957        if (mShowVisualization)
3958        {
3959                // use pvs size for color coding
3960                mColorCode = 1;
3961                Exporter *exporter = Exporter::GetExporter("merged_view_cells_pvs.wrl");
3962
3963                cout << "exporting view cells after merge (pvs size) ... ";     
3964
3965                if (exporter)
3966                {
3967                        exporter->SetFilled();
3968
3969                        ExportViewCellsForViz(exporter, NULL, GetClipPlane());
3970
3971                        if (mExportGeometry)
3972                        {
3973                                Material m;
3974                                m.mDiffuseColor = RgbColor(0, 1, 0);
3975                                exporter->SetForcedMaterial(m);
3976                                exporter->SetFilled();
3977
3978                                exporter->ExportGeometry(objects);
3979                        }
3980
3981                        delete exporter;
3982                }
3983                cout << "finished" << endl;
3984        }
3985
3986        mColorCode = savedColorCode;
3987}
3988
3989
3990void VspBspViewCellsManager::RefineViewCells(const VssRayContainer &rays,
3991                                                                                         const ObjectContainer &objects)
3992{
3993        mRenderer->RenderScene();
3994
3995        SimulationStatistics ss;
3996        dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
3997    Debug << "render time before refine\n\n" << ss << endl;
3998
3999        const long startTime = GetTime();
4000        cout << "Refining the merged view cells ... ";
4001
4002        // refining the merged view cells
4003        const int refined = mViewCellsTree->RefineViewCells(rays, objects);
4004
4005        //-- stats and visualizations
4006        cout << "finished" << endl;
4007        cout << "refined " << refined << " view cells in "
4008                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
4009
4010        Debug << "Postprocessing: refined " << refined << " view cells in "
4011                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
4012}
4013
4014
4015int VspBspViewCellsManager::PostProcess(const ObjectContainer &objects,
4016                                                                                const VssRayContainer &rays)
4017{
4018        if (!ViewCellsConstructed())
4019        {
4020                Debug << "postprocess error: no view cells constructed" << endl;
4021                return 0;
4022        }
4023
4024        // view cells already finished before post processing step
4025        // (i.e. because they were loaded)
4026        if (mViewCellsFinished)
4027        {
4028                FinalizeViewCells(true);
4029                EvaluateViewCellsStats();
4030
4031                return 0;
4032        }
4033
4034        // check if new view cells turned invalid
4035        int minPvs, maxPvs;
4036
4037        if (0)
4038        {
4039                minPvs = mMinPvsSize;
4040                maxPvs = mMaxPvsSize;
4041        }
4042        else
4043        {
4044                // problem matt: why did I start here from zero?
4045                minPvs = 0;
4046                maxPvs = mMaxPvsSize;
4047        }
4048
4049        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
4050        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
4051       
4052        SetValidity(minPvs, maxPvs);
4053
4054        // update valid view space according to valid view cells
4055        if (0) mVspBspTree->ValidateTree();
4056
4057        // area has to be recomputed
4058        mTotalAreaValid = false;
4059        VssRayContainer postProcessRays;
4060        GetRaySets(rays, mPostProcessSamples, postProcessRays);
4061
4062        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
4063
4064        // should maybe be done here to allow merge working
4065        // with area or volume and to correct the rendering statistics
4066        if (0) FinalizeViewCells(false);
4067               
4068        //////////
4069        //-- merge the individual view cells
4070        MergeViewCells(postProcessRays, objects);
4071       
4072        // refines the merged view cells
4073        if (0) RefineViewCells(postProcessRays, objects);
4074
4075
4076        ///////////
4077        //-- render simulation after merge + refine
4078
4079        cout << "\nview cells partition render time before compress" << endl << endl;;
4080        dynamic_cast<RenderSimulator *>(mRenderer)->RenderScene();
4081        SimulationStatistics ss;
4082        dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
4083        cout << ss << endl;
4084       
4085
4086        ////////////
4087        //-- compression
4088//#if HAS_TO_BE_REDONE
4089        if (ViewCellsTreeConstructed() && mCompressViewCells)
4090        {
4091                int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
4092                Debug << "number of entries before compress: " << pvsEntries << endl;
4093
4094                mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
4095
4096                pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
4097                Debug << "number of entries after compress: " << pvsEntries << endl;
4098        }
4099//#endif
4100
4101        // collapse sibling leaves that share the same view cell
4102        if (0) mVspBspTree->CollapseTree();
4103
4104        // recompute view cell list and statistics
4105        ResetViewCells();
4106
4107        // compute final meshes and volume / area
4108        if (1) FinalizeViewCells(true);
4109
4110        // write view cells to disc
4111        if (1 && mExportViewCells)
4112        {
4113                char filename[100];
4114                Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
4115                ExportViewCells(filename, mExportPvs, objects);
4116        }
4117
4118        return 0;
4119}
4120
4121
4122int VspBspViewCellsManager::GetType() const
4123{
4124        return VSP_BSP;
4125}
4126
4127
4128ViewCell *VspBspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
4129{
4130        // terminate recursion
4131        if (root->IsLeaf())
4132        {
4133                BspLeaf *leaf = dynamic_cast<BspLeaf *>(root);
4134                leaf->GetViewCell()->SetMergeCost(0.0f);
4135                return leaf->GetViewCell();
4136        }
4137       
4138       
4139        BspInterior *interior = dynamic_cast<BspInterior *>(root);
4140        ViewCellInterior *viewCellInterior = new ViewCellInterior();
4141               
4142        // evaluate merge cost for priority traversal
4143        float mergeCost = 1.0f / (float)root->mTimeStamp;
4144        viewCellInterior->SetMergeCost(mergeCost);
4145
4146        float volume = 0;
4147       
4148        BspNode *front = interior->GetFront();
4149        BspNode *back = interior->GetBack();
4150
4151
4152        ObjectPvs frontPvs, backPvs;
4153
4154        //-- recursivly compute child hierarchies
4155        ViewCell *backVc = ConstructSpatialMergeTree(back);
4156        ViewCell *frontVc = ConstructSpatialMergeTree(front);
4157
4158
4159        viewCellInterior->SetupChildLink(backVc);
4160        viewCellInterior->SetupChildLink(frontVc);
4161
4162        volume += backVc->GetVolume();
4163        volume += frontVc->GetVolume();
4164
4165        viewCellInterior->SetVolume(volume);
4166
4167        return viewCellInterior;
4168}
4169
4170
4171bool VspBspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
4172{
4173        if (!ViewCellsConstructed())
4174                return ViewCellsManager::GetViewPoint(viewPoint);
4175
4176        // TODO: set reasonable limit
4177        const int limit = 20;
4178
4179        for (int i = 0; i < limit; ++ i)
4180        {
4181                viewPoint = mViewSpaceBox.GetRandomPoint();
4182                if (mVspBspTree->ViewPointValid(viewPoint))
4183                {
4184                        return true;
4185                }
4186        }
4187
4188        Debug << "failed to find valid view point, taking " << viewPoint << endl;
4189        return false;
4190}
4191
4192
4193bool VspBspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
4194{
4195        // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
4196        // validy update in preprocessor for all managers)
4197        return ViewCellsManager::ViewPointValid(viewPoint);
4198
4199        //      return mViewSpaceBox.IsInside(viewPoint) &&
4200        //                 mVspBspTree->ViewPointValid(viewPoint);
4201}
4202
4203
4204void VspBspViewCellsManager::Visualize(const ObjectContainer &objects,
4205                                                                           const VssRayContainer &sampleRays)
4206{
4207        if (!ViewCellsConstructed())
4208                return;
4209
4210        VssRayContainer visRays;
4211        GetRaySets(sampleRays, mVisualizationSamples, visRays);
4212       
4213        if (1)
4214        {       
4215                //////////////////
4216                //-- export final view cell partition
4217
4218                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
4219               
4220                if (exporter)
4221                {
4222                        cout << "exporting view cells after post process ... ";
4223                        if (0)
4224                        {       // export view space box
4225                                exporter->SetWireframe();
4226                                exporter->ExportBox(mViewSpaceBox);
4227                                exporter->SetFilled();
4228                        }
4229
4230                        Material m;
4231                        m.mDiffuseColor.r = 0.0f;
4232                        m.mDiffuseColor.g = 0.5f;
4233                        m.mDiffuseColor.b = 0.5f;
4234
4235            exporter->SetForcedMaterial(m);
4236
4237                        if (1 && mExportGeometry)
4238                        {
4239                                exporter->ExportGeometry(objects);
4240                        }
4241
4242                        if (0 && mExportRays)
4243                        {
4244                                exporter->ExportRays(visRays, RgbColor(1, 0, 0));
4245                        }
4246                        ExportViewCellsForViz(exporter, NULL, GetClipPlane());
4247
4248                        delete exporter;
4249                        cout << "finished" << endl;
4250                }
4251        }
4252
4253        ////////////////
4254        //-- visualization of the BSP splits
4255
4256        bool exportSplits = false;
4257        Environment::GetSingleton()->GetBoolValue("VspBspTree.Visualization.exportSplits", exportSplits);
4258
4259        if (exportSplits)
4260        {
4261                cout << "exporting splits ... ";
4262                ExportSplits(objects, visRays);
4263                cout << "finished" << endl;
4264        }
4265
4266        ////////
4267        //-- export single view cells
4268       
4269        int leafOut;
4270        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
4271        const int raysOut = 100;
4272       
4273        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
4274}
4275
4276
4277void VspBspViewCellsManager::ExportSplits(const ObjectContainer &objects,
4278                                                                                  const VssRayContainer &rays)
4279{
4280        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
4281
4282        if (exporter)
4283        {
4284                Material m;
4285                m.mDiffuseColor = RgbColor(1, 0, 0);
4286                exporter->SetForcedMaterial(m);
4287                exporter->SetWireframe();
4288
4289                exporter->ExportBspSplits(*mVspBspTree, true);
4290
4291                // take forced material, else big scenes cannot be viewed
4292                m.mDiffuseColor = RgbColor(0, 1, 0);
4293                exporter->SetForcedMaterial(m);
4294                exporter->SetFilled();
4295
4296                exporter->ResetForcedMaterial();
4297
4298                // export rays
4299                if (mExportRays)
4300                {
4301                        exporter->ExportRays(rays, RgbColor(1, 1, 0));
4302                }
4303
4304                if (mExportGeometry)
4305                {
4306                        exporter->ExportGeometry(objects);
4307                }
4308                delete exporter;
4309        }
4310}
4311
4312
4313void VspBspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
4314                                                                                                   const int maxViewCells,
4315                                                                                                   const bool sortViewCells,
4316                                                                                                   const bool exportPvs,
4317                                                                                                   const bool exportRays,
4318                                                                                                   const int maxRays,
4319                                                                                                   const string prefix,
4320                                                                                                   VssRayContainer *visRays)
4321{       
4322        if (sortViewCells)
4323        {
4324                // sort view cells to visualize the largest view cells
4325                stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
4326        }
4327
4328        //////////
4329        //-- some view cells for output
4330
4331        ViewCell::NewMail();
4332        const int limit = min(maxViewCells, (int)mViewCells.size());
4333       
4334        for (int i = 0; i < limit; ++ i)
4335        {
4336                cout << "creating output for view cell " << i << " ... ";
4337
4338                ViewCell *vc = sortViewCells ? // largest view cell pvs first?
4339                        mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 0.5f)] : mViewCells[i];
4340
4341                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
4342                        continue;
4343
4344                vc->Mail();
4345
4346                ObjectPvs pvs;
4347                mViewCellsTree->GetPvs(vc, pvs);
4348
4349                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
4350                Exporter *exporter = Exporter::GetExporter(s);
4351               
4352                const int pvsSize = (int)mViewCellsTree->GetPvsSize(vc);
4353                cout << "view cell " << vc->GetId() << ": pvs size=" << pvsSize << endl;
4354
4355                if (exportRays)
4356                {
4357                        ////////////
4358                        //-- export rays piercing this view cell
4359
4360                        // take rays stored with the view cells during subdivision
4361                        VssRayContainer vcRays;
4362            VssRayContainer collectRays;
4363
4364                        // collect initial view cells
4365                        ViewCellContainer leaves;
4366                        mViewCellsTree->CollectLeaves(vc, leaves);
4367
4368                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
4369                for (vit = leaves.begin(); vit != vit_end; ++ vit)
4370                        {       
4371                                BspLeaf *vcLeaf = dynamic_cast<BspViewCell *>(*vit)->mLeaves[0];
4372                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
4373
4374                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
4375                                {
4376                                        collectRays.push_back(*rit);
4377                                }
4378                        }
4379
4380                        const int raysOut = min((int)collectRays.size(), maxRays);
4381               
4382                        // prepare some rays for output
4383                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
4384                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
4385                        {
4386                                const float p = RandomValue(0.0f, (float)collectRays.size());
4387                       
4388                                if (p < raysOut)
4389                                {
4390                                        vcRays.push_back(*rit);
4391                                }
4392                        }
4393
4394                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
4395                }
4396               
4397                ////////////////
4398                //-- export view cell geometry
4399
4400                exporter->SetWireframe();
4401
4402                Material m;//= RandomMaterial();
4403                m.mDiffuseColor = RgbColor(0, 1, 0);
4404                exporter->SetForcedMaterial(m);
4405
4406                ExportViewCellGeometry(exporter, vc, NULL, NULL);
4407                exporter->SetFilled();
4408
4409                if (exportPvs)
4410                {
4411                        Intersectable::NewMail();
4412
4413                        ObjectPvsMap::const_iterator oit, oit_end = pvs.mEntries.end();
4414                        cout << endl;
4415                        // output PVS of view cell
4416                        for (oit = pvs.mEntries.begin(); oit != oit_end; ++ oit)
4417                        {               
4418                                Intersectable *intersect = (*oit).first;
4419                               
4420                                if (!intersect->Mailed())
4421                                {
4422                                        intersect->Mail();
4423
4424                                        m = RandomMaterial();
4425                                        exporter->SetForcedMaterial(m);
4426                                        exporter->ExportIntersectable(intersect);
4427                                }
4428                        }
4429                        cout << endl;
4430                }
4431               
4432                DEL_PTR(exporter);
4433                cout << "finished" << endl;
4434        }
4435}
4436
4437
4438void VspBspViewCellsManager::TestFilter(const ObjectContainer &objects)
4439{
4440        Exporter *exporter = Exporter::GetExporter("filter.x3d");
4441
4442        Vector3 bsize = mViewSpaceBox.Size();
4443        const Vector3 viewPoint(mViewSpaceBox.Center());
4444        float w = Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
4445        const Vector3 width = Vector3(w);
4446       
4447        PrVs testPrVs;
4448       
4449        if (exporter)
4450        {
4451                ViewCellContainer viewCells;
4452       
4453        const AxisAlignedBox3 tbox = GetFilterBBox(viewPoint, mFilterWidth);
4454
4455                GetPrVS(viewPoint, testPrVs, GetFilterWidth());
4456
4457                exporter->SetWireframe();
4458
4459                exporter->SetForcedMaterial(RgbColor(1,1,1));
4460                exporter->ExportBox(tbox);
4461               
4462                exporter->SetFilled();
4463
4464                exporter->SetForcedMaterial(RgbColor(0,1,0));
4465                ExportViewCellGeometry(exporter, GetViewCell(viewPoint), NULL, NULL);
4466
4467                //exporter->ResetForcedMaterial();
4468                exporter->SetForcedMaterial(RgbColor(0,0,1));
4469                ExportViewCellGeometry(exporter, testPrVs.mViewCell, NULL, NULL);
4470
4471        exporter->SetForcedMaterial(RgbColor(1,0,0));
4472                exporter->ExportGeometry(objects);
4473
4474                delete exporter;
4475        }
4476}
4477
4478
4479int VspBspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
4480                                                                                                        ViewCellContainer &viewCells) const
4481{
4482        return mVspBspTree->ComputeBoxIntersections(box, viewCells);
4483}
4484
4485
4486int VspBspViewCellsManager::CastLineSegment(const Vector3 &origin,
4487                                                                                        const Vector3 &termination,
4488                                                                                        ViewCellContainer &viewcells)
4489{
4490        return mVspBspTree->CastLineSegment(origin, termination, viewcells);
4491}
4492
4493
4494void VspBspViewCellsManager::VisualizeWithFromPointQueries()
4495{
4496        int numSamples;
4497       
4498        Environment::GetSingleton()->GetIntValue("RenderSampler.samples", numSamples);
4499        cout << "samples" << numSamples << endl;
4500
4501        vector<RenderCostSample> samples;
4502 
4503        if (!mPreprocessor->GetRenderer())
4504                return;
4505
4506        //start the view point queries
4507        long startTime = GetTime();
4508        cout << "starting sampling of render cost ... ";
4509       
4510        mPreprocessor->GetRenderer()->SampleRenderCost(numSamples, samples, true);
4511
4512        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
4513
4514
4515        // for each sample:
4516        //    find view cells associated with the samples
4517        //    store the sample pvs with the pvs associated with the view cell
4518        //
4519        // for each view cell:
4520        //    compute difference point sampled pvs - view cell pvs
4521        //    export geometry with color coded pvs difference
4522       
4523    std::map<ViewCell *, ObjectPvs> sampleMap;
4524
4525        vector<RenderCostSample>::const_iterator rit, rit_end = samples.end();
4526
4527        for (rit = samples.begin(); rit != rit_end; ++ rit)
4528        {
4529                RenderCostSample sample = *rit;
4530       
4531                ViewCell *vc = GetViewCell(sample.mPosition);
4532
4533                std::map<ViewCell *, ObjectPvs>::iterator it = sampleMap.find(vc);
4534
4535                if (it == sampleMap.end())
4536                {
4537                        sampleMap[vc] = sample.mPvs;
4538                }
4539                else
4540                {
4541                        (*it).second.Merge(sample.mPvs);
4542                }
4543        }
4544
4545        // visualize the view cells
4546        std::map<ViewCell *, ObjectPvs>::const_iterator vit, vit_end = sampleMap.end();
4547
4548        Material m;//= RandomMaterial();
4549
4550        for (vit = sampleMap.begin(); vit != vit_end; ++ vit)
4551        {
4552                ViewCell *vc = (*vit).first;
4553               
4554                const int pvsVc = mViewCellsTree->GetPvsEntries(vc);
4555                const int pvsPtSamples = (*vit).second.GetSize();
4556
4557        m.mDiffuseColor.r = (float) (pvsVc - pvsPtSamples);
4558                m.mDiffuseColor.b = 1.0f;
4559                //exporter->SetForcedMaterial(m);
4560                //ExportViewCellGeometry(exporter, vc, mClipPlaneForViz);
4561
4562                /*      // counting the pvss
4563                for (rit = samples.begin(); rit != rit_end; ++ rit)
4564                {
4565                        RenderCostSample sample = *rit;
4566                        ViewCell *vc = GetViewCell(sample.mPosition);
4567
4568                        AxisAlignedBox3 box(sample.mPosition - Vector3(1, 1, 1), sample.mPosition + Vector3(1, 1, 1));
4569                        Mesh *hMesh = CreateMeshFromBox(box);
4570
4571                        DEL_PTR(hMesh);
4572                }
4573                */
4574        }
4575}
4576
4577
4578void VspBspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
4579                                                                                                        ViewCell *vc,
4580                                                                                                        const AxisAlignedBox3 *sceneBox,
4581                                                                                                        const AxisAlignedPlane *clipPlane
4582                                                                                                        ) const
4583{
4584        if (clipPlane)
4585        {
4586                const Plane3 plane = clipPlane->GetPlane();
4587
4588                ViewCellContainer leaves;
4589                mViewCellsTree->CollectLeaves(vc, leaves);
4590                ViewCellContainer::const_iterator it, it_end = leaves.end();
4591
4592                for (it = leaves.begin(); it != it_end; ++ it)
4593                {
4594                        BspNodeGeometry geom;
4595                        BspNodeGeometry front;
4596                        BspNodeGeometry back;
4597
4598                        mVspBspTree->ConstructGeometry(*it, geom);
4599
4600                        const float eps = 0.0001f;
4601                        const int cf = geom.Side(plane, eps);
4602
4603                        if (cf == -1)
4604                        {
4605                                exporter->ExportPolygons(geom.GetPolys());
4606                        }
4607                        else if (cf == 0)
4608                        {
4609                                geom.SplitGeometry(front,
4610                                                                   back,
4611                                                                   plane,
4612                                                                   mViewSpaceBox,
4613                                                                   eps);
4614
4615                                if (back.Valid())
4616                                {
4617                                        exporter->ExportPolygons(back.GetPolys());
4618                                }                       
4619                        }
4620                }
4621        }
4622        else
4623        {
4624                // export mesh if available
4625                // TODO: some bug here?
4626                if (1 && vc->GetMesh())
4627                {
4628                        exporter->ExportMesh(vc->GetMesh());
4629                }
4630                else
4631                {
4632                        BspNodeGeometry geom;
4633                        mVspBspTree->ConstructGeometry(vc, geom);
4634                        exporter->ExportPolygons(geom.GetPolys());
4635                }
4636        }
4637}
4638
4639
4640int VspBspViewCellsManager::GetMaxTreeDiff(ViewCell *vc) const
4641{
4642        ViewCellContainer leaves;
4643        mViewCellsTree->CollectLeaves(vc, leaves);
4644
4645        int maxDist = 0;
4646       
4647        // compute max height difference
4648        for (int i = 0; i < (int)leaves.size(); ++ i)
4649        {
4650                for (int j = 0; j < (int)leaves.size(); ++ j)
4651                {
4652                        BspLeaf *leaf = dynamic_cast<BspViewCell *>(leaves[i])->mLeaves[0];
4653
4654                        if (i != j)
4655                        {
4656                                BspLeaf *leaf2 =dynamic_cast<BspViewCell *>(leaves[j])->mLeaves[0];
4657                                const int dist = mVspBspTree->TreeDistance(leaf, leaf2);
4658                               
4659                                if (dist > maxDist)
4660                                        maxDist = dist;
4661                        }
4662                }
4663        }
4664
4665        return maxDist;
4666}
4667
4668
4669ViewCell *VspBspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
4670{
4671        if (!ViewCellsConstructed())
4672                return NULL;
4673
4674        if (!mViewSpaceBox.IsInside(point))
4675          return NULL;
4676
4677        return mVspBspTree->GetViewCell(point, active);
4678}
4679
4680
4681void VspBspViewCellsManager::CreateMesh(ViewCell *vc)
4682{
4683        BspNodeGeometry geom;
4684        mVspBspTree->ConstructGeometry(vc, geom);
4685       
4686        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
4687        IncludeNodeGeomInMesh(geom, *mesh);
4688
4689        vc->SetMesh(mesh);
4690}
4691
4692
4693int VspBspViewCellsManager::CastBeam(Beam &beam)
4694{
4695        return mVspBspTree->CastBeam(beam);
4696}
4697
4698
4699void VspBspViewCellsManager::Finalize(ViewCell *viewCell,
4700                                                                          const bool createMesh)
4701{
4702        float area = 0;
4703        float volume = 0;
4704
4705        ViewCellContainer leaves;
4706        mViewCellsTree->CollectLeaves(viewCell, leaves);
4707
4708        ViewCellContainer::const_iterator it, it_end = leaves.end();
4709
4710    for (it = leaves.begin(); it != it_end; ++ it)
4711        {
4712                BspNodeGeometry geom;
4713                mVspBspTree->ConstructGeometry(*it, geom);
4714
4715                const float lVol = geom.GetVolume();
4716                const float lArea = geom.GetArea();
4717
4718                area += lArea;
4719                volume += lVol;
4720
4721                if (createMesh)
4722                        CreateMesh(*it);
4723        }
4724
4725        viewCell->SetVolume(volume);
4726        viewCell->SetArea(area);
4727}
4728
4729
4730void VspBspViewCellsManager::TestSubdivision()
4731{
4732        ViewCellContainer leaves;
4733        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
4734
4735        ViewCellContainer::const_iterator it, it_end = leaves.end();
4736
4737        const float vol = mViewSpaceBox.GetVolume();
4738        float subdivVol = 0;
4739        float newVol = 0;
4740
4741        for (it = leaves.begin(); it != it_end; ++ it)
4742        {
4743                BspNodeGeometry geom;
4744                mVspBspTree->ConstructGeometry(*it, geom);
4745
4746                const float lVol = geom.GetVolume();
4747               
4748                newVol += lVol;
4749                subdivVol += (*it)->GetVolume();
4750               
4751                float thres = 0.9f;
4752                if ((lVol < ((*it)->GetVolume() * thres)) || (lVol * thres > ((*it)->GetVolume())))
4753                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
4754        }
4755       
4756        Debug << "exact volume: " << vol << endl;
4757        Debug << "subdivision volume: " << subdivVol << endl;
4758        Debug << "new volume: " << newVol << endl;
4759}
4760
4761
4762void VspBspViewCellsManager::PrepareLoadedViewCells()
4763{
4764        // TODO: do I still need this here?
4765        if (0)
4766                mVspBspTree->RepairViewCellsLeafLists();
4767}
4768
4769
4770
4771/**************************************************************************/
4772/*                   VspOspViewCellsManager implementation                */
4773/**************************************************************************/
4774
4775
4776VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm)
4777: ViewCellsManager(vcTree), mHierarchyManager(hm)
4778{
4779        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
4780
4781        mHierarchyManager->SetViewCellsManager(this);
4782        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
4783}
4784
4785
4786VspOspViewCellsManager::~VspOspViewCellsManager()
4787{
4788}
4789
4790
4791float VspOspViewCellsManager::GetProbability(ViewCell *viewCell)
4792{
4793        return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
4794}
4795
4796
4797void VspOspViewCellsManager::CollectViewCells()
4798{
4799        // view cells tree constructed
4800        if (!ViewCellsTreeConstructed())
4801        {
4802                mHierarchyManager->GetVspTree()->CollectViewCells(mViewCells, false);
4803        }
4804        else
4805        {       // we can use the view cells tree hierarchy to get the right set
4806                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
4807        }
4808}
4809
4810
4811bool VspOspViewCellsManager::ViewCellsConstructed() const
4812{
4813        return mHierarchyManager->GetVspTree()->GetRoot() != NULL;
4814}
4815
4816
4817ViewCell *VspOspViewCellsManager::GenerateViewCell(Mesh *mesh) const
4818{
4819        return new VspViewCell(mesh);
4820}
4821
4822
4823int VspOspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4824                                                                                                 const VssRayContainer &rays)
4825{
4826        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
4827
4828        // skip rest if view cells were already constructed
4829        if (ViewCellsConstructed())
4830                return 0;
4831
4832        int sampleContributions = 0;
4833        VssRayContainer sampleRays;
4834
4835        int limit = min (mInitialSamples, (int)rays.size());
4836
4837        VssRayContainer constructionRays;
4838        VssRayContainer savedRays;
4839
4840        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
4841                  << ", actual rays: " << (int)rays.size() << endl;
4842
4843        GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
4844
4845        Debug << "initial rays used for construction: " << (int)constructionRays.size() << endl;
4846        Debug << "saved rays: " << (int)savedRays.size() << endl;
4847
4848        mHierarchyManager->Construct(constructionRays, objects, &mViewSpaceBox);
4849
4850#if TEST_EVALUATION
4851        VssRayContainer::const_iterator tit, tit_end = constructionRays.end();
4852        for (tit = constructionRays.begin(); tit != tit_end; ++ tit)
4853        {
4854                storedRays.push_back(new VssRay(*(*tit)));
4855        }
4856#endif
4857
4858        /////////////////////////
4859        //-- print satistics for subdivision and view cells
4860
4861        Debug << endl << endl << *mHierarchyManager << endl;
4862
4863        ResetViewCells();
4864        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4865
4866        //////////////
4867        //-- recast rest of rays
4868       
4869        const long startTime = GetTime();
4870        cout << "Computing remaining ray contributions ... ";
4871
4872        if (SAMPLE_AFTER_SUBDIVISION)
4873                ComputeSampleContributions(savedRays, true, false);
4874
4875        Debug << "finished computing remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
4876                  << " secs" << endl;
4877
4878        if (0)
4879        {       // real meshes are constructed at this stage
4880                cout << "finalizing view cells ... ";
4881                FinalizeViewCells(true);
4882                cout << "finished" << endl;
4883        }
4884
4885        return sampleContributions;
4886}
4887
4888
4889int VspOspViewCellsManager::PostProcess(const ObjectContainer &objects,
4890                                                                                const VssRayContainer &rays)
4891{
4892        if (!ViewCellsConstructed())
4893        {
4894                Debug << "postprocess error: no view cells constructed" << endl;
4895                return 0;
4896        }
4897
4898        // if view cells were already constructed before post processing step
4899        // (e.g., because they were loaded), we are finished
4900        if (mViewCellsFinished)
4901        {
4902                FinalizeViewCells(true);
4903                EvaluateViewCellsStats();
4904
4905                return 0;
4906        }
4907
4908        // check if new view cells turned invalid
4909        int minPvs, maxPvs;
4910
4911        if (0)
4912        {
4913                minPvs = mMinPvsSize;
4914                maxPvs = mMaxPvsSize;
4915        }
4916        else
4917        {
4918                // problem matt: why did I start here from zero?
4919                minPvs = 0;
4920                maxPvs = mMaxPvsSize;
4921        }
4922
4923        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
4924        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
4925       
4926        SetValidity(minPvs, maxPvs);
4927
4928       
4929        // area is not up to date, has to be recomputed
4930        mTotalAreaValid = false;
4931        VssRayContainer postProcessRays;
4932        GetRaySets(rays, mPostProcessSamples, postProcessRays);
4933
4934        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
4935
4936
4937        // should maybe be done here to allow merge working with area or volume
4938        // and to correct the rendering statistics
4939        if (0) FinalizeViewCells(false);
4940               
4941        // compute tree by merging the nodes of the spatial hierarchy
4942        ViewCell *root = ConstructSpatialMergeTree(mHierarchyManager->GetVspTree()->GetRoot());
4943        mViewCellsTree->SetRoot(root);
4944
4945
4946        //////////////////////////
4947        //-- update pvs in the whole hierarchy
4948        ObjectPvs pvs;
4949        UpdatePvsForEvaluation(root, pvs);
4950
4951
4952        //////////////////////
4953        //-- render simulation after merge + refine
4954
4955        cout << "\nview cells partition render time before compress" << endl << endl;
4956        dynamic_cast<RenderSimulator *>(mRenderer)->RenderScene();
4957        SimulationStatistics ss;
4958        dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
4959        cout << ss << endl;
4960       
4961
4962        ///////////
4963        //-- compression
4964
4965        if (ViewCellsTreeConstructed() && mCompressViewCells)
4966        {
4967                int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
4968                Debug << "number of entries before compress: " << pvsEntries << endl;
4969
4970                mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
4971
4972                pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
4973                Debug << "number of entries after compress: " << pvsEntries << endl;
4974        }
4975
4976        /////////////
4977        //-- some tasks still to do on the view cells:
4978        //-- Compute meshes from view cell geometry, evaluate volume and / or area
4979        if (1) FinalizeViewCells(true);
4980
4981        // write out view cells (this moved to preprocessor)
4982        if (1 && mExportViewCells)
4983        {
4984                char filename[100];
4985                Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
4986                ExportViewCells(filename, mExportPvs, objects);
4987        }
4988
4989        return 0;
4990}
4991
4992
4993int VspOspViewCellsManager::GetType() const
4994{
4995        return VSP_OSP;
4996}
4997
4998
4999ViewCell *VspOspViewCellsManager::ConstructSpatialMergeTree(VspNode *root)
5000{
5001        // terminate recursion
5002        if (root->IsLeaf())
5003        {
5004                VspLeaf *leaf = dynamic_cast<VspLeaf *>(root);
5005                leaf->GetViewCell()->SetMergeCost(0.0f);
5006                return leaf->GetViewCell();
5007        }
5008       
5009        VspInterior *interior = dynamic_cast<VspInterior *>(root);
5010        ViewCellInterior *viewCellInterior = new ViewCellInterior();
5011               
5012        // evaluate merge cost for priority traversal
5013        float mergeCost = 1.0f / (float)root->mTimeStamp;
5014        viewCellInterior->SetMergeCost(mergeCost);
5015
5016        float volume = 0;
5017       
5018        VspNode *front = interior->GetFront();
5019        VspNode *back = interior->GetBack();
5020
5021        ObjectPvs frontPvs, backPvs;
5022
5023        /////////
5024        //-- recursivly compute child hierarchies
5025
5026        ViewCell *backVc = ConstructSpatialMergeTree(back);
5027        ViewCell *frontVc = ConstructSpatialMergeTree(front);
5028
5029        viewCellInterior->SetupChildLink(backVc);
5030        viewCellInterior->SetupChildLink(frontVc);
5031
5032        volume += backVc->GetVolume();
5033        volume += frontVc->GetVolume();
5034
5035        viewCellInterior->SetVolume(volume);
5036
5037        return viewCellInterior;
5038}
5039
5040
5041bool VspOspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
5042{
5043        if (!ViewCellsConstructed())
5044                return ViewCellsManager::GetViewPoint(viewPoint);
5045
5046        // TODO: set reasonable limit
5047        const int limit = 20;
5048
5049        for (int i = 0; i < limit; ++ i)
5050        {
5051                viewPoint = mViewSpaceBox.GetRandomPoint();
5052
5053                if (mHierarchyManager->GetVspTree()->ViewPointValid(viewPoint))
5054                {
5055                        return true;
5056                }
5057        }
5058
5059        Debug << "failed to find valid view point, taking " << viewPoint << endl;
5060        return false;
5061}
5062
5063
5064void VspOspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
5065                                                                                                        ViewCell *vc,
5066                                                                                                        const AxisAlignedBox3 *sceneBox,
5067                                                                                                        const AxisAlignedPlane *clipPlane
5068                                                                                                        ) const
5069{
5070        ViewCellContainer leaves;
5071        mViewCellsTree->CollectLeaves(vc, leaves);
5072        ViewCellContainer::const_iterator it, it_end = leaves.end();
5073
5074        Plane3 plane;
5075        if (clipPlane)
5076        {
5077                // arbitrary plane definition
5078                plane = clipPlane->GetPlane();
5079        }
5080
5081        for (it = leaves.begin(); it != it_end; ++ it)
5082        {
5083                VspViewCell *vspVc = dynamic_cast<VspViewCell *>(*it);
5084                VspLeaf *l = vspVc->mLeaves[0];
5085
5086                const AxisAlignedBox3 box =
5087                        mHierarchyManager->GetVspTree()->GetBoundingBox(vspVc->mLeaves[0]);
5088               
5089                if (sceneBox && !Overlap(*sceneBox, box))
5090                        continue;
5091
5092                if (clipPlane)
5093                {
5094                        if (box.Side(plane) == -1)
5095                        {
5096                                exporter->ExportBox(box);
5097                        }
5098                        else if (box.Side(plane) == 0)
5099                        {
5100                                // intersection
5101                                AxisAlignedBox3 fbox, bbox;
5102                                box.Split(clipPlane->mAxis, clipPlane->mPosition, fbox, bbox);
5103                                exporter->ExportBox(bbox);
5104                        }
5105                }
5106                else
5107                {
5108                        exporter->ExportBox(box);
5109                }
5110        }
5111}
5112
5113
5114bool VspOspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
5115{
5116  // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
5117  // validy update in preprocessor for all managers)
5118  return ViewCellsManager::ViewPointValid(viewPoint);
5119
5120  //    return mViewSpaceBox.IsInside(viewPoint) &&
5121  //               mVspTree->ViewPointValid(viewPoint);
5122}
5123
5124
5125void VspOspViewCellsManager::Visualize(const ObjectContainer &objects,
5126                                                                           const VssRayContainer &sampleRays)
5127{
5128        if (!ViewCellsConstructed())
5129                return;
5130
5131        VssRayContainer visRays;
5132        GetRaySets(sampleRays, mVisualizationSamples, visRays);
5133
5134        ////////////
5135        //-- export final view cells
5136
5137        Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
5138
5139        if (exporter)
5140        {
5141                // hack color code (show pvs size)
5142                const int savedColorCode = mColorCode;
5143                mColorCode = 0;
5144
5145                const long starttime = GetTime();
5146                cout << "exporting final view cells (after initial construction + post process) ... ";
5147
5148                // matt: hack for clamping scene
5149                AxisAlignedBox3 bbox = mViewSpaceBox;
5150                bbox.Scale(Vector3(0.5, 1, 0.5));
5151                if (CLAMP_TO_BOX)
5152                {       
5153                        exporter->SetWireframe();
5154                        exporter->ExportBox(bbox);
5155                        exporter->SetFilled();
5156                }
5157
5158                if (0 && mExportGeometry)
5159                {
5160                        exporter->ExportGeometry(objects, true, CLAMP_TO_BOX ? &bbox : NULL);
5161                }
5162
5163                if (1 && mExportRays)
5164                {       
5165                        exporter->ExportRays(visRays, RgbColor(0, 1, 0));
5166                }
5167
5168                mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects, CLAMP_TO_BOX ? &bbox : NULL, false);
5169                ExportViewCellsForViz(exporter, CLAMP_TO_BOX ? &bbox : NULL, GetClipPlane());
5170
5171                delete exporter;
5172                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
5173                mColorCode = savedColorCode;
5174        }
5175
5176        // export final object partition
5177        exporter = Exporter::GetExporter("final_object_partition.wrl");
5178
5179        if (exporter)
5180        {
5181                const long starttime = GetTime();
5182
5183                // matt: hack for making visualization smaller in size
5184                AxisAlignedBox3 bbox = mHierarchyManager->GetObjectSpaceBox();
5185                bbox.Scale(Vector3(0.5, 1, 0.5));
5186
5187                cout << "exporting object space hierarchy ... ";
5188                mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects, CLAMP_TO_BOX ? &bbox : NULL);
5189
5190                delete exporter;
5191                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
5192        }
5193
5194       
5195        //  visualization of the view cells
5196        if (0) ExportMergedViewCells(objects);
5197
5198        // export some view cell
5199        int leafOut;
5200        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
5201        const int raysOut = 100;
5202
5203        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
5204}
5205
5206
5207void VspOspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
5208                                                                                                   const int maxViewCells,
5209                                                                                                   const bool sortViewCells,
5210                                                                                                   const bool exportPvs,
5211                                                                                                   const bool exportRays,
5212                                                                                                   const int maxRays,
5213                                                                                                   const string prefix,
5214                                                                                                   VssRayContainer *visRays)
5215{
5216        if (sortViewCells)
5217        {
5218                // sort view cells to visualize the view cells with highest render cost
5219                stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
5220        }
5221
5222        ViewCell::NewMail();
5223        const int limit = min(maxViewCells, (int)mViewCells.size());
5224       
5225        cout << "\nExporting " << limit << " single view cells: " << endl;
5226       
5227        for (int i = 0; i < limit; ++ i)
5228        {
5229                cout << "creating output for view cell " << i << " ... ";
5230               
5231                // largest view cell pvs first of random view cell
5232                ViewCell *vc = sortViewCells ?
5233                        mViewCells[i] : mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 1)];
5234               
5235                if (vc->Mailed()) // already used
5236                        continue;
5237
5238                vc->Mail();
5239
5240                ObjectPvs pvs;
5241                mViewCellsTree->GetPvs(vc, pvs);
5242
5243                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
5244                Exporter *exporter = Exporter::GetExporter(s);
5245               
5246                cout << "view cell " << vc->GetId() << ": pvs size=" << (int)mViewCellsTree->GetPvsSize(vc) << endl;
5247
5248                if (exportPvs)
5249                {
5250                        Material m;
5251
5252                        Intersectable::NewMail();
5253                        ObjectPvsMap::const_iterator oit, oit_end = pvs.mEntries.end();
5254                       
5255                        // output PVS of view cell
5256                        for (oit = pvs.mEntries.begin(); oit != oit_end; ++ oit)
5257                        {               
5258                                Intersectable *intersect = (*oit).first;
5259                                if (!intersect->Mailed())
5260                                {
5261                                        m = RandomMaterial();
5262                                        exporter->SetForcedMaterial(m);
5263
5264                                        exporter->ExportIntersectable(intersect);
5265                                        intersect->Mail();
5266                                }
5267                        }
5268                }
5269
5270                if (exportRays)
5271                {
5272                        ////////////
5273                        //-- export the sample rays
5274
5275                        // output rays stored with the view cells during subdivision
5276                        VssRayContainer vcRays;
5277                        VssRayContainer collectRays;
5278
5279                        // collect intial view cells
5280                        ViewCellContainer leaves;
5281                        mViewCellsTree->CollectLeaves(vc, leaves);
5282
5283                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
5284
5285                        for (vit = leaves.begin(); vit != vit_end; ++ vit)
5286                        {
5287                                VspLeaf *vcLeaf = dynamic_cast<VspViewCell *>(*vit)->mLeaves[0];
5288                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
5289
5290                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
5291                                {
5292                                        collectRays.push_back(*rit);
5293                                }
5294                        }
5295
5296                        const int raysOut = min((int)collectRays.size(), maxRays);
5297
5298                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
5299
5300                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
5301                        {
5302                                const float p = RandomValue(0.0f, (float)collectRays.size());
5303
5304                                if (p < raysOut)
5305                                        vcRays.push_back(*rit);
5306                        }
5307
5308                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
5309                }
5310               
5311       
5312                /////////////////
5313                //-- export view cell geometry
5314
5315                exporter->SetWireframe();
5316
5317                Material m;
5318                m.mDiffuseColor = RgbColor(0, 1, 0);
5319                exporter->SetForcedMaterial(m);
5320
5321                ExportViewCellGeometry(exporter, vc, NULL, NULL);
5322                exporter->SetFilled();
5323
5324                DEL_PTR(exporter);
5325                cout << "finished" << endl;
5326        }
5327
5328        cout << endl;
5329}
5330
5331
5332int VspOspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
5333                                                                                                        ViewCellContainer &viewCells) const
5334{
5335        return mHierarchyManager->GetVspTree()->ComputeBoxIntersections(box, viewCells);
5336}
5337
5338
5339int VspOspViewCellsManager::CastLineSegment(const Vector3 &origin,
5340                                                                                        const Vector3 &termination,
5341                                                                                        ViewCellContainer &viewcells)
5342{
5343        return mHierarchyManager->GetVspTree()->CastLineSegment(origin, termination, viewcells);
5344}
5345
5346
5347bool VspOspViewCellsManager::ExportViewCells(const string filename,
5348                                                                                         const bool exportPvs,
5349                                                                                         const ObjectContainer &objects)
5350{
5351        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
5352                return false;
5353
5354        const long starttime = GetTime();
5355        cout << "exporting view cells to xml ... ";
5356       
5357        OUT_STREAM stream(filename.c_str());
5358
5359        // for output we need unique ids for each view cell
5360        CreateUniqueViewCellIds();
5361
5362        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
5363        stream << "<VisibilitySolution>" << endl;
5364
5365        if (exportPvs)
5366        {
5367        ///////////////
5368                //-- export bounding boxes
5369                //-- The bounding boxes are used to identify
5370                //-- the objects in the rendering engine
5371                mHierarchyManager->ExportBoundingBoxes(stream, objects);
5372        }
5373
5374        //////////////////////////
5375        //-- export the view cells and the pvs
5376
5377        const int numViewCells = mCurrentViewCellsStats.viewCells;
5378
5379        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
5380        mViewCellsTree->Export(stream, exportPvs);
5381        stream << "</ViewCells>" << endl;
5382
5383        //////////////////////
5384        //-- export the view space hierarchy
5385       
5386        stream << "<ViewSpaceHierarchy type=\"vsp\""
5387                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
5388                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
5389
5390        mHierarchyManager->GetVspTree()->Export(stream);
5391        stream << "</ViewSpaceHierarchy>" << endl;
5392
5393        ////////////////////// 
5394        //-- export the object space partition
5395       
5396        mHierarchyManager->ExportObjectSpaceHierarchy(stream);
5397       
5398        stream << "</VisibilitySolution>" << endl;
5399        stream.close();
5400       
5401        cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3 << " secs" << endl;
5402        return true;
5403}
5404
5405
5406
5407ViewCell *VspOspViewCellsManager::GetViewCell(const Vector3 &point,
5408                                                                                          const bool active) const
5409{
5410        if (!ViewCellsConstructed())
5411                return NULL;
5412
5413        if (!mViewSpaceBox.IsInside(point))
5414                return NULL;
5415
5416        return mHierarchyManager->GetVspTree()->GetViewCell(point, active);
5417}
5418
5419
5420void VspOspViewCellsManager::CreateMesh(ViewCell *vc)
5421{
5422        // matt: TODO
5423        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
5424
5425        ViewCellContainer leaves;
5426        mViewCellsTree->CollectLeaves(vc, leaves);
5427
5428        ViewCellContainer::const_iterator it, it_end = leaves.end();
5429
5430    for (it = leaves.begin(); it != it_end; ++ it)
5431        {
5432                VspLeaf *leaf = dynamic_cast<VspViewCell *>(*it)->mLeaves[0];
5433                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
5434        IncludeBoxInMesh(box, *mesh);
5435        }
5436
5437        vc->SetMesh(mesh);
5438}
5439
5440
5441int VspOspViewCellsManager::CastBeam(Beam &beam)
5442{
5443        // matt: TODO
5444        return 0;
5445}
5446
5447
5448void VspOspViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
5449{
5450        float area = 0;
5451        float volume = 0;
5452
5453        ViewCellContainer leaves;
5454        mViewCellsTree->CollectLeaves(viewCell, leaves);
5455
5456        ViewCellContainer::const_iterator it, it_end = leaves.end();
5457
5458    for (it = leaves.begin(); it != it_end; ++ it)
5459        {
5460                VspLeaf *leaf = dynamic_cast<VspViewCell *>(*it)->mLeaves[0];
5461               
5462                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
5463
5464                const float lVol = box.GetVolume();
5465                const float lArea = box.SurfaceArea();
5466
5467                area += lArea;
5468                volume += lVol;
5469
5470        CreateMesh(*it);
5471        }
5472
5473        viewCell->SetVolume(volume);
5474        viewCell->SetArea(area);
5475}
5476       
5477
5478float VspOspViewCellsManager::ComputeSampleContribution(VssRay &ray,
5479                                                                                                                const bool addRays,
5480                                                                                                                const bool storeViewCells)
5481{
5482        ViewCellContainer viewcells;
5483
5484        ray.mPvsContribution = 0;
5485        ray.mRelativePvsContribution = 0.0f;
5486
5487        static Ray hray;
5488        hray.Init(ray);
5489        //hray.mFlags |= Ray::CULL_BACKFACES;
5490        //Ray hray(ray);
5491
5492        float tmin = 0, tmax = 1.0;
5493
5494        if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
5495                return 0;
5496
5497        Vector3 origin = hray.Extrap(tmin);
5498        Vector3 termination = hray.Extrap(tmax);
5499
5500        ViewCell::NewMail();
5501
5502        // traverse the view space subdivision
5503        CastLineSegment(origin, termination, viewcells);
5504
5505        if (storeViewCells)
5506        {       
5507                // copy viewcells memory efficiently
5508                ray.mViewCells.reserve(viewcells.size());
5509                ray.mViewCells = viewcells;
5510        }
5511
5512        ViewCellContainer::const_iterator it = viewcells.begin();
5513
5514        for (; it != viewcells.end(); ++ it)
5515        {
5516                ViewCell *viewcell = *it;
5517
5518                if (viewcell->GetValid())
5519                {       // if ray not outside of view space
5520                        float contribution;
5521
5522                        if (ray.mTerminationObject)
5523                        {
5524                                // todo: maybe not correct for kd node pvs
5525                                Intersectable *obj = mHierarchyManager->GetIntersectable(ray, true);
5526
5527                                if (viewcell->GetPvs().GetSampleContribution(obj,
5528                                        ray.mPdf,
5529                                        contribution))
5530                                {
5531                                        ++ ray.mPvsContribution;
5532                                }
5533
5534                                ray.mRelativePvsContribution += contribution;
5535                        }
5536
5537                        //-- for directional sampling it is important to count only contributions
5538                        //-- made in one direction!
5539                        //-- the other contributions of this sample will be counted for the opposite ray!
5540#if SAMPLE_ORIGIN_OBJECTS
5541                        if (ray.mOriginObject &&
5542                                viewcell->GetPvs().GetSampleContribution(ray.mOriginObject,
5543                                ray.mPdf,
5544                                contribution))
5545                        {
5546                                ++ ray.mPvsContribution;
5547                                ray.mRelativePvsContribution += contribution;
5548                        }
5549#endif
5550                }
5551        }
5552
5553        if (!addRays)
5554        {
5555                return ray.mRelativePvsContribution;
5556        }
5557
5558        // sampled objects are stored in the pvs
5559        for (it = viewcells.begin(); it != viewcells.end(); ++ it)
5560        {
5561                ViewCell *viewCell = *it;
5562
5563                if (!viewCell->GetValid())
5564                        break;
5565
5566                AddSampleToPvs(
5567                        ray.mTerminationObject,
5568                        ray.mTermination,
5569                        viewCell,
5570                        ray.mPdf,
5571                        ray.mRelativePvsContribution);
5572
5573#if SAMPLE_ORIGIN_OBJECTS
5574
5575                AddSampleToPvs(
5576                        ray.mOriginObject,
5577                        ray.mOrigin,
5578                        viewCell,
5579                        ray.mPdf,
5580                        ray.mRelativePvsContribution);
5581#endif                 
5582        }
5583
5584        return ray.mRelativePvsContribution;
5585}
5586
5587
5588bool VspOspViewCellsManager::AddSampleToPvs(Intersectable *obj,
5589                                                                                        const Vector3 &hitPoint,
5590                                                                                        ViewCell *vc,
5591                                                                                        const float pdf,
5592                                                                                        float &contribution) const
5593{
5594        // The hierarchy manager decides about the type of sample cast
5595        return mHierarchyManager->AddSampleToPvs(obj, hitPoint, vc, pdf, contribution);
5596}
5597
5598
5599void VspOspViewCellsManager::PrepareLoadedViewCells()
5600{
5601        // TODO
5602}
5603
5604
5605ViewCellsManager *VspOspViewCellsManager::LoadViewCells(const string &filename,
5606                                                                                                                ObjectContainer *objects,
5607                                                                                                                const bool finalizeViewCells,
5608                                                                                                                BoundingBoxConverter *bconverter)
5609                                                                                                 
5610{
5611        ViewCellsManager *vm =
5612                ViewCellsManager::LoadViewCells(filename, objects, finalizeViewCells, bconverter);
5613#if 0
5614        // insert scene objects in tree
5615        mOspTree->InsertObjects(mOspTree->GetRoot(), *objects);
5616#endif
5617        return vm;
5618}
5619
5620
5621#if TEST_EVALUATION
5622void VspOspViewCellsManager::EvalViewCellPartition()
5623{
5624        const int castSamples = (int)storedRays.size();
5625        char s[64];
5626        char statsPrefix[100];
5627
5628        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
5629
5630        Debug << "view cell stats prefix: " << statsPrefix << endl;
5631
5632        // should directional sampling be used?
5633        const bool dirSamples = (mEvaluationSamplingType == SamplingStrategy::DIRECTION_BASED_DISTRIBUTION);
5634
5635        cout << "reseting pvs ... ";
5636        const bool startFromZero = true;
5637
5638        if (startFromZero)
5639        {
5640                // reset pvs and start over from zero
5641                mViewCellsTree->ResetPvs();
5642        }
5643        else
5644        {
5645                // statistics before casting more samples
5646                cout << "compute new statistics ... ";
5647                sprintf(s, "-%09d-eval.log", castSamples);
5648                string fName = string(statsPrefix) + string(s);
5649
5650                mViewCellsTree->ExportStats(fName);
5651                cout << "finished" << endl;
5652        }
5653        cout << "finished" << endl;
5654
5655    cout << "Evaluating view cell partition ... " << endl;
5656
5657        VssRayContainer evaluationSamples = storedRays;
5658        const int samplingType = mEvaluationSamplingType;
5659       
5660        cout << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
5661       
5662        ComputeSampleContributions(evaluationSamples, true, false);
5663       
5664        cout << "finished" << endl;
5665       
5666        cout << "compute new statistics ... ";
5667       
5668        // propagate pvs or pvs size information
5669        ObjectPvs pvs;
5670        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), pvs);
5671
5672
5673        /////////////////////
5674        // $§temporary matt: test render cost
5675
5676        sprintf(s, "-%09d-eval.log", castSamples);
5677        string fileName = string(statsPrefix) + string(s);
5678
5679        ViewCellContainer leaves;
5680
5681        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
5682        float rc = 0;
5683
5684        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
5685       
5686        for (vit = leaves.begin(); vit != vit_end; ++ vit)
5687        {
5688                ViewCell *vc = *vit;
5689                int pvs = vc->GetPvs().CountObjectsInPvs();
5690                float vol = vc->GetVolume();
5691                rc += pvs * vol;
5692        }
5693
5694        Debug << "\nrendercost hack: " << rc / mViewSpaceBox.GetVolume() << endl;
5695        mViewCellsTree->ExportStats(fileName);
5696        cout << "finished" << endl;
5697
5698        disposeRays(evaluationSamples, NULL);
5699}
5700
5701#endif
5702}
Note: See TracBrowser for help on using the repository browser.