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

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