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

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