source: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp @ 2232

Revision 2232, 72.4 KB checked in by mattausch, 17 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "ViewCell.h"
6#include "Plane3.h"
7#include "HierarchyManager.h"
8#include "Mesh.h"
9#include "common.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellsManager.h"
17#include "Beam.h"
18#include "KdTree.h"
19#include "IntersectableWrapper.h"
20#include "VspTree.h"
21#include "OspTree.h"
22#include "BvHierarchy.h"
23#include "ViewCell.h"
24#include "TraversalTree.h"
25
26
27namespace GtpVisibilityPreprocessor {
28
29
30#define USE_FIXEDPOINT_T 0
31#define STUPID_METHOD 0
32
33
34
35/*******************************************************************/
36/*              class HierarchyManager implementation              */
37/*******************************************************************/
38
39
40HierarchyManager::HierarchyManager(const int objectSpaceSubdivisionType):
41mObjectSpaceSubdivisionType(objectSpaceSubdivisionType),
42mOspTree(NULL),
43mBvHierarchy(NULL),
44mTraversalTree(NULL)
45{
46        switch(mObjectSpaceSubdivisionType)
47        {
48        case KD_BASED_OBJ_SUBDIV:
49                mOspTree = new OspTree();
50                mOspTree->mVspTree = mVspTree;
51                mOspTree->mHierarchyManager = this;
52                break;
53        case BV_BASED_OBJ_SUBDIV:
54        mBvHierarchy = new BvHierarchy();
55                mBvHierarchy->mHierarchyManager = this;
56                break;
57        default:
58                break;
59        }
60
61        // hierarchy manager links view space partition and object space partition
62        mVspTree = new VspTree();
63        mVspTree->mHierarchyManager = this;
64       
65        mViewSpaceSubdivisionType = KD_BASED_VIEWSPACE_SUBDIV;
66        ParseEnvironment();
67}
68
69
70HierarchyManager::HierarchyManager(KdTree *kdTree):
71mObjectSpaceSubdivisionType(KD_BASED_OBJ_SUBDIV),
72mBvHierarchy(NULL)
73{
74        mOspTree = new OspTree(*kdTree);
75        mOspTree->mVspTree = mVspTree;
76
77        mVspTree = new VspTree();
78        mVspTree->mHierarchyManager = this;
79
80        mViewSpaceSubdivisionType = KD_BASED_VIEWSPACE_SUBDIV;
81        ParseEnvironment();
82}
83
84
85void HierarchySubdivisionStats::Print(ostream &app) const
86{
87        app << "#Pass\n" << 0 << endl
88                << "#Splits\n" << mNumSplits << endl
89                << "#TotalRenderCost\n" << mTotalRenderCost << endl
90                << "#TotalEntriesInPvs\n" << mEntriesInPvs << endl
91                << "#Memory\n" << mMemoryCost << endl
92                << "#StepsView\n" << mViewSpaceSplits << endl
93                << "#StepsObject\n" << mObjectSpaceSplits << endl
94                << "#VspOspRatio\n" << VspOspRatio() << endl
95                << "#FullMem\n" << mFullMemory << endl
96                << "#RenderCostDecrease\n" << mRenderCostDecrease << endl
97                << "#Priority\n" << mPriority << endl
98                << "#FpsPerMb\n" << FpsPerMb() << endl
99                << endl;
100}
101
102
103void HierarchyManager::ParseEnvironment()
104{
105        Environment::GetSingleton()->GetFloatValue(
106                "Hierarchy.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
107
108        Environment::GetSingleton()->GetFloatValue("Hierarchy.minRenderCost", mMinRenderCost);
109
110        Environment::GetSingleton()->GetIntValue(
111                "Hierarchy.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
112
113        Environment::GetSingleton()->GetBoolValue(
114                "Hierarchy.Construction.startWithObjectSpace", mStartWithObjectSpace);
115
116        Environment::GetSingleton()->GetIntValue(
117                "Hierarchy.Termination.maxLeaves", mTermMaxLeaves);
118
119        Environment::GetSingleton()->GetIntValue(
120                "Hierarchy.Construction.type", mConstructionType);
121
122        Environment::GetSingleton()->GetIntValue(
123                "Hierarchy.Construction.minDepthForOsp", mMinDepthForObjectSpaceSubdivion);
124
125        Environment::GetSingleton()->GetIntValue(
126                "Hierarchy.Construction.minDepthForVsp", mMinDepthForViewSpaceSubdivion);
127       
128        Environment::GetSingleton()->GetBoolValue(
129                "Hierarchy.Construction.repairQueue", mRepairQueue);
130
131        Environment::GetSingleton()->GetBoolValue(
132                "Hierarchy.Construction.useMultiLevel", mUseMultiLevelConstruction);
133
134        Environment::GetSingleton()->GetIntValue(
135                "Hierarchy.Construction.levels", mNumMultiLevels);
136
137        Environment::GetSingleton()->GetIntValue(
138                "Hierarchy.Construction.minStepsOfSameType", mMinStepsOfSameType);
139       
140        Environment::GetSingleton()->GetIntValue(
141                "Hierarchy.Construction.maxStepsOfSameType", mMaxStepsOfSameType);
142
143        char subdivisionStatsLog[100];
144        Environment::GetSingleton()->GetStringValue("Hierarchy.subdivisionStats", subdivisionStatsLog);
145        mSubdivisionStats.open(subdivisionStatsLog);
146
147        Environment::GetSingleton()->GetBoolValue(
148                "Hierarchy.Construction.recomputeSplitPlaneOnRepair", mRecomputeSplitPlaneOnRepair);
149
150        Environment::GetSingleton()->GetBoolValue(
151                "Hierarchy.Construction.considerMemory", mConsiderMemory);
152
153        Environment::GetSingleton()->GetFloatValue(
154                "Hierarchy.Termination.maxMemory", mTermMaxMemory);
155
156        Environment::GetSingleton()->GetIntValue(
157                "Hierarchy.Construction.maxRepairs", mMaxRepairs);
158
159        Environment::GetSingleton()->GetFloatValue(
160                "Hierarchy.Construction.maxAvgRaysPerObject", mMaxAvgRaysPerObject);
161
162        Environment::GetSingleton()->GetFloatValue(
163                "Hierarchy.Construction.minAvgRaysPerObject", mMinAvgRaysPerObject);
164
165        Environment::GetSingleton()->GetBoolValue(
166                "Hierarchy.useTraversalTree", mUseTraversalTree);
167
168        Debug << "******** Hierarchy Manager Options ***********" << endl;
169        Debug << "max leaves: " << mTermMaxLeaves << endl;
170        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
171        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
172        Debug << "min depth for object space subdivision: " << mMinDepthForObjectSpaceSubdivion << endl;
173        Debug << "repair queue: " << mRepairQueue << endl;
174        Debug << "number of multilevels: " << mNumMultiLevels << endl;
175        Debug << "recompute split plane on repair: " << mRecomputeSplitPlaneOnRepair << endl;
176        Debug << "minimal number of steps from same type: " << mMinStepsOfSameType << endl;
177        Debug << "maximal allowed memory: " << mTermMaxMemory << endl;
178        Debug << "consider memory: " << mConsiderMemory << endl;
179        Debug << "min steps of same kind: " << mMinStepsOfSameType << endl;
180        Debug << "max steps of same kind: " << mMaxStepsOfSameType << endl;
181        Debug << "max repairs: " << mMaxRepairs << endl;
182        Debug << "max avg rays per object: " << mMaxAvgRaysPerObject << endl;
183        Debug << "mín avg rays per object: " << mMinAvgRaysPerObject << endl;
184        Debug << "mín render cost: " << mMinRenderCost << endl;
185
186        // for comparing it with byte - value
187        mTermMaxMemory *= (1024.0f * 1024.0f);
188
189        switch (mConstructionType)
190        {
191        case 0:
192                Debug << "construction type: sequential" << endl;
193                break;
194        case 1:
195                Debug << "construction type: interleaved" << endl;
196                break;
197        case 2:
198                Debug << "construction type: gradient" << endl;
199                break;
200        case 3:
201                Debug << "construction type: multilevel" << endl;
202                break;
203        default:
204                Debug << "construction type " << mConstructionType << " unknown" << endl;
205                break;
206        }
207
208        //Debug << "min render cost " << mMinRenderCostDecrease << endl;
209        Debug << endl;
210}
211
212
213HierarchyManager::~HierarchyManager()
214{
215        DEL_PTR(mOspTree);
216        DEL_PTR(mVspTree);
217        DEL_PTR(mBvHierarchy);
218}
219
220
221int HierarchyManager::GetObjectSpaceSubdivisionType() const
222{
223        return mObjectSpaceSubdivisionType;
224}
225
226
227int HierarchyManager::GetViewSpaceSubdivisionType() const
228{
229        return mViewSpaceSubdivisionType;
230}
231
232
233void HierarchyManager::SetViewCellsManager(ViewCellsManager *vcm)
234{
235        mVspTree->SetViewCellsManager(vcm);
236
237        if (mOspTree)
238        {
239                mOspTree->SetViewCellsManager(vcm);
240        }
241        else if (mBvHierarchy)
242        {
243                mBvHierarchy->SetViewCellsManager(vcm);
244        }
245}
246
247
248void HierarchyManager::SetViewCellsTree(ViewCellsTree *vcTree)
249{
250        mVspTree->SetViewCellsTree(vcTree);
251}
252
253
254VspTree *HierarchyManager::GetVspTree()
255{
256        return mVspTree;
257}
258
259/*
260AxisAlignedBox3 HierarchyManager::GetViewSpaceBox() const
261{
262        return mVspTree->mBoundingBox;
263}*/
264
265
266AxisAlignedBox3 HierarchyManager::GetObjectSpaceBox() const
267{
268        switch (mObjectSpaceSubdivisionType)
269        {
270        case KD_BASED_OBJ_SUBDIV:
271                return mOspTree->mBoundingBox;
272        case BV_BASED_OBJ_SUBDIV:
273                return mBvHierarchy->mBoundingBox;
274        default:
275                // hack: empty box
276                return AxisAlignedBox3();
277        }
278}
279
280
281SubdivisionCandidate *HierarchyManager::NextSubdivisionCandidate(SplitQueue &splitQueue)
282{
283        SubdivisionCandidate *splitCandidate = splitQueue.Top();
284        splitQueue.Pop();
285
286        // split was not reevaluated before => do it now
287        if (splitCandidate->IsDirty())
288        {
289                splitCandidate->EvalCandidate();
290        }
291
292        return splitCandidate;
293}
294
295
296float HierarchyManager::EvalFullMem() const
297{
298        // question: should I also add the mem usage of the hierarchies?
299        const float objectSpaceMem = 16;//GetObjectSpaceMemUsage();
300        const float viewSpaceMem = 16;//mVspTree->GetMemUsage();
301        // HACK: the same value is used for view and object space
302        return mHierarchyStats.mMemory + mHierarchyStats.Leaves() * objectSpaceMem;
303}
304
305
306void HierarchyManager::EvalSubdivisionStats()
307{
308       
309        HierarchySubdivisionStats stats;
310
311        stats.mNumSplits = mHierarchyStats.Leaves();
312        stats.mTotalRenderCost = mHierarchyStats.mTotalCost;
313        stats.mEntriesInPvs = mHierarchyStats.mPvsEntries;
314        stats.mMemoryCost = mHierarchyStats.mMemory  / float(1024 * 1024);
315        stats.mFullMemory = EvalFullMem() / float(1024 * 1024);
316        stats.mViewSpaceSplits = mVspTree->mVspStats.Leaves();
317        stats.mObjectSpaceSplits = GetObjectSpaceSubdivisionLeaves();
318        stats.mRenderCostDecrease = mHierarchyStats.mRenderCostDecrease;
319        stats.mPriority = mPriority;
320
321        stats.Print(mSubdivisionStats);
322}
323
324
325void HierarchyManager::AddSubdivisionStats(const int splits,
326                                                                                   const float renderCostDecr,
327                                                                                   const float totalRenderCost,
328                                                                                   const int pvsEntries,
329                                                                                   const float memory,
330                                                                                   const float renderCostPerStorage,
331                                                                                   const float vspOspRatio)
332{
333        mSubdivisionStats
334                        << "#Splits\n" << splits << endl
335                        << "#RenderCostDecrease\n" << renderCostDecr << endl
336                        << "#TotalEntriesInPvs\n" << pvsEntries << endl
337                        << "#TotalRenderCost\n" << totalRenderCost << endl
338                        << "#Memory\n" << memory << endl
339                        << "#FpsPerMb\n" << renderCostPerStorage << endl
340                        << "#VspOspRatio\n" << vspOspRatio << endl
341                        << endl;
342}
343
344
345bool HierarchyManager::GlobalTerminationCriteriaMet(SubdivisionCandidate *candidate) const
346{
347        const bool terminationCriteriaMet =
348                (0
349                || (mHierarchyStats.Leaves() >= mTermMaxLeaves)
350                //|| (mHierarchyStats.mMemory >= mTermMaxMemory)
351                || (EvalFullMem() >= mTermMaxMemory)
352                || candidate->GlobalTerminationCriteriaMet()
353                //|| (mHierarchyStats.mRenderCostDecrease < mMinRenderCostDecrease)
354                //|| (mHierarchyStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
355                );
356
357#if GTP_DEBUG
358        if (terminationCriteriaMet)
359        {
360                Debug << "hierarchy global termination criteria met:" << endl;
361                Debug << "leaves: " << mHierarchyStats.Leaves() << " " << mTermMaxLeaves << endl;
362                Debug << "cost misses: " << mHierarchyStats.mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl;
363                Debug << "memory: " << mHierarchyStats.mMemory << " " << mTermMaxMemory << endl;
364                Debug << "full memory: " << EvalFullMem() << " " << mTermMaxMemory << endl;
365        }
366#endif
367
368        return terminationCriteriaMet;
369}
370
371
372void HierarchyManager::Construct(const VssRayContainer &sampleRays,
373                                                                 const ObjectContainer &objects,
374                                                                 AxisAlignedBox3 *forcedViewSpace)
375{
376        mTimeStamp = 1;
377
378        switch (mConstructionType)
379        {
380        case MULTILEVEL:
381                ConstructMultiLevel(sampleRays, objects, forcedViewSpace);
382                break;
383        case INTERLEAVED:
384        case SEQUENTIAL:
385                ConstructInterleaved(sampleRays, objects, forcedViewSpace);
386                PrintTimings(true);
387                break;
388        case GRADIENT:
389                ConstructInterleavedWithGradient(sampleRays, objects, forcedViewSpace);
390                PrintTimings(true);
391                break;
392        default:
393                break;
394        }
395
396        // hack
397        if (mUseMultiLevelConstruction)
398        {
399                cout << "starting optimizing multilevel ... " << endl;
400                // try to optimize the hierarchy from above
401                OptimizeMultiLevel(sampleRays, objects, forcedViewSpace);
402               
403                cout << "finished" << endl;
404        }
405
406        if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
407        {
408                mBvHierarchy->SetUniqueNodeIds();
409        }
410
411        // create a traversal tree which is optimized for view cell casting
412        if (mUseTraversalTree)
413        {
414                CreateTraversalTree();
415        }
416}
417
418
419void HierarchyManager::PrintTimings(const bool lastSplitWasOsp)
420{
421        double sortTime, evalTime, nodeTime, splitTime, subdTime, planeTime, collectTime, viewCellsTime;
422
423        sortTime = mBvHierarchy->mSortTimer.TotalTime();
424        evalTime = mBvHierarchy->mEvalTimer.TotalTime();
425        nodeTime = mBvHierarchy->mNodeTimer.TotalTime();
426        splitTime = mBvHierarchy->mSplitTimer.TotalTime();
427        subdTime = mBvHierarchy->mSubdivTimer.TotalTime();
428        planeTime = mBvHierarchy->mPlaneTimer.TotalTime();
429        collectTime = mBvHierarchy->mCollectTimer.TotalTime();
430
431        cout << "bvh times"
432                 << " sort : " << sortTime
433                 << " eval : " << evalTime
434                 << " node : " << nodeTime
435                 << " split: " << splitTime
436                 << " subd : " << subdTime
437                 << " plane: " << planeTime
438                 << " colct: " << collectTime
439                 << endl;
440
441        Debug << "bvh times"
442                << " sort : " << sortTime
443                 << " eval : " << evalTime
444                 << " node : " << nodeTime
445                 << " split: " << splitTime
446                 << " subd : " << subdTime
447                 << " plane: " << planeTime
448                 << " colct: " << collectTime
449                 << endl;
450
451        sortTime = mVspTree->mSortTimer.TotalTime();
452        evalTime = mVspTree->mEvalTimer.TotalTime();
453        nodeTime = mVspTree->mNodeTimer.TotalTime();
454        splitTime = mVspTree->mSplitTimer.TotalTime();
455        subdTime = mVspTree->mSubdivTimer.TotalTime();
456        planeTime = mVspTree->mPlaneTimer.TotalTime();
457        viewCellsTime = mVspTree->mViewCellsTimer.TotalTime();
458
459        cout << "vsp times"
460                 << " sort : " << sortTime
461                 << " eval : " << evalTime
462                 << " node : " << nodeTime
463                 << " split: " << splitTime
464                 << " subd : " << subdTime
465                 << " plane: " << planeTime
466                 << " viewc: " << viewCellsTime
467                 << endl;
468
469        Debug << "vsp times"
470                  << " sort : " << sortTime
471                  << " eval : " << evalTime
472                  << " node : " << nodeTime
473                  << " split: " << splitTime
474                  << " subd : " << subdTime
475                  << " plane: " << planeTime
476                  << " viewc: " << viewCellsTime
477                  << endl;
478
479        cout << endl;
480        Debug << endl;
481}
482
483
484void HierarchyManager::ConstructInterleavedWithGradient(const VssRayContainer &sampleRays,
485                                                                                                                const ObjectContainer &objects,
486                                                                                                                AxisAlignedBox3 *forcedViewSpace)
487{
488        mHierarchyStats.Reset();
489        mHierarchyStats.Start();
490       
491        mHierarchyStats.mNodes = 2;
492
493        // create first nodes
494        mVspTree->Initialise(sampleRays, forcedViewSpace);
495        InitialiseObjectSpaceSubdivision(objects);
496
497        // hack: assume that object space can be seen from view space
498        mHierarchyStats.mTotalCost = mInitialRenderCost = (float)objects.size();
499        // only one entry for start
500        mHierarchyStats.mPvsEntries = 1;
501        mHierarchyStats.mMemory = (float)ObjectPvs::GetEntrySizeByte();
502
503        EvalSubdivisionStats();
504        Debug << "setting total cost to " << mHierarchyStats.mTotalCost << endl;
505
506        const long startTime = GetTime();
507        cout << "Constructing view space / object space tree ... \n";
508       
509        SplitQueue objectSpaceQueue;
510        SplitQueue viewSpaceQueue;
511
512        int vspSteps = 0, ospSteps = 0;
513
514        // use sah for evaluating osp tree construction
515        // in the first iteration of the subdivision
516        mSavedViewSpaceSubdivisionType = mViewSpaceSubdivisionType;
517        mViewSpaceSubdivisionType = NO_VIEWSPACE_SUBDIV;
518        mSavedObjectSpaceSubdivisionType = mObjectSpaceSubdivisionType;
519
520        // number of initial splits
521        const int minSteps = mMinStepsOfSameType;
522        const int maxSteps = mMaxStepsOfSameType;
523
524        PrepareObjectSpaceSubdivision(objectSpaceQueue, sampleRays, objects);
525       
526        /////////////////////////
527        // calulcate initial object space splits
528       
529        SubdivisionCandidateContainer dirtyList;
530
531        // subdivide object space first
532        // for first round, use sah splits. Once view space partition
533        // has started, use render cost heuristics instead
534        ospSteps = RunConstruction(objectSpaceQueue,
535                                                           dirtyList,
536                                                           NULL,
537                                                           minSteps,
538                                                           maxSteps);
539
540        cout << "\n" << ospSteps << " object space partition steps taken" << endl;
541
542        //PrintTimings(true);
543
544        ///////////////
545        //-- create view space
546        PrepareViewSpaceSubdivision(viewSpaceQueue, sampleRays, objects);
547
548        dirtyList.clear();
549        // view space subdivision started
550        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
551
552        if (1)
553        {
554                // rather also start with 100 view space splits to avoid initial bias.
555                vspSteps = RunConstruction(viewSpaceQueue, dirtyList, NULL, minSteps, maxSteps);
556                cout << "\n" << vspSteps << " view space partition steps taken" << endl;
557               
558                /// Repair split queue
559                cout << "repairing queue ... " << endl;
560                RepairQueue(dirtyList, objectSpaceQueue, true);
561                cout << "repaired " << (int)dirtyList.size() << " candidates" << endl;
562
563                dirtyList.clear();
564                //PrintTimings(false);
565        }
566        else
567        {
568                // the priorities were calculated for driving sah.
569                // => recalculate "real" priorities taking visibility into
570                // account so we can compare to view space splits
571                ResetQueue(objectSpaceQueue, false);
572        }
573
574        // This method subdivides view space / object space
575        // in order to converge to some optimal cost for this partition
576        // start with object space partiton
577        // then optimizate view space partition for the current osp
578        // and vice versa until iteration depth is reached.
579
580        bool lastSplitWasOsp = true;
581
582        while (!(viewSpaceQueue.Empty() && objectSpaceQueue.Empty()))
583        {
584                // decide upon next split type
585                const float vspPriority =
586                        viewSpaceQueue.Top() ? viewSpaceQueue.Top()->GetPriority() : -1e20f;
587                const float ospPriority =
588                        objectSpaceQueue.Top() ? objectSpaceQueue.Top()->GetPriority() : -1e20f;
589               
590                cout << "new decicion, vsp: " << vspPriority << ", osp: " << ospPriority << endl;
591
592                // should view or object space be subdivided further?
593                if (ospPriority >= vspPriority)
594                //if (!lastSplitWasOsp)
595                {
596                        /////////////////
597                        // subdivide object space with respect to the objects
598
599                        lastSplitWasOsp = true;
600                        cout << "osp" << endl;
601                       
602                        // dirtied view space candidates
603                        SubdivisionCandidateContainer dirtyVspList;
604
605                        // subdivide object space first for first round,
606                        // use sah splits. Once view space partition
607                        // has started, use render cost heuristics instead
608                        const int ospSteps = RunConstruction(objectSpaceQueue,
609                                                                                                 dirtyVspList,
610                                                                                                 viewSpaceQueue.Top(),
611                                                                                                 minSteps,
612                                                                                                 maxSteps);
613
614                        cout << "\n" << ospSteps << " object space partition steps taken" << endl;
615                        Debug << "\n" << ospSteps << " object space partition steps taken" << endl;
616
617                        /// Repair split queue, i.e., affected view space candidates
618                        cout << "repairing queue ... " << endl;
619                        const int repaired = RepairQueue(dirtyVspList, viewSpaceQueue, true);
620           
621                        cout << "\nrepaired " << repaired << " candidates from "
622                                 << (int)dirtyVspList.size() << " dirtied candidates" << endl;
623                }
624                else
625                {
626                        /////////////////
627                        // subdivide view space with respect to the objects
628
629                        lastSplitWasOsp = false;
630                        cout << "vsp" << endl;
631
632                        // dirtied object space candidates
633                        SubdivisionCandidateContainer dirtyOspList;
634
635                        // process view space candidates
636                        const int vspSteps = RunConstruction(viewSpaceQueue,
637                                                                                                 dirtyOspList,
638                                                                                                 objectSpaceQueue.Top(),
639                                                                                                 minSteps,
640                                                                                                 maxSteps);
641
642                        cout << "\n" << vspSteps << " view space partition steps taken" << endl;
643                        Debug << "\n" << vspSteps << " view space partition steps taken" << endl;
644
645                        // view space subdivision constructed
646                        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
647
648                        /// Repair split queue
649                        cout << "repairing queue ... " << endl;
650                        const int repaired = RepairQueue(dirtyOspList, objectSpaceQueue, true);
651
652                        cout << "\nrepaired " << repaired << " candidates from "
653                                 << (int)dirtyOspList.size() << " dirtied candidates" << endl;
654                }
655
656                //PrintTimings(lastSplitWasOsp);
657        }
658
659        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
660
661        mHierarchyStats.Stop();
662        mVspTree->mVspStats.Stop();
663
664        FinishObjectSpaceSubdivision(objects, !mUseMultiLevelConstruction);
665}
666
667
668void HierarchyManager::ConstructInterleaved(const VssRayContainer &sampleRays,
669                                                                                        const ObjectContainer &objects,
670                                                                                        AxisAlignedBox3 *forcedViewSpace)
671{
672        mHierarchyStats.Reset();
673        mHierarchyStats.Start();
674
675        // two nodes for view space and object space
676        mHierarchyStats.mNodes = 2;
677        mHierarchyStats.mPvsEntries = 1;
678        mHierarchyStats.mMemory = (float)ObjectPvs::GetEntrySizeByte();
679        mHierarchyStats.mTotalCost = (float)objects.size();
680
681        mHierarchyStats.mRenderCostDecrease = 0;
682
683        EvalSubdivisionStats();
684        Debug << "setting total cost to " << mHierarchyStats.mTotalCost << endl;
685
686        const long startTime = GetTime();
687        cout << "Constructing view space / object space tree ... \n";
688       
689        // create only roots
690        mVspTree->Initialise(sampleRays, forcedViewSpace);
691        InitialiseObjectSpaceSubdivision(objects);
692
693        // use objects for evaluating vsp tree construction in the
694        // first levels of the subdivision
695        mSavedObjectSpaceSubdivisionType = mObjectSpaceSubdivisionType;
696        mObjectSpaceSubdivisionType = NO_OBJ_SUBDIV;
697
698        mSavedViewSpaceSubdivisionType = mViewSpaceSubdivisionType;
699        mViewSpaceSubdivisionType = NO_VIEWSPACE_SUBDIV;
700
701        // start view space subdivison immediately?
702        if (StartViewSpaceSubdivision())
703        {
704                // prepare vsp tree for traversal
705        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
706                PrepareViewSpaceSubdivision(mTQueue, sampleRays, objects);
707        }
708       
709        // start object space subdivision immediately?
710        if (StartObjectSpaceSubdivision())
711        {
712                mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
713                PrepareObjectSpaceSubdivision(mTQueue, sampleRays, objects);
714        }
715       
716        // begin subdivision
717        RunConstruction(mRepairQueue, sampleRays, objects, forcedViewSpace);
718       
719        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
720
721        mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
722        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
723
724        mHierarchyStats.Stop();
725        mVspTree->mVspStats.Stop();
726       
727        FinishObjectSpaceSubdivision(objects, !mUseMultiLevelConstruction);
728}
729
730
731void HierarchyManager::PrepareViewSpaceSubdivision(SplitQueue &tQueue,
732                                                                                                   const VssRayContainer &sampleRays,
733                                                                                                   const ObjectContainer &objects)
734{
735        cout << "\npreparing view space hierarchy construction ... " << endl;
736
737        // hack: reset global cost misses
738        mHierarchyStats.mGlobalCostMisses = 0;
739
740        RayInfoContainer *viewSpaceRays = new RayInfoContainer();
741        mVspTree->PrepareConstruction(tQueue, sampleRays, *viewSpaceRays);
742
743        /////////
744        //-- new stats
745
746        mHierarchyStats.mTotalCost = mVspTree->mTotalCost;
747        cout << "\nreseting cost for vsp, new total cost: " << mHierarchyStats.mTotalCost << endl;
748}
749
750
751float HierarchyManager::GetObjectSpaceMemUsage() const
752{
753        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
754        {
755                // TODO;
756        }
757        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
758        {
759                return mBvHierarchy->GetMemUsage();
760        }
761
762        return -1;
763}
764
765
766void HierarchyManager::InitialiseObjectSpaceSubdivision(const ObjectContainer &objects)
767{
768        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
769        {
770                // TODO;
771        }
772        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
773        {
774                mBvHierarchy->Initialise(objects);
775        }
776}
777
778
779void HierarchyManager::PrepareObjectSpaceSubdivision(SplitQueue &tQueue,
780                                                                                                         const VssRayContainer &sampleRays,
781                                                                                                         const ObjectContainer &objects)
782{
783        // hack: reset global cost misses
784        mHierarchyStats.mGlobalCostMisses = 0;
785
786        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
787        {
788                return PrepareOspTree(tQueue, sampleRays, objects);
789        }
790        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
791        {
792                return PrepareBvHierarchy(tQueue, sampleRays, objects);
793        }
794}
795
796
797void HierarchyManager::PrepareBvHierarchy(SplitQueue &tQueue,
798                                                                                  const VssRayContainer &sampleRays,
799                                                                                  const ObjectContainer &objects)
800{
801        const long startTime = GetTime();
802
803        cout << "preparing bv hierarchy construction ... " << endl;
804       
805        // compute first candidate
806        mBvHierarchy->PrepareConstruction(tQueue, sampleRays, objects);
807
808        mHierarchyStats.mTotalCost = mBvHierarchy->mTotalCost;
809        Debug << "\nreseting cost, new total cost: " << mHierarchyStats.mTotalCost << endl;
810
811        cout << "finished bv hierarchy preparation in "
812                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
813}
814
815
816void HierarchyManager::PrepareOspTree(SplitQueue &tQueue,
817                                                                          const VssRayContainer &sampleRays,
818                                                                          const ObjectContainer &objects)
819{
820        cout << "starting osp tree construction ... " << endl;
821
822        RayInfoContainer *objectSpaceRays = new RayInfoContainer();
823
824        // start with one big kd cell - all objects can be seen from everywhere
825        // note: only true for view space = object space
826
827        // compute first candidate
828        mOspTree->PrepareConstruction(tQueue, sampleRays, objects, *objectSpaceRays);
829
830        mHierarchyStats.mTotalCost = mOspTree->mTotalCost;
831        Debug << "\nreseting cost for osp, new total cost: " << mHierarchyStats.mTotalCost << endl;
832}
833
834
835float HierarchyManager::EvalCorrectedPvs(const float childPvs,
836                                                                                 const float totalPvs,
837                                                                                 const float avgRaysPerObjects) const
838{
839        // don't correct pvss
840        if (mMaxAvgRaysPerObject <= mMinAvgRaysPerObject)
841        {
842                return childPvs;
843        }
844       
845        // assume pvs sampled sufficiently => take child pvs
846        if (avgRaysPerObjects >= mMaxAvgRaysPerObject)
847        {
848                return childPvs;
849        }
850
851        // assume pvs not sampled sufficiently => pvs equal to parent pvs
852        // we should not subdivide further from this point
853        if (avgRaysPerObjects <= mMinAvgRaysPerObject)
854        {
855                //cout << "t ";// << avgRaysPerObjects << " ";
856                return totalPvs;
857        }
858
859        ///////////
860        //-- blend pvss
861
862        const float alpha = (mMaxAvgRaysPerObject - avgRaysPerObjects) /
863                                                (mMaxAvgRaysPerObject - mMinAvgRaysPerObject);
864
865        /// rays per object == max threshold => alpha == 0 => newPvs is childPvs
866        /// rays per object == min threshold => alpha == 1 => newPvs is totalPvs
867       
868        const float beta = alpha * (totalPvs - childPvs);
869#if 1
870        const float newPvs = childPvs + beta;
871#else
872        const float newPvs = alpha * childPvs + (1.0f - alpha) * totalPvs;
873#endif
874//cout << "b ";// << avgRaysPerObjects << " ";
875        //cout << "alpha " << alpha << " beta: " << beta << " child: " << childPvs << " parent: " << totalPvs << endl;
876       
877        if ((newPvs < childPvs - Limits::Small) || (newPvs > totalPvs + Limits::Small))
878                cout << "w: " << newPvs << " < child ("
879                         << childPvs << ") or > parent (" << totalPvs << ")" << endl;
880
881        return newPvs;
882}
883
884
885bool HierarchyManager::ApplySubdivisionCandidate(SubdivisionCandidate *sc,
886                                                                                                 SplitQueue &splitQueue,
887                                                                                                 //const bool repairQueue,
888                                                                                                 SubdivisionCandidateContainer &dirtyList)
889{
890        const bool terminationCriteriaMet = GlobalTerminationCriteriaMet(sc);
891        const bool success = sc->Apply(splitQueue, terminationCriteriaMet, dirtyList);
892
893        if (sc->IsDirty())
894                cerr << "Error: Should never come here!" << endl;
895
896        if (!success) // split was not taken
897        {
898                //cout << "x";
899                return false;
900        }
901
902       
903        ///////////////
904        //-- split was successful => update stats and queue
905
906    // cost ratio of cost decrease / totalCost
907        const float costRatio = sc->GetRenderCostDecrease() / mHierarchyStats.mTotalCost;
908        //cout << "ratio: " << costRatio << " min ratio: " << mTermMinGlobalCostRatio << endl;
909       
910        if (costRatio < mTermMinGlobalCostRatio)
911        {
912                ++ mHierarchyStats.mGlobalCostMisses;
913        }
914       
915        /////////////
916        // update stats
917
918        mHierarchyStats.mNodes += 2;
919        mHierarchyStats.mTotalCost -= sc->GetRenderCostDecrease();
920
921        const int pvsEntriesIncr = sc->GetPvsEntriesIncr();
922        mHierarchyStats.mPvsEntries += pvsEntriesIncr;
923        //cout << "pvs entries: " << pvsEntriesIncr << " " << mHierarchyStats.mPvsEntries << endl;
924
925        // memory size in byte
926        float mem = (float)ObjectPvs::GetEntrySizeByte() * pvsEntriesIncr;
927
928#if USE_AVGRAYCONTRI
929        // high avg ray contri, the result is influenced by undersampling
930        // => decrease priority
931
932        if (sc->GetAvgRayContribution() > mMaxAvgRayContri)
933        {
934                const float factor = 1.0f + sc->GetAvgRayContribution() - mMaxAvgRayContri;
935                cout << "h " << factor << endl;
936
937                mem *= factor;
938        }
939#endif
940
941        mHierarchyStats.mMemory += mem;
942        mHierarchyStats.mRenderCostDecrease = sc->GetRenderCostDecrease();
943       
944        mPriority = sc->GetPriority();
945
946        cout << sc->Type() << " ";
947
948        //////////
949        // show current memory
950
951        static float memoryCount = 0;
952
953        if (mHierarchyStats.mMemory > memoryCount)
954        {
955                memoryCount += 100000;
956                cout << "\nstorage cost: " << mHierarchyStats.mMemory / float(1024 * 1024)
957                         << " MB, steps: " << mHierarchyStats.Leaves() << endl;
958        }
959
960        // output stats
961        EvalSubdivisionStats();
962
963        return true;
964}
965
966
967int HierarchyManager::GetObjectSpaceSubdivisionDepth() const
968{
969        int maxDepth = 0;
970
971        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
972        {
973                maxDepth = mOspTree->mOspStats.maxDepth;
974        }
975        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
976        {
977                maxDepth = mBvHierarchy->mBvhStats.maxDepth;
978        }
979
980        return maxDepth;
981}
982
983
984int HierarchyManager::GetObjectSpaceSubdivisionLeaves() const
985{
986        int maxLeaves= 0;
987
988        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
989        {
990                maxLeaves = mOspTree->mOspStats.Leaves();
991        }
992        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
993        {
994                maxLeaves = mBvHierarchy->mBvhStats.Leaves();
995        }
996
997        return maxLeaves;
998}
999
1000
1001int HierarchyManager::GetObjectSpaceSubdivisionNodes() const
1002{
1003        int maxLeaves = 0;
1004
1005        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
1006        {
1007                maxLeaves = mOspTree->mOspStats.nodes;
1008        }
1009        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
1010        {
1011                maxLeaves = mBvHierarchy->mBvhStats.nodes;
1012        }
1013
1014        return maxLeaves;
1015}
1016
1017bool HierarchyManager::StartObjectSpaceSubdivision() const
1018{
1019        // view space construction already started
1020        if (ObjectSpaceSubdivisionConstructed())
1021                return false;
1022
1023        // start immediately with object space subdivision?
1024        if (mStartWithObjectSpace)
1025                return true;
1026
1027        // is the queue empty again?
1028        if (ViewSpaceSubdivisionConstructed() && mTQueue.Empty())
1029                return true;
1030
1031        // has the depth for subdivision been reached?
1032        return
1033                ((mConstructionType == INTERLEAVED) &&
1034                 (mMinStepsOfSameType <= mVspTree->mVspStats.nodes));
1035}
1036
1037
1038bool HierarchyManager::StartViewSpaceSubdivision() const
1039{
1040        // view space construction already started
1041        if (ViewSpaceSubdivisionConstructed())
1042                return false;
1043
1044        // start immediately with view space subdivision?
1045        if (!mStartWithObjectSpace)
1046                return true;
1047
1048        // is the queue empty again?
1049        if (ObjectSpaceSubdivisionConstructed() && mTQueue.Empty())
1050                return true;
1051
1052        // has the depth for subdivision been reached?
1053        return
1054                ((mConstructionType == INTERLEAVED) &&
1055                 (mMinStepsOfSameType <= GetObjectSpaceSubdivisionLeaves()));
1056}
1057
1058
1059void HierarchyManager::RunConstruction(const bool repairQueue,
1060                                                                           const VssRayContainer &sampleRays,
1061                                                                           const ObjectContainer &objects,
1062                                                                           AxisAlignedBox3 *forcedViewSpace)
1063{
1064        SubdivisionCandidate::NewMail();
1065
1066        while (!FinishedConstruction())
1067        {
1068                SubdivisionCandidate *sc = NextSubdivisionCandidate(mTQueue);   
1069       
1070                ///////////////////
1071                //-- subdivide leaf node
1072
1073                SubdivisionCandidateContainer dirtyList;
1074
1075                ApplySubdivisionCandidate(sc, mTQueue, dirtyList);
1076                               
1077                if (repairQueue)
1078                {
1079                        // reevaluate candidates affected by the split for view space splits,
1080                        // this would be object space splits and other way round
1081                        RepairQueue(dirtyList, mTQueue, mRecomputeSplitPlaneOnRepair);
1082                }       
1083
1084                // we use objects for evaluating vsp tree construction until
1085                // a certain depth once a certain depth existiert ...
1086                if (StartObjectSpaceSubdivision())
1087                {
1088                        mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
1089
1090                        cout << "\nstarting object space subdivision after "
1091                                 << mVspTree->mVspStats.nodes << " (" << mMinStepsOfSameType << ") steps, mem="
1092                                 << mHierarchyStats.mMemory / float(1024 * 1024) << " MB" << endl;
1093
1094                        PrepareObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1095                       
1096                        cout << "reseting queue ... ";
1097                        ResetQueue(mTQueue, mRecomputeSplitPlaneOnRepair);
1098                        cout << "finished" << endl;
1099                }
1100
1101                if (StartViewSpaceSubdivision())
1102                {
1103                        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
1104
1105                        cout << "\nstarting view space subdivision at "
1106                                 << GetObjectSpaceSubdivisionLeaves() << " ("
1107                                 << mMinStepsOfSameType << ") , mem="
1108                                 << mHierarchyStats.mMemory / float(1024 * 1024) << " MB" << endl;
1109
1110                        PrepareViewSpaceSubdivision(mTQueue, sampleRays, objects);
1111
1112                        cout << "reseting queue ... ";
1113                        ResetQueue(mTQueue, mRecomputeSplitPlaneOnRepair);
1114                        cout << "finished" << endl;
1115                }
1116
1117                DEL_PTR(sc);
1118        }
1119}
1120
1121
1122void HierarchyManager::RunConstruction(const bool repairQueue)
1123{
1124        // main loop
1125        while (!FinishedConstruction())
1126        {
1127                SubdivisionCandidate *sc = NextSubdivisionCandidate(mTQueue);   
1128               
1129                ////////
1130                //-- subdivide leaf node of either type
1131
1132                SubdivisionCandidateContainer dirtyList;
1133        ApplySubdivisionCandidate(sc, mTQueue, dirtyList);
1134               
1135                if (repairQueue)
1136                {
1137                        RepairQueue(dirtyList, mTQueue, mRecomputeSplitPlaneOnRepair);
1138                }
1139
1140                DEL_PTR(sc);
1141        }
1142}
1143
1144
1145int HierarchyManager::RunConstruction(SplitQueue &splitQueue,
1146                                                                          SubdivisionCandidateContainer &dirtyCandidates,
1147                                                                          SubdivisionCandidate *oldCandidate,
1148                                                                          const int minSteps,
1149                                                                          const int maxSteps)
1150{
1151        if (minSteps >= maxSteps)
1152                cout << "error!! " << minSteps << " equal or larger maxSteps" << endl;
1153
1154        int steps = 0;
1155        SubdivisionCandidate::NewMail();
1156
1157        // main loop
1158        while (!splitQueue.Empty())
1159        {
1160                const float priority = splitQueue.Top()->GetPriority();
1161                const float threshold = oldCandidate ? oldCandidate->GetPriority() : 1e20f;
1162
1163                // minimum slope reached
1164                if ((steps >= maxSteps) || ((priority < threshold) && !(steps < minSteps)))
1165                {
1166                        cout << "\nbreaking on " << priority << " smaller than " << threshold << endl;
1167                        break;
1168                }
1169               
1170                ////////
1171                //-- subdivide leaf node of either type
1172
1173                SubdivisionCandidate *sc = NextSubdivisionCandidate(splitQueue);
1174
1175                const bool success = ApplySubdivisionCandidate(sc, splitQueue, dirtyCandidates);
1176
1177                if (success)
1178                {
1179                        //sc->CollectDirtyCandidates(dirtyCandidates, true);
1180                        //if (steps % 10 == 0) cout << sc->Type() << " ";
1181                       
1182                        ++ steps;
1183                }
1184
1185                DEL_PTR(sc);
1186        }
1187
1188        return steps;
1189}
1190
1191
1192void HierarchyManager::ResetObjectSpaceSubdivision(SplitQueue &tQueue,
1193                                                                                                   const VssRayContainer &sampleRays,
1194                                                                                                   const ObjectContainer &objects)
1195{       
1196        // object space partition constructed => reconstruct
1197        switch (mObjectSpaceSubdivisionType)
1198        {
1199        case BV_BASED_OBJ_SUBDIV:
1200                {
1201                        cout << "\nreseting bv hierarchy" << endl;
1202                        Debug << "old bv hierarchy:\n " << mBvHierarchy->mBvhStats << endl;
1203                               
1204                        // rather use this: remove previous nodes and add the two new ones
1205                        //mHierarchyStats.mNodes -= mBvHierarchy->mBvhStats.nodes + 1;
1206                        mHierarchyStats.mNodes = mVspTree->mVspStats.nodes;
1207                       
1208                        // create root
1209                        mBvHierarchy->Initialise(objects);
1210       
1211                        mBvHierarchy->Reset(tQueue, sampleRays, objects);
1212
1213                        mHierarchyStats.mTotalCost = mBvHierarchy->mTotalCost;
1214                       
1215                        //mHierarchyStats.mPvsEntries -= mBvHierarchy->mPvsEntries + 1;
1216                        mHierarchyStats.mPvsEntries = mBvHierarchy->CountViewCells(objects);
1217
1218                        mHierarchyStats.mMemory =
1219                                (float)mHierarchyStats.mPvsEntries * ObjectPvs::GetEntrySizeByte();
1220
1221                        mHierarchyStats.mRenderCostDecrease = 0;
1222
1223                        // evaluate stats before first subdivision
1224                        EvalSubdivisionStats();
1225                        cout << "finished bv hierarchy preparation" << endl;
1226                }
1227                break;
1228
1229        case KD_BASED_OBJ_SUBDIV:
1230                // TODO
1231        default:
1232                break;
1233        }
1234}
1235
1236
1237void HierarchyManager::ResetViewSpaceSubdivision(SplitQueue &tQueue,
1238                                                                                                 const VssRayContainer &sampleRays,
1239                                                                                                 const ObjectContainer &objects,
1240                                                                                                 AxisAlignedBox3 *forcedViewSpace)
1241{
1242        ViewCellsManager *vm = mVspTree->mViewCellsManager;
1243
1244        // HACK: rather not destroy vsp tree
1245        DEL_PTR(mVspTree);
1246        mVspTree = new VspTree();
1247
1248        mVspTree->mHierarchyManager = this;
1249        mVspTree->mViewCellsManager = vm;
1250
1251        mVspTree->Initialise(sampleRays, forcedViewSpace);
1252       
1253        //////////
1254        //-- reset stats
1255    mHierarchyStats.mNodes = GetObjectSpaceSubdivisionNodes();
1256                //-mVspTree->mVspStats.nodes + 1;
1257       
1258        PrepareViewSpaceSubdivision(mTQueue, sampleRays, objects);
1259       
1260        mHierarchyStats.mPvsEntries = mVspTree->mPvsEntries;
1261        mHierarchyStats.mRenderCostDecrease = 0;
1262
1263        mHierarchyStats.mMemory =
1264                (float)mHierarchyStats.mPvsEntries * ObjectPvs::GetEntrySizeByte();
1265
1266        // evaluate new stats before first subdivsiion
1267        EvalSubdivisionStats();
1268}
1269
1270
1271void HierarchyManager::ConstructMultiLevel(const VssRayContainer &sampleRays,                                                                                   
1272                                                                                   const ObjectContainer &objects,
1273                                                                                   AxisAlignedBox3 *forcedViewSpace)
1274{
1275        mHierarchyStats.Reset();
1276        mHierarchyStats.Start();
1277        mHierarchyStats.mNodes = 2;
1278       
1279        mHierarchyStats.mTotalCost = (float)objects.size();
1280        Debug << "setting total cost to " << mHierarchyStats.mTotalCost << endl;
1281
1282        const long startTime = GetTime();
1283        cout << "Constructing view space / object space tree ... \n";
1284       
1285        // initialise view / object space
1286        mVspTree->Initialise(sampleRays, forcedViewSpace);
1287        InitialiseObjectSpaceSubdivision(objects);
1288
1289        // use sah for evaluating osp tree construction
1290        // in the first iteration of the subdivision
1291
1292        mSavedViewSpaceSubdivisionType = mViewSpaceSubdivisionType;
1293        mViewSpaceSubdivisionType = NO_VIEWSPACE_SUBDIV;
1294
1295        PrepareObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1296
1297        //////////////////////////
1298
1299
1300        const int limit = mNumMultiLevels;
1301        int i = 0;
1302
1303        // This method subdivides view space / object space
1304        // in order to converge to some optimal cost for this partition
1305        // start with object space partiton
1306        // then optimizate view space partition for the current osp
1307        // and vice versa until iteration depth is reached.
1308        while (1)
1309        {
1310                char subdivisionStatsLog[100];
1311                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", i);
1312                mSubdivisionStats.open(subdivisionStatsLog);
1313
1314                // subdivide object space first
1315                ResetObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1316
1317                // process object space candidates
1318                RunConstruction(false);
1319
1320                // object space subdivision constructed
1321                mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
1322
1323                cout << "iteration " << i << " of " << limit << " finished" << endl;
1324                mSubdivisionStats.close();
1325
1326                if ((i ++) >= limit)
1327                        break;
1328
1329                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", i);
1330                mSubdivisionStats.open(subdivisionStatsLog);
1331
1332
1333                /////////////////
1334                // subdivide view space with respect to the objects
1335
1336                ResetViewSpaceSubdivision(mTQueue, sampleRays, objects, forcedViewSpace);
1337               
1338                // view space subdivision constructed
1339                mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
1340               
1341                // process view space candidates
1342                RunConstruction(false);
1343
1344                cout << "iteration " << i << " of " << limit << " finished" << endl;
1345                mSubdivisionStats.close();
1346
1347                if ((i ++) >= limit)
1348                        break;
1349        }
1350       
1351        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
1352
1353        mHierarchyStats.Stop();
1354        mVspTree->mVspStats.Stop();
1355        FinishObjectSpaceSubdivision(objects);
1356}
1357
1358
1359void HierarchyManager::OptimizeMultiLevel(const VssRayContainer &sampleRays,                                                                                     
1360                                                                                  const ObjectContainer &objects,
1361                                                                                  AxisAlignedBox3 *forcedViewSpace)
1362{
1363        const long startTime = GetTime();
1364        const int limit = mNumMultiLevels;
1365
1366        // open up new subdivision
1367        mSubdivisionStats.close();
1368
1369        int steps = 0;
1370
1371        int maxViewSpaceLeaves = mVspTree->mVspStats.Leaves();
1372        int maxObjectSpaceLeaves;
1373       
1374        // set the number of leaves 'evaluated' from the previous methods
1375        // we go for the same numbers, but we try to optimize both subdivisions
1376        switch (mObjectSpaceSubdivisionType)
1377        {
1378        case BV_BASED_OBJ_SUBDIV:
1379                maxObjectSpaceLeaves = mBvHierarchy->mBvhStats.Leaves();
1380                break;
1381        case KD_BASED_OBJ_SUBDIV:
1382                maxObjectSpaceLeaves = mOspTree->mOspStats.Leaves();
1383        default:
1384                maxObjectSpaceLeaves = 0;
1385                break;
1386        }
1387
1388        // This method subdivides view space / object space
1389        // in order to converge to some optimal cost for this partition
1390        // start with object space partiton
1391        // then optimizate view space partition for the current osp
1392        // and vice versa until iteration depth is reached.
1393        while (1)
1394        {
1395                char subdivisionStatsLog[100];
1396                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", steps);
1397                mSubdivisionStats.open(subdivisionStatsLog);
1398
1399                // subdivide object space first
1400                ResetObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1401       
1402                // set the number of leaves 'evaluated' from the previous methods
1403                // we go for the same numbers, but we try to optimize both subdivisions
1404                mBvHierarchy->mTermMaxLeaves = maxObjectSpaceLeaves;
1405
1406                // process object space candidates
1407                RunConstruction(false);
1408
1409                cout << "iteration " << steps << " of " << limit << " finished" << endl;
1410                mSubdivisionStats.close();
1411
1412                if ((++ steps) >= limit)
1413                        break;
1414
1415                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", steps);
1416                mSubdivisionStats.open(subdivisionStatsLog);
1417
1418                /////////////////
1419                // subdivide view space with respect to the objects
1420
1421                ResetViewSpaceSubdivision(mTQueue, sampleRays, objects, forcedViewSpace);
1422
1423                mVspTree->mMaxViewCells = maxViewSpaceLeaves;
1424
1425                // process view space candidates
1426                RunConstruction(false);
1427
1428                cout << "iteration " << steps << " of " << limit << " finished" << endl;
1429                mSubdivisionStats.close();
1430
1431                if ((++ steps) >= limit)
1432                        break;
1433        }
1434       
1435        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
1436
1437        mHierarchyStats.Stop();
1438        mVspTree->mVspStats.Stop();
1439        FinishObjectSpaceSubdivision(objects);
1440}
1441
1442
1443
1444bool HierarchyManager::FinishedConstruction() const
1445{
1446        return mTQueue.Empty();
1447}
1448
1449
1450bool HierarchyManager::ObjectSpaceSubdivisionConstructed() const
1451{
1452        /*switch (mObjectSpaceSubdivisionType)
1453        {
1454        case KD_BASED_OBJ_SUBDIV:
1455                return mOspTree && mOspTree->GetRoot();
1456        case BV_BASED_OBJ_SUBDIV:
1457                return mBvHierarchy && mBvHierarchy->GetRoot();
1458        default:
1459                return false;
1460        }*/
1461        return mObjectSpaceSubdivisionType != NO_OBJ_SUBDIV;
1462}
1463
1464
1465bool HierarchyManager::ViewSpaceSubdivisionConstructed() const
1466{
1467        return mViewSpaceSubdivisionType != NO_VIEWSPACE_SUBDIV;
1468        //return mVspTree && mVspTree->GetRoot();
1469}
1470
1471
1472void HierarchyManager::CollectDirtyCandidates(const SubdivisionCandidateContainer &chosenCandidates,
1473                                                                                          SubdivisionCandidateContainer &dirtyList)
1474{
1475        SubdivisionCandidateContainer::const_iterator sit, sit_end = chosenCandidates.end();
1476        SubdivisionCandidate::NewMail();
1477
1478        for (sit = chosenCandidates.begin(); sit != sit_end; ++ sit)
1479        {
1480                (*sit)->CollectDirtyCandidates(dirtyList, true);
1481        }
1482}
1483
1484
1485int HierarchyManager::RepairQueue(const SubdivisionCandidateContainer &dirtyList,
1486                                                                  SplitQueue &splitQueue,
1487                                                                  const bool recomputeSplitPlaneOnRepair)
1488{
1489        // for each update of the view space partition:
1490        // the candidates from object space partition which
1491        // have been afected by the view space split (the kd split candidates
1492        // which saw the view cell which was split) must be reevaluated
1493        // (maybe not locally, just reinsert them into the queue)
1494        //
1495        // vice versa for the view cells
1496        // for each update of the object space partition
1497        // reevaluate split candidate for view cells which saw the split kd cell
1498        //
1499        // the priority queue update can be solved by implementing a binary heap
1500        // (explicit data structure, binary tree)
1501        // *) inserting and removal is efficient
1502        // *) search is not efficient => store queue position with each
1503        // split candidate
1504
1505        int repaired = 0;
1506
1507        // collect list of "dirty" candidates
1508        const long startTime = GetTime();
1509        if (0) cout << "repairing " << (int)dirtyList.size() << " candidates ... ";
1510
1511        const float prop = (float)mMaxRepairs / (float)dirtyList.size();
1512
1513        ///////////////////////////
1514        //-- reevaluate the dirty list
1515
1516        SubdivisionCandidateContainer::const_iterator sit, sit_end = dirtyList.end();
1517       
1518        int i = 0;
1519        for (sit = dirtyList.begin(); sit != sit_end; ++ sit, ++ i)
1520        {
1521                // only repair a certain number of candidates
1522                if ((mMaxRepairs < (int)dirtyList.size()) && (Random(1.0f) >= prop))
1523                        continue;
1524
1525                SubdivisionCandidate* sc = *sit;
1526                const float rcd = sc->GetRenderCostDecrease();
1527               
1528                // erase from queue
1529                splitQueue.Erase(sc);
1530                // reevaluate candidate
1531                sc->EvalCandidate(recomputeSplitPlaneOnRepair);
1532                 // reinsert
1533                splitQueue.Push(sc);
1534               
1535                ++ repaired;
1536                //if (i % 10 == 0)
1537                        cout << ".";
1538
1539#ifdef GTP_DEBUG
1540                Debug << "candidate " << sc << " reevaluated\n"
1541                          << "render cost decrease diff " <<  rcd - sc->GetRenderCostDecrease()
1542                          << " old: " << rcd << " new " << sc->GetRenderCostDecrease() << endl;
1543#endif 
1544        }
1545
1546        const long endTime = GetTime();
1547        const Real timeDiff = TimeDiff(startTime, endTime);
1548
1549        mHierarchyStats.mRepairTime += timeDiff;
1550
1551        return repaired;
1552}
1553
1554
1555void HierarchyManager::ResetQueue(SplitQueue &splitQueue, const bool recomputeSplitPlane)
1556{
1557        SubdivisionCandidateContainer mCandidateBuffer;
1558
1559        // remove from queue
1560        while (!splitQueue.Empty())
1561        {
1562                SubdivisionCandidate *candidate = NextSubdivisionCandidate(splitQueue);
1563               
1564                // reevaluate local split plane and priority
1565                candidate->EvalCandidate(recomputeSplitPlane);
1566                cout << ".";
1567                mCandidateBuffer.push_back(candidate);
1568        }
1569
1570        // put back into queue
1571        SubdivisionCandidateContainer::const_iterator sit, sit_end = mCandidateBuffer.end();
1572    for (sit = mCandidateBuffer.begin(); sit != sit_end; ++ sit)
1573        {
1574                splitQueue.Push(*sit);
1575        }
1576}
1577
1578
1579void HierarchyManager::ExportObjectSpaceHierarchy(OUT_STREAM &stream)
1580{
1581        // the type of the view cells hierarchy
1582        switch (mObjectSpaceSubdivisionType)
1583        {
1584        case KD_BASED_OBJ_SUBDIV:
1585                stream << "<ObjectSpaceHierarchy type=\"osp\">" << endl;
1586                mOspTree->Export(stream);
1587                stream << endl << "</ObjectSpaceHierarchy>" << endl;
1588                break;         
1589        case BV_BASED_OBJ_SUBDIV:
1590                stream << "<ObjectSpaceHierarchy type=\"bvh\">" << endl;
1591                mBvHierarchy->Export(stream);
1592                stream << endl << "</ObjectSpaceHierarchy>" << endl;
1593                break;
1594        }
1595}
1596
1597
1598void HierarchyManager::PrintHierarchyStatistics(ostream &stream) const
1599{
1600        stream << mHierarchyStats << endl;
1601        stream << "\nview space:" << endl << endl;
1602        stream << mVspTree->GetStatistics() << endl;
1603        stream << "\nobject space:" << endl << endl;
1604
1605        switch (mObjectSpaceSubdivisionType)
1606        {
1607        case KD_BASED_OBJ_SUBDIV:
1608                {
1609                        stream << mOspTree->GetStatistics() << endl;
1610                        break;
1611                }
1612        case BV_BASED_OBJ_SUBDIV:
1613                {
1614                        stream << mBvHierarchy->GetStatistics() << endl;
1615                        break;
1616                }
1617        default:
1618                break;
1619        }
1620}
1621
1622
1623void HierarchyManager::ExportObjectSpaceHierarchy(Exporter *exporter,
1624                                                                                                  const ObjectContainer &objects,
1625                                                                                                  AxisAlignedBox3 *bbox,
1626                                                                                                  const float maxRenderCost,
1627                                                                                                  const bool exportBounds) const
1628{
1629        switch (mObjectSpaceSubdivisionType)
1630        {
1631        case KD_BASED_OBJ_SUBDIV:
1632                {
1633                        ExportOspTree(exporter, objects);
1634                        break;
1635                }
1636        case BV_BASED_OBJ_SUBDIV:
1637                {
1638                        exporter->ExportBvHierarchy(*mBvHierarchy, maxRenderCost, bbox, exportBounds);
1639                        break;
1640                }
1641        default:
1642                break;
1643        }
1644}
1645
1646
1647void HierarchyManager::ExportOspTree(Exporter *exporter,
1648                                                                         const ObjectContainer &objects) const
1649{
1650        if (0) exporter->ExportGeometry(objects);
1651                       
1652        exporter->SetWireframe();
1653        exporter->ExportOspTree(*mOspTree, 0);
1654}
1655
1656
1657Intersectable *HierarchyManager::GetIntersectable(Intersectable *obj,
1658                                                                                                  const Vector3 &point) const
1659{
1660
1661        if (!obj)
1662                return NULL;
1663
1664        switch (mObjectSpaceSubdivisionType)
1665        {
1666        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
1667                {
1668                        KdLeaf *leaf = mOspTree->GetLeaf(point, NULL);
1669                        return mOspTree->GetOrCreateKdIntersectable(leaf);
1670                }
1671        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
1672                {
1673                        BvhLeaf *leaf = mBvHierarchy->GetLeaf(obj);
1674                        return leaf;
1675                }
1676        default:
1677                return obj;
1678        }
1679}
1680
1681Intersectable *HierarchyManager::GetIntersectable(const VssRay &ray,
1682                                                                                                  const bool isTermination) const
1683{
1684        Intersectable *obj = NULL;
1685        Vector3 pt;
1686        KdNode *node;
1687
1688        ray.GetSampleData(isTermination, pt, &obj, &node);
1689
1690        if (!obj)
1691                return NULL;
1692
1693        switch (mObjectSpaceSubdivisionType)
1694        {
1695        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
1696                {
1697                        KdLeaf *leaf = mOspTree->GetLeaf(pt, node);
1698                        return mOspTree->GetOrCreateKdIntersectable(leaf);
1699                }
1700        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
1701                {
1702                        BvhLeaf *leaf = mBvHierarchy->GetLeaf(obj);
1703                        return leaf;
1704                }
1705        default:
1706                break;
1707        }
1708
1709        return obj;
1710}
1711
1712
1713void HierarchyStatistics::Print(ostream &app) const
1714{
1715        app << "=========== Hierarchy statistics ===============\n";
1716
1717        app << setprecision(4);
1718
1719        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
1720       
1721        app << "#N_RTIME  ( Repair time [s] )\n" << mRepairTime * 1e-3f << " \n";
1722
1723        app << "#N_NODES ( Number of nodes )\n" << mNodes << "\n";
1724
1725        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
1726
1727        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
1728
1729        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << mMaxDepth << endl;
1730
1731        app << "#N_GLOBALCOSTMISSES ( Global cost misses )\n" << mGlobalCostMisses << endl;
1732       
1733        app << "========== END OF Hierarchy statistics ==========\n";
1734}
1735
1736
1737static void RemoveRayRefs(const ObjectContainer &objects)
1738{
1739        ObjectContainer::const_iterator oit, oit_end = objects.end();
1740        for (oit = objects.begin(); oit != oit_end; ++ oit)
1741        {
1742                (*oit)->DelRayRefs();
1743        }
1744}
1745
1746
1747void HierarchyManager::FinishObjectSpaceSubdivision(const ObjectContainer &objects,
1748                                                                                                        const bool removeRayRefs) const
1749{
1750        switch (mObjectSpaceSubdivisionType)
1751        {
1752        case KD_BASED_OBJ_SUBDIV:
1753                {
1754                        mOspTree->mOspStats.Stop();
1755                        break;
1756                }
1757        case BV_BASED_OBJ_SUBDIV:
1758                {
1759                        mBvHierarchy->mBvhStats.Stop();
1760                        if (removeRayRefs)
1761                                RemoveRayRefs(objects);
1762                        break;
1763                }
1764        default:
1765                break;
1766        }
1767}
1768
1769
1770void HierarchyManager::ExportBoundingBoxes(OUT_STREAM &stream, const ObjectContainer &objects)
1771{
1772        stream << "<BoundingBoxes>" << endl;
1773           
1774        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
1775        {
1776                KdIntersectableMap::const_iterator kit, kit_end = mOspTree->mKdIntersectables.end();
1777
1778                int id = 0;
1779                for (kit = mOspTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
1780                {
1781                        Intersectable *obj = (*kit).second;
1782                        const AxisAlignedBox3 box = obj->GetBox();
1783               
1784                        obj->SetId(id);
1785
1786                        stream << "<BoundingBox" << " id=\"" << id << "\""
1787                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1788                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1789                }
1790        }
1791        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
1792        {
1793                // export bounding boxes
1794        vector<BvhNode *> nodes;
1795
1796                // hack: should also expect interior nodes
1797                mBvHierarchy->CollectNodes(mBvHierarchy->GetRoot(), nodes);
1798
1799                vector<BvhNode *>::const_iterator oit, oit_end = nodes.end();
1800
1801                for (oit = nodes.begin(); oit != oit_end; ++ oit)
1802                {
1803                        const AxisAlignedBox3 box = (*oit)->GetBox();
1804                        const int id = (*oit)->GetId();
1805                       
1806                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
1807                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1808                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1809                }
1810        }
1811        else
1812        {
1813                ObjectContainer::const_iterator oit, oit_end = objects.end();
1814
1815                for (oit = objects.begin(); oit != oit_end; ++ oit)
1816                {
1817                        const AxisAlignedBox3 box = (*oit)->GetBox();
1818               
1819                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
1820                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1821                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1822                }
1823        }
1824               
1825        stream << "</BoundingBoxes>" << endl;
1826}
1827
1828
1829class HierarchyNodeWrapper;
1830
1831
1832template <typename T> class myless
1833{
1834public:
1835        bool operator() (T v1, T v2) const
1836        {
1837                return (v1->GetMergeCost() < v2->GetMergeCost());
1838        }
1839};
1840
1841
1842typedef priority_queue<HierarchyNodeWrapper *, vector<HierarchyNodeWrapper *>,
1843                                           myless<vector<HierarchyNodeWrapper *>::value_type> > HierarchyNodeQueue;
1844
1845class HierarchyNodeWrapper
1846{
1847public:
1848        enum {VSP_NODE, BVH_NODE, VIEW_CELL};
1849
1850        virtual float GetMergeCost() const = 0;
1851        virtual int Type() const  = 0;
1852        virtual bool IsLeaf() const = 0;
1853
1854        virtual void PushChildren(HierarchyNodeQueue &tQueue) = 0;
1855};
1856
1857
1858class VspNodeWrapper: public HierarchyNodeWrapper
1859{
1860public:
1861        VspNodeWrapper(VspNode *node): mNode(node) {}
1862
1863        int Type() const { return VSP_NODE; }
1864
1865        float GetMergeCost() const { return (float) -mNode->mTimeStamp; };
1866
1867        bool IsLeaf() const { return mNode->IsLeaf(); }
1868
1869        void PushChildren(HierarchyNodeQueue &tQueue)
1870        {
1871                if (!mNode->IsLeaf())
1872                {
1873                        VspInterior *interior = static_cast<VspInterior *>(mNode);
1874
1875                        tQueue.push(new VspNodeWrapper(interior->GetFront()));
1876                        tQueue.push(new VspNodeWrapper(interior->GetBack()));
1877                }
1878        }
1879
1880        VspNode *mNode;
1881};
1882
1883
1884class BvhNodeWrapper: public HierarchyNodeWrapper
1885{
1886public:
1887        BvhNodeWrapper(BvhNode *node): mNode(node) {}
1888       
1889        int Type()  const { return BVH_NODE; }
1890
1891        float GetMergeCost() const { return (float)-mNode->GetTimeStamp(); };
1892
1893        bool IsLeaf() const { return mNode->IsLeaf(); }
1894
1895        void PushChildren(HierarchyNodeQueue &tQueue)
1896        {
1897                if (!mNode->IsLeaf())
1898                {
1899                        BvhInterior *interior = static_cast<BvhInterior *>(mNode);
1900
1901                        tQueue.push(new BvhNodeWrapper(interior->GetFront()));
1902                        tQueue.push(new BvhNodeWrapper(interior->GetBack()));
1903                }
1904        }
1905
1906        BvhNode *mNode;
1907};
1908
1909
1910class ViewCellWrapper: public HierarchyNodeWrapper
1911{
1912public:
1913
1914        ViewCellWrapper(ViewCell *vc): mViewCell(vc) {}
1915       
1916        int Type()  const { return VIEW_CELL; }
1917
1918        float GetMergeCost() const { return mViewCell->GetMergeCost(); };
1919
1920        bool IsLeaf() const { return mViewCell->IsLeaf(); }
1921
1922        void PushChildren(HierarchyNodeQueue &tQueue)
1923        {
1924                if (!mViewCell->IsLeaf())
1925                {
1926                        ViewCellInterior *interior = static_cast<ViewCellInterior *>(mViewCell);
1927
1928                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1929
1930                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1931                        {
1932                                tQueue.push(new ViewCellWrapper(*it));
1933                        }
1934                }
1935        }
1936
1937        ViewCell *mViewCell;
1938};
1939
1940
1941void HierarchyManager::CollectBestSet(const int maxSplits,
1942                                                                          const float maxMemoryCost,
1943                                                                          ViewCellContainer &viewCells,
1944                                                                          vector<BvhNode *> &bvhNodes)
1945{
1946        HierarchyNodeQueue tqueue;
1947        //tqueue.push(new VspNodeWrapper(mVspTree->GetRoot()));
1948        tqueue.push(new ViewCellWrapper(mVspTree->mViewCellsTree->GetRoot()));
1949        tqueue.push(new BvhNodeWrapper(mBvHierarchy->GetRoot()));
1950       
1951        float memCost = 0;
1952
1953        while (!tqueue.empty())
1954        {
1955                HierarchyNodeWrapper *nodeWrapper = tqueue.top();
1956                tqueue.pop();
1957                //cout << "priority: " << nodeWrapper->GetMergeCost() << endl;
1958                // save the view cells if it is a leaf or if enough view cells have already been traversed
1959                // because of the priority queue, this will be the optimal set of view cells
1960                if (nodeWrapper->IsLeaf() ||
1961                        ((viewCells.size() + bvhNodes.size() + tqueue.size() + 1) >= maxSplits) ||
1962                        (memCost > maxMemoryCost)
1963                        )
1964                {
1965                        if (nodeWrapper->Type() == HierarchyNodeWrapper::VIEW_CELL)
1966                        {
1967                                //cout << "1";
1968                                ViewCellWrapper *viewCellWrapper = static_cast<ViewCellWrapper *>(nodeWrapper);
1969                                viewCells.push_back(viewCellWrapper->mViewCell);
1970                        }
1971                        else
1972                        {
1973                                //cout << "0";
1974                                BvhNodeWrapper *bvhNodeWrapper = static_cast<BvhNodeWrapper *>(nodeWrapper);
1975                                bvhNodes.push_back(bvhNodeWrapper->mNode);
1976                        }
1977                }
1978                else
1979                {       
1980                        nodeWrapper->PushChildren(tqueue);
1981                }
1982
1983                delete nodeWrapper;
1984        }
1985}
1986
1987
1988void HierarchyManager::ComputePvs(const ObjectPvs &pvs,
1989                                                                  float &rc,
1990                                                                  int &pvsEntries)
1991{
1992        BvhNode::NewMail();
1993
1994        ObjectPvsIterator pit = pvs.GetIterator();
1995
1996        while (pit.HasMoreEntries())
1997        {
1998                Intersectable *obj = pit.Next();
1999
2000                if (obj->Type() != Intersectable::BVH_INTERSECTABLE)
2001                {
2002                        cout << "error: wrong object type detected: " << obj->Type() << endl;
2003                        exit(0);
2004                }
2005
2006                BvhNode *intersect = static_cast<BvhNode *>(obj);
2007                BvhNode *activeNode;
2008
2009                // hack for choosing which node to account for
2010                if (intersect->IsLeaf())
2011                {
2012                        activeNode =
2013                                static_cast<BvhLeaf *>(intersect)->GetActiveNode();
2014                }
2015                else
2016                {
2017                        activeNode = intersect;
2018                }
2019
2020                if (!activeNode->Mailed())
2021                {
2022                        activeNode->Mail();
2023
2024#if STUPID_METHOD
2025
2026                        ObjectContainer objects;
2027            activeNode->CollectObjects(objects);
2028                        rc += mBvHierarchy->EvalAbsCost(objects);
2029#else
2030                        rc += mBvHierarchy->GetRenderCostIncrementially(activeNode);
2031#endif
2032                        ++ pvsEntries;
2033                }
2034        }
2035}
2036
2037
2038void HierarchyManager::GetPvsEfficiently(ViewCell *viewCell, ObjectPvs &pvs) const
2039{
2040        ////////////////
2041        //-- pvs is not stored with the interiors => reconstruct
2042       
2043        // add pvs from leaves
2044        stack<ViewCell *> tstack;
2045        tstack.push(viewCell);
2046
2047        Intersectable::NewMail();
2048
2049        while (!tstack.empty())
2050        {
2051                ViewCell *vc = tstack.top();
2052                tstack.pop();
2053       
2054                // add newly found pvs to merged pvs: break here even for interior
2055                if (!vc->GetPvs().Empty())
2056                {
2057                        ObjectPvsIterator pit = vc->GetPvs().GetIterator();
2058
2059                        while (pit.HasMoreEntries())
2060                        {               
2061                                Intersectable *object = pit.Next();
2062
2063                                if (!object->Mailed())
2064                                {
2065                                        object->Mail();
2066                                        pvs.AddSampleDirty(object, 1.0f);
2067                                }
2068                        }
2069                }
2070                else if (!vc->IsLeaf()) // interior cells: go down to leaf level
2071                {
2072                        ViewCellInterior *interior = static_cast<ViewCellInterior *>(vc);
2073                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
2074
2075                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
2076                        {
2077                                tstack.push(*it);
2078                        }               
2079                }
2080        }
2081}
2082
2083
2084// TODO matt: implement this function for different storing methods
2085void HierarchyManager::GetPvsIncrementially(ViewCell *vc, ObjectPvs &pvs) const
2086{
2087        ////////////////
2088        //-- pvs is not stored with the interiors => reconstruct
2089       
2090        // add pvs from leaves
2091        stack<ViewCell *> tstack;
2092        tstack.push(vc);
2093
2094        while (!tstack.empty())
2095        {
2096                vc = tstack.top();
2097                tstack.pop();
2098       
2099                // add newly found pvs to merged pvs: break here even for interior
2100                if (!vc->GetPvs().Empty())
2101                {
2102                        pvs.MergeInPlace(vc->GetPvs());
2103                }
2104                else if (!vc->IsLeaf()) // interior cells: go down to leaf level
2105                {
2106                        ViewCellInterior *interior = static_cast<ViewCellInterior *>(vc);
2107                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
2108
2109                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
2110                        {
2111                                tstack.push(*it);
2112                        }               
2113                }
2114        }
2115}
2116
2117
2118// TODO matt: implement this function for different storing methods
2119void HierarchyManager::PullUpPvsIncrementally(ViewCell *viewCell) const
2120{
2121        ////////////////
2122        //-- pvs is not stored with the interiors => reconstruct
2123       
2124        // early exit: pvs is already pulled up to this view cell
2125        if (!viewCell->GetPvs().Empty())
2126                return;
2127
2128        // add pvs from leaves
2129        stack<ViewCell *> tstack;
2130        tstack.push(viewCell);
2131
2132        ViewCell *vc = viewCell;
2133
2134        while (!tstack.empty())
2135        {
2136                vc = tstack.top();
2137                tstack.pop();
2138       
2139                // add newly found pvs to merged pvs: break here even for interior
2140                if (!vc->GetPvs().Empty())
2141                {
2142                        viewCell->GetPvs().MergeInPlace(vc->GetPvs());
2143                }
2144                else if (!vc->IsLeaf()) // interior cells: go down to leaf level
2145                {
2146                        //cout <<" t";
2147                        ViewCellInterior *interior = static_cast<ViewCellInterior *>(vc);
2148                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
2149
2150                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
2151                        {
2152                                tstack.push(*it);
2153                        }               
2154                }
2155        }
2156}
2157
2158
2159
2160// TODO matt: implement this function for different storing methods
2161void HierarchyManager::GetPvsRecursive(ViewCell *vc, ObjectPvs &pvs) const
2162{
2163        ////////////////
2164        //-- pvs is not stored with the interiors => reconstruct
2165        if (vc->IsLeaf() || !vc->GetPvs().Empty())
2166        {
2167                pvs = vc->GetPvs();
2168        }
2169        else
2170        {
2171                ViewCellInterior *interior = static_cast<ViewCellInterior *>(vc);
2172#if 0
2173                ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
2174                const int childPvsSize = (int)interior->mChildren.size();
2175                vector<ObjectPvs> childPvs;
2176                childPvs.resize((int)interior->mChildren.size());
2177
2178                int i = 0;
2179                for (it = interior->mChildren.begin(); it != it_end; ++ it, ++ i)
2180                {
2181                        GetPvsRecursive(*it, childPvs[i]);
2182                        pvs.MergeInPlace(childPvs[i]);
2183                }
2184#else
2185
2186                ObjectPvs leftPvs, rightPvs;
2187
2188                GetPvsRecursive(interior->mChildren[0], leftPvs);
2189                GetPvsRecursive(interior->mChildren[1], rightPvs);
2190
2191                ObjectPvs::Merge(pvs, leftPvs, rightPvs);
2192#endif
2193        }
2194}
2195
2196
2197int HierarchyManager::ExtractStatistics(const int maxSplits,
2198                                                                                const float maxMemoryCost,
2199                                                                                float &renderCost,
2200                                                                                float &memory,
2201                                                                                int &pvsEntries,
2202                                                                                int &viewSpaceSplits,
2203                                                                                int &objectSpaceSplits,
2204                                                                                const bool useFilter,
2205                                                                                const bool useHisto,
2206                                                                                const int histoMem,
2207                                                                                const int pass,
2208                                                                                bool &histoUsed)
2209{
2210        ViewCellContainer viewCells;
2211        vector<BvhNode *> bvhNodes;
2212
2213        // collect best set of view cells for this #splits
2214    CollectBestSet(maxSplits, maxMemoryCost, viewCells, bvhNodes);
2215        vector<BvhNode *>::const_iterator bit, bit_end = bvhNodes.end();
2216       
2217        // set new nodes to be active
2218        for (bit = bvhNodes.begin(); bit != bit_end; ++ bit)
2219        {
2220                mBvHierarchy->SetActive(*bit);
2221        }
2222
2223        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
2224
2225        pvsEntries = 0;
2226        renderCost = 0.0f;
2227
2228        ViewCell::NewMail();
2229
2230        //cout << "\nviewcells: " << viewCells.size() << endl;
2231        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
2232        {
2233                ViewCell *vc = *vit;
2234                float rc = 0;
2235       
2236#if STUPID_METHOD       
2237                ObjectPvs pvs;
2238                GetPvsIncrementially(vc, pvs);
2239                vc->SetPvs(pvs);
2240               
2241#else
2242       
2243                ObjectPvs pvs;
2244                               
2245                if (vc->GetPvs().Empty())
2246                {
2247                        // warning: uses mailing, pvs not sorted!!
2248                        GetPvsEfficiently(vc, pvs);
2249                        //GetPvsRecursive(vc, pvs);
2250                        vc->SetPvs(pvs);
2251                }
2252#endif
2253
2254                vc->Mail();
2255
2256                if (useFilter)
2257                {
2258                        const long startT = GetTime();
2259                        ObjectPvs filteredPvs;
2260                        mVspTree->mViewCellsManager->ApplyFilter2(vc, false, 1.0f, filteredPvs);
2261                        const long endT = GetTime();
2262
2263                        //cout << "filter computed in " << TimeDiff(startT, endT) * 1e-3f << " secs" << endl;
2264                        ComputePvs(filteredPvs, rc, pvsEntries);
2265                }
2266                else
2267                {
2268                        ComputePvs(vc->GetPvs(), rc, pvsEntries);
2269                        vc->SetPvsCost(rc);
2270                }
2271
2272                rc *= vc->GetVolume();
2273                renderCost += rc;
2274        }
2275
2276        renderCost /= mVspTree->mViewCellsManager->GetViewSpaceBox().GetVolume();
2277        memory = pvsEntries * ObjectPvs::GetEntrySize();
2278
2279        viewSpaceSplits = (int)viewCells.size();
2280        objectSpaceSplits = (int)bvhNodes.size();
2281
2282        ////////////////////////
2283    //-- evaluate histogram for pvs size
2284
2285        if (useHisto && (memory <= (float)histoMem))
2286        {
2287                char str[100];
2288                char statsPrefix[100];
2289                //int histoStepSize;
2290
2291                Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
2292       
2293                cout << "computing pvs histogram for " << histoMem << " memory" << endl;
2294                Debug << "computing pvs histogram for " << histoMem << " memory" << endl;
2295               
2296                sprintf(str, "-%05d-%05d-histo-pvs.log", pass, histoMem);
2297                const string filename = string(statsPrefix) + string(str);
2298
2299                mVspTree->mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, viewCells);
2300
2301                histoUsed = true;
2302        }
2303
2304        //cout << "viewCells: " << (int)viewCells.size() << " nodes: " << (int)bvhNodes.size() << " rc: " << renderCost << " entries: " << pvsEntries << endl;
2305
2306        // delete old "base" view cells if they are not leaves
2307        ViewCellContainer::const_iterator oit, oit_end = mOldViewCells.end();
2308
2309        for (oit = mOldViewCells.begin(); oit != oit_end; ++ oit)
2310        {
2311                if (!(*oit)->Mailed() && !(*oit)->IsLeaf())
2312                {
2313                        (*oit)->GetPvs().Clear();
2314                }
2315        }
2316
2317        // store current level
2318        mOldViewCells = viewCells;
2319
2320        return (int)(viewCells.size() + bvhNodes.size());
2321}
2322
2323
2324void HierarchyManager::ExportStats(ofstream &stats,
2325                                                                   SplitQueue &tQueue,
2326                                                                   const ObjectContainer &objects)
2327{
2328        HierarchySubdivisionStats subStats;
2329        subStats.Reset();
2330
2331        /////////////
2332        //-- initial situation
2333
2334        subStats.mNumSplits = 0;
2335        subStats.mTotalRenderCost = (float)objects.size();
2336        subStats.mEntriesInPvs = 1;
2337        subStats.mMemoryCost = (float)ObjectPvs::GetEntrySize();
2338        subStats.mFullMemory = subStats.mMemoryCost;
2339        subStats.mViewSpaceSplits = 0;
2340        subStats.mObjectSpaceSplits = 0;
2341        subStats.mRenderCostDecrease = 0;
2342        subStats.Print(stats);
2343
2344        cout << "exporting vsposp stats ... " << endl;
2345
2346        //-- go through tree in the order of render cost decrease
2347        //-- which is the same order as the view cells were merged
2348        //-- or the reverse order of subdivision for subdivision-only
2349        //-- view cell hierarchies.
2350
2351        while (!tQueue.Empty())
2352        {
2353                SubdivisionCandidate *nextCandidate = NextSubdivisionCandidate(tQueue);
2354                bool isLeaf;
2355                int timeStamp;
2356                //float rcDecr;
2357                //int entriesIncr;
2358
2359                if (nextCandidate->Type() == SubdivisionCandidate::VIEW_SPACE)
2360                {
2361                        timeStamp = (int)-nextCandidate->GetPriority();
2362
2363                        VspNode *newNode = mVspTree->SubdivideAndCopy(tQueue, nextCandidate);
2364                        VspNode *oldNode = (VspNode *)nextCandidate->mEvaluationHack;
2365
2366                        isLeaf = newNode->IsLeaf();
2367                        //subStats.mRenderCostDecrease = oldNode->mRenderCostDecr;
2368                        //entriesIncr = oldNode->mPvsEntriesIncr;
2369                }
2370                else
2371                {
2372                        timeStamp = (int)-nextCandidate->GetPriority();
2373
2374                        BvhNode *newNode = mBvHierarchy->SubdivideAndCopy(tQueue, nextCandidate);
2375                        BvhNode *oldNode = (BvhNode *)nextCandidate->mEvaluationHack;
2376
2377                        isLeaf = newNode->IsLeaf();
2378                        //subStats.mRenderCostDecrease = oldNode->mRenderCostDecr;
2379                        //entriesIncr = oldNode->mPvsEntriesIncr;
2380                }               
2381
2382                if (!isLeaf)
2383                {
2384                        subStats.mTotalRenderCost -= subStats.mRenderCostDecrease;
2385                        //subStats.mEntriesInPvs += entriesIncr;
2386
2387                        if (nextCandidate->Type() == SubdivisionCandidate::VIEW_SPACE)
2388                        {
2389                                ++ subStats.mViewSpaceSplits;
2390                                //cout << "v";
2391                                //cout << "vsp t: " << timeStamp << " rc: " << rcDecr << " pvs: " << entriesIncr << endl;
2392                        }
2393                        else
2394                        {
2395                                ++ subStats.mObjectSpaceSplits;
2396                                //cout << "o";
2397                                //"osp t: " << timeStamp << " rc: " << rcDecr << " pvs: " << entriesIncr << endl;
2398                        }
2399
2400                        ++ subStats.mNumSplits;
2401
2402                        if ((subStats.mNumSplits % 500) == 499)
2403                                cout << subStats.mNumSplits << " steps taken" << endl;
2404
2405                        subStats.mMemoryCost = (float)subStats.mEntriesInPvs * (float)ObjectPvs::GetEntrySize();
2406                        subStats.mFullMemory = subStats.mMemoryCost;
2407
2408                        subStats.Print(stats);
2409
2410                }
2411
2412                DEL_PTR(nextCandidate);
2413        }
2414
2415        stats.close();
2416}
2417
2418
2419void HierarchyManager::EvaluateSubdivision(const VssRayContainer &sampleRays,
2420                                                                                   const ObjectContainer &objects,
2421                                                                                   const string &filename)
2422{
2423#if 0
2424        VspTree *oldVspTree = mVspTree;
2425        ViewCellsManager *vm = mVspTree->mViewCellsManager;
2426        BvHierarchy *oldHierarchy = mBvHierarchy;
2427
2428        mBvHierarchy = new BvHierarchy();
2429        mBvHierarchy->mHierarchyManager = this;
2430        mBvHierarchy->mViewCellsManager = vm;
2431
2432        mVspTree = new VspTree();
2433        mVspTree->mHierarchyManager = this;
2434        mVspTree->mViewCellsManager = vm;
2435
2436        // create first nodes
2437        mVspTree->Initialise(sampleRays, &oldVspTree->mBoundingBox);
2438        InitialiseObjectSpaceSubdivision(objects);
2439
2440        const long startTime = GetTime();
2441        cout << "Constructing evaluation hierarchies ... \n";
2442       
2443        ofstream stats;
2444        stats.open(filename.c_str());
2445        SplitQueue tQueue;
2446
2447        BvhNode *oldBvhRoot = oldHierarchy->GetRoot();
2448        VspNode *oldVspRoot = oldVspTree->GetRoot();
2449
2450        RayInfoContainer *viewSpaceRays = new RayInfoContainer();
2451       
2452        SubdivisionCandidate *firstVsp = mVspTree->PrepareConstruction(sampleRays, *viewSpaceRays);
2453        tQueue.Push(firstVsp);
2454
2455        mBvHierarchy->PrepareConstruction(tQueue, sampleRays, objects);
2456
2457    firstVsp->mEvaluationHack = oldVspRoot;
2458        firstBvh->mEvaluationHack = oldBvhRoot;
2459
2460        firstVsp->SetPriority((float)-oldVspRoot->mTimeStamp);
2461        firstBvh->SetPriority((float)-oldBvhRoot->GetTimeStamp());
2462       
2463        ExportStats(stats, tQueue, objects);
2464
2465        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
2466        RemoveRayRefs(objects);
2467
2468        // view cells needed only for evaluation
2469        ViewCellContainer viewCells;
2470        mVspTree->CollectViewCells(viewCells, false);
2471       
2472        // helper trees can be destroyed
2473        DEL_PTR(mVspTree);
2474        DEL_PTR(mBvHierarchy);
2475
2476        CLEAR_CONTAINER(viewCells);
2477
2478        // reset hierarchies
2479        mVspTree = oldVspTree;
2480        mBvHierarchy = oldHierarchy;
2481
2482        // reinstall old bv refs
2483        vector<BvhLeaf *> leaves;
2484        mBvHierarchy->CollectLeaves(mBvHierarchy->GetRoot(), leaves);
2485        vector<BvhLeaf *>::const_iterator bit, bit_end = leaves.end();
2486
2487        for (bit = leaves.begin(); bit != bit_end; ++ bit)
2488        {
2489                mBvHierarchy->AssociateObjectsWithLeaf(*bit);
2490        }
2491#endif
2492}
2493
2494
2495void HierarchyManager::EvaluateSubdivision2(ofstream &splitsStats,
2496                                                                                        const int splitsStepSize,
2497                                                                                        const bool useFilter,
2498                                                                                        const bool useHisto,
2499                                                                                        const int histoMem,
2500                                                                                        const int pass)
2501{
2502        vector<HierarchySubdivisionStats> subStatsContainer;
2503
2504        int splits = (1 + (mHierarchyStats.Leaves() - 1) / splitsStepSize) * splitsStepSize;
2505        cout << "splits: " << splits << endl;
2506
2507        bool histoUsed = false;
2508
2509        while (1)
2510        {
2511                HierarchySubdivisionStats subStats;
2512                subStats.mNumSplits = ExtractStatistics(splits,
2513                                                                                                99999.0,
2514                                                                                                subStats.mTotalRenderCost,
2515                                                                                                subStats.mMemoryCost,
2516                                                                                                subStats.mEntriesInPvs,
2517                                                                                                subStats.mViewSpaceSplits,
2518                                                                                                subStats.mObjectSpaceSplits,
2519                                                                                                useFilter,
2520                                                                                                useHisto && !histoUsed,
2521                                                                                                histoMem,
2522                                                                                                pass,
2523                                                                                                histoUsed);
2524
2525               
2526                const float objectSpaceHierarchyMem = float(
2527                                                                                          subStats.mObjectSpaceSplits * mBvHierarchy->mMemoryConst//sizeof(ObjectContainer)
2528                                                                                          //+ (subStats.mObjectSpaceSplits - 1) * sizeof(BvhInterior)
2529                                                                                          //+sizeof(BvHierarchy)
2530                                                                                          ) / float(1024 * 1024);
2531
2532                       
2533                const float viewSpaceHierarchyMem = float(
2534                                                                                        subStats.mViewSpaceSplits * mVspTree->mMemoryConst//sizeof(ObjectPvs)
2535                                                                                        //+ (subStats.mViewSpaceSplits - 1) * sizeof(VspInterior)
2536                                                                                        + sizeof(ObjectPvs)
2537                                                                                        //+ sizeof(VspTree)
2538                                                                                        )  / float(1024 * 1024);
2539
2540                subStats.mFullMemory = subStats.mMemoryCost + objectSpaceHierarchyMem + viewSpaceHierarchyMem;
2541               
2542                subStatsContainer.push_back(subStats);
2543               
2544                if (splits == 0)
2545                {
2546                        break;
2547                }
2548                splits -= splitsStepSize;
2549
2550                cout << "splits: " << subStats.mNumSplits << " ";
2551        }
2552
2553        vector<HierarchySubdivisionStats>::const_reverse_iterator hit, hit_end = subStatsContainer.rend();
2554
2555        for (hit = subStatsContainer.rbegin(); hit != hit_end; ++ hit)
2556        {
2557                (*hit).Print(splitsStats);
2558        }
2559
2560        // delete old "base" view cells: only pvss in the leaves are allowed
2561        ViewCellContainer::const_iterator oit, oit_end = mOldViewCells.end();
2562
2563        for (oit = mOldViewCells.begin(); oit != oit_end; ++ oit)
2564        {
2565                if (!(*oit)->IsLeaf())
2566                {
2567                        (*oit)->GetPvs().Clear();
2568                }
2569        }
2570
2571        mOldViewCells.clear();
2572
2573        // reset active nodes
2574        vector<BvhLeaf *> bvhLeaves;
2575
2576        mBvHierarchy->CollectLeaves(mBvHierarchy->GetRoot(), bvhLeaves);
2577
2578        vector<BvhLeaf *>::const_iterator bit, bit_end = bvhLeaves.end();
2579
2580        for (bit = bvhLeaves.begin(); bit != bit_end; ++ bit)
2581        {
2582                (*bit)->SetActiveNode(*bit);
2583        }
2584
2585        cout << endl;
2586}
2587
2588
2589void HierarchyManager::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
2590{
2591        mBvHierarchy->CollectObjects(box, objects);
2592}
2593
2594
2595int HierarchyManager::CompressObjectSpace()
2596{
2597        //mBvHierarchy->Compress();
2598        return mVspTree->CompressObjects();
2599}
2600
2601
2602void HierarchyManager::CreateUniqueObjectIds()
2603{
2604        mBvHierarchy->CreateUniqueObjectIds();
2605}
2606
2607
2608void HierarchyManager::CreateTraversalTree()
2609{
2610        int mind, maxd;
2611        mVspTree->EvalMinMaxDepth(mind, maxd);
2612
2613        cout << "old tree balance: " << mind << " " << maxd << endl;
2614        mTraversalTree = new TraversalTree;
2615
2616        ViewCellContainer viewCells;
2617        mVspTree->CollectViewCells(viewCells, false);
2618
2619        const long startTime = GetTime();
2620       
2621        cout << "building traversal tree ... " << endl;
2622
2623        mTraversalTree->Construct(viewCells);
2624
2625        cout << "finished traversal tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
2626                 << " secs " << endl;
2627
2628        Debug << "*** TraversalTree Stats ***" << endl;
2629        Debug << mTraversalTree->GetStatistics() << endl;
2630
2631        if (1)
2632        {
2633                Exporter *exporter = Exporter::GetExporter("traversal.wrl");
2634                exporter->ExportTraversalTree(*mTraversalTree, true);
2635                delete exporter;
2636        }
2637}
2638
2639
2640int HierarchyManager::CastLineSegment(const Vector3 &origin,
2641                                                                          const Vector3 &termination,
2642                                                                          ViewCellContainer &viewcells,
2643                                                                          const bool useMailboxing)
2644{
2645        if (!mTraversalTree)
2646        {
2647                return mVspTree->CastLineSegment(origin,termination, viewcells, useMailboxing);
2648        }
2649        else
2650        {
2651                return mTraversalTree->CastLineSegment(origin,termination, viewcells, useMailboxing);
2652        }
2653}
2654
2655
2656}
Note: See TracBrowser for help on using the repository browser.