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

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