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

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