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

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