source: GTP/trunk/Lib/Vis/Preprocessing/src/FromPointVisibilityTree.cpp @ 860

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