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

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