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

Revision 727, 90.1 KB checked in by mattausch, 18 years ago (diff)

added view cell description bsp tree

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