source: GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp @ 1692

Revision 1692, 78.4 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "ViewCell.h"
6#include "Plane3.h"
7#include "VspTree.h"
8#include "Mesh.h"
9#include "common.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellsManager.h"
17#include "Beam.h"
18#include "KdTree.h"
19#include "IntersectableWrapper.h"
20#include "HierarchyManager.h"
21#include "BvHierarchy.h"
22#include "OspTree.h"
23
24
25
26namespace GtpVisibilityPreprocessor {
27
28
29#define USE_FIXEDPOINT_T 0
30
31/////////////
32//-- static members
33
34VspTree *VspTree::VspSubdivisionCandidate::sVspTree = NULL;
35int VspNode::sMailId = 1;
36
37// variable for debugging volume contribution for heuristics
38static float debugVol;
39
40
41// pvs penalty can be different from pvs size
42inline static float EvalPvsPenalty(const int pvs,
43                                                                   const int lower,
44                                                                   const int upper)
45{
46        // clamp to minmax values
47        if (pvs < lower)
48        {
49                return (float)lower;
50        }
51        else if (pvs > upper)
52        {
53                return (float)upper;
54        }
55        return (float)pvs;
56}
57
58#if WORK_WITH_VIEWCELLS
59static bool ViewCellHasMultipleReferences(Intersectable *obj,
60                                                                                  ViewCell *vc,
61                                                                                  bool checkOnlyMailed)
62{
63        MailablePvsData *vdata = obj->mViewCellPvs.Find(vc);
64
65        if (vdata)
66        {
67                // more than one view cell sees this object inside different kd cells
68                if (!checkOnlyMailed || !vdata->Mailed())
69                {
70                        if (checkOnlyMailed)
71                                vdata->Mail();
72                        //Debug << "sumpdf: " << vdata->mSumPdf << endl;
73                        if (vdata->mSumPdf > 1.5f)
74                                return true;
75                }
76        }
77       
78        return false;
79}
80
81
82void VspTree::RemoveParentViewCellReferences(ViewCell *parent) const
83{
84        KdLeaf::NewMail();
85
86        // remove the parents from the object pvss
87        ObjectPvsMap::const_iterator oit, oit_end = parent->GetPvs().mEntries.end();
88
89        for (oit = parent->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
90        {
91                Intersectable *object = (*oit).first;
92                // HACK: make sure that the view cell is removed from the pvs
93                const float high_contri = 9999999;
94
95                // remove reference count of view cells
96                object->mViewCellPvs.RemoveSample(parent, high_contri);
97        }
98}
99
100
101void VspTree::AddViewCellReferences(ViewCell *vc) const
102{
103        KdLeaf::NewMail();
104
105        // Add front view cell to the object pvsss
106        ObjectPvsMap::const_iterator oit, oit_end = vc->GetPvs().mEntries.end();
107
108        for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
109        {
110                Intersectable *object = (*oit).first;
111
112                // increase reference count of view cells
113                object->mViewCellPvs.AddSample(vc, 1);
114        }
115}
116
117#endif
118
119void VspTreeStatistics::Print(ostream &app) const
120{
121        app << "=========== VspTree statistics ===============\n";
122
123        app << setprecision(4);
124
125        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
126
127        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
128
129        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
130
131        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
132
133        app << "#N_SPLITS ( Number of splits in axes x y z)\n";
134
135        for (int i = 0; i < 3; ++ i)
136                app << splits[i] << " ";
137
138        app << endl;
139
140        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
141                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
142
143        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
144                << minPvsNodes * 100 / (double)Leaves() << endl;
145
146        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
147                << minRaysNodes * 100 / (double)Leaves() << endl;
148
149        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
150                << maxCostNodes * 100 / (double)Leaves() << endl;
151
152        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
153                << minProbabilityNodes * 100 / (double)Leaves() << endl;
154
155        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
156                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
157
158        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
159
160        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
161
162        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
163
164        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
165
166        app << "#AVGRAYS (number of rays / leaf)\n" << AvgRays() << endl;
167       
168        app << "#N_GLOBALCOSTMISSES ( Global cost misses )\n" << mGlobalCostMisses << endl;
169
170        app << "========== END OF VspTree statistics ==========\n";
171}
172
173
174
175/******************************************************************/
176/*                  class VspNode implementation                  */
177/******************************************************************/
178
179
180VspNode::VspNode():
181mParent(NULL),
182mTreeValid(true),
183mTimeStamp(0),
184mRenderCostDecr(0),
185mMemoryIncr(0),
186mPvsEntriesIncr(0)
187{}
188
189
190VspNode::VspNode(VspInterior *parent):
191mParent(parent),
192mTreeValid(true),
193mMemoryIncr(0),
194mRenderCostDecr(0),
195mPvsEntriesIncr(0),
196mTimeStamp(0)
197{}
198
199
200bool VspNode::IsRoot() const
201{
202        return mParent == NULL;
203}
204
205
206VspInterior *VspNode::GetParent()
207{
208        return mParent;
209}
210
211
212void VspNode::SetParent(VspInterior *parent)
213{
214        mParent = parent;
215}
216
217
218bool VspNode::IsSibling(VspNode *n) const
219{
220        return  ((this != n) && mParent &&
221                         (mParent->GetFront() == n) || (mParent->GetBack() == n));
222}
223
224
225int VspNode::GetDepth() const
226{
227        int depth = 0;
228        VspNode *p = mParent;
229       
230        while (p)
231        {
232                p = p->mParent;
233                ++ depth;
234        }
235
236        return depth;
237}
238
239
240bool VspNode::TreeValid() const
241{
242        return mTreeValid;
243}
244
245
246void VspNode::SetTreeValid(const bool v)
247{
248        mTreeValid = v;
249}
250
251
252
253/****************************************************************/
254/*              class VspInterior implementation                */
255/****************************************************************/
256
257
258VspInterior::VspInterior(const AxisAlignedPlane &plane):
259mPlane(plane), mFront(NULL), mBack(NULL)
260{}
261
262
263VspInterior::~VspInterior()
264{
265        DEL_PTR(mFront);
266        DEL_PTR(mBack);
267}
268
269
270bool VspInterior::IsLeaf() const
271{
272        return false;
273}
274
275
276VspNode *VspInterior::GetBack()
277{
278        return mBack;
279}
280
281
282VspNode *VspInterior::GetFront()
283{
284        return mFront;
285}
286
287
288AxisAlignedPlane VspInterior::GetPlane() const
289{
290        return mPlane;
291}
292
293
294float VspInterior::GetPosition() const
295{
296        return mPlane.mPosition;
297}
298
299
300int VspInterior::GetAxis() const
301{
302        return mPlane.mAxis;
303}
304
305
306void VspInterior::ReplaceChildLink(VspNode *oldChild, VspNode *newChild)
307{
308        if (mBack == oldChild)
309                mBack = newChild;
310        else
311                mFront = newChild;
312}
313
314
315void VspInterior::SetupChildLinks(VspNode *front, VspNode *back)
316{
317    mBack = back;
318    mFront = front;
319}
320
321
322AxisAlignedBox3 VspInterior::GetBoundingBox() const
323{
324        return mBoundingBox;
325}
326
327
328void VspInterior::SetBoundingBox(const AxisAlignedBox3 &box)
329{
330        mBoundingBox = box;
331}
332
333
334int VspInterior::Type() const
335{
336        return Interior;
337}
338
339
340
341/****************************************************************/
342/*                  class VspLeaf implementation                */
343/****************************************************************/
344
345
346VspLeaf::VspLeaf():
347mViewCell(NULL), mPvs(NULL), mSubdivisionCandidate(NULL)
348{
349}
350
351
352VspLeaf::~VspLeaf()
353{
354        DEL_PTR(mPvs);
355
356        VssRayContainer::const_iterator vit, vit_end = mVssRays.end();
357        for (vit = mVssRays.begin(); vit != vit_end; ++ vit)
358        {
359                VssRay *ray = *vit;
360                ray->Unref();
361
362                if (!ray->IsActive())
363                        delete ray;
364        }
365        //CLEAR_CONTAINER(mVssRays);
366}
367
368
369int VspLeaf::Type() const
370{
371        return Leaf;
372}
373
374
375VspLeaf::VspLeaf(ViewCellLeaf *viewCell):
376mViewCell(viewCell)
377{
378}
379
380
381VspLeaf::VspLeaf(VspInterior *parent):
382VspNode(parent), mViewCell(NULL), mPvs(NULL)
383{}
384
385
386VspLeaf::VspLeaf(VspInterior *parent, ViewCellLeaf *viewCell):
387VspNode(parent), mViewCell(viewCell), mPvs(NULL)
388{
389}
390
391
392ViewCellLeaf *VspLeaf::GetViewCell() const
393{
394        return mViewCell;
395}
396
397
398void VspLeaf::SetViewCell(ViewCellLeaf *viewCell)
399{
400        mViewCell = viewCell;
401}
402
403
404bool VspLeaf::IsLeaf() const
405{
406        return true;
407}
408
409
410
411/*************************************************************************/
412/*                       class VspTree implementation                    */
413/*************************************************************************/
414
415
416VspTree::VspTree():
417mRoot(NULL),
418mOutOfBoundsCell(NULL),
419mStoreRays(false),
420mTimeStamp(1),
421mHierarchyManager(NULL)
422{
423        mLocalSubdivisionCandidates = new vector<SortableEntry>;
424
425        bool randomize = false;
426        Environment::GetSingleton()->GetBoolValue("VspTree.Construction.randomize", randomize);
427        if (randomize)
428                Randomize(); // initialise random generator for heuristics
429
430        char subdivisionStatsLog[100];
431        Environment::GetSingleton()->GetStringValue("VspTree.subdivisionStats", subdivisionStatsLog);
432        mSubdivisionStats.open(subdivisionStatsLog);
433
434        /////////////
435        //-- termination criteria for autopartition
436
437        Environment::GetSingleton()->GetIntValue("VspTree.Termination.maxDepth", mTermMaxDepth);
438        Environment::GetSingleton()->GetIntValue("VspTree.Termination.minPvs", mTermMinPvs);
439        Environment::GetSingleton()->GetIntValue("VspTree.Termination.minRays", mTermMinRays);
440        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.minProbability", mTermMinProbability);
441        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.maxRayContribution", mTermMaxRayContribution);
442       
443        Environment::GetSingleton()->GetIntValue("VspTree.Termination.missTolerance", mTermMissTolerance);
444        Environment::GetSingleton()->GetIntValue("VspTree.Termination.maxViewCells", mMaxViewCells);
445        // max cost ratio for early tree termination
446        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.maxCostRatio", mTermMaxCostRatio);
447
448        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
449        Environment::GetSingleton()->GetIntValue("VspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
450
451        Environment::GetSingleton()->GetFloatValue("VspTree.maxStaticMemory", mMaxMemory);
452
453
454        //////////////
455        //-- factors for bsp tree split plane heuristics
456
457        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.ct_div_ci", mCtDivCi);
458        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.epsilon", mEpsilon);
459        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.minBand", mMinBand);
460        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.maxBand", mMaxBand);
461        Environment::GetSingleton()->GetIntValue("VspTree.maxTests", mMaxTests);
462
463        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
464       
465        // if only the driving axis is used for axis aligned split
466        Environment::GetSingleton()->GetBoolValue("VspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
467        Environment::GetSingleton()->GetBoolValue("VspTree.useCostHeuristics", mUseCostHeuristics);
468        Environment::GetSingleton()->GetBoolValue("VspTree.simulateOctree", mCirculatingAxis);
469
470
471        //////////////
472        //-- debug output
473
474        Debug << "******* VSP options ******** " << endl;
475
476    Debug << "max depth: " << mTermMaxDepth << endl;
477        Debug << "min PVS: " << mTermMinPvs << endl;
478        Debug << "min probabiliy: " << mTermMinProbability << endl;
479        Debug << "min rays: " << mTermMinRays << endl;
480        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
481        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
482        Debug << "miss tolerance: " << mTermMissTolerance << endl;
483        Debug << "max view cells: " << mMaxViewCells << endl;
484        Debug << "randomize: " << randomize << endl;
485
486        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
487        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
488        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
489        Debug << "max memory: " << mMaxMemory << endl;
490        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
491        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
492        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
493
494        Debug << "circulating axis: " << mCirculatingAxis << endl;
495        Debug << "minband: " << mMinBand << endl;
496        Debug << "maxband: " << mMaxBand << endl;
497
498        Debug << endl;
499}
500
501
502VspViewCell *VspTree::GetOutOfBoundsCell()
503{
504        return mOutOfBoundsCell;
505}
506
507
508VspViewCell *VspTree::GetOrCreateOutOfBoundsCell()
509{
510        if (!mOutOfBoundsCell)
511        {
512                mOutOfBoundsCell = new VspViewCell();
513                mOutOfBoundsCell->SetId(-1);
514                mOutOfBoundsCell->SetValid(false);
515        }
516
517        return mOutOfBoundsCell;
518}
519
520
521const VspTreeStatistics &VspTree::GetStatistics() const
522{
523        return mVspStats;
524}
525
526
527VspTree::~VspTree()
528{
529        DEL_PTR(mRoot);
530        DEL_PTR(mLocalSubdivisionCandidates);
531}
532
533
534void VspTree::ComputeBoundingBox(const VssRayContainer &rays,
535                                                                 AxisAlignedBox3 *forcedBoundingBox)
536{       
537        if (forcedBoundingBox)
538        {
539                mBoundingBox = *forcedBoundingBox;
540                return;
541        }
542       
543        //////////////////////////////////////////////
544        // bounding box of view space includes all visibility events
545        mBoundingBox.Initialize();
546        VssRayContainer::const_iterator rit, rit_end = rays.end();
547
548        for (rit = rays.begin(); rit != rit_end; ++ rit)
549        {
550                VssRay *ray = *rit;
551
552                mBoundingBox.Include(ray->GetTermination());
553                mBoundingBox.Include(ray->GetOrigin());
554        }
555}
556
557
558void VspTree::AddSubdivisionStats(const int viewCells,
559                                                                  const float renderCostDecr,
560                                                                  const float totalRenderCost,
561                                                                  const float avgRenderCost)
562{
563        mSubdivisionStats
564                        << "#ViewCells\n" << viewCells << endl
565                        << "#RenderCostDecrease\n" << renderCostDecr << endl
566                        << "#TotalRenderCost\n" << totalRenderCost << endl
567                        << "#AvgRenderCost\n" << avgRenderCost << endl;
568}
569
570
571// $$matt temporary: number of rayrefs + pvs should be in there, but
572// commented out for testing
573float VspTree::GetMemUsage() const
574{
575        return (float)
576                 (sizeof(VspTree)
577                  + mVspStats.Leaves() * sizeof(VspLeaf)
578                  + mVspStats.Leaves() * sizeof(VspViewCell)
579                  + mVspStats.Interior() * sizeof(VspInterior)
580                  //+ mVspStats.pvs * sizeof(PvsData)
581                  //+ mVspStats.rayRefs * sizeof(RayInfo)
582                  ) / (1024.0f * 1024.0f);
583}
584
585
586inline bool VspTree::LocalTerminationCriteriaMet(const VspTraversalData &data) const
587{
588        const bool localTerminationCriteriaMet = (0
589                || ((int)data.mRays->size() <= mTermMinRays)
590                || (data.mPvs <= mTermMinPvs)
591                || (data.mProbability <= mTermMinProbability)
592                //|| (data.GetAvgRayContribution() > mTermMaxRayContribution)
593                || (data.mDepth >= mTermMaxDepth)
594                );
595
596#if _DEBUG
597        if (localTerminationCriteriaMet)
598        {
599                Debug << "local termination criteria met:" << endl;
600                Debug << "rays: " << (int)data.mRays->size() << "  " << mTermMinRays << endl;
601                Debug << "pvs: " << data.mPvs << " " << mTermMinPvs << endl;
602                Debug << "p: " <<  data.mProbability << " " << mTermMinProbability << endl;
603                Debug << "avg contri: " << data.GetAvgRayContribution() << " " << mTermMaxRayContribution << endl;
604                Debug << "depth " << data.mDepth << " " << mTermMaxDepth << endl;
605        }
606#endif
607        return localTerminationCriteriaMet;             
608}
609
610
611inline bool VspTree::GlobalTerminationCriteriaMet(const VspTraversalData &data) const
612{
613        // note: to track for global cost misses does not really
614        // make sense because cost termination  happens in the hierarchy mananger
615
616        const bool terminationCriteriaMet = (0
617                // || mOutOfMemory
618                || (mVspStats.Leaves() >= mMaxViewCells)
619                // || (mVspStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
620                );
621
622#if _DEBUG
623        if (terminationCriteriaMet)
624        {
625                Debug << "vsp global termination criteria met:" << endl;
626                Debug << "cost misses: " << mVspStats.mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl;
627                Debug << "leaves: " << mVspStats.Leaves() << " " <<  mMaxViewCells << endl;
628        }
629#endif
630
631        return terminationCriteriaMet;
632}
633
634
635void VspTree::CreateViewCell(VspTraversalData &tData, const bool updatePvs)
636{
637        ///////////////
638        //-- create new view cell
639
640        VspLeaf *leaf = tData.mNode;
641
642        VspViewCell *viewCell = new VspViewCell();
643    leaf->SetViewCell(viewCell);
644       
645        int conSamp = 0;
646        float sampCon = 0.0f;
647
648        if (updatePvs)
649        {
650                // update pvs of view cell
651                AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp);
652
653                // update scalar pvs size value
654                ObjectPvs &pvs = viewCell->GetPvs();
655                mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.CountObjectsInPvs(), pvs.GetSize());
656
657                mVspStats.contributingSamples += conSamp;
658                mVspStats.sampleContributions += (int)sampCon;
659        }
660
661        if (mStoreRays)
662        {
663                ///////////
664                //-- store sampling rays
665
666        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
667
668                for (it = tData.mRays->begin(); it != it_end; ++ it)
669                {
670                        (*it).mRay->Ref();                     
671                        // note: should rather store rays with view cell
672                        leaf->mVssRays.push_back((*it).mRay);
673                }
674        }
675               
676        // set view cell values
677        viewCell->mLeaves.push_back(leaf);
678
679        viewCell->SetVolume(tData.mProbability);
680    leaf->mProbability = tData.mProbability;
681}
682
683
684void VspTree::EvalSubdivisionStats(const SubdivisionCandidate &sc)
685{
686        const float costDecr = sc.GetRenderCostDecrease();
687       
688        AddSubdivisionStats(mVspStats.Leaves(),
689                                                costDecr,
690                                                mTotalCost,
691                                                (float)mTotalPvsSize / (float)mVspStats.Leaves());
692}
693
694
695VspNode *VspTree::Subdivide(SplitQueue &tQueue,
696                                                        SubdivisionCandidate *splitCandidate,
697                                                        const bool globalCriteriaMet)
698{
699        // todo remove dynamic cast
700        VspSubdivisionCandidate *sc =
701                dynamic_cast<VspSubdivisionCandidate *>(splitCandidate);
702
703        VspTraversalData &tData = sc->mParentData;
704        VspNode *newNode = tData.mNode;
705
706        if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet)
707        {       
708                ///////////
709                //-- continue subdivision
710
711                VspTraversalData tFrontData;
712                VspTraversalData tBackData;
713               
714                // create new interior node and two leaf node
715                const AxisAlignedPlane splitPlane = sc->mSplitPlane;
716                const int maxCostMisses = sc->GetMaxCostMisses();
717
718                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData);
719       
720                // how often was max cost ratio missed in this branch?
721                tFrontData.mMaxCostMisses = maxCostMisses;
722                tBackData.mMaxCostMisses = maxCostMisses;
723                       
724                mTotalCost -= sc->GetRenderCostDecrease();
725                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
726                mPvsEntries += sc->GetPvsEntriesIncr();
727
728                // subdivision statistics
729                if (1) EvalSubdivisionStats(*sc);
730               
731                /////////////
732                //-- evaluate new split candidates for global greedy cost heuristics
733
734                VspSubdivisionCandidate *frontCandidate = new VspSubdivisionCandidate(tFrontData);
735                VspSubdivisionCandidate *backCandidate = new VspSubdivisionCandidate(tBackData);
736
737                EvalSubdivisionCandidate(*frontCandidate);
738                EvalSubdivisionCandidate(*backCandidate);
739
740                // cross reference
741                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
742                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
743
744                tQueue.Push(frontCandidate);
745                tQueue.Push(backCandidate);
746
747                // note: leaf is not destroyed because it is needed to collect
748                // dirty candidates in hierarchy manager
749        }
750
751        if (newNode->IsLeaf()) // subdivision terminated
752        {
753                VspLeaf *leaf = dynamic_cast<VspLeaf *>(newNode);
754               
755#if 0
756        /////////////
757                //-- store pvs optained from rays
758
759                // view cell is created during subdivision
760                ViewCell *viewCell = leaf->GetViewCell();
761
762                int conSamp = 0;
763                float sampCon = 0.0f;
764
765                AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp);
766
767                // update scalar pvs size value
768                ObjectPvs &pvs = viewCell->GetPvs();
769                mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.CountObjectsInPvs(), pvs.GetSize());
770
771                mVspStats.contributingSamples += conSamp;
772                mVspStats.sampleContributions += (int)sampCon;
773#endif
774                if (mStoreRays)
775                {
776                        //////////
777                        //-- store rays piercing this view cell
778                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
779                        for (it = tData.mRays->begin(); it != it_end; ++ it)
780                        {
781                                (*it).mRay->Ref();                     
782                                leaf->mVssRays.push_back((*it).mRay);
783                                //leaf->mVssRays.push_back(new VssRay(*(*it).mRay));
784                        }
785                }
786
787                // finally evaluate statistics for this leaf
788                EvaluateLeafStats(tData);
789                // detach subdivision candidate: this leaf is no candidate for
790                // splitting anymore
791                tData.mNode->SetSubdivisionCandidate(NULL);
792                // detach node so it won't get deleted
793                tData.mNode = NULL;
794        }
795
796        return newNode;
797}
798
799
800void VspTree::EvalSubdivisionCandidate(VspSubdivisionCandidate &splitCandidate,
801                                                                           bool computeSplitPlane)
802{
803        if (computeSplitPlane)
804        {
805                float frontProb;
806                float backProb;
807
808                // compute locally best split plane
809                const float ratio = SelectSplitPlane(splitCandidate.mParentData,
810                                                                                         splitCandidate.mSplitPlane,
811                                                                                         frontProb,
812                                                                                         backProb);
813       
814                const bool maxCostRatioViolated = mTermMaxCostRatio < ratio;
815
816                const int maxCostMisses = splitCandidate.mParentData.mMaxCostMisses;
817                // max cost threshold violated?
818                splitCandidate.SetMaxCostMisses(maxCostRatioViolated  ? maxCostMisses + 1: maxCostMisses);
819        }
820       
821        VspLeaf *leaf = dynamic_cast<VspLeaf *>(splitCandidate.mParentData.mNode);
822       
823        // compute global decrease in render cost
824        float oldRenderCost;
825        const float renderCostDecr = EvalRenderCostDecrease(splitCandidate.mSplitPlane,
826                                                                                                                splitCandidate.mParentData,
827                                                                                                                oldRenderCost);
828
829        splitCandidate.SetRenderCostDecrease(renderCostDecr);
830
831        // the increase in pvs entries num induced by this split
832        const int pvsEntriesIncr = EvalPvsEntriesIncr(splitCandidate);
833        splitCandidate.SetPvsEntriesIncr(pvsEntriesIncr);
834
835        // take render cost of node into account
836        // otherwise danger of being stuck in a local minimum!
837        const float factor = mRenderCostDecreaseWeight;
838        float priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
839
840        if (mHierarchyManager->mConsiderMemory2)
841        {
842                priority /= ((float)splitCandidate.GetPvsEntriesIncr() + mHierarchyManager->mMemoryConst);
843        }
844       
845        splitCandidate.SetPriority(priority);
846}
847
848
849int VspTree::EvalPvsEntriesIncr(VspSubdivisionCandidate &splitCandidate) const
850{
851        float oldPvsSize = 0;
852        float fPvsSize = 0;
853        float bPvsSize = 0;
854       
855        const AxisAlignedPlane candidatePlane = splitCandidate.mSplitPlane;
856       
857        Intersectable::NewMail(3);
858        KdLeaf::NewMail(3);
859        BvhLeaf::NewMail(3);
860
861        RayInfoContainer::const_iterator rit, rit_end = splitCandidate.mParentData.mRays->end();
862
863    // this is the main ray classification loop!
864        for(rit = splitCandidate.mParentData.mRays->begin(); rit != rit_end; ++ rit)
865        {
866                VssRay *ray = (*rit).mRay;
867                RayInfo rayInf = *rit;
868               
869                float t;
870                // classify ray
871                const int cf =  rayInf.ComputeRayIntersection(candidatePlane.mAxis,
872                                                                                                          candidatePlane.mPosition, t);
873
874                UpdatePvsEntriesContribution(*ray, true, cf, fPvsSize, bPvsSize, oldPvsSize);
875#if COUNT_ORIGIN_OBJECTS
876                UpdatePvsEntriesContribution(*ray, false, cf, fPvsSize, bPvsSize, oldPvsSize);
877#endif
878        }
879
880        return (int)(fPvsSize + bPvsSize - oldPvsSize);
881}
882
883
884VspInterior *VspTree::SubdivideNode(const AxisAlignedPlane &splitPlane,
885                                                                        VspTraversalData &tData,
886                                                                        VspTraversalData &frontData,
887                                                                        VspTraversalData &backData)
888{
889        VspLeaf *leaf = dynamic_cast<VspLeaf *>(tData.mNode);
890       
891        ///////////////
892        //-- new traversal values
893
894        frontData.mDepth = tData.mDepth + 1;
895        backData.mDepth = tData.mDepth + 1;
896
897        frontData.mRays = new RayInfoContainer();
898        backData.mRays = new RayInfoContainer();
899
900        //-- subdivide rays
901        SplitRays(splitPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
902
903        //-- compute pvs
904        frontData.mPvs = EvalPvsSize(*frontData.mRays);
905        backData.mPvs = EvalPvsSize(*backData.mRays);
906               
907        //-- split front and back node geometry and compute area
908        tData.mBoundingBox.Split(splitPlane.mAxis,
909                                                         splitPlane.mPosition,
910                                                         frontData.mBoundingBox,
911                                                         backData.mBoundingBox);
912
913        frontData.mProbability = frontData.mBoundingBox.GetVolume();
914        backData.mProbability = tData.mProbability - frontData.mProbability;
915
916
917        ////////
918        //-- update some stats
919       
920        if (tData.mDepth > mVspStats.maxDepth)
921        {       
922                mVspStats.maxDepth = tData.mDepth;
923        }
924
925        // two more leaves per split
926        mVspStats.nodes += 2;
927        // and a new split
928        ++ mVspStats.splits[splitPlane.mAxis];
929
930
931        ////////////////
932        //-- create front and back and subdivide further
933
934        VspInterior *interior = new VspInterior(splitPlane);
935        VspInterior *parent = leaf->GetParent();
936
937        // replace a link from node's parent
938        if (parent)
939        {
940                parent->ReplaceChildLink(leaf, interior);
941                interior->SetParent(parent);
942#if WORK_WITH_VIEWCELLS
943                // remove "parent" view cell from pvs of all objects (traverse trough rays)
944                RemoveParentViewCellReferences(tData.mNode->GetViewCell());
945#endif
946        }
947        else // new root
948        {
949                mRoot = interior;
950        }
951
952        VspLeaf *frontLeaf = new VspLeaf(interior);
953        VspLeaf *backLeaf = new VspLeaf(interior);
954
955        // and setup child links
956        interior->SetupChildLinks(frontLeaf, backLeaf);
957       
958        // add bounding box
959        interior->SetBoundingBox(tData.mBoundingBox);
960
961        // set front and back leaf
962        frontData.mNode = frontLeaf;
963        backData.mNode = backLeaf;
964
965        // explicitely create front and back view cell
966        CreateViewCell(frontData, false);
967        CreateViewCell(backData, false);
968
969        // set the time stamp so the order of traversal can be reconstructed
970        interior->mTimeStamp = mHierarchyManager->mTimeStamp ++;
971
972#if WORK_WITH_VIEWCELL_PVS
973        // create front and back view cell
974        // add front and back view cell to
975        // "potentially visible view cells"
976        // of the objects in front and back pvs
977
978        AddViewCellReferences(frontLeaf->GetViewCell());
979        AddViewCellReferences(backLeaf->GetViewCell());
980#endif
981
982        return interior;
983}
984
985
986void VspTree::AddSamplesToPvs(VspLeaf *leaf,
987                                                          const RayInfoContainer &rays,
988                                                          float &sampleContributions,
989                                                          int &contributingSamples)
990{
991        sampleContributions = 0;
992        contributingSamples = 0;
993 
994        RayInfoContainer::const_iterator it, it_end = rays.end();
995 
996        ViewCellLeaf *vc = leaf->GetViewCell();
997
998        // add contributions from samples to the pvs
999        for (it = rays.begin(); it != it_end; ++ it)
1000        {
1001                float sc = 0.0f;
1002                VssRay *ray = (*it).mRay;
1003
1004                bool madeContrib = false;
1005                float contribution;
1006
1007                Intersectable *obj = ray->mTerminationObject;
1008
1009                if (obj)
1010                {
1011                        madeContrib =
1012                                mViewCellsManager->AddSampleToPvs(
1013                                        obj,
1014                                        ray->mTermination,
1015                                        vc,
1016                                        ray->mPdf,
1017                                        contribution);
1018
1019                        sc += contribution;
1020                }
1021#if COUNT_ORIGIN_OBJECTS
1022                obj = ray->mOriginObject;
1023
1024                if (obj)
1025                {
1026                        madeContrib =
1027                                mViewCellsManager->AddSampleToPvs(
1028                                        obj,
1029                                        ray->mOrigin,
1030                                        vc,
1031                                        ray->mPdf,
1032                                        contribution);
1033
1034                        sc += contribution;
1035                }
1036#endif
1037                if (madeContrib)
1038                {
1039                        ++ contributingSamples;
1040                }
1041
1042                // store rays for visualization
1043                if (0) leaf->mVssRays.push_back(new VssRay(*ray));
1044        }
1045}
1046
1047
1048void VspTree::SortSubdivisionCandidates(const RayInfoContainer &rays,
1049                                                                  const int axis,
1050                                                                  float minBand,
1051                                                                  float maxBand)
1052{
1053        mLocalSubdivisionCandidates->clear();
1054
1055        const int requestedSize = 2 * (int)(rays.size());
1056
1057        // creates a sorted split candidates array
1058        if (mLocalSubdivisionCandidates->capacity() > 500000 &&
1059                requestedSize < (int)(mLocalSubdivisionCandidates->capacity() / 10) )
1060        {
1061        delete mLocalSubdivisionCandidates;
1062                mLocalSubdivisionCandidates = new vector<SortableEntry>;
1063        }
1064
1065        mLocalSubdivisionCandidates->reserve(requestedSize);
1066
1067        float pos;
1068        RayInfoContainer::const_iterator rit, rit_end = rays.end();
1069
1070        const bool delayMinEvent = false;
1071
1072        ////////////
1073        //-- insert all queries
1074        for (rit = rays.begin(); rit != rit_end; ++ rit)
1075        {
1076                const bool positive = (*rit).mRay->HasPosDir(axis);
1077               
1078                // origin point
1079                pos = (*rit).ExtrapOrigin(axis);
1080                const int oType = positive ? SortableEntry::ERayMin : SortableEntry::ERayMax;
1081
1082                if (delayMinEvent && oType == SortableEntry::ERayMin)
1083                        pos += mEpsilon; // could be useful feature for walls
1084
1085                mLocalSubdivisionCandidates->push_back(SortableEntry(oType, pos, (*rit).mRay));
1086
1087                // termination point
1088                pos = (*rit).ExtrapTermination(axis);
1089                const int tType = positive ? SortableEntry::ERayMax : SortableEntry::ERayMin;
1090
1091                if (delayMinEvent && tType == SortableEntry::ERayMin)
1092                        pos += mEpsilon; // could be useful feature for walls
1093
1094                mLocalSubdivisionCandidates->push_back(SortableEntry(tType, pos, (*rit).mRay));
1095        }
1096
1097        stable_sort(mLocalSubdivisionCandidates->begin(), mLocalSubdivisionCandidates->end());
1098}
1099
1100
1101int VspTree::PrepareHeuristics(KdLeaf *leaf)
1102{       
1103        int pvsSize = 0;
1104       
1105        if (!leaf->Mailed())
1106        {
1107                leaf->Mail();
1108                leaf->mCounter = 1;
1109                // add objects without the objects which are in several kd leaves
1110                pvsSize += (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size());
1111        }
1112        else
1113        {
1114                ++ leaf->mCounter;
1115        }
1116
1117        //-- the objects belonging to several leaves must be handled seperately
1118        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1119
1120        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1121        {
1122                Intersectable *object = *oit;
1123                                               
1124                if (!object->Mailed())
1125                {
1126                        object->Mail();
1127                        object->mCounter = 1;
1128
1129                        ++ pvsSize;
1130                }
1131                else
1132                {
1133                        ++ object->mCounter;
1134                }
1135        }
1136       
1137        return pvsSize;
1138}
1139
1140
1141int VspTree::PrepareHeuristics(const RayInfoContainer &rays)
1142{       
1143        Intersectable::NewMail();
1144        KdNode::NewMail();
1145        BvhLeaf::NewMail();
1146
1147        int pvsSize = 0;
1148
1149        RayInfoContainer::const_iterator ri, ri_end = rays.end();
1150
1151    // set all kd nodes / objects as belonging to the front pvs
1152        for (ri = rays.begin(); ri != ri_end; ++ ri)
1153        {
1154                VssRay *ray = (*ri).mRay;
1155               
1156                pvsSize += PrepareHeuristics(*ray, true);
1157#if COUNT_ORIGIN_OBJECTS
1158                pvsSize += PrepareHeuristics(*ray, false);
1159#endif
1160        }
1161
1162        return pvsSize;
1163}
1164
1165
1166int VspTree::EvalMaxEventContribution(KdLeaf *leaf) const
1167{
1168        int pvs = 0;
1169
1170        // leaf falls out of right pvs
1171        if (-- leaf->mCounter == 0)
1172        {
1173                pvs -= ((int)leaf->mObjects.size() - (int)leaf->mMultipleObjects.size());
1174        }
1175
1176        //-- separately handle objects which are in several kd leaves
1177
1178        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1179
1180        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1181        {
1182                Intersectable *object = *oit;
1183
1184                if (-- object->mCounter == 0)
1185                {
1186                        ++ pvs;
1187                }
1188        }
1189
1190        return pvs;
1191}
1192
1193
1194int VspTree::EvalMinEventContribution(KdLeaf *leaf) const
1195{
1196        if (leaf->Mailed())
1197                return 0;
1198       
1199        leaf->Mail();
1200
1201        // add objects without those which are part of several kd leaves
1202        int pvs = ((int)leaf->mObjects.size() - (int)leaf->mMultipleObjects.size());
1203
1204        // separately handle objects which are part of several kd leaves
1205        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1206
1207        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1208        {
1209                Intersectable *object = *oit;
1210
1211                // object not previously in pvs
1212                if (!object->Mailed())
1213                {
1214                        object->Mail();
1215                        ++ pvs;
1216                }
1217        }       
1218
1219        return pvs;
1220}
1221
1222
1223void VspTree::EvalHeuristics(const SortableEntry &ci,
1224                                                         int &pvsLeft,
1225                                                         int &pvsRight) const
1226{
1227        VssRay *ray = ci.ray;
1228
1229        // eval changes in pvs causes by min event
1230        if (ci.type == SortableEntry::ERayMin)
1231        {
1232#if COUNT_ORIGIN_OBJECTS
1233                pvsLeft += EvalMinEventContribution(*ray, true);
1234#else
1235                pvsLeft += EvalMinEventContribution(*ray, false);
1236#endif
1237        }
1238        else // eval changes in pvs causes by max event
1239        {
1240#if COUNT_ORIGIN_OBJECTS
1241                pvsRight -= EvalMaxEventContribution(*ray, true);
1242#else
1243                pvsRight -= EvalMaxEventContribution(*ray, false);
1244#endif
1245        }
1246}
1247
1248
1249float VspTree::EvalLocalCostHeuristics(const VspTraversalData &tData,
1250                                                                           const AxisAlignedBox3 &box,
1251                                                                           const int axis,
1252                                                                           float &position)
1253{
1254        // get subset of rays
1255        RayInfoContainer usedRays;
1256
1257        if (mMaxTests < (int)tData.mRays->size())
1258        {
1259                GetRayInfoSets(*tData.mRays, mMaxTests, usedRays);
1260        }
1261        else
1262        {
1263                usedRays = *tData.mRays;
1264        }
1265
1266        const float minBox = box.Min(axis);
1267        const float maxBox = box.Max(axis);
1268
1269        const float sizeBox = maxBox - minBox;
1270
1271        const float minBand = minBox + mMinBand * sizeBox;
1272        const float maxBand = minBox + mMaxBand * sizeBox;
1273
1274        SortSubdivisionCandidates(usedRays, axis, minBand, maxBand);
1275
1276        // prepare the sweep
1277        // note: returns pvs size => no need t give pvs size as function parameter
1278        const int pvsSize = PrepareHeuristics(usedRays);
1279
1280        // go through the lists, count the number of objects left and right
1281        // and evaluate the following cost funcion:
1282        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
1283
1284        int pvsl = 0;
1285        int pvsr = pvsSize;
1286
1287        int pvsBack = pvsl;
1288        int pvsFront = pvsr;
1289
1290        float sum = (float)pvsSize * sizeBox;
1291        float minSum = 1e20f;
1292
1293        // if no good split can be found, take mid split
1294        position = minBox + 0.5f * sizeBox;
1295       
1296        // the relative cost ratio
1297        float ratio = 99999999.0f;
1298        bool splitPlaneFound = false;
1299
1300        Intersectable::NewMail();
1301        KdLeaf::NewMail();
1302        BvhLeaf::NewMail();
1303
1304        //-- traverse through visibility events
1305        vector<SortableEntry>::const_iterator ci, ci_end = mLocalSubdivisionCandidates->end();
1306
1307#ifdef _DEBUG
1308        const float volRatio = tData.mBoundingBox.GetVolume() / (sizeBox * mBoundingBox.GetVolume());
1309        const int leaves = mVspStats.Leaves();
1310        const bool printStats = ((axis == 0) && (leaves > 0) && (leaves < 90));
1311       
1312        ofstream sumStats;
1313        ofstream pvslStats;
1314        ofstream pvsrStats;
1315
1316        if (printStats)
1317        {
1318                char str[64];
1319               
1320                sprintf(str, "tmp/vsp_heur_sum-%04d.log", leaves);
1321                sumStats.open(str);
1322                sprintf(str, "tmp/vsp_heur_pvsl-%04d.log", leaves);
1323                pvslStats.open(str);
1324                sprintf(str, "tmp/vsp_heur_pvsr-%04d.log", leaves);
1325                pvsrStats.open(str);
1326        }
1327
1328#endif
1329        for (ci = mLocalSubdivisionCandidates->begin(); ci != ci_end; ++ ci)
1330        {
1331                // compute changes to front and back pvs
1332                EvalHeuristics(*ci, pvsl, pvsr);
1333
1334                // Note: sufficient to compare size of bounding boxes of front and back side?
1335                if (((*ci).value >= minBand) && ((*ci).value <= maxBand))
1336                {
1337                        float currentPos;
1338                       
1339                        // HACK: current positition is BETWEEN visibility events
1340                        if (0 && ((ci + 1) != ci_end))
1341                                currentPos = ((*ci).value + (*(ci + 1)).value) * 0.5f;
1342                        else
1343                                currentPos = (*ci).value;                       
1344
1345                        sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value);
1346                       
1347#ifdef _DEBUG
1348                        if (printStats)
1349                        {
1350                                sumStats
1351                                        << "#Position\n" << currentPos << endl
1352                                        << "#Sum\n" << sum * volRatio << endl
1353                                        << "#Pvs\n" << pvsl + pvsr << endl;
1354
1355                                pvslStats
1356                                        << "#Position\n" << currentPos << endl
1357                                        << "#Pvsl\n" << pvsl << endl;
1358
1359                                pvsrStats
1360                                        << "#Position\n" << currentPos << endl
1361                                        << "#Pvsr\n" << pvsr << endl;
1362                        }
1363#endif
1364
1365                        if (sum < minSum)
1366                        {
1367                                splitPlaneFound = true;
1368
1369                                minSum = sum;
1370                                position = currentPos;
1371                               
1372                                pvsBack = pvsl;
1373                                pvsFront = pvsr;
1374                        }
1375                }
1376        }
1377       
1378        /////////       
1379        //-- compute cost
1380
1381        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1382        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1383
1384        const float pOverall = sizeBox;
1385        const float pBack = position - minBox;
1386        const float pFront = maxBox - position;
1387
1388        const float penaltyOld = EvalPvsPenalty(pvsSize, lowerPvsLimit, upperPvsLimit);
1389    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1390        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1391       
1392        const float oldRenderCost = penaltyOld * pOverall + Limits::Small;
1393        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1394
1395        if (splitPlaneFound)
1396        {
1397                ratio = newRenderCost / oldRenderCost;
1398        }
1399       
1400#ifdef _DEBUG
1401        Debug << "\n§§§§ eval local cost §§§§" << endl
1402                  << "back pvs: " << penaltyBack << " front pvs: " << penaltyFront << " total pvs: " << penaltyOld << endl
1403                  << "back p: " << pBack * volRatio << " front p " << pFront * volRatio << " p: " << pOverall * volRatio << endl
1404                  << "old rc: " << oldRenderCost * volRatio << " new rc: " << newRenderCost * volRatio << endl
1405                  << "render cost decrease: " << oldRenderCost * volRatio - newRenderCost * volRatio << endl;
1406#endif
1407        return ratio;
1408}
1409
1410
1411float VspTree::SelectSplitPlane(const VspTraversalData &tData,
1412                                                                AxisAlignedPlane &plane,
1413                                                                float &pFront,
1414                                                                float &pBack)
1415{
1416        float nPosition[3];
1417        float nCostRatio[3];
1418        float nProbFront[3];
1419        float nProbBack[3];
1420
1421        // create bounding box of node geometry
1422        AxisAlignedBox3 box = tData.mBoundingBox;
1423               
1424        int sAxis = 0;
1425        int bestAxis = -1;
1426
1427        // do we use some kind of specialised "fixed" axis?
1428    const bool useSpecialAxis =
1429                mOnlyDrivingAxis || mCirculatingAxis;
1430       
1431        if (mCirculatingAxis)
1432        {
1433                int parentAxis = 0;
1434                VspNode *parent = tData.mNode->GetParent();
1435
1436                if (parent)
1437                        parentAxis = dynamic_cast<VspInterior *>(parent)->GetAxis();
1438
1439                sAxis = (parentAxis + 1) % 3;
1440        }
1441        else if (mOnlyDrivingAxis)
1442        {
1443                sAxis = box.Size().DrivingAxis();
1444        }
1445       
1446        for (int axis = 0; axis < 3; ++ axis)
1447        {
1448                if (!useSpecialAxis || (axis == sAxis))
1449                {
1450                        if (mUseCostHeuristics)
1451                        {
1452                                //-- place split plane using heuristics
1453                                nCostRatio[axis] =
1454                                        EvalLocalCostHeuristics(tData,
1455                                                                                        box,
1456                                                                                        axis,
1457                                                                                        nPosition[axis]);                       
1458                        }
1459                        else
1460                        {
1461                                //-- split plane position is spatial median                             
1462                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1463                                nCostRatio[axis] = EvalLocalSplitCost(tData,
1464                                                                                                          box,
1465                                                                                                          axis,
1466                                                                                                          nPosition[axis],
1467                                                                                                          nProbFront[axis],
1468                                                                                                          nProbBack[axis]);
1469                        }
1470                                               
1471                        if (bestAxis == -1)
1472                        {
1473                                bestAxis = axis;
1474                        }
1475                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
1476                        {
1477                                bestAxis = axis;
1478                        }
1479                }
1480        }
1481
1482        ////////////////////////////////
1483        //-- assign values of best split
1484
1485        plane.mAxis = bestAxis;
1486        // best split plane position
1487        plane.mPosition = nPosition[bestAxis];
1488
1489        pFront = nProbFront[bestAxis];
1490        pBack = nProbBack[bestAxis];
1491
1492        return nCostRatio[bestAxis];
1493}
1494
1495
1496float VspTree::EvalRenderCostDecrease(const AxisAlignedPlane &candidatePlane,
1497                                                                          const VspTraversalData &data,
1498                                                                          float &normalizedOldRenderCost) const
1499{
1500        float pvsFront = 0;
1501        float pvsBack = 0;
1502        float totalPvs = 0;
1503
1504        const float viewSpaceVol = mBoundingBox.GetVolume();
1505
1506        //////////////////////////////////////////////
1507        // mark objects in the front / back / both using mailboxing
1508        // then count pvs sizes
1509
1510        Intersectable::NewMail(3);
1511        KdLeaf::NewMail(3);
1512        BvhLeaf::NewMail(3);
1513
1514        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1515
1516        for (rit = data.mRays->begin(); rit != rit_end; ++ rit)
1517        {
1518                RayInfo rayInf = *rit;
1519
1520                float t;
1521               
1522                // classify ray
1523                const int cf = rayInf.ComputeRayIntersection(candidatePlane.mAxis,
1524                                                                                                         candidatePlane.mPosition,
1525                                                                                                         t);
1526
1527                VssRay *ray = rayInf.mRay;
1528
1529                // evaluate contribution of ray endpoint to front
1530                // and back pvs with respect to the classification
1531                UpdateContributionsToPvs(*ray, true, cf, pvsFront, pvsBack, totalPvs);
1532#if COUNT_ORIGIN_OBJECTS
1533                UpdateContributionsToPvs(*ray, false, cf, pvsFront, pvsBack, totalPvs);
1534#endif
1535        }
1536   
1537        AxisAlignedBox3 frontBox;
1538        AxisAlignedBox3 backBox;
1539
1540        data.mBoundingBox.Split(candidatePlane.mAxis, candidatePlane.mPosition, frontBox, backBox);
1541
1542        // probability that view point lies in back / front node
1543        float pOverall = data.mProbability;
1544        float pFront = pFront = frontBox.GetVolume();
1545        float pBack = pOverall - pFront;
1546
1547
1548        ////////////////////////////////////
1549        //-- evaluate render cost heuristics
1550
1551        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1552        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1553
1554        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
1555    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
1556        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
1557                       
1558        const float oldRenderCost = pOverall * penaltyOld;
1559        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1560
1561        // we also return the old render cost
1562        normalizedOldRenderCost = oldRenderCost / viewSpaceVol;
1563
1564        // the render cost decrase for this split
1565        const float renderCostDecrease = (oldRenderCost - newRenderCost) / viewSpaceVol;
1566
1567#ifdef _DEBUG
1568        Debug << "\nvsp render cost decrease" << endl
1569                  << "back pvs: " << pvsBack << " front pvs " << pvsFront << " total pvs: " << totalPvs << endl
1570                  << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << " p: " << pOverall / viewSpaceVol << endl
1571                  << "old rc: " << normalizedOldRenderCost << " new rc: " << newRenderCost / viewSpaceVol << endl
1572                  << "render cost decrease: " << renderCostDecrease << endl;
1573#endif
1574
1575        return renderCostDecrease;
1576}
1577
1578
1579
1580float VspTree::EvalLocalSplitCost(const VspTraversalData &data,
1581                                                                  const AxisAlignedBox3 &box,
1582                                                                  const int axis,
1583                                                                  const float &position,
1584                                                                  float &pFront,
1585                                                                  float &pBack) const
1586{
1587        float pvsTotal = 0;
1588        float pvsFront = 0;
1589        float pvsBack = 0;
1590       
1591        // create unique ids for pvs heuristics
1592        Intersectable::NewMail(3);
1593        BvhLeaf::NewMail(3);
1594        KdLeaf::NewMail(3);
1595
1596        const int pvsSize = data.mPvs;
1597        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1598
1599        // this is the main ray classification loop!
1600        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
1601        {
1602                VssRay *ray = (*rit).mRay;
1603
1604                // determine the side of this ray with respect to the plane
1605                float t;
1606                const int side = (*rit).ComputeRayIntersection(axis, position, t);
1607       
1608                UpdateContributionsToPvs(*ray, true, side, pvsFront, pvsBack, pvsTotal);
1609                UpdateContributionsToPvs(*ray, false, side, pvsFront, pvsBack, pvsTotal);
1610        }
1611
1612        //////////////
1613        //-- evaluate cost heuristics
1614        float pOverall = data.mProbability;
1615
1616        // we use spatial mid split => simplified computation
1617        pBack = pFront = pOverall * 0.5f;
1618       
1619        const float newCost = pvsBack * pBack + pvsFront * pFront;
1620        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
1621       
1622#ifdef _DEBUG
1623        Debug << "axis: " << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
1624        Debug << "p: " << pFront << " " << pBack << " " << pOverall << endl;
1625#endif
1626
1627        return  (mCtDivCi + newCost) / oldCost;
1628}
1629
1630
1631void VspTree::UpdateContributionsToPvs(Intersectable *obj,
1632                                                                           const int cf,
1633                                                                           float &frontPvs,
1634                                                                           float &backPvs,
1635                                                                           float &totalPvs) const
1636{
1637        if (!obj) return;
1638
1639        //const float renderCost = mViewCellsManager->SimpleRay &raynderCost(obj);
1640        const int renderCost = 1;
1641
1642        // object in no pvs => new
1643        if (!obj->Mailed() && !obj->Mailed(1) && !obj->Mailed(2))
1644        {
1645                totalPvs += renderCost;
1646        }
1647
1648        // QUESTION matt: is it safe to assume that
1649        // the object belongs to no pvs in this case?
1650        //if (cf == Ray::COINCIDENT) return;
1651
1652        if (cf >= 0) // front pvs
1653        {
1654                if (!obj->Mailed() && !obj->Mailed(2))
1655                {
1656                        frontPvs += renderCost;
1657               
1658                        // already in back pvs => in both pvss
1659                        if (obj->Mailed(1))
1660                                obj->Mail(2);
1661                        else
1662                                obj->Mail();
1663                }
1664        }
1665
1666        if (cf <= 0) // back pvs
1667        {
1668                if (!obj->Mailed(1) && !obj->Mailed(2))
1669                {
1670                        backPvs += renderCost;
1671               
1672                        // already in front pvs => in both pvss
1673                        if (obj->Mailed())
1674                                obj->Mail(2);
1675                        else
1676                                obj->Mail(1);
1677                }
1678        }
1679}
1680
1681
1682void VspTree::UpdateContributionsToPvs(BvhLeaf *leaf,
1683                                                                           const int cf,
1684                                                                           float &frontPvs,
1685                                                                           float &backPvs,
1686                                                                           float &totalPvs,
1687                                                                           const bool countEntries) const
1688{
1689        if (!leaf) return;
1690        const int renderCost = countEntries ? 1 : (int)leaf->mObjects.size();
1691       
1692        // leaf in no pvs => new
1693        if (!leaf->Mailed() && !leaf->Mailed(1) && !leaf->Mailed(2))
1694        {
1695                totalPvs += renderCost;
1696        }
1697
1698        if (cf >= 0) // front pvs
1699        {
1700                if (!leaf->Mailed() && !leaf->Mailed(2))
1701                {
1702                        frontPvs += renderCost;
1703       
1704                        // already in back pvs => in both pvss
1705                        if (leaf->Mailed(1))
1706                                leaf->Mail(2);
1707                        else
1708                                leaf->Mail();
1709                }
1710        }
1711
1712        if (cf <= 0) // back pvs
1713        {
1714                if (!leaf->Mailed(1) && !leaf->Mailed(2))
1715                {
1716                        backPvs += renderCost;
1717               
1718                        // already in front pvs => in both pvss
1719                        if (leaf->Mailed())
1720                        {
1721                                leaf->Mail(2);
1722                        }
1723                        else
1724                                leaf->Mail(1);
1725                }
1726        }
1727}
1728
1729
1730
1731void VspTree::UpdateContributionsToPvs(KdLeaf *leaf,
1732                                                                           const int cf,
1733                                                                           float &frontPvs,
1734                                                                           float &backPvs,
1735                                                                           float &totalPvs) const
1736{
1737        if (!leaf) return;
1738
1739        // the objects which are referenced in this and only this leaf
1740        const int contri = (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size());
1741       
1742        // newly found leaf
1743        if (!leaf->Mailed() && !leaf->Mailed(1) && !leaf->Mailed(2))
1744        {
1745                totalPvs += contri;
1746        }
1747
1748        // recursivly update contributions of yet unclassified objects
1749        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1750
1751        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1752        {       
1753                UpdateContributionsToPvs(*oit, cf, frontPvs, backPvs, totalPvs);
1754    }   
1755       
1756        if (cf >= 0) // front pvs
1757        {
1758                if (!leaf->Mailed() && !leaf->Mailed(2))
1759                {
1760                        frontPvs += contri;
1761               
1762                        // already in back pvs => in both pvss
1763                        if (leaf->Mailed(1))
1764                                leaf->Mail(2);
1765                        else
1766                                leaf->Mail();
1767                }
1768        }
1769
1770        if (cf <= 0) // back pvs
1771        {
1772                if (!leaf->Mailed(1) && !leaf->Mailed(2))
1773                {
1774                        backPvs += contri;
1775               
1776                        // already in front pvs => in both pvss
1777                        if (leaf->Mailed())
1778                                leaf->Mail(2);
1779                        else
1780                                leaf->Mail(1);
1781                }
1782        }
1783}
1784
1785
1786void VspTree::CollectLeaves(vector<VspLeaf *> &leaves,
1787                                                        const bool onlyUnmailed,
1788                                                        const int maxPvsSize) const
1789{
1790        stack<VspNode *> nodeStack;
1791        nodeStack.push(mRoot);
1792
1793        while (!nodeStack.empty())
1794        {
1795                VspNode *node = nodeStack.top();
1796                nodeStack.pop();
1797               
1798                if (node->IsLeaf())
1799                {
1800                        // test if this leaf is in valid view space
1801                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
1802                        if (leaf->TreeValid() &&
1803                                (!onlyUnmailed || !leaf->Mailed()) &&
1804                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().CountObjectsInPvs() <= maxPvsSize)))
1805                        {
1806                                leaves.push_back(leaf);
1807                        }
1808                }
1809                else
1810                {
1811                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
1812
1813                        nodeStack.push(interior->GetBack());
1814                        nodeStack.push(interior->GetFront());
1815                }
1816        }
1817}
1818
1819
1820AxisAlignedBox3 VspTree::GetBoundingBox() const
1821{
1822        return mBoundingBox;
1823}
1824
1825
1826VspNode *VspTree::GetRoot() const
1827{
1828        return mRoot;
1829}
1830
1831
1832void VspTree::EvaluateLeafStats(const VspTraversalData &data)
1833{
1834        // the node became a leaf -> evaluate stats for leafs
1835        VspLeaf *leaf = dynamic_cast<VspLeaf *>(data.mNode);
1836
1837
1838        if (data.mPvs > mVspStats.maxPvs)
1839        {
1840                mVspStats.maxPvs = data.mPvs;
1841        }
1842
1843        mVspStats.pvs += data.mPvs;
1844
1845        if (data.mDepth < mVspStats.minDepth)
1846        {
1847                mVspStats.minDepth = data.mDepth;
1848        }
1849       
1850        if (data.mDepth >= mTermMaxDepth)
1851        {
1852        ++ mVspStats.maxDepthNodes;
1853                //Debug << "new max depth: " << mVspStats.maxDepthNodes << endl;
1854        }
1855
1856        // accumulate rays to compute rays /  leaf
1857        mVspStats.rayRefs += (int)data.mRays->size();
1858
1859        if (data.mPvs < mTermMinPvs)
1860                ++ mVspStats.minPvsNodes;
1861
1862        if ((int)data.mRays->size() < mTermMinRays)
1863                ++ mVspStats.minRaysNodes;
1864
1865        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1866                ++ mVspStats.maxRayContribNodes;
1867
1868        if (data.mProbability <= mTermMinProbability)
1869                ++ mVspStats.minProbabilityNodes;
1870       
1871        // accumulate depth to compute average depth
1872        mVspStats.accumDepth += data.mDepth;
1873
1874        ++ mCreatedViewCells;
1875
1876#ifdef _DEBUG
1877        Debug << "BSP stats: "
1878                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1879                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1880                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1881                  << "#pvs: " << leaf->GetViewCell()->GetPvs().CountObjectsInPvs() << "), "
1882                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1883#endif
1884}
1885
1886
1887void VspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
1888{
1889        ViewCell::NewMail();
1890        CollectViewCells(mRoot, onlyValid, viewCells, true);
1891}
1892
1893
1894void VspTree::CollapseViewCells()
1895{
1896// TODO matt
1897#if HAS_TO_BE_REDONE
1898        stack<VspNode *> nodeStack;
1899
1900        if (!mRoot)
1901                return;
1902
1903        nodeStack.push(mRoot);
1904       
1905        while (!nodeStack.empty())
1906        {
1907                VspNode *node = nodeStack.top();
1908                nodeStack.pop();
1909               
1910                if (node->IsLeaf())
1911        {
1912                        BspViewCell *viewCell = dynamic_cast<VspLeaf *>(node)->GetViewCell();
1913
1914                        if (!viewCell->GetValid())
1915                        {
1916                                BspViewCell *viewCell = dynamic_cast<VspLeaf *>(node)->GetViewCell();
1917       
1918                                ViewCellContainer leaves;
1919                                mViewCellsTree->CollectLeaves(viewCell, leaves);
1920
1921                                ViewCellContainer::const_iterator it, it_end = leaves.end();
1922
1923                                for (it = leaves.begin(); it != it_end; ++ it)
1924                                {
1925                                        VspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
1926                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
1927                                        ++ mVspStats.invalidLeaves;
1928                                }
1929
1930                                // add to unbounded view cell
1931                                ViewCell *outOfBounds = GetOrCreateOutOfBoundsCell();
1932                                outOfBounds->GetPvs().AddPvs(viewCell->GetPvs());
1933                                DEL_PTR(viewCell);
1934                        }
1935                }
1936                else
1937                {
1938                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
1939               
1940                        nodeStack.push(interior->GetFront());
1941                        nodeStack.push(interior->GetBack());
1942                }
1943        }
1944
1945        Debug << "invalid leaves: " << mVspStats.invalidLeaves << endl;
1946#endif
1947}
1948
1949
1950void VspTree::CollectRays(VssRayContainer &rays)
1951{
1952        vector<VspLeaf *> leaves;
1953        CollectLeaves(leaves);
1954
1955        vector<VspLeaf *>::const_iterator lit, lit_end = leaves.end();
1956
1957        for (lit = leaves.begin(); lit != lit_end; ++ lit)
1958        {
1959                VspLeaf *leaf = *lit;
1960                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
1961
1962                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
1963                        rays.push_back(*rit);
1964        }
1965}
1966
1967
1968void VspTree::SetViewCellsManager(ViewCellsManager *vcm)
1969{
1970        mViewCellsManager = vcm;
1971}
1972
1973
1974void VspTree::ValidateTree()
1975{
1976        if (!mRoot)
1977                return;
1978
1979        mVspStats.invalidLeaves = 0;
1980        stack<VspNode *> nodeStack;
1981
1982        nodeStack.push(mRoot);
1983
1984        while (!nodeStack.empty())
1985        {
1986                VspNode *node = nodeStack.top();
1987                nodeStack.pop();
1988               
1989                if (node->IsLeaf())
1990                {
1991                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
1992
1993                        if (!leaf->GetViewCell()->GetValid())
1994                                ++ mVspStats.invalidLeaves;
1995
1996                        // validity flags don't match => repair
1997                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
1998                        {
1999                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2000                                PropagateUpValidity(leaf);
2001                        }
2002                }
2003                else
2004                {
2005                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2006               
2007                        nodeStack.push(interior->GetFront());
2008                        nodeStack.push(interior->GetBack());
2009                }
2010        }
2011
2012        Debug << "invalid leaves: " << mVspStats.invalidLeaves << endl;
2013}
2014
2015
2016
2017void VspTree::CollectViewCells(VspNode *root,
2018                                                                  bool onlyValid,
2019                                                                  ViewCellContainer &viewCells,
2020                                                                  bool onlyUnmailed) const
2021{
2022        if (!root)
2023                return;
2024
2025        stack<VspNode *> nodeStack;
2026        nodeStack.push(root);
2027       
2028        while (!nodeStack.empty())
2029        {
2030                VspNode *node = nodeStack.top();
2031                nodeStack.pop();
2032               
2033                if (node->IsLeaf())
2034                {
2035                        if (!onlyValid || node->TreeValid())
2036                        {
2037                                ViewCellLeaf *leafVc = dynamic_cast<VspLeaf *>(node)->GetViewCell();
2038
2039                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2040                                               
2041                                if (!onlyUnmailed || !viewCell->Mailed())
2042                                {
2043                                        viewCell->Mail();
2044                                        viewCells.push_back(viewCell);
2045                                }
2046                        }
2047                }
2048                else
2049                {
2050                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2051               
2052                        nodeStack.push(interior->GetFront());
2053                        nodeStack.push(interior->GetBack());
2054                }
2055        }
2056}
2057
2058
2059int VspTree::FindNeighbors(VspLeaf *n,
2060                                                   vector<VspLeaf *> &neighbors,
2061                                                   const bool onlyUnmailed) const
2062{
2063        stack<VspNode *> nodeStack;
2064        nodeStack.push(mRoot);
2065
2066        const AxisAlignedBox3 box = GetBoundingBox(n);
2067
2068        while (!nodeStack.empty())
2069        {
2070                VspNode *node = nodeStack.top();
2071                nodeStack.pop();
2072
2073                if (node->IsLeaf())
2074                {
2075                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2076
2077                        if (leaf != n && (!onlyUnmailed || !leaf->Mailed()))
2078                                neighbors.push_back(leaf);
2079                }
2080                else
2081                {
2082                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2083                       
2084                        if (interior->GetPosition() > box.Max(interior->GetAxis()))
2085                                nodeStack.push(interior->GetBack());
2086                        else
2087                        {
2088                                if (interior->GetPosition() < box.Min(interior->GetAxis()))
2089                                        nodeStack.push(interior->GetFront());
2090                                else
2091                                {
2092                                        // random decision
2093                                        nodeStack.push(interior->GetBack());
2094                                        nodeStack.push(interior->GetFront());
2095                                }
2096                        }
2097                }
2098        }
2099
2100        return (int)neighbors.size();
2101}
2102
2103
2104// Find random neighbor which was not mailed
2105VspLeaf *VspTree::GetRandomLeaf(const Plane3 &plane)
2106{
2107        stack<VspNode *> nodeStack;
2108        nodeStack.push(mRoot);
2109 
2110        int mask = rand();
2111 
2112        while (!nodeStack.empty())
2113        {
2114                VspNode *node = nodeStack.top();
2115               
2116                nodeStack.pop();
2117               
2118                if (node->IsLeaf())
2119                {
2120                        return dynamic_cast<VspLeaf *>(node);
2121                }
2122                else
2123                {
2124                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2125                        VspNode *next;
2126                       
2127                        if (GetBoundingBox(interior->GetBack()).Side(plane) < 0)
2128                        {
2129                                next = interior->GetFront();
2130                        }
2131            else
2132                        {
2133                                if (GetBoundingBox(interior->GetFront()).Side(plane) < 0)
2134                                {
2135                                        next = interior->GetBack();
2136                                }
2137                                else
2138                                {
2139                                        // random decision
2140                                        if (mask & 1)
2141                                                next = interior->GetBack();
2142                                        else
2143                                                next = interior->GetFront();
2144                                        mask = mask >> 1;
2145                                }
2146                        }
2147                       
2148                        nodeStack.push(next);
2149                }
2150        }
2151 
2152        return NULL;
2153}
2154
2155
2156VspLeaf *VspTree::GetRandomLeaf(const bool onlyUnmailed)
2157{
2158        stack<VspNode *> nodeStack;
2159
2160        nodeStack.push(mRoot);
2161
2162        int mask = rand();
2163
2164        while (!nodeStack.empty())
2165        {
2166                VspNode *node = nodeStack.top();
2167                nodeStack.pop();
2168
2169                if (node->IsLeaf())
2170                {
2171                        if ( (!onlyUnmailed || !node->Mailed()) )
2172                                return dynamic_cast<VspLeaf *>(node);
2173                }
2174                else
2175                {
2176                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2177
2178                        // random decision
2179                        if (mask & 1)
2180                                nodeStack.push(interior->GetBack());
2181                        else
2182                                nodeStack.push(interior->GetFront());
2183
2184                        mask = mask >> 1;
2185                }
2186        }
2187
2188        return NULL;
2189}
2190
2191
2192int VspTree::EvalPvsSize(const RayInfoContainer &rays) const
2193{
2194        int pvsSize = 0;
2195       
2196        Intersectable::NewMail();
2197        KdNode::NewMail();
2198        BvhLeaf::NewMail();
2199
2200        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2201
2202        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2203        {
2204                VssRay *ray = (*rit).mRay;
2205#if COUNT_ORIGIN_OBJECTS
2206                pvsSize += EvalContributionToPvs(*ray, true);
2207#else
2208                pvsSize += EvalContributionToPvs(*ray, false);
2209#endif
2210        }
2211       
2212        return pvsSize;
2213}
2214
2215
2216int VspTree::EvalPvsEntriesContribution(const VssRay &ray,
2217                                                                                const bool isTermination) const
2218
2219{
2220                Intersectable *obj;
2221                Vector3 pt;
2222                KdNode *node;
2223
2224                ray.GetSampleData(isTermination, pt, &obj, &node);
2225                if (!obj) return 0;
2226
2227                switch(mHierarchyManager->GetObjectSpaceSubdivisionType())
2228                {
2229                case HierarchyManager::NO_OBJ_SUBDIV:
2230                {
2231                        if (!obj->Mailed())
2232                        {
2233                                obj->Mail();
2234                                return 1;
2235                        }
2236                       
2237                        return 0;
2238                }
2239
2240                case HierarchyManager::KD_BASED_OBJ_SUBDIV:
2241                {
2242                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
2243                        if (!leaf->Mailed())
2244                        {
2245                                leaf->Mail();
2246                                return 1;
2247                        }
2248                       
2249                        return 0;
2250                }
2251        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
2252                {
2253                        BvhLeaf *bvhleaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
2254
2255                        if (!bvhleaf->Mailed())
2256                        {
2257                                bvhleaf->Mail();
2258                                return 1;
2259                        }
2260                       
2261                        return 0;
2262                }
2263        default:
2264                break;
2265        }
2266
2267        return 0;
2268}
2269
2270
2271int VspTree::EvalPvsEntriesSize(const RayInfoContainer &rays) const
2272{
2273        int pvsSize = 0;
2274
2275        Intersectable::NewMail();
2276        KdNode::NewMail();
2277        BvhLeaf::NewMail();
2278
2279        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2280
2281        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2282        {
2283                VssRay *ray = (*rit).mRay;
2284#if COUNT_ORIGIN_OBJECTS
2285                pvsSize += EvalPvsEntriesContribution(*ray, true);
2286#else
2287                pvsSize += EvalPvsEntriesContribution(*ray, false);
2288#endif
2289        }
2290
2291        return pvsSize;
2292}
2293
2294
2295float VspTree::GetEpsilon() const
2296{
2297        return mEpsilon;
2298}
2299
2300
2301int VspTree::CastLineSegment(const Vector3 &origin,
2302                                                         const Vector3 &termination,
2303                             ViewCellContainer &viewcells,
2304                                                         const bool useMailboxing)
2305{
2306        int hits = 0;
2307
2308        float mint = 0.0f, maxt = 1.0f;
2309        const Vector3 dir = termination - origin;
2310
2311        stack<LineTraversalData> tStack;
2312
2313        Vector3 entp = origin;
2314        Vector3 extp = termination;
2315
2316        VspNode *node = mRoot;
2317        VspNode *farChild;
2318
2319        float position;
2320        int axis;
2321
2322        while (1)
2323        {
2324                if (!node->IsLeaf())
2325                {
2326                        VspInterior *in = dynamic_cast<VspInterior *>(node);
2327                        position = in->GetPosition();
2328                        axis = in->GetAxis();
2329
2330                        if (entp[axis] <= position)
2331                        {
2332                                if (extp[axis] <= position)
2333                                {
2334                                        node = in->GetBack();
2335                                        // cases N1,N2,N3,P5,Z2,Z3
2336                                        continue;
2337                                } else
2338                                {
2339                                        // case N4
2340                                        node = in->GetBack();
2341                                        farChild = in->GetFront();
2342                                }
2343                        }
2344                        else
2345                        {
2346                                if (position <= extp[axis])
2347                                {
2348                                        node = in->GetFront();
2349                                        // cases P1,P2,P3,N5,Z1
2350                                        continue;
2351                                }
2352                                else
2353                                {
2354                                        node = in->GetFront();
2355                                        farChild = in->GetBack();
2356                                        // case P4
2357                                }
2358                        }
2359
2360                        // $$ modification 3.5.2004 - hints from Kamil Ghais
2361                        // case N4 or P4
2362                        const float tdist = (position - origin[axis]) / dir[axis];
2363                        tStack.push(LineTraversalData(farChild, extp, maxt)); //TODO
2364
2365                        extp = origin + dir * tdist;
2366                        maxt = tdist;
2367                }
2368                else
2369                {
2370                        // compute intersection with all objects in this leaf
2371                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2372                        ViewCell *viewCell;
2373                        if (0)
2374                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2375                        else
2376                                viewCell = leaf->GetViewCell();
2377
2378                        // don't have to mail if each view cell belongs to exactly one leaf
2379                        if (!useMailboxing || !viewCell->Mailed())
2380                        {
2381                                if (useMailboxing)
2382                                        viewCell->Mail();
2383
2384                                viewcells.push_back(viewCell);
2385                                ++ hits;
2386                        }
2387
2388                        // get the next node from the stack
2389                        if (tStack.empty())
2390                                break;
2391
2392                        entp = extp;
2393                        mint = maxt;
2394                       
2395                        LineTraversalData &s  = tStack.top();
2396                        node = s.mNode;
2397                        extp = s.mExitPoint;
2398                        maxt = s.mMaxT;
2399
2400                        tStack.pop();
2401                }
2402        }
2403
2404        return hits;
2405}
2406
2407
2408int VspTree::CastRay(Ray &ray)
2409{
2410        int hits = 0;
2411
2412        stack<LineTraversalData> tStack;
2413        const Vector3 dir = ray.GetDir();
2414
2415        float maxt, mint;
2416
2417        if (!mBoundingBox.GetRaySegment(ray, mint, maxt))
2418                return 0;
2419
2420        Intersectable::NewMail();
2421        ViewCell::NewMail();
2422
2423        Vector3 entp = ray.Extrap(mint);
2424        Vector3 extp = ray.Extrap(maxt);
2425
2426        const Vector3 origin = entp;
2427
2428        VspNode *node = mRoot;
2429        VspNode *farChild = NULL;
2430
2431        float position;
2432        int axis;
2433
2434        while (1)
2435        {
2436                if (!node->IsLeaf())
2437                {
2438                        VspInterior *in = dynamic_cast<VspInterior *>(node);
2439                        position = in->GetPosition();
2440                        axis = in->GetAxis();
2441
2442                        if (entp[axis] <= position)
2443                        {
2444                                if (extp[axis] <= position)
2445                                {
2446                                        node = in->GetBack();
2447                                        // cases N1,N2,N3,P5,Z2,Z3
2448                                        continue;
2449                                }
2450                                else
2451                                {
2452                                        // case N4
2453                                        node = in->GetBack();
2454                                        farChild = in->GetFront();
2455                                }
2456                        }
2457                        else
2458                        {
2459                                if (position <= extp[axis])
2460                                {
2461                                        node = in->GetFront();
2462                                        // cases P1,P2,P3,N5,Z1
2463                                        continue;
2464                                }
2465                                else
2466                                {
2467                                        node = in->GetFront();
2468                                        farChild = in->GetBack();
2469                                        // case P4
2470                                }
2471                        }
2472
2473                        // $$ modification 3.5.2004 - hints from Kamil Ghais
2474                        // case N4 or P4
2475                        const float tdist = (position - origin[axis]) / dir[axis];
2476                        tStack.push(LineTraversalData(farChild, extp, maxt)); //TODO
2477                        extp = origin + dir * tdist;
2478                        maxt = tdist;
2479                }
2480                else
2481                {
2482                        // compute intersection with all objects in this leaf
2483                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2484                        ViewCell *vc = leaf->GetViewCell();
2485
2486                        if (!vc->Mailed())
2487                        {
2488                                vc->Mail();
2489                                // todo: add view cells to ray
2490                                ++ hits;
2491                        }
2492
2493                        // get the next node from the stack
2494                        if (tStack.empty())
2495                                break;
2496
2497                        entp = extp;
2498                        mint = maxt;
2499                       
2500                        LineTraversalData &s  = tStack.top();
2501                        node = s.mNode;
2502                        extp = s.mExitPoint;
2503                        maxt = s.mMaxT;
2504                        tStack.pop();
2505                }
2506        }
2507
2508        return hits;
2509}
2510
2511
2512ViewCell *VspTree::GetViewCell(const Vector3 &point, const bool active)
2513{
2514        if (mRoot == NULL)
2515                return NULL;
2516
2517        stack<VspNode *> nodeStack;
2518        nodeStack.push(mRoot);
2519 
2520        ViewCellLeaf *viewcell = NULL;
2521 
2522        while (!nodeStack.empty()) 
2523        {
2524                VspNode *node = nodeStack.top();
2525                nodeStack.pop();
2526       
2527                if (node->IsLeaf())
2528                {
2529                        /*const AxisAlignedBox3 box = GetBoundingBox(dynamic_cast<VspLeaf *>(node));
2530                        if (!box.IsInside(point))
2531                                cerr << "error, point " << point << " should be in view cell " << box << endl;
2532                        */     
2533                        viewcell = dynamic_cast<VspLeaf *>(node)->GetViewCell();
2534                        break;
2535                }
2536                else   
2537                {       
2538                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2539     
2540                        // random decision
2541                        if (interior->GetPosition() - point[interior->GetAxis()] < 0)
2542                        {
2543                                nodeStack.push(interior->GetFront());
2544                        }
2545                        else
2546                        {
2547                                nodeStack.push(interior->GetBack());
2548                        }
2549                }
2550        }
2551 
2552        if (active)
2553        {
2554                return mViewCellsTree->GetActiveViewCell(viewcell);
2555        }
2556        else
2557        {
2558                return viewcell;
2559        }
2560}
2561
2562
2563bool VspTree::ViewPointValid(const Vector3 &viewPoint) const
2564{
2565        VspNode *node = mRoot;
2566
2567        while (1)
2568        {
2569                // early exit
2570                if (node->TreeValid())
2571                        return true;
2572
2573                if (node->IsLeaf())
2574                        return false;
2575                       
2576                VspInterior *in = dynamic_cast<VspInterior *>(node);
2577                                       
2578                if (in->GetPosition() - viewPoint[in->GetAxis()] <= 0)
2579                {
2580                        node = in->GetBack();
2581                }
2582                else
2583                {
2584                        node = in->GetFront();
2585                }
2586        }
2587
2588        // should never come here
2589        return false;
2590}
2591
2592
2593void VspTree::PropagateUpValidity(VspNode *node)
2594{
2595        const bool isValid = node->TreeValid();
2596
2597        // propagative up invalid flag until only invalid nodes exist over this node
2598        if (!isValid)
2599        {
2600                while (!node->IsRoot() && node->GetParent()->TreeValid())
2601                {
2602                        node = node->GetParent();
2603                        node->SetTreeValid(false);
2604                }
2605        }
2606        else
2607        {
2608                // propagative up valid flag until one of the subtrees is invalid
2609                while (!node->IsRoot() && !node->TreeValid())
2610                {
2611            node = node->GetParent();
2612                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2613                       
2614                        // the parent is valid iff both leaves are valid
2615                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
2616                                                           interior->GetFront()->TreeValid());
2617                }
2618        }
2619}
2620
2621
2622bool VspTree::Export(OUT_STREAM &stream)
2623{
2624        ExportNode(mRoot, stream);
2625
2626        return true;
2627}
2628
2629
2630void VspTree::ExportNode(VspNode *node, OUT_STREAM &stream)
2631{
2632        if (node->IsLeaf())
2633        {
2634                VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2635                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2636
2637                int id = -1;
2638                if (viewCell != mOutOfBoundsCell)
2639                        id = viewCell->GetId();
2640
2641                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
2642        }
2643        else
2644        {       
2645                VspInterior *interior = dynamic_cast<VspInterior *>(node);
2646       
2647                AxisAlignedPlane plane = interior->GetPlane();
2648                stream << "<Interior plane=\"" << plane.mPosition << " "
2649                           << plane.mAxis << "\">" << endl;
2650
2651                ExportNode(interior->GetBack(), stream);
2652                ExportNode(interior->GetFront(), stream);
2653
2654                stream << "</Interior>" << endl;
2655        }
2656}
2657
2658
2659int VspTree::SplitRays(const AxisAlignedPlane &plane,
2660                                           RayInfoContainer &rays,
2661                                           RayInfoContainer &frontRays,
2662                                           RayInfoContainer &backRays) const
2663{
2664        int splits = 0;
2665
2666        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2667
2668        for (rit = rays.begin(); rit != rit_end; ++ rit)
2669        {
2670                RayInfo bRay = *rit;
2671               
2672                VssRay *ray = bRay.mRay;
2673                float t;
2674
2675                // get classification and receive new t
2676                // test if start point behind or in front of plane
2677                const int side = bRay.ComputeRayIntersection(plane.mAxis, plane.mPosition, t);
2678                       
2679                if (side == 0)
2680                {
2681                        ++ splits;
2682
2683                        if (ray->HasPosDir(plane.mAxis))
2684                        {
2685                                backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2686                                frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2687                        }
2688                        else
2689                        {
2690                                frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2691                                backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2692                        }
2693                }
2694                else if (side == 1)
2695                {
2696                        frontRays.push_back(bRay);
2697                }
2698                else
2699                {
2700                        backRays.push_back(bRay);
2701                }
2702        }
2703
2704        return splits;
2705}
2706
2707
2708AxisAlignedBox3 VspTree::GetBoundingBox(VspNode *node) const
2709{
2710        if (!node->GetParent())
2711                return mBoundingBox;
2712
2713        if (!node->IsLeaf())
2714        {
2715                return (dynamic_cast<VspInterior *>(node))->GetBoundingBox();           
2716        }
2717
2718        VspInterior *parent = dynamic_cast<VspInterior *>(node->GetParent());
2719
2720        AxisAlignedBox3 box(parent->GetBoundingBox());
2721
2722        if (parent->GetFront() == node)
2723                box.SetMin(parent->GetAxis(), parent->GetPosition());
2724    else
2725                box.SetMax(parent->GetAxis(), parent->GetPosition());
2726
2727        return box;
2728}
2729
2730
2731int VspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2732                                                                         ViewCellContainer &viewCells) const
2733{
2734        stack<VspNode *> nodeStack;
2735 
2736        ViewCell::NewMail();
2737
2738        while (!nodeStack.empty())
2739        {
2740                VspNode *node = nodeStack.top();
2741                nodeStack.pop();
2742
2743                const AxisAlignedBox3 bbox = GetBoundingBox(node);
2744
2745                if (bbox.Includes(box))
2746                {
2747                        // node geometry is contained in box
2748                        CollectViewCells(node, true, viewCells, true);
2749                }
2750                else if (Overlap(bbox, box))
2751                {
2752                        if (node->IsLeaf())
2753                        {
2754                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2755                       
2756                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2757                                {
2758                                        leaf->GetViewCell()->Mail();
2759                                        viewCells.push_back(leaf->GetViewCell());
2760                                }
2761                        }
2762                        else
2763                        {
2764                                VspInterior *interior = dynamic_cast<VspInterior *>(node);
2765                       
2766                                VspNode *first = interior->GetFront();
2767                                VspNode *second = interior->GetBack();
2768           
2769                                nodeStack.push(first);
2770                                nodeStack.push(second);
2771                        }
2772                }       
2773                // default: cull
2774        }
2775
2776        return (int)viewCells.size();
2777}
2778
2779
2780void VspTree::PreprocessRays(const VssRayContainer &sampleRays,
2781                                                         RayInfoContainer &rays)
2782{
2783        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
2784
2785        long startTime = GetTime();
2786
2787        cout << "storing rays ... ";
2788
2789        Intersectable::NewMail();
2790
2791        //-- store rays and objects
2792        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
2793        {
2794                VssRay *ray = *rit;
2795                float minT, maxT;
2796                static Ray hray;
2797
2798                hray.Init(*ray);
2799               
2800                // TODO: not very efficient to implictly cast between rays types
2801                if (GetBoundingBox().GetRaySegment(hray, minT, maxT))
2802                {
2803                        float len = ray->Length();
2804
2805                        if (!len)
2806                                len = Limits::Small;
2807
2808                        rays.push_back(RayInfo(ray, minT / len, maxT / len));
2809                }
2810        }
2811
2812        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
2813}
2814
2815
2816void VspTree::GetViewCells(const VssRay &ray, ViewCellContainer &viewCells)
2817{
2818        static Ray hray;
2819        hray.Init(ray);
2820       
2821        float tmin = 0, tmax = 1.0;
2822
2823        if (!mBoundingBox.GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
2824                return;
2825
2826        const Vector3 origin = hray.Extrap(tmin);
2827        const Vector3 termination = hray.Extrap(tmax);
2828
2829        // view cells were not precomputed
2830        // don't mail because we need mailboxing for something else
2831        CastLineSegment(origin, termination, viewCells, false);
2832}
2833
2834
2835void VspTree::Initialise(const VssRayContainer &rays,
2836                                                 AxisAlignedBox3 *forcedBoundingBox)
2837{
2838        ComputeBoundingBox(rays, forcedBoundingBox);
2839
2840        VspLeaf *leaf = new VspLeaf();
2841        mRoot = leaf;
2842
2843        VspViewCell *viewCell = new VspViewCell();
2844    leaf->SetViewCell(viewCell);
2845
2846        // set view cell values
2847        viewCell->mLeaves.push_back(leaf);
2848
2849        viewCell->SetVolume(mBoundingBox.GetVolume());
2850    leaf->mProbability = mBoundingBox.GetVolume();
2851}
2852
2853
2854SubdivisionCandidate *VspTree::PrepareConstruction(const VssRayContainer &sampleRays,
2855                                                                                                   RayInfoContainer &rays)
2856{       
2857        mVspStats.Reset();
2858        mVspStats.Start();
2859        mVspStats.nodes = 1;
2860
2861        // store pointer to this tree
2862        VspSubdivisionCandidate::sVspTree = this;
2863       
2864        // initialise termination criteria
2865        mTermMinProbability *= mBoundingBox.GetVolume();
2866       
2867        // get clipped rays
2868        PreprocessRays(sampleRays, rays);
2869
2870        /// collect pvs from rays
2871        const int pvsSize = EvalPvsSize(rays);
2872       
2873        // root and bounding box were already constructed
2874        VspLeaf *leaf = dynamic_cast<VspLeaf *>(mRoot);
2875
2876        //////////
2877        //-- prepare view space partition
2878
2879        const float prop = mBoundingBox.GetVolume();
2880       
2881        // first vsp traversal data
2882        VspTraversalData vData(leaf, 0, &rays, pvsSize, prop, mBoundingBox);
2883
2884
2885#if WORK_WITH_VIEWCELL_PVS
2886        // add first view cell to all the objects view cell pvs
2887        ObjectPvsMap::const_iterator oit,
2888                oit_end = leaf->GetViewCell()->GetPvs().mEntries.end();
2889
2890        for (oit = leaf->GetViewCell()->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
2891        {
2892                Intersectable *obj = (*oit).first;
2893                obj->mViewCellPvs.AddSample(leaf->GetViewCell(), 1);
2894        }
2895#endif
2896
2897        //////////////
2898        //-- create the first split candidate
2899
2900        VspSubdivisionCandidate *splitCandidate = new VspSubdivisionCandidate(vData);
2901    EvalSubdivisionCandidate(*splitCandidate);
2902        leaf->SetSubdivisionCandidate(splitCandidate);
2903
2904        mTotalCost = (float)pvsSize;
2905        mPvsEntries = EvalPvsEntriesSize(rays);
2906
2907        EvalSubdivisionStats(*splitCandidate);
2908
2909        return splitCandidate;
2910}
2911
2912
2913void VspTree::CollectDirtyCandidate(const VssRay &ray,
2914                                                                        const bool isTermination,
2915                                                                        vector<SubdivisionCandidate *> &dirtyList,
2916                                                                        const bool onlyUnmailed) const
2917{
2918
2919        Intersectable *obj;
2920        Vector3 pt;
2921        KdNode *node;
2922
2923        ray.GetSampleData(isTermination, pt, &obj, &node);
2924       
2925        if (!obj) return;
2926       
2927        SubdivisionCandidate *candidate = NULL;
2928               
2929        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
2930        {
2931        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
2932                {
2933                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
2934
2935                        if (!leaf->Mailed())
2936                        {
2937                                leaf->Mail();
2938                                candidate = leaf->mSubdivisionCandidate;
2939                        }
2940                        break;
2941                }
2942        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
2943                {
2944                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
2945
2946                        if (!leaf->Mailed())
2947                        {
2948                                leaf->Mail();
2949                                candidate = leaf->GetSubdivisionCandidate();
2950                        }
2951                        break;
2952                }
2953        default:
2954                cerr << "not implemented yet" << endl;
2955                candidate = NULL;
2956                break;
2957        }
2958
2959        // is this leaf still a split candidate?
2960        if (candidate && (!onlyUnmailed || !candidate->Mailed()))
2961        {
2962                candidate->Mail();
2963                dirtyList.push_back(candidate);
2964        }
2965}
2966
2967
2968void VspTree::CollectDirtyCandidates(VspSubdivisionCandidate *sc,
2969                                                                         vector<SubdivisionCandidate *> &dirtyList,
2970                                                                         const bool onlyUnmailed)
2971{
2972        VspTraversalData &tData = sc->mParentData;
2973        VspLeaf *node = tData.mNode;
2974       
2975        KdLeaf::NewMail();
2976        BvhLeaf::NewMail();
2977       
2978        RayInfoContainer::const_iterator rit, rit_end = tData.mRays->end();
2979
2980        // add all kd nodes seen by the rays
2981        for (rit = tData.mRays->begin(); rit != rit_end; ++ rit)
2982        {
2983                VssRay *ray = (*rit).mRay;
2984               
2985                CollectDirtyCandidate(*ray, true, dirtyList, onlyUnmailed);
2986        CollectDirtyCandidate(*ray, false, dirtyList, onlyUnmailed);
2987        }
2988}
2989
2990
2991int VspTree::EvalMaxEventContribution(const VssRay &ray,
2992                                                                          const bool isTermination) const
2993{
2994        Intersectable *obj;
2995        Vector3 pt;
2996        KdNode *node;
2997
2998        ray.GetSampleData(isTermination, pt, &obj, &node);
2999
3000        if (!obj)
3001                return 0;
3002
3003        int pvs = 0;
3004
3005        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3006        {
3007        case HierarchyManager::NO_OBJ_SUBDIV:
3008                {
3009                        if (-- obj->mCounter == 0)
3010                                ++ pvs;
3011                        break;
3012                }
3013        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3014                {
3015                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3016
3017                        // add contributions of the kd nodes
3018                        pvs += EvalMaxEventContribution(leaf);
3019                        break;
3020                }
3021        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3022                {
3023                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3024
3025                        if (-- leaf->mCounter == 0)
3026                                pvs += (int)leaf->mObjects.size();
3027                        break;
3028                }
3029        default:
3030                break;
3031        }
3032
3033        return pvs;
3034}
3035
3036
3037int VspTree::PrepareHeuristics(const VssRay &ray, const bool isTermination)
3038{
3039        int pvsSize = 0;
3040       
3041        Intersectable *obj;
3042        Vector3 pt;
3043        KdNode *node;
3044
3045        ray.GetSampleData(isTermination, pt, &obj, &node);
3046
3047        if (!obj)
3048                return 0;
3049
3050        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3051        {
3052        case HierarchyManager::NO_OBJ_SUBDIV:
3053                {
3054                        if (!obj->Mailed())
3055                        {
3056                                obj->Mail();
3057                                obj->mCounter = 0;
3058                                ++ pvsSize;
3059                        }
3060
3061                        ++ obj->mCounter;       
3062                        break;
3063                }
3064        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3065                {
3066                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3067                        pvsSize += PrepareHeuristics(leaf);     
3068                        break;
3069                }
3070        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3071                {
3072                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3073
3074                        if (!leaf->Mailed())
3075                        {
3076                                leaf->Mail();
3077                                leaf->mCounter = 0;
3078                                pvsSize += (int)leaf->mObjects.size();
3079                        }
3080
3081                        ++ leaf->mCounter;     
3082                        break;
3083                }
3084        default:
3085                break;
3086        }
3087
3088        return pvsSize;
3089}
3090
3091
3092int VspTree::EvalMinEventContribution(const VssRay &ray,
3093                                                                          const bool isTermination) const
3094{
3095        Intersectable *obj;
3096        Vector3 pt;
3097        KdNode *node;
3098
3099        ray.GetSampleData(isTermination, pt, &obj, &node);
3100
3101        if (!obj) return 0;
3102
3103        int pvs = 0;
3104
3105        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3106        {
3107        case HierarchyManager::NO_OBJ_SUBDIV:
3108                {
3109                        if (!obj->Mailed())
3110                        {
3111                                obj->Mail();
3112                                ++ pvs;
3113                        }
3114                        break;
3115                }
3116        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3117                {
3118                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3119                        // add contributions of the kd nodes
3120                        pvs += EvalMinEventContribution(leaf);                         
3121                        break;
3122                }
3123        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3124                {
3125                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3126                        if (!leaf->Mailed())
3127                        {
3128                                leaf->Mail();
3129                                pvs += (int)leaf->mObjects.size();
3130                        }
3131                        break;
3132                }
3133        default:
3134                break;
3135        }
3136
3137        return pvs;
3138}
3139
3140
3141void VspTree::UpdateContributionsToPvs(const VssRay &ray,
3142                                                                           const bool isTermination,
3143                                                                           const int cf,
3144                                                                           float &frontPvs,
3145                                                                           float &backPvs,
3146                                                                           float &totalPvs) const
3147{
3148        Intersectable *obj;
3149        Vector3 pt;
3150        KdNode *node;
3151
3152        ray.GetSampleData(isTermination, pt, &obj, &node);
3153
3154        if (!obj) return;
3155
3156        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3157        {
3158                case HierarchyManager::NO_OBJ_SUBDIV:
3159                {
3160                        // find front and back pvs for origing and termination object
3161                        UpdateContributionsToPvs(obj, cf, frontPvs, backPvs, totalPvs);
3162                        break;
3163                }
3164                case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3165                {
3166                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3167                        UpdateContributionsToPvs(leaf, cf, frontPvs, backPvs, totalPvs);
3168                        break;
3169                }
3170                case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3171                {
3172                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3173                        UpdateContributionsToPvs(leaf, cf, frontPvs, backPvs, totalPvs);
3174                        break;
3175                }
3176        }
3177}
3178
3179
3180void VspTree::UpdatePvsEntriesContribution(const VssRay &ray,
3181                                                                                   const bool isTermination,
3182                                                                                   const int cf,
3183                                                                                   float &pvsFront,
3184                                                                                   float &pvsBack,
3185                                                                                   float &totalPvs) const
3186{
3187        Intersectable *obj;
3188        Vector3 pt;
3189        KdNode *node;
3190
3191        ray.GetSampleData(isTermination, pt, &obj, &node);
3192        if (!obj) return;
3193
3194        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3195        {
3196        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3197                // TODO
3198                break;
3199        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3200                {
3201                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3202                        UpdateContributionsToPvs(leaf, cf, pvsFront, pvsBack, totalPvs, true);
3203                        break;
3204                }
3205        default:
3206                UpdateContributionsToPvs(obj, cf, pvsFront, pvsBack, totalPvs);
3207                break;
3208        }
3209}
3210
3211
3212int VspTree::EvalContributionToPvs(const VssRay &ray, const bool isTermination) const
3213{       
3214        Intersectable *obj;
3215        Vector3 pt;
3216        KdNode *node;
3217
3218        ray.GetSampleData(isTermination, pt, &obj, &node);
3219
3220        if (!obj) return 0;
3221
3222        int pvs = 0;
3223
3224        switch(mHierarchyManager->GetObjectSpaceSubdivisionType())
3225        {
3226        case HierarchyManager::NO_OBJ_SUBDIV:
3227                {
3228                        if (!obj->Mailed())
3229                        {
3230                                obj->Mail();
3231                                ++ pvs;
3232                        }
3233                        break;
3234                }
3235        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3236                {
3237                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3238                        pvs += EvalContributionToPvs(leaf);
3239                        break;
3240                }
3241        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3242                {
3243                        BvhLeaf *bvhleaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3244
3245                        if (!bvhleaf->Mailed())
3246                        {
3247                                bvhleaf->Mail();
3248                                pvs += (int)bvhleaf->mObjects.size();
3249                        }
3250                        break;
3251                }
3252        default:
3253                break;
3254        }
3255
3256        return pvs;
3257}
3258
3259
3260int VspTree::EvalContributionToPvs(KdLeaf *leaf) const
3261{
3262        if (leaf->Mailed()) // leaf already mailed
3263                return 0;
3264       
3265        leaf->Mail();
3266
3267        // this is the pvs which is uniquely part of this kd leaf
3268        int pvs = (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size());
3269
3270        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
3271
3272        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
3273        {
3274                Intersectable *obj = *oit;
3275                if (!obj->Mailed())
3276                {
3277                        obj->Mail();
3278                        ++ pvs;
3279                }
3280        }
3281
3282        return pvs;
3283}
3284
3285
3286VspNode *VspTree::SubdivideAndCopy(SplitQueue &tQueue,
3287                                                                   SubdivisionCandidate *splitCandidate)
3288{
3289        // todo remove dynamic cast
3290        VspSubdivisionCandidate *sc = dynamic_cast<VspSubdivisionCandidate *>(splitCandidate);
3291
3292        VspTraversalData &tData = sc->mParentData;
3293        VspNode *newNode = tData.mNode;
3294        VspNode *oldNode = (VspNode *)splitCandidate->mEvaluationHack;
3295
3296        if (!oldNode->IsLeaf())
3297        {       
3298                ///////////
3299                //-- continue subdivision
3300
3301                VspTraversalData tFrontData;
3302                VspTraversalData tBackData;
3303               
3304                VspInterior *oldInterior = dynamic_cast<VspInterior *>(oldNode);
3305
3306                // create new interior node and two leaf node
3307                const AxisAlignedPlane splitPlane = oldInterior->GetPlane();
3308       
3309                sc->mSplitPlane = splitPlane;
3310       
3311                // evaluate the changes in render cost and pvs entries
3312                EvalSubdivisionCandidate(*sc, false);
3313
3314                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData);
3315       
3316                //oldNode->mRenderCostDecr += sc->GetRenderCostDecrease();
3317                //oldNode->mPvsEntriesIncr += sc->GetPvsEntriesIncr();
3318
3319                oldNode->mRenderCostDecr = sc->GetRenderCostDecrease();
3320                oldNode->mPvsEntriesIncr = sc->GetPvsEntriesIncr();
3321
3322                /////////////
3323                //-- evaluate new split candidates for global greedy cost heuristics
3324
3325                VspSubdivisionCandidate *frontCandidate = new VspSubdivisionCandidate(tFrontData);
3326                VspSubdivisionCandidate *backCandidate = new VspSubdivisionCandidate(tBackData);
3327
3328                frontCandidate->SetPriority((float)-oldInterior->GetFront()->mTimeStamp);
3329                backCandidate->SetPriority((float)-oldInterior->GetBack()->mTimeStamp);
3330
3331                frontCandidate->mEvaluationHack = oldInterior->GetFront();
3332                backCandidate->mEvaluationHack = oldInterior->GetBack();
3333
3334                // cross reference
3335                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
3336                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
3337
3338                tQueue.Push(frontCandidate);
3339                tQueue.Push(backCandidate);
3340
3341                // note: leaf is not destroyed because it is needed to collect
3342                // dirty candidates in hierarchy manager
3343        }
3344
3345        if (newNode->IsLeaf()) // subdivision terminated
3346        {
3347                // detach subdivision candidate: this leaf is no candidate for splitting anymore
3348                tData.mNode->SetSubdivisionCandidate(NULL);
3349                // detach node so it won't get deleted
3350                tData.mNode = NULL;
3351        }
3352
3353        return newNode;
3354}
3355
3356}
Note: See TracBrowser for help on using the repository browser.