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

Revision 1004, 95.7 KB checked in by mattausch, 18 years ago (diff)

environment as a singleton

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