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

Revision 837, 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.0f;
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 max cost ratio is exceeded, take split along longest axis instead
1433        const float maxCostRatioForArbitraryAxis = 0.9f;
1434
1435        if (mUseDrivingAxisForMaxCost)
1436                bestAxis = box.Size().DrivingAxis();
1437        else
1438                bestAxis = -1;
1439
1440        // mximum cost ratio for axis to be valid:
1441        // if exceeded, spatial mid split is used instead
1442        //const maxCostRatioForHeur = 0.99f;
1443
1444
1445    const bool useSpecialAxis =
1446                mOnlyDrivingAxis || mUseRandomAxis || 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
1479
1480                        // also use median split if cost ratio very low as
1481                        // there are not enough visibility cues
1482                        //if (!mUseCostHeuristics || (nCostRatio[axis] > maxCostRatioForHeur))
1483                        else
1484                        {
1485
1486                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1487                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
1488
1489                                // allows faster split because we have axis aligned kd tree boxes
1490                                if (isKdNode)
1491                                {
1492                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
1493                                                                                                                                box,
1494                                                                                                                                axis,
1495                                                                                                                                nPosition[axis],
1496                                                                                                                                nProbFront[axis],
1497                                                                                                                                nProbBack[axis]);
1498                                       
1499                                        Vector3 pos;
1500                                       
1501                                        // create back geometry from box
1502                                        // NOTE: the geometry is saved when possible
1503                                        pos = box.Max(); pos[axis] = nPosition[axis];
1504                                        AxisAlignedBox3 bBox(box.Min(), pos);
1505                                        PolygonContainer fPolys;
1506                                        bBox.ExtractPolys(fPolys);
1507
1508                                        nBackGeom[axis] = new BspNodeGeometry(fPolys);
1509       
1510                                        //-- create front geometry from box
1511                                        pos = box.Min(); pos[axis] = nPosition[axis];
1512                                        AxisAlignedBox3 fBox(pos, box.Max());
1513
1514                                        PolygonContainer bPolys;
1515                                        fBox.ExtractPolys(bPolys);
1516                                        nFrontGeom[axis] = new BspNodeGeometry(bPolys);
1517                                }
1518                                else
1519                                {
1520                                        nFrontGeom[axis] = new BspNodeGeometry();
1521                                        nBackGeom[axis] = new BspNodeGeometry();
1522
1523                                        nCostRatio[axis] =
1524                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1525                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1526                                                                                   nProbFront[axis], nProbBack[axis]);
1527                                }
1528                        }
1529                                               
1530
1531                        if (!mUseDrivingAxisForMaxCost)
1532                        {
1533                                if (bestAxis == -1)
1534                                {
1535                                        bestAxis = axis;
1536                                }
1537                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
1538                                {
1539                                        bestAxis = axis;
1540                                }
1541                        }
1542                        else
1543                        {
1544                                 // NOTE: takes longest axis split if cost ratio exceeds threshold
1545                                if (nCostRatio[axis] < min(maxCostRatioForArbitraryAxis, nCostRatio[bestAxis]))
1546                                {
1547                                        bestAxis = axis;
1548                                }
1549                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
1550                                        Debug << "taking split along longest axis (" << bestAxis << ") instead of  (" << axis << ")" << endl;
1551                               
1552                        }
1553                }
1554        }
1555
1556        //-- assign values
1557        axis = bestAxis;
1558        pFront = nProbFront[bestAxis];
1559        pBack = nProbBack[bestAxis];
1560
1561        // assign best split nodes geometry
1562        *frontGeom = nFrontGeom[bestAxis];
1563        *backGeom = nBackGeom[bestAxis];
1564
1565        // and delete other geometry
1566        DEL_PTR(nFrontGeom[(bestAxis + 1) % 3]);
1567        DEL_PTR(nBackGeom[(bestAxis + 2) % 3]);
1568
1569        //-- split plane
1570    Vector3 normal(0,0,0); normal[bestAxis] = 1;
1571        plane = Plane3(normal, nPosition[bestAxis]);
1572
1573        //Debug << "best axis: " << bestAxis << " pos " << nPosition[bestAxis] << endl;
1574        //Debug << "!!!!!!!!!!!!!!" << endl;
1575        return nCostRatio[bestAxis];
1576}
1577
1578
1579bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1580                                                         BspLeaf *leaf,
1581                                                         VspBspTraversalData &data,                                                     
1582                                                         VspBspTraversalData &frontData,
1583                                                         VspBspTraversalData &backData,
1584                                                         int &splitAxis)
1585{
1586        // HACK matt: subdivide regularily to certain depth
1587        if (data.mDepth < 0)   
1588        {
1589                cout << "d: " << data.mDepth << endl;
1590                // return axis aligned split
1591                AxisAlignedBox3 box;
1592                box.Initialize();
1593       
1594                // create bounding box of region
1595                data.mGeometry->GetBoundingBox(box);
1596       
1597                const int axis = box.Size().DrivingAxis();
1598                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1599
1600                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1601                bestPlane = Plane3(norm, position);
1602                splitAxis = axis;
1603                return true;
1604        }
1605
1606        // simplest strategy: just take next polygon
1607        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1608        {
1609        if (!data.mPolygons->empty())
1610                {
1611                        const int randIdx =
1612                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1613                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
1614
1615                        bestPlane = nextPoly->GetSupportingPlane();
1616                        return true;
1617                }
1618        }
1619
1620        //-- use heuristics to find appropriate plane
1621
1622        // intermediate plane
1623        Plane3 plane;
1624        float lowestCost = MAX_FLOAT;
1625       
1626        // decides if the first few splits should be only axisAligned
1627        const bool onlyAxisAligned  =
1628                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1629                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1630                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1631       
1632        const int limit = onlyAxisAligned ? 0 :
1633                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1634
1635        float candidateCost;
1636
1637        int maxIdx = (int)data.mPolygons->size();
1638
1639        for (int i = 0; i < limit; ++ i)
1640        {
1641                // the already taken candidates are stored behind maxIdx
1642                // => assure that no index is taken twice
1643                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1644                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1645
1646                // swap candidate to the end to avoid testing same plane
1647                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1648                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1649
1650                // evaluate current candidate
1651                BspNodeGeometry fGeom, bGeom;
1652                float fArea, bArea;
1653                plane = poly->GetSupportingPlane();
1654                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
1655               
1656                if (candidateCost < lowestCost)
1657                {
1658                        bestPlane = plane;
1659                        lowestCost = candidateCost;
1660                }
1661        }
1662
1663        //-- evaluate axis aligned splits
1664        int axis;
1665        BspNodeGeometry *fGeom, *bGeom;
1666        float pFront, pBack;
1667
1668        candidateCost = 99999999.0f;
1669
1670        // option: axis aligned split only if no polygon available
1671        if (!mUsePolygonSplitIfAvailable || data.mPolygons->empty())
1672        {
1673                candidateCost = SelectAxisAlignedPlane(plane,
1674                                                                                           data,
1675                                                                                           axis,
1676                                                                                           &fGeom,
1677                                                                                           &bGeom,
1678                                                                                           pFront,
1679                                                                                           pBack,
1680                                                                                           data.mIsKdNode);     
1681        }
1682
1683        splitAxis = 3;
1684
1685        if (candidateCost < lowestCost)
1686        {       
1687                bestPlane = plane;
1688                lowestCost = candidateCost;
1689                splitAxis = axis;
1690       
1691                // assign already computed values
1692                // we can do this because we always save the
1693                // computed values from the axis aligned splits         
1694
1695                if (fGeom && bGeom)
1696                {
1697                        frontData.mGeometry = fGeom;
1698                        backData.mGeometry = bGeom;
1699       
1700                        frontData.mProbability = pFront;
1701                        backData.mProbability = pBack;
1702                }
1703        }
1704        else
1705        {
1706                DEL_PTR(fGeom);
1707                DEL_PTR(bGeom);
1708        }
1709   
1710#ifdef _DEBUG
1711        Debug << "plane lowest cost: " << lowestCost << endl;
1712#endif
1713
1714        // exeeded relative max cost ratio
1715        if (lowestCost > mTermMaxCostRatio)
1716        {
1717                return false;
1718        }
1719
1720        return true;
1721}
1722
1723
1724Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
1725{
1726        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1727
1728        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1729        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1730
1731        const Vector3 pt = (maxPt + minPt) * 0.5;
1732        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1733
1734        return Plane3(normal, pt);
1735}
1736
1737
1738Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
1739{
1740        Vector3 pt[3];
1741
1742        int idx[3];
1743        int cmaxT = 0;
1744        int cminT = 0;
1745        bool chooseMin = false;
1746
1747        for (int j = 0; j < 3; ++ j)
1748        {
1749                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1750
1751                if (idx[j] >= (int)rays.size())
1752                {
1753                        idx[j] -= (int)rays.size();
1754
1755                        chooseMin = (cminT < 2);
1756                }
1757                else
1758                        chooseMin = (cmaxT < 2);
1759
1760                RayInfo rayInf = rays[idx[j]];
1761                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1762        }
1763
1764        return Plane3(pt[0], pt[1], pt[2]);
1765}
1766
1767
1768Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1769{
1770        Vector3 pt[3];
1771
1772        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1773        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1774
1775        // check if rays different
1776        if (idx1 == idx2)
1777                idx2 = (idx2 + 1) % (int)rays.size();
1778
1779        const RayInfo ray1 = rays[idx1];
1780        const RayInfo ray2 = rays[idx2];
1781
1782        // normal vector of the plane parallel to both lines
1783        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1784
1785        // vector from line 1 to line 2
1786        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1787
1788        // project vector on normal to get distance
1789        const float dist = DotProd(vd, norm);
1790
1791        // point on plane lies halfway between the two planes
1792        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1793
1794        return Plane3(norm, planePt);
1795}
1796
1797
1798inline void VspBspTree::GenerateUniqueIdsForPvs()
1799{
1800        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1801        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1802        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
1803}
1804
1805
1806float VspBspTree::EvalRenderCostDecrease(const Plane3 &candidatePlane,
1807                                                                                 const VspBspTraversalData &data) const
1808{
1809        float pvsFront = 0;
1810        float pvsBack = 0;
1811        float totalPvs = 0;
1812
1813        // probability that view point lies in back / front node
1814        float pOverall = data.mProbability;
1815        float pFront = 0;
1816        float pBack = 0;
1817
1818
1819        // create unique ids for pvs heuristics
1820        GenerateUniqueIdsForPvs();
1821       
1822        for (int i = 0; i < data.mRays->size(); ++ i)
1823        {
1824                RayInfo rayInf = (*data.mRays)[i];
1825
1826                float t;
1827                VssRay *ray = rayInf.mRay;
1828                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1829
1830                // find front and back pvs for origing and termination object
1831                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1832                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1833        }
1834
1835
1836        BspNodeGeometry geomFront;
1837        BspNodeGeometry geomBack;
1838
1839        // construct child geometry with regard to the candidate split plane
1840        data.mGeometry->SplitGeometry(geomFront,
1841                                                                  geomBack,
1842                                                                  candidatePlane,
1843                                                                  mBox,
1844                                                                  //0.0f);
1845                                                                  mEpsilon);
1846
1847        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1848        {
1849                pFront = geomFront.GetVolume();
1850                pBack = pOverall - pFront;
1851
1852                // something is wrong with the volume
1853                if ((pFront < 0.0) || (pBack < 0.0))
1854                {
1855                        Debug << "ERROR in volume:\n"
1856                                  << "volume f :" << pFront << " b: " << pBack << " p: " << pOverall
1857                                  << ", real volume f: " << pFront << " b: " << geomBack.GetVolume()
1858                                  << ", #polygons f: " << geomFront.Size() << " b: " << geomBack.Size() << " p: " << data.mGeometry->Size() << endl;
1859                }
1860        }
1861        else
1862        {
1863                pFront = geomFront.GetArea();
1864                pBack = geomBack.GetArea();
1865        }
1866       
1867
1868        // -- pvs rendering heuristics
1869        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1870        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1871
1872        // only render cost heuristics or combined with standard deviation
1873        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1874    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1875        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1876                       
1877        const float oldRenderCost = pOverall * penaltyOld;
1878        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1879
1880        //Debug << "decrease: " << oldRenderCost - newRenderCost << endl;
1881        const float renderCostDecrease = (oldRenderCost - newRenderCost) / mBox.GetVolume();
1882       
1883
1884#if 1
1885        // take render cost of node into account
1886        const float normalizedOldRenderCost = oldRenderCost / mBox.GetVolume();
1887        //Debug << "rendercostdecr: " << 0.99f * renderCostDecrease << " old render cost: " << 0.01f * normalizedOldRenderCost << endl;
1888        //return 0.5f * renderCostDecrease + 0.5f * normalizedOldRenderCost;
1889        return 0.99f * renderCostDecrease + 0.01f * normalizedOldRenderCost;
1890#else
1891        return renderCostDecrease;
1892#endif
1893}
1894
1895
1896float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1897                                                                         const VspBspTraversalData &data,
1898                                                                         BspNodeGeometry &geomFront,
1899                                                                         BspNodeGeometry &geomBack,
1900                                                                         float &pFront,
1901                                                                         float &pBack) const
1902{
1903        float cost = 0;
1904
1905        float totalPvs = 0;
1906        float pvsFront = 0;
1907        float pvsBack = 0;
1908       
1909        // probability that view point lies in back / front node
1910        float pOverall = 0;
1911        pFront = 0;
1912        pBack = 0;
1913
1914
1915        int limit;
1916        bool useRand;
1917
1918        // create unique ids for pvs heuristics
1919        GenerateUniqueIdsForPvs();
1920
1921        // choose test rays randomly if too much
1922        if ((int)data.mRays->size() > mMaxTests)
1923        {
1924                useRand = true;
1925                limit = mMaxTests;
1926        }
1927        else
1928        {
1929                useRand = false;
1930                limit = (int)data.mRays->size();
1931        }
1932       
1933        for (int i = 0; i < limit; ++ i)
1934        {
1935                const int testIdx = useRand ?
1936                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
1937                RayInfo rayInf = (*data.mRays)[testIdx];
1938
1939                float t;
1940                VssRay *ray = rayInf.mRay;
1941                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1942
1943                // find front and back pvs for origing and termination object
1944                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1945                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1946        }
1947
1948        // construct child geometry with regard to the candidate split plane
1949        bool splitSuccessFull = data.mGeometry->SplitGeometry(geomFront,
1950                                                                                                                  geomBack,
1951                                                                                                                  candidatePlane,
1952                                                                                                                  mBox,
1953                                                                                                                  //0.0f);
1954                                                                                                                  mEpsilon);
1955
1956        pOverall = data.mProbability;
1957
1958        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1959        {
1960                pFront = geomFront.GetVolume();
1961                pBack = pOverall - pFront;
1962               
1963                // HACK: precision issues possible for unbalanced split => don't take this split!
1964                if (1 &&
1965                        (!splitSuccessFull || (pFront <= 0) || (pBack <= 0) ||
1966                        !geomFront.Valid() || !geomBack.Valid()))
1967                {
1968                        //Debug << "error f: " << pFront << " b: " << pBack << endl;
1969                        // high penalty for this split
1970                        return 99999.9f;
1971                }
1972        }
1973        else
1974        {
1975                pFront = geomFront.GetArea();
1976                pBack = geomBack.GetArea();
1977        }
1978       
1979
1980        // -- pvs rendering heuristics
1981        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1982        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1983
1984        // only render cost heuristics or combined with standard deviation
1985        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
1986    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
1987        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
1988                       
1989        const float oldRenderCost = pOverall * penaltyOld;
1990        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1991
1992        float oldCost, newCost;
1993
1994        // only render cost
1995        if (1)
1996        {
1997                oldCost = oldRenderCost;
1998                newCost = newRenderCost;
1999        }
2000        else // also considering standard deviation
2001        {
2002                // standard deviation is difference of back and front pvs
2003                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
2004
2005                const float newDeviation = 0.5f *
2006                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
2007
2008                const float oldDeviation = penaltyOld;
2009
2010                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
2011                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
2012        }
2013
2014        cost += mPvsFactor * newCost / (oldCost + Limits::Small);
2015               
2016
2017#ifdef _DEBUG
2018        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
2019                  << " frontpvs: " << pvsFront << " pFront: " << pFront
2020                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
2021        Debug << "cost: " << cost << endl;
2022#endif
2023
2024        return cost;
2025}
2026
2027
2028int VspBspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2029                                                                                ViewCellContainer &viewCells) const
2030{
2031        stack<bspNodePair> nodeStack;
2032        BspNodeGeometry *rgeom = new BspNodeGeometry();
2033
2034        ConstructGeometry(mRoot, *rgeom);
2035
2036        nodeStack.push(bspNodePair(mRoot, rgeom));
2037 
2038        ViewCell::NewMail();
2039
2040        while (!nodeStack.empty())
2041        {
2042                BspNode *node = nodeStack.top().first;
2043                BspNodeGeometry *geom = nodeStack.top().second;
2044                nodeStack.pop();
2045
2046                const int side = geom->ComputeIntersection(box);
2047               
2048                switch (side)
2049                {
2050                case -1:
2051                        // node geometry is contained in box
2052                        CollectViewCells(node, true, viewCells, true);
2053                        break;
2054
2055                case 0:
2056                        if (node->IsLeaf())
2057                        {
2058                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2059                       
2060                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2061                                {
2062                                        leaf->GetViewCell()->Mail();
2063                                        viewCells.push_back(leaf->GetViewCell());
2064                                }
2065                        }
2066                        else
2067                        {
2068                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2069                       
2070                                BspNode *first = interior->GetFront();
2071                                BspNode *second = interior->GetBack();
2072           
2073                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2074                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2075
2076                                geom->SplitGeometry(*firstGeom,
2077                                                                        *secondGeom,
2078                                                                        interior->GetPlane(),
2079                                                                        mBox,
2080                                                                        //0.0000001f);
2081                                                                        mEpsilon);
2082
2083                                nodeStack.push(bspNodePair(first, firstGeom));
2084                                nodeStack.push(bspNodePair(second, secondGeom));
2085                        }
2086                       
2087                        break;
2088                default:
2089                        // default: cull
2090                        break;
2091                }
2092               
2093                DEL_PTR(geom);
2094               
2095        }
2096
2097        return (int)viewCells.size();
2098}
2099
2100
2101float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
2102                                                                                   const AxisAlignedBox3 &box,
2103                                                                                   const int axis,
2104                                                                                   const float &position,                                                                                 
2105                                                                                   float &pFront,
2106                                                                                   float &pBack) const
2107{
2108        float pvsTotal = 0;
2109        float pvsFront = 0;
2110        float pvsBack = 0;
2111       
2112        // create unique ids for pvs heuristics
2113        GenerateUniqueIdsForPvs();
2114
2115        const int pvsSize = data.mPvs;
2116
2117        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
2118
2119        // this is the main ray classification loop!
2120        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
2121        {
2122                //if (!(*rit).mRay->IsActive()) continue;
2123
2124                // determine the side of this ray with respect to the plane
2125                float t;
2126                const int side = (*rit).ComputeRayIntersection(axis, position, t);
2127       
2128                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
2129                AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
2130        }
2131
2132        //-- pvs heuristics
2133        float pOverall;
2134
2135        //-- compute heurstics
2136        //-- we take simplified computation for mid split
2137               
2138        pOverall = data.mProbability;
2139
2140        if (!mUseAreaForPvs)
2141        {   // volume
2142                pBack = pFront = pOverall * 0.5f;
2143               
2144#if 0
2145                // box length substitute for probability
2146                const float minBox = box.Min(axis);
2147                const float maxBox = box.Max(axis);
2148
2149                pBack = position - minBox;
2150                pFront = maxBox - position;
2151                pOverall = maxBox - minBox;
2152#endif
2153        }
2154        else //-- area substitute for probability
2155        {
2156                const int axis2 = (axis + 1) % 3;
2157                const int axis3 = (axis + 2) % 3;
2158
2159                const float faceArea =
2160                        (box.Max(axis2) - box.Min(axis2)) *
2161                        (box.Max(axis3) - box.Min(axis3));
2162
2163                pBack = pFront = pOverall * 0.5f + faceArea;
2164        }
2165
2166#ifdef _DEBUG
2167        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
2168        Debug << pFront << " " << pBack << " " << pOverall << endl;
2169#endif
2170
2171       
2172        const float newCost = pvsBack * pBack + pvsFront * pFront;
2173        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
2174
2175        return  (mCtDivCi + newCost) / oldCost;
2176}
2177
2178
2179void VspBspTree::AddObjToPvs(Intersectable *obj,
2180                                                         const int cf,
2181                                                         float &frontPvs,
2182                                                         float &backPvs,
2183                                                         float &totalPvs) const
2184{
2185        if (!obj)
2186                return;
2187
2188        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
2189
2190        // new object
2191        if ((obj->mMailbox != sFrontId) &&
2192                (obj->mMailbox != sBackId) &&
2193                (obj->mMailbox != sFrontAndBackId))
2194        {
2195                totalPvs += renderCost;
2196        }
2197
2198        // TODO: does this really belong to no pvs?
2199        //if (cf == Ray::COINCIDENT) return;
2200
2201        // object belongs to both PVS
2202        if (cf >= 0)
2203        {
2204                if ((obj->mMailbox != sFrontId) &&
2205                        (obj->mMailbox != sFrontAndBackId))
2206                {
2207                        frontPvs += renderCost;
2208               
2209                        if (obj->mMailbox == sBackId)
2210                                obj->mMailbox = sFrontAndBackId;
2211                        else
2212                                obj->mMailbox = sFrontId;
2213                }
2214        }
2215
2216        if (cf <= 0)
2217        {
2218                if ((obj->mMailbox != sBackId) &&
2219                        (obj->mMailbox != sFrontAndBackId))
2220                {
2221                        backPvs += renderCost;
2222               
2223                        if (obj->mMailbox == sFrontId)
2224                                obj->mMailbox = sFrontAndBackId;
2225                        else
2226                                obj->mMailbox = sBackId;
2227                }
2228        }
2229}
2230
2231
2232void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
2233                                                           const bool onlyUnmailed,
2234                                                           const int maxPvsSize) const
2235{
2236        stack<BspNode *> nodeStack;
2237        nodeStack.push(mRoot);
2238
2239        while (!nodeStack.empty())
2240        {
2241                BspNode *node = nodeStack.top();
2242                nodeStack.pop();
2243               
2244                if (node->IsLeaf())
2245                {
2246                        // test if this leaf is in valid view space
2247                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2248                        if (leaf->TreeValid() &&
2249                                (!onlyUnmailed || !leaf->Mailed()) &&
2250                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
2251                        {
2252                                leaves.push_back(leaf);
2253                        }
2254                }
2255                else
2256                {
2257                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2258
2259                        nodeStack.push(interior->GetBack());
2260                        nodeStack.push(interior->GetFront());
2261                }
2262        }
2263}
2264
2265
2266AxisAlignedBox3 VspBspTree::GetBoundingBox() const
2267{
2268        return mBox;
2269}
2270
2271
2272BspNode *VspBspTree::GetRoot() const
2273{
2274        return mRoot;
2275}
2276
2277
2278void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
2279{
2280        // the node became a leaf -> evaluate stats for leafs
2281        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
2282
2283
2284        if (data.mPvs > mBspStats.maxPvs)
2285        {
2286                mBspStats.maxPvs = data.mPvs;
2287        }
2288
2289        mBspStats.pvs += data.mPvs;
2290
2291        if (data.mDepth < mBspStats.minDepth)
2292        {
2293                mBspStats.minDepth = data.mDepth;
2294        }
2295       
2296        if (data.mDepth >= mTermMaxDepth)
2297        {
2298        ++ mBspStats.maxDepthNodes;
2299                //Debug << "new max depth: " << mBspStats.maxDepthNodes << endl;
2300        }
2301
2302        // accumulate rays to compute rays /  leaf
2303        mBspStats.accumRays += (int)data.mRays->size();
2304
2305        if (data.mPvs < mTermMinPvs)
2306                ++ mBspStats.minPvsNodes;
2307
2308        if ((int)data.mRays->size() < mTermMinRays)
2309                ++ mBspStats.minRaysNodes;
2310
2311        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
2312                ++ mBspStats.maxRayContribNodes;
2313
2314        if (data.mProbability <= mTermMinProbability)
2315                ++ mBspStats.minProbabilityNodes;
2316       
2317        // accumulate depth to compute average depth
2318        mBspStats.accumDepth += data.mDepth;
2319
2320        ++ mCreatedViewCells;
2321
2322#ifdef _DEBUG
2323        Debug << "BSP stats: "
2324                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
2325                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
2326          //              << "Area: " << data.mProbability << " (min: " << mTermMinProbability << "), "
2327                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
2328                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
2329                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
2330#endif
2331}
2332
2333
2334int VspBspTree::CastRay(Ray &ray)
2335{
2336        int hits = 0;
2337
2338        stack<BspRayTraversalData> tQueue;
2339
2340        float maxt, mint;
2341
2342        if (!mBox.GetRaySegment(ray, mint, maxt))
2343                return 0;
2344
2345        Intersectable::NewMail();
2346        ViewCell::NewMail();
2347        Vector3 entp = ray.Extrap(mint);
2348        Vector3 extp = ray.Extrap(maxt);
2349
2350        BspNode *node = mRoot;
2351        BspNode *farChild = NULL;
2352
2353        while (1)
2354        {
2355                if (!node->IsLeaf())
2356                {
2357                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2358
2359                        Plane3 splitPlane = in->GetPlane();
2360                        const int entSide = splitPlane.Side(entp);
2361                        const int extSide = splitPlane.Side(extp);
2362
2363                        if (entSide < 0)
2364                        {
2365                                node = in->GetBack();
2366
2367                                if(extSide <= 0) // plane does not split ray => no far child
2368                                        continue;
2369
2370                                farChild = in->GetFront(); // plane splits ray
2371
2372                        } else if (entSide > 0)
2373                        {
2374                                node = in->GetFront();
2375
2376                                if (extSide >= 0) // plane does not split ray => no far child
2377                                        continue;
2378
2379                                farChild = in->GetBack(); // plane splits ray
2380                        }
2381                        else // ray and plane are coincident
2382                        {
2383                                // WHAT TO DO IN THIS CASE ?
2384                                //break;
2385                                node = in->GetFront();
2386                                continue;
2387                        }
2388
2389                        // push data for far child
2390                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
2391
2392                        // find intersection of ray segment with plane
2393                        float t;
2394                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2395                        maxt *= t;
2396
2397                } else // reached leaf => intersection with view cell
2398                {
2399                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2400
2401                        if (!leaf->GetViewCell()->Mailed())
2402                        {
2403                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2404                                leaf->GetViewCell()->Mail();
2405                                ++ hits;
2406                        }
2407
2408                        //-- fetch the next far child from the stack
2409                        if (tQueue.empty())
2410                                break;
2411
2412                        entp = extp;
2413                        mint = maxt; // NOTE: need this?
2414
2415                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2416                                break;
2417
2418                        BspRayTraversalData &s = tQueue.top();
2419
2420                        node = s.mNode;
2421                        extp = s.mExitPoint;
2422                        maxt = s.mMaxT;
2423
2424                        tQueue.pop();
2425                }
2426        }
2427
2428        return hits;
2429}
2430
2431
2432void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
2433{
2434        ViewCell::NewMail();
2435       
2436        CollectViewCells(mRoot, onlyValid, viewCells, true);
2437}
2438
2439
2440void VspBspTree::CollapseViewCells()
2441{
2442// TODO
2443#if HAS_TO_BE_REDONE
2444        stack<BspNode *> nodeStack;
2445
2446        if (!mRoot)
2447                return;
2448
2449        nodeStack.push(mRoot);
2450       
2451        while (!nodeStack.empty())
2452        {
2453                BspNode *node = nodeStack.top();
2454                nodeStack.pop();
2455               
2456                if (node->IsLeaf())
2457        {
2458                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2459
2460                        if (!viewCell->GetValid())
2461                        {
2462                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2463       
2464                                ViewCellContainer leaves;
2465                                mViewCellsTree->CollectLeaves(viewCell, leaves);
2466
2467                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2468
2469                                for (it = leaves.begin(); it != it_end; ++ it)
2470                                {
2471                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2472                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2473                                        ++ mBspStats.invalidLeaves;
2474                                }
2475
2476                                // add to unbounded view cell
2477                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2478                                DEL_PTR(viewCell);
2479                        }
2480                }
2481                else
2482                {
2483                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2484               
2485                        nodeStack.push(interior->GetFront());
2486                        nodeStack.push(interior->GetBack());
2487                }
2488        }
2489
2490        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2491#endif
2492}
2493
2494
2495void VspBspTree::CollectRays(VssRayContainer &rays)
2496{
2497        vector<BspLeaf *> leaves;
2498
2499        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2500
2501        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2502        {
2503                BspLeaf *leaf = *lit;
2504                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2505
2506                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2507                        rays.push_back(*rit);
2508        }
2509}
2510
2511
2512void VspBspTree::ValidateTree()
2513{
2514        stack<BspNode *> nodeStack;
2515
2516        if (!mRoot)
2517                return;
2518
2519        nodeStack.push(mRoot);
2520       
2521        mBspStats.invalidLeaves = 0;
2522        while (!nodeStack.empty())
2523        {
2524                BspNode *node = nodeStack.top();
2525                nodeStack.pop();
2526               
2527                if (node->IsLeaf())
2528                {
2529                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2530
2531                        if (!leaf->GetViewCell()->GetValid())
2532                                ++ mBspStats.invalidLeaves;
2533
2534                        // validity flags don't match => repair
2535                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2536                        {
2537                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2538                                PropagateUpValidity(leaf);
2539                        }
2540                }
2541                else
2542                {
2543                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2544               
2545                        nodeStack.push(interior->GetFront());
2546                        nodeStack.push(interior->GetBack());
2547                }
2548        }
2549
2550        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2551}
2552
2553
2554
2555void VspBspTree::CollectViewCells(BspNode *root,
2556                                                                  bool onlyValid,
2557                                                                  ViewCellContainer &viewCells,
2558                                                                  bool onlyUnmailed) const
2559{
2560        stack<BspNode *> nodeStack;
2561
2562        if (!root)
2563                return;
2564
2565        nodeStack.push(root);
2566       
2567        while (!nodeStack.empty())
2568        {
2569                BspNode *node = nodeStack.top();
2570                nodeStack.pop();
2571               
2572                if (node->IsLeaf())
2573                {
2574                        if (!onlyValid || node->TreeValid())
2575                        {
2576                                ViewCell *leafVc = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2577
2578                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2579                                               
2580                                if (!onlyUnmailed || !viewCell->Mailed())
2581                                {
2582                                        viewCell->Mail();
2583                                        viewCells.push_back(viewCell);
2584                                }
2585                        }
2586                }
2587                else
2588                {
2589                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2590               
2591                        nodeStack.push(interior->GetFront());
2592                        nodeStack.push(interior->GetBack());
2593                }
2594        }
2595
2596}
2597
2598
2599void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2600{
2601        // preprocess: throw out polygons coincident to the view space box (not needed)
2602        PolygonContainer boxPolys;
2603        mBox.ExtractPolys(boxPolys);
2604        vector<Plane3> boxPlanes;
2605
2606        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2607
2608        // extract planes of box
2609        // TODO: can be done more elegantly than first extracting polygons
2610        // and take their planes
2611        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2612        {
2613                boxPlanes.push_back((*pit)->GetSupportingPlane());
2614        }
2615
2616        pit_end = polys.end();
2617
2618        for (pit = polys.begin(); pit != pit_end; ++ pit)
2619        {
2620                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2621               
2622                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2623                {
2624                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2625
2626                        if (cf == Polygon3::COINCIDENT)
2627                        {
2628                                DEL_PTR(*pit);
2629                                //Debug << "coincident!!" << endl;
2630                        }
2631                }
2632        }
2633
2634        // remove deleted entries
2635        for (int i = 0; i < (int)polys.size(); ++ i)
2636        {
2637                while (!polys[i] && (i < (int)polys.size()))
2638                {
2639                        swap(polys[i], polys.back());
2640                        polys.pop_back();
2641                }
2642        }
2643}
2644
2645
2646float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2647{
2648        float len = 0;
2649
2650        RayInfoContainer::const_iterator it, it_end = rays.end();
2651
2652        for (it = rays.begin(); it != it_end; ++ it)
2653                len += (*it).SegmentLength();
2654
2655        return len;
2656}
2657
2658
2659int VspBspTree::SplitRays(const Plane3 &plane,
2660                                                  RayInfoContainer &rays,
2661                                                  RayInfoContainer &frontRays,
2662                                                  RayInfoContainer &backRays) const
2663{
2664        int splits = 0;
2665
2666        RayInfoContainer::const_iterator it, it_end = rays.end();
2667
2668        for (it = rays.begin(); it != it_end; ++ it)
2669        {
2670                RayInfo bRay = *it;
2671               
2672                VssRay *ray = bRay.mRay;
2673                float t;
2674
2675                // get classification and receive new t
2676                const int cf = bRay.ComputeRayIntersection(plane, t);
2677
2678                switch (cf)
2679                {
2680                case -1:
2681                        backRays.push_back(bRay);
2682                        break;
2683                case 1:
2684                        frontRays.push_back(bRay);
2685                        break;
2686                case 0:
2687                        {
2688                                //-- split ray
2689                                //   test if start point behind or in front of plane
2690                                const int side = plane.Side(bRay.ExtrapOrigin());
2691
2692                                if (side <= 0)
2693                                {
2694                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2695                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2696                                }
2697                                else
2698                                {
2699                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2700                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2701                                }
2702                        }
2703                        break;
2704                default:
2705                        Debug << "Should not come here" << endl;
2706                        break;
2707                }
2708        }
2709
2710        return splits;
2711}
2712
2713
2714void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2715{
2716        BspNode *lastNode;
2717
2718        do
2719        {
2720                lastNode = n;
2721
2722                // want to get planes defining geometry of this node => don't take
2723                // split plane of node itself
2724                n = n->GetParent();
2725
2726                if (n)
2727                {
2728                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2729                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2730
2731            if (interior->GetBack() != lastNode)
2732                                halfSpace.ReverseOrientation();
2733
2734                        halfSpaces.push_back(halfSpace);
2735                }
2736        }
2737        while (n);
2738}
2739
2740
2741void VspBspTree::ConstructGeometry(BspNode *n,
2742                                                                   BspNodeGeometry &geom) const
2743{
2744        vector<Plane3> halfSpaces;
2745        ExtractHalfSpaces(n, halfSpaces);
2746
2747        PolygonContainer candidatePolys;
2748        vector<Plane3> candidatePlanes;
2749
2750        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2751
2752        // bounded planes are added to the polygons
2753        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
2754        {
2755                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
2756
2757                if (p->Valid(mEpsilon))
2758                {
2759                        candidatePolys.push_back(p);
2760                        candidatePlanes.push_back(*pit);
2761                }
2762        }
2763
2764        // add faces of bounding box (also could be faces of the cell)
2765        for (int i = 0; i < 6; ++ i)
2766        {
2767                VertexContainer vertices;
2768
2769                for (int j = 0; j < 4; ++ j)
2770                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2771
2772                Polygon3 *poly = new Polygon3(vertices);
2773
2774                candidatePolys.push_back(poly);
2775                candidatePlanes.push_back(poly->GetSupportingPlane());
2776        }
2777
2778        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2779        {
2780                // polygon is split by all other planes
2781                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2782                {
2783                        if (i == j) // polygon and plane are coincident
2784                                continue;
2785
2786                        VertexContainer splitPts;
2787                        Polygon3 *frontPoly, *backPoly;
2788
2789                        const int cf =
2790                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2791                                                                                                 mEpsilon);
2792
2793                        switch (cf)
2794                        {
2795                                case Polygon3::SPLIT:
2796                                        frontPoly = new Polygon3();
2797                                        backPoly = new Polygon3();
2798
2799                                        candidatePolys[i]->Split(halfSpaces[j],
2800                                                                                         *frontPoly,
2801                                                                                         *backPoly,
2802                                                                                         mEpsilon);
2803
2804                                        DEL_PTR(candidatePolys[i]);
2805
2806                                        if (backPoly->Valid(mEpsilon))
2807                                                candidatePolys[i] = backPoly;
2808                                        else
2809                                                DEL_PTR(backPoly);
2810
2811                                        // outside, don't need this
2812                                        DEL_PTR(frontPoly);
2813                                        break;
2814                                // polygon outside of halfspace
2815                                case Polygon3::FRONT_SIDE:
2816                                        DEL_PTR(candidatePolys[i]);
2817                                        break;
2818                                // just take polygon as it is
2819                                case Polygon3::BACK_SIDE:
2820                                case Polygon3::COINCIDENT:
2821                                default:
2822                                        break;
2823                        }
2824                }
2825
2826                if (candidatePolys[i])
2827                {
2828                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2829                        //      geom.mPolys.push_back(candidates[i]);
2830                }
2831        }
2832}
2833
2834
2835void VspBspTree::ConstructGeometry(ViewCell *vc,
2836                                                                   BspNodeGeometry &vcGeom) const
2837{
2838        ViewCellContainer leaves;
2839       
2840        mViewCellsTree->CollectLeaves(vc, leaves);
2841
2842        ViewCellContainer::const_iterator it, it_end = leaves.end();
2843
2844        for (it = leaves.begin(); it != it_end; ++ it)
2845        {
2846                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2847               
2848                ConstructGeometry(l, vcGeom);
2849        }
2850}
2851
2852
2853int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2854                                                          const bool onlyUnmailed) const
2855{
2856        stack<bspNodePair> nodeStack;
2857       
2858        BspNodeGeometry nodeGeom;
2859        ConstructGeometry(n, nodeGeom);
2860//      const float eps = 0.5f;
2861        const float eps = 0.01f;
2862        // split planes from the root to this node
2863        // needed to verify that we found neighbor leaf
2864        // TODO: really needed?
2865        vector<Plane3> halfSpaces;
2866        ExtractHalfSpaces(n, halfSpaces);
2867
2868
2869        BspNodeGeometry *rgeom = new BspNodeGeometry();
2870        ConstructGeometry(mRoot, *rgeom);
2871
2872        nodeStack.push(bspNodePair(mRoot, rgeom));
2873
2874        while (!nodeStack.empty())
2875        {
2876                BspNode *node = nodeStack.top().first;
2877                BspNodeGeometry *geom = nodeStack.top().second;
2878       
2879                nodeStack.pop();
2880
2881                if (node->IsLeaf())
2882                {
2883                        // test if this leaf is in valid view space
2884                        if (node->TreeValid() &&
2885                                (node != n) &&
2886                                (!onlyUnmailed || !node->Mailed()))
2887                        {
2888                                bool isAdjacent = true;
2889
2890                                if (1)
2891                                {
2892                                        // test all planes of current node if still adjacent
2893                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2894                                        {
2895                                                const int cf =
2896                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2897                                                                                                        halfSpaces[i],
2898                                                                                                        eps);
2899
2900                                                if (cf == Polygon3::FRONT_SIDE)
2901                                                {
2902                                                        isAdjacent = false;
2903                                                }
2904                                        }
2905                                }
2906                                else
2907                                {
2908                                        // TODO: why is this wrong??
2909                                        // test all planes of current node if still adjacent
2910                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
2911                                        {
2912                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
2913
2914                                                const int cf =
2915                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2916                                                                                                        poly->GetSupportingPlane(),
2917                                                                                                        eps);
2918
2919                                                if (cf == Polygon3::FRONT_SIDE)
2920                                                {
2921                                                        isAdjacent = false;
2922                                                }
2923                                        }
2924                                }
2925                                // neighbor was found
2926                                if (isAdjacent)
2927                                {       
2928                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2929                                }
2930                        }
2931                }
2932                else
2933                {
2934                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2935
2936                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
2937                                                                                                   interior->GetPlane(),
2938                                                                                                   eps);
2939                       
2940                        BspNode *front = interior->GetFront();
2941                        BspNode *back = interior->GetBack();
2942           
2943                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2944                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2945
2946                        geom->SplitGeometry(*fGeom,
2947                                                                *bGeom,
2948                                                                interior->GetPlane(),
2949                                                                mBox,
2950                                                                //0.0000001f);
2951                                                                eps);
2952               
2953                        if (cf == Polygon3::BACK_SIDE)
2954                        {
2955                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2956                                DEL_PTR(fGeom);
2957                        }
2958                        else
2959                        {
2960                                if (cf == Polygon3::FRONT_SIDE)
2961                                {
2962                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2963                                        DEL_PTR(bGeom);
2964                                }
2965                                else
2966                                {       // random decision
2967                                        nodeStack.push(bspNodePair(front, fGeom));
2968                                        nodeStack.push(bspNodePair(back, bGeom));
2969                                }
2970                        }
2971                }
2972       
2973                DEL_PTR(geom);
2974        }
2975
2976        return (int)neighbors.size();
2977}
2978
2979
2980
2981int VspBspTree::FindApproximateNeighbors(BspNode *n,
2982                                                                                 vector<BspLeaf *> &neighbors,
2983                                                                                 const bool onlyUnmailed) const
2984{
2985        stack<bspNodePair> nodeStack;
2986       
2987        BspNodeGeometry nodeGeom;
2988        ConstructGeometry(n, nodeGeom);
2989       
2990        float eps = 0.01f;
2991        // split planes from the root to this node
2992        // needed to verify that we found neighbor leaf
2993        // TODO: really needed?
2994        vector<Plane3> halfSpaces;
2995        ExtractHalfSpaces(n, halfSpaces);
2996
2997
2998        BspNodeGeometry *rgeom = new BspNodeGeometry();
2999        ConstructGeometry(mRoot, *rgeom);
3000
3001        nodeStack.push(bspNodePair(mRoot, rgeom));
3002
3003        while (!nodeStack.empty())
3004        {
3005                BspNode *node = nodeStack.top().first;
3006                BspNodeGeometry *geom = nodeStack.top().second;
3007       
3008                nodeStack.pop();
3009
3010                if (node->IsLeaf())
3011                {
3012                        // test if this leaf is in valid view space
3013                        if (node->TreeValid() &&
3014                                (node != n) &&
3015                                (!onlyUnmailed || !node->Mailed()))
3016                        {
3017                                bool isAdjacent = true;
3018
3019                                // neighbor was found
3020                                if (isAdjacent)
3021                                {       
3022                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
3023                                }
3024                        }
3025                }
3026                else
3027                {
3028                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3029
3030                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
3031                                                                                                   interior->GetPlane(),
3032                                                                                                   eps);
3033                       
3034                        BspNode *front = interior->GetFront();
3035                        BspNode *back = interior->GetBack();
3036           
3037                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3038                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3039
3040                        geom->SplitGeometry(*fGeom,
3041                                                                *bGeom,
3042                                                                interior->GetPlane(),
3043                                                                mBox,
3044                                                                //0.0000001f);
3045                                                                eps);
3046               
3047                        if (cf == Polygon3::BACK_SIDE)
3048                        {
3049                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3050                                DEL_PTR(fGeom);
3051                                }
3052                        else
3053                        {
3054                                if (cf == Polygon3::FRONT_SIDE)
3055                                {
3056                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3057                                        DEL_PTR(bGeom);
3058                                }
3059                                else
3060                                {       // random decision
3061                                        nodeStack.push(bspNodePair(front, fGeom));
3062                                        nodeStack.push(bspNodePair(back, bGeom));
3063                                }
3064                        }
3065                }
3066       
3067                DEL_PTR(geom);
3068        }
3069
3070        return (int)neighbors.size();
3071}
3072
3073
3074
3075BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
3076{
3077    stack<BspNode *> nodeStack;
3078        nodeStack.push(mRoot);
3079
3080        int mask = rand();
3081
3082        while (!nodeStack.empty())
3083        {
3084                BspNode *node = nodeStack.top();
3085                nodeStack.pop();
3086
3087                if (node->IsLeaf())
3088                {
3089                        return dynamic_cast<BspLeaf *>(node);
3090                }
3091                else
3092                {
3093                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3094                        BspNode *next;
3095                        BspNodeGeometry geom;
3096
3097                        // todo: not very efficient: constructs full cell everytime
3098                        ConstructGeometry(interior, geom);
3099
3100                        const int cf =
3101                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
3102
3103                        if (cf == Polygon3::BACK_SIDE)
3104                                next = interior->GetFront();
3105                        else
3106                                if (cf == Polygon3::FRONT_SIDE)
3107                                        next = interior->GetFront();
3108                        else
3109                        {
3110                                // random decision
3111                                if (mask & 1)
3112                                        next = interior->GetBack();
3113                                else
3114                                        next = interior->GetFront();
3115                                mask = mask >> 1;
3116                        }
3117
3118                        nodeStack.push(next);
3119                }
3120        }
3121
3122        return NULL;
3123}
3124
3125
3126BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3127{
3128        stack<BspNode *> nodeStack;
3129
3130        nodeStack.push(mRoot);
3131
3132        int mask = rand();
3133
3134        while (!nodeStack.empty())
3135        {
3136                BspNode *node = nodeStack.top();
3137                nodeStack.pop();
3138
3139                if (node->IsLeaf())
3140                {
3141                        if ( (!onlyUnmailed || !node->Mailed()) )
3142                                return dynamic_cast<BspLeaf *>(node);
3143                }
3144                else
3145                {
3146                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3147
3148                        // random decision
3149                        if (mask & 1)
3150                                nodeStack.push(interior->GetBack());
3151                        else
3152                                nodeStack.push(interior->GetFront());
3153
3154                        mask = mask >> 1;
3155                }
3156        }
3157
3158        return NULL;
3159}
3160
3161
3162int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3163{
3164        int pvsSize = 0;
3165
3166        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3167
3168        Intersectable::NewMail();
3169
3170        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3171        {
3172                VssRay *ray = (*rit).mRay;
3173
3174                if (ray->mOriginObject)
3175                {
3176                        if (!ray->mOriginObject->Mailed())
3177                        {
3178                                ray->mOriginObject->Mail();
3179                                ++ pvsSize;
3180                        }
3181                }
3182                if (ray->mTerminationObject)
3183                {
3184                        if (!ray->mTerminationObject->Mailed())
3185                        {
3186                                ray->mTerminationObject->Mail();
3187                                ++ pvsSize;
3188                        }
3189                }
3190        }
3191
3192        return pvsSize;
3193}
3194
3195
3196float VspBspTree::GetEpsilon() const
3197{
3198        return mEpsilon;
3199}
3200
3201
3202int VspBspTree::SplitPolygons(const Plane3 &plane,
3203                                                          PolygonContainer &polys,
3204                                                          PolygonContainer &frontPolys,
3205                                                          PolygonContainer &backPolys,
3206                                                          PolygonContainer &coincident) const
3207{
3208        int splits = 0;
3209
3210        PolygonContainer::const_iterator it, it_end = polys.end();
3211
3212        for (it = polys.begin(); it != polys.end(); ++ it)     
3213        {
3214                Polygon3 *poly = *it;
3215
3216                // classify polygon
3217                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3218
3219                switch (cf)
3220                {
3221                        case Polygon3::COINCIDENT:
3222                                coincident.push_back(poly);
3223                                break;
3224                        case Polygon3::FRONT_SIDE:
3225                                frontPolys.push_back(poly);
3226                                break;
3227                        case Polygon3::BACK_SIDE:
3228                                backPolys.push_back(poly);
3229                                break;
3230                        case Polygon3::SPLIT:
3231                                backPolys.push_back(poly);
3232                                frontPolys.push_back(poly);
3233                                ++ splits;
3234                                break;
3235                        default:
3236                Debug << "SHOULD NEVER COME HERE\n";
3237                                break;
3238                }
3239        }
3240
3241        return splits;
3242}
3243
3244
3245int VspBspTree::CastLineSegment(const Vector3 &origin,
3246                                                                const Vector3 &termination,
3247                                                                vector<ViewCell *> &viewcells)
3248{
3249        int hits = 0;
3250        stack<BspRayTraversalData> tStack;
3251
3252        float mint = 0.0f, maxt = 1.0f;
3253
3254        Intersectable::NewMail();
3255        ViewCell::NewMail();
3256
3257        Vector3 entp = origin;
3258        Vector3 extp = termination;
3259
3260        BspNode *node = mRoot;
3261        BspNode *farChild = NULL;
3262
3263        float t;
3264        const float thresh = 1e-6f; // matt: change this to adjustable value
3265       
3266        while (1)
3267        {
3268                if (!node->IsLeaf())
3269                {
3270                        BspInterior *in = dynamic_cast<BspInterior *>(node);
3271
3272                        Plane3 splitPlane = in->GetPlane();
3273                       
3274                        const int entSide = splitPlane.Side(entp, thresh);
3275                        const int extSide = splitPlane.Side(extp, thresh);
3276
3277                        if (entSide < 0)
3278                        {
3279                                node = in->GetBack();
3280                               
3281                                // plane does not split ray => no far child
3282                                if (extSide <= 0)
3283                                        continue;
3284 
3285                                farChild = in->GetFront(); // plane splits ray
3286                        }
3287                        else if (entSide > 0)
3288                        {
3289                                node = in->GetFront();
3290
3291                                if (extSide >= 0) // plane does not split ray => no far child
3292                                        continue;
3293
3294                                farChild = in->GetBack(); // plane splits ray
3295                        }
3296                        else // one of the ray end points is on the plane
3297                        {       // NOTE: what to do if ray is coincident with plane?
3298                                if (extSide < 0)
3299                                        node = in->GetBack();
3300                                else //if (extSide > 0)
3301                                        node = in->GetFront();
3302                                //else break; // coincident => count no intersections
3303
3304                                continue; // no far child
3305                        }
3306
3307                        // push data for far child
3308                        tStack.push(BspRayTraversalData(farChild, extp));
3309
3310                        // find intersection of ray segment with plane
3311                        extp = splitPlane.FindIntersection(origin, extp, &t);
3312                }
3313                else
3314                {
3315                        // reached leaf => intersection with view cell
3316                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3317                        ViewCell *viewCell;
3318                       
3319                        if (0)
3320                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3321                        else
3322                                viewCell = leaf->GetViewCell();
3323
3324                        if (!viewCell->Mailed())
3325                        {
3326                                viewcells.push_back(viewCell);
3327                                viewCell->Mail();
3328                                ++ hits;
3329                        }
3330
3331                        //-- fetch the next far child from the stack
3332                        if (tStack.empty())
3333                                break;
3334
3335                        entp = extp;
3336                       
3337                        const BspRayTraversalData &s = tStack.top();
3338
3339                        node = s.mNode;
3340                        extp = s.mExitPoint;
3341
3342                        tStack.pop();
3343                }
3344        }
3345
3346        return hits;
3347}
3348
3349
3350
3351
3352int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
3353{
3354        std::deque<BspNode *> path1;
3355        BspNode *p1 = n1;
3356
3357        // create path from node 1 to root
3358        while (p1)
3359        {
3360                if (p1 == n2) // second node on path
3361                        return (int)path1.size();
3362
3363                path1.push_front(p1);
3364                p1 = p1->GetParent();
3365        }
3366
3367        int depth = n2->GetDepth();
3368        int d = depth;
3369
3370        BspNode *p2 = n2;
3371
3372        // compare with same depth
3373        while (1)
3374        {
3375                if ((d < (int)path1.size()) && (p2 == path1[d]))
3376                        return (depth - d) + ((int)path1.size() - 1 - d);
3377
3378                -- d;
3379                p2 = p2->GetParent();
3380        }
3381
3382        return 0; // never come here
3383}
3384
3385
3386BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
3387{
3388// TODO
3389#if HAS_TO_BE_REDONE
3390        if (node->IsLeaf())
3391                return node;
3392
3393        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3394
3395        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3396        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
3397
3398        if (front->IsLeaf() && back->IsLeaf())
3399        {
3400                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
3401                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
3402
3403                //-- collapse tree
3404                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3405                {
3406                        BspViewCell *vc = frontLeaf->GetViewCell();
3407
3408                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
3409                        leaf->SetTreeValid(frontLeaf->TreeValid());
3410
3411                        // replace a link from node's parent
3412                        if (leaf->GetParent())
3413                                leaf->GetParent()->ReplaceChildLink(node, leaf);
3414                        else
3415                                mRoot = leaf;
3416
3417                        ++ collapsed;
3418                        delete interior;
3419
3420                        return leaf;
3421                }
3422        }
3423#endif
3424        return node;
3425}
3426
3427
3428int VspBspTree::CollapseTree()
3429{
3430        int collapsed = 0;
3431        //TODO
3432#if HAS_TO_BE_REDONE
3433        (void)CollapseTree(mRoot, collapsed);
3434
3435        // revalidate leaves
3436        RepairViewCellsLeafLists();
3437#endif
3438        return collapsed;
3439}
3440
3441
3442void VspBspTree::RepairViewCellsLeafLists()
3443{
3444// TODO
3445#if HAS_TO_BE_REDONE
3446        // list not valid anymore => clear
3447        stack<BspNode *> nodeStack;
3448        nodeStack.push(mRoot);
3449
3450        ViewCell::NewMail();
3451
3452        while (!nodeStack.empty())
3453        {
3454                BspNode *node = nodeStack.top();
3455                nodeStack.pop();
3456
3457                if (node->IsLeaf())
3458                {
3459                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3460
3461                        BspViewCell *viewCell = leaf->GetViewCell();
3462
3463                        if (!viewCell->Mailed())
3464                        {
3465                                viewCell->mLeaves.clear();
3466                                viewCell->Mail();
3467                        }
3468       
3469                        viewCell->mLeaves.push_back(leaf);
3470
3471                }
3472                else
3473                {
3474                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3475
3476                        nodeStack.push(interior->GetFront());
3477                        nodeStack.push(interior->GetBack());
3478                }
3479        }
3480// TODO
3481#endif
3482}
3483
3484
3485typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
3486
3487
3488int VspBspTree::CastBeam(Beam &beam)
3489{
3490    stack<bspNodePair> nodeStack;
3491        BspNodeGeometry *rgeom = new BspNodeGeometry();
3492        ConstructGeometry(mRoot, *rgeom);
3493
3494        nodeStack.push(bspNodePair(mRoot, rgeom));
3495 
3496        ViewCell::NewMail();
3497
3498        while (!nodeStack.empty())
3499        {
3500                BspNode *node = nodeStack.top().first;
3501                BspNodeGeometry *geom = nodeStack.top().second;
3502                nodeStack.pop();
3503               
3504                AxisAlignedBox3 box;
3505                geom->GetBoundingBox(box);
3506
3507                const int side = beam.ComputeIntersection(box);
3508               
3509                switch (side)
3510                {
3511                case -1:
3512                        CollectViewCells(node, true, beam.mViewCells, true);
3513                        break;
3514                case 0:
3515                       
3516                        if (node->IsLeaf())
3517                        {
3518                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3519                       
3520                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
3521                                {
3522                                        leaf->GetViewCell()->Mail();
3523                                        beam.mViewCells.push_back(leaf->GetViewCell());
3524                                }
3525                        }
3526                        else
3527                        {
3528                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3529                       
3530                                BspNode *first = interior->GetFront();
3531                                BspNode *second = interior->GetBack();
3532           
3533                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3534                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3535
3536                                geom->SplitGeometry(*firstGeom,
3537                                                                        *secondGeom,
3538                                                                        interior->GetPlane(),
3539                                                                        mBox,
3540                                                                        //0.0000001f);
3541                                                                        mEpsilon);
3542
3543                                // decide on the order of the nodes
3544                                if (DotProd(beam.mPlanes[0].mNormal,
3545                                        interior->GetPlane().mNormal) > 0)
3546                                {
3547                                        swap(first, second);
3548                                        swap(firstGeom, secondGeom);
3549                                }
3550
3551                                nodeStack.push(bspNodePair(first, firstGeom));
3552                                nodeStack.push(bspNodePair(second, secondGeom));
3553                        }
3554                       
3555                        break;
3556                default:
3557                        // default: cull
3558                        break;
3559                }
3560               
3561                DEL_PTR(geom);
3562               
3563        }
3564
3565        return (int)beam.mViewCells.size();
3566}
3567
3568
3569void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
3570{
3571        mViewCellsManager = vcm;
3572}
3573
3574
3575int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3576                                                                           vector<MergeCandidate> &candidates)
3577{
3578        BspLeaf::NewMail();
3579       
3580        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3581
3582        int numCandidates = 0;
3583
3584        // find merge candidates and push them into queue
3585        for (it = leaves.begin(); it != it_end; ++ it)
3586        {
3587                BspLeaf *leaf = *it;
3588               
3589                // the same leaves must not be part of two merge candidates
3590                leaf->Mail();
3591               
3592                vector<BspLeaf *> neighbors;
3593               
3594                // appoximate neighbor search has slightl relaxed constraints
3595                if (1)
3596                        FindNeighbors(leaf, neighbors, true);
3597                else
3598                        FindApproximateNeighbors(leaf, neighbors, true);
3599
3600                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3601
3602                // TODO: test if at least one ray goes from one leaf to the other
3603                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
3604                {
3605                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
3606                        {
3607                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
3608
3609                                // dont't merge view cells if they are empty and not front and back leaf of the same parent
3610                                // in the tree?
3611                                if (mEmptyViewCellsMergeAllowed ||
3612                                        !leaf->GetViewCell()->GetPvs().Empty() ||
3613                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
3614                    leaf->IsSibling(*nit))
3615                                {
3616                                        candidates.push_back(mc);
3617                                }
3618
3619                                ++ numCandidates;
3620                                if ((numCandidates % 1000) == 0)
3621                                {
3622                                        cout << "collected " << numCandidates << " merge candidates" << endl;
3623                                }
3624                        }
3625                }
3626        }
3627
3628        Debug << "merge queue: " << (int)candidates.size() << endl;
3629        Debug << "leaves in queue: " << numCandidates << endl;
3630       
3631
3632        return (int)leaves.size();
3633}
3634
3635
3636int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3637                                                                           vector<MergeCandidate> &candidates)
3638{
3639        ViewCell::NewMail();
3640        long startTime = GetTime();
3641       
3642        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
3643        ViewCellContainer::const_iterator iit;
3644
3645        int numLeaves = 0;
3646       
3647        BspLeaf::NewMail();
3648
3649        for (int i = 0; i < (int)rays.size(); ++ i)
3650        { 
3651                VssRay *ray = rays[i];
3652       
3653                // traverse leaves stored in the rays and compare and
3654                // merge consecutive leaves (i.e., the neighbors in the tree)
3655                if (ray->mViewCells.size() < 2)
3656                        continue;
3657//TODO viewcellhierarchy
3658                iit = ray->mViewCells.begin();
3659                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
3660                BspLeaf *leaf = bspVc->mLeaf;
3661               
3662                // traverse intersections
3663                // consecutive leaves are neighbors => add them to queue
3664                for (; iit != ray->mViewCells.end(); ++ iit)
3665                {
3666                        // next pair
3667                        BspLeaf *prevLeaf = leaf;
3668                        bspVc = dynamic_cast<BspViewCell *>(*iit);
3669            leaf = bspVc->mLeaf;
3670
3671                        // view space not valid or same view cell
3672                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3673                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
3674                                continue;
3675
3676                vector<BspLeaf *> &neighbors = neighborMap[leaf];
3677                       
3678                        bool found = false;
3679
3680                        // both leaves inserted in queue already =>
3681                        // look if double pair already exists
3682                        if (leaf->Mailed() && prevLeaf->Mailed())
3683                        {
3684                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3685                               
3686                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3687                                        if (*it == prevLeaf)
3688                                                found = true; // already in queue
3689                        }
3690               
3691                        if (!found)
3692                        {
3693                                // this pair is not in map yet
3694                                // => insert into the neighbor map and the queue
3695                                neighbors.push_back(prevLeaf);
3696                                neighborMap[prevLeaf].push_back(leaf);
3697
3698                                leaf->Mail();
3699                                prevLeaf->Mail();
3700               
3701                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3702                               
3703                                candidates.push_back(mc);
3704
3705                                if (((int)candidates.size() % 1000) == 0)
3706                                {
3707                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
3708                                }
3709                        }
3710        }
3711        }
3712
3713        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
3714        Debug << "merge queue: " << (int)candidates.size() << endl;
3715        Debug << "leaves in queue: " << numLeaves << endl;
3716
3717
3718        //-- collect the leaves which haven't been found by ray casting
3719        if (0)
3720        {
3721                cout << "finding additional merge candidates using geometry" << endl;
3722                vector<BspLeaf *> leaves;
3723                CollectLeaves(leaves, true);
3724                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
3725                CollectMergeCandidates(leaves, candidates);
3726        }
3727
3728        return numLeaves;
3729}
3730
3731
3732
3733
3734ViewCell *VspBspTree::GetViewCell(const Vector3 &point)
3735{
3736  if (mRoot == NULL)
3737        return NULL;
3738 
3739  stack<BspNode *> nodeStack;
3740  nodeStack.push(mRoot);
3741 
3742  ViewCell *viewcell = NULL;
3743 
3744  while (!nodeStack.empty())  {
3745        BspNode *node = nodeStack.top();
3746        nodeStack.pop();
3747       
3748        if (node->IsLeaf()) {
3749          viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
3750          break;
3751        } else {
3752         
3753          BspInterior *interior = dynamic_cast<BspInterior *>(node);
3754               
3755          // random decision
3756          if (interior->GetPlane().Side(point) < 0)
3757                nodeStack.push(interior->GetBack());
3758          else
3759                nodeStack.push(interior->GetFront());
3760        }
3761  }
3762 
3763  return viewcell;
3764}
3765
3766
3767bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3768{
3769        BspNode *node = mRoot;
3770
3771        while (1)
3772        {
3773                // early exit
3774                if (node->TreeValid())
3775                        return true;
3776
3777                if (node->IsLeaf())
3778                        return false;
3779                       
3780                BspInterior *in = dynamic_cast<BspInterior *>(node);
3781                                       
3782                if (in->GetPlane().Side(viewPoint) <= 0)
3783                {
3784                        node = in->GetBack();
3785                }
3786                else
3787                {
3788                        node = in->GetFront();
3789                }
3790        }
3791
3792        // should never come here
3793        return false;
3794}
3795
3796
3797void VspBspTree::PropagateUpValidity(BspNode *node)
3798{
3799        const bool isValid = node->TreeValid();
3800
3801        // propagative up invalid flag until only invalid nodes exist over this node
3802        if (!isValid)
3803        {
3804                while (!node->IsRoot() && node->GetParent()->TreeValid())
3805                {
3806                        node = node->GetParent();
3807                        node->SetTreeValid(false);
3808                }
3809        }
3810        else
3811        {
3812                // propagative up valid flag until one of the subtrees is invalid
3813                while (!node->IsRoot() && !node->TreeValid())
3814                {
3815            node = node->GetParent();
3816                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3817                       
3818                        // the parent is valid iff both leaves are valid
3819                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3820                                                           interior->GetFront()->TreeValid());
3821                }
3822        }
3823}
3824
3825
3826bool VspBspTree::Export(ofstream &stream)
3827{
3828        ExportNode(mRoot, stream);
3829
3830        return true;
3831}
3832
3833
3834void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
3835{
3836        if (node->IsLeaf())
3837        {
3838                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3839                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3840
3841                int id = -1;
3842                if (viewCell != mOutOfBoundsCell)
3843                        id = viewCell->GetId();
3844
3845                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3846        }
3847        else
3848        {
3849                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3850       
3851                Plane3 plane = interior->GetPlane();
3852                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3853                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3854                           << plane.mD << "\">" << endl;
3855
3856                ExportNode(interior->GetBack(), stream);
3857                ExportNode(interior->GetFront(), stream);
3858
3859                stream << "</Interior>" << endl;
3860        }
3861}
Note: See TracBrowser for help on using the repository browser.