source: GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp @ 1696

Revision 1696, 58.6 KB checked in by mattausch, 18 years ago (diff)

removed memory leaks

Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "BvHierarchy.h"
6#include "ViewCell.h"
7#include "Plane3.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 "VspTree.h"
19#include "HierarchyManager.h"
20
21
22namespace GtpVisibilityPreprocessor {
23
24
25#define PROBABILIY_IS_BV_VOLUME 1
26#define USE_FIXEDPOINT_T 0
27#define USE_VOLUMES_FOR_HEURISTICS 1
28
29int BvhNode::sMailId = 10000; //2147483647;
30int BvhNode::sReservedMailboxes = 1;
31
32BvHierarchy *BvHierarchy::BvhSubdivisionCandidate::sBvHierarchy = NULL;
33
34
35/// sorting operator
36inline static bool ilt(Intersectable *obj1, Intersectable *obj2)
37{
38        return obj1->mId < obj2->mId;
39}
40
41
42/***************************************************************/
43/*              class BvhNode implementation                   */
44/***************************************************************/
45
46BvhNode::BvhNode():
47mParent(NULL),
48mMailbox(0),
49mRenderCostDecr(0),
50mMemoryIncr(0),
51mPvsEntriesIncr(0),
52mTimeStamp(0)
53{
54}
55
56BvhNode::BvhNode(const AxisAlignedBox3 &bbox):
57mParent(NULL),
58mBoundingBox(bbox),
59mMailbox(0),
60mMemoryIncr(0),
61mRenderCostDecr(0),
62mPvsEntriesIncr(0),
63mTimeStamp(0)
64{
65}
66
67
68BvhNode::BvhNode(const AxisAlignedBox3 &bbox, BvhInterior *parent):
69mBoundingBox(bbox),
70mParent(parent),
71mMailbox(0),
72mMemoryIncr(0),
73mRenderCostDecr(0),
74mPvsEntriesIncr(0),
75mTimeStamp(0)
76{
77}
78
79
80bool BvhNode::IsRoot() const
81{
82        return mParent == NULL;
83}
84
85
86BvhInterior *BvhNode::GetParent()
87{
88        return mParent;
89}
90
91
92void BvhNode::SetParent(BvhInterior *parent)
93{
94        mParent = parent;
95}
96
97
98
99/******************************************************************/
100/*              class BvhInterior implementation                  */
101/******************************************************************/
102
103
104BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox):
105BvhNode(bbox), mSubdivisionCandidate(NULL)
106{
107}
108
109
110BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox, BvhInterior *parent):
111BvhNode(bbox, parent)
112{
113}
114
115
116BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox,
117                                 BvhInterior *parent,
118                                 const int numObjects):
119BvhNode(bbox, parent)
120{
121        mObjects.reserve(numObjects);
122}
123
124
125bool BvhLeaf::IsLeaf() const
126{
127        return true;
128}
129
130
131BvhLeaf::~BvhLeaf()
132{
133}
134
135
136void BvhLeaf::CollectObjects(ObjectContainer &objects)
137{
138        ObjectContainer::const_iterator oit, oit_end = mObjects.end();
139        for (oit = mObjects.begin(); oit != oit_end; ++ oit)
140        {
141                objects.push_back(*oit);
142        }
143}
144
145/******************************************************************/
146/*              class BvhInterior implementation                  */
147/******************************************************************/
148
149
150BvhInterior::BvhInterior(const AxisAlignedBox3 &bbox):
151BvhNode(bbox), mFront(NULL), mBack(NULL)
152{
153}
154
155
156BvhInterior::BvhInterior(const AxisAlignedBox3 &bbox, BvhInterior *parent):
157BvhNode(bbox, parent), mFront(NULL), mBack(NULL)
158{
159}
160
161
162void BvhInterior::ReplaceChildLink(BvhNode *oldChild, BvhNode *newChild)
163{
164        if (mBack == oldChild)
165                mBack = newChild;
166        else
167                mFront = newChild;
168}
169
170
171bool BvhInterior::IsLeaf() const
172{
173        return false;
174}
175
176
177BvhInterior::~BvhInterior()
178{
179        DEL_PTR(mFront);
180        DEL_PTR(mBack);
181}
182
183
184void BvhInterior::SetupChildLinks(BvhNode *front, BvhNode *back)
185{
186    mBack = back;
187    mFront = front;
188}
189
190
191void BvhInterior::CollectObjects(ObjectContainer &objects)
192{
193        mFront->CollectObjects(objects);
194        mBack->CollectObjects(objects);
195}
196
197
198/*******************************************************************/
199/*                  class BvHierarchy implementation               */
200/*******************************************************************/
201
202
203BvHierarchy::BvHierarchy():
204mRoot(NULL),
205mTimeStamp(1)
206{
207        ReadEnvironment();
208        mSubdivisionCandidates = new SortableEntryContainer;
209        for (int i = 0; i < 3; ++ i)
210                mSortedObjects[i] = NULL;
211}
212
213
214BvHierarchy::~BvHierarchy()
215{
216        // delete bvh intersectables
217        BvhIntersectableMap::iterator it, it_end = mBvhIntersectables.end();
218
219        for (it = mBvhIntersectables.begin(); it != mBvhIntersectables.end(); ++ it)
220        {
221                DEL_PTR((*it).second);
222        }
223
224        // delete the local subdivision candidates
225        DEL_PTR(mSubdivisionCandidates);
226
227        // delete the presorted objects
228        for (int i = 0; i < 3; ++ i)
229        {
230                DEL_PTR(mSortedObjects[i]);
231        }
232       
233        // delete the tree
234        DEL_PTR(mRoot);
235}
236
237
238void BvHierarchy::ReadEnvironment()
239{
240        bool randomize = false;
241        Environment::GetSingleton()->GetBoolValue("VspTree.Construction.randomize", randomize);
242        if (randomize)
243                Randomize(); // initialise random generator for heuristics
244
245
246        ////////////////////////////////////
247        //-- termination criteria for autopartition
248
249        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.maxDepth", mTermMaxDepth);
250        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.maxLeaves", mTermMaxLeaves);
251        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.minObjects", mTermMinObjects);
252        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.minRays", mTermMinRays);
253        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.minProbability", mTermMinProbability);
254       
255        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.missTolerance", mTermMissTolerance);
256
257
258        //////////////////////////////
259        //-- max cost ratio for early tree termination
260
261        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.maxCostRatio", mTermMaxCostRatio);
262        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.minGlobalCostRatio",
263                mTermMinGlobalCostRatio);
264        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.globalCostMissTolerance",
265                mTermGlobalCostMissTolerance);
266
267
268        //////////////////////////////
269        //-- factors for subdivision heuristics
270
271        // if only the driving axis is used for splits
272        Environment::GetSingleton()->GetBoolValue("BvHierarchy.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
273        Environment::GetSingleton()->GetFloatValue("BvHierarchy.maxStaticMemory", mMaxMemory);
274        Environment::GetSingleton()->GetBoolValue("BvHierarchy.useCostHeuristics", mUseCostHeuristics);
275        Environment::GetSingleton()->GetBoolValue("BvHierarchy.useSah", mUseSah);
276
277    char subdivisionStatsLog[100];
278        Environment::GetSingleton()->GetStringValue("BvHierarchy.subdivisionStats", subdivisionStatsLog);
279        mSubdivisionStats.open(subdivisionStatsLog);
280
281        Environment::GetSingleton()->GetFloatValue(
282                "BvHierarchy.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
283       
284        Environment::GetSingleton()->GetBoolValue("BvHierarchy.Construction.useGlobalSorting", mUseGlobalSorting);
285        Environment::GetSingleton()->GetIntValue("BvHierarchy.minRaysForVisibility", mMinRaysForVisibility);
286       
287
288        mUseBboxAreaForSah = true;
289
290        /////////////
291        //-- debug output
292
293        Debug << "******* Bvh hierarchy options ******** " << endl;
294    Debug << "max depth: " << mTermMaxDepth << endl;
295        Debug << "min probabiliy: " << mTermMinProbability<< endl;
296        Debug << "min objects: " << mTermMinObjects << endl;
297        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
298        Debug << "miss tolerance: " << mTermMissTolerance << endl;
299        Debug << "max leaves: " << mTermMaxLeaves << endl;
300        Debug << "randomize: " << randomize << endl;
301        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
302        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
303        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
304        Debug << "max memory: " << mMaxMemory << endl;
305        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
306        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
307        Debug << "split borders: " << mSplitBorder << endl;
308        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
309        Debug << "use global sort: " << mUseGlobalSorting << endl;
310        Debug << "minimal rays for visibility: " << mMinRaysForVisibility << endl;
311
312        Debug << endl;
313}
314
315
316void BvHierarchy::AssociateObjectsWithLeaf(BvhLeaf *leaf)
317{
318        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
319
320        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
321        {
322                (*oit)->mBvhLeaf = leaf;
323        }
324}
325
326
327static int CountRays(const ObjectContainer &objects)
328{
329        int nRays = 0;
330
331        ObjectContainer::const_iterator oit, oit_end = objects.end();
332
333        for (oit = objects.begin(); oit != oit_end; ++ oit)
334        {
335                nRays += (int)(*oit)->GetOrCreateRays()->size();
336        }
337
338        return nRays;
339}
340                                                                       
341
342BvhInterior *BvHierarchy::SubdivideNode(const BvhSubdivisionCandidate &sc,
343                                                                                BvhTraversalData &frontData,
344                                                                                BvhTraversalData &backData)
345{
346        const BvhTraversalData &tData = sc.mParentData;
347        BvhLeaf *leaf = tData.mNode;
348        AxisAlignedBox3 parentBox = leaf->GetBoundingBox();
349
350        // update stats: we have two new leaves
351        mBvhStats.nodes += 2;
352
353        if (tData.mDepth > mBvhStats.maxDepth)
354        {
355                mBvhStats.maxDepth = tData.mDepth;
356        }
357
358        // add the new nodes to the tree
359        BvhInterior *node = new BvhInterior(parentBox, leaf->GetParent());
360       
361
362        //////////////////
363        //-- create front and back leaf
364
365        AxisAlignedBox3 fbox = EvalBoundingBox(sc.mFrontObjects, &parentBox);
366        AxisAlignedBox3 bbox = EvalBoundingBox(sc.mBackObjects, &parentBox);
367
368        BvhLeaf *back = new BvhLeaf(bbox, node, (int)sc.mBackObjects.size());
369        BvhLeaf *front = new BvhLeaf(fbox, node, (int)sc.mFrontObjects.size());
370
371        BvhInterior *parent = leaf->GetParent();
372
373        // replace a link from node's parent
374        if (parent)
375        {
376                parent->ReplaceChildLink(leaf, node);
377                node->SetParent(parent);
378        }
379        else // no parent => this node is the root
380        {
381                mRoot = node;
382        }
383
384        // and setup child links
385        node->SetupChildLinks(front, back);
386
387        ++ mBvhStats.splits;
388
389
390        ////////////////////////////////////////
391        //-- fill  front and back traversal data with the new values
392
393        frontData.mDepth = backData.mDepth = tData.mDepth + 1;
394
395        frontData.mNode = front;
396        backData.mNode = back;
397
398        back->mObjects = sc.mBackObjects;
399        front->mObjects = sc.mFrontObjects;
400
401        // if the number of rays is too low, no assumptions can be made
402        // (=> switch to surface area heuristics?)
403        frontData.mNumRays = CountRays(sc.mFrontObjects);
404        backData.mNumRays = CountRays(sc.mBackObjects);
405
406        AssociateObjectsWithLeaf(back);
407        AssociateObjectsWithLeaf(front);
408   
409#if PROBABILIY_IS_BV_VOLUME
410        // volume of bvh (= probability that this bvh can be seen)
411        frontData.mProbability = fbox.GetVolume();
412        backData.mProbability = bbox.GetVolume();
413#else
414        // compute probability of this node being visible,
415        // i.e., volume of the view cells that can see this node
416        frontData.mProbability = EvalViewCellsVolume(sc.mFrontObjects);
417        backData.mProbability = EvalViewCellsVolume(sc.mBackObjects);
418#endif
419
420    // how often was max cost ratio missed in this branch?
421        frontData.mMaxCostMisses = sc.GetMaxCostMisses();
422        backData.mMaxCostMisses = sc.GetMaxCostMisses();
423       
424        // set the time stamp so the order of traversal can be reconstructed
425        node->mTimeStamp = mHierarchyManager->mTimeStamp ++;
426               
427        // assign the objects in sorted order
428        if (mUseGlobalSorting)
429        {
430                AssignSortedObjects(sc, frontData, backData);
431        }
432       
433        // return the new interior node
434        return node;
435}
436
437
438BvhNode *BvHierarchy::Subdivide(SplitQueue &tQueue,
439                                                                SubdivisionCandidate *splitCandidate,
440                                                                const bool globalCriteriaMet)
441{
442        BvhSubdivisionCandidate *sc = dynamic_cast<BvhSubdivisionCandidate *>(splitCandidate);
443        BvhTraversalData &tData = sc->mParentData;
444
445        BvhNode *currentNode = tData.mNode;
446
447        if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet)
448        {       
449                //////////////
450                //-- continue subdivision
451
452                BvhTraversalData tFrontData;
453                BvhTraversalData tBackData;
454                       
455                // create new interior node and two leaf node
456                currentNode = SubdivideNode(*sc, tFrontData, tBackData);
457       
458                // decrease the weighted average cost of the subdivisoin
459                mTotalCost -= sc->GetRenderCostDecrease();
460                mPvsEntries += sc->GetPvsEntriesIncr();
461
462                // subdivision statistics
463                if (1) PrintSubdivisionStats(*sc);
464
465
466                ///////////////////////////
467                //-- push the new split candidates on the queue
468               
469                BvhSubdivisionCandidate *frontCandidate = new BvhSubdivisionCandidate(tFrontData);
470                BvhSubdivisionCandidate *backCandidate = new BvhSubdivisionCandidate(tBackData);
471
472                EvalSubdivisionCandidate(*frontCandidate);
473                EvalSubdivisionCandidate(*backCandidate);
474       
475                // cross reference
476                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
477                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
478
479                //cout << "f: " << frontCandidate->GetPriority() << " b: " << backCandidate->GetPriority() << endl;
480                tQueue.Push(frontCandidate);
481                tQueue.Push(backCandidate);
482        }
483
484        /////////////////////////////////
485        //-- node is a leaf => terminate traversal
486
487        if (currentNode->IsLeaf())
488        {
489                /////////////////////
490                //-- store additional info
491                EvaluateLeafStats(tData);
492       
493                const bool mStoreRays = true;
494                if (mStoreRays)
495                {
496                        BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(currentNode);
497                        CollectRays(leaf->mObjects, leaf->mVssRays);
498                }
499               
500                //////////////////////////////////////
501               
502                // this leaf is no candidate for splitting anymore
503                // => detach subdivision candidate
504                tData.mNode->SetSubdivisionCandidate(NULL);
505                // detach node so we don't delete it with the traversal data
506                tData.mNode = NULL;
507        }
508       
509        return currentNode;
510}
511
512
513void BvHierarchy::EvalSubdivisionCandidate(BvhSubdivisionCandidate &splitCandidate,
514                                                                                   bool computeSplitPlane)
515{
516        if (computeSplitPlane)
517        {
518                const bool sufficientSamples = splitCandidate.mParentData.mNumRays > mMinRaysForVisibility;
519
520                const bool useVisibiliyBasedHeuristics =
521                        !mUseSah &&
522                        (mHierarchyManager->GetViewSpaceSubdivisionType() == HierarchyManager::KD_BASED_VIEWSPACE_SUBDIV) &&
523                        sufficientSamples;
524
525                // compute best object partition
526                const float ratio =     SelectObjectPartition(splitCandidate.mParentData,
527                                                                                                  splitCandidate.mFrontObjects,
528                                                                                                  splitCandidate.mBackObjects,
529                                                                                                  useVisibiliyBasedHeuristics);
530       
531                // cost ratio violated?
532                const bool maxCostRatioViolated = mTermMaxCostRatio < ratio;
533
534                const int previousMisses = splitCandidate.mParentData.mMaxCostMisses;
535
536                splitCandidate.SetMaxCostMisses(maxCostRatioViolated ? previousMisses + 1 : previousMisses);
537
538        }
539
540        BvhLeaf *leaf = splitCandidate.mParentData.mNode;
541
542        const float oldProp = EvalViewCellsVolume(leaf->mObjects);
543        const float oldRenderCost = EvalRenderCost(leaf->mObjects);
544               
545        // compute global decrease in render cost
546        const float newRenderCost = EvalRenderCost(splitCandidate.mFrontObjects) +
547                                                                EvalRenderCost(splitCandidate.mBackObjects);
548
549        const float renderCostDecr = oldRenderCost - newRenderCost;
550       
551        splitCandidate.SetRenderCostDecrease(renderCostDecr);
552
553        // increase in pvs entries
554        const int pvsEntriesIncr = EvalPvsEntriesIncr(splitCandidate);
555        splitCandidate.SetPvsEntriesIncr(pvsEntriesIncr);
556
557#ifdef _DEBUG
558        Debug << "old render cost: " << oldRenderCost << endl;
559        Debug << "new render cost: " << newRenderCost << endl;
560        Debug << "render cost decrease: " << renderCostDecr << endl;
561#endif
562
563        float priority;
564
565        // surface area heuristics is used when there is no view space subdivision available.
566        // In order to have some prioritized traversal, use this formula instead
567        if (mHierarchyManager->GetViewSpaceSubdivisionType() ==
568                HierarchyManager::NO_VIEWSPACE_SUBDIV)
569        {
570                ////////////////
571                //-- surface area heuristics
572
573                const AxisAlignedBox3 box = EvalBoundingBox(leaf->mObjects);
574                const float area = box.SurfaceArea();
575                const float viewSpaceArea = mViewCellsManager->GetViewSpaceBox().SurfaceArea();
576
577                priority = (float)leaf->mObjects.size() * area / viewSpaceArea;
578        }
579        else
580        {
581                // take render cost of node into account
582                // otherwise danger of being stuck in a local minimum!
583                const float factor = mRenderCostDecreaseWeight;
584                priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
585
586                if (mHierarchyManager->mConsiderMemory2)
587                {
588                        priority /= ((float)splitCandidate.GetPvsEntriesIncr() + mHierarchyManager->mMemoryConst);
589                }
590        }
591
592        // compute global decrease in render cost
593        splitCandidate.SetPriority(priority);
594}
595
596
597int BvHierarchy::EvalPvsEntriesIncr(BvhSubdivisionCandidate &splitCandidate) const
598{
599        const int oldPvsSize = CountViewCells(splitCandidate.mParentData.mNode->mObjects);
600       
601        const int fPvsSize = CountViewCells(splitCandidate.mFrontObjects);
602        const int bPvsSize = CountViewCells(splitCandidate.mBackObjects);
603
604        return fPvsSize + bPvsSize - oldPvsSize;
605}
606
607
608inline bool BvHierarchy::LocalTerminationCriteriaMet(const BvhTraversalData &data) const
609{
610        return ( 0
611                        || ((int)data.mNode->mObjects.size() <= mTermMinObjects)
612                        //|| (data.mProbability <= mTermMinProbability)
613                        || (data.mNumRays <= mTermMinRays)
614                 );
615}
616
617
618inline bool BvHierarchy::GlobalTerminationCriteriaMet(const BvhTraversalData &data) const
619{
620        // note: tracking for global cost termination
621        // does not make much sense for interleaved vsp / osp partition
622        // as it is the responsibility of the hierarchy manager
623
624        const bool terminationCriteriaMet =
625                (0
626                || (mBvhStats.Leaves() >= mTermMaxLeaves)
627                //|| (mBvhStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
628                //|| mOutOfMemory
629                );
630
631#ifdef _DEBUG
632        if (terminationCriteriaMet)
633        {
634                Debug << "bvh global termination criteria met:" << endl;
635                Debug << "cost misses: " << mBvhStats.mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl;
636                Debug << "leaves: " << mBvhStats.Leaves() << " " << mTermMaxLeaves << endl;
637        }
638#endif
639        return terminationCriteriaMet;
640}
641
642
643void BvHierarchy::EvaluateLeafStats(const BvhTraversalData &data)
644{
645        // the node became a leaf -> evaluate stats for leafs
646        BvhLeaf *leaf = data.mNode;
647       
648        ++ mCreatedLeaves;
649
650       
651        if (data.mProbability <= mTermMinProbability)
652        {
653                ++ mBvhStats.minProbabilityNodes;
654        }
655
656        ////////////////////////////////////////////
657        // depth related stuff
658
659        if (data.mDepth < mBvhStats.minDepth)
660        {
661                mBvhStats.minDepth = data.mDepth;
662        }
663
664        if (data.mDepth >= mTermMaxDepth)
665        {
666        ++ mBvhStats.maxDepthNodes;
667        }
668
669        // accumulate depth to compute average depth
670        mBvhStats.accumDepth += data.mDepth;
671
672
673        ////////////////////////////////////////////
674        // objects related stuff
675
676        // note: this number should always accumulate to the total number of objects
677        mBvhStats.objectRefs += (int)leaf->mObjects.size();
678
679        if ((int)leaf->mObjects.size() <= mTermMinObjects)
680        {
681             ++ mBvhStats.minObjectsNodes;
682        }
683
684        if (leaf->mObjects.empty())
685        {
686                ++ mBvhStats.emptyNodes;
687        }
688
689        if ((int)leaf->mObjects.size() > mBvhStats.maxObjectRefs)
690        {
691                mBvhStats.maxObjectRefs = (int)leaf->mObjects.size();
692        }
693
694        if ((int)leaf->mObjects.size() < mBvhStats.minObjectRefs)
695        {
696                mBvhStats.minObjectRefs = (int)leaf->mObjects.size();
697        }
698
699        ////////////////////////////////////////////
700        // ray related stuff
701
702        // note: this number should always accumulate to the total number of rays
703        mBvhStats.rayRefs += data.mNumRays;
704       
705        if (data.mNumRays <= mTermMinRays)
706        {
707             ++ mBvhStats.minRaysNodes;
708        }
709
710        if (data.mNumRays > mBvhStats.maxRayRefs)
711        {
712                mBvhStats.maxRayRefs = data.mNumRays;
713        }
714
715        if (data.mNumRays < mBvhStats.minRayRefs)
716        {
717                mBvhStats.minRayRefs = data.mNumRays;
718        }
719
720#if 0
721        cout << "depth: " << data.mDepth << " objects: " << (int)leaf->mObjects.size()
722                 << " rays: " << data.mNumRays << " rays / objects "
723                 << (float)data.mNumRays / (float)leaf->mObjects.size() << endl;
724#endif
725}
726
727
728#if 0
729
730/// compute object boundaries using spatial mid split
731float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
732                                                                                        const int axis,
733                                                                                        ObjectContainer &objectsFront,
734                                                                                        ObjectContainer &objectsBack)
735{
736        const float maxBox = tData.mBoundingBox.Max(axis);
737        const float minBox = tData.mBoundingBox.Min(axis);
738
739        float midPoint = (maxBox + minBox) * 0.5f;
740
741        ObjectContainer::const_iterator oit, oit_end = tData.mNode->mObjects.end();
742       
743        for (oit = tData.mNode->mObjects.begin(); oit != oit_end; ++ oit)
744        {
745                Intersectable *obj = *oit;
746                const AxisAlignedBox3 box = obj->GetBox();
747
748                const float objMid = (box.Max(axis) + box.Min(axis)) * 0.5f;
749
750                // object mailed => belongs to back objects
751                if (objMid < midPoint)
752                {
753                        objectsBack.push_back(obj);
754                }
755                else
756                {
757                        objectsFront.push_back(obj);
758                }
759        }
760
761        const float oldRenderCost = EvalRenderCost(tData.mNode->mObjects);
762        const float newRenderCost =
763                EvalRenderCost(objectsFront) * EvalRenderCost(objectsBack);
764
765        const float ratio = newRenderCost / oldRenderCost;
766        return ratio;
767}
768
769#else
770
771/// compute object partition by getting balanced objects on the left and right side
772float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
773                                                                                        const int axis,
774                                                                                        ObjectContainer &objectsFront,
775                                                                                        ObjectContainer &objectsBack)
776{
777        PrepareLocalSubdivisionCandidates(tData, axis);
778       
779        SortableEntryContainer::const_iterator cit, cit_end = mSubdivisionCandidates->end();
780
781        int i = 0;
782        const int border = (int)tData.mNode->mObjects.size() / 2;
783
784    for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ i)
785        {
786                Intersectable *obj = (*cit).mObject;
787
788                // object mailed => belongs to back objects
789                if (i < border)
790                {
791                        objectsBack.push_back(obj);
792                }
793                else
794                {
795                        objectsFront.push_back(obj);
796                }
797        }
798
799        const float oldRenderCost = EvalRenderCost(tData.mNode->mObjects);
800        const float newRenderCost = EvalRenderCost(objectsFront) + EvalRenderCost(objectsBack);
801
802        const float ratio = newRenderCost / oldRenderCost;
803        return ratio;
804}
805#endif
806
807
808float BvHierarchy::EvalSah(const BvhTraversalData &tData,
809                                                   const int axis,
810                                                   ObjectContainer &objectsFront,
811                                                   ObjectContainer &objectsBack)
812{
813        // go through the lists, count the number of objects left and right
814        // and evaluate the following cost funcion:
815        // C = ct_div_ci  + (ol + or)/queries
816        PrepareLocalSubdivisionCandidates(tData, axis);
817
818        int objectsLeft = 0, objectsRight = (int)tData.mNode->mObjects.size();
819 
820        const AxisAlignedBox3 nodeBbox = tData.mNode->GetBoundingBox();
821
822        const float minBox = nodeBbox.Min(axis);
823        const float maxBox = nodeBbox.Max(axis);
824        const float boxArea = nodeBbox.SurfaceArea();
825
826        float minSum = 1e20f;
827 
828        float minBorder = maxBox;
829        float maxBorder = minBox;
830        float areaLeft = 0, areaRight = 0;
831
832        SortableEntryContainer::const_iterator currentPos =
833                mSubdivisionCandidates->begin();
834       
835        vector<float> bordersRight;
836
837        if (mUseBboxAreaForSah)
838        {
839                // we keep track of both borders of the bounding boxes =>
840                // store the events in descending order
841
842                bordersRight.resize(mSubdivisionCandidates->size());
843
844                SortableEntryContainer::reverse_iterator rcit =
845                        mSubdivisionCandidates->rbegin(), rcit_end = mSubdivisionCandidates->rend();
846       
847                vector<float>::reverse_iterator rbit = bordersRight.rbegin();
848       
849                for (; rcit != rcit_end; ++ rcit, ++ rbit)
850                {
851                        Intersectable *obj = (*rcit).mObject;
852                        const AxisAlignedBox3 obox = obj->GetBox();
853
854                        if (obox.Min(axis) < minBorder)
855                        {
856                                minBorder = obox.Min(axis);
857                        }
858
859                        (*rbit) = minBorder;
860                }
861        }
862
863        // temporary surface areas
864        float al = 0;
865        float ar = boxArea;
866
867        vector<float>::const_iterator bit = bordersRight.begin();
868        SortableEntryContainer::const_iterator cit, cit_end = mSubdivisionCandidates->end();
869
870        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ bit)
871        {
872                Intersectable *obj = (*cit).mObject;
873
874                ++ objectsLeft;
875                -- objectsRight;
876
877                const AxisAlignedBox3 obox = obj->GetBox();
878
879                if (mUseBboxAreaForSah)
880                {
881                        AxisAlignedBox3 lbox = nodeBbox;
882                        AxisAlignedBox3 rbox = nodeBbox;
883       
884                        // the borders of the bounding boxes have changed
885                        if (obox.Max(axis) > maxBorder)
886                        {
887                                maxBorder = obox.Max(axis);
888                        }
889
890                        minBorder = (*bit);
891
892                        lbox.SetMax(axis, maxBorder);
893                        rbox.SetMin(axis, minBorder);
894       
895                        al = lbox.SurfaceArea();
896                        ar = rbox.SurfaceArea();
897                }
898                else
899                {
900                        // just add up areas of the objects itself
901                        // (as we are not sampling volumetric visibility,
902                        // this should provide better heuristics
903                        const float area = obj->GetArea();//obox.SurfaceArea();
904
905                        al += area;
906                        ar -= area;
907                }
908
909                const float sum = objectsLeft * al + objectsRight * ar;
910     
911                /*cout << "pos=" << (*cit).mPos << "\t q=(" << objectsLeft << "," << objectsRight <<")\t r=("
912                         << lbox.SurfaceArea() << "," << rbox.SurfaceArea() << ")" << endl;
913                cout << "minborder: " << minBorder << " maxborder: " << maxBorder << endl;
914            cout << "cost= " << sum << endl;
915*/
916                if (sum < minSum)
917                {
918                        minSum = sum;
919                        areaLeft = al;
920                        areaRight = ar;
921                        // objects belong to left side now
922                        for (; currentPos != (cit + 1); ++ currentPos);
923                }
924        }
925
926
927        ////////////////////////////////////////////
928        //-- assign object to front and back volume
929
930        // belongs to back bv
931        for (cit = mSubdivisionCandidates->begin(); cit != currentPos; ++ cit)
932                objectsBack.push_back((*cit).mObject);
933       
934        // belongs to front bv
935        for (cit = currentPos; cit != cit_end; ++ cit)
936                objectsFront.push_back((*cit).mObject);
937
938        float oldCost = (float)tData.mNode->mObjects.size();
939        float newCost = minSum / boxArea;
940        float ratio = newCost / oldCost;
941 
942#ifdef _DEBUG
943        cout << "\n\nobjects=(" << (int)objectsBack.size() << "," << (int)objectsFront.size() << " of "
944                 << (int)tData.mNode->mObjects.size() << ")\t area=("
945                 << areaLeft << "," << areaRight << ")" << endl
946                 << "cost= " << minSum << endl;
947#endif
948
949  return ratio;
950}
951
952
953static bool PrepareOutput(const int axis,
954                                                  const int leaves,
955                                                  ofstream &sumStats,
956                                                  ofstream &vollStats,
957                                                  ofstream &volrStats)
958{
959        if ((axis == 0) && (leaves > 0) && (leaves < 90))
960        {
961                char str[64];   
962                sprintf(str, "tmp/bvh_heur_sum-%04d.log", leaves);
963                sumStats.open(str);
964                sprintf(str, "tmp/bvh_heur_voll-%04d.log", leaves);
965                vollStats.open(str);
966                sprintf(str, "tmp/bvh_heur_volr-%04d.log", leaves);
967                volrStats.open(str);
968        }
969
970        return sumStats.is_open() && vollStats.is_open() && volrStats.is_open();
971}
972
973
974static void PrintHeuristics(const int objectsRight,
975                                                        const float sum,
976                                                        const float volLeft,
977                                                        const float volRight,
978                                                        const float viewSpaceVol,
979                                                        ofstream &sumStats,
980                                                        ofstream &vollStats,
981                                                        ofstream &volrStats)
982{
983        sumStats
984                << "#Position\n" << objectsRight << endl
985                << "#Sum\n" << sum / viewSpaceVol << endl
986                << "#Vol\n" << (volLeft +  volRight) / viewSpaceVol << endl;
987
988        vollStats
989                << "#Position\n" << objectsRight << endl
990                << "#Vol\n" << volLeft / viewSpaceVol << endl;
991
992        volrStats
993                << "#Position\n" << objectsRight << endl
994                << "#Vol\n" << volRight / viewSpaceVol << endl;
995}
996
997
998float BvHierarchy::EvalLocalCostHeuristics(const BvhTraversalData &tData,
999                                                                                   const int axis,
1000                                                                                   ObjectContainer &objectsFront,
1001                                                                                   ObjectContainer &objectsBack)
1002{
1003        ////////////////////////////////////////////////////////////////
1004        // go through the lists, count the number of objects left and right
1005        // and evaluate the cost funcion
1006
1007        // prepare the heuristics by setting mailboxes and counters.
1008        const float totalVol = PrepareHeuristics(tData, axis);
1009       
1010        // local helper variables
1011        float volLeft = 0;
1012        float volRight = totalVol;
1013        int nObjectsLeft = 0;
1014        const int nTotalObjects = (int)tData.mNode->mObjects.size();
1015        const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
1016
1017        SortableEntryContainer::const_iterator backObjectsStart =
1018                mSubdivisionCandidates->begin();
1019
1020        /////////////////////////////////
1021        //-- the parameters for the current optimum
1022
1023        float volBack = volLeft;
1024        float volFront = volRight;
1025        float newRenderCost = nTotalObjects * totalVol;
1026
1027#ifdef _DEBUG
1028        ofstream sumStats;
1029        ofstream vollStats;
1030        ofstream volrStats;
1031
1032        const bool printStats =
1033                PrepareOutput(axis, mBvhStats.Leaves(), sumStats, vollStats, volrStats);
1034#endif
1035
1036        ///////////////////////////////////////////////////
1037        //-- the sweep heuristics
1038        //-- traverse through events and find best split plane
1039
1040        SortableEntryContainer::const_iterator cit, cit_end = cit_end = mSubdivisionCandidates->end();
1041
1042        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit)
1043        {
1044                Intersectable *object = (*cit).mObject;
1045       
1046                // evaluate change in l and r volume
1047                // voll = view cells that see only left node (i.e., left pvs)
1048                // volr = view cells that see only right node (i.e., right pvs)
1049                EvalHeuristicsContribution(object, volLeft, volRight);
1050
1051                ++ nObjectsLeft;
1052                const int nObjectsRight = nTotalObjects - nObjectsLeft;
1053
1054                // the heuristics
1055            const float sum = volLeft * (float)nObjectsLeft +
1056                                                  volRight * (float)nObjectsRight;
1057
1058#ifdef _DEBUG
1059                if (printStats)
1060                {
1061                        PrintHeuristics(nObjectsRight, sum, volLeft, volRight, viewSpaceVol,
1062                                                        sumStats, vollStats, volrStats);
1063                }
1064#endif
1065
1066                if (sum < newRenderCost)
1067                {
1068                        newRenderCost = sum;
1069
1070                        volBack = volLeft;
1071                        volFront = volRight;
1072
1073                        // objects belongs to left side now
1074                        for (; backObjectsStart != (cit + 1); ++ backObjectsStart);
1075                }
1076        }
1077
1078        ////////////////////////////////////////////
1079        //-- assign object to front and back volume
1080
1081        // belongs to back bv
1082        for (cit = mSubdivisionCandidates->begin(); cit != backObjectsStart; ++ cit)
1083        {
1084                objectsBack.push_back((*cit).mObject);
1085        }
1086        // belongs to front bv
1087        for (cit = backObjectsStart; cit != cit_end; ++ cit)
1088        {
1089                objectsFront.push_back((*cit).mObject);
1090        }
1091
1092        // render cost of the old parent
1093        const float oldRenderCost = (float)nTotalObjects * totalVol + Limits::Small;
1094        // the relative cost ratio
1095        const float ratio = newRenderCost / oldRenderCost;
1096
1097#ifdef _DEBUG
1098        Debug << "\n§§§§ bvh eval const decrease §§§§" << endl
1099                  << "back pvs: " << (int)objectsBack.size() << " front pvs: " << (int)objectsFront.size() << " total pvs: " << nTotalObjects << endl
1100                  << "back p: " << volBack / viewSpaceVol << " front p " << volFront / viewSpaceVol << " p: " << totalVol / viewSpaceVol << endl
1101                  << "old rc: " << oldRenderCost / viewSpaceVol << " new rc: " << newRenderCost / viewSpaceVol << endl
1102                  << "render cost decrease: " << oldRenderCost / viewSpaceVol - newRenderCost / viewSpaceVol << endl;
1103#endif
1104
1105        return ratio;
1106}
1107
1108
1109void BvHierarchy::PrepareLocalSubdivisionCandidates(const BvhTraversalData &tData,
1110                                                                                                        const int axis)                                                                                 
1111{
1112        //-- insert object queries
1113        ObjectContainer *objects = mUseGlobalSorting ?
1114                tData.mSortedObjects[axis] : &tData.mNode->mObjects;
1115
1116        CreateLocalSubdivisionCandidates(*objects, &mSubdivisionCandidates, !mUseGlobalSorting, axis);
1117}
1118
1119
1120void BvHierarchy::CreateLocalSubdivisionCandidates(const ObjectContainer &objects,
1121                                                                                                  SortableEntryContainer **subdivisionCandidates,
1122                                                                                                  const bool sort,
1123                                                                                                  const int axis)
1124{
1125        (*subdivisionCandidates)->clear();
1126
1127        // compute requested size and look if subdivision candidate has to be recomputed
1128        const int requestedSize = (int)objects.size() * 2;
1129       
1130        // creates a sorted split candidates array
1131        if ((*subdivisionCandidates)->capacity() > 500000 &&
1132                requestedSize < (int)((*subdivisionCandidates)->capacity() / 10) )
1133        {
1134        delete (*subdivisionCandidates);
1135                (*subdivisionCandidates) = new SortableEntryContainer;
1136        }
1137
1138        (*subdivisionCandidates)->reserve(requestedSize);
1139
1140        ObjectContainer::const_iterator oit, oit_end = objects.end();
1141
1142        for (oit = objects.begin(); oit < oit_end; ++ oit)
1143        {
1144                Intersectable *object = *oit;
1145                const AxisAlignedBox3 &box = object->GetBox();
1146                const float midPt = (box.Min(axis) + box.Max(axis)) * 0.5f;
1147
1148                (*subdivisionCandidates)->push_back(SortableEntry(object, midPt));
1149        }
1150
1151        if (sort)
1152        {       // no presorted candidate list
1153                stable_sort((*subdivisionCandidates)->begin(), (*subdivisionCandidates)->end());
1154        }
1155}
1156
1157
1158const BvhStatistics &BvHierarchy::GetStatistics() const
1159{
1160        return mBvhStats;
1161}
1162
1163
1164float BvHierarchy::PrepareHeuristics(const BvhTraversalData &tData, const int axis)
1165{       
1166        BvhLeaf *leaf = tData.mNode;
1167        float vol = 0;
1168
1169    // sort so we can use a sweep from right to left
1170        PrepareLocalSubdivisionCandidates(tData, axis);
1171       
1172        // collect and mark the view cells as belonging to front pvs
1173        ViewCellContainer viewCells;
1174        CollectViewCells(tData.mNode->mObjects, viewCells, true);
1175                       
1176        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1177        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1178        {
1179#if USE_VOLUMES_FOR_HEURISTICS
1180                const float volIncr = (*vit)->GetVolume();
1181#else
1182                const float volIncr = 1.0f;
1183#endif
1184                vol += volIncr;
1185        }
1186
1187        // we will mail view cells switching to the back side
1188        ViewCell::NewMail();
1189       
1190        return vol;
1191}
1192
1193///////////////////////////////////////////////////////////
1194
1195
1196void BvHierarchy::EvalHeuristicsContribution(Intersectable *obj,
1197                                                                                         float &volLeft,
1198                                                                                         float &volRight)
1199{
1200        // collect all view cells associated with this objects
1201        // (also multiple times, if they are pierced by several rays)
1202        ViewCellContainer viewCells;
1203        const bool useMailboxing = false;
1204
1205        CollectViewCells(obj, viewCells, useMailboxing);
1206
1207        // classify view cells and compute volume contri accordingly
1208        // possible view cell classifications:
1209        // view cell mailed => view cell can be seen from left child node
1210        // view cell counter > 0 view cell can be seen from right child node
1211        // combined: view cell volume belongs to both nodes
1212        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1213       
1214        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1215        {
1216                // view cells can also be seen from left child node
1217                ViewCell *viewCell = *vit;
1218#if USE_VOLUMES_FOR_HEURISTICS
1219                const float vol = viewCell->GetVolume();
1220#else
1221                const float vol = 1.0f;
1222#endif
1223                if (!viewCell->Mailed())
1224                {
1225                        viewCell->Mail();
1226                        // we now see view cell from both nodes
1227                        // => add volume to left node
1228                        volLeft += vol;
1229                }
1230
1231                // last reference into the right node
1232                if (-- viewCell->mCounter == 0)
1233                {       
1234                        // view cell was previously seen from both nodes  =>
1235                        // remove volume from right node
1236                        volRight -= vol;
1237                }
1238        }
1239}
1240
1241
1242void BvHierarchy::SetViewCellsManager(ViewCellsManager *vcm)
1243{
1244        mViewCellsManager = vcm;
1245}
1246
1247
1248AxisAlignedBox3 BvHierarchy::GetBoundingBox() const
1249{
1250        return mBoundingBox;
1251}
1252
1253
1254float BvHierarchy::SelectObjectPartition(const BvhTraversalData &tData,
1255                                                                                 ObjectContainer &frontObjects,
1256                                                                                 ObjectContainer &backObjects,
1257                                                                                 bool useVisibilityBasedHeuristics)
1258{
1259        ObjectContainer nFrontObjects[3];
1260        ObjectContainer nBackObjects[3];
1261        float nCostRatio[3];
1262
1263        int sAxis = 0;
1264        int bestAxis = -1;
1265
1266        if (mOnlyDrivingAxis)
1267        {
1268                const AxisAlignedBox3 box = tData.mNode->GetBoundingBox();
1269                sAxis = box.Size().DrivingAxis();
1270        }
1271       
1272        ////////////////////////////////////
1273        //-- evaluate split cost for all three axis
1274       
1275        for (int axis = 0; axis < 3; ++ axis)
1276        {
1277                if (!mOnlyDrivingAxis || (axis == sAxis))
1278                {
1279                        if (mUseCostHeuristics)
1280                        {
1281                                //////////////////////////////////
1282                //-- split objects using heuristics
1283                               
1284                                if (useVisibilityBasedHeuristics)
1285                                {
1286                                        //cout << "v rays: " << tData.mNumRays << " " << endl;
1287                                        ///////////
1288                                        //-- heuristics using objects weighted by view cells volume
1289                                        nCostRatio[axis] =
1290                                                EvalLocalCostHeuristics(tData, axis, nFrontObjects[axis], nBackObjects[axis]);
1291                                }
1292                                else
1293                                {       //cout << "e rays: " << tData.mNumRays << " ";
1294                                        //////////////////
1295                                        //-- view cells not constructed yet     => use surface area heuristic                   
1296                                        nCostRatio[axis] =
1297                                                EvalSah(tData, axis, nFrontObjects[axis], nBackObjects[axis]);
1298                                }
1299                        }
1300                        else
1301                        {
1302                                //-- split objects using some simple criteria
1303                                nCostRatio[axis] =
1304                                        EvalLocalObjectPartition(tData, axis, nFrontObjects[axis], nBackObjects[axis]);
1305                        }
1306
1307                        if (bestAxis == -1)
1308                        {
1309                                bestAxis = axis;
1310                        }
1311                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
1312                        {
1313                                bestAxis = axis;
1314                        }
1315                }
1316        }
1317
1318    ////////////////
1319        //-- assign values
1320
1321        frontObjects = nFrontObjects[bestAxis];
1322        backObjects = nBackObjects[bestAxis];
1323
1324        //Debug << "val: " << nCostRatio[bestAxis] << " axis: " << bestAxis << endl;
1325        return nCostRatio[bestAxis];
1326}
1327
1328
1329int BvHierarchy::AssociateObjectsWithRays(const VssRayContainer &rays) const
1330{
1331        int nRays = 0;
1332        VssRayContainer::const_iterator rit, rit_end = rays.end();
1333
1334        VssRay::NewMail();
1335
1336    for (rit = rays.begin(); rit != rays.end(); ++ rit)
1337        {
1338                VssRay *ray = (*rit);
1339
1340                if (ray->mTerminationObject)
1341                {
1342                        ray->mTerminationObject->GetOrCreateRays()->push_back(ray);
1343                        if (!ray->Mailed())
1344                        {
1345                                ray->Mail();
1346                                ++ nRays;
1347                        }
1348                }
1349#if COUNT_ORIGIN_OBJECTS
1350                if (ray->mOriginObject)
1351                {
1352                        ray->mOriginObject->GetOrCreateRays()->push_back(ray);
1353
1354                        if (!ray->Mailed())
1355                        {
1356                                ray->Mail();
1357                                ++ nRays;
1358                        }
1359                }
1360#endif
1361        }
1362
1363        return nRays;
1364}
1365
1366
1367void BvHierarchy::PrintSubdivisionStats(const SubdivisionCandidate &sc)
1368{
1369        const float costDecr =
1370                sc.GetRenderCostDecrease();// / mHierarchyManager->GetViewSpaceBox().GetVolume();       
1371
1372        mSubdivisionStats
1373                        << "#Leaves\n" << mBvhStats.Leaves() << endl
1374                        << "#RenderCostDecrease\n" << costDecr << endl
1375                        << "#TotalRenderCost\n" << mTotalCost << endl
1376                        << "#EntriesInPvs\n" << mPvsEntries << endl;
1377}
1378
1379
1380void BvHierarchy::CollectRays(const ObjectContainer &objects,
1381                                                          VssRayContainer &rays) const
1382{
1383        VssRay::NewMail();
1384        ObjectContainer::const_iterator oit, oit_end = objects.end();
1385
1386        // evaluate reverse pvs and view cell volume on left and right cell
1387        // note: should I take all leaf objects or rather the objects hit by rays?
1388        for (oit = objects.begin(); oit != oit_end; ++ oit)
1389        {
1390                Intersectable *obj = *oit;
1391                VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
1392
1393                for (rit = obj->GetOrCreateRays()->begin(); rit < rit_end; ++ rit)
1394                {
1395                        VssRay *ray = (*rit);
1396
1397                        if (!ray->Mailed())
1398                        {
1399                                ray->Mail();
1400                                rays.push_back(ray);
1401                        }
1402                }
1403        }
1404}
1405
1406
1407float BvHierarchy::EvalRenderCost(const ObjectContainer &objects) const
1408{       
1409        if (0 &&
1410                (mHierarchyManager->GetViewSpaceSubdivisionType() ==
1411                HierarchyManager::NO_VIEWSPACE_SUBDIV))
1412        {
1413                ////////////////
1414                //-- surface area heuristics
1415
1416                if (objects.empty())
1417                        return 0.0f;
1418
1419                const AxisAlignedBox3 box = EvalBoundingBox(objects);
1420                const float area = box.SurfaceArea();
1421                const float viewSpaceArea = mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1422
1423                return (float)objects.size() * area / viewSpaceArea;
1424        }
1425        else
1426        {       ///////////////
1427                //-- render cost heuristics
1428
1429                const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
1430
1431                // probability that view point lies in a view cell which sees this node
1432                const float p = EvalViewCellsVolume(objects) / viewSpaceVol;   
1433
1434                return (float)objects.size() * p;
1435        }
1436}
1437
1438
1439AxisAlignedBox3 BvHierarchy::EvalBoundingBox(const ObjectContainer &objects,
1440                                                                                         const AxisAlignedBox3 *parentBox) const
1441{
1442        // if there are no objects in this box, box size is set to parent box size.
1443        // Question: Invalidate box instead?
1444        if (parentBox && objects.empty())
1445                return *parentBox;
1446
1447        AxisAlignedBox3 box;
1448        box.Initialize();
1449
1450        ObjectContainer::const_iterator oit, oit_end = objects.end();
1451
1452        for (oit = objects.begin(); oit != oit_end; ++ oit)
1453        {
1454                Intersectable *obj = *oit;
1455                // grow bounding box to include all objects
1456                box.Include(obj->GetBox());
1457        }
1458
1459        return box;
1460}
1461
1462
1463void BvHierarchy::CollectLeaves(vector<BvhLeaf *> &leaves) const
1464{
1465        stack<BvhNode *> nodeStack;
1466        nodeStack.push(mRoot);
1467
1468        while (!nodeStack.empty())
1469        {
1470                BvhNode *node = nodeStack.top();
1471                nodeStack.pop();
1472
1473                if (node->IsLeaf())
1474                {
1475                        BvhLeaf *leaf = (BvhLeaf *)node;
1476                        leaves.push_back(leaf);
1477                }
1478                else
1479                {
1480                        BvhInterior *interior = (BvhInterior *)node;
1481
1482                        nodeStack.push(interior->GetBack());
1483                        nodeStack.push(interior->GetFront());
1484                }
1485        }
1486}
1487
1488
1489AxisAlignedBox3 BvHierarchy::GetBoundingBox(BvhNode *node) const
1490{
1491        return node->GetBoundingBox();
1492}
1493
1494
1495void BvHierarchy::CollectViewCells(const ObjectContainer &objects,
1496                                                                   ViewCellContainer &viewCells,
1497                                                                   const bool setCounter) const
1498{
1499        // no view cells yet
1500        if (0 && mHierarchyManager->GetViewSpaceSubdivisionType() ==
1501                HierarchyManager::NO_VIEWSPACE_SUBDIV)
1502                return;
1503
1504        ViewCell::NewMail();
1505        ObjectContainer::const_iterator oit, oit_end = objects.end();
1506
1507        // loop through all object and collect view cell pvs of this node
1508        for (oit = objects.begin(); oit != oit_end; ++ oit)
1509        {
1510                CollectViewCells(*oit, viewCells, true, setCounter);
1511        }
1512}
1513
1514
1515void BvHierarchy::CollectViewCells(Intersectable *obj,
1516                                                                   ViewCellContainer &viewCells,
1517                                                                   const bool useMailBoxing,
1518                                                                   const bool setCounter) const
1519{
1520        VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
1521
1522        for (rit = obj->GetOrCreateRays()->begin(); rit < rit_end; ++ rit)
1523        {
1524                VssRay *ray = (*rit);
1525                ViewCellContainer tmpViewCells;
1526       
1527                mHierarchyManager->mVspTree->GetViewCells(*ray, tmpViewCells);
1528
1529                // matt: probably slow to allocate memory for view cells every time
1530                ViewCellContainer::const_iterator vit, vit_end = tmpViewCells.end();
1531
1532                for (vit = tmpViewCells.begin(); vit != vit_end; ++ vit)
1533                {
1534                        ViewCell *vc = *vit;
1535
1536                        // store view cells
1537                        if (!useMailBoxing || !vc->Mailed())
1538                        {
1539                                if (useMailBoxing)
1540                                {
1541                                        vc->Mail();
1542                                        if (setCounter)
1543                                        {
1544                                                vc->mCounter = 0;
1545                                        }
1546                                }
1547                                viewCells.push_back(vc);
1548                        }
1549                       
1550                        if (setCounter)
1551                        {
1552                                ++ vc->mCounter;
1553                        }
1554                }
1555        }
1556}
1557
1558
1559int BvHierarchy::CountViewCells(Intersectable *obj) const
1560{
1561        int result = 0;
1562       
1563        VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
1564
1565        for (rit = obj->GetOrCreateRays()->begin(); rit < rit_end; ++ rit)
1566        {
1567                VssRay *ray = (*rit);
1568                ViewCellContainer tmpViewCells;
1569       
1570                mHierarchyManager->mVspTree->GetViewCells(*ray, tmpViewCells);
1571               
1572                ViewCellContainer::const_iterator vit, vit_end = tmpViewCells.end();
1573                for (vit = tmpViewCells.begin(); vit != vit_end; ++ vit)
1574                {
1575                        ViewCell *vc = *vit;
1576
1577                        // store view cells
1578                        if (!vc->Mailed())
1579                        {
1580                                vc->Mail();
1581                                ++ result;
1582                        }
1583                }
1584        }
1585
1586        return result;
1587}
1588
1589
1590int BvHierarchy::CountViewCells(const ObjectContainer &objects) const
1591{
1592        // no view cells yet
1593        if (0 && mHierarchyManager->GetViewSpaceSubdivisionType() ==
1594                HierarchyManager::NO_VIEWSPACE_SUBDIV)
1595                return 1;
1596
1597        int nViewCells = 0;
1598
1599        ViewCell::NewMail();
1600
1601        ObjectContainer::const_iterator oit, oit_end = objects.end();
1602
1603        // loop through all object and collect view cell pvs of this node
1604        for (oit = objects.begin(); oit != oit_end; ++ oit)
1605        {
1606                nViewCells += CountViewCells(*oit);
1607        }
1608
1609        return nViewCells;
1610}
1611
1612
1613void BvHierarchy::CollectDirtyCandidates(BvhSubdivisionCandidate *sc,
1614                                                                                 vector<SubdivisionCandidate *> &dirtyList,
1615                                                                                 const bool onlyUnmailed)
1616{
1617        BvhTraversalData &tData = sc->mParentData;
1618        BvhLeaf *node = tData.mNode;
1619       
1620        ViewCellContainer viewCells;
1621        ViewCell::NewMail();
1622        CollectViewCells(node->mObjects, viewCells, true);
1623
1624        if (0) cout << "collected " << (int)viewCells.size() << " dirty candidates" << endl;
1625       
1626        // split candidates handling
1627        // these view cells  are thrown into dirty list
1628        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1629
1630        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1631        {
1632        VspViewCell *vc = dynamic_cast<VspViewCell *>(*vit);
1633                VspLeaf *leaf = vc->mLeaves[0];
1634       
1635                SubdivisionCandidate *candidate = leaf->GetSubdivisionCandidate();
1636               
1637                // is this leaf still a split candidate?
1638                if (candidate && (!onlyUnmailed || !candidate->Mailed()))
1639                {
1640                        candidate->Mail();
1641                        dirtyList.push_back(candidate);
1642                }
1643        }
1644}
1645
1646
1647BvhNode *BvHierarchy::GetRoot() const
1648{
1649        return mRoot;
1650}
1651
1652
1653bool BvHierarchy::IsObjectInLeaf(BvhLeaf *leaf, Intersectable *object) const
1654{
1655        ObjectContainer::const_iterator oit =
1656                lower_bound(leaf->mObjects.begin(), leaf->mObjects.end(), object, ilt);
1657                               
1658        // objects sorted by id
1659        if ((oit != leaf->mObjects.end()) && ((*oit)->GetId() == object->GetId()))
1660        {
1661                return true;
1662        }
1663        else
1664        {
1665                return false;
1666        }
1667}
1668
1669
1670BvhLeaf *BvHierarchy::GetLeaf(Intersectable *object, BvhNode *node) const
1671{
1672        // rather use the simple version
1673        if (!object)
1674                return NULL;
1675       
1676        return object->mBvhLeaf;
1677       
1678        ///////////////////////////////////////
1679        // start from root of tree
1680       
1681        if (node == NULL)
1682                node = mRoot;
1683       
1684        vector<BvhLeaf *> leaves;
1685
1686        stack<BvhNode *> nodeStack;
1687        nodeStack.push(node);
1688 
1689        BvhLeaf *leaf = NULL;
1690 
1691        while (!nodeStack.empty()) 
1692        {
1693                BvhNode *node = nodeStack.top();
1694                nodeStack.pop();
1695       
1696                if (node->IsLeaf())
1697                {
1698                        leaf = dynamic_cast<BvhLeaf *>(node);
1699
1700                        if (IsObjectInLeaf(leaf, object))
1701                        {
1702                                return leaf;
1703                        }
1704                }
1705                else   
1706                {       
1707                        // find point
1708                        BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1709       
1710                        if (interior->GetBack()->GetBoundingBox().Includes(object->GetBox()))
1711                        {
1712                                nodeStack.push(interior->GetBack());
1713                        }
1714                       
1715                        // search both sides as we are using bounding volumes
1716                        if (interior->GetFront()->GetBoundingBox().Includes(object->GetBox()))
1717                        {
1718                                nodeStack.push(interior->GetFront());
1719                        }
1720                }
1721        }
1722 
1723        return leaf;
1724}
1725
1726
1727BvhIntersectable *BvHierarchy::GetOrCreateBvhIntersectable(BvhNode *node)
1728{
1729        // search nodes
1730        std::map<BvhNode *, BvhIntersectable *>::const_iterator it
1731                = mBvhIntersectables.find(node);
1732
1733        if (it != mBvhIntersectables.end())
1734        {
1735                return (*it).second;
1736        }
1737
1738        // not in map => create new entry
1739        BvhIntersectable *bvhObj = new BvhIntersectable(node);
1740        mBvhIntersectables[node] = bvhObj;
1741
1742        return bvhObj;
1743}
1744
1745
1746bool BvHierarchy::Export(OUT_STREAM &stream)
1747{
1748        ExportNode(mRoot, stream);
1749
1750        return true;
1751}
1752
1753
1754void BvHierarchy::ExportObjects(BvhLeaf *leaf, OUT_STREAM &stream)
1755{
1756        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
1757        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
1758        {
1759                stream << (*oit)->GetId() << " ";
1760        }
1761}
1762
1763
1764void BvHierarchy::ExportNode(BvhNode *node, OUT_STREAM &stream)
1765{
1766        if (node->IsLeaf())
1767        {
1768                BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(node);
1769                const AxisAlignedBox3 box = leaf->GetBoundingBox();
1770                stream << "<Leaf"
1771                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1772                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\""
1773                           << " objects=\"";
1774               
1775                //-- export objects
1776                ExportObjects(leaf, stream);
1777               
1778                stream << "\" />" << endl;
1779        }
1780        else
1781        {       
1782                BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1783                const AxisAlignedBox3 box = interior->GetBoundingBox();
1784
1785                stream << "<Interior"
1786                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1787                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z
1788                           << "\">" << endl;
1789
1790                ExportNode(interior->GetBack(), stream);
1791                ExportNode(interior->GetFront(), stream);
1792
1793                stream << "</Interior>" << endl;
1794        }
1795}
1796
1797
1798float BvHierarchy::EvalViewCellsVolume(const ObjectContainer &objects) const
1799{
1800        float vol = 0;
1801
1802        ViewCellContainer viewCells;
1803        CollectViewCells(objects, viewCells);
1804
1805        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1806
1807        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1808        {
1809                vol += (*vit)->GetVolume();
1810        }
1811
1812        return vol;
1813}
1814
1815
1816void BvHierarchy::Initialise(const ObjectContainer &objects)
1817{
1818        ///////
1819        //-- create new root
1820
1821        AxisAlignedBox3 box = EvalBoundingBox(objects);
1822        BvhLeaf *bvhleaf = new BvhLeaf(box, NULL, (int)objects.size());
1823        bvhleaf->mObjects = objects;
1824        mRoot = bvhleaf;
1825
1826        // compute bounding box from objects
1827        mBoundingBox = mRoot->GetBoundingBox();
1828
1829        // associate root with current objects
1830        AssociateObjectsWithLeaf(bvhleaf);
1831}
1832
1833
1834/*
1835Mesh *BvHierarchy::MergeLeafToMesh()
1836void BvHierarchy::MergeLeavesToMeshes()
1837{
1838        vector<BvhLeaf *> leaves;
1839        CollectLeaves(leaves);
1840
1841        vector<BvhLeaf *>::const_iterator lit, lit_end = leaves.end();
1842
1843        for (lit = leaves.begin(); lit != lit_end; ++ lit)
1844        {
1845                Mesh *mesh = MergeLeafToMesh(*lit);
1846        }
1847}*/
1848
1849
1850SubdivisionCandidate *BvHierarchy::PrepareConstruction(const VssRayContainer &sampleRays,
1851                                                                                                           const ObjectContainer &objects)
1852{
1853        ///////////////////////////////////////
1854        //-- we assume that we have objects sorted by their id =>
1855        //-- we don't have to sort them here and an binary search
1856        //-- for identifying if a object is in a leaf.
1857       
1858        mBvhStats.Reset();
1859        mBvhStats.Start();
1860        mBvhStats.nodes = 1;
1861               
1862        // store pointer to this tree
1863        BvhSubdivisionCandidate::sBvHierarchy = this;
1864       
1865        // root and bounding box was already constructed
1866        BvhLeaf *bvhLeaf = dynamic_cast<BvhLeaf *>(mRoot);
1867
1868        // multiply termination criterium for comparison,
1869        // so it can be set between zero and one and
1870        // no division is necessary during traversal
1871
1872#if PROBABILIY_IS_BV_VOLUME
1873        mTermMinProbability *= mBoundingBox.GetVolume();
1874        // probability that bounding volume is seen
1875        const float prop = GetBoundingBox().GetVolume();
1876#else
1877        mTermMinProbability *= mVspTree->GetBoundingBox().GetVolume();
1878        // probability that volume is "seen" from the view cells
1879        const float prop = EvalViewCellsVolume(objects);
1880#endif
1881
1882        // only rays intersecting objects in node are interesting
1883        const int nRays = AssociateObjectsWithRays(sampleRays);
1884        //Debug << "using " << nRays << " of " << (int)sampleRays.size() << " rays" << endl;
1885
1886        // create bvh traversal data
1887        BvhTraversalData oData(bvhLeaf, 0, prop, nRays);
1888
1889        // create sorted object lists for the first data
1890        if (mUseGlobalSorting)
1891        {
1892                AssignInitialSortedObjectList(oData);
1893        }
1894       
1895
1896        ///////////////////
1897        //-- add first candidate for object space partition     
1898
1899        BvhSubdivisionCandidate *oSubdivisionCandidate = new BvhSubdivisionCandidate(oData);
1900
1901        // evaluate priority
1902        EvalSubdivisionCandidate(*oSubdivisionCandidate);
1903        bvhLeaf->SetSubdivisionCandidate(oSubdivisionCandidate);
1904
1905        const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
1906        mTotalCost = (float)objects.size() * prop / viewSpaceVol;
1907        mPvsEntries = CountViewCells(objects);
1908
1909        PrintSubdivisionStats(*oSubdivisionCandidate);
1910       
1911        return oSubdivisionCandidate;
1912}
1913
1914
1915void BvHierarchy::AssignInitialSortedObjectList(BvhTraversalData &tData)
1916{
1917        // we sort the objects as a preprocess so they don't have
1918        // to be sorted for each split
1919        for (int i = 0; i < 3; ++ i)
1920        {
1921                // create new objects
1922                if (!mSortedObjects[i])
1923                {
1924                        mSortedObjects[i] = new SortableEntryContainer();
1925                        CreateLocalSubdivisionCandidates(tData.mNode->mObjects, &mSortedObjects[i], true, i);
1926                }
1927
1928                // copy list into traversal data list
1929                tData.mSortedObjects[i] = new ObjectContainer();
1930                tData.mSortedObjects[i]->reserve((int)mSortedObjects[i]->size());
1931
1932                SortableEntryContainer::const_iterator oit, oit_end = mSortedObjects[i]->end();
1933
1934                for (oit = mSortedObjects[i]->begin(); oit != oit_end; ++ oit)
1935                {
1936                        tData.mSortedObjects[i]->push_back((*oit).mObject);
1937                }
1938        }
1939}
1940
1941
1942void BvHierarchy::AssignSortedObjects(const BvhSubdivisionCandidate &sc,
1943                                                                          BvhTraversalData &frontData,
1944                                                                          BvhTraversalData &backData)
1945{
1946        Intersectable::NewMail();
1947
1948        // we sorted the objects as a preprocess so they don't have
1949        // to be sorted for each split
1950        ObjectContainer::const_iterator fit, fit_end = sc.mFrontObjects.end();
1951
1952        for (fit = sc.mFrontObjects.begin(); fit != fit_end; ++ fit)
1953        {
1954                (*fit)->Mail();
1955        }
1956
1957        for (int i = 0; i < 3; ++ i)
1958        {
1959                frontData.mSortedObjects[i] = new ObjectContainer();
1960                backData.mSortedObjects[i] = new ObjectContainer();
1961
1962                frontData.mSortedObjects[i]->reserve((int)sc.mFrontObjects.size());
1963                backData.mSortedObjects[i]->reserve((int)sc.mFrontObjects.size());
1964
1965                ObjectContainer::const_iterator oit, oit_end = sc.mParentData.mSortedObjects[i]->end();
1966
1967                for (oit = sc.mParentData.mSortedObjects[i]->begin(); oit != oit_end; ++ oit)
1968                {
1969                        if ((*oit)->Mailed())
1970                        {
1971                                frontData.mSortedObjects[i]->push_back(*oit);
1972                        }
1973                        else
1974                        {
1975                                backData.mSortedObjects[i]->push_back(*oit);
1976                        }
1977                }
1978        }
1979}
1980
1981
1982SubdivisionCandidate *BvHierarchy::Reset(const VssRayContainer &sampleRays,
1983                                                                                 const ObjectContainer &objects)
1984{
1985        // reset stats
1986        mBvhStats.Reset();
1987        mBvhStats.Start();
1988        mBvhStats.nodes = 1;
1989
1990        // reset root
1991        DEL_PTR(mRoot);
1992       
1993        BvhLeaf *bvhleaf = new BvhLeaf(mBoundingBox, NULL, (int)objects.size());
1994        bvhleaf->mObjects = objects;
1995        mRoot = bvhleaf;
1996       
1997#if PROBABILIY_IS_BV_VOLUME
1998        mTermMinProbability *= mBoundingBox.GetVolume();
1999        // probability that bounding volume is seen
2000        const float prop = GetBoundingBox().GetVolume();
2001#else
2002        mTermMinProbability *= mVspTree->GetBoundingBox().GetVolume();
2003        // probability that volume is "seen" from the view cells
2004        const float prop = EvalViewCellsVolume(objects);
2005#endif
2006
2007        const int nRays = CountRays(objects);
2008        BvhLeaf *bvhLeaf = dynamic_cast<BvhLeaf *>(mRoot);
2009
2010        // create bvh traversal data
2011        BvhTraversalData oData(bvhLeaf, 0, prop, nRays);
2012
2013        AssignInitialSortedObjectList(oData);
2014       
2015
2016        ///////////////////
2017        //-- add first candidate for object space partition     
2018
2019        BvhSubdivisionCandidate *oSubdivisionCandidate =
2020                new BvhSubdivisionCandidate(oData);
2021
2022        EvalSubdivisionCandidate(*oSubdivisionCandidate);
2023        bvhLeaf->SetSubdivisionCandidate(oSubdivisionCandidate);
2024
2025        const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
2026        mTotalCost = (float)objects.size() * prop / viewSpaceVol;
2027
2028        PrintSubdivisionStats(*oSubdivisionCandidate);
2029
2030        return oSubdivisionCandidate;
2031}
2032
2033
2034void BvhStatistics::Print(ostream &app) const
2035{
2036        app << "=========== BvHierarchy statistics ===============\n";
2037
2038        app << setprecision(4);
2039
2040        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
2041
2042        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
2043
2044        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
2045
2046        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
2047
2048        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits << endl;
2049
2050        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
2051                << maxCostNodes * 100 / (double)Leaves() << endl;
2052
2053        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
2054                << minProbabilityNodes * 100 / (double)Leaves() << endl;
2055
2056
2057        //////////////////////////////////////////////////
2058       
2059        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
2060                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
2061       
2062        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
2063
2064        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
2065
2066        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
2067
2068       
2069        ////////////////////////////////////////////////////////
2070       
2071        app << "#N_PMINOBJECTSLEAVES  ( Percentage of leaves with mininum objects )\n"
2072                << minObjectsNodes * 100 / (double)Leaves() << endl;
2073
2074        app << "#N_MAXOBJECTREFS  ( Max number of object refs / leaf )\n" << maxObjectRefs << "\n";
2075
2076        app << "#N_MINOBJECTREFS  ( Min number of object refs / leaf )\n" << minObjectRefs << "\n";
2077
2078        app << "#N_EMPTYLEAFS ( Empty leafs )\n" << emptyNodes << "\n";
2079       
2080        app << "#N_PAVGOBJECTSLEAVES  ( average object refs / leaf)\n" << AvgObjectRefs() << endl;
2081
2082
2083        ////////////////////////////////////////////////////////
2084       
2085        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with mininum rays )\n"
2086                << minRaysNodes * 100 / (double)Leaves() << endl;
2087
2088        app << "#N_MAXRAYREFS  ( Max number of ray refs / leaf )\n" << maxRayRefs << "\n";
2089
2090        app << "#N_MINRAYREFS  ( Min number of ray refs / leaf )\n" << minRayRefs << "\n";
2091       
2092        app << "#N_PAVGRAYLEAVES  ( average ray refs / leaf )\n" << AvgRayRefs() << endl;
2093       
2094        app << "#N_PAVGRAYCONTRIBLEAVES  ( Average ray contribution)\n" <<
2095                rayRefs / (double)objectRefs << endl;
2096
2097        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"<<
2098                maxRayContriNodes * 100 / (double)Leaves() << endl;
2099
2100        app << "#N_PGLOBALCOSTMISSES ( Global cost misses )\n" << mGlobalCostMisses << endl;
2101
2102        app << "========== END OF BvHierarchy statistics ==========\n";
2103}
2104
2105
2106// TODO: return memory usage in MB
2107float BvHierarchy::GetMemUsage() const
2108{
2109        return (float)(sizeof(BvHierarchy)
2110                                   + mBvhStats.Leaves() * sizeof(BvhLeaf)
2111                                   + mBvhStats.Interior() * sizeof(BvhInterior)
2112                                   ) / float(1024 * 1024);
2113}
2114
2115
2116BvhNode *BvHierarchy::SubdivideAndCopy(SplitQueue &tQueue,
2117                                                                           SubdivisionCandidate *splitCandidate)
2118{
2119        BvhSubdivisionCandidate *sc =
2120                dynamic_cast<BvhSubdivisionCandidate *>(splitCandidate);
2121        BvhTraversalData &tData = sc->mParentData;
2122
2123        BvhNode *currentNode = tData.mNode;
2124        BvhNode *oldNode = (BvhNode *)splitCandidate->mEvaluationHack;
2125
2126        if (!oldNode->IsLeaf())
2127        {       
2128                //////////////
2129                //-- continue subdivision
2130
2131                BvhTraversalData tFrontData;
2132                BvhTraversalData tBackData;
2133                       
2134                BvhInterior *oldInterior = dynamic_cast<BvhInterior *>(oldNode);
2135               
2136                sc->mFrontObjects.clear();
2137                sc->mBackObjects.clear();
2138
2139                oldInterior->GetFront()->CollectObjects(sc->mFrontObjects);
2140                oldInterior->GetBack()->CollectObjects(sc->mBackObjects);
2141               
2142                // evaluate the changes in render cost and pvs entries
2143                EvalSubdivisionCandidate(*sc, false);
2144
2145                // create new interior node and two leaf node
2146                currentNode = SubdivideNode(*sc, tFrontData, tBackData);
2147       
2148                //oldNode->mRenderCostDecr += sc->GetRenderCostDecrease();
2149                //oldNode->mPvsEntriesIncr += sc->GetPvsEntriesIncr();
2150               
2151                oldNode->mRenderCostDecr = sc->GetRenderCostDecrease();
2152                oldNode->mPvsEntriesIncr = sc->GetPvsEntriesIncr();
2153               
2154                ///////////////////////////
2155                //-- push the new split candidates on the queue
2156               
2157                BvhSubdivisionCandidate *frontCandidate = new BvhSubdivisionCandidate(tFrontData);
2158                BvhSubdivisionCandidate *backCandidate = new BvhSubdivisionCandidate(tBackData);
2159
2160                frontCandidate->SetPriority((float)-oldInterior->GetFront()->mTimeStamp);
2161                backCandidate->SetPriority((float)-oldInterior->GetBack()->mTimeStamp);
2162
2163                frontCandidate->mEvaluationHack = oldInterior->GetFront();
2164                backCandidate->mEvaluationHack = oldInterior->GetBack();
2165
2166                // cross reference
2167                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
2168                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
2169
2170                //cout << "f: " << frontCandidate->GetPriority() << " b: " << backCandidate->GetPriority() << endl;
2171                tQueue.Push(frontCandidate);
2172                tQueue.Push(backCandidate);
2173        }
2174
2175        /////////////////////////////////
2176        //-- node is a leaf => terminate traversal
2177
2178        if (currentNode->IsLeaf())
2179        {
2180                // this leaf is no candidate for splitting anymore
2181                // => detach subdivision candidate
2182                tData.mNode->SetSubdivisionCandidate(NULL);
2183                // detach node so we don't delete it with the traversal data
2184                tData.mNode = NULL;
2185        }
2186       
2187        return currentNode;
2188}
2189
2190
2191}
Note: See TracBrowser for help on using the repository browser.