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

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