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

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