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

Revision 1308, 37.1 KB checked in by mattausch, 18 years ago (diff)

changed hierarchy construction: up to a certain level view space split is taken

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
20
21namespace GtpVisibilityPreprocessor {
22
23
24#define USE_FIXEDPOINT_T 0
25
26static float debugVol = 0;
27
28int BvhNode::sMailId = 10000;//2147483647;
29int BvhNode::sReservedMailboxes = 1;
30
31BvHierarchy *BvHierarchy::BvhSubdivisionCandidate::sBvHierarchy = NULL;
32
33
34inline static bool ilt(Intersectable *obj1, Intersectable *obj2)
35{
36        return obj1->mId < obj2->mId;
37}
38
39
40/***************************************************************/
41/*              class BvhNode implementation                   */
42/***************************************************************/
43
44BvhNode::BvhNode(): mParent(NULL), mMailbox(0)
45{
46}
47
48BvhNode::BvhNode(const AxisAlignedBox3 &bbox):
49mParent(NULL), mBoundingBox(bbox), mMailbox(0)
50{
51}
52
53
54BvhNode::BvhNode(const AxisAlignedBox3 &bbox, BvhInterior *parent):
55mBoundingBox(bbox), mParent(parent), mMailbox(0)
56{
57}
58
59
60bool BvhNode::IsRoot() const
61{
62        return mParent == NULL;
63}
64
65
66BvhInterior *BvhNode::GetParent()
67{
68        return mParent;
69}
70
71
72void BvhNode::SetParent(BvhInterior *parent)
73{
74        mParent = parent;
75}
76
77
78
79/******************************************************************/
80/*              class BvhInterior implementation                  */
81/******************************************************************/
82
83
84BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox):
85BvhNode(bbox), mSubdivisionCandidate(NULL)
86{
87}
88
89
90BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox, BvhInterior *parent):
91BvhNode(bbox, parent)
92{
93}
94
95
96BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox,
97                                 BvhInterior *parent,
98                                 const int numObjects):
99BvhNode(bbox, parent)
100{
101        mObjects.reserve(numObjects);
102}
103
104
105bool BvhLeaf::IsLeaf() const
106{
107        return true;
108}
109
110
111BvhLeaf::~BvhLeaf()
112{
113}
114
115
116/******************************************************************/
117/*              class BvhInterior implementation                  */
118/******************************************************************/
119
120
121BvhInterior::BvhInterior(const AxisAlignedBox3 &bbox):
122BvhNode(bbox), mFront(NULL), mBack(NULL)
123{
124}
125
126
127BvhInterior::BvhInterior(const AxisAlignedBox3 &bbox, BvhInterior *parent):
128BvhNode(bbox, parent), mFront(NULL), mBack(NULL)
129{
130}
131
132
133void BvhInterior::ReplaceChildLink(BvhNode *oldChild, BvhNode *newChild)
134{
135        if (mBack == oldChild)
136                mBack = newChild;
137        else
138                mFront = newChild;
139}
140
141
142bool BvhInterior::IsLeaf() const
143{
144        return false;
145}
146
147
148BvhInterior::~BvhInterior()
149{
150        DEL_PTR(mFront);
151        DEL_PTR(mBack);
152}
153
154
155void BvhInterior::SetupChildLinks(BvhNode *front, BvhNode *back)
156{
157    mBack = back;
158    mFront = front;
159}
160
161
162
163/*******************************************************************/
164/*                  class BvHierarchy implementation               */
165/*******************************************************************/
166
167
168BvHierarchy::BvHierarchy():
169mRoot(NULL),
170mTimeStamp(1)
171{
172        ReadEnvironment();
173        mSubdivisionCandidates = new vector<SortableEntry>;
174}
175
176
177BvHierarchy::~BvHierarchy()
178{
179        // delete kd intersectables
180        BvhIntersectableMap::iterator it, it_end = mBvhIntersectables.end();
181
182        for (it = mBvhIntersectables.begin(); it != mBvhIntersectables.end(); ++ it)
183        {
184                DEL_PTR((*it).second);
185        }
186
187        DEL_PTR(mSubdivisionCandidates);
188
189        mSubdivisionStats.close();
190}
191
192
193void BvHierarchy::ReadEnvironment()
194{
195        bool randomize = false;
196        Environment::GetSingleton()->GetBoolValue("VspTree.Construction.randomize", randomize);
197        if (randomize)
198                Randomize(); // initialise random generator for heuristics
199
200        //-- termination criteria for autopartition
201        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.maxDepth", mTermMaxDepth);
202        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.maxLeaves", mTermMaxLeaves);
203        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.minObjects", mTermMinObjects);
204        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.minProbability", mTermMinProbability);
205       
206        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.missTolerance", mTermMissTolerance);
207       
208        //-- max cost ratio for early tree termination
209        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.maxCostRatio", mTermMaxCostRatio);
210
211        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.minGlobalCostRatio",
212                mTermMinGlobalCostRatio);
213        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.globalCostMissTolerance",
214                mTermGlobalCostMissTolerance);
215
216        //-- factors for bsp tree split plane heuristics
217
218        // if only the driving axis is used for axis aligned split
219        Environment::GetSingleton()->GetBoolValue("BvHierarchy.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
220        Environment::GetSingleton()->GetFloatValue("BvHierarchy.maxStaticMemory", mMaxMemory);
221        Environment::GetSingleton()->GetBoolValue("BvHierarchy.useCostHeuristics", mUseCostHeuristics);
222
223        char subdivisionStatsLog[100];
224        Environment::GetSingleton()->GetStringValue("BvHierarchy.subdivisionStats", subdivisionStatsLog);
225        mSubdivisionStats.open(subdivisionStatsLog);
226
227        Environment::GetSingleton()->GetFloatValue(
228                "BvHierarchy.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
229       
230
231        //-- debug output
232
233        Debug << "******* Bvh hierarchy options ******** " << endl;
234    Debug << "max depth: " << mTermMaxDepth << endl;
235        Debug << "min probabiliy: " << mTermMinProbability<< endl;
236        Debug << "min objects: " << mTermMinObjects << endl;
237        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
238        Debug << "miss tolerance: " << mTermMissTolerance << endl;
239        Debug << "max leaves: " << mTermMaxLeaves << endl;
240        Debug << "randomize: " << randomize << endl;
241        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
242        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
243        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
244        Debug << "max memory: " << mMaxMemory << endl;
245        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
246        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
247       
248        Debug << "split borders: " << mSplitBorder << endl;
249        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
250        Debug << endl;
251}
252
253
254void AssociateObjectsWithLeaf(BvhLeaf *leaf)
255{
256        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
257        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
258        {
259                (*oit)->mBvhLeaf = leaf;
260        }
261}
262
263
264BvhInterior *BvHierarchy::SubdivideNode(const ObjectContainer &frontObjects,
265                                                                                const ObjectContainer &backObjects,
266                                                                                const BvhTraversalData &tData,
267                                                                                BvhTraversalData &frontData,
268                                                                                BvhTraversalData &backData)
269{
270        BvhLeaf *leaf = tData.mNode;
271       
272        // two new leaves
273    mBvhStats.nodes += 2;
274
275        // add the new nodes to the tree
276        BvhInterior *node = new BvhInterior(tData.mBoundingBox, leaf->GetParent());
277       
278
279        //-- the front and back traversal data is filled with the new values
280
281        frontData.mDepth = backData.mDepth = tData.mDepth + 1;
282
283        frontData.mBoundingBox = ComputeBoundingBox(frontObjects, &tData.mBoundingBox);
284        backData.mBoundingBox = ComputeBoundingBox(backObjects, &tData.mBoundingBox);
285       
286        /////////////
287        //-- create front and back leaf
288
289        BvhLeaf *back =
290                new BvhLeaf(backData.mBoundingBox, node, (int)backObjects.size());
291        BvhLeaf *front =
292                new BvhLeaf(frontData.mBoundingBox, node, (int)frontObjects.size());
293
294        BvhInterior *parent = leaf->GetParent();
295
296
297        // replace a link from node's parent
298        if (parent)
299        {
300                parent->ReplaceChildLink(leaf, node);
301                node->SetParent(parent);
302        }
303        else // new root
304        {
305                mRoot = node;
306        }
307
308        // and setup child links
309        node->SetupChildLinks(front, back);
310
311        ++ mBvhStats.splits;
312
313
314        ////////////////////////////////////
315
316        frontData.mNode = front;
317        backData.mNode = back;
318
319        back->mObjects = backObjects;
320        front->mObjects = frontObjects;
321
322        AssociateObjectsWithLeaf(back);
323        AssociateObjectsWithLeaf(front);
324   
325        // compute probability, i.e., volume of seen view cells
326        frontData.mProbability = EvalViewCellsVolume(frontObjects);
327        backData.mProbability = EvalViewCellsVolume(backObjects);
328
329        return node;
330}
331
332
333BvhNode *BvHierarchy::Subdivide(SplitQueue &tQueue,
334                                                                SubdivisionCandidate *splitCandidate,
335                                                                const bool globalCriteriaMet)
336{
337        BvhSubdivisionCandidate *sc =
338                dynamic_cast<BvhSubdivisionCandidate *>(splitCandidate);
339        BvhTraversalData &tData = sc->mParentData;
340
341        BvhNode *newNode = tData.mNode;
342
343        if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet)
344        {       
345                //-- continue subdivision
346
347                BvhTraversalData tFrontData;
348                BvhTraversalData tBackData;
349                       
350                // create new interior node and two leaf node
351                newNode = SubdivideNode(sc->mFrontObjects,
352                                                                sc->mBackObjects,
353                                                                tData,
354                                                                tFrontData,
355                                                                tBackData);
356       
357                const int maxCostMisses = sc->mMaxCostMisses;
358
359        // how often was max cost ratio missed in this branch?
360                tFrontData.mMaxCostMisses = maxCostMisses;
361                tBackData.mMaxCostMisses = maxCostMisses;
362               
363                // decrease the weighted average cost of the subdivisoin
364                mTotalCost -= sc->GetRenderCostDecrease();
365
366                // subdivision statistics
367                if (1) PrintSubdivisionStats(*sc);
368
369                //-- push the new split candidates on the queue
370               
371                BvhSubdivisionCandidate *frontCandidate =
372                        new BvhSubdivisionCandidate(tFrontData);
373                BvhSubdivisionCandidate *backCandidate =
374                        new BvhSubdivisionCandidate(tBackData);
375
376                EvalSubdivisionCandidate(*frontCandidate);
377                EvalSubdivisionCandidate(*backCandidate);
378       
379                // cross reference
380                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
381                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
382
383                Debug << "leaf: " << tFrontData.mNode << " setting f candidate: " << tFrontData.mNode->GetSubdivisionCandidate() << " type: " << tFrontData.mNode->GetSubdivisionCandidate()->Type() << endl;
384                Debug << "leaf: " << tBackData.mNode << " setting b candidate: " << tBackData.mNode->GetSubdivisionCandidate() << " type: " << tBackData.mNode->GetSubdivisionCandidate()->Type() << endl;
385               
386                tQueue.Push(frontCandidate);
387                tQueue.Push(backCandidate);
388
389                // delete old leaf node
390                //DEL_PTR(tData.mNode);
391        }
392
393        //-- terminate traversal
394
395    if (newNode->IsLeaf())
396        {
397                //-- store additional info
398               
399                EvaluateLeafStats(tData);
400       
401                const bool mStoreRays = true;
402                if (mStoreRays)
403                {
404                        BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(newNode);
405                        CollectRays(leaf->mObjects, leaf->mVssRays);
406                }
407               
408                // detach subdivision candidate: this leaf is no candidate for
409                // splitting anymore
410                tData.mNode->SetSubdivisionCandidate(NULL);
411                // detach node so it won't get deleted
412                tData.mNode = NULL;
413        }
414       
415        return newNode;
416}
417
418
419void BvHierarchy::EvalSubdivisionCandidate(BvhSubdivisionCandidate &splitCandidate)
420{
421        // compute best object partition
422        const float ratio =     SelectObjectPartition(
423                                                        splitCandidate.mParentData,
424                                                        splitCandidate.mFrontObjects,
425                                                        splitCandidate.mBackObjects);
426       
427        BvhLeaf *leaf = splitCandidate.mParentData.mNode;
428
429        // cost ratio violated?
430        const bool maxCostRatioViolated = mTermMaxCostRatio < ratio;
431
432        splitCandidate.mMaxCostMisses = maxCostRatioViolated ?
433                splitCandidate.mParentData.mMaxCostMisses + 1 :
434                splitCandidate.mParentData.mMaxCostMisses;
435
436        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
437        const float oldProp = EvalViewCellsVolume(leaf->mObjects);
438        //const float oldProp2 = splitCandidate.mParentData.mProbability; Debug << "here8 " << (oldProp - oldProp2) / viewSpaceVol << "  " << oldProp  / viewSpaceVol << " " << oldProp2  / viewSpaceVol << endl;
439
440        const float oldRenderCost = oldProp * (float)leaf->mObjects.size() / viewSpaceVol;
441
442        // compute global decrease in render cost
443        float newRenderCost = EvalRenderCost(splitCandidate.mParentData,
444                                                                             splitCandidate.mFrontObjects,
445                                                                                 splitCandidate.mBackObjects);
446
447        newRenderCost /=  viewSpaceVol;
448        const float renderCostDecr = oldRenderCost - newRenderCost;
449
450        Debug << "\nbvh render cost decr: " << renderCostDecr << endl;
451        splitCandidate.SetRenderCostDecrease(renderCostDecr);
452
453#if 1
454        const float priority = (float)-splitCandidate.mParentData.mDepth;
455#else   
456        // take render cost of node into account
457        // otherwise danger of being stuck in a local minimum!!
458        const float factor = mRenderCostDecreaseWeight;
459        const float priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
460#endif
461
462        // compute global decrease in render cost
463        splitCandidate.SetPriority(priority);
464}
465
466
467inline bool BvHierarchy::LocalTerminationCriteriaMet(const BvhTraversalData &data) const
468{
469        // matt: TODO
470        return ( 0
471                //|| ((int)data.mNode->mObjects.size() < mTermMinObjects)
472                //|| (data.mProbability <= mTermMinProbability)
473                //|| (data.mDepth >= mTermMaxDepth)
474                 );
475}
476
477
478inline bool BvHierarchy::GlobalTerminationCriteriaMet(const BvhTraversalData &data) const
479{
480        // matt: TODO
481        return (0
482                || (mBvhStats.Leaves() >= mTermMaxLeaves)
483                //|| (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
484                //|| mOutOfMemory
485                );
486}
487
488
489void BvHierarchy::EvaluateLeafStats(const BvhTraversalData &data)
490{
491        // the node became a leaf -> evaluate stats for leafs
492        BvhLeaf *leaf = data.mNode;
493       
494        ++ mCreatedLeaves;
495
496        if (data.mDepth >= mTermMaxDepth)
497        {
498        ++ mBvhStats.maxDepthNodes;
499                //Debug << "new max depth: " << mVspStats.maxDepthNodes << endl;
500        }
501
502        if (data.mDepth < mTermMaxDepth)
503        {
504        ++ mBvhStats.minDepthNodes;
505        }
506
507        if (data.mProbability <= mTermMinProbability)
508                ++ mBvhStats.minProbabilityNodes;
509       
510        // accumulate depth to compute average depth
511        mBvhStats.accumDepth += data.mDepth;
512 
513        if ((int)(leaf->mObjects.size()) < mTermMinObjects)
514             ++ mBvhStats.minObjectsNodes;
515 
516        if ((int)(leaf->mObjects.size()) > mBvhStats.maxObjectRefs)
517                mBvhStats.maxObjectRefs = (int)leaf->mObjects.size();
518}
519
520
521#if 0
522float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
523                                                                                        const int axis,
524                                                                                        ObjectContainer &objectsFront,
525                                                                                        ObjectContainer &objectsBack)
526{
527        const float maxBox = tData.mBoundingBox.Max(axis);
528        const float minBox = tData.mBoundingBox.Min(axis);
529
530        float midPoint = (maxBox + minBox) * 0.5f;
531
532        ObjectContainer::const_iterator oit, oit_end = tData.mNode->mObjects.end();
533       
534        for (oit = tData.mNode->mObjects.begin(); oit != oit_end; ++ oit)
535        {
536                Intersectable *obj = *oit;
537                const AxisAlignedBox3 box = obj->GetBox();
538
539                const float objMid = (box.Max(axis) + box.Min(axis)) * 0.5f;
540
541                // object mailed => belongs to back objects
542                if (objMid < midPoint)
543                        objectsBack.push_back(obj);
544                else
545                        objectsFront.push_back(obj);
546        }
547
548        const float oldRenderCost = tData.mProbability * (float)tData.mNode->mObjects.size();
549        const float newRenderCost =
550                EvalRenderCost(tData, objectsFront, objectsBack);
551
552        const float ratio = newRenderCost / oldRenderCost;
553        return ratio;
554}
555
556#else
557
558float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
559                                                                                        const int axis,
560                                                                                        ObjectContainer &objectsFront,
561                                                                                        ObjectContainer &objectsBack)
562{
563        SortSubdivisionCandidates(tData, axis);
564       
565        vector<SortableEntry>::const_iterator cit, cit_end = mSubdivisionCandidates->end();
566
567        int i = 0;
568        const int border = (int)tData.mNode->mObjects.size() / 2;
569
570    for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ i)
571        {
572                Intersectable *obj = (*cit).mObject;
573
574                // object mailed => belongs to back objects
575                if (i < border)
576                        objectsBack.push_back(obj);
577                else
578                        objectsFront.push_back(obj);
579        }
580
581        const float oldProp = EvalViewCellsVolume(tData.mNode->mObjects);
582        //const float oldProp2 = tData.mProbability; Debug << "here65 " << oldProp - oldProp2 << endl;
583
584        const float oldRenderCost = oldProp * (float)tData.mNode->mObjects.size();
585        const float newRenderCost = EvalRenderCost(tData, objectsFront, objectsBack);
586
587        const float ratio = newRenderCost / oldRenderCost;
588        return ratio;
589}
590#endif
591
592
593float BvHierarchy::EvalLocalCostHeuristics(const BvhTraversalData &tData,
594                                                                                   const int axis,
595                                                                                   ObjectContainer &objectsFront,
596                                                                                   ObjectContainer &objectsBack)
597{
598        // prepare the heuristics by setting mailboxes and counters.
599        const float totalVol = PrepareHeuristics(tData, axis);
600
601        // go through the lists, count the number of objects left and right
602        // and evaluate the cost funcion
603
604        // local helper variables
605        float volLeft = 0;
606        float volRight = totalVol;
607
608        int nObjectsLeft = 0;
609
610        const int nTotalObjects = (int)tData.mNode->mObjects.size();
611        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
612
613        vector<SortableEntry>::const_iterator currentPos =
614                mSubdivisionCandidates->begin();
615
616        /////////////////////////////////
617        // the parameters for the current optimum
618
619        float volBack = volLeft;
620        float volFront = volRight;
621
622        float newRenderCost = nTotalObjects * totalVol;
623
624
625        /////////////////////////////
626        // the sweep heuristics
627       
628        //-- traverse through events and find best split plane
629
630        vector<SortableEntry>::const_iterator cit, cit_end = mSubdivisionCandidates->end();
631
632        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit)
633        {
634                Intersectable *object = (*cit).mObject;
635               
636                // evaluate change in l and r volume
637                // voll = view cells that see only left node (i.e., left pvs)
638                // volr = view cells that see only right node (i.e., right pvs)
639                EvalHeuristicsContribution(object, volLeft, volRight);
640
641                ++ nObjectsLeft;
642               
643                const int nObjectsRight = nTotalObjects - nObjectsLeft;
644
645                // the heuristics
646            const float sum = volLeft * (float)nObjectsLeft +
647                                                  volRight * (float)nObjectsRight;
648
649                if (sum < newRenderCost)
650                {
651                        newRenderCost = sum;
652
653                        volBack = volLeft;
654                        volFront = volRight;
655
656                        // objects belongs to left side now
657                        for (; currentPos != (cit + 1); ++ currentPos);
658                }
659        }
660
661        //-- assign object to front and back volume
662
663        // belongs to back bv
664        for (cit = mSubdivisionCandidates->begin(); cit != currentPos; ++ cit)
665                objectsBack.push_back((*cit).mObject);
666       
667        // belongs to front bv
668        for (cit = currentPos; cit != cit_end; ++ cit)
669                objectsFront.push_back((*cit).mObject);
670
671        tData.mNode->mObjects.end();
672
673        const float oldRenderCost = (float)nTotalObjects * totalVol + Limits::Small;
674        // the relative cost ratio
675        const float ratio = newRenderCost / oldRenderCost;
676
677        Debug << "\n§§§§ eval local cost §§§§" << endl
678                  << "back pvs: " << (int)objectsBack.size() << " front pvs: " << (int)objectsFront.size() << " total pvs: " << nTotalObjects << endl
679                  << "back p: " << volBack / viewSpaceVol << " front p " << volFront / viewSpaceVol << " p: " << totalVol / viewSpaceVol << endl
680                  << "old rc: " << oldRenderCost / viewSpaceVol << " new rc: " << newRenderCost / viewSpaceVol << endl
681                  << "render cost decrease: " << oldRenderCost / viewSpaceVol - newRenderCost / viewSpaceVol << endl;
682
683        return ratio;
684}
685
686
687void BvHierarchy::SortSubdivisionCandidates(const BvhTraversalData &tData,
688                                                                                        const int axis)                                                                                 
689{
690        mSubdivisionCandidates->clear();
691
692        //RayInfoContainer *rays = tData.mRays;
693        BvhLeaf *leaf = tData.mNode;
694
695        // compute requested size
696        const int requestedSize = (int)leaf->mObjects.size() * 2;
697       
698        // creates a sorted split candidates array
699        if (mSubdivisionCandidates->capacity() > 500000 &&
700                requestedSize < (int)(mSubdivisionCandidates->capacity() / 10) )
701        {
702        delete mSubdivisionCandidates;
703                mSubdivisionCandidates = new vector<SortableEntry>;
704        }
705
706        mSubdivisionCandidates->reserve(requestedSize);
707
708        //-- insert object queries
709        //-- These queries can induce a change in pvs size.
710        //-- Note that they cannot induce a change in view cell volume, as
711        //-- there is no ray associated with these events!!
712
713        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
714
715        for (oit = leaf->mObjects.begin(); oit < oit_end; ++ oit)
716        {
717                Intersectable *obj = *oit;
718               
719                Intersectable *object = *oit;
720                const AxisAlignedBox3 &box = object->GetBox();
721                const float midPt = (box.Min(axis) + box.Max(axis)) * 0.5f;
722
723                mSubdivisionCandidates->push_back(SortableEntry(object, midPt));
724        }
725
726        stable_sort(mSubdivisionCandidates->begin(), mSubdivisionCandidates->end());
727}
728
729
730const BvhStatistics &BvHierarchy::GetStatistics() const
731{
732        return mBvhStats;
733}
734
735
736float BvHierarchy::PrepareHeuristics(const BvhTraversalData &tData, const int axis)
737{       
738        //-- sort so we can use a sweep from right to left
739        SortSubdivisionCandidates(tData, axis);
740
741        float vol = 0;
742        BvhLeaf *leaf = tData.mNode;
743
744        // collect and mark the view cells as belonging to front pvs
745        ViewCellContainer viewCells;
746        CollectViewCells(tData.mNode->mObjects, viewCells, true);
747
748    ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
749
750        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
751        {
752                vol += (*vit)->GetVolume();
753        }
754
755        // mail view cells on the left side
756        ViewCell::NewMail();
757        // mail the objects on the left side
758        Intersectable::NewMail();
759
760        return vol;
761}
762///////////////////////////////////////////////////////////
763
764
765void BvHierarchy::EvalHeuristicsContribution(Intersectable *obj,
766                                                                                         float &volLeft,
767                                                                                         float &volRight)
768{
769        // collect all view cells associated with this objects
770        // (also multiple times, if they are pierced by several rays)
771
772        ViewCellContainer viewCells;
773       
774        const bool useMailboxing = false;
775        CollectViewCells(obj, viewCells, useMailboxing);
776
777
778        /// classify view cells and compute volume contri accordingly
779        /// possible view cell classifications:
780        /// view cell mailed => view cell can be seen from left child node
781        /// view cell counter > 0 view cell can be seen from right child node
782        /// combined: view cell volume belongs to both nodes
783        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
784       
785        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
786        {
787                // view cells can also be seen from left child node
788                ViewCell *viewCell = *vit;
789
790                const float vol = viewCell->GetVolume();
791
792                if (!viewCell->Mailed())
793                {
794                        viewCell->Mail();
795
796                        // we now see view cell from both nodes
797                        // => add volume to left node
798                        volLeft += vol;
799                }
800
801                // last reference into the right node
802                if (-- viewCell->mCounter == 0)
803                {
804                        // view cell was previously seen from both nodes  =>
805                        // remove volume from right node
806                        volRight -= vol;
807                }
808        }
809}
810
811
812void BvHierarchy::SetViewCellsManager(ViewCellsManager *vcm)
813{
814        mViewCellsManager = vcm;
815}
816
817
818AxisAlignedBox3 BvHierarchy::GetBoundingBox() const
819{
820        return mBoundingBox;
821}
822
823
824float BvHierarchy::SelectObjectPartition(const BvhTraversalData &tData,
825                                                                                 ObjectContainer &frontObjects,
826                                                                                 ObjectContainer &backObjects)
827{
828        ObjectContainer nFrontObjects[3];
829        ObjectContainer nBackObjects[3];
830
831        float nCostRatio[3];
832
833        // create bounding box of node geometry
834        AxisAlignedBox3 box = tData.mBoundingBox;
835               
836        int sAxis = 0;
837        int bestAxis = -1;
838
839        if (mOnlyDrivingAxis)
840        {
841                sAxis = box.Size().DrivingAxis();
842        }
843       
844        // -- evaluate split cost for all three axis
845       
846        for (int axis = 0; axis < 3; ++ axis)
847        {
848                if (!mOnlyDrivingAxis || (axis == sAxis))
849                {
850                        if (mUseCostHeuristics)
851                        {
852                                //-- partition objects using heuristics
853                                nCostRatio[axis] =
854                                        EvalLocalCostHeuristics(
855                                                                                        tData,
856                                                                                        axis,
857                                                                                        nFrontObjects[axis],
858                                                                                        nBackObjects[axis]);
859                        }
860                        else
861                        {
862                                nCostRatio[axis] =
863                                        EvalLocalObjectPartition(
864                                                                                         tData,
865                                                                                         axis,
866                                                                                         nFrontObjects[axis],
867                                                                                         nBackObjects[axis]);
868                        }
869
870                        if (bestAxis == -1)
871                        {
872                                bestAxis = axis;
873                        }
874                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
875                        {
876                                bestAxis = axis;
877                        }
878                }
879        }
880
881        //-- assign values
882
883        frontObjects = nFrontObjects[bestAxis];
884        backObjects = nBackObjects[bestAxis];
885
886        //Debug << "val: " << nCostRatio[bestAxis] << " axis: " << bestAxis << endl;
887        return nCostRatio[bestAxis];
888}
889
890
891void BvHierarchy::AssociateObjectsWithRays(const VssRayContainer &rays)
892{
893
894        VssRayContainer::const_iterator rit, rit_end = rays.end();
895
896    for (rit = rays.begin(); rit != rays.end(); ++ rit)
897        {
898                VssRay *ray = (*rit);
899
900                if (ray->mTerminationObject)
901                {
902                        ray->mTerminationObject->mVssRays.push_back(ray);
903                }
904
905                if (0 && ray->mOriginObject)
906                {
907                        ray->mOriginObject->mVssRays.push_back(ray);
908                }
909        }
910}
911
912
913void BvHierarchy::PrintSubdivisionStats(const SubdivisionCandidate &sc)
914{
915        const float costDecr = sc.GetRenderCostDecrease();     
916
917        mSubdivisionStats
918                        << "#Leaves\n" << mBvhStats.Leaves()
919                        << "#RenderCostDecrease\n" << costDecr << endl
920                        << "#TotalRenderCost\n" << mTotalCost << endl;
921                        //<< "#AvgRenderCost\n" << avgRenderCost << endl;
922}
923
924
925void BvHierarchy::CollectRays(const ObjectContainer &objects,
926                                                          VssRayContainer &rays) const
927{
928        VssRay::NewMail();
929       
930        ObjectContainer::const_iterator oit, oit_end = objects.end();
931
932        // evaluate reverse pvs and view cell volume on left and right cell
933        // note: should I take all leaf objects or rather the objects hit by rays?
934        for (oit = objects.begin(); oit != oit_end; ++ oit)
935        {
936                Intersectable *obj = *oit;
937               
938                VssRayContainer::const_iterator rit, rit_end = obj->mVssRays.end();
939
940                for (rit = obj->mVssRays.begin(); rit < rit_end; ++ rit)
941                {
942                        VssRay *ray = (*rit);
943
944                        if (!ray->Mailed())
945                        {
946                                ray->Mail();
947                                rays.push_back(ray);
948                        }
949                }
950        }
951}
952
953
954float BvHierarchy::EvalRenderCost(const BvhTraversalData &tData,
955                                                                  const ObjectContainer &objectsFront,
956                                                                  const ObjectContainer &objectsBack) const
957{
958        BvhLeaf *leaf = tData.mNode;
959
960        // probability that view point lies in a view cell which sees this node
961        const float pFront = EvalViewCellsVolume(objectsFront);
962        const float pBack = EvalViewCellsVolume(objectsBack);
963               
964        const int totalObjects = (int)leaf->mObjects.size();
965        const int nObjectsFront = (int)objectsFront.size();
966        const int nObjectsBack = (int)objectsBack.size();
967
968        //-- pvs rendering heuristics
969        const float newRenderCost = nObjectsFront * pFront + nObjectsBack * pBack;
970        /*
971        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
972        Debug << "\nbvh render cost\n"
973                  << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << endl
974                  << "new rc: " << newRenderCost / viewSpaceVol << endl;*/
975
976        return newRenderCost;
977}
978
979
980AxisAlignedBox3 BvHierarchy::ComputeBoundingBox(const ObjectContainer &objects,
981                                                                                                const AxisAlignedBox3 *parentBox)
982{
983        if (parentBox && objects.empty())
984                return *parentBox;
985
986        AxisAlignedBox3 box;
987        box.Initialize();
988
989        ObjectContainer::const_iterator oit, oit_end = objects.end();
990
991        //-- compute bounding box
992        for (oit = objects.begin(); oit != oit_end; ++ oit)
993        {
994                Intersectable *obj = *oit;
995
996                // compute bounding box of view space
997                box.Include(obj->GetBox());
998        }
999
1000        return box;
1001}
1002
1003
1004void BvHierarchy::CollectLeaves(vector<BvhLeaf *> &leaves) const
1005{
1006        stack<BvhNode *> nodeStack;
1007        nodeStack.push(mRoot);
1008
1009        while (!nodeStack.empty())
1010        {
1011                BvhNode *node = nodeStack.top();
1012                nodeStack.pop();
1013
1014                if (node->IsLeaf())
1015                {
1016                        BvhLeaf *leaf = (BvhLeaf *)node;
1017                        leaves.push_back(leaf);
1018                }
1019                else
1020                {
1021                        BvhInterior *interior = (BvhInterior *)node;
1022
1023                        nodeStack.push(interior->GetBack());
1024                        nodeStack.push(interior->GetFront());
1025                }
1026        }
1027}
1028
1029
1030AxisAlignedBox3 BvHierarchy::GetBoundingBox(BvhNode *node) const
1031{
1032        return node->GetBoundingBox();
1033}
1034
1035
1036void BvHierarchy::CollectViewCells(const ObjectContainer &objects,
1037                                                                   ViewCellContainer &viewCells,
1038                                                                   const bool setCounter) const
1039{
1040        ViewCell::NewMail();
1041        ObjectContainer::const_iterator oit, oit_end = objects.end();
1042
1043        // loop through all object and collect view cell pvs of this node
1044        for (oit = objects.begin(); oit != oit_end; ++ oit)
1045        {
1046                CollectViewCells(*oit, viewCells, true, setCounter);
1047        }
1048}
1049
1050
1051void BvHierarchy::CollectViewCells(Intersectable *obj,
1052                                                                   ViewCellContainer &viewCells,
1053                                                                   const bool useMailBoxing,
1054                                                                   const bool setCounter) const
1055{
1056        VssRayContainer::const_iterator rit, rit_end = obj->mVssRays.end();
1057
1058        for (rit = obj->mVssRays.begin(); rit < rit_end; ++ rit)
1059        {
1060                VssRay *ray = (*rit);
1061                ViewCellContainer tmpViewCells;
1062       
1063                mVspTree->GetViewCells(*ray, tmpViewCells);
1064
1065                ViewCellContainer::const_iterator vit, vit_end = tmpViewCells.end();
1066
1067                for (vit = tmpViewCells.begin(); vit != vit_end; ++ vit)
1068                {
1069                        VspViewCell *vc = dynamic_cast<VspViewCell *>(*vit);
1070
1071                        // store view cells
1072                        if (!useMailBoxing || !vc->Mailed())
1073                        {
1074                                if (useMailBoxing)
1075                                {
1076                                        vc->Mail();
1077                                        if (setCounter)
1078                                        {
1079                                                vc->mCounter = 0;
1080                                        }
1081                                }
1082                                viewCells.push_back(vc);
1083                        }
1084                       
1085                        if (setCounter)
1086                        {
1087                                ++ vc->mCounter;
1088                        }
1089                }
1090        }
1091}
1092
1093
1094void BvHierarchy::CollectDirtyCandidates(BvhSubdivisionCandidate *sc,
1095                                                                                 vector<SubdivisionCandidate *> &dirtyList)
1096{
1097        BvhTraversalData &tData = sc->mParentData;
1098        BvhLeaf *node = tData.mNode;
1099       
1100        ViewCellContainer viewCells;
1101        CollectViewCells(node->mObjects, viewCells);
1102
1103        // split candidates handling
1104        // these view cells  are thrown into dirty list
1105        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1106
1107        Debug << "collecting " << (int)viewCells.size() << " dirty candidates" << endl;
1108
1109        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1110        {
1111                VspViewCell *vc = dynamic_cast<VspViewCell *>(*vit);
1112                VspLeaf *leaf = vc->mLeaf;
1113                SubdivisionCandidate *candidate = leaf->GetSubdivisionCandidate();
1114               
1115                if (candidate) // is this leaf still a split candidate?
1116                {
1117                        dirtyList.push_back(candidate);
1118                }
1119        }
1120}
1121
1122
1123BvhNode *BvHierarchy::GetRoot() const
1124{
1125        return mRoot;
1126}
1127
1128
1129bool BvHierarchy::IsObjectInLeaf(BvhLeaf *leaf, Intersectable *object) const
1130{
1131        ObjectContainer::const_iterator oit =
1132                lower_bound(leaf->mObjects.begin(), leaf->mObjects.end(), object, ilt);
1133                               
1134        // objects sorted by id
1135        if ((oit != leaf->mObjects.end()) && ((*oit)->GetId() == object->GetId()))
1136        {
1137                return true;
1138        }
1139        else
1140        {
1141                return false;
1142        }
1143}
1144
1145
1146BvhLeaf *BvHierarchy::GetLeaf(Intersectable *object, BvhNode *node) const
1147{
1148        // rather use the simple version
1149        if (!object) return NULL;
1150        return object->mBvhLeaf;
1151       
1152        ///////////////////////////////////////
1153        // start from root of tree
1154       
1155        if (node == NULL)
1156                node = mRoot;
1157       
1158        vector<BvhLeaf *> leaves;
1159
1160        stack<BvhNode *> nodeStack;
1161        nodeStack.push(node);
1162 
1163        BvhLeaf *leaf = NULL;
1164 
1165        while (!nodeStack.empty()) 
1166        {
1167                BvhNode *node = nodeStack.top();
1168                nodeStack.pop();
1169       
1170                if (node->IsLeaf())
1171                {
1172                        leaf = dynamic_cast<BvhLeaf *>(node);
1173
1174                        if (IsObjectInLeaf(leaf, object))
1175                        {
1176                                return leaf;
1177                        }
1178                }
1179                else   
1180                {       
1181                        // find point
1182                        BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1183       
1184                        if (interior->GetBack()->GetBoundingBox().Includes(object->GetBox()))
1185                        {
1186                                nodeStack.push(interior->GetBack());
1187                        }
1188                       
1189                        // search both sides as we are using bounding volumes
1190                        if (interior->GetFront()->GetBoundingBox().Includes(object->GetBox()))
1191                        {
1192                                nodeStack.push(interior->GetFront());
1193                        }
1194                }
1195        }
1196 
1197        return leaf;
1198}
1199
1200
1201BvhIntersectable *BvHierarchy::GetOrCreateBvhIntersectable(BvhNode *node)
1202{
1203        // search nodes
1204        std::map<BvhNode *, BvhIntersectable *>::
1205                const_iterator it = mBvhIntersectables.find(node);
1206
1207        if (it != mBvhIntersectables.end())
1208        {
1209                return (*it).second;
1210        }
1211
1212        // not in map => create new entry
1213        BvhIntersectable *bvhObj = new BvhIntersectable(node);
1214        mBvhIntersectables[node] = bvhObj;
1215
1216        return bvhObj;
1217}
1218
1219
1220bool BvHierarchy::Export(OUT_STREAM &stream)
1221{
1222        ExportNode(mRoot, stream);
1223
1224        return true;
1225}
1226
1227
1228void BvHierarchy::ExportObjects(BvhLeaf *leaf, OUT_STREAM &stream)
1229{
1230        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
1231        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
1232        {
1233                stream << (*oit)->GetId() << " ";
1234        }
1235}
1236
1237
1238void BvHierarchy::ExportNode(BvhNode *node, OUT_STREAM &stream)
1239{
1240        if (node->IsLeaf())
1241        {
1242                BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(node);
1243                const AxisAlignedBox3 box = leaf->GetBoundingBox();
1244                stream << "<Leaf"
1245                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1246                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\""
1247                           << " objects=\"";
1248               
1249                //-- export objects
1250                ExportObjects(leaf, stream);
1251               
1252                stream << "\" />" << endl;
1253        }
1254        else
1255        {       
1256                BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1257                const AxisAlignedBox3 box = interior->GetBoundingBox();
1258
1259                stream << "<Interior"
1260                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1261                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z
1262                           << "\">" << endl;
1263
1264                ExportNode(interior->GetBack(), stream);
1265                ExportNode(interior->GetFront(), stream);
1266
1267                stream << "</Interior>" << endl;
1268        }
1269}
1270
1271
1272float BvHierarchy::EvalViewCellsVolume(const ObjectContainer &objects) const
1273{
1274        float vol = 0;
1275
1276        ViewCellContainer viewCells;
1277        CollectViewCells(objects, viewCells);
1278
1279        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1280
1281        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1282        {
1283                vol += (*vit)->GetVolume();
1284        }
1285
1286        return vol;
1287}
1288
1289void BvHierarchy::CreateRoot(const ObjectContainer &objects)
1290{
1291        //-- create new root
1292        AxisAlignedBox3 box = ComputeBoundingBox(objects);
1293        BvhLeaf *bvhleaf = new BvhLeaf(box, NULL, (int)objects.size());
1294        bvhleaf->mObjects = objects;
1295
1296        mRoot = bvhleaf;
1297
1298        // associate root with current objects
1299        AssociateObjectsWithLeaf(bvhleaf);
1300}
1301
1302
1303SubdivisionCandidate *BvHierarchy::PrepareConstruction(const VssRayContainer &sampleRays,
1304                                                                                                           const ObjectContainer &objects)
1305{
1306        mBvhStats.Reset();
1307        mBvhStats.Start();
1308        mBvhStats.nodes = 1;
1309
1310        // note matt: we assume that we have objects sorted by their id
1311
1312        // store pointer to this tree
1313        BvhSubdivisionCandidate::sBvHierarchy = this;
1314        mBvhStats.nodes = 1;
1315
1316        // compute bounding box from objects
1317        // note: we assume that root was already created
1318        mBoundingBox = mRoot->GetBoundingBox();
1319        BvhLeaf *bvhleaf = dynamic_cast<BvhLeaf *>(mRoot);
1320
1321        mTermMinProbability *= mBoundingBox.GetVolume();
1322        mGlobalCostMisses = 0;
1323       
1324        // only rays intersecting objects in node are interesting
1325        AssociateObjectsWithRays(sampleRays);
1326       
1327        // probabilty is voume of all "seen" view cells
1328#if 1
1329        const float prop = EvalViewCellsVolume(objects);
1330#else
1331        const float prop = GetBoundingBox().GetVolume();
1332#endif
1333
1334        // create bvh traversal data
1335        BvhTraversalData oData(bvhleaf, 0, mBoundingBox, prop);
1336
1337        //-- add first candidate for object space partition     
1338        BvhSubdivisionCandidate *oSubdivisionCandidate =
1339                new BvhSubdivisionCandidate(oData);
1340
1341        EvalSubdivisionCandidate(*oSubdivisionCandidate);
1342        bvhleaf->SetSubdivisionCandidate(oSubdivisionCandidate);
1343
1344        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
1345        mTotalCost = (float)objects.size() * prop / viewSpaceVol;
1346
1347        PrintSubdivisionStats(*oSubdivisionCandidate);
1348
1349        return oSubdivisionCandidate;
1350}
1351
1352
1353bool BvHierarchy::AddLeafToPvs(BvhLeaf *leaf,
1354                                                           ViewCell *vc,
1355                                                           const float pdf,
1356                                                           float &contribution)
1357{
1358        // add kd intersecable to pvs
1359        BvhIntersectable *bvhObj = GetOrCreateBvhIntersectable(leaf);
1360       
1361        return vc->AddPvsSample(bvhObj, pdf, contribution);
1362}
1363
1364
1365void BvhStatistics::Print(ostream &app) const
1366{
1367        app << "=========== BvHierarchy statistics ===============\n";
1368
1369        app << setprecision(4);
1370
1371        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
1372
1373        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
1374
1375        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
1376
1377        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
1378
1379        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits << endl;
1380
1381        app << "#N_PMINDEPTHLEAVES ( Percentage of leaves at minimum depth )\n"
1382                <<      minDepthNodes * 100 / (double)Leaves() << endl;
1383
1384        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
1385                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
1386
1387        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
1388                << maxCostNodes * 100 / (double)Leaves() << endl;
1389
1390        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
1391                << minProbabilityNodes * 100 / (double)Leaves() << endl;
1392
1393        app << "#N_PMINOBJECTSLEAVES  ( Percentage of leaves with mininum objects )\n"
1394                << minObjectsNodes * 100 / (double)Leaves() << endl;
1395
1396        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
1397
1398        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
1399
1400        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
1401
1402        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
1403
1404        app << "#N_MAXOBJECTREFS  ( Max number of object refs / leaf )\n" << maxObjectRefs << "\n";
1405
1406        //app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl;
1407       
1408        app << "========== END OF VspTree statistics ==========\n";
1409}
1410
1411
1412}
Note: See TracBrowser for help on using the repository browser.