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

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