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

Revision 1145, 98.3 KB checked in by mattausch, 18 years ago (diff)

vsposp debug version

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