source: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp @ 744

Revision 744, 90.6 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.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 "ViewCellBsp.h"
17#include "ViewCellsManager.h"
18#include "Beam.h"
19
20#define USE_FIXEDPOINT_T 0
21
22
23//-- static members
24
25
26int VspBspTree::sFrontId = 0;
27int VspBspTree::sBackId = 0;
28int VspBspTree::sFrontAndBackId = 0;
29
30typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
31
32
33// pvs penalty can be different from pvs size
34inline float EvalPvsPenalty(const int pvs,
35                                                        const int lower,
36                                                        const int upper)
37{
38        // clamp to minmax values
39        if (pvs < lower)
40                return (float)lower;
41        if (pvs > upper)
42                return (float)upper;
43
44        return (float)pvs;
45}
46
47
48
49
50/******************************************************************************/
51/*                       class VspBspTree implementation                      */
52/******************************************************************************/
53
54
55VspBspTree::VspBspTree():
56mRoot(NULL),
57mUseAreaForPvs(false),
58mCostNormalizer(Limits::Small),
59mViewCellsManager(NULL),
60mOutOfBoundsCell(NULL),
61mStoreRays(false),
62mRenderCostWeight(0.5),
63mUseRandomAxis(false),
64mTimeStamp(1)
65{
66        bool randomize = false;
67        environment->GetBoolValue("VspBspTree.Construction.randomize", randomize);
68        if (randomize)
69                Randomize(); // initialise random generator for heuristics
70
71        //-- termination criteria for autopartition
72        environment->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
73        environment->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
74        environment->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
75        environment->GetFloatValue("VspBspTree.Termination.minProbability", mTermMinProbability);
76        environment->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
77        environment->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
78        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
79        environment->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
80        environment->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
81
82        //-- max cost ratio for early tree termination
83        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
84
85        environment->GetFloatValue("VspBspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
86        environment->GetIntValue("VspBspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
87
88        // HACK//mTermMinPolygons = 25;
89
90        //-- factors for bsp tree split plane heuristics
91        environment->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
92        environment->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
93
94
95        //-- partition criteria
96        environment->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
97        environment->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
98        environment->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
99
100        environment->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
101        environment->GetIntValue("VspBspTree.maxTests", mMaxTests);
102
103        // if only the driving axis is used for axis aligned split
104        environment->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
105       
106        //-- termination criteria for axis aligned split
107        environment->GetFloatValue("VspBspTree.Termination.AxisAligned.maxRayContribution",
108                                                                mTermMaxRayContriForAxisAligned);
109        environment->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
110                                                         mTermMinRaysForAxisAligned);
111
112        //environment->GetFloatValue("VspBspTree.maxTotalMemory", mMaxTotalMemory);
113        environment->GetFloatValue("VspBspTree.maxStaticMemory", mMaxMemory);
114
115        environment->GetFloatValue("VspBspTree.Construction.renderCostWeight", mRenderCostWeight);
116        environment->GetBoolValue("VspBspTree.usePolygonSplitIfAvailable", mUsePolygonSplitIfAvailable);
117
118        environment->GetBoolValue("VspBspTree.useCostHeuristics", mUseCostHeuristics);
119        environment->GetBoolValue("VspBspTree.useSplitCostQueue", mUseSplitCostQueue);
120        environment->GetBoolValue("VspBspTree.simulateOctree", mSimulateOctree);
121        environment->GetBoolValue("VspBspTree.useRandomAxis", mUseRandomAxis);
122        environment->GetIntValue("VspBspTree.nodePriorityQueueType", mNodePriorityQueueType);
123
124        environment->GetBoolValue("ViewCells.PostProcess.emptyViewCellsMerge", mEmptyViewCellsMergeAllowed);
125       
126        char subdivisionStatsLog[100];
127        environment->GetStringValue("VspBspTree.subdivisionStats", subdivisionStatsLog);
128        mSubdivisionStats.open(subdivisionStatsLog);
129
130        //-- debug output
131
132        Debug << "******* VSP BSP options ******** " << endl;
133    Debug << "max depth: " << mTermMaxDepth << endl;
134        Debug << "min PVS: " << mTermMinPvs << endl;
135        Debug << "min probabiliy: " << mTermMinProbability << endl;
136        Debug << "min rays: " << mTermMinRays << endl;
137        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
138        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
139        Debug << "miss tolerance: " << mTermMissTolerance << endl;
140        Debug << "max view cells: " << mMaxViewCells << endl;
141        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
142        //Debug << "max plane candidates: " << mMaxRayCandidates << endl;
143        Debug << "randomize: " << randomize << endl;
144
145        Debug << "using area for pvs: " << mUseAreaForPvs << endl;
146        Debug << "render cost weight: " << mRenderCostWeight << endl;
147        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
148        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
149        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
150        Debug << "max memory: " << mMaxMemory << endl;
151        Debug << "use poly split if available: " << mUsePolygonSplitIfAvailable << endl;
152        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
153        Debug << "use split cost queue: " << mUseSplitCostQueue << endl;
154        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
155        Debug << "use random axis: " << mUseRandomAxis << endl;
156        Debug << "priority queue type: " << mNodePriorityQueueType << endl;
157        Debug << "empty view cells merge: " << mEmptyViewCellsMergeAllowed << endl;
158        Debug << "octree: " << mSimulateOctree << endl;
159
160        Debug << "Split plane strategy: ";
161
162        if (mSplitPlaneStrategy & RANDOM_POLYGON)
163        {
164                Debug << "random polygon ";
165        }
166        if (mSplitPlaneStrategy & AXIS_ALIGNED)
167        {
168                Debug << "axis aligned ";
169        }
170        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
171        {
172                mCostNormalizer += mLeastRaySplitsFactor;
173                Debug << "least ray splits ";
174        }
175        if (mSplitPlaneStrategy & BALANCED_RAYS)
176        {
177                mCostNormalizer += mBalancedRaysFactor;
178                Debug << "balanced rays ";
179        }
180        if (mSplitPlaneStrategy & PVS)
181        {
182                mCostNormalizer += mPvsFactor;
183                Debug << "pvs";
184        }
185
186
187        mSplitCandidates = new vector<SortableEntry>;
188
189        Debug << endl;
190}
191
192
193BspViewCell *VspBspTree::GetOutOfBoundsCell()
194{
195        return mOutOfBoundsCell;
196}
197
198
199BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
200{
201        if (!mOutOfBoundsCell)
202        {
203                mOutOfBoundsCell = new BspViewCell();
204                mOutOfBoundsCell->SetId(-1);
205                mOutOfBoundsCell->SetValid(false);
206        }
207
208        return mOutOfBoundsCell;
209}
210
211
212const BspTreeStatistics &VspBspTree::GetStatistics() const
213{
214        return mBspStats;
215}
216
217
218VspBspTree::~VspBspTree()
219{
220        DEL_PTR(mRoot);
221        DEL_PTR(mSplitCandidates);
222}
223
224
225int VspBspTree::AddMeshToPolygons(Mesh *mesh,
226                                                                  PolygonContainer &polys,
227                                                                  MeshInstance *parent)
228{
229        FaceContainer::const_iterator fi;
230
231        // copy the face data to polygons
232        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
233        {
234                Polygon3 *poly = new Polygon3((*fi), mesh);
235
236                if (poly->Valid(mEpsilon))
237                {
238                        poly->mParent = parent; // set parent intersectable
239                        polys.push_back(poly);
240                }
241                else
242                        DEL_PTR(poly);
243        }
244        return (int)mesh->mFaces.size();
245}
246
247
248int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
249                                                          PolygonContainer &polys,
250                                                          int maxObjects)
251{
252        int limit = (maxObjects > 0) ?
253                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
254
255        int polysSize = 0;
256
257        for (int i = 0; i < limit; ++ i)
258        {
259                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
260                {
261                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
262                        polysSize +=
263                                AddMeshToPolygons(viewCells[i]->GetMesh(),
264                                                                  polys,
265                                                                  viewCells[i]);
266                }
267        }
268
269        return polysSize;
270}
271
272
273int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
274                                                                 PolygonContainer &polys,
275                                                                 int maxObjects)
276{
277        int limit = (maxObjects > 0) ?
278                Min((int)objects.size(), maxObjects) : (int)objects.size();
279
280        for (int i = 0; i < limit; ++i)
281        {
282                Intersectable *object = objects[i];//*it;
283                Mesh *mesh = NULL;
284
285                switch (object->Type()) // extract the meshes
286                {
287                case Intersectable::MESH_INSTANCE:
288                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
289                        break;
290                case Intersectable::VIEW_CELL:
291                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
292                        break;
293                        // TODO: handle transformed mesh instances
294                default:
295                        Debug << "intersectable type not supported" << endl;
296                        break;
297                }
298
299        if (mesh) // copy the mesh data to polygons
300                {
301                        mBox.Include(object->GetBox()); // add to BSP tree aabb
302                        AddMeshToPolygons(mesh, polys, NULL);
303                }
304        }
305
306        return (int)polys.size();
307}
308
309
310void VspBspTree::Construct(const VssRayContainer &sampleRays,
311                                                   AxisAlignedBox3 *forcedBoundingBox)
312{
313        mBspStats.nodes = 1;
314        mBox.Initialize();      // initialise BSP tree bounding box
315
316        if (forcedBoundingBox)
317                mBox = *forcedBoundingBox;
318       
319        PolygonContainer polys;
320        RayInfoContainer *rays = new RayInfoContainer();
321
322        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
323
324        long startTime = GetTime();
325
326        cout << "Extracting polygons from rays ... ";
327
328        Intersectable::NewMail();
329
330        int numObj = 0;
331
332        //-- extract polygons intersected by the rays
333        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
334        {
335                VssRay *ray = *rit;
336
337                if ((mBox.IsInside(ray->mTermination) || !forcedBoundingBox) &&
338                        ray->mTerminationObject &&
339                        !ray->mTerminationObject->Mailed())
340                {
341                        ray->mTerminationObject->Mail();
342                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mTerminationObject);
343                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
344                        ++ numObj;
345
346                        //-- compute bounding box
347                        if (!forcedBoundingBox)
348                                mBox.Include(ray->mTermination);
349                }
350
351                if ((mBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
352                        ray->mOriginObject &&
353                        !ray->mOriginObject->Mailed())
354                {
355                        ray->mOriginObject->Mail();
356                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
357                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
358                        ++ numObj;
359
360                        //-- compute bounding box
361                        if (!forcedBoundingBox)
362                                mBox.Include(ray->mOrigin);
363                }
364        }
365       
366        Debug << "maximal pvs (i.e., pvs still considered as valid) : "
367                  << mViewCellsManager->GetMaxPvsSize() << endl;
368
369        //-- store rays
370        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
371        {
372                VssRay *ray = *rit;
373
374                float minT, maxT;
375
376                static Ray hray;
377                hray.Init(*ray);
378
379                // TODO: not very efficient to implictly cast between rays types
380                if (mBox.GetRaySegment(hray, minT, maxT))
381                {
382                        float len = ray->Length();
383
384                        if (!len)
385                                len = Limits::Small;
386
387                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
388                }
389        }
390
391        // normalize
392        if (mUseAreaForPvs)
393                mTermMinProbability *= mBox.SurfaceArea();
394        else
395                mTermMinProbability *= mBox.GetVolume();
396
397        // throw out unnecessary polygons
398        PreprocessPolygons(polys);
399
400        mBspStats.polys = (int)polys.size();
401        mGlobalCostMisses = 0;
402
403        cout << "finished" << endl;
404
405        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
406                  << (int)sampleRays.size() << " rays in "
407                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
408
409        // use split cost priority queue
410        if (mUseSplitCostQueue)
411        {
412                ConstructWithSplitQueue(polys, rays);
413        }
414        else
415        {
416                Construct(polys, rays);
417        }
418
419        // clean up polygons
420        CLEAR_CONTAINER(polys);
421}
422
423
424// TODO: return memory usage in MB
425float VspBspTree::GetMemUsage() const
426{
427        return (float)
428                 (sizeof(VspBspTree) +
429                  mBspStats.Leaves() * sizeof(BspLeaf) +
430                  mCreatedViewCells * sizeof(BspViewCell) +
431                  mBspStats.pvs * sizeof(ObjectPvsData) +
432                  mBspStats.Interior() * sizeof(BspInterior) +
433                  mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
434}
435
436
437
438void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
439{
440        VspBspTraversalQueue tQueue;
441
442        mRoot = new BspLeaf();
443
444        // constrruct root node geometry
445        BspNodeGeometry *geom = new BspNodeGeometry();
446        ConstructGeometry(mRoot, *geom);
447
448        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
449
450        VspBspTraversalData tData(mRoot,
451                                                          new PolygonContainer(polys),
452                                                          0,
453                                                          rays,
454                              ComputePvsSize(*rays),
455                                                          prop,
456                                                          geom);
457
458        EvalPriority(tData);
459
460
461        // first node is kd node, i.e. an axis aligned box
462        if (1)
463        tData.mIsKdNode = true;
464        else
465                tData.mIsKdNode = false;
466
467        tQueue.push(tData);
468
469
470        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
471        mTotalPvsSize = tData.mPvs;
472       
473        mSubdivisionStats
474                        << "#ViewCells\n1\n" <<  endl
475                        << "#RenderCostDecrease\n0\n" << endl
476                        << "#TotalRenderCost\n" << mTotalCost << endl
477                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
478
479        Debug << "total cost: " << mTotalCost << endl;
480       
481       
482        mBspStats.Start();
483        cout << "Constructing vsp bsp tree ... \n";
484
485        long startTime = GetTime();     
486        int nLeaves = 500;
487        int nViewCells = 500;
488
489        // used for intermediate time measurements and progress
490        long interTime = GetTime();     
491
492        mOutOfMemory = false;
493
494        mCreatedViewCells = 0;
495       
496        while (!tQueue.empty())
497        {
498                tData = tQueue.top();
499            tQueue.pop();               
500
501                if (0 && !mOutOfMemory)
502                {
503                        float mem = GetMemUsage();
504
505                        if (mem > mMaxMemory)
506                        {
507                                mOutOfMemory = true;
508                                Debug << "memory limit reached: " << mem << endl;
509                        }
510                }
511
512                // subdivide leaf node
513                BspNode *r = Subdivide(tQueue, tData);
514
515                if (r == mRoot)
516                        Debug << "VSP BSP tree construction time spent at root: "
517                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
518
519                if (mBspStats.Leaves() >= nLeaves)
520                {
521                        nLeaves += 500;
522
523                        cout << "leaves=" << mBspStats.Leaves() << endl;
524                        Debug << "needed "
525                                  << TimeDiff(interTime, GetTime())*1e-3
526                                  << " secs to create 500 view cells" << endl;
527                        interTime = GetTime();
528                }
529
530                if (mCreatedViewCells >= nViewCells)
531                {
532                        nViewCells += 500;
533
534                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
535                }
536        }
537
538        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
539        cout << "finished\n";
540
541        mBspStats.Stop();
542}
543
544
545
546void VspBspTree::ConstructWithSplitQueue(const PolygonContainer &polys,
547                                                                                          RayInfoContainer *rays)
548{
549        VspBspSplitQueue tQueue;
550
551        mRoot = new BspLeaf();
552
553        // constrruct root node geometry
554        BspNodeGeometry *geom = new BspNodeGeometry();
555        ConstructGeometry(mRoot, *geom);
556
557        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
558
559        VspBspTraversalData tData(mRoot,
560                                                          new PolygonContainer(polys),
561                                                          0,
562                                                          rays,
563                              ComputePvsSize(*rays),
564                                                          prop,
565                                                          geom);
566
567
568        // compute first split candidate
569        VspBspSplitCandidate splitCandidate;
570        EvalSplitCandidate(tData, splitCandidate);
571
572        tQueue.push(splitCandidate);
573
574        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
575        mTotalPvsSize = tData.mPvs;
576       
577        mSubdivisionStats
578                        << "#ViewCells\n1\n" <<  endl
579                        << "#RenderCostDecrease\n0\n" << endl
580                        << "#dummy\n0\n" << endl
581                        << "#TotalRenderCost\n" << mTotalCost << endl
582                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
583
584        Debug << "total cost: " << mTotalCost << endl;
585       
586       
587        mBspStats.Start();
588        cout << "Constructing vsp bsp tree ... \n";
589
590        long startTime = GetTime();     
591        int nLeaves = 500;
592        int nViewCells = 500;
593
594        // used for intermediate time measurements and progress
595        long interTime = GetTime();     
596
597        mOutOfMemory = false;
598
599        mCreatedViewCells = 0;
600       
601        while (!tQueue.empty())
602        {
603                splitCandidate = tQueue.top();
604            tQueue.pop();               
605
606                // cost ratio of cost decrease / totalCost
607                float costRatio = splitCandidate.GetCost() / mTotalCost;
608
609                //Debug << "cost ratio: " << costRatio << endl;
610
611                if (costRatio < mTermMinGlobalCostRatio)
612                        ++ mGlobalCostMisses;
613               
614                if (0 && !mOutOfMemory)
615                {
616                        float mem = GetMemUsage();
617
618                        if (mem > mMaxMemory)
619                        {
620                                mOutOfMemory = true;
621                                Debug << "memory limit reached: " << mem << endl;
622                        }
623                }
624
625                // subdivide leaf node
626                BspNode *r = Subdivide(tQueue, splitCandidate);
627
628                if (r == mRoot)
629                        Debug << "VSP BSP tree construction time spent at root: "
630                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
631
632                if (mBspStats.Leaves() >= nLeaves)
633                {
634                        nLeaves += 500;
635
636                        cout << "leaves=" << mBspStats.Leaves() << endl;
637                        Debug << "needed "
638                                  << TimeDiff(interTime, GetTime())*1e-3
639                                  << " secs to create 500 view cells" << endl;
640                        interTime = GetTime();
641                }
642
643                if (mCreatedViewCells == nViewCells)
644                {
645                        nViewCells += 500;
646
647                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
648                }
649        }
650
651        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
652        cout << "finished\n";
653
654        mBspStats.Stop();
655}
656
657
658bool VspBspTree::LocalTerminationCriteriaMet(const VspBspTraversalData &data) const
659{
660        return
661                (((int)data.mRays->size() <= mTermMinRays) ||
662                 (data.mPvs <= mTermMinPvs)   ||
663                 (data.mProbability <= mTermMinProbability) ||
664                 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
665                 (data.mDepth >= mTermMaxDepth));
666}
667
668
669bool VspBspTree::GlobalTerminationCriteriaMet(const VspBspTraversalData &data) const
670{
671        return
672                (mOutOfMemory
673                || (mBspStats.Leaves() >= mMaxViewCells)
674                || (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
675                 );
676}
677
678
679
680BspNode *VspBspTree::Subdivide(VspBspTraversalQueue &tQueue,
681                                                           VspBspTraversalData &tData)
682{
683        BspNode *newNode = tData.mNode;
684
685        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
686        {
687                PolygonContainer coincident;
688
689                VspBspTraversalData tFrontData;
690                VspBspTraversalData tBackData;
691
692                // create new interior node and two leaf nodes
693                // or return leaf as it is (if maxCostRatio missed)
694                int splitAxis;
695                bool splitFurther = true;
696                int maxCostMisses = tData.mMaxCostMisses;
697               
698                Plane3 splitPlane;
699                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
700               
701                // choose next split plane
702                if (!SelectPlane(splitPlane, leaf, tData, tFrontData, tBackData, splitAxis))
703                {
704                        ++ maxCostMisses;
705
706                        if (maxCostMisses > mTermMissTolerance)
707                        {
708                                // terminate branch because of max cost
709                                ++ mBspStats.maxCostNodes;
710                                splitFurther = false;
711                        }
712                }
713       
714                // if this a valid split => subdivide this node further
715                if (splitFurther) //-- continue subdivision
716                {
717                        newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
718
719                        if (splitAxis < 3)
720                                ++ mBspStats.splits[splitAxis];
721                        else
722                                ++ mBspStats.polySplits;
723
724                        tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
725                        tFrontData.mAxis = tBackData.mAxis = splitAxis;
726
727                        // how often was max cost ratio missed in this branch?
728                        tFrontData.mMaxCostMisses = maxCostMisses;
729                        tBackData.mMaxCostMisses = maxCostMisses;
730
731                        EvalPriority(tFrontData);
732                        EvalPriority(tBackData);
733
734                        // evaluate subdivision stats
735                        if (1)
736                        {
737                                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
738                                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
739                                float cData = (float)tData.mPvs * tData.mProbability;;
740
741                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
742
743                                mTotalCost += costDecr;
744                                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
745
746                                mSubdivisionStats
747                                                << "#ViewCells\n" << mBspStats.Leaves() << endl
748                                                << "#RenderCostDecrease\n" << -costDecr << endl
749                                                << "#TotalRenderCost\n" << mTotalCost << endl
750                                                << "#AvgRenderCost\n" << (float)mTotalPvsSize / (float)mBspStats.Leaves() << endl;
751                        }
752
753                        // push the children on the stack
754                        tQueue.push(tFrontData);
755                        tQueue.push(tBackData);
756
757                        // delete old leaf node
758                        DEL_PTR(tData.mNode);
759                }
760        }
761
762        //-- terminate traversal and create new view cell
763        if (newNode->IsLeaf())
764        {
765                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
766                BspViewCell *viewCell = new BspViewCell();
767               
768                leaf->SetViewCell(viewCell);
769       
770                //-- update pvs
771                int conSamp = 0;
772                float sampCon = 0.0f;
773                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
774
775                mBspStats.contributingSamples += conSamp;
776                mBspStats.sampleContributions +=(int) sampCon;
777
778                //-- store additional info
779                if (mStoreRays)
780                {
781                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
782                        for (it = tData.mRays->begin(); it != it_end; ++ it)
783                        {
784                                (*it).mRay->Ref();                     
785                                leaf->mVssRays.push_back((*it).mRay);
786                        }
787                }
788
789                // should I check here?
790                if (0 && !mViewCellsManager->CheckValidity(viewCell, 0, mViewCellsManager->GetMaxPvsSize()))
791                {
792                        viewCell->SetValid(false);
793                        leaf->SetTreeValid(false);
794                        PropagateUpValidity(leaf);
795
796                        ++ mBspStats.invalidLeaves;
797                }
798               
799        viewCell->mLeaf = leaf;
800
801                if (mUseAreaForPvs)
802                        viewCell->SetArea(tData.mProbability);
803                else
804                        viewCell->SetVolume(tData.mProbability);
805
806                leaf->mProbability = tData.mProbability;
807
808                EvaluateLeafStats(tData);               
809        }
810
811        //-- cleanup
812        tData.Clear();
813
814        return newNode;
815}
816
817// subdivide using a split plane queue
818BspNode *VspBspTree::Subdivide(VspBspSplitQueue &tQueue,
819                                                           VspBspSplitCandidate &splitCandidate)
820{
821        VspBspTraversalData &tData = splitCandidate.mParentData;
822
823        BspNode *newNode = tData.mNode;
824
825        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
826        {       
827                PolygonContainer coincident;
828
829                VspBspTraversalData tFrontData;
830                VspBspTraversalData tBackData;
831
832                //-- continue subdivision
833               
834                // create new interior node and two leaf node
835                const Plane3 splitPlane = splitCandidate.mSplitPlane;
836                               
837                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
838       
839                const int splitAxis = splitCandidate.mSplitAxis;
840                const int maxCostMisses = splitCandidate.mMaxCostMisses;
841
842                if (splitAxis < 3)
843                        ++ mBspStats.splits[splitAxis];
844                else
845                        ++ mBspStats.polySplits;
846
847                tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
848                tFrontData.mAxis = tBackData.mAxis = splitAxis;
849
850                // how often was max cost ratio missed in this branch?
851                tFrontData.mMaxCostMisses = maxCostMisses;
852                tBackData.mMaxCostMisses = maxCostMisses;
853                       
854               
855                if (1)
856                {
857                        float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
858                        float cBack = (float)tBackData.mPvs * tBackData.mProbability;
859                        float cData = (float)tData.mPvs * tData.mProbability;
860
861                       
862                        float costDecr =
863                                (cFront + cBack - cData) / mBox.GetVolume();
864
865                        mTotalCost += costDecr;
866                        mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
867
868                        mSubdivisionStats
869                                        << "#ViewCells\n" << mBspStats.Leaves() << endl
870                                        << "#RenderCostDecrease\n" << -costDecr << endl
871                                        << "#dummy\n" << splitCandidate.GetCost() << endl
872                                        << "#TotalRenderCost\n" << mTotalCost << endl
873                                        << "#AvgRenderCost\n" << (float)mTotalPvsSize / (float)mBspStats.Leaves() << endl;
874                }
875
876       
877                //-- push the new split candidates on the stack
878                VspBspSplitCandidate frontCandidate;
879                VspBspSplitCandidate backCandidate;
880
881                EvalSplitCandidate(tFrontData, frontCandidate);
882                EvalSplitCandidate(tBackData, backCandidate);
883       
884                tQueue.push(frontCandidate);
885                tQueue.push(backCandidate);
886       
887                // delete old leaf node
888                DEL_PTR(tData.mNode);
889        }
890
891
892        //-- terminate traversal and create new view cell
893        if (newNode->IsLeaf())
894        {
895                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
896                BspViewCell *viewCell = new BspViewCell();
897
898        leaf->SetViewCell(viewCell);
899               
900                //-- update pvs
901                int conSamp = 0;
902                float sampCon = 0.0f;
903                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
904
905                mBspStats.contributingSamples += conSamp;
906                mBspStats.sampleContributions +=(int) sampCon;
907
908                //-- store additional info
909                if (mStoreRays)
910                {
911                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
912                        for (it = tData.mRays->begin(); it != it_end; ++ it)
913                        {
914                                (*it).mRay->Ref();                     
915                                leaf->mVssRays.push_back((*it).mRay);
916                        }
917                }
918
919                // should I check here?
920                viewCell->mLeaf = leaf;
921
922                if (mUseAreaForPvs)
923                        viewCell->SetArea(tData.mProbability);
924                else
925                        viewCell->SetVolume(tData.mProbability);
926
927        leaf->mProbability = tData.mProbability;
928
929                EvaluateLeafStats(tData);               
930        }
931
932        //-- cleanup
933        tData.Clear();
934
935        return newNode;
936}
937
938
939void VspBspTree::EvalPriority(VspBspTraversalData &tData) const
940{
941    switch (mNodePriorityQueueType)
942        {
943        case BREATH_FIRST:
944                tData.mPriority = (float)-tData.mDepth;
945                break;
946        case DEPTH_FIRST:
947                tData.mPriority = (float)tData.mDepth;
948                break;
949        default:
950                tData.mPriority = tData.mPvs * tData.mProbability;
951                //Debug << "priority: " << tData.mPriority << endl;
952                break;
953        }
954}
955
956
957void VspBspTree::EvalSplitCandidate(VspBspTraversalData &tData,
958                                                                        VspBspSplitCandidate &splitData)
959{
960        VspBspTraversalData frontData;
961        VspBspTraversalData backData;
962
963        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
964
965        // compute locally best split plane
966    bool success = SelectPlane(splitData.mSplitPlane, leaf, tData,
967                                                           frontData, backData, splitData.mSplitAxis);
968
969        // TODO: reuse
970        DEL_PTR(frontData.mGeometry);
971        DEL_PTR(backData.mGeometry);
972       
973        // compute global decrease in render cost
974        splitData.mRenderCost = EvalRenderCostDecrease(splitData.mSplitPlane, tData);
975        splitData.mParentData = tData;
976        splitData.mMaxCostMisses = success ? tData.mMaxCostMisses : tData.mMaxCostMisses + 1;
977}
978
979
980BspInterior *VspBspTree::SubdivideNode(const Plane3 &splitPlane,
981                                                                           VspBspTraversalData &tData,
982                                                                           VspBspTraversalData &frontData,
983                                                                           VspBspTraversalData &backData,
984                                                                           PolygonContainer &coincident)
985{
986        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
987       
988        //-- the front and back traversal data is filled with the new values
989        frontData.mDepth = tData.mDepth + 1;
990        frontData.mPolygons = new PolygonContainer();
991        frontData.mRays = new RayInfoContainer();
992       
993        backData.mDepth = tData.mDepth + 1;
994        backData.mPolygons = new PolygonContainer();
995        backData.mRays = new RayInfoContainer();
996       
997
998        //-- subdivide rays
999        SplitRays(splitPlane,
1000                          *tData.mRays,
1001                          *frontData.mRays,
1002                          *backData.mRays);
1003
1004
1005        // compute pvs
1006        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1007        backData.mPvs = ComputePvsSize(*backData.mRays);
1008
1009        // split front and back node geometry and compute area
1010       
1011        // if geometry was not already computed
1012        if (!frontData.mGeometry && !backData.mGeometry)
1013        {
1014                frontData.mGeometry = new BspNodeGeometry();
1015                backData.mGeometry = new BspNodeGeometry();
1016
1017                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1018                                                                           *backData.mGeometry,
1019                                                                           splitPlane,
1020                                                                           mBox,
1021                                                                           //0.0f);
1022                                                                           mEpsilon);
1023               
1024                if (mUseAreaForPvs)
1025                {
1026                        frontData.mProbability = frontData.mGeometry->GetArea();
1027                        backData.mProbability = backData.mGeometry->GetArea();
1028                }
1029                else
1030                {
1031                        frontData.mProbability = frontData.mGeometry->GetVolume();
1032                        backData.mProbability = tData.mProbability - frontData.mProbability;
1033
1034                        // should never come here: wrong volume !!!
1035                        if (0)
1036                        {
1037                                if (frontData.mProbability < -0.00001)
1038                                        Debug << "fatal error f: " << frontData.mProbability << endl;
1039                                if (backData.mProbability < -0.00001)
1040                                        Debug << "fatal error b: " << backData.mProbability << endl;
1041
1042                                // clamp because of precision issues
1043                                if (frontData.mProbability < 0) frontData.mProbability = 0;
1044                                if (backData.mProbability < 0) backData.mProbability = 0;
1045                        }
1046                }
1047        }
1048
1049       
1050    // subdivide polygons
1051        SplitPolygons(splitPlane,
1052                                  *tData.mPolygons,
1053                      *frontData.mPolygons,
1054                                  *backData.mPolygons,
1055                                  coincident);
1056
1057
1058
1059        ///////////////////////////////////////
1060        // subdivide further
1061
1062        // store maximal and minimal depth
1063        if (tData.mDepth > mBspStats.maxDepth)
1064        {
1065                Debug << "max depth increases to " << tData.mDepth << " at " << mBspStats.Leaves() << " leaves" << endl;
1066                mBspStats.maxDepth = tData.mDepth;
1067        }
1068
1069        mBspStats.nodes += 2;
1070
1071   
1072        BspInterior *interior = new BspInterior(splitPlane);
1073
1074#ifdef _DEBUG
1075        Debug << interior << endl;
1076#endif
1077
1078
1079        //-- create front and back leaf
1080
1081        BspInterior *parent = leaf->GetParent();
1082
1083        // replace a link from node's parent
1084        if (parent)
1085        {
1086                parent->ReplaceChildLink(leaf, interior);
1087                interior->SetParent(parent);
1088        }
1089        else // new root
1090        {
1091                mRoot = interior;
1092        }
1093
1094        // and setup child links
1095        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1096
1097        frontData.mNode = interior->GetFront();
1098        backData.mNode = interior->GetBack();
1099
1100        interior->mTimeStamp = mTimeStamp ++;
1101       
1102
1103        //DEL_PTR(leaf);
1104        return interior;
1105}
1106
1107
1108void VspBspTree::AddToPvs(BspLeaf *leaf,
1109                                                  const RayInfoContainer &rays,
1110                                                  float &sampleContributions,
1111                                                  int &contributingSamples)
1112{
1113  sampleContributions = 0;
1114  contributingSamples = 0;
1115 
1116  RayInfoContainer::const_iterator it, it_end = rays.end();
1117 
1118  ViewCell *vc = leaf->GetViewCell();
1119 
1120  // add contributions from samples to the PVS
1121  for (it = rays.begin(); it != it_end; ++ it)
1122        {
1123          float sc = 0.0f;
1124          VssRay *ray = (*it).mRay;
1125          bool madeContrib = false;
1126          float contribution;
1127          if (ray->mTerminationObject) {
1128                if (vc->GetPvs().AddSample(ray->mTerminationObject, ray->mPdf, contribution))
1129                  madeContrib = true;
1130                sc += contribution;
1131          }
1132         
1133          if (ray->mOriginObject) {
1134                if (vc->GetPvs().AddSample(ray->mOriginObject, ray->mPdf, contribution))
1135                  madeContrib = true;
1136                sc += contribution;
1137          }
1138         
1139          sampleContributions += sc;
1140          if (madeContrib)
1141                  ++ contributingSamples;
1142               
1143          //leaf->mVssRays.push_back(ray);
1144        }
1145}
1146
1147
1148void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays,
1149                                                                         const int axis,
1150                                                                         float minBand,
1151                                                                         float maxBand)
1152{
1153        mSplitCandidates->clear();
1154
1155        int requestedSize = 2 * (int)(rays.size());
1156        // creates a sorted split candidates array
1157        if (mSplitCandidates->capacity() > 500000 &&
1158                requestedSize < (int)(mSplitCandidates->capacity() / 10) )
1159        {
1160        delete mSplitCandidates;
1161                mSplitCandidates = new vector<SortableEntry>;
1162        }
1163
1164        mSplitCandidates->reserve(requestedSize);
1165
1166        float pos;
1167
1168        // float values => don't compare with exact values
1169        if (0)
1170        {
1171                minBand += Limits::Small;
1172                maxBand -= Limits::Small;
1173        }
1174
1175        // insert all queries
1176        for (RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
1177        {
1178                const bool positive = (*ri).mRay->HasPosDir(axis);
1179                               
1180                pos = (*ri).ExtrapOrigin(axis);
1181                // clamp to min / max band
1182                if (0) ClipValue(pos, minBand, maxBand);
1183               
1184                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
1185                        pos, (*ri).mRay));
1186
1187                pos = (*ri).ExtrapTermination(axis);
1188                // clamp to min / max band
1189                if (0) ClipValue(pos, minBand, maxBand);
1190
1191                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
1192                        pos, (*ri).mRay));
1193        }
1194
1195        stable_sort(mSplitCandidates->begin(), mSplitCandidates->end());
1196}
1197
1198
1199float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
1200                                                                                  const AxisAlignedBox3 &box,
1201                                                                                  const int pvsSize,
1202                                                                                  const int axis,
1203                                          float &position)
1204{
1205        const float minBox = box.Min(axis);
1206        const float maxBox = box.Max(axis);
1207        const float sizeBox = maxBox - minBox;
1208
1209        const float minBand = minBox + 0.1f * sizeBox;
1210        const float maxBand = minBox + 0.9f * sizeBox;
1211
1212        SortSplitCandidates(rays, axis, minBand, maxBand);
1213
1214        // go through the lists, count the number of objects left and right
1215        // and evaluate the following cost funcion:
1216        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
1217
1218        int pvsl = 0, pvsr = pvsSize;
1219
1220        int pvsBack = pvsl;
1221        int pvsFront = pvsr;
1222
1223        float sum = (float)pvsSize * sizeBox;
1224        float minSum = 1e20f;
1225
1226        // if no border can be found, take mid split
1227        position = minBox + 0.5f * sizeBox;
1228
1229        Intersectable::NewMail();
1230
1231        RayInfoContainer::const_iterator ri, ri_end = rays.end();
1232
1233        // set all object as belonging to the front pvs
1234        for(ri = rays.begin(); ri != ri_end; ++ ri)
1235        {
1236                Intersectable *oObject = (*ri).mRay->mOriginObject;
1237                Intersectable *tObject = (*ri).mRay->mTerminationObject;
1238
1239                if (oObject)
1240                {
1241                        if (!oObject->Mailed())
1242                        {
1243                                oObject->Mail();
1244                                oObject->mCounter = 1;
1245                        }
1246                        else
1247                        {
1248                                ++ oObject->mCounter;
1249                        }
1250                }
1251                if (tObject)
1252                {
1253                        if (!tObject->Mailed())
1254                        {
1255                                tObject->Mail();
1256                                tObject->mCounter = 1;
1257                        }
1258                        else
1259                        {
1260                                ++ tObject->mCounter;
1261                        }
1262                }
1263        }
1264
1265        Intersectable::NewMail();
1266
1267        vector<SortableEntry>::const_iterator ci, ci_end = mSplitCandidates->end();
1268
1269        for (ci = mSplitCandidates->begin(); ci < ci_end; ++ ci)
1270        {
1271                VssRay *ray;
1272                ray = (*ci).ray;
1273               
1274                Intersectable *oObject = ray->mOriginObject;
1275                Intersectable *tObject = ray->mTerminationObject;
1276               
1277
1278                switch ((*ci).type)
1279                {
1280                        case SortableEntry::ERayMin:
1281                                {
1282                                        if (oObject && !oObject->Mailed())
1283                                        {
1284                                                oObject->Mail();
1285                                                ++ pvsl;
1286                                        }
1287                                        if (tObject && !tObject->Mailed())
1288                                        {
1289                                                tObject->Mail();
1290                                                ++ pvsl;
1291                                        }
1292                                        break;
1293                                }
1294                        case SortableEntry::ERayMax:
1295                                {
1296                                        if (oObject)
1297                                        {
1298                                                if (-- oObject->mCounter == 0)
1299                                                        -- pvsr;
1300                                        }
1301
1302                                        if (tObject)
1303                                        {
1304                                                if (-- tObject->mCounter == 0)
1305                                                        -- pvsr;
1306                                        }
1307
1308                                        break;
1309                                }
1310                }
1311
1312                // Note: sufficient to compare size of bounding boxes of front and back side?
1313                if (((*ci).value >= minBand) && ((*ci).value <= maxBand))
1314                {
1315                        sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value);
1316
1317                        //  cout<<"pos="<<(*ci).value<<"\t q=("<<ql<<","<<qr<<")\t r=("<<rl<<","<<rr<<")"<<endl;
1318                        // cout<<"cost= "<<sum<<endl;
1319
1320                        if (sum < minSum)
1321                        {
1322                                minSum = sum;
1323                                position = (*ci).value;
1324                               
1325                                pvsBack = pvsl;
1326                                pvsFront = pvsr;
1327                        }
1328                }
1329        }
1330       
1331        //Debug << "pos: " << position << " sizebox: " << sizeBox << " pvs: " << pvsSize << endl;
1332
1333        // -- compute cost
1334        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1335        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1336
1337        const float pOverall = sizeBox;
1338
1339        const float pBack = position - minBox;
1340        const float pFront = maxBox - position;
1341       
1342        const float penaltyOld = EvalPvsPenalty(pvsSize, lowerPvsLimit, upperPvsLimit);
1343    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1344        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1345       
1346        const float oldRenderCost = penaltyOld * pOverall;
1347        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1348
1349        float ratio = mPvsFactor * newRenderCost / (oldRenderCost + Limits::Small);
1350
1351        //Debug << "costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
1352        //     <<"\t q=(" << queriesBack << "," << queriesFront << ")\t r=(" << raysBack << "," << raysFront << ")" << endl;
1353
1354        return ratio;
1355}
1356
1357
1358float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
1359                                                                                 const VspBspTraversalData &tData,
1360                                                                                 int &axis,
1361                                                                                 BspNodeGeometry **frontGeom,
1362                                                                                 BspNodeGeometry **backGeom,
1363                                                                                 float &pFront,
1364                                                                                 float &pBack,
1365                                                                                 const bool isKdNode)
1366{
1367        float nPosition[3];
1368        float nCostRatio[3];
1369        float nProbFront[3];
1370        float nProbBack[3];
1371
1372        BspNodeGeometry *nFrontGeom[3];
1373        BspNodeGeometry *nBackGeom[3];
1374
1375        for (int i = 0; i < 3; ++ i)
1376        {
1377                nFrontGeom[i] = NULL;
1378                nBackGeom[i] = NULL;
1379        }
1380
1381        int bestAxis = -1;
1382
1383        // create bounding box of node geometry
1384        AxisAlignedBox3 box;
1385               
1386        //TODO: for kd split geometry already is box => only take minmax vertices
1387        if (1)
1388        {
1389                tData.mGeometry->GetBoundingBox(box);
1390        }
1391        else
1392        {
1393                box.Initialize();
1394                RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
1395
1396                for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
1397                        box.Include((*ri).ExtrapTermination());
1398        }
1399
1400        int sAxis = 0;
1401
1402        bool useSpecialAxis = mOnlyDrivingAxis || mUseRandomAxis || mSimulateOctree;
1403
1404        // use some kind of specialised fixed axis
1405        if (mOnlyDrivingAxis)
1406                sAxis = box.Size().DrivingAxis();
1407        else if (mUseRandomAxis)
1408                sAxis = Random(3);
1409        else if (mSimulateOctree)
1410                sAxis = (tData.mAxis + 1) % 3;
1411               
1412        //Debug << "use special axis: " << useSpecialAxis << endl;
1413        //Debug << "axis: " << sAxis << " drivingaxis: " << box.Size().DrivingAxis();
1414
1415        for (axis = 0; axis < 3; ++ axis)
1416        {
1417                if (!useSpecialAxis || (axis == sAxis))
1418                {
1419                        if (!mUseCostHeuristics)
1420                        {
1421                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1422                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
1423
1424                                // allows faster split because we have axis aligned kd tree boxes
1425                                if (0 && isKdNode)
1426                                {
1427                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
1428                                                                                                                                box,
1429                                                                                                                                axis,
1430                                                                                                                                nPosition[axis],
1431                                                                                                                                nProbFront[axis],
1432                                                                                                                                nProbBack[axis]);
1433                                       
1434                                        Vector3 pos;
1435                                       
1436                                        // create back geometry from box
1437                                        pos = box.Max(); pos[axis] = nPosition[axis];
1438                                        AxisAlignedBox3 bBox(box.Min(), pos);
1439                                        PolygonContainer fPolys;
1440                                        bBox.ExtractPolys(fPolys);
1441
1442                                        nBackGeom[axis] = new BspNodeGeometry(fPolys);
1443       
1444                                        // create front geometry from box
1445                                        pos = box.Min(); pos[axis] = nPosition[axis];
1446                                        AxisAlignedBox3 fBox(pos, box.Max());
1447
1448                                        PolygonContainer bPolys;
1449                                        fBox.ExtractPolys(bPolys);
1450                                        nFrontGeom[axis] = new BspNodeGeometry(bPolys);
1451                                }
1452                                else
1453                                {
1454                                        nFrontGeom[axis] = new BspNodeGeometry();
1455                                        nBackGeom[axis] = new BspNodeGeometry();
1456
1457                                        nCostRatio[axis] =
1458                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1459                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1460                                                                                   nProbFront[axis], nProbBack[axis]);
1461                                }
1462                        }
1463                        else
1464                        {
1465                                nCostRatio[axis] =
1466                                        BestCostRatioHeuristics(*tData.mRays,
1467                                                                                    box,
1468                                                                                        tData.mPvs,
1469                                                                                        axis,
1470                                                                                        nPosition[axis]);
1471                        }
1472
1473                        if (bestAxis == -1)
1474                        {
1475                                bestAxis = axis;
1476                        }
1477                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
1478                        {
1479                                bestAxis = axis;
1480                        }
1481
1482                }
1483        }
1484
1485        //-- assign values
1486        axis = bestAxis;
1487        pFront = nProbFront[bestAxis];
1488        pBack = nProbBack[bestAxis];
1489
1490        // assign best split nodes geometry
1491        *frontGeom = nFrontGeom[bestAxis];
1492        *backGeom = nBackGeom[bestAxis];
1493
1494        // and delete other geometry
1495        DEL_PTR(nFrontGeom[(bestAxis + 1) % 3]);
1496        DEL_PTR(nBackGeom[(bestAxis + 2) % 3]);
1497
1498        //-- split plane
1499    Vector3 normal(0,0,0); normal[bestAxis] = 1;
1500        plane = Plane3(normal, nPosition[bestAxis]);
1501
1502        return nCostRatio[bestAxis];
1503}
1504
1505
1506bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1507                                                         BspLeaf *leaf,
1508                                                         VspBspTraversalData &data,                                                     
1509                                                         VspBspTraversalData &frontData,
1510                                                         VspBspTraversalData &backData,
1511                                                         int &splitAxis)
1512{
1513        // simplest strategy: just take next polygon
1514        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1515        {
1516        if (!data.mPolygons->empty())
1517                {
1518                        const int randIdx =
1519                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1520                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
1521
1522                        bestPlane = nextPoly->GetSupportingPlane();
1523                        return true;
1524                }
1525        }
1526
1527        //-- use heuristics to find appropriate plane
1528
1529        // intermediate plane
1530        Plane3 plane;
1531        float lowestCost = MAX_FLOAT;
1532       
1533        // decides if the first few splits should be only axisAligned
1534        const bool onlyAxisAligned  =
1535                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1536                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1537                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1538       
1539        const int limit = onlyAxisAligned ? 0 :
1540                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1541
1542        float candidateCost;
1543
1544        int maxIdx = (int)data.mPolygons->size();
1545
1546        for (int i = 0; i < limit; ++ i)
1547        {
1548                // the already taken candidates are stored behind maxIdx
1549                // => assure that no index is taken twice
1550                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1551                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1552
1553                // swap candidate to the end to avoid testing same plane
1554                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1555                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1556
1557                // evaluate current candidate
1558                BspNodeGeometry fGeom, bGeom;
1559                float fArea, bArea;
1560                plane = poly->GetSupportingPlane();
1561                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
1562               
1563                if (candidateCost < lowestCost)
1564                {
1565                        bestPlane = plane;
1566                        lowestCost = candidateCost;
1567                }
1568        }
1569
1570        //-- evaluate axis aligned splits
1571        int axis;
1572        BspNodeGeometry *fGeom, *bGeom;
1573        float pFront, pBack;
1574
1575        candidateCost = 99999999.0f;
1576
1577        // option: axis aligned split only if no polygon available
1578        if (!mUsePolygonSplitIfAvailable || data.mPolygons->empty())
1579        {
1580                candidateCost = SelectAxisAlignedPlane(plane,
1581                                                                                           data,
1582                                                                                           axis,
1583                                                                                           &fGeom,
1584                                                                                           &bGeom,
1585                                                                                           pFront,
1586                                                                                           pBack,
1587                                                                                           data.mIsKdNode);     
1588        }
1589
1590        splitAxis = 3;
1591
1592        if (candidateCost < lowestCost)
1593        {       
1594                bestPlane = plane;
1595                lowestCost = candidateCost;
1596                splitAxis = axis;
1597       
1598                // assign already computed values
1599                // we can do this because we always save the
1600                // computed values from the axis aligned splits         
1601
1602                if (fGeom && bGeom)
1603                {
1604                        frontData.mGeometry = fGeom;
1605                        backData.mGeometry = bGeom;
1606       
1607                        frontData.mProbability = pFront;
1608                        backData.mProbability = pBack;
1609                }
1610        }
1611        else
1612        {
1613                DEL_PTR(fGeom);
1614                DEL_PTR(bGeom);
1615        }
1616   
1617
1618//      if (lowestCost > 10)
1619//              Debug << "warning!! lowest cost: " << lowestCost << endl;
1620       
1621#ifdef _DEBUG
1622        Debug << "plane lowest cost: " << lowestCost << endl;
1623#endif
1624
1625        if (lowestCost > mTermMaxCostRatio)
1626        {
1627                return false;
1628        }
1629
1630        return true;
1631}
1632
1633
1634Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
1635{
1636        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1637
1638        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1639        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1640
1641        const Vector3 pt = (maxPt + minPt) * 0.5;
1642        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1643
1644        return Plane3(normal, pt);
1645}
1646
1647
1648Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
1649{
1650        Vector3 pt[3];
1651
1652        int idx[3];
1653        int cmaxT = 0;
1654        int cminT = 0;
1655        bool chooseMin = false;
1656
1657        for (int j = 0; j < 3; ++ j)
1658        {
1659                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1660
1661                if (idx[j] >= (int)rays.size())
1662                {
1663                        idx[j] -= (int)rays.size();
1664
1665                        chooseMin = (cminT < 2);
1666                }
1667                else
1668                        chooseMin = (cmaxT < 2);
1669
1670                RayInfo rayInf = rays[idx[j]];
1671                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1672        }
1673
1674        return Plane3(pt[0], pt[1], pt[2]);
1675}
1676
1677
1678Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1679{
1680        Vector3 pt[3];
1681
1682        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1683        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1684
1685        // check if rays different
1686        if (idx1 == idx2)
1687                idx2 = (idx2 + 1) % (int)rays.size();
1688
1689        const RayInfo ray1 = rays[idx1];
1690        const RayInfo ray2 = rays[idx2];
1691
1692        // normal vector of the plane parallel to both lines
1693        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1694
1695        // vector from line 1 to line 2
1696        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1697
1698        // project vector on normal to get distance
1699        const float dist = DotProd(vd, norm);
1700
1701        // point on plane lies halfway between the two planes
1702        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1703
1704        return Plane3(norm, planePt);
1705}
1706
1707
1708inline void VspBspTree::GenerateUniqueIdsForPvs()
1709{
1710        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1711        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1712        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
1713}
1714
1715
1716float VspBspTree::EvalRenderCostDecrease(const Plane3 &candidatePlane,
1717                                                                                 const VspBspTraversalData &data) const
1718{
1719        float pvsFront = 0;
1720        float pvsBack = 0;
1721        float totalPvs = 0;
1722
1723        // probability that view point lies in back / front node
1724        float pOverall = data.mProbability;
1725        float pFront = 0;
1726        float pBack = 0;
1727
1728
1729        // create unique ids for pvs heuristics
1730        GenerateUniqueIdsForPvs();
1731       
1732        for (int i = 0; i < data.mRays->size(); ++ i)
1733        {
1734                RayInfo rayInf = (*data.mRays)[i];
1735
1736                float t;
1737                VssRay *ray = rayInf.mRay;
1738                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1739
1740                // find front and back pvs for origing and termination object
1741                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1742                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1743        }
1744
1745
1746        BspNodeGeometry geomFront;
1747        BspNodeGeometry geomBack;
1748
1749        // construct child geometry with regard to the candidate split plane
1750        data.mGeometry->SplitGeometry(geomFront,
1751                                                                  geomBack,
1752                                                                  candidatePlane,
1753                                                                  mBox,
1754                                                                  //0.0f);
1755                                                                  mEpsilon);
1756
1757        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1758        {
1759                pFront = geomFront.GetVolume();
1760                pBack = pOverall - pFront;
1761
1762                // something is wrong with the volume
1763                if ((pFront < 0.0) || (pBack < 0.0))
1764                {
1765                        Debug << "vol f " << pFront << " b " << pBack << " p " << pOverall << endl;
1766                        Debug << "real vol f " << pFront << " b " << geomBack.GetVolume() << " p " << pOverall << endl;
1767                        Debug << "polys f " << geomFront.Size() << " b " << geomBack.Size() << " data " << data.mGeometry->Size() << endl;
1768                }
1769
1770                // clamp because of possible precision issues
1771                if (0)
1772                {
1773                        if (pFront < 0) pFront = 0;
1774                        if (pBack < 0) pBack = 0;
1775                }
1776        }
1777        else
1778        {
1779                pFront = geomFront.GetArea();
1780                pBack = geomBack.GetArea();
1781        }
1782       
1783
1784        // -- pvs rendering heuristics
1785        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1786        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1787
1788        // only render cost heuristics or combined with standard deviation
1789        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1790    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1791        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1792                       
1793        const float oldRenderCost = pOverall * penaltyOld;
1794        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1795
1796        //Debug << "decrease: " << oldRenderCost - newRenderCost << endl;
1797        return (oldRenderCost - newRenderCost) / mBox.GetVolume();
1798}
1799
1800
1801float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1802                                                                         const VspBspTraversalData &data,
1803                                                                         BspNodeGeometry &geomFront,
1804                                                                         BspNodeGeometry &geomBack,
1805                                                                         float &pFront,
1806                                                                         float &pBack) const
1807{
1808        float cost = 0;
1809
1810        float totalPvs = 0;
1811        float pvsFront = 0;
1812        float pvsBack = 0;
1813       
1814        // probability that view point lies in back / front node
1815        float pOverall = 0;
1816        pFront = 0;
1817        pBack = 0;
1818
1819
1820        int limit;
1821        bool useRand;
1822
1823        // create unique ids for pvs heuristics
1824        GenerateUniqueIdsForPvs();
1825
1826        // choose test rays randomly if too much
1827        if ((int)data.mRays->size() > mMaxTests)
1828        {
1829                useRand = true;
1830                limit = mMaxTests;
1831        }
1832        else
1833        {
1834                useRand = false;
1835                limit = (int)data.mRays->size();
1836        }
1837       
1838        for (int i = 0; i < limit; ++ i)
1839        {
1840                const int testIdx = useRand ?
1841                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
1842                RayInfo rayInf = (*data.mRays)[testIdx];
1843
1844                float t;
1845                VssRay *ray = rayInf.mRay;
1846                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1847
1848                // find front and back pvs for origing and termination object
1849                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1850                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1851        }
1852
1853        // construct child geometry with regard to the candidate split plane
1854        bool splitSuccessFull = data.mGeometry->SplitGeometry(geomFront,
1855                                                                                                                  geomBack,
1856                                                                                                                  candidatePlane,
1857                                                                                                                  mBox,
1858                                                                                                                  //0.0f);
1859                                                                                                                  mEpsilon);
1860
1861        pOverall = data.mProbability;
1862
1863        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1864        {
1865                pFront = geomFront.GetVolume();
1866                pBack = pOverall - pFront;
1867               
1868                // HACK: precision issues possible for unbalanced split => don't take this split!
1869                if (1 &&
1870                        (!splitSuccessFull || (pFront <= 0) || (pBack <= 0) ||
1871                        !geomFront.Valid() || !geomBack.Valid()))
1872                {
1873                        Debug << "error f: " << pFront << " b: " << pBack << endl;
1874                        return 99999.9f;
1875                }
1876        }
1877        else
1878        {
1879                pFront = geomFront.GetArea();
1880                pBack = geomBack.GetArea();
1881        }
1882       
1883
1884        // -- pvs rendering heuristics
1885        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1886        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1887
1888        // only render cost heuristics or combined with standard deviation
1889        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1890    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1891        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1892                       
1893        const float oldRenderCost = pOverall * penaltyOld;
1894        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1895
1896        float oldCost, newCost;
1897
1898        // only render cost
1899        if (1)
1900        {
1901                oldCost = oldRenderCost;
1902                newCost = newRenderCost;
1903        }
1904        else // also considering standard deviation
1905        {
1906                // standard deviation is difference of back and front pvs
1907                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
1908
1909                const float newDeviation = 0.5f *
1910                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
1911
1912                const float oldDeviation = penaltyOld;
1913
1914                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
1915                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
1916        }
1917
1918        cost += mPvsFactor * newCost / (oldCost + Limits::Small);
1919               
1920
1921#ifdef _DEBUG
1922        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
1923                  << " frontpvs: " << pvsFront << " pFront: " << pFront
1924                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
1925        Debug << "cost: " << cost << endl;
1926#endif
1927
1928        return cost;
1929}
1930
1931
1932int VspBspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
1933                                                                                ViewCellContainer &viewCells) const
1934{
1935        stack<bspNodePair> nodeStack;
1936        BspNodeGeometry *rgeom = new BspNodeGeometry();
1937
1938        ConstructGeometry(mRoot, *rgeom);
1939
1940        nodeStack.push(bspNodePair(mRoot, rgeom));
1941 
1942        ViewCell::NewMail();
1943
1944        while (!nodeStack.empty())
1945        {
1946                BspNode *node = nodeStack.top().first;
1947                BspNodeGeometry *geom = nodeStack.top().second;
1948                nodeStack.pop();
1949
1950                const int side = geom->ComputeIntersection(box);
1951               
1952                switch (side)
1953                {
1954                case -1:
1955                        // node geometry is contained in box
1956                        CollectViewCells(node, true, viewCells, true);
1957                        break;
1958
1959                case 0:
1960                        if (node->IsLeaf())
1961                        {
1962                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1963                       
1964                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
1965                                {
1966                                        leaf->GetViewCell()->Mail();
1967                                        viewCells.push_back(leaf->GetViewCell());
1968                                }
1969                        }
1970                        else
1971                        {
1972                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
1973                       
1974                                BspNode *first = interior->GetFront();
1975                                BspNode *second = interior->GetBack();
1976           
1977                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
1978                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
1979
1980                                geom->SplitGeometry(*firstGeom,
1981                                                                        *secondGeom,
1982                                                                        interior->GetPlane(),
1983                                                                        mBox,
1984                                                                        //0.0000001f);
1985                                                                        mEpsilon);
1986
1987                                nodeStack.push(bspNodePair(first, firstGeom));
1988                                nodeStack.push(bspNodePair(second, secondGeom));
1989                        }
1990                       
1991                        break;
1992                default:
1993                        // default: cull
1994                        break;
1995                }
1996               
1997                DEL_PTR(geom);
1998               
1999        }
2000
2001        return (int)viewCells.size();
2002}
2003
2004
2005float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
2006                                                                                   const AxisAlignedBox3 &box,
2007                                                                                   const int axis,
2008                                                                                   const float &position,                                                                                 
2009                                                                                   float &pFront,
2010                                                                                   float &pBack) const
2011{
2012        float pvsTotal = 0;
2013        float pvsFront = 0;
2014        float pvsBack = 0;
2015       
2016        // create unique ids for pvs heuristics
2017        GenerateUniqueIdsForPvs();
2018
2019        const int pvsSize = data.mPvs;
2020
2021        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
2022
2023        // this is the main ray classification loop!
2024        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
2025        {
2026                //if (!(*rit).mRay->IsActive()) continue;
2027
2028                // determine the side of this ray with respect to the plane
2029                float t;
2030                const int side = (*rit).ComputeRayIntersection(axis, position, t);
2031       
2032                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
2033                AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
2034        }
2035
2036        //-- pvs heuristics
2037        float pOverall;
2038
2039        //-- compute heurstics
2040        //   we take simplified computation for mid split
2041               
2042        pOverall = data.mProbability;
2043
2044        if (!mUseAreaForPvs)
2045        {   // volume
2046                pBack = pFront = pOverall * 0.5f;
2047               
2048#if 0
2049                // box length substitute for probability
2050                const float minBox = box.Min(axis);
2051                const float maxBox = box.Max(axis);
2052
2053                pBack = position - minBox;
2054                pFront = maxBox - position;
2055                pOverall = maxBox - minBox;
2056#endif
2057        }
2058        else //-- area substitute for probability
2059        {
2060                const int axis2 = (axis + 1) % 3;
2061                const int axis3 = (axis + 2) % 3;
2062
2063                const float faceArea =
2064                        (box.Max(axis2) - box.Min(axis2)) *
2065                        (box.Max(axis3) - box.Min(axis3));
2066
2067                pBack = pFront = pOverall * 0.5f + faceArea;
2068        }
2069
2070#ifdef _DEBUG
2071        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
2072        Debug << pFront << " " << pBack << " " << pOverall << endl;
2073#endif
2074
2075       
2076        const float newCost = pvsBack * pBack + pvsFront * pFront;
2077        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
2078
2079        return  (mCtDivCi + newCost) / oldCost;
2080}
2081
2082
2083void VspBspTree::AddObjToPvs(Intersectable *obj,
2084                                                         const int cf,
2085                                                         float &frontPvs,
2086                                                         float &backPvs,
2087                                                         float &totalPvs) const
2088{
2089        if (!obj)
2090                return;
2091
2092        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
2093
2094        // new object
2095        if ((obj->mMailbox != sFrontId) &&
2096                (obj->mMailbox != sBackId) &&
2097                (obj->mMailbox != sFrontAndBackId))
2098        {
2099                totalPvs += renderCost;
2100        }
2101
2102        // TODO: does this really belong to no pvs?
2103        //if (cf == Ray::COINCIDENT) return;
2104
2105        // object belongs to both PVS
2106        if (cf >= 0)
2107        {
2108                if ((obj->mMailbox != sFrontId) &&
2109                        (obj->mMailbox != sFrontAndBackId))
2110                {
2111                        frontPvs += renderCost;
2112               
2113                        if (obj->mMailbox == sBackId)
2114                                obj->mMailbox = sFrontAndBackId;
2115                        else
2116                                obj->mMailbox = sFrontId;
2117                }
2118        }
2119
2120        if (cf <= 0)
2121        {
2122                if ((obj->mMailbox != sBackId) &&
2123                        (obj->mMailbox != sFrontAndBackId))
2124                {
2125                        backPvs += renderCost;
2126               
2127                        if (obj->mMailbox == sFrontId)
2128                                obj->mMailbox = sFrontAndBackId;
2129                        else
2130                                obj->mMailbox = sBackId;
2131                }
2132        }
2133}
2134
2135
2136void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
2137                                                           const bool onlyUnmailed,
2138                                                           const int maxPvsSize) const
2139{
2140        stack<BspNode *> nodeStack;
2141        nodeStack.push(mRoot);
2142
2143        while (!nodeStack.empty())
2144        {
2145                BspNode *node = nodeStack.top();
2146                nodeStack.pop();
2147               
2148                if (node->IsLeaf())
2149                {
2150                        // test if this leaf is in valid view space
2151                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2152                        if (leaf->TreeValid() &&
2153                                (!onlyUnmailed || !leaf->Mailed()) &&
2154                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
2155                        {
2156                                leaves.push_back(leaf);
2157                        }
2158                }
2159                else
2160                {
2161                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2162
2163                        nodeStack.push(interior->GetBack());
2164                        nodeStack.push(interior->GetFront());
2165                }
2166        }
2167}
2168
2169
2170AxisAlignedBox3 VspBspTree::GetBoundingBox() const
2171{
2172        return mBox;
2173}
2174
2175
2176BspNode *VspBspTree::GetRoot() const
2177{
2178        return mRoot;
2179}
2180
2181
2182void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
2183{
2184        // the node became a leaf -> evaluate stats for leafs
2185        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
2186
2187
2188        if (data.mPvs > mBspStats.maxPvs)
2189        {
2190                mBspStats.maxPvs = data.mPvs;
2191        }
2192
2193        mBspStats.pvs += data.mPvs;
2194
2195        if (data.mDepth < mBspStats.minDepth)
2196        {
2197                mBspStats.minDepth = data.mDepth;
2198        }
2199       
2200        if (data.mDepth >= mTermMaxDepth)
2201        {
2202        ++ mBspStats.maxDepthNodes;
2203                //Debug << "new max depth: " << mBspStats.maxDepthNodes << endl;
2204        }
2205
2206        // accumulate rays to compute rays /  leaf
2207        mBspStats.accumRays += (int)data.mRays->size();
2208
2209        if (data.mPvs < mTermMinPvs)
2210                ++ mBspStats.minPvsNodes;
2211
2212        if ((int)data.mRays->size() < mTermMinRays)
2213                ++ mBspStats.minRaysNodes;
2214
2215        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
2216                ++ mBspStats.maxRayContribNodes;
2217
2218        if (data.mProbability <= mTermMinProbability)
2219                ++ mBspStats.minProbabilityNodes;
2220       
2221        // accumulate depth to compute average depth
2222        mBspStats.accumDepth += data.mDepth;
2223
2224        ++ mCreatedViewCells;
2225
2226#ifdef _DEBUG
2227        Debug << "BSP stats: "
2228                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
2229                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
2230          //              << "Area: " << data.mProbability << " (min: " << mTermMinProbability << "), "
2231                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
2232                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
2233                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
2234#endif
2235}
2236
2237
2238int VspBspTree::CastRay(Ray &ray)
2239{
2240        int hits = 0;
2241
2242        stack<BspRayTraversalData> tQueue;
2243
2244        float maxt, mint;
2245
2246        if (!mBox.GetRaySegment(ray, mint, maxt))
2247                return 0;
2248
2249        Intersectable::NewMail();
2250        ViewCell::NewMail();
2251        Vector3 entp = ray.Extrap(mint);
2252        Vector3 extp = ray.Extrap(maxt);
2253
2254        BspNode *node = mRoot;
2255        BspNode *farChild = NULL;
2256
2257        while (1)
2258        {
2259                if (!node->IsLeaf())
2260                {
2261                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2262
2263                        Plane3 splitPlane = in->GetPlane();
2264                        const int entSide = splitPlane.Side(entp);
2265                        const int extSide = splitPlane.Side(extp);
2266
2267                        if (entSide < 0)
2268                        {
2269                                node = in->GetBack();
2270
2271                                if(extSide <= 0) // plane does not split ray => no far child
2272                                        continue;
2273
2274                                farChild = in->GetFront(); // plane splits ray
2275
2276                        } else if (entSide > 0)
2277                        {
2278                                node = in->GetFront();
2279
2280                                if (extSide >= 0) // plane does not split ray => no far child
2281                                        continue;
2282
2283                                farChild = in->GetBack(); // plane splits ray
2284                        }
2285                        else // ray and plane are coincident
2286                        {
2287                                // WHAT TO DO IN THIS CASE ?
2288                                //break;
2289                                node = in->GetFront();
2290                                continue;
2291                        }
2292
2293                        // push data for far child
2294                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
2295
2296                        // find intersection of ray segment with plane
2297                        float t;
2298                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2299                        maxt *= t;
2300
2301                } else // reached leaf => intersection with view cell
2302                {
2303                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2304
2305                        if (!leaf->GetViewCell()->Mailed())
2306                        {
2307                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2308                                leaf->GetViewCell()->Mail();
2309                                ++ hits;
2310                        }
2311
2312                        //-- fetch the next far child from the stack
2313                        if (tQueue.empty())
2314                                break;
2315
2316                        entp = extp;
2317                        mint = maxt; // NOTE: need this?
2318
2319                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2320                                break;
2321
2322                        BspRayTraversalData &s = tQueue.top();
2323
2324                        node = s.mNode;
2325                        extp = s.mExitPoint;
2326                        maxt = s.mMaxT;
2327
2328                        tQueue.pop();
2329                }
2330        }
2331
2332        return hits;
2333}
2334
2335
2336void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
2337{
2338        ViewCell::NewMail();
2339       
2340        CollectViewCells(mRoot, onlyValid, viewCells, true);
2341}
2342
2343
2344void VspBspTree::CollapseViewCells()
2345{
2346// TODO
2347#if HAS_TO_BE_REDONE
2348        stack<BspNode *> nodeStack;
2349
2350        if (!mRoot)
2351                return;
2352
2353        nodeStack.push(mRoot);
2354       
2355        while (!nodeStack.empty())
2356        {
2357                BspNode *node = nodeStack.top();
2358                nodeStack.pop();
2359               
2360                if (node->IsLeaf())
2361        {
2362                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2363
2364                        if (!viewCell->GetValid())
2365                        {
2366                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2367       
2368                                ViewCellContainer leaves;
2369                                mViewCellsTree->CollectLeaves(viewCell, leaves);
2370
2371                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2372
2373                                for (it = leaves.begin(); it != it_end; ++ it)
2374                                {
2375                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2376                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2377                                        ++ mBspStats.invalidLeaves;
2378                                }
2379
2380                                // add to unbounded view cell
2381                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2382                                DEL_PTR(viewCell);
2383                        }
2384                }
2385                else
2386                {
2387                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2388               
2389                        nodeStack.push(interior->GetFront());
2390                        nodeStack.push(interior->GetBack());
2391                }
2392        }
2393
2394        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2395#endif
2396}
2397
2398
2399void VspBspTree::CollectRays(VssRayContainer &rays)
2400{
2401        vector<BspLeaf *> leaves;
2402
2403        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2404
2405        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2406        {
2407                BspLeaf *leaf = *lit;
2408                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2409
2410                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2411                        rays.push_back(*rit);
2412        }
2413}
2414
2415
2416void VspBspTree::ValidateTree()
2417{
2418        stack<BspNode *> nodeStack;
2419
2420        if (!mRoot)
2421                return;
2422
2423        nodeStack.push(mRoot);
2424       
2425        mBspStats.invalidLeaves = 0;
2426        while (!nodeStack.empty())
2427        {
2428                BspNode *node = nodeStack.top();
2429                nodeStack.pop();
2430               
2431                if (node->IsLeaf())
2432                {
2433                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2434
2435                        if (!leaf->GetViewCell()->GetValid())
2436                                ++ mBspStats.invalidLeaves;
2437
2438                        // validity flags don't match => repair
2439                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2440                        {
2441                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2442                                PropagateUpValidity(leaf);
2443                        }
2444                }
2445                else
2446                {
2447                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2448               
2449                        nodeStack.push(interior->GetFront());
2450                        nodeStack.push(interior->GetBack());
2451                }
2452        }
2453
2454        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2455}
2456
2457
2458
2459void VspBspTree::CollectViewCells(BspNode *root,
2460                                                                  bool onlyValid,
2461                                                                  ViewCellContainer &viewCells,
2462                                                                  bool onlyUnmailed) const
2463{
2464        stack<BspNode *> nodeStack;
2465
2466        if (!root)
2467                return;
2468
2469        nodeStack.push(root);
2470       
2471        while (!nodeStack.empty())
2472        {
2473                BspNode *node = nodeStack.top();
2474                nodeStack.pop();
2475               
2476                if (node->IsLeaf())
2477                {
2478                        if (!onlyValid || node->TreeValid())
2479                        {
2480                                ViewCell *leafVc = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2481
2482                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2483                                               
2484                                if (!onlyUnmailed || !viewCell->Mailed())
2485                                {
2486                                        viewCell->Mail();
2487                                        viewCells.push_back(viewCell);
2488                                }
2489                        }
2490                }
2491                else
2492                {
2493                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2494               
2495                        nodeStack.push(interior->GetFront());
2496                        nodeStack.push(interior->GetBack());
2497                }
2498        }
2499
2500}
2501
2502
2503void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2504{
2505        // preprocess: throw out polygons coincident to the view space box (not needed)
2506        PolygonContainer boxPolys;
2507        mBox.ExtractPolys(boxPolys);
2508        vector<Plane3> boxPlanes;
2509
2510        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2511
2512        // extract planes of box
2513        // TODO: can be done more elegantly than first extracting polygons
2514        // and take their planes
2515        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2516        {
2517                boxPlanes.push_back((*pit)->GetSupportingPlane());
2518        }
2519
2520        pit_end = polys.end();
2521
2522        for (pit = polys.begin(); pit != pit_end; ++ pit)
2523        {
2524                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2525               
2526                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2527                {
2528                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2529
2530                        if (cf == Polygon3::COINCIDENT)
2531                        {
2532                                DEL_PTR(*pit);
2533                                //Debug << "coincident!!" << endl;
2534                        }
2535                }
2536        }
2537
2538        // remove deleted entries
2539        for (int i = 0; i < (int)polys.size(); ++ i)
2540        {
2541                while (!polys[i] && (i < (int)polys.size()))
2542                {
2543                        swap(polys[i], polys.back());
2544                        polys.pop_back();
2545                }
2546        }
2547}
2548
2549
2550float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2551{
2552        float len = 0;
2553
2554        RayInfoContainer::const_iterator it, it_end = rays.end();
2555
2556        for (it = rays.begin(); it != it_end; ++ it)
2557                len += (*it).SegmentLength();
2558
2559        return len;
2560}
2561
2562
2563int VspBspTree::SplitRays(const Plane3 &plane,
2564                                                  RayInfoContainer &rays,
2565                                                  RayInfoContainer &frontRays,
2566                                                  RayInfoContainer &backRays) const
2567{
2568        int splits = 0;
2569
2570        RayInfoContainer::const_iterator it, it_end = rays.end();
2571
2572        for (it = rays.begin(); it != it_end; ++ it)
2573        {
2574                RayInfo bRay = *it;
2575               
2576                VssRay *ray = bRay.mRay;
2577                float t;
2578
2579                // get classification and receive new t
2580                const int cf = bRay.ComputeRayIntersection(plane, t);
2581
2582                switch (cf)
2583                {
2584                case -1:
2585                        backRays.push_back(bRay);
2586                        break;
2587                case 1:
2588                        frontRays.push_back(bRay);
2589                        break;
2590                case 0:
2591                        {
2592                                //-- split ray
2593                                //   test if start point behind or in front of plane
2594                                const int side = plane.Side(bRay.ExtrapOrigin());
2595
2596                                if (side <= 0)
2597                                {
2598                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2599                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2600                                }
2601                                else
2602                                {
2603                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2604                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2605                                }
2606                        }
2607                        break;
2608                default:
2609                        Debug << "Should not come here" << endl;
2610                        break;
2611                }
2612        }
2613
2614        return splits;
2615}
2616
2617
2618void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2619{
2620        BspNode *lastNode;
2621
2622        do
2623        {
2624                lastNode = n;
2625
2626                // want to get planes defining geometry of this node => don't take
2627                // split plane of node itself
2628                n = n->GetParent();
2629
2630                if (n)
2631                {
2632                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2633                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2634
2635            if (interior->GetBack() != lastNode)
2636                                halfSpace.ReverseOrientation();
2637
2638                        halfSpaces.push_back(halfSpace);
2639                }
2640        }
2641        while (n);
2642}
2643
2644
2645void VspBspTree::ConstructGeometry(BspNode *n,
2646                                                                   BspNodeGeometry &geom) const
2647{
2648        vector<Plane3> halfSpaces;
2649        ExtractHalfSpaces(n, halfSpaces);
2650
2651        PolygonContainer candidatePolys;
2652        vector<Plane3> candidatePlanes;
2653
2654        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2655
2656        // bounded planes are added to the polygons
2657        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
2658        {
2659                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
2660
2661                if (p->Valid(mEpsilon))
2662                {
2663                        candidatePolys.push_back(p);
2664                        candidatePlanes.push_back(*pit);
2665                }
2666        }
2667
2668        // add faces of bounding box (also could be faces of the cell)
2669        for (int i = 0; i < 6; ++ i)
2670        {
2671                VertexContainer vertices;
2672
2673                for (int j = 0; j < 4; ++ j)
2674                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2675
2676                Polygon3 *poly = new Polygon3(vertices);
2677
2678                candidatePolys.push_back(poly);
2679                candidatePlanes.push_back(poly->GetSupportingPlane());
2680        }
2681
2682        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2683        {
2684                // polygon is split by all other planes
2685                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2686                {
2687                        if (i == j) // polygon and plane are coincident
2688                                continue;
2689
2690                        VertexContainer splitPts;
2691                        Polygon3 *frontPoly, *backPoly;
2692
2693                        const int cf =
2694                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2695                                                                                                 mEpsilon);
2696
2697                        switch (cf)
2698                        {
2699                                case Polygon3::SPLIT:
2700                                        frontPoly = new Polygon3();
2701                                        backPoly = new Polygon3();
2702
2703                                        candidatePolys[i]->Split(halfSpaces[j],
2704                                                                                         *frontPoly,
2705                                                                                         *backPoly,
2706                                                                                         mEpsilon);
2707
2708                                        DEL_PTR(candidatePolys[i]);
2709
2710                                        if (backPoly->Valid(mEpsilon))
2711                                                candidatePolys[i] = backPoly;
2712                                        else
2713                                                DEL_PTR(backPoly);
2714
2715                                        // outside, don't need this
2716                                        DEL_PTR(frontPoly);
2717                                        break;
2718                                // polygon outside of halfspace
2719                                case Polygon3::FRONT_SIDE:
2720                                        DEL_PTR(candidatePolys[i]);
2721                                        break;
2722                                // just take polygon as it is
2723                                case Polygon3::BACK_SIDE:
2724                                case Polygon3::COINCIDENT:
2725                                default:
2726                                        break;
2727                        }
2728                }
2729
2730                if (candidatePolys[i])
2731                {
2732                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2733                        //      geom.mPolys.push_back(candidates[i]);
2734                }
2735        }
2736}
2737
2738
2739void VspBspTree::ConstructGeometry(ViewCell *vc,
2740                                                                   BspNodeGeometry &vcGeom) const
2741{
2742        ViewCellContainer leaves;
2743       
2744        mViewCellsTree->CollectLeaves(vc, leaves);
2745
2746        ViewCellContainer::const_iterator it, it_end = leaves.end();
2747
2748        for (it = leaves.begin(); it != it_end; ++ it)
2749        {
2750                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2751               
2752                ConstructGeometry(l, vcGeom);
2753        }
2754}
2755
2756
2757int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2758                                                          const bool onlyUnmailed) const
2759{
2760        stack<bspNodePair> nodeStack;
2761       
2762        BspNodeGeometry nodeGeom;
2763        ConstructGeometry(n, nodeGeom);
2764       
2765        // split planes from the root to this node
2766        // needed to verify that we found neighbor leaf
2767        // TODO: really needed?
2768        vector<Plane3> halfSpaces;
2769        ExtractHalfSpaces(n, halfSpaces);
2770
2771
2772        BspNodeGeometry *rgeom = new BspNodeGeometry();
2773        ConstructGeometry(mRoot, *rgeom);
2774
2775        nodeStack.push(bspNodePair(mRoot, rgeom));
2776
2777        while (!nodeStack.empty())
2778        {
2779                BspNode *node = nodeStack.top().first;
2780                BspNodeGeometry *geom = nodeStack.top().second;
2781       
2782                nodeStack.pop();
2783
2784                if (node->IsLeaf())
2785                {
2786                        // test if this leaf is in valid view space
2787                        if (node->TreeValid() &&
2788                                (node != n) &&
2789                                (!onlyUnmailed || !node->Mailed()))
2790                        {
2791                                bool isAdjacent = true;
2792
2793                                if (1)
2794                                {
2795                                        // test all planes of current node if still adjacent
2796                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2797                                        {
2798                                                const int cf =
2799                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2800                                                                                                        halfSpaces[i],
2801                                                                                                        mEpsilon);
2802
2803                                                if (cf == Polygon3::FRONT_SIDE)
2804                                                {
2805                                                        isAdjacent = false;
2806                                                }
2807                                        }
2808                                }
2809                                else
2810                                {
2811                                        // TODO: why is this wrong??
2812                                        // test all planes of current node if still adjacent
2813                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
2814                                        {
2815                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
2816
2817                                                const int cf =
2818                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2819                                                                                                        poly->GetSupportingPlane(),
2820                                                                                                        mEpsilon);
2821
2822                                                if (cf == Polygon3::FRONT_SIDE)
2823                                                {
2824                                                        isAdjacent = false;
2825                                                }
2826                                        }
2827                                }
2828                                // neighbor was found
2829                                if (isAdjacent)
2830                                {       
2831                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2832                                }
2833                        }
2834                }
2835                else
2836                {
2837                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2838
2839                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
2840                                                                                                   interior->GetPlane(),
2841                                                                                                   mEpsilon);
2842                       
2843                        BspNode *front = interior->GetFront();
2844                        BspNode *back = interior->GetBack();
2845           
2846                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2847                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2848
2849                        geom->SplitGeometry(*fGeom,
2850                                                                *bGeom,
2851                                                                interior->GetPlane(),
2852                                                                mBox,
2853                                                                //0.0000001f);
2854                                                                mEpsilon);
2855               
2856                        if (cf == Polygon3::BACK_SIDE)
2857                        {
2858                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2859                                DEL_PTR(fGeom);
2860                        }
2861                        else
2862                        {
2863                                if (cf == Polygon3::FRONT_SIDE)
2864                                {
2865                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2866                                        DEL_PTR(bGeom);
2867                                }
2868                                else
2869                                {       // random decision
2870                                        nodeStack.push(bspNodePair(front, fGeom));
2871                                        nodeStack.push(bspNodePair(back, bGeom));
2872                                }
2873                        }
2874                }
2875       
2876                DEL_PTR(geom);
2877        }
2878
2879        return (int)neighbors.size();
2880}
2881
2882
2883
2884int VspBspTree::FindApproximateNeighbors(BspNode *n,
2885                                                                                 vector<BspLeaf *> &neighbors,
2886                                                                                 const bool onlyUnmailed) const
2887{
2888        stack<bspNodePair> nodeStack;
2889       
2890        BspNodeGeometry nodeGeom;
2891        ConstructGeometry(n, nodeGeom);
2892       
2893        // split planes from the root to this node
2894        // needed to verify that we found neighbor leaf
2895        // TODO: really needed?
2896        vector<Plane3> halfSpaces;
2897        ExtractHalfSpaces(n, halfSpaces);
2898
2899
2900        BspNodeGeometry *rgeom = new BspNodeGeometry();
2901        ConstructGeometry(mRoot, *rgeom);
2902
2903        nodeStack.push(bspNodePair(mRoot, rgeom));
2904
2905        while (!nodeStack.empty())
2906        {
2907                BspNode *node = nodeStack.top().first;
2908                BspNodeGeometry *geom = nodeStack.top().second;
2909       
2910                nodeStack.pop();
2911
2912                if (node->IsLeaf())
2913                {
2914                        // test if this leaf is in valid view space
2915                        if (node->TreeValid() &&
2916                                (node != n) &&
2917                                (!onlyUnmailed || !node->Mailed()))
2918                        {
2919                                bool isAdjacent = true;
2920
2921                                // neighbor was found
2922                                if (isAdjacent)
2923                                {       
2924                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2925                                }
2926                        }
2927                }
2928                else
2929                {
2930                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2931
2932                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
2933                                                                                                   interior->GetPlane(),
2934                                                                                                   mEpsilon);
2935                       
2936                        BspNode *front = interior->GetFront();
2937                        BspNode *back = interior->GetBack();
2938           
2939                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2940                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2941
2942                        geom->SplitGeometry(*fGeom,
2943                                                                *bGeom,
2944                                                                interior->GetPlane(),
2945                                                                mBox,
2946                                                                //0.0000001f);
2947                                                                mEpsilon);
2948               
2949                        if (cf == Polygon3::BACK_SIDE)
2950                        {
2951                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2952                                DEL_PTR(fGeom);
2953                                }
2954                        else
2955                        {
2956                                if (cf == Polygon3::FRONT_SIDE)
2957                                {
2958                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2959                                        DEL_PTR(bGeom);
2960                                }
2961                                else
2962                                {       // random decision
2963                                        nodeStack.push(bspNodePair(front, fGeom));
2964                                        nodeStack.push(bspNodePair(back, bGeom));
2965                                }
2966                        }
2967                }
2968       
2969                DEL_PTR(geom);
2970        }
2971
2972        return (int)neighbors.size();
2973}
2974
2975
2976
2977BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
2978{
2979    stack<BspNode *> nodeStack;
2980        nodeStack.push(mRoot);
2981
2982        int mask = rand();
2983
2984        while (!nodeStack.empty())
2985        {
2986                BspNode *node = nodeStack.top();
2987                nodeStack.pop();
2988
2989                if (node->IsLeaf())
2990                {
2991                        return dynamic_cast<BspLeaf *>(node);
2992                }
2993                else
2994                {
2995                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2996                        BspNode *next;
2997                        BspNodeGeometry geom;
2998
2999                        // todo: not very efficient: constructs full cell everytime
3000                        ConstructGeometry(interior, geom);
3001
3002                        const int cf =
3003                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
3004
3005                        if (cf == Polygon3::BACK_SIDE)
3006                                next = interior->GetFront();
3007                        else
3008                                if (cf == Polygon3::FRONT_SIDE)
3009                                        next = interior->GetFront();
3010                        else
3011                        {
3012                                // random decision
3013                                if (mask & 1)
3014                                        next = interior->GetBack();
3015                                else
3016                                        next = interior->GetFront();
3017                                mask = mask >> 1;
3018                        }
3019
3020                        nodeStack.push(next);
3021                }
3022        }
3023
3024        return NULL;
3025}
3026
3027
3028BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3029{
3030        stack<BspNode *> nodeStack;
3031
3032        nodeStack.push(mRoot);
3033
3034        int mask = rand();
3035
3036        while (!nodeStack.empty())
3037        {
3038                BspNode *node = nodeStack.top();
3039                nodeStack.pop();
3040
3041                if (node->IsLeaf())
3042                {
3043                        if ( (!onlyUnmailed || !node->Mailed()) )
3044                                return dynamic_cast<BspLeaf *>(node);
3045                }
3046                else
3047                {
3048                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3049
3050                        // random decision
3051                        if (mask & 1)
3052                                nodeStack.push(interior->GetBack());
3053                        else
3054                                nodeStack.push(interior->GetFront());
3055
3056                        mask = mask >> 1;
3057                }
3058        }
3059
3060        return NULL;
3061}
3062
3063
3064int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3065{
3066        int pvsSize = 0;
3067
3068        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3069
3070        Intersectable::NewMail();
3071
3072        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3073        {
3074                VssRay *ray = (*rit).mRay;
3075
3076                if (ray->mOriginObject)
3077                {
3078                        if (!ray->mOriginObject->Mailed())
3079                        {
3080                                ray->mOriginObject->Mail();
3081                                ++ pvsSize;
3082                        }
3083                }
3084                if (ray->mTerminationObject)
3085                {
3086                        if (!ray->mTerminationObject->Mailed())
3087                        {
3088                                ray->mTerminationObject->Mail();
3089                                ++ pvsSize;
3090                        }
3091                }
3092        }
3093
3094        return pvsSize;
3095}
3096
3097
3098float VspBspTree::GetEpsilon() const
3099{
3100        return mEpsilon;
3101}
3102
3103
3104int VspBspTree::SplitPolygons(const Plane3 &plane,
3105                                                          PolygonContainer &polys,
3106                                                          PolygonContainer &frontPolys,
3107                                                          PolygonContainer &backPolys,
3108                                                          PolygonContainer &coincident) const
3109{
3110        int splits = 0;
3111
3112        PolygonContainer::const_iterator it, it_end = polys.end();
3113
3114        for (it = polys.begin(); it != polys.end(); ++ it)     
3115        {
3116                Polygon3 *poly = *it;
3117
3118                // classify polygon
3119                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3120
3121                switch (cf)
3122                {
3123                        case Polygon3::COINCIDENT:
3124                                coincident.push_back(poly);
3125                                break;
3126                        case Polygon3::FRONT_SIDE:
3127                                frontPolys.push_back(poly);
3128                                break;
3129                        case Polygon3::BACK_SIDE:
3130                                backPolys.push_back(poly);
3131                                break;
3132                        case Polygon3::SPLIT:
3133                                backPolys.push_back(poly);
3134                                frontPolys.push_back(poly);
3135                                ++ splits;
3136                                break;
3137                        default:
3138                Debug << "SHOULD NEVER COME HERE\n";
3139                                break;
3140                }
3141        }
3142
3143        return splits;
3144}
3145
3146
3147int VspBspTree::CastLineSegment(const Vector3 &origin,
3148                                                                const Vector3 &termination,
3149                                                                vector<ViewCell *> &viewcells)
3150{
3151        int hits = 0;
3152        stack<BspRayTraversalData> tStack;
3153
3154        float mint = 0.0f, maxt = 1.0f;
3155
3156        Intersectable::NewMail();
3157        ViewCell::NewMail();
3158
3159        Vector3 entp = origin;
3160        Vector3 extp = termination;
3161
3162        BspNode *node = mRoot;
3163        BspNode *farChild = NULL;
3164
3165        float t;
3166        const float thresh = 1e-6f; // matt: change this
3167       
3168        while (1)
3169        {
3170                if (!node->IsLeaf())
3171                {
3172                        BspInterior *in = dynamic_cast<BspInterior *>(node);
3173
3174                        Plane3 splitPlane = in->GetPlane();
3175                       
3176                        const int entSide = splitPlane.Side(entp, thresh);
3177                        const int extSide = splitPlane.Side(extp, thresh);
3178
3179                        if (entSide < 0)
3180                        {
3181                                node = in->GetBack();
3182                               
3183                                // plane does not split ray => no far child
3184                                if (extSide <= 0)
3185                                        continue;
3186 
3187                                farChild = in->GetFront(); // plane splits ray
3188                        }
3189                        else if (entSide > 0)
3190                        {
3191                                node = in->GetFront();
3192
3193                                if (extSide >= 0) // plane does not split ray => no far child
3194                                        continue;
3195
3196                                farChild = in->GetBack(); // plane splits ray
3197                        }
3198                        else // one of the ray end points is on the plane
3199                        {       // NOTE: what to do if ray is coincident with plane?
3200                                if (extSide < 0)
3201                                        node = in->GetBack();
3202                                else //if (extSide > 0)
3203                                        node = in->GetFront();
3204                                //else break; // coincident => count no intersections
3205
3206                                continue; // no far child
3207                        }
3208
3209                        // push data for far child
3210                        tStack.push(BspRayTraversalData(farChild, extp));
3211
3212                        // find intersection of ray segment with plane
3213                        extp = splitPlane.FindIntersection(origin, extp, &t);
3214                }
3215                else
3216                {
3217                        // reached leaf => intersection with view cell
3218                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3219                        ViewCell *viewCell;
3220                       
3221                        if (0)
3222                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3223                        else
3224                                viewCell = leaf->GetViewCell();
3225
3226                        if (!viewCell->Mailed())
3227                        {
3228                                viewcells.push_back(viewCell);
3229                                viewCell->Mail();
3230                                ++ hits;
3231                        }
3232
3233                        //-- fetch the next far child from the stack
3234                        if (tStack.empty())
3235                                break;
3236
3237                        entp = extp;
3238                       
3239                        const BspRayTraversalData &s = tStack.top();
3240
3241                        node = s.mNode;
3242                        extp = s.mExitPoint;
3243
3244                        tStack.pop();
3245                }
3246        }
3247
3248        return hits;
3249}
3250
3251
3252
3253
3254int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
3255{
3256        std::deque<BspNode *> path1;
3257        BspNode *p1 = n1;
3258
3259        // create path from node 1 to root
3260        while (p1)
3261        {
3262                if (p1 == n2) // second node on path
3263                        return (int)path1.size();
3264
3265                path1.push_front(p1);
3266                p1 = p1->GetParent();
3267        }
3268
3269        int depth = n2->GetDepth();
3270        int d = depth;
3271
3272        BspNode *p2 = n2;
3273
3274        // compare with same depth
3275        while (1)
3276        {
3277                if ((d < (int)path1.size()) && (p2 == path1[d]))
3278                        return (depth - d) + ((int)path1.size() - 1 - d);
3279
3280                -- d;
3281                p2 = p2->GetParent();
3282        }
3283
3284        return 0; // never come here
3285}
3286
3287
3288BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
3289{
3290// TODO
3291#if HAS_TO_BE_REDONE
3292        if (node->IsLeaf())
3293                return node;
3294
3295        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3296
3297        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3298        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
3299
3300        if (front->IsLeaf() && back->IsLeaf())
3301        {
3302                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
3303                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
3304
3305                //-- collapse tree
3306                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3307                {
3308                        BspViewCell *vc = frontLeaf->GetViewCell();
3309
3310                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
3311                        leaf->SetTreeValid(frontLeaf->TreeValid());
3312
3313                        // replace a link from node's parent
3314                        if (leaf->GetParent())
3315                                leaf->GetParent()->ReplaceChildLink(node, leaf);
3316                        else
3317                                mRoot = leaf;
3318
3319                        ++ collapsed;
3320                        delete interior;
3321
3322                        return leaf;
3323                }
3324        }
3325#endif
3326        return node;
3327}
3328
3329
3330int VspBspTree::CollapseTree()
3331{
3332        int collapsed = 0;
3333        //TODO
3334#if HAS_TO_BE_REDONE
3335        (void)CollapseTree(mRoot, collapsed);
3336
3337        // revalidate leaves
3338        RepairViewCellsLeafLists();
3339#endif
3340        return collapsed;
3341}
3342
3343
3344void VspBspTree::RepairViewCellsLeafLists()
3345{
3346// TODO
3347#if HAS_TO_BE_REDONE
3348        // list not valid anymore => clear
3349        stack<BspNode *> nodeStack;
3350        nodeStack.push(mRoot);
3351
3352        ViewCell::NewMail();
3353
3354        while (!nodeStack.empty())
3355        {
3356                BspNode *node = nodeStack.top();
3357                nodeStack.pop();
3358
3359                if (node->IsLeaf())
3360                {
3361                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3362
3363                        BspViewCell *viewCell = leaf->GetViewCell();
3364
3365                        if (!viewCell->Mailed())
3366                        {
3367                                viewCell->mLeaves.clear();
3368                                viewCell->Mail();
3369                        }
3370       
3371                        viewCell->mLeaves.push_back(leaf);
3372
3373                }
3374                else
3375                {
3376                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3377
3378                        nodeStack.push(interior->GetFront());
3379                        nodeStack.push(interior->GetBack());
3380                }
3381        }
3382// TODO
3383#endif
3384}
3385
3386
3387typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
3388
3389
3390int VspBspTree::CastBeam(Beam &beam)
3391{
3392    stack<bspNodePair> nodeStack;
3393        BspNodeGeometry *rgeom = new BspNodeGeometry();
3394        ConstructGeometry(mRoot, *rgeom);
3395
3396        nodeStack.push(bspNodePair(mRoot, rgeom));
3397 
3398        ViewCell::NewMail();
3399
3400        while (!nodeStack.empty())
3401        {
3402                BspNode *node = nodeStack.top().first;
3403                BspNodeGeometry *geom = nodeStack.top().second;
3404                nodeStack.pop();
3405               
3406                AxisAlignedBox3 box;
3407                geom->GetBoundingBox(box);
3408
3409                const int side = beam.ComputeIntersection(box);
3410               
3411                switch (side)
3412                {
3413                case -1:
3414                        CollectViewCells(node, true, beam.mViewCells, true);
3415                        break;
3416                case 0:
3417                       
3418                        if (node->IsLeaf())
3419                        {
3420                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3421                       
3422                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
3423                                {
3424                                        leaf->GetViewCell()->Mail();
3425                                        beam.mViewCells.push_back(leaf->GetViewCell());
3426                                }
3427                        }
3428                        else
3429                        {
3430                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3431                       
3432                                BspNode *first = interior->GetFront();
3433                                BspNode *second = interior->GetBack();
3434           
3435                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3436                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3437
3438                                geom->SplitGeometry(*firstGeom,
3439                                                                        *secondGeom,
3440                                                                        interior->GetPlane(),
3441                                                                        mBox,
3442                                                                        //0.0000001f);
3443                                                                        mEpsilon);
3444
3445                                // decide on the order of the nodes
3446                                if (DotProd(beam.mPlanes[0].mNormal,
3447                                        interior->GetPlane().mNormal) > 0)
3448                                {
3449                                        swap(first, second);
3450                                        swap(firstGeom, secondGeom);
3451                                }
3452
3453                                nodeStack.push(bspNodePair(first, firstGeom));
3454                                nodeStack.push(bspNodePair(second, secondGeom));
3455                        }
3456                       
3457                        break;
3458                default:
3459                        // default: cull
3460                        break;
3461                }
3462               
3463                DEL_PTR(geom);
3464               
3465        }
3466
3467        return (int)beam.mViewCells.size();
3468}
3469
3470
3471void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
3472{
3473        mViewCellsManager = vcm;
3474}
3475
3476
3477int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3478                                                                           vector<MergeCandidate> &candidates)
3479{
3480        BspLeaf::NewMail();
3481       
3482        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3483
3484        int numCandidates = 0;
3485
3486        // find merge candidates and push them into queue
3487        for (it = leaves.begin(); it != it_end; ++ it)
3488        {
3489                BspLeaf *leaf = *it;
3490               
3491                // the same leaves must not be part of two merge candidates
3492                leaf->Mail();
3493               
3494                vector<BspLeaf *> neighbors;
3495               
3496                // appoximate neighbor search has slightl relaxed constraints
3497                if (1)
3498                        FindNeighbors(leaf, neighbors, true);
3499                else
3500                        FindApproximateNeighbors(leaf, neighbors, true);
3501
3502                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3503
3504                // TODO: test if at least one ray goes from one leaf to the other
3505                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
3506                {
3507                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
3508                        {
3509                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
3510
3511                                // dont't merge view cells if they are empty and not front and back leaf of the same parent
3512                                // in the tree?
3513                                if (mEmptyViewCellsMergeAllowed ||
3514                                        !leaf->GetViewCell()->GetPvs().Empty() ||
3515                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
3516                    leaf->IsSibling(*nit))
3517                                {
3518                                        candidates.push_back(mc);
3519                                }
3520
3521                                ++ numCandidates;
3522                                if ((numCandidates % 1000) == 0)
3523                                {
3524                                        cout << "collected " << numCandidates << " merge candidates" << endl;
3525                                }
3526                        }
3527                }
3528        }
3529
3530        Debug << "merge queue: " << (int)candidates.size() << endl;
3531        Debug << "leaves in queue: " << numCandidates << endl;
3532       
3533
3534        return (int)leaves.size();
3535}
3536
3537
3538int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3539                                                                           vector<MergeCandidate> &candidates)
3540{
3541        ViewCell::NewMail();
3542        long startTime = GetTime();
3543       
3544        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
3545        ViewCellContainer::const_iterator iit;
3546
3547        int numLeaves = 0;
3548       
3549        BspLeaf::NewMail();
3550
3551        for (int i = 0; i < (int)rays.size(); ++ i)
3552        { 
3553                VssRay *ray = rays[i];
3554       
3555                // traverse leaves stored in the rays and compare and
3556                // merge consecutive leaves (i.e., the neighbors in the tree)
3557                if (ray->mViewCells.size() < 2)
3558                        continue;
3559//TODO viewcellhierarchy
3560                iit = ray->mViewCells.begin();
3561                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
3562                BspLeaf *leaf = bspVc->mLeaf;
3563               
3564                // traverse intersections
3565                // consecutive leaves are neighbors => add them to queue
3566                for (; iit != ray->mViewCells.end(); ++ iit)
3567                {
3568                        // next pair
3569                        BspLeaf *prevLeaf = leaf;
3570                        bspVc = dynamic_cast<BspViewCell *>(*iit);
3571            leaf = bspVc->mLeaf;
3572
3573                        // view space not valid or same view cell
3574                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3575                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
3576                                continue;
3577
3578                vector<BspLeaf *> &neighbors = neighborMap[leaf];
3579                       
3580                        bool found = false;
3581
3582                        // both leaves inserted in queue already =>
3583                        // look if double pair already exists
3584                        if (leaf->Mailed() && prevLeaf->Mailed())
3585                        {
3586                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3587                               
3588                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3589                                        if (*it == prevLeaf)
3590                                                found = true; // already in queue
3591                        }
3592               
3593                        if (!found)
3594                        {
3595                                // this pair is not in map yet
3596                                // => insert into the neighbor map and the queue
3597                                neighbors.push_back(prevLeaf);
3598                                neighborMap[prevLeaf].push_back(leaf);
3599
3600                                leaf->Mail();
3601                                prevLeaf->Mail();
3602               
3603                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3604                               
3605                                candidates.push_back(mc);
3606
3607                                if (((int)candidates.size() % 1000) == 0)
3608                                {
3609                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
3610                                }
3611                        }
3612        }
3613        }
3614
3615        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
3616        Debug << "merge queue: " << (int)candidates.size() << endl;
3617        Debug << "leaves in queue: " << numLeaves << endl;
3618
3619
3620        //-- collect the leaves which haven't been found by ray casting
3621        if (0)
3622        {
3623                cout << "finding additional merge candidates using geometry" << endl;
3624                vector<BspLeaf *> leaves;
3625                CollectLeaves(leaves, true);
3626                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
3627                CollectMergeCandidates(leaves, candidates);
3628        }
3629
3630        return numLeaves;
3631}
3632
3633
3634
3635
3636ViewCell *VspBspTree::GetViewCell(const Vector3 &point)
3637{
3638  if (mRoot == NULL)
3639        return NULL;
3640 
3641  stack<BspNode *> nodeStack;
3642  nodeStack.push(mRoot);
3643 
3644  ViewCell *viewcell = NULL;
3645 
3646  while (!nodeStack.empty())  {
3647        BspNode *node = nodeStack.top();
3648        nodeStack.pop();
3649       
3650        if (node->IsLeaf()) {
3651          viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
3652          break;
3653        } else {
3654         
3655          BspInterior *interior = dynamic_cast<BspInterior *>(node);
3656               
3657          // random decision
3658          if (interior->GetPlane().Side(point) < 0)
3659                nodeStack.push(interior->GetBack());
3660          else
3661                nodeStack.push(interior->GetFront());
3662        }
3663  }
3664 
3665  return viewcell;
3666}
3667
3668
3669bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3670{
3671        BspNode *node = mRoot;
3672
3673        while (1)
3674        {
3675                // early exit
3676                if (node->TreeValid())
3677                        return true;
3678
3679                if (node->IsLeaf())
3680                        return false;
3681                       
3682                BspInterior *in = dynamic_cast<BspInterior *>(node);
3683                                       
3684                if (in->GetPlane().Side(viewPoint) <= 0)
3685                {
3686                        node = in->GetBack();
3687                }
3688                else
3689                {
3690                        node = in->GetFront();
3691                }
3692        }
3693
3694        // should never come here
3695        return false;
3696}
3697
3698
3699void VspBspTree::PropagateUpValidity(BspNode *node)
3700{
3701        const bool isValid = node->TreeValid();
3702
3703        // propagative up invalid flag until only invalid nodes exist over this node
3704        if (!isValid)
3705        {
3706                while (!node->IsRoot() && node->GetParent()->TreeValid())
3707                {
3708                        node = node->GetParent();
3709                        node->SetTreeValid(false);
3710                }
3711        }
3712        else
3713        {
3714                // propagative up valid flag until one of the subtrees is invalid
3715                while (!node->IsRoot() && !node->TreeValid())
3716                {
3717            node = node->GetParent();
3718                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3719                       
3720                        // the parent is valid iff both leaves are valid
3721                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3722                                                           interior->GetFront()->TreeValid());
3723                }
3724        }
3725}
3726
3727
3728bool VspBspTree::Export(ofstream &stream)
3729{
3730        ExportNode(mRoot, stream);
3731
3732        return true;
3733}
3734
3735
3736void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
3737{
3738        if (node->IsLeaf())
3739        {
3740                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3741                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3742
3743                int id = -1;
3744                if (viewCell != mOutOfBoundsCell)
3745                        id = viewCell->GetId();
3746
3747                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3748        }
3749        else
3750        {
3751                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3752       
3753                Plane3 plane = interior->GetPlane();
3754                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3755                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3756                           << plane.mD << "\">" << endl;
3757
3758                ExportNode(interior->GetBack(), stream);
3759                ExportNode(interior->GetFront(), stream);
3760
3761                stream << "</Interior>" << endl;
3762        }
3763}
Note: See TracBrowser for help on using the repository browser.