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

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