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

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