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

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