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

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