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

Revision 1047, 96.7 KB checked in by mattausch, 18 years ago (diff)

fixed vsp part of vsp osp tree

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                if (0) leaf->mVssRays.push_back(new VssRay(*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 returned from the function so we
1576                                        // don't have to recompute it when possible
1577                                        pos = box.Max(); pos[axis] = nPosition[axis];
1578                                        AxisAlignedBox3 bBox(box.Min(), pos);
1579                                        PolygonContainer fPolys;
1580                                        bBox.ExtractPolys(fPolys);
1581
1582                                        nBackGeom[axis] = new BspNodeGeometry(fPolys);
1583       
1584                                        //-- create front geometry from box
1585                                        pos = box.Min(); pos[axis] = nPosition[axis];
1586                                        AxisAlignedBox3 fBox(pos, box.Max());
1587
1588                                        PolygonContainer bPolys;
1589                                        fBox.ExtractPolys(bPolys);
1590                                        nFrontGeom[axis] = new BspNodeGeometry(bPolys);
1591                                }
1592                                else
1593                                {
1594                                        nFrontGeom[axis] = new BspNodeGeometry();
1595                                        nBackGeom[axis] = new BspNodeGeometry();
1596
1597                                        nCostRatio[axis] =
1598                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1599                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1600                                                                                   nProbFront[axis], nProbBack[axis]);
1601                                }
1602                        }
1603                                               
1604                       
1605                        if (mUseDrivingAxisIfMaxCostViolated)
1606                        {
1607                                // we take longest axis split if cost ratio exceeds threshold
1608                                if (nCostRatio[axis] < min(maxCostRatioForArbitraryAxis, nCostRatio[bestAxis]))
1609                                {
1610                                        bestAxis = axis;
1611                                }
1612                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
1613                                        Debug << "taking split along longest axis (" << bestAxis << ") instead of  (" << axis << ")" << endl;
1614                               
1615                        }
1616                        else
1617                        {
1618                                if (bestAxis == -1)
1619                                {
1620                                        bestAxis = axis;
1621                                }
1622                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
1623                                {
1624                                        bestAxis = axis;
1625                                }
1626                        }
1627                }
1628        }
1629
1630        //-- assign values
1631        axis = bestAxis;
1632        pFront = nProbFront[bestAxis];
1633        pBack = nProbBack[bestAxis];
1634
1635        // assign best split nodes geometry
1636        *frontGeom = nFrontGeom[bestAxis];
1637        *backGeom = nBackGeom[bestAxis];
1638
1639        // and delete other geometry
1640        DEL_PTR(nFrontGeom[(bestAxis + 1) % 3]);
1641        DEL_PTR(nBackGeom[(bestAxis + 2) % 3]);
1642
1643        //-- split plane
1644    Vector3 normal(0,0,0); normal[bestAxis] = 1;
1645        plane = Plane3(normal, nPosition[bestAxis]);
1646
1647        //Debug << "best axis: " << bestAxis << " pos " << nPosition[bestAxis] << endl;
1648        //Debug << "!!!!!!!!!!!!!!" << endl;
1649        return nCostRatio[bestAxis];
1650}
1651
1652
1653bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1654                                                         BspLeaf *leaf,
1655                                                         VspBspTraversalData &data,                                                     
1656                                                         VspBspTraversalData &frontData,
1657                                                         VspBspTraversalData &backData,
1658                                                         int &splitAxis)
1659{
1660        // HACK matt: subdivide regularily to certain depth
1661        if (data.mDepth < 0)   
1662        {
1663                cout << "d: " << data.mDepth << endl;
1664                // return axis aligned split
1665                AxisAlignedBox3 box;
1666                box.Initialize();
1667       
1668                // create bounding box of region
1669                data.mGeometry->GetBoundingBox(box);
1670       
1671                const int axis = box.Size().DrivingAxis();
1672                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1673
1674                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1675                bestPlane = Plane3(norm, position);
1676                splitAxis = axis;
1677                return true;
1678        }
1679
1680        // simplest strategy: just take next polygon
1681        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1682        {
1683        if (!data.mPolygons->empty())
1684                {
1685                        const int randIdx =
1686                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1687                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
1688
1689                        bestPlane = nextPoly->GetSupportingPlane();
1690                        return true;
1691                }
1692        }
1693
1694        //-- use heuristics to find appropriate plane
1695
1696        // intermediate plane
1697        Plane3 plane;
1698        float lowestCost = MAX_FLOAT;
1699       
1700        // decides if the first few splits should be only axisAligned
1701        const bool onlyAxisAligned  =
1702                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1703                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1704                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1705       
1706        const int limit = onlyAxisAligned ? 0 :
1707                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1708
1709        float candidateCost;
1710
1711        int maxIdx = (int)data.mPolygons->size();
1712
1713        for (int i = 0; i < limit; ++ i)
1714        {
1715                // the already taken candidates are stored behind maxIdx
1716                // => assure that no index is taken twice
1717                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1718                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1719
1720                // swap candidate to the end to avoid testing same plane
1721                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1722                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1723
1724                // evaluate current candidate
1725                BspNodeGeometry fGeom, bGeom;
1726                float fArea, bArea;
1727                plane = poly->GetSupportingPlane();
1728                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
1729               
1730                if (candidateCost < lowestCost)
1731                {
1732                        bestPlane = plane;
1733                        lowestCost = candidateCost;
1734                }
1735        }
1736
1737
1738        //-- evaluate axis aligned splits
1739       
1740        int axis;
1741        BspNodeGeometry *fGeom, *bGeom;
1742        float pFront, pBack;
1743
1744        candidateCost = 99999999.0f;
1745
1746        // as a variant, we take axis aligned split only if there is
1747        // more polygon available to guide the split
1748        if (!mUsePolygonSplitIfAvailable || data.mPolygons->empty())
1749        {
1750                candidateCost = SelectAxisAlignedPlane(plane,
1751                                                                                           data,
1752                                                                                           axis,
1753                                                                                           &fGeom,
1754                                                                                           &bGeom,
1755                                                                                           pFront,
1756                                                                                           pBack,
1757                                                                                           data.mIsKdNode);     
1758        }
1759
1760        splitAxis = 3;
1761
1762        if (candidateCost < lowestCost)
1763        {       
1764                bestPlane = plane;
1765                lowestCost = candidateCost;
1766                splitAxis = axis;
1767       
1768                // assign already computed values
1769                // we can do this because we always save the
1770                // computed values from the axis aligned splits         
1771
1772                if (fGeom && bGeom)
1773                {
1774                        frontData.mGeometry = fGeom;
1775                        backData.mGeometry = bGeom;
1776       
1777                        frontData.mProbability = pFront;
1778                        backData.mProbability = pBack;
1779                }
1780        }
1781        else
1782        {
1783                DEL_PTR(fGeom);
1784                DEL_PTR(bGeom);
1785        }
1786   
1787#ifdef _DEBUG
1788        Debug << "plane lowest cost: " << lowestCost << endl;
1789#endif
1790
1791        // exeeded relative max cost ratio
1792        if (lowestCost > mTermMaxCostRatio)
1793        {
1794                return false;
1795        }
1796
1797        return true;
1798}
1799
1800
1801Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
1802{
1803        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1804
1805        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1806        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1807
1808        const Vector3 pt = (maxPt + minPt) * 0.5;
1809        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1810
1811        return Plane3(normal, pt);
1812}
1813
1814
1815Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
1816{
1817        Vector3 pt[3];
1818
1819        int idx[3];
1820        int cmaxT = 0;
1821        int cminT = 0;
1822        bool chooseMin = false;
1823
1824        for (int j = 0; j < 3; ++ j)
1825        {
1826                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1827
1828                if (idx[j] >= (int)rays.size())
1829                {
1830                        idx[j] -= (int)rays.size();
1831
1832                        chooseMin = (cminT < 2);
1833                }
1834                else
1835                        chooseMin = (cmaxT < 2);
1836
1837                RayInfo rayInf = rays[idx[j]];
1838                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1839        }
1840
1841        return Plane3(pt[0], pt[1], pt[2]);
1842}
1843
1844
1845Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1846{
1847        Vector3 pt[3];
1848
1849        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1850        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1851
1852        // check if rays different
1853        if (idx1 == idx2)
1854                idx2 = (idx2 + 1) % (int)rays.size();
1855
1856        const RayInfo ray1 = rays[idx1];
1857        const RayInfo ray2 = rays[idx2];
1858
1859        // normal vector of the plane parallel to both lines
1860        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1861
1862        // vector from line 1 to line 2
1863        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1864
1865        // project vector on normal to get distance
1866        const float dist = DotProd(vd, norm);
1867
1868        // point on plane lies halfway between the two planes
1869        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1870
1871        return Plane3(norm, planePt);
1872}
1873
1874
1875inline void VspBspTree::GenerateUniqueIdsForPvs()
1876{
1877        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1878        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1879        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
1880}
1881
1882
1883float VspBspTree::EvalRenderCostDecrease(const Plane3 &candidatePlane,
1884                                                                                 const VspBspTraversalData &data) const
1885{
1886        float pvsFront = 0;
1887        float pvsBack = 0;
1888        float totalPvs = 0;
1889
1890        // probability that view point lies in back / front node
1891        float pOverall = data.mProbability;
1892        float pFront = 0;
1893        float pBack = 0;
1894
1895
1896        // create unique ids for pvs heuristics
1897        GenerateUniqueIdsForPvs();
1898       
1899        for (int i = 0; i < data.mRays->size(); ++ i)
1900        {
1901                RayInfo rayInf = (*data.mRays)[i];
1902
1903                float t;
1904                VssRay *ray = rayInf.mRay;
1905                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1906
1907                // find front and back pvs for origing and termination object
1908                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1909
1910                if (COUNT_ORIGIN_OBJECTS)
1911                        AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1912        }
1913
1914
1915        BspNodeGeometry geomFront;
1916        BspNodeGeometry geomBack;
1917
1918        // construct child geometry with regard to the candidate split plane
1919        data.mGeometry->SplitGeometry(geomFront,
1920                                                                  geomBack,
1921                                                                  candidatePlane,
1922                                                                  mBox,
1923                                                                  //0.0f);
1924                                                                  mEpsilon);
1925
1926        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1927        {
1928                pFront = geomFront.GetVolume();
1929                pBack = pOverall - pFront;
1930
1931                // something is wrong with the volume
1932                if (0 && ((pFront < 0.0) || (pBack < 0.0)))
1933                {
1934                        Debug << "ERROR in volume:\n"
1935                                  << "volume f :" << pFront << " b: " << pBack << " p: " << pOverall
1936                                  << ", real volume f: " << pFront << " b: " << geomBack.GetVolume()
1937                                  << ", #polygons f: " << geomFront.Size() << " b: " << geomBack.Size() << " p: " << data.mGeometry->Size() << endl;
1938                }
1939        }
1940        else
1941        {
1942                pFront = geomFront.GetArea();
1943                pBack = geomBack.GetArea();
1944        }
1945       
1946
1947        // -- pvs rendering heuristics
1948
1949        // upper and lower bounds
1950        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1951        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1952
1953        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
1954    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
1955        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
1956                       
1957        const float oldRenderCost = pOverall * penaltyOld;
1958        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1959
1960        //Debug << "decrease: " << oldRenderCost - newRenderCost << endl;
1961        const float renderCostDecrease = (oldRenderCost - newRenderCost) / mBox.GetVolume();
1962       
1963        const float weight = mRenderCostDecreaseWeight;
1964        // take render cost of node into account to avoid being stuck in a local minimum
1965        const float normalizedOldRenderCost = oldRenderCost / mBox.GetVolume();
1966       
1967        //Debug << "rendercostdecr: " << weight * renderCostDecrease << " old render cost: " << (1.0f - weight) * normalizedOldRenderCost << endl;
1968        return weight * renderCostDecrease + (1.0f - weight) * normalizedOldRenderCost;
1969}
1970
1971
1972float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1973                                                                         const VspBspTraversalData &data,
1974                                                                         BspNodeGeometry &geomFront,
1975                                                                         BspNodeGeometry &geomBack,
1976                                                                         float &pFront,
1977                                                                         float &pBack) const
1978{
1979        float totalPvs = 0;
1980        float pvsFront = 0;
1981        float pvsBack = 0;
1982       
1983        // overall probability is used as normalizer
1984        float pOverall = 0;
1985
1986        // probability that view point lies in back / front node
1987        pFront = 0;
1988        pBack = 0;
1989
1990        int numTests; // the number of tests
1991
1992        // if random samples shold be taken instead of testing all the rays
1993        bool useRand;
1994
1995        if ((int)data.mRays->size() > mMaxTests)
1996        {
1997                useRand = true;
1998                numTests = mMaxTests;
1999        }
2000        else
2001        {
2002                useRand = false;
2003                numTests = (int)data.mRays->size();
2004        }
2005       
2006        // create unique ids for pvs heuristics
2007        GenerateUniqueIdsForPvs();
2008
2009        for (int i = 0; i < numTests; ++ i)
2010        {
2011                const int testIdx = useRand ?
2012                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
2013                RayInfo rayInf = (*data.mRays)[testIdx];
2014
2015                float t;
2016                VssRay *ray = rayInf.mRay;
2017                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
2018
2019                // find front and back pvs for origing and termination object
2020                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
2021
2022                if (COUNT_ORIGIN_OBJECTS)
2023                        AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
2024        }
2025
2026        // construct child geometry with regard to the candidate split plane
2027        bool splitSuccessFull = data.mGeometry->SplitGeometry(geomFront,
2028                                                                                                                  geomBack,
2029                                                                                                                  candidatePlane,
2030                                                                                                                  mBox,
2031                                                                                                                  //0.0f);
2032                                                                                                                  mEpsilon);
2033
2034        pOverall = data.mProbability;
2035
2036        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
2037        {
2038                pFront = geomFront.GetVolume();
2039                pBack = pOverall - pFront;
2040               
2041                // HACK: precision issues possible for unbalanced split => don't take this split!
2042                if (1 &&
2043                        (!splitSuccessFull || (pFront <= 0) || (pBack <= 0) ||
2044                        !geomFront.Valid() || !geomBack.Valid()))
2045                {
2046                        //Debug << "error f: " << pFront << " b: " << pBack << endl;
2047
2048                        // high penalty for degenerated / wrong split
2049                        return 99999.9f;
2050                }
2051        }
2052        else
2053        {
2054                pFront = geomFront.GetArea();
2055                pBack = geomBack.GetArea();
2056        }
2057       
2058
2059        // -- pvs rendering heuristics
2060        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
2061        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
2062
2063        // only render cost heuristics or combined with standard deviation
2064        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
2065    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
2066        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
2067                       
2068        const float oldRenderCost = pOverall * penaltyOld;
2069        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
2070
2071        float oldCost, newCost;
2072
2073        // only render cost
2074        if (1)
2075        {
2076                oldCost = oldRenderCost;
2077                newCost = newRenderCost;
2078        }
2079        else // also considering standard deviation
2080        {
2081                // standard deviation is difference of back and front pvs
2082                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
2083
2084                const float newDeviation = 0.5f *
2085                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
2086
2087                const float oldDeviation = penaltyOld;
2088
2089                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
2090                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
2091        }
2092
2093        const float cost = mPvsFactor * newCost / (oldCost + Limits::Small);
2094               
2095
2096#ifdef _DEBUG
2097        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
2098                  << " frontpvs: " << pvsFront << " pFront: " << pFront
2099                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
2100        Debug << "cost: " << cost << endl;
2101#endif
2102
2103        return cost;
2104}
2105
2106
2107int VspBspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2108                                                                                ViewCellContainer &viewCells) const
2109{
2110        stack<bspNodePair> nodeStack;
2111        BspNodeGeometry *rgeom = new BspNodeGeometry();
2112
2113        ConstructGeometry(mRoot, *rgeom);
2114
2115        nodeStack.push(bspNodePair(mRoot, rgeom));
2116 
2117        ViewCell::NewMail();
2118
2119        while (!nodeStack.empty())
2120        {
2121                BspNode *node = nodeStack.top().first;
2122                BspNodeGeometry *geom = nodeStack.top().second;
2123                nodeStack.pop();
2124
2125                const int side = geom->ComputeIntersection(box);
2126               
2127                switch (side)
2128                {
2129                case -1:
2130                        // node geometry is contained in box
2131                        CollectViewCells(node, true, viewCells, true);
2132                        break;
2133
2134                case 0:
2135                        if (node->IsLeaf())
2136                        {
2137                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2138                       
2139                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2140                                {
2141                                        leaf->GetViewCell()->Mail();
2142                                        viewCells.push_back(leaf->GetViewCell());
2143                                }
2144                        }
2145                        else
2146                        {
2147                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2148                       
2149                                BspNode *first = interior->GetFront();
2150                                BspNode *second = interior->GetBack();
2151           
2152                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2153                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2154
2155                                geom->SplitGeometry(*firstGeom,
2156                                                                        *secondGeom,
2157                                                                        interior->GetPlane(),
2158                                                                        mBox,
2159                                                                        //0.0000001f);
2160                                                                        mEpsilon);
2161
2162                                nodeStack.push(bspNodePair(first, firstGeom));
2163                                nodeStack.push(bspNodePair(second, secondGeom));
2164                        }
2165                       
2166                        break;
2167                default:
2168                        // default: cull
2169                        break;
2170                }
2171               
2172                DEL_PTR(geom);
2173               
2174        }
2175
2176        return (int)viewCells.size();
2177}
2178
2179
2180float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
2181                                                                                   const AxisAlignedBox3 &box,
2182                                                                                   const int axis,
2183                                                                                   const float &position,                                                                                 
2184                                                                                   float &pFront,
2185                                                                                   float &pBack) const
2186{
2187        float pvsTotal = 0;
2188        float pvsFront = 0;
2189        float pvsBack = 0;
2190       
2191        // create unique ids for pvs heuristics
2192        GenerateUniqueIdsForPvs();
2193
2194        const int pvsSize = data.mPvs;
2195
2196        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
2197
2198        // this is the main ray classification loop!
2199        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
2200        {
2201                // determine the side of this ray with respect to the plane
2202                float t;
2203                const int side = (*rit).ComputeRayIntersection(axis, position, t);
2204       
2205                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
2206
2207                if (COUNT_ORIGIN_OBJECTS)
2208                        AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
2209        }
2210
2211
2212        //-- pvs heuristics
2213
2214        float pOverall = data.mProbability;
2215
2216        // note: we use a simplified computation assuming that we always do a
2217        // spatial mid split   
2218       
2219        if (!mUseAreaForPvs)
2220        {   
2221                // volume
2222                pBack = pFront = pOverall * 0.5f;
2223#if 0
2224                // box length substitute for probability
2225                const float minBox = box.Min(axis);
2226                const float maxBox = box.Max(axis);
2227
2228                pBack = position - minBox;
2229                pFront = maxBox - position;
2230                pOverall = maxBox - minBox;
2231#endif
2232        }
2233        else //-- area substitute for probability
2234        {
2235                const int axis2 = (axis + 1) % 3;
2236                const int axis3 = (axis + 2) % 3;
2237
2238                const float faceArea =
2239                        (box.Max(axis2) - box.Min(axis2)) *
2240                        (box.Max(axis3) - box.Min(axis3));
2241
2242                pBack = pFront = pOverall * 0.5f + faceArea;
2243        }
2244
2245#ifdef _DEBUG
2246        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
2247        Debug << pFront << " " << pBack << " " << pOverall << endl;
2248#endif
2249
2250       
2251        const float newCost = pvsBack * pBack + pvsFront * pFront;
2252        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
2253
2254        return  (mCtDivCi + newCost) / oldCost;
2255}
2256
2257
2258void VspBspTree::AddObjToPvs(Intersectable *obj,
2259                                                         const int cf,
2260                                                         float &frontPvs,
2261                                                         float &backPvs,
2262                                                         float &totalPvs) const
2263{
2264        if (!obj)
2265                return;
2266
2267        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
2268
2269        // new object
2270        if ((obj->mMailbox != sFrontId) &&
2271                (obj->mMailbox != sBackId) &&
2272                (obj->mMailbox != sFrontAndBackId))
2273        {
2274                totalPvs += renderCost;
2275        }
2276
2277        // TODO: does this really belong to no pvs?
2278        //if (cf == Ray::COINCIDENT) return;
2279
2280        // object belongs to both PVS
2281        if (cf >= 0)
2282        {
2283                if ((obj->mMailbox != sFrontId) &&
2284                        (obj->mMailbox != sFrontAndBackId))
2285                {
2286                        frontPvs += renderCost;
2287               
2288                        if (obj->mMailbox == sBackId)
2289                                obj->mMailbox = sFrontAndBackId;
2290                        else
2291                                obj->mMailbox = sFrontId;
2292                }
2293        }
2294
2295        if (cf <= 0)
2296        {
2297                if ((obj->mMailbox != sBackId) &&
2298                        (obj->mMailbox != sFrontAndBackId))
2299                {
2300                        backPvs += renderCost;
2301               
2302                        if (obj->mMailbox == sFrontId)
2303                                obj->mMailbox = sFrontAndBackId;
2304                        else
2305                                obj->mMailbox = sBackId;
2306                }
2307        }
2308}
2309
2310
2311void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
2312                                                           const bool onlyUnmailed,
2313                                                           const int maxPvsSize) const
2314{
2315        stack<BspNode *> nodeStack;
2316        nodeStack.push(mRoot);
2317
2318        while (!nodeStack.empty())
2319        {
2320                BspNode *node = nodeStack.top();
2321                nodeStack.pop();
2322               
2323                if (node->IsLeaf())
2324                {
2325                        // test if this leaf is in valid view space
2326                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2327                        if (leaf->TreeValid() &&
2328                                (!onlyUnmailed || !leaf->Mailed()) &&
2329                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
2330                        {
2331                                leaves.push_back(leaf);
2332                        }
2333                }
2334                else
2335                {
2336                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2337
2338                        nodeStack.push(interior->GetBack());
2339                        nodeStack.push(interior->GetFront());
2340                }
2341        }
2342}
2343
2344
2345AxisAlignedBox3 VspBspTree::GetBoundingBox() const
2346{
2347        return mBox;
2348}
2349
2350
2351BspNode *VspBspTree::GetRoot() const
2352{
2353        return mRoot;
2354}
2355
2356
2357void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
2358{
2359        // the node became a leaf -> evaluate stats for leafs
2360        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
2361
2362
2363        if (data.mPvs > mBspStats.maxPvs)
2364        {
2365                mBspStats.maxPvs = data.mPvs;
2366        }
2367
2368        mBspStats.pvs += data.mPvs;
2369
2370        if (data.mDepth < mBspStats.minDepth)
2371        {
2372                mBspStats.minDepth = data.mDepth;
2373        }
2374       
2375        if (data.mDepth >= mTermMaxDepth)
2376        {
2377        ++ mBspStats.maxDepthNodes;
2378                //Debug << "new max depth: " << mBspStats.maxDepthNodes << endl;
2379        }
2380
2381        // accumulate rays to compute rays /  leaf
2382        mBspStats.accumRays += (int)data.mRays->size();
2383
2384        if (data.mPvs < mTermMinPvs)
2385                ++ mBspStats.minPvsNodes;
2386
2387        if ((int)data.mRays->size() < mTermMinRays)
2388                ++ mBspStats.minRaysNodes;
2389
2390        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
2391                ++ mBspStats.maxRayContribNodes;
2392
2393        if (data.mProbability <= mTermMinProbability)
2394                ++ mBspStats.minProbabilityNodes;
2395       
2396        // accumulate depth to compute average depth
2397        mBspStats.accumDepth += data.mDepth;
2398
2399        ++ mCreatedViewCells;
2400
2401#ifdef _DEBUG
2402        Debug << "BSP stats: "
2403                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
2404                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
2405                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
2406                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "), "
2407                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
2408#endif
2409}
2410
2411
2412int VspBspTree::CastRay(Ray &ray)
2413{
2414        int hits = 0;
2415
2416        stack<BspRayTraversalData> tQueue;
2417
2418        float maxt, mint;
2419
2420        if (!mBox.GetRaySegment(ray, mint, maxt))
2421                return 0;
2422
2423        Intersectable::NewMail();
2424        ViewCell::NewMail();
2425
2426        Vector3 entp = ray.Extrap(mint);
2427        Vector3 extp = ray.Extrap(maxt);
2428
2429        BspNode *node = mRoot;
2430        BspNode *farChild = NULL;
2431
2432        while (1)
2433        {
2434                if (!node->IsLeaf())
2435                {
2436                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2437
2438                        Plane3 splitPlane = in->GetPlane();
2439                        const int entSide = splitPlane.Side(entp);
2440                        const int extSide = splitPlane.Side(extp);
2441
2442                        if (entSide < 0)
2443                        {
2444                                node = in->GetBack();
2445
2446                                if(extSide <= 0) // plane does not split ray => no far child
2447                                        continue;
2448
2449                                farChild = in->GetFront(); // plane splits ray
2450
2451                        } else if (entSide > 0)
2452                        {
2453                                node = in->GetFront();
2454
2455                                if (extSide >= 0) // plane does not split ray => no far child
2456                                        continue;
2457
2458                                farChild = in->GetBack(); // plane splits ray
2459                        }
2460                        else // ray and plane are coincident
2461                        {
2462                                // matt: WHAT TO DO IN THIS CASE ?
2463                                //break;
2464                                node = in->GetFront();
2465                                continue;
2466                        }
2467
2468                        // push data for far child
2469                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
2470
2471                        // find intersection of ray segment with plane
2472                        float t;
2473                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2474                        maxt *= t;
2475                }
2476                else // reached leaf => intersection with view cell
2477                {
2478                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2479
2480                        if (!leaf->GetViewCell()->Mailed())
2481                        {
2482                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2483                                leaf->GetViewCell()->Mail();
2484                                ++ hits;
2485                        }
2486
2487                        //-- fetch the next far child from the stack
2488                        if (tQueue.empty())
2489                                break;
2490
2491                        entp = extp;
2492                        mint = maxt; // NOTE: need this?
2493
2494                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2495                                break;
2496
2497                        BspRayTraversalData &s = tQueue.top();
2498
2499                        node = s.mNode;
2500                        extp = s.mExitPoint;
2501                        maxt = s.mMaxT;
2502
2503                        tQueue.pop();
2504                }
2505        }
2506
2507        return hits;
2508}
2509
2510
2511void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
2512{
2513        ViewCell::NewMail();
2514       
2515        CollectViewCells(mRoot, onlyValid, viewCells, true);
2516}
2517
2518
2519void VspBspTree::CollapseViewCells()
2520{
2521// TODO
2522#if HAS_TO_BE_REDONE
2523        stack<BspNode *> nodeStack;
2524
2525        if (!mRoot)
2526                return;
2527
2528        nodeStack.push(mRoot);
2529       
2530        while (!nodeStack.empty())
2531        {
2532                BspNode *node = nodeStack.top();
2533                nodeStack.pop();
2534               
2535                if (node->IsLeaf())
2536        {
2537                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2538
2539                        if (!viewCell->GetValid())
2540                        {
2541                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2542       
2543                                ViewCellContainer leaves;
2544                                mViewCellsTree->CollectLeaves(viewCell, leaves);
2545
2546                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2547
2548                                for (it = leaves.begin(); it != it_end; ++ it)
2549                                {
2550                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2551                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2552                                        ++ mBspStats.invalidLeaves;
2553                                }
2554
2555                                // add to unbounded view cell
2556                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2557                                DEL_PTR(viewCell);
2558                        }
2559                }
2560                else
2561                {
2562                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2563               
2564                        nodeStack.push(interior->GetFront());
2565                        nodeStack.push(interior->GetBack());
2566                }
2567        }
2568
2569        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2570#endif
2571}
2572
2573
2574void VspBspTree::CollectRays(VssRayContainer &rays)
2575{
2576        vector<BspLeaf *> leaves;
2577
2578        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2579
2580        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2581        {
2582                BspLeaf *leaf = *lit;
2583                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2584
2585                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2586                        rays.push_back(*rit);
2587        }
2588}
2589
2590
2591void VspBspTree::ValidateTree()
2592{
2593        stack<BspNode *> nodeStack;
2594
2595        if (!mRoot)
2596                return;
2597
2598        nodeStack.push(mRoot);
2599       
2600        mBspStats.invalidLeaves = 0;
2601        while (!nodeStack.empty())
2602        {
2603                BspNode *node = nodeStack.top();
2604                nodeStack.pop();
2605               
2606                if (node->IsLeaf())
2607                {
2608                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2609
2610                        if (!leaf->GetViewCell()->GetValid())
2611                                ++ mBspStats.invalidLeaves;
2612
2613                        // validity flags don't match => repair
2614                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2615                        {
2616                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2617                                PropagateUpValidity(leaf);
2618                        }
2619                }
2620                else
2621                {
2622                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2623               
2624                        nodeStack.push(interior->GetFront());
2625                        nodeStack.push(interior->GetBack());
2626                }
2627        }
2628
2629        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2630}
2631
2632
2633
2634void VspBspTree::CollectViewCells(BspNode *root,
2635                                                                  bool onlyValid,
2636                                                                  ViewCellContainer &viewCells,
2637                                                                  bool onlyUnmailed) const
2638{
2639        stack<BspNode *> nodeStack;
2640
2641        if (!root)
2642                return;
2643
2644        nodeStack.push(root);
2645       
2646        while (!nodeStack.empty())
2647        {
2648                BspNode *node = nodeStack.top();
2649                nodeStack.pop();
2650               
2651                if (node->IsLeaf())
2652                {
2653                        if (!onlyValid || node->TreeValid())
2654                        {
2655                                ViewCellLeaf *leafVc = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2656
2657                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2658                                               
2659                                if (!onlyUnmailed || !viewCell->Mailed())
2660                                {
2661                                        viewCell->Mail();
2662                                        viewCells.push_back(viewCell);
2663                                }
2664                        }
2665                }
2666                else
2667                {
2668                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2669               
2670                        nodeStack.push(interior->GetFront());
2671                        nodeStack.push(interior->GetBack());
2672                }
2673        }
2674
2675}
2676
2677
2678void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2679{
2680        // preprocess: throw out polygons coincident to the view space box (not needed)
2681        PolygonContainer boxPolys;
2682       
2683        mBox.ExtractPolys(boxPolys);
2684        vector<Plane3> boxPlanes;
2685
2686        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2687
2688        // extract planes of box
2689        // TODO: can be done more elegantly than first extracting polygons
2690        // and take their planes
2691        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2692        {
2693                boxPlanes.push_back((*pit)->GetSupportingPlane());
2694        }
2695
2696        pit_end = polys.end();
2697
2698        for (pit = polys.begin(); pit != pit_end; ++ pit)
2699        {
2700                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2701               
2702                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2703                {
2704                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2705
2706                        if (cf == Polygon3::COINCIDENT)
2707                        {
2708                                DEL_PTR(*pit);
2709                                //Debug << "coincident!!" << endl;
2710                        }
2711                }
2712        }
2713
2714        // remove deleted entries after swapping them to end of vector
2715        for (int i = 0; i < (int)polys.size(); ++ i)
2716        {
2717                while (!polys[i] && (i < (int)polys.size()))
2718                {
2719                        swap(polys[i], polys.back());
2720                        polys.pop_back();
2721                }
2722        }
2723}
2724
2725
2726float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2727{
2728        float len = 0;
2729
2730        RayInfoContainer::const_iterator it, it_end = rays.end();
2731
2732        for (it = rays.begin(); it != it_end; ++ it)
2733                len += (*it).SegmentLength();
2734
2735        return len;
2736}
2737
2738
2739int VspBspTree::SplitRays(const Plane3 &plane,
2740                                                  RayInfoContainer &rays,
2741                                                  RayInfoContainer &frontRays,
2742                                                  RayInfoContainer &backRays) const
2743{
2744        int splits = 0;
2745
2746        RayInfoContainer::const_iterator it, it_end = rays.end();
2747
2748        for (it = rays.begin(); it != it_end; ++ it)
2749        {
2750                RayInfo bRay = *it;
2751               
2752                VssRay *ray = bRay.mRay;
2753                float t;
2754
2755                // get classification and receive new t
2756                const int cf = bRay.ComputeRayIntersection(plane, t);
2757
2758                switch (cf)
2759                {
2760                case -1:
2761                        backRays.push_back(bRay);
2762                        break;
2763                case 1:
2764                        frontRays.push_back(bRay);
2765                        break;
2766                case 0:
2767                        {
2768                                //-- split ray
2769                                //   test if start point behind or in front of plane
2770                                const int side = plane.Side(bRay.ExtrapOrigin());
2771
2772                                ++ splits;
2773
2774                                if (side <= 0)
2775                                {
2776                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2777                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2778                                }
2779                                else
2780                                {
2781                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2782                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2783                                }
2784                        }
2785                        break;
2786                default:
2787                        Debug << "Should not come here" << endl;
2788                        break;
2789                }
2790        }
2791
2792        return splits;
2793}
2794
2795
2796void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2797{
2798        BspNode *lastNode;
2799
2800        do
2801        {
2802                lastNode = n;
2803
2804                // want to get planes defining geometry of this node => don't take
2805                // split plane of node itself
2806                n = n->GetParent();
2807
2808                if (n)
2809                {
2810                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2811                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2812
2813            if (interior->GetBack() != lastNode)
2814                                halfSpace.ReverseOrientation();
2815
2816                        halfSpaces.push_back(halfSpace);
2817                }
2818        }
2819        while (n);
2820}
2821
2822
2823void VspBspTree::ConstructGeometry(BspNode *n,
2824                                                                   BspNodeGeometry &geom) const
2825{
2826        vector<Plane3> halfSpaces;
2827        ExtractHalfSpaces(n, halfSpaces);
2828
2829        PolygonContainer candidatePolys;
2830        vector<Plane3> candidatePlanes;
2831
2832        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2833
2834        // bounded planes are added to the polygons
2835        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
2836        {
2837                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
2838
2839                if (p->Valid(mEpsilon))
2840                {
2841                        candidatePolys.push_back(p);
2842                        candidatePlanes.push_back(*pit);
2843                }
2844        }
2845
2846        // add faces of bounding box (also could be faces of the cell)
2847        for (int i = 0; i < 6; ++ i)
2848        {
2849                VertexContainer vertices;
2850
2851                for (int j = 0; j < 4; ++ j)
2852                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2853
2854                Polygon3 *poly = new Polygon3(vertices);
2855
2856                candidatePolys.push_back(poly);
2857                candidatePlanes.push_back(poly->GetSupportingPlane());
2858        }
2859
2860        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2861        {
2862                // polygon is split by all other planes
2863                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2864                {
2865                        if (i == j) // polygon and plane are coincident
2866                                continue;
2867
2868                        VertexContainer splitPts;
2869                        Polygon3 *frontPoly, *backPoly;
2870
2871                        const int cf =
2872                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2873                                                                                                 mEpsilon);
2874
2875                        switch (cf)
2876                        {
2877                                case Polygon3::SPLIT:
2878                                        frontPoly = new Polygon3();
2879                                        backPoly = new Polygon3();
2880
2881                                        candidatePolys[i]->Split(halfSpaces[j],
2882                                                                                         *frontPoly,
2883                                                                                         *backPoly,
2884                                                                                         mEpsilon);
2885
2886                                        DEL_PTR(candidatePolys[i]);
2887
2888                                        if (backPoly->Valid(mEpsilon))
2889                                                candidatePolys[i] = backPoly;
2890                                        else
2891                                                DEL_PTR(backPoly);
2892
2893                                        // outside, don't need this
2894                                        DEL_PTR(frontPoly);
2895                                        break;
2896                                // polygon outside of halfspace
2897                                case Polygon3::FRONT_SIDE:
2898                                        DEL_PTR(candidatePolys[i]);
2899                                        break;
2900                                // just take polygon as it is
2901                                case Polygon3::BACK_SIDE:
2902                                case Polygon3::COINCIDENT:
2903                                default:
2904                                        break;
2905                        }
2906                }
2907
2908                if (candidatePolys[i])
2909                {
2910                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2911                        //      geom.mPolys.push_back(candidates[i]);
2912                }
2913        }
2914}
2915
2916
2917void VspBspTree::ConstructGeometry(ViewCell *vc,
2918                                                                   BspNodeGeometry &vcGeom) const
2919{
2920        ViewCellContainer leaves;
2921       
2922        mViewCellsTree->CollectLeaves(vc, leaves);
2923
2924        ViewCellContainer::const_iterator it, it_end = leaves.end();
2925
2926        for (it = leaves.begin(); it != it_end; ++ it)
2927        {
2928                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2929               
2930                ConstructGeometry(l, vcGeom);
2931        }
2932}
2933
2934
2935int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2936                                                          const bool onlyUnmailed) const
2937{
2938        stack<bspNodePair> nodeStack;
2939       
2940        BspNodeGeometry nodeGeom;
2941        ConstructGeometry(n, nodeGeom);
2942//      const float eps = 0.5f;
2943        const float eps = 0.01f;
2944        // split planes from the root to this node
2945        // needed to verify that we found neighbor leaf
2946        // TODO: really needed?
2947        vector<Plane3> halfSpaces;
2948        ExtractHalfSpaces(n, halfSpaces);
2949
2950
2951        BspNodeGeometry *rgeom = new BspNodeGeometry();
2952        ConstructGeometry(mRoot, *rgeom);
2953
2954        nodeStack.push(bspNodePair(mRoot, rgeom));
2955
2956        while (!nodeStack.empty())
2957        {
2958                BspNode *node = nodeStack.top().first;
2959                BspNodeGeometry *geom = nodeStack.top().second;
2960       
2961                nodeStack.pop();
2962
2963                if (node->IsLeaf())
2964                {
2965                        // test if this leaf is in valid view space
2966                        if (node->TreeValid() &&
2967                                (node != n) &&
2968                                (!onlyUnmailed || !node->Mailed()))
2969                        {
2970                                bool isAdjacent = true;
2971
2972                                if (1)
2973                                {
2974                                        // test all planes of current node if still adjacent
2975                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2976                                        {
2977                                                const int cf =
2978                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2979                                                                                                        halfSpaces[i],
2980                                                                                                        eps);
2981
2982                                                if (cf == Polygon3::FRONT_SIDE)
2983                                                {
2984                                                        isAdjacent = false;
2985                                                }
2986                                        }
2987                                }
2988                                else
2989                                {
2990                                        // TODO: why is this wrong??
2991                                        // test all planes of current node if still adjacent
2992                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
2993                                        {
2994                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
2995
2996                                                const int cf =
2997                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2998                                                                                                        poly->GetSupportingPlane(),
2999                                                                                                        eps);
3000
3001                                                if (cf == Polygon3::FRONT_SIDE)
3002                                                {
3003                                                        isAdjacent = false;
3004                                                }
3005                                        }
3006                                }
3007                                // neighbor was found
3008                                if (isAdjacent)
3009                                {       
3010                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
3011                                }
3012                        }
3013                }
3014                else
3015                {
3016                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3017
3018                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
3019                                                                                                   interior->GetPlane(),
3020                                                                                                   eps);
3021                       
3022                        BspNode *front = interior->GetFront();
3023                        BspNode *back = interior->GetBack();
3024           
3025                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3026                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3027
3028                        geom->SplitGeometry(*fGeom,
3029                                                                *bGeom,
3030                                                                interior->GetPlane(),
3031                                                                mBox,
3032                                                                //0.0000001f);
3033                                                                eps);
3034               
3035                        if (cf == Polygon3::BACK_SIDE)
3036                        {
3037                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3038                                DEL_PTR(fGeom);
3039                        }
3040                        else
3041                        {
3042                                if (cf == Polygon3::FRONT_SIDE)
3043                                {
3044                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3045                                        DEL_PTR(bGeom);
3046                                }
3047                                else
3048                                {       // random decision
3049                                        nodeStack.push(bspNodePair(front, fGeom));
3050                                        nodeStack.push(bspNodePair(back, bGeom));
3051                                }
3052                        }
3053                }
3054       
3055                DEL_PTR(geom);
3056        }
3057
3058        return (int)neighbors.size();
3059}
3060
3061
3062
3063int VspBspTree::FindApproximateNeighbors(BspNode *n,
3064                                                                                 vector<BspLeaf *> &neighbors,
3065                                                                                 const bool onlyUnmailed) const
3066{
3067        stack<bspNodePair> nodeStack;
3068       
3069        BspNodeGeometry nodeGeom;
3070        ConstructGeometry(n, nodeGeom);
3071       
3072        float eps = 0.01f;
3073        // split planes from the root to this node
3074        // needed to verify that we found neighbor leaf
3075        // TODO: really needed?
3076        vector<Plane3> halfSpaces;
3077        ExtractHalfSpaces(n, halfSpaces);
3078
3079
3080        BspNodeGeometry *rgeom = new BspNodeGeometry();
3081        ConstructGeometry(mRoot, *rgeom);
3082
3083        nodeStack.push(bspNodePair(mRoot, rgeom));
3084
3085        while (!nodeStack.empty())
3086        {
3087                BspNode *node = nodeStack.top().first;
3088                BspNodeGeometry *geom = nodeStack.top().second;
3089       
3090                nodeStack.pop();
3091
3092                if (node->IsLeaf())
3093                {
3094                        // test if this leaf is in valid view space
3095                        if (node->TreeValid() &&
3096                                (node != n) &&
3097                                (!onlyUnmailed || !node->Mailed()))
3098                        {
3099                                bool isAdjacent = true;
3100
3101                                // neighbor was found
3102                                if (isAdjacent)
3103                                {       
3104                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
3105                                }
3106                        }
3107                }
3108                else
3109                {
3110                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3111
3112                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
3113                                                                                                   interior->GetPlane(),
3114                                                                                                   eps);
3115                       
3116                        BspNode *front = interior->GetFront();
3117                        BspNode *back = interior->GetBack();
3118           
3119                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3120                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3121
3122                        geom->SplitGeometry(*fGeom,
3123                                                                *bGeom,
3124                                                                interior->GetPlane(),
3125                                                                mBox,
3126                                                                //0.0000001f);
3127                                                                eps);
3128               
3129                        if (cf == Polygon3::BACK_SIDE)
3130                        {
3131                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3132                                DEL_PTR(fGeom);
3133                                }
3134                        else
3135                        {
3136                                if (cf == Polygon3::FRONT_SIDE)
3137                                {
3138                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3139                                        DEL_PTR(bGeom);
3140                                }
3141                                else
3142                                {       // random decision
3143                                        nodeStack.push(bspNodePair(front, fGeom));
3144                                        nodeStack.push(bspNodePair(back, bGeom));
3145                                }
3146                        }
3147                }
3148       
3149                DEL_PTR(geom);
3150        }
3151
3152        return (int)neighbors.size();
3153}
3154
3155
3156
3157BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
3158{
3159    stack<BspNode *> nodeStack;
3160        nodeStack.push(mRoot);
3161
3162        int mask = rand();
3163
3164        while (!nodeStack.empty())
3165        {
3166                BspNode *node = nodeStack.top();
3167                nodeStack.pop();
3168
3169                if (node->IsLeaf())
3170                {
3171                        return dynamic_cast<BspLeaf *>(node);
3172                }
3173                else
3174                {
3175                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3176                        BspNode *next;
3177                        BspNodeGeometry geom;
3178
3179                        // todo: not very efficient: constructs full cell everytime
3180                        ConstructGeometry(interior, geom);
3181
3182                        const int cf =
3183                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
3184
3185                        if (cf == Polygon3::BACK_SIDE)
3186                                next = interior->GetFront();
3187                        else
3188                                if (cf == Polygon3::FRONT_SIDE)
3189                                        next = interior->GetFront();
3190                        else
3191                        {
3192                                // random decision
3193                                if (mask & 1)
3194                                        next = interior->GetBack();
3195                                else
3196                                        next = interior->GetFront();
3197                                mask = mask >> 1;
3198                        }
3199
3200                        nodeStack.push(next);
3201                }
3202        }
3203
3204        return NULL;
3205}
3206
3207
3208BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3209{
3210        stack<BspNode *> nodeStack;
3211
3212        nodeStack.push(mRoot);
3213
3214        int mask = rand();
3215
3216        while (!nodeStack.empty())
3217        {
3218                BspNode *node = nodeStack.top();
3219                nodeStack.pop();
3220
3221                if (node->IsLeaf())
3222                {
3223                        if ( (!onlyUnmailed || !node->Mailed()) )
3224                                return dynamic_cast<BspLeaf *>(node);
3225                }
3226                else
3227                {
3228                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3229
3230                        // random decision
3231                        if (mask & 1)
3232                                nodeStack.push(interior->GetBack());
3233                        else
3234                                nodeStack.push(interior->GetFront());
3235
3236                        mask = mask >> 1;
3237                }
3238        }
3239
3240        return NULL;
3241}
3242
3243
3244int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3245{
3246        int pvsSize = 0;
3247
3248        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3249
3250        Intersectable::NewMail();
3251
3252        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3253        {
3254                VssRay *ray = (*rit).mRay;
3255
3256                if (COUNT_ORIGIN_OBJECTS && ray->mOriginObject)
3257                {
3258                        if (!ray->mOriginObject->Mailed())
3259                        {
3260                                ray->mOriginObject->Mail();
3261                                ++ pvsSize;
3262                        }
3263                }
3264
3265                if (ray->mTerminationObject)
3266                {
3267                        if (!ray->mTerminationObject->Mailed())
3268                        {
3269                                ray->mTerminationObject->Mail();
3270                                ++ pvsSize;
3271                        }
3272                }
3273        }
3274
3275        return pvsSize;
3276}
3277
3278
3279float VspBspTree::GetEpsilon() const
3280{
3281        return mEpsilon;
3282}
3283
3284
3285int VspBspTree::SplitPolygons(const Plane3 &plane,
3286                                                          PolygonContainer &polys,
3287                                                          PolygonContainer &frontPolys,
3288                                                          PolygonContainer &backPolys,
3289                                                          PolygonContainer &coincident) const
3290{
3291        int splits = 0;
3292
3293        PolygonContainer::const_iterator it, it_end = polys.end();
3294
3295        for (it = polys.begin(); it != polys.end(); ++ it)     
3296        {
3297                Polygon3 *poly = *it;
3298
3299                // classify polygon
3300                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3301
3302                switch (cf)
3303                {
3304                        case Polygon3::COINCIDENT:
3305                                coincident.push_back(poly);
3306                                break;
3307                        case Polygon3::FRONT_SIDE:
3308                                frontPolys.push_back(poly);
3309                                break;
3310                        case Polygon3::BACK_SIDE:
3311                                backPolys.push_back(poly);
3312                                break;
3313                        case Polygon3::SPLIT:
3314                                backPolys.push_back(poly);
3315                                frontPolys.push_back(poly);
3316                                ++ splits;
3317                                break;
3318                        default:
3319                Debug << "SHOULD NEVER COME HERE\n";
3320                                break;
3321                }
3322        }
3323
3324        return splits;
3325}
3326
3327
3328int VspBspTree::CastLineSegment(const Vector3 &origin,
3329                                                                const Vector3 &termination,
3330                                                                ViewCellContainer &viewcells)
3331{
3332        int hits = 0;
3333        stack<BspRayTraversalData> tStack;
3334
3335        float mint = 0.0f, maxt = 1.0f;
3336
3337        Intersectable::NewMail();
3338        ViewCell::NewMail();
3339
3340        Vector3 entp = origin;
3341        Vector3 extp = termination;
3342
3343        BspNode *node = mRoot;
3344        BspNode *farChild = NULL;
3345
3346        float t;
3347        const float thresh = 1e-6f; // matt: change this to adjustable value
3348       
3349        while (1)
3350        {
3351                if (!node->IsLeaf())
3352                {
3353                        BspInterior *in = dynamic_cast<BspInterior *>(node);
3354
3355                        Plane3 splitPlane = in->GetPlane();
3356                       
3357                        const int entSide = splitPlane.Side(entp, thresh);
3358                        const int extSide = splitPlane.Side(extp, thresh);
3359
3360                        if (entSide < 0)
3361                        {
3362                                node = in->GetBack();
3363                               
3364                                // plane does not split ray => no far child
3365                                if (extSide <= 0)
3366                                        continue;
3367 
3368                                farChild = in->GetFront(); // plane splits ray
3369                        }
3370                        else if (entSide > 0)
3371                        {
3372                                node = in->GetFront();
3373
3374                                if (extSide >= 0) // plane does not split ray => no far child
3375                                        continue;
3376
3377                                farChild = in->GetBack(); // plane splits ray
3378                        }
3379                        else // one of the ray end points is on the plane
3380                        {       
3381                                // NOTE: what to do if ray is coincident with plane?
3382                                if (extSide < 0)
3383                                        node = in->GetBack();
3384                                else //if (extSide > 0)
3385                                        node = in->GetFront();
3386                                //else break; // coincident => count no intersections
3387
3388                                continue; // no far child
3389                        }
3390
3391                        // push data for far child
3392                        tStack.push(BspRayTraversalData(farChild, extp));
3393
3394                        // find intersection of ray segment with plane
3395                        extp = splitPlane.FindIntersection(origin, extp, &t);
3396                }
3397                else
3398                {
3399                        // reached leaf => intersection with view cell
3400                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3401                        ViewCell *viewCell;
3402                       
3403                        // question: always contribute to leaf or to currently active view cell?
3404                        if (0)
3405                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3406                        else
3407                                viewCell = leaf->GetViewCell();
3408
3409                        if (!viewCell->Mailed())
3410                        {
3411                                viewcells.push_back(viewCell);
3412                                viewCell->Mail();
3413                                ++ hits;
3414                        }
3415
3416                        //-- fetch the next far child from the stack
3417                        if (tStack.empty())
3418                                break;
3419
3420                        entp = extp;
3421                       
3422                        const BspRayTraversalData &s = tStack.top();
3423
3424                        node = s.mNode;
3425                        extp = s.mExitPoint;
3426
3427                        tStack.pop();
3428                }
3429        }
3430
3431        return hits;
3432}
3433
3434
3435
3436
3437int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
3438{
3439        std::deque<BspNode *> path1;
3440        BspNode *p1 = n1;
3441
3442        // create path from node 1 to root
3443        while (p1)
3444        {
3445                if (p1 == n2) // second node on path
3446                        return (int)path1.size();
3447
3448                path1.push_front(p1);
3449                p1 = p1->GetParent();
3450        }
3451
3452        int depth = n2->GetDepth();
3453        int d = depth;
3454
3455        BspNode *p2 = n2;
3456
3457        // compare with same depth
3458        while (1)
3459        {
3460                if ((d < (int)path1.size()) && (p2 == path1[d]))
3461                        return (depth - d) + ((int)path1.size() - 1 - d);
3462
3463                -- d;
3464                p2 = p2->GetParent();
3465        }
3466
3467        return 0; // never come here
3468}
3469
3470
3471BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
3472{
3473// TODO
3474#if HAS_TO_BE_REDONE
3475        if (node->IsLeaf())
3476                return node;
3477
3478        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3479
3480        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3481        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
3482
3483        if (front->IsLeaf() && back->IsLeaf())
3484        {
3485                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
3486                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
3487
3488                //-- collapse tree
3489                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3490                {
3491                        BspViewCell *vc = frontLeaf->GetViewCell();
3492
3493                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
3494                        leaf->SetTreeValid(frontLeaf->TreeValid());
3495
3496                        // replace a link from node's parent
3497                        if (leaf->GetParent())
3498                                leaf->GetParent()->ReplaceChildLink(node, leaf);
3499                        else
3500                                mRoot = leaf;
3501
3502                        ++ collapsed;
3503                        delete interior;
3504
3505                        return leaf;
3506                }
3507        }
3508#endif
3509        return node;
3510}
3511
3512
3513int VspBspTree::CollapseTree()
3514{
3515        int collapsed = 0;
3516        //TODO
3517#if HAS_TO_BE_REDONE
3518        (void)CollapseTree(mRoot, collapsed);
3519
3520        // revalidate leaves
3521        RepairViewCellsLeafLists();
3522#endif
3523        return collapsed;
3524}
3525
3526
3527void VspBspTree::RepairViewCellsLeafLists()
3528{
3529// TODO
3530#if HAS_TO_BE_REDONE
3531        // list not valid anymore => clear
3532        stack<BspNode *> nodeStack;
3533        nodeStack.push(mRoot);
3534
3535        ViewCell::NewMail();
3536
3537        while (!nodeStack.empty())
3538        {
3539                BspNode *node = nodeStack.top();
3540                nodeStack.pop();
3541
3542                if (node->IsLeaf())
3543                {
3544                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3545
3546                        BspViewCell *viewCell = leaf->GetViewCell();
3547
3548                        if (!viewCell->Mailed())
3549                        {
3550                                viewCell->mLeaves.clear();
3551                                viewCell->Mail();
3552                        }
3553       
3554                        viewCell->mLeaves.push_back(leaf);
3555
3556                }
3557                else
3558                {
3559                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3560
3561                        nodeStack.push(interior->GetFront());
3562                        nodeStack.push(interior->GetBack());
3563                }
3564        }
3565// TODO
3566#endif
3567}
3568
3569
3570int VspBspTree::CastBeam(Beam &beam)
3571{
3572    stack<bspNodePair> nodeStack;
3573        BspNodeGeometry *rgeom = new BspNodeGeometry();
3574        ConstructGeometry(mRoot, *rgeom);
3575
3576        nodeStack.push(bspNodePair(mRoot, rgeom));
3577 
3578        ViewCell::NewMail();
3579
3580        while (!nodeStack.empty())
3581        {
3582                BspNode *node = nodeStack.top().first;
3583                BspNodeGeometry *geom = nodeStack.top().second;
3584                nodeStack.pop();
3585               
3586                AxisAlignedBox3 box;
3587                geom->GetBoundingBox(box);
3588
3589                const int side = beam.ComputeIntersection(box);
3590               
3591                switch (side)
3592                {
3593                case -1:
3594                        CollectViewCells(node, true, beam.mViewCells, true);
3595                        break;
3596                case 0:
3597                       
3598                        if (node->IsLeaf())
3599                        {
3600                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3601                       
3602                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
3603                                {
3604                                        leaf->GetViewCell()->Mail();
3605                                        beam.mViewCells.push_back(leaf->GetViewCell());
3606                                }
3607                        }
3608                        else
3609                        {
3610                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3611                       
3612                                BspNode *first = interior->GetFront();
3613                                BspNode *second = interior->GetBack();
3614           
3615                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3616                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3617
3618                                geom->SplitGeometry(*firstGeom,
3619                                                                        *secondGeom,
3620                                                                        interior->GetPlane(),
3621                                                                        mBox,
3622                                                                        //0.0000001f);
3623                                                                        mEpsilon);
3624
3625                                // decide on the order of the nodes
3626                                if (DotProd(beam.mPlanes[0].mNormal,
3627                                        interior->GetPlane().mNormal) > 0)
3628                                {
3629                                        swap(first, second);
3630                                        swap(firstGeom, secondGeom);
3631                                }
3632
3633                                nodeStack.push(bspNodePair(first, firstGeom));
3634                                nodeStack.push(bspNodePair(second, secondGeom));
3635                        }
3636                       
3637                        break;
3638                default:
3639                        // default: cull
3640                        break;
3641                }
3642               
3643                DEL_PTR(geom);
3644               
3645        }
3646
3647        return (int)beam.mViewCells.size();
3648}
3649
3650
3651void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
3652{
3653        mViewCellsManager = vcm;
3654}
3655
3656
3657int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3658                                                                           vector<MergeCandidate> &candidates)
3659{
3660        BspLeaf::NewMail();
3661       
3662        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3663
3664        int numCandidates = 0;
3665
3666        // find merge candidates and push them into queue
3667        for (it = leaves.begin(); it != it_end; ++ it)
3668        {
3669                BspLeaf *leaf = *it;
3670               
3671                // the same leaves must not be part of two merge candidates
3672                leaf->Mail();
3673               
3674                vector<BspLeaf *> neighbors;
3675               
3676                // appoximate neighbor search has slightl relaxed constraints
3677                if (1)
3678                        FindNeighbors(leaf, neighbors, true);
3679                else
3680                        FindApproximateNeighbors(leaf, neighbors, true);
3681
3682                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3683
3684                // TODO: test if at least one ray goes from one leaf to the other
3685                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
3686                {
3687                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
3688                        {
3689                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
3690
3691                                if (!leaf->GetViewCell()->GetPvs().Empty() ||
3692                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
3693                    leaf->IsSibling(*nit))
3694                                {
3695                                        candidates.push_back(mc);
3696                                }
3697
3698                                ++ numCandidates;
3699                                if ((numCandidates % 1000) == 0)
3700                                {
3701                                        cout << "collected " << numCandidates << " merge candidates" << endl;
3702                                }
3703                        }
3704                }
3705        }
3706
3707        Debug << "merge queue: " << (int)candidates.size() << endl;
3708        Debug << "leaves in queue: " << numCandidates << endl;
3709       
3710
3711        return (int)leaves.size();
3712}
3713
3714
3715int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3716                                                                           vector<MergeCandidate> &candidates)
3717{
3718        ViewCell::NewMail();
3719        long startTime = GetTime();
3720       
3721        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
3722        ViewCellContainer::const_iterator iit;
3723
3724        int numLeaves = 0;
3725       
3726        BspLeaf::NewMail();
3727
3728        for (int i = 0; i < (int)rays.size(); ++ i)
3729        { 
3730                VssRay *ray = rays[i];
3731       
3732                // traverse leaves stored in the rays and compare and
3733                // merge consecutive leaves (i.e., the neighbors in the tree)
3734                if (ray->mViewCells.size() < 2)
3735                        continue;
3736//TODO viewcellhierarchy
3737                iit = ray->mViewCells.begin();
3738                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
3739                BspLeaf *leaf = bspVc->mLeaf;
3740               
3741                // traverse intersections
3742                // consecutive leaves are neighbors => add them to queue
3743                for (; iit != ray->mViewCells.end(); ++ iit)
3744                {
3745                        // next pair
3746                        BspLeaf *prevLeaf = leaf;
3747                        bspVc = dynamic_cast<BspViewCell *>(*iit);
3748            leaf = bspVc->mLeaf;
3749
3750                        // view space not valid or same view cell
3751                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3752                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
3753                                continue;
3754
3755                vector<BspLeaf *> &neighbors = neighborMap[leaf];
3756                       
3757                        bool found = false;
3758
3759                        // both leaves inserted in queue already =>
3760                        // look if double pair already exists
3761                        if (leaf->Mailed() && prevLeaf->Mailed())
3762                        {
3763                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3764                               
3765                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3766                                        if (*it == prevLeaf)
3767                                                found = true; // already in queue
3768                        }
3769               
3770                        if (!found)
3771                        {
3772                                // this pair is not in map yet
3773                                // => insert into the neighbor map and the queue
3774                                neighbors.push_back(prevLeaf);
3775                                neighborMap[prevLeaf].push_back(leaf);
3776
3777                                leaf->Mail();
3778                                prevLeaf->Mail();
3779               
3780                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3781                               
3782                                candidates.push_back(mc);
3783
3784                                if (((int)candidates.size() % 1000) == 0)
3785                                {
3786                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
3787                                }
3788                        }
3789        }
3790        }
3791
3792        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
3793        Debug << "merge queue: " << (int)candidates.size() << endl;
3794        Debug << "leaves in queue: " << numLeaves << endl;
3795
3796
3797        //-- collect the leaves which haven't been found by ray casting
3798        if (0)
3799        {
3800                cout << "finding additional merge candidates using geometry" << endl;
3801                vector<BspLeaf *> leaves;
3802                CollectLeaves(leaves, true);
3803                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
3804                CollectMergeCandidates(leaves, candidates);
3805        }
3806
3807        return numLeaves;
3808}
3809
3810
3811
3812
3813ViewCell *VspBspTree::GetViewCell(const Vector3 &point, const bool active)
3814{
3815        if (mRoot == NULL)
3816                return NULL;
3817
3818        stack<BspNode *> nodeStack;
3819        nodeStack.push(mRoot);
3820 
3821        ViewCellLeaf *viewcell = NULL;
3822 
3823        while (!nodeStack.empty()) 
3824        {
3825                BspNode *node = nodeStack.top();
3826                nodeStack.pop();
3827       
3828                if (node->IsLeaf())
3829                {
3830                        viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
3831                        break;
3832                }
3833                else   
3834                {       
3835                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3836       
3837                        // random decision
3838                        if (interior->GetPlane().Side(point) < 0)
3839                                nodeStack.push(interior->GetBack());
3840                        else
3841                                nodeStack.push(interior->GetFront());
3842                }
3843        }
3844 
3845        if (active)
3846                return mViewCellsTree->GetActiveViewCell(viewcell);
3847        else
3848                return viewcell;
3849}
3850
3851
3852bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3853{
3854        BspNode *node = mRoot;
3855
3856        while (1)
3857        {
3858                // early exit
3859                if (node->TreeValid())
3860                        return true;
3861
3862                if (node->IsLeaf())
3863                        return false;
3864                       
3865                BspInterior *in = dynamic_cast<BspInterior *>(node);
3866                                       
3867                if (in->GetPlane().Side(viewPoint) <= 0)
3868                {
3869                        node = in->GetBack();
3870                }
3871                else
3872                {
3873                        node = in->GetFront();
3874                }
3875        }
3876
3877        // should never come here
3878        return false;
3879}
3880
3881
3882void VspBspTree::PropagateUpValidity(BspNode *node)
3883{
3884        const bool isValid = node->TreeValid();
3885
3886        // propagative up invalid flag until only invalid nodes exist over this node
3887        if (!isValid)
3888        {
3889                while (!node->IsRoot() && node->GetParent()->TreeValid())
3890                {
3891                        node = node->GetParent();
3892                        node->SetTreeValid(false);
3893                }
3894        }
3895        else
3896        {
3897                // propagative up valid flag until one of the subtrees is invalid
3898                while (!node->IsRoot() && !node->TreeValid())
3899                {
3900            node = node->GetParent();
3901                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3902                       
3903                        // the parent is valid iff both leaves are valid
3904                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3905                                                           interior->GetFront()->TreeValid());
3906                }
3907        }
3908}
3909
3910#if ZIPPED_VIEWCELLS
3911bool VspBspTree::Export(ogzstream &stream)
3912#else
3913bool VspBspTree::Export(ofstream &stream)
3914#endif
3915{
3916        ExportNode(mRoot, stream);
3917
3918        return true;
3919}
3920
3921#if ZIPPED_VIEWCELLS
3922void VspBspTree::ExportNode(BspNode *node, ogzstream &stream)
3923#else
3924void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
3925#endif
3926{
3927        if (node->IsLeaf())
3928        {
3929                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3930                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3931
3932                int id = -1;
3933                if (viewCell != mOutOfBoundsCell)
3934                        id = viewCell->GetId();
3935
3936                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3937        }
3938        else
3939        {
3940                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3941       
3942                Plane3 plane = interior->GetPlane();
3943                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3944                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3945                           << plane.mD << "\">" << endl;
3946
3947                ExportNode(interior->GetBack(), stream);
3948                ExportNode(interior->GetFront(), stream);
3949
3950                stream << "</Interior>" << endl;
3951        }
3952}
3953
3954}
Note: See TracBrowser for help on using the repository browser.