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

Revision 653, 82.9 KB checked in by mattausch, 18 years ago (diff)

implemented split queue (but not tested yet!)

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