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

Revision 719, 90.1 KB checked in by mattausch, 19 years ago (diff)

updating view cell hierarchy before pvs statistics

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