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

Revision 1302, 36.6 KB checked in by mattausch, 18 years ago (diff)
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                tQueue.Push(frontCandidate);
384                tQueue.Push(backCandidate);
385
386                // delete old leaf node
387                //DEL_PTR(tData.mNode);
388        }
389
390
391        //-- terminate traversal
392    if (newNode->IsLeaf())
393        {
394                //-- store additional info
395                EvaluateLeafStats(tData);
396       
397                const bool mStoreRays = true;
398                if (mStoreRays)
399                {
400                        BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(newNode);
401                        CollectRays(leaf->mObjects, leaf->mVssRays);
402                }
403
404                // detach node so it won't get deleted
405                tData.mNode = NULL;
406        }
407       
408        return newNode;
409}
410
411
412void BvHierarchy::EvalSubdivisionCandidate(BvhSubdivisionCandidate &splitCandidate)
413{
414        // compute best object partition
415        const float ratio =     SelectObjectPartition(
416                                                        splitCandidate.mParentData,
417                                                        splitCandidate.mFrontObjects,
418                                                        splitCandidate.mBackObjects);
419       
420        BvhLeaf *leaf = splitCandidate.mParentData.mNode;
421
422        // cost ratio violated?
423        const bool maxCostRatioViolated = mTermMaxCostRatio < ratio;
424
425        splitCandidate.mMaxCostMisses = maxCostRatioViolated ?
426                splitCandidate.mParentData.mMaxCostMisses + 1 :
427                splitCandidate.mParentData.mMaxCostMisses;
428
429        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
430        const float oldProp = EvalViewCellsVolume(leaf->mObjects);
431        const float oldProp2 = splitCandidate.mParentData.mProbability; //Debug << "here8 " << (oldProp - oldProp2) / viewSpaceVol << "  " << oldProp  / viewSpaceVol << " " << oldProp2  / viewSpaceVol << endl;
432
433        const float oldRenderCost = oldProp * (float)leaf->mObjects.size() / viewSpaceVol;
434
435        // compute global decrease in render cost
436        float newRenderCost = EvalRenderCost(splitCandidate.mParentData,
437                                                                             splitCandidate.mFrontObjects,
438                                                                                 splitCandidate.mBackObjects);
439
440        newRenderCost /=  viewSpaceVol;
441
442        const float renderCostDecr = oldRenderCost - newRenderCost;
443
444        Debug << "\nbvh render cost decr: " << renderCostDecr << endl;
445        splitCandidate.SetRenderCostDecrease(renderCostDecr);
446
447#if 1
448        const float priority = (float)-splitCandidate.mParentData.mDepth;
449#else   
450        // take render cost of node into account
451        // otherwise danger of being stuck in a local minimum!!
452        const float factor = mRenderCostDecreaseWeight;
453        const float priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
454#endif
455
456        // compute global decrease in render cost
457        splitCandidate.SetPriority(priority);
458}
459
460
461inline bool BvHierarchy::LocalTerminationCriteriaMet(const BvhTraversalData &data) const
462{
463        // matt: TODO
464        return ( 0
465                //|| ((int)data.mNode->mObjects.size() < mTermMinObjects)
466                //|| (data.mProbability <= mTermMinProbability)
467                //|| (data.mDepth >= mTermMaxDepth)
468                 );
469}
470
471
472inline bool BvHierarchy::GlobalTerminationCriteriaMet(const BvhTraversalData &data) const
473{
474        // matt: TODO
475        return (0
476                || (mBvhStats.Leaves() >= mTermMaxLeaves)
477                //|| (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
478                //|| mOutOfMemory
479                );
480}
481
482
483void BvHierarchy::EvaluateLeafStats(const BvhTraversalData &data)
484{
485        // the node became a leaf -> evaluate stats for leafs
486        BvhLeaf *leaf = data.mNode;
487       
488        ++ mCreatedLeaves;
489
490        if (data.mDepth >= mTermMaxDepth)
491        {
492        ++ mBvhStats.maxDepthNodes;
493                //Debug << "new max depth: " << mVspStats.maxDepthNodes << endl;
494        }
495
496        if (data.mDepth < mTermMaxDepth)
497        {
498        ++ mBvhStats.minDepthNodes;
499        }
500
501        if (data.mProbability <= mTermMinProbability)
502                ++ mBvhStats.minProbabilityNodes;
503       
504        // accumulate depth to compute average depth
505        mBvhStats.accumDepth += data.mDepth;
506 
507        if ((int)(leaf->mObjects.size()) < mTermMinObjects)
508             ++ mBvhStats.minObjectsNodes;
509 
510        if ((int)(leaf->mObjects.size()) > mBvhStats.maxObjectRefs)
511                mBvhStats.maxObjectRefs = (int)leaf->mObjects.size();
512}
513
514
515#if 0
516float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
517                                                                                        const int axis,
518                                                                                        ObjectContainer &objectsFront,
519                                                                                        ObjectContainer &objectsBack)
520{
521        const float maxBox = tData.mBoundingBox.Max(axis);
522        const float minBox = tData.mBoundingBox.Min(axis);
523
524        float midPoint = (maxBox + minBox) * 0.5f;
525
526        ObjectContainer::const_iterator oit, oit_end = tData.mNode->mObjects.end();
527       
528        for (oit = tData.mNode->mObjects.begin(); oit != oit_end; ++ oit)
529        {
530                Intersectable *obj = *oit;
531                const AxisAlignedBox3 box = obj->GetBox();
532
533                const float objMid = (box.Max(axis) + box.Min(axis)) * 0.5f;
534
535                // object mailed => belongs to back objects
536                if (objMid < midPoint)
537                        objectsBack.push_back(obj);
538                else
539                        objectsFront.push_back(obj);
540        }
541
542        const float oldRenderCost = tData.mProbability * (float)tData.mNode->mObjects.size();
543        const float newRenderCost =
544                EvalRenderCost(tData, objectsFront, objectsBack);
545
546        const float ratio = newRenderCost / oldRenderCost;
547        return ratio;
548}
549
550#else
551
552float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
553                                                                                        const int axis,
554                                                                                        ObjectContainer &objectsFront,
555                                                                                        ObjectContainer &objectsBack)
556{
557        SortSubdivisionCandidates(tData, axis);
558       
559        vector<SortableEntry>::const_iterator cit, cit_end = mSubdivisionCandidates->end();
560
561        int i = 0;
562        const int border = (int)tData.mNode->mObjects.size() / 2;
563
564    for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ i)
565        {
566                Intersectable *obj = (*cit).mObject;
567
568                // object mailed => belongs to back objects
569                if (i < border)
570                        objectsBack.push_back(obj);
571                else
572                        objectsFront.push_back(obj);
573        }
574
575        const float oldProp = EvalViewCellsVolume(tData.mNode->mObjects);
576        //const float oldProp2 = tData.mProbability; Debug << "here65 " << oldProp - oldProp2 << endl;
577
578        const float oldRenderCost = oldProp * (float)tData.mNode->mObjects.size();
579        const float newRenderCost = EvalRenderCost(tData, objectsFront, objectsBack);
580
581        const float ratio = newRenderCost / oldRenderCost;
582        return ratio;
583}
584#endif
585
586
587float BvHierarchy::EvalLocalCostHeuristics(const BvhTraversalData &tData,
588                                                                                   const int axis,
589                                                                                   ObjectContainer &objectsFront,
590                                                                                   ObjectContainer &objectsBack)
591{
592        // prepare the heuristics by setting mailboxes and counters.
593        const float totalVol = PrepareHeuristics(tData, axis);
594
595        // go through the lists, count the number of objects left and right
596        // and evaluate the cost funcion
597
598        // local helper variables
599        float volLeft = 0;
600        float volRight = totalVol;
601
602        int nObjectsLeft = 0;
603
604        const int nTotalObjects = (int)tData.mNode->mObjects.size();
605        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
606
607        vector<SortableEntry>::const_iterator currentPos =
608                mSubdivisionCandidates->begin();
609
610        /////////////////////////////////
611        // the parameters for the current optimum
612
613        float volBack = volLeft;
614        float volFront = volRight;
615
616        float newRenderCost = nTotalObjects * totalVol;
617
618
619        /////////////////////////////
620        // the sweep heuristics
621       
622        //-- traverse through events and find best split plane
623
624        vector<SortableEntry>::const_iterator cit, cit_end = mSubdivisionCandidates->end();
625
626        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit)
627        {
628                Intersectable *object = (*cit).mObject;
629               
630                // evaluate change in l and r volume
631                // voll = view cells that see only left node (i.e., left pvs)
632                // volr = view cells that see only right node (i.e., right pvs)
633                EvalHeuristicsContribution(object, volLeft, volRight);
634
635                ++ nObjectsLeft;
636               
637                const int nObjectsRight = nTotalObjects - nObjectsLeft;
638
639                // the heuristics
640            const float sum = volLeft * (float)nObjectsLeft +
641                                                  volRight * (float)nObjectsRight;
642
643                if (sum < newRenderCost)
644                {
645                        newRenderCost = sum;
646
647                        volBack = volLeft;
648                        volFront = volRight;
649
650                        // objects belongs to left side now
651                        for (; currentPos != (cit + 1); ++ currentPos);
652                }
653        }
654
655        //-- assign object to front and back volume
656
657        // belongs to back bv
658        for (cit = mSubdivisionCandidates->begin(); cit != currentPos; ++ cit)
659                objectsBack.push_back((*cit).mObject);
660       
661        // belongs to front bv
662        for (cit = currentPos; cit != cit_end; ++ cit)
663                objectsFront.push_back((*cit).mObject);
664
665        tData.mNode->mObjects.end();
666
667        const float oldRenderCost = (float)nTotalObjects * totalVol + Limits::Small;
668        // the relative cost ratio
669        const float ratio = newRenderCost / oldRenderCost;
670
671        Debug << "\n§§§§ eval local cost §§§§" << endl
672                  << "back pvs: " << (int)objectsBack.size() << " front pvs: " << (int)objectsFront.size() << " total pvs: " << nTotalObjects << endl
673                  << "back p: " << volBack / viewSpaceVol << " front p " << volFront / viewSpaceVol << " p: " << totalVol / viewSpaceVol << endl
674                  << "old rc: " << oldRenderCost / viewSpaceVol << " new rc: " << newRenderCost / viewSpaceVol << endl
675                  << "render cost decrease: " << oldRenderCost / viewSpaceVol - newRenderCost / viewSpaceVol << endl;
676
677        return ratio;
678}
679
680
681void BvHierarchy::SortSubdivisionCandidates(const BvhTraversalData &tData,
682                                                                                        const int axis)                                                                                 
683{
684        mSubdivisionCandidates->clear();
685
686        //RayInfoContainer *rays = tData.mRays;
687        BvhLeaf *leaf = tData.mNode;
688
689        // compute requested size
690        const int requestedSize = (int)leaf->mObjects.size() * 2;
691       
692        // creates a sorted split candidates array
693        if (mSubdivisionCandidates->capacity() > 500000 &&
694                requestedSize < (int)(mSubdivisionCandidates->capacity() / 10) )
695        {
696        delete mSubdivisionCandidates;
697                mSubdivisionCandidates = new vector<SortableEntry>;
698        }
699
700        mSubdivisionCandidates->reserve(requestedSize);
701
702        //-- insert object queries
703        //-- These queries can induce a change in pvs size.
704        //-- Note that they cannot induce a change in view cell volume, as
705        //-- there is no ray associated with these events!!
706
707        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
708
709        for (oit = leaf->mObjects.begin(); oit < oit_end; ++ oit)
710        {
711                Intersectable *obj = *oit;
712               
713                Intersectable *object = *oit;
714                const AxisAlignedBox3 &box = object->GetBox();
715                const float midPt = (box.Min(axis) + box.Max(axis)) * 0.5f;
716
717                mSubdivisionCandidates->push_back(SortableEntry(object, midPt));
718        }
719
720        stable_sort(mSubdivisionCandidates->begin(), mSubdivisionCandidates->end());
721}
722
723
724const BvhStatistics &BvHierarchy::GetStatistics() const
725{
726        return mBvhStats;
727}
728
729
730float BvHierarchy::PrepareHeuristics(const BvhTraversalData &tData, const int axis)
731{       
732        //-- sort so we can use a sweep from right to left
733        SortSubdivisionCandidates(tData, axis);
734
735        float vol = 0;
736        BvhLeaf *leaf = tData.mNode;
737
738        // collect and mark the view cells as belonging to front pvs
739        ViewCellContainer viewCells;
740        CollectViewCells(tData.mNode->mObjects, viewCells, true);
741
742    ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
743
744        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
745        {
746                vol += (*vit)->GetVolume();
747        }
748
749        // mail view cells on the left side
750        ViewCell::NewMail();
751        // mail the objects on the left side
752        Intersectable::NewMail();
753
754        return vol;
755}
756///////////////////////////////////////////////////////////
757
758
759void BvHierarchy::EvalHeuristicsContribution(Intersectable *obj,
760                                                                                         float &volLeft,
761                                                                                         float &volRight)
762{
763        // collect all view cells associated with this objects
764        // (also multiple times, if they are pierced by several rays)
765
766        ViewCellContainer viewCells;
767       
768        const bool useMailboxing = false;
769        CollectViewCells(obj, viewCells, useMailboxing);
770
771
772        /// classify view cells and compute volume contri accordingly
773        /// possible view cell classifications:
774        /// view cell mailed => view cell can be seen from left child node
775        /// view cell counter > 0 view cell can be seen from right child node
776        /// combined: view cell volume belongs to both nodes
777        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
778       
779        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
780        {
781                // view cells can also be seen from left child node
782                ViewCell *viewCell = *vit;
783
784                const float vol = viewCell->GetVolume();
785
786                if (!viewCell->Mailed())
787                {
788                        viewCell->Mail();
789
790                        // we now see view cell from both nodes
791                        // => add volume to left node
792                        volLeft += vol;
793                }
794
795                // last reference into the right node
796                if (-- viewCell->mCounter == 0)
797                {
798                        // view cell was previously seen from both nodes  =>
799                        // remove volume from right node
800                        volRight -= vol;
801                }
802        }
803}
804
805
806void BvHierarchy::SetViewCellsManager(ViewCellsManager *vcm)
807{
808        mViewCellsManager = vcm;
809}
810
811
812AxisAlignedBox3 BvHierarchy::GetBoundingBox() const
813{
814        return mBoundingBox;
815}
816
817
818float BvHierarchy::SelectObjectPartition(const BvhTraversalData &tData,
819                                                                                 ObjectContainer &frontObjects,
820                                                                                 ObjectContainer &backObjects)
821{
822        ObjectContainer nFrontObjects[3];
823        ObjectContainer nBackObjects[3];
824
825        float nCostRatio[3];
826
827        // create bounding box of node geometry
828        AxisAlignedBox3 box = tData.mBoundingBox;
829               
830        int sAxis = 0;
831        int bestAxis = -1;
832
833        if (mOnlyDrivingAxis)
834        {
835                sAxis = box.Size().DrivingAxis();
836        }
837       
838        // -- evaluate split cost for all three axis
839       
840        for (int axis = 0; axis < 3; ++ axis)
841        {
842                if (!mOnlyDrivingAxis || (axis == sAxis))
843                {
844                        if (mUseCostHeuristics)
845                        {
846                                //-- partition objects using heuristics
847                                nCostRatio[axis] =
848                                        EvalLocalCostHeuristics(
849                                                                                        tData,
850                                                                                        axis,
851                                                                                        nFrontObjects[axis],
852                                                                                        nBackObjects[axis]);
853                        }
854                        else
855                        {
856                                nCostRatio[axis] =
857                                        EvalLocalObjectPartition(
858                                                                                         tData,
859                                                                                         axis,
860                                                                                         nFrontObjects[axis],
861                                                                                         nBackObjects[axis]);
862                        }
863
864                        if (bestAxis == -1)
865                        {
866                                bestAxis = axis;
867                        }
868                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
869                        {
870                                bestAxis = axis;
871                        }
872                }
873        }
874
875        //-- assign values
876
877        frontObjects = nFrontObjects[bestAxis];
878        backObjects = nBackObjects[bestAxis];
879
880        //Debug << "val: " << nCostRatio[bestAxis] << " axis: " << bestAxis << endl;
881        return nCostRatio[bestAxis];
882}
883
884
885void BvHierarchy::AssociateObjectsWithRays(const VssRayContainer &rays)
886{
887
888        VssRayContainer::const_iterator rit, rit_end = rays.end();
889
890    for (rit = rays.begin(); rit != rays.end(); ++ rit)
891        {
892                VssRay *ray = (*rit);
893
894                if (ray->mTerminationObject)
895                {
896                        ray->mTerminationObject->mVssRays.push_back(ray);
897                }
898
899                if (0 && ray->mOriginObject)
900                {
901                        ray->mOriginObject->mVssRays.push_back(ray);
902                }
903        }
904}
905
906
907void BvHierarchy::PrintSubdivisionStats(const SubdivisionCandidate &sc)
908{
909        const float costDecr = sc.GetRenderCostDecrease();     
910
911        mSubdivisionStats
912                        << "#Leaves\n" << mBvhStats.Leaves()
913                        << "#RenderCostDecrease\n" << costDecr << endl
914                        << "#TotalRenderCost\n" << mTotalCost << endl;
915                        //<< "#AvgRenderCost\n" << avgRenderCost << endl;
916}
917
918
919void BvHierarchy::CollectRays(const ObjectContainer &objects,
920                                                          VssRayContainer &rays) const
921{
922        VssRay::NewMail();
923       
924        ObjectContainer::const_iterator oit, oit_end = objects.end();
925
926        // evaluate reverse pvs and view cell volume on left and right cell
927        // note: should I take all leaf objects or rather the objects hit by rays?
928        for (oit = objects.begin(); oit != oit_end; ++ oit)
929        {
930                Intersectable *obj = *oit;
931               
932                VssRayContainer::const_iterator rit, rit_end = obj->mVssRays.end();
933
934                for (rit = obj->mVssRays.begin(); rit < rit_end; ++ rit)
935                {
936                        VssRay *ray = (*rit);
937
938                        if (!ray->Mailed())
939                        {
940                                ray->Mail();
941                                rays.push_back(ray);
942                        }
943                }
944        }
945}
946
947
948float BvHierarchy::EvalRenderCost(const BvhTraversalData &tData,
949                                                                  const ObjectContainer &objectsFront,
950                                                                  const ObjectContainer &objectsBack) const
951{
952        BvhLeaf *leaf = tData.mNode;
953
954        // probability that view point lies in a view cell which sees this node
955        const float pFront = EvalViewCellsVolume(objectsFront);
956        const float pBack = EvalViewCellsVolume(objectsBack);
957               
958        const int totalObjects = (int)leaf->mObjects.size();
959        const int nObjectsFront = (int)objectsFront.size();
960        const int nObjectsBack = (int)objectsBack.size();
961
962        //-- pvs rendering heuristics
963        const float newRenderCost = nObjectsFront * pFront + nObjectsBack * pBack;
964        /*
965        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
966        Debug << "\nbvh render cost\n"
967                  << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << endl
968                  << "new rc: " << newRenderCost / viewSpaceVol << endl;*/
969
970        return newRenderCost;
971}
972
973
974AxisAlignedBox3 BvHierarchy::ComputeBoundingBox(const ObjectContainer &objects,
975                                                                                                const AxisAlignedBox3 *parentBox)
976{
977        if (parentBox && objects.empty())
978                return *parentBox;
979
980        AxisAlignedBox3 box;
981        box.Initialize();
982
983        ObjectContainer::const_iterator oit, oit_end = objects.end();
984
985        //-- compute bounding box
986        for (oit = objects.begin(); oit != oit_end; ++ oit)
987        {
988                Intersectable *obj = *oit;
989
990                // compute bounding box of view space
991                box.Include(obj->GetBox());
992        }
993
994        return box;
995}
996
997
998void BvHierarchy::CollectLeaves(vector<BvhLeaf *> &leaves) const
999{
1000        stack<BvhNode *> nodeStack;
1001        nodeStack.push(mRoot);
1002
1003        while (!nodeStack.empty())
1004        {
1005                BvhNode *node = nodeStack.top();
1006                nodeStack.pop();
1007
1008                if (node->IsLeaf())
1009                {
1010                        BvhLeaf *leaf = (BvhLeaf *)node;
1011                        leaves.push_back(leaf);
1012                }
1013                else
1014                {
1015                        BvhInterior *interior = (BvhInterior *)node;
1016
1017                        nodeStack.push(interior->GetBack());
1018                        nodeStack.push(interior->GetFront());
1019                }
1020        }
1021}
1022
1023
1024AxisAlignedBox3 BvHierarchy::GetBoundingBox(BvhNode *node) const
1025{
1026        return node->GetBoundingBox();
1027}
1028
1029
1030void BvHierarchy::CollectViewCells(const ObjectContainer &objects,
1031                                                                   ViewCellContainer &viewCells,
1032                                                                   const bool setCounter) const
1033{
1034        ViewCell::NewMail();
1035        ObjectContainer::const_iterator oit, oit_end = objects.end();
1036
1037        // loop through all object and collect view cell pvs of this node
1038        for (oit = objects.begin(); oit != oit_end; ++ oit)
1039        {
1040                CollectViewCells(*oit, viewCells, true, setCounter);
1041        }
1042}
1043
1044
1045void BvHierarchy::CollectViewCells(Intersectable *obj,
1046                                                                   ViewCellContainer &viewCells,
1047                                                                   const bool useMailBoxing,
1048                                                                   const bool setCounter) const
1049{
1050        VssRayContainer::const_iterator rit, rit_end = obj->mVssRays.end();
1051
1052        for (rit = obj->mVssRays.begin(); rit < rit_end; ++ rit)
1053        {
1054                VssRay *ray = (*rit);
1055                ViewCellContainer tmpViewCells;
1056       
1057                mVspTree->GetViewCells(*ray, tmpViewCells);
1058
1059                ViewCellContainer::const_iterator vit, vit_end = tmpViewCells.end();
1060
1061                for (vit = tmpViewCells.begin(); vit != vit_end; ++ vit)
1062                {
1063                        VspViewCell *vc = dynamic_cast<VspViewCell *>(*vit);
1064
1065                        // store view cells
1066                        if (!useMailBoxing || !vc->Mailed())
1067                        {
1068                                if (useMailBoxing)
1069                                {
1070                                        vc->Mail();
1071                                        if (setCounter)
1072                                                vc->mCounter = 0;
1073                                }
1074                               
1075                                viewCells.push_back(vc);
1076                        }
1077                       
1078                        if (setCounter)
1079                        {
1080                                ++ vc->mCounter;
1081                        }
1082                }
1083        }
1084}
1085
1086
1087void BvHierarchy::CollectDirtyCandidates(BvhSubdivisionCandidate *sc,
1088                                                                                 vector<SubdivisionCandidate *> &dirtyList)
1089{
1090        BvhTraversalData &tData = sc->mParentData;
1091        BvhLeaf *node = tData.mNode;
1092       
1093        ViewCellContainer viewCells;
1094        CollectViewCells(node->mObjects, viewCells);
1095
1096        // split candidates handling
1097        // these view cells  are thrown into dirty list
1098        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1099
1100        Debug << "collecting " << (int)viewCells.size() << " dirty candidates" << endl;
1101
1102        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1103        {
1104                VspViewCell *vc = dynamic_cast<VspViewCell *>(*vit);
1105                VspLeaf *leaf = vc->mLeaf;
1106                SubdivisionCandidate *candidate = leaf->GetSubdivisionCandidate();
1107                Debug << "here100 candidate: " << candidate << " type: " << candidate->Type() << endl;
1108               
1109                dirtyList.push_back(leaf->GetSubdivisionCandidate());
1110        }
1111}
1112
1113
1114BvhNode *BvHierarchy::GetRoot() const
1115{
1116        return mRoot;
1117}
1118
1119
1120bool BvHierarchy::IsObjectInLeaf(BvhLeaf *leaf, Intersectable *object) const
1121{
1122        ObjectContainer::const_iterator oit =
1123                lower_bound(leaf->mObjects.begin(), leaf->mObjects.end(), object, ilt);
1124                               
1125        // objects sorted by id
1126        if ((oit != leaf->mObjects.end()) && ((*oit)->GetId() == object->GetId()))
1127        {
1128                return true;
1129        }
1130        else
1131        {
1132                return false;
1133        }
1134}
1135
1136
1137BvhLeaf *BvHierarchy::GetLeaf(Intersectable *object, BvhNode *node) const
1138{
1139        // rather use the simple version
1140        if (!object) return NULL;
1141        return object->mBvhLeaf;
1142       
1143        ///////////////////////////////////////
1144        // start from root of tree
1145       
1146        if (node == NULL)
1147                node = mRoot;
1148       
1149        vector<BvhLeaf *> leaves;
1150
1151        stack<BvhNode *> nodeStack;
1152        nodeStack.push(node);
1153 
1154        BvhLeaf *leaf = NULL;
1155 
1156        while (!nodeStack.empty()) 
1157        {
1158                BvhNode *node = nodeStack.top();
1159                nodeStack.pop();
1160       
1161                if (node->IsLeaf())
1162                {
1163                        leaf = dynamic_cast<BvhLeaf *>(node);
1164
1165                        if (IsObjectInLeaf(leaf, object))
1166                        {
1167                                return leaf;
1168                        }
1169                }
1170                else   
1171                {       
1172                        // find point
1173                        BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1174       
1175                        if (interior->GetBack()->GetBoundingBox().Includes(object->GetBox()))
1176                        {
1177                                nodeStack.push(interior->GetBack());
1178                        }
1179                       
1180                        // search both sides as we are using bounding volumes
1181                        if (interior->GetFront()->GetBoundingBox().Includes(object->GetBox()))
1182                        {
1183                                nodeStack.push(interior->GetFront());
1184                        }
1185                }
1186        }
1187 
1188        return leaf;
1189}
1190
1191
1192BvhIntersectable *BvHierarchy::GetOrCreateBvhIntersectable(BvhNode *node)
1193{
1194        // search nodes
1195        std::map<BvhNode *, BvhIntersectable *>::
1196                const_iterator it = mBvhIntersectables.find(node);
1197
1198        if (it != mBvhIntersectables.end())
1199        {
1200                return (*it).second;
1201        }
1202
1203        // not in map => create new entry
1204        BvhIntersectable *bvhObj = new BvhIntersectable(node);
1205        mBvhIntersectables[node] = bvhObj;
1206
1207        return bvhObj;
1208}
1209
1210
1211bool BvHierarchy::Export(OUT_STREAM &stream)
1212{
1213        ExportNode(mRoot, stream);
1214
1215        return true;
1216}
1217
1218
1219void BvHierarchy::ExportObjects(BvhLeaf *leaf, OUT_STREAM &stream)
1220{
1221        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
1222        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
1223        {
1224                stream << (*oit)->GetId() << " ";
1225        }
1226}
1227
1228
1229void BvHierarchy::ExportNode(BvhNode *node, OUT_STREAM &stream)
1230{
1231        if (node->IsLeaf())
1232        {
1233                BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(node);
1234                const AxisAlignedBox3 box = leaf->GetBoundingBox();
1235                stream << "<Leaf"
1236                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1237                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\""
1238                           << " objects=\"";
1239               
1240                //-- export objects
1241                ExportObjects(leaf, stream);
1242               
1243                stream << "\" />" << endl;
1244        }
1245        else
1246        {       
1247                BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1248                const AxisAlignedBox3 box = interior->GetBoundingBox();
1249
1250                stream << "<Interior"
1251                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1252                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z
1253                           << "\">" << endl;
1254
1255                ExportNode(interior->GetBack(), stream);
1256                ExportNode(interior->GetFront(), stream);
1257
1258                stream << "</Interior>" << endl;
1259        }
1260}
1261
1262
1263float BvHierarchy::EvalViewCellsVolume(const ObjectContainer &objects) const
1264{
1265        float vol = 0;
1266
1267        ViewCellContainer viewCells;
1268        CollectViewCells(objects, viewCells);
1269
1270        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1271
1272        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1273        {
1274                vol += (*vit)->GetVolume();
1275        }
1276
1277        return vol;
1278}
1279
1280void BvHierarchy::CreateRoot(const ObjectContainer &objects)
1281{
1282        //-- create new root
1283        AxisAlignedBox3 box = ComputeBoundingBox(objects);
1284        BvhLeaf *bvhleaf = new BvhLeaf(box, NULL, (int)objects.size());
1285        bvhleaf->mObjects = objects;
1286
1287        mRoot = bvhleaf;
1288
1289        // associate root with current objects
1290        AssociateObjectsWithLeaf(bvhleaf);
1291}
1292
1293
1294SubdivisionCandidate *BvHierarchy::PrepareConstruction(const VssRayContainer &sampleRays,
1295                                                                                                           const ObjectContainer &objects)
1296{
1297        // note matt: we assume that we have objects sorted by their id
1298
1299        // store pointer to this tree
1300        BvhSubdivisionCandidate::sBvHierarchy = this;
1301        mBvhStats.nodes = 1;
1302
1303        // compute bounding box from objects
1304        // note: we assume that root was already created
1305        mBoundingBox = mRoot->GetBoundingBox();
1306        BvhLeaf *bvhleaf = dynamic_cast<BvhLeaf *>(mRoot);
1307
1308        mTermMinProbability *= mBoundingBox.GetVolume();
1309        mGlobalCostMisses = 0;
1310       
1311        // only rays intersecting objects in node are interesting
1312        AssociateObjectsWithRays(sampleRays);
1313       
1314        // probabilty is voume of all "seen" view cells
1315#if 1
1316        const float prop = EvalViewCellsVolume(objects);
1317#else
1318        const float prop = GetBoundingBox().GetVolume();
1319#endif
1320
1321        // create bvh traversal data
1322        BvhTraversalData oData(bvhleaf, 0, mBoundingBox, prop);
1323
1324        //-- add first candidate for object space partition     
1325        BvhSubdivisionCandidate *oSubdivisionCandidate =
1326                new BvhSubdivisionCandidate(oData);
1327
1328        EvalSubdivisionCandidate(*oSubdivisionCandidate);
1329        bvhleaf->SetSubdivisionCandidate(oSubdivisionCandidate);
1330
1331        const float viewSpaceVol = mVspTree->GetBoundingBox().GetVolume();
1332        mTotalCost = (float)objects.size() * prop / viewSpaceVol;
1333
1334        PrintSubdivisionStats(*oSubdivisionCandidate);
1335
1336        return oSubdivisionCandidate;
1337}
1338
1339
1340bool BvHierarchy::AddLeafToPvs(BvhLeaf *leaf,
1341                                                           ViewCell *vc,
1342                                                           const float pdf,
1343                                                           float &contribution)
1344{
1345        // add kd intersecable to pvs
1346        BvhIntersectable *bvhObj = GetOrCreateBvhIntersectable(leaf);
1347       
1348        return vc->AddPvsSample(bvhObj, pdf, contribution);
1349}
1350
1351
1352void BvhStatistics::Print(ostream &app) const
1353{
1354        app << "=========== BvHierarchy statistics ===============\n";
1355
1356        app << setprecision(4);
1357
1358        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
1359
1360        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
1361
1362        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
1363
1364        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
1365
1366        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits << endl;
1367
1368        app << "#N_PMINDEPTHLEAVES ( Percentage of leaves at minimum depth )\n"
1369                <<      minDepthNodes * 100 / (double)Leaves() << endl;
1370
1371        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
1372                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
1373
1374        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
1375                << maxCostNodes * 100 / (double)Leaves() << endl;
1376
1377        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
1378                << minProbabilityNodes * 100 / (double)Leaves() << endl;
1379
1380        app << "#N_PMINOBJECTSLEAVES  ( Percentage of leaves with mininum objects )\n"
1381                << minObjectsNodes * 100 / (double)Leaves() << endl;
1382
1383        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
1384
1385        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
1386
1387        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
1388
1389        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
1390
1391        app << "#N_MAXOBJECTREFS  ( Max number of object refs / leaf )\n" << maxObjectRefs << "\n";
1392
1393        //app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl;
1394       
1395        app << "========== END OF VspTree statistics ==========\n";
1396}
1397
1398
1399}
Note: See TracBrowser for help on using the repository browser.