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

Revision 1764, 60.7 KB checked in by mattausch, 18 years ago (diff)

removed error in sample registration

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