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

Revision 1551, 98.4 KB checked in by mattausch, 18 years ago (diff)

updated view cells loading. probably no optimal for performance

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