source: trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp @ 497

Revision 497, 68.0 KB checked in by mattausch, 18 years ago (diff)

beware: bug in view cells merging

Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellBsp.h"
17#include "ViewCellsManager.h"
18
19
20//-- static members
21/** Evaluates split plane classification with respect to the plane's
22        contribution for a minimum number of ray splits.
23*/
24const float VspBspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
25/** Evaluates split plane classification with respect to the plane's
26        contribution for balanced rays.
27*/
28const float VspBspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
29
30
31int VspBspTree::sFrontId = 0;
32int VspBspTree::sBackId = 0;
33int VspBspTree::sFrontAndBackId = 0;
34
35float BspMergeCandidate::sOverallCost = 0;
36
37/****************************************************************/
38/*                  class VspBspTree implementation             */
39/****************************************************************/
40
41VspBspTree::VspBspTree():
42mRoot(NULL),
43mPvsUseArea(true),
44mCostNormalizer(Limits::Small),
45mViewCellsManager(NULL),
46mStoreRays(false),
47mOutOfBoundsCell(NULL),
48mShowInvalidSpace(false)
49{
50        bool randomize = false;
51        environment->GetBoolValue("VspBspTree.Construction.randomize", randomize);
52        if (randomize)
53                Randomize(); // initialise random generator for heuristics
54
55        //-- termination criteria for autopartition
56        environment->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
57        environment->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
58        environment->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
59        environment->GetFloatValue("VspBspTree.Termination.minArea", mTermMinArea);
60        environment->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
61        environment->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
62        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
63        environment->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
64
65        //-- factors for bsp tree split plane heuristics
66        environment->GetFloatValue("VspBspTree.Factor.balancedRays", mBalancedRaysFactor);
67        environment->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
68        environment->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
69
70        //-- max cost ratio for early tree termination
71        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
72
73        //-- partition criteria
74        environment->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
75        environment->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
76        environment->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
77
78        environment->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
79        environment->GetIntValue("VspBspTree.maxTests", mMaxTests);
80
81        // maximum and minimum number of view cells
82        environment->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
83        environment->GetIntValue("VspBspTree.PostProcess.minViewCells", mMergeMinViewCells);
84        environment->GetFloatValue("VspBspTree.PostProcess.maxCostRatio", mMergeMaxCostRatio);
85
86        environment->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
87        environment->GetBoolValue("VspBspTree.PostProcess.useRaysForMerge", mUseRaysForMerge);
88        environment->GetIntValue("ViewCells.maxPvs", mMaxPvs);
89
90
91        //-- debug output
92        Debug << "******* VSP BSP options ******** " << endl;
93    Debug << "max depth: " << mTermMaxDepth << endl;
94        Debug << "min PVS: " << mTermMinPvs << endl;
95        Debug << "min area: " << mTermMinArea << endl;
96        Debug << "min rays: " << mTermMinRays << endl;
97        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
98        //Debug << "VSP BSP mininam accumulated ray lenght: ", mTermMinAccRayLength) << endl;
99        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
100        Debug << "miss tolerance: " << mTermMissTolerance << endl;
101        Debug << "max view cells: " << mMaxViewCells << endl;
102        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
103        Debug << "max plane candidates: " << mMaxRayCandidates << endl;
104        Debug << "randomize: " << randomize << endl;
105
106        Debug << "Split plane strategy: ";
107        if (mSplitPlaneStrategy & RANDOM_POLYGON)
108        {
109                Debug << "random polygon ";
110        }
111        if (mSplitPlaneStrategy & AXIS_ALIGNED)
112        {
113                Debug << "axis aligned ";
114        }
115        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
116        {
117                mCostNormalizer += mLeastRaySplitsFactor;
118                Debug << "least ray splits ";
119        }
120        if (mSplitPlaneStrategy & BALANCED_RAYS)
121        {
122                mCostNormalizer += mBalancedRaysFactor;
123                Debug << "balanced rays ";
124        }
125        if (mSplitPlaneStrategy & PVS)
126        {
127                mCostNormalizer += mPvsFactor;
128                Debug << "pvs";
129        }
130
131
132        mSplitCandidates = new vector<SortableEntry>;
133
134        Debug << endl;
135}
136
137
138BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
139{
140        if (!mOutOfBoundsCell)
141                mOutOfBoundsCell = new BspViewCell();
142
143        return mOutOfBoundsCell;
144}
145
146
147const BspTreeStatistics &VspBspTree::GetStatistics() const
148{
149        return mStat;
150}
151
152
153VspBspTree::~VspBspTree()
154{
155        DEL_PTR(mRoot);
156        DEL_PTR(mSplitCandidates);
157}
158
159int VspBspTree::AddMeshToPolygons(Mesh *mesh,
160                                                                  PolygonContainer &polys,
161                                                                  MeshInstance *parent)
162{
163        FaceContainer::const_iterator fi;
164
165        // copy the face data to polygons
166        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
167        {
168                Polygon3 *poly = new Polygon3((*fi), mesh);
169
170                if (poly->Valid(mEpsilon))
171                {
172                        poly->mParent = parent; // set parent intersectable
173                        polys.push_back(poly);
174                }
175                else
176                        DEL_PTR(poly);
177        }
178        return (int)mesh->mFaces.size();
179}
180
181int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
182                                                          PolygonContainer &polys,
183                                                          int maxObjects)
184{
185        int limit = (maxObjects > 0) ?
186                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
187
188        int polysSize = 0;
189
190        for (int i = 0; i < limit; ++ i)
191        {
192                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
193                {
194                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
195                        polysSize +=
196                                AddMeshToPolygons(viewCells[i]->GetMesh(),
197                                                                  polys,
198                                                                  viewCells[i]);
199                }
200        }
201
202        return polysSize;
203}
204
205int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
206                                                                 PolygonContainer &polys,
207                                                                 int maxObjects)
208{
209        int limit = (maxObjects > 0) ?
210                Min((int)objects.size(), maxObjects) : (int)objects.size();
211
212        for (int i = 0; i < limit; ++i)
213        {
214                Intersectable *object = objects[i];//*it;
215                Mesh *mesh = NULL;
216
217                switch (object->Type()) // extract the meshes
218                {
219                case Intersectable::MESH_INSTANCE:
220                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
221                        break;
222                case Intersectable::VIEW_CELL:
223                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
224                        break;
225                        // TODO: handle transformed mesh instances
226                default:
227                        Debug << "intersectable type not supported" << endl;
228                        break;
229                }
230
231        if (mesh) // copy the mesh data to polygons
232                {
233                        mBox.Include(object->GetBox()); // add to BSP tree aabb
234                        AddMeshToPolygons(mesh, polys, NULL);
235                }
236        }
237
238        return (int)polys.size();
239}
240
241void VspBspTree::Construct(const VssRayContainer &sampleRays,
242                                                   AxisAlignedBox3 *forcedBoundingBox)
243{
244    mStat.nodes = 1;
245        mBox.Initialize();      // initialise BSP tree bounding box
246
247        if (forcedBoundingBox)
248                mBox = *forcedBoundingBox;
249       
250        PolygonContainer polys;
251        RayInfoContainer *rays = new RayInfoContainer();
252
253        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
254
255        long startTime = GetTime();
256
257        cout << "Extracting polygons from rays ... ";
258
259        Intersectable::NewMail();
260
261        //-- extract polygons intersected by the rays
262        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
263        {
264                VssRay *ray = *rit;
265
266                if ((mBox.IsInside(ray->mTermination) || !forcedBoundingBox) &&
267                        ray->mTerminationObject &&
268                        !ray->mTerminationObject->Mailed())
269                {
270                        ray->mTerminationObject->Mail();
271                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mTerminationObject);
272                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
273                        //-- compute bounding box
274                        if (!forcedBoundingBox)
275                                mBox.Include(ray->mTermination);
276                }
277
278                if ((mBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
279                        ray->mOriginObject &&
280                        !ray->mOriginObject->Mailed())
281                {
282                        ray->mOriginObject->Mail();
283                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
284                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
285                        //-- compute bounding box
286                        if (!forcedBoundingBox)
287                                mBox.Include(ray->mOrigin);
288                }
289        }
290
291        //-- compute bounding box
292        //if (!forcedBoundingBox) Polygon3::IncludeInBox(polys, mBox);
293
294        //-- store rays
295        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
296        {
297                VssRay *ray = *rit;
298
299                float minT, maxT;
300
301                // TODO: not very efficient to implictly cast between rays types
302                if (mBox.GetRaySegment(*ray, minT, maxT))
303                {
304                        float len = ray->Length();
305
306                        if (!len)
307                                len = Limits::Small;
308
309                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
310                }
311        }
312
313        mTermMinArea *= mBox.SurfaceArea(); // normalize
314        mStat.polys = (int)polys.size();
315
316        cout << "finished" << endl;
317
318        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
319                  << (int)sampleRays.size() << " rays in "
320                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
321
322        Construct(polys, rays);
323
324        // clean up polygons
325        CLEAR_CONTAINER(polys);
326}
327
328void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
329{
330        VspBspTraversalStack tStack;
331
332        mRoot = new BspLeaf();
333
334        // constrruct root node geometry
335        BspNodeGeometry *geom = new BspNodeGeometry();
336        ConstructGeometry(mRoot, *geom);
337
338        VspBspTraversalData tData(mRoot,
339                                                          new PolygonContainer(polys),
340                                                          0,
341                                                          rays,
342                              ComputePvsSize(*rays),
343                                                          geom->GetArea(),
344                                                          geom);
345
346        tStack.push(tData);
347
348        mStat.Start();
349        cout << "Contructing vsp bsp tree ... ";
350
351        long startTime = GetTime();
352
353        while (!tStack.empty())
354        {
355                tData = tStack.top();
356
357            tStack.pop();
358
359                // subdivide leaf node
360                BspNode *r = Subdivide(tStack, tData);
361
362                if (r == mRoot)
363                        Debug << "VSP BSP tree construction time spent at root: "
364                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl << endl;
365        }
366
367        cout << "finished\n";
368
369        mStat.Stop();
370}
371
372bool VspBspTree::TerminationCriteriaMet(const VspBspTraversalData &data) const
373{
374        return
375                (((int)data.mRays->size() <= mTermMinRays) ||
376                 (data.mPvs <= mTermMinPvs)   ||
377                 (data.mArea <= mTermMinArea) ||
378                 (mStat.Leaves() >= mMaxViewCells) ||
379                // (data.GetAvgRayContribution() >= mTermMaxRayContribution) ||
380                 (data.mDepth >= mTermMaxDepth));
381}
382
383BspNode *VspBspTree::Subdivide(VspBspTraversalStack &tStack,
384                                                           VspBspTraversalData &tData)
385{
386        BspNode *newNode = tData.mNode;
387
388        if (!TerminationCriteriaMet(tData))
389        {
390                PolygonContainer coincident;
391
392                VspBspTraversalData tFrontData;
393                VspBspTraversalData tBackData;
394
395                // create new interior node and two leaf nodes
396                // or return leaf as it is (if maxCostRatio missed)
397                newNode = SubdivideNode(tData, tFrontData, tBackData, coincident);
398
399                if (!newNode->IsLeaf()) //-- continue subdivision
400                {
401                        // push the children on the stack
402                        tStack.push(tFrontData);
403                        tStack.push(tBackData);
404
405                        // delete old leaf node
406                        DEL_PTR(tData.mNode);
407                }
408        }
409
410        //-- terminate traversal and create new view cell
411        if (newNode->IsLeaf())
412        {
413                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
414                BspViewCell *viewCell;
415
416                if (!CheckValid(tData))
417                {
418                        leaf->SetTreeValid(false);
419                        PropagateUpValidity(leaf);
420                        // view cell for invalid view space
421                        viewCell = GetOrCreateOutOfBoundsCell();
422                        ++ mStat.invalidLeaves;
423                }
424                else
425                {
426                        // create new view cell for this leaf
427                        viewCell = new BspViewCell();
428                }
429               
430                leaf->SetViewCell(viewCell);
431       
432                //-- update pvs
433                int conSamp = 0, sampCon = 0;
434                AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
435
436                mStat.contributingSamples += conSamp;
437                mStat.sampleContributions += sampCon;
438
439                //-- store additional info
440                if (mStoreRays)
441                {
442                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
443                        for (it = tData.mRays->begin(); it != it_end; ++ it)
444                                leaf->mVssRays.push_back((*it).mRay);
445                }
446
447                viewCell->mLeaves.push_back(leaf);
448                viewCell->SetArea(tData.mArea);
449                leaf->mArea = tData.mArea;
450
451                EvaluateLeafStats(tData);               
452        }
453
454        //-- cleanup
455        tData.Clear();
456
457        return newNode;
458}
459
460
461BspNode *VspBspTree::SubdivideNode(VspBspTraversalData &tData,
462                                                                   VspBspTraversalData &frontData,
463                                                                   VspBspTraversalData &backData,
464                                                                   PolygonContainer &coincident)
465{
466        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
467
468        int maxCostMisses = tData.mMaxCostMisses;
469
470        // select subdivision plane
471        Plane3 splitPlane;
472        if (!SelectPlane(splitPlane, leaf, tData))
473        {
474                ++ maxCostMisses;
475
476                if (maxCostMisses > mTermMissTolerance)
477                {
478                        // terminate branch because of max cost
479                        ++ mStat.maxCostNodes;
480            return leaf;
481                }
482        }
483
484        mStat.nodes += 2;
485
486        //-- subdivide further
487        BspInterior *interior = new BspInterior(splitPlane);
488
489#ifdef _DEBUG
490        Debug << interior << endl;
491#endif
492
493        //-- the front and back traversal data is filled with the new values
494        frontData.mPolygons = new PolygonContainer();
495        frontData.mDepth = tData.mDepth + 1;
496        frontData.mRays = new RayInfoContainer();
497        frontData.mGeometry = new BspNodeGeometry();
498
499        backData.mPolygons = new PolygonContainer();
500        backData.mDepth = tData.mDepth + 1;
501        backData.mRays = new RayInfoContainer();
502        backData.mGeometry = new BspNodeGeometry();
503
504        // subdivide rays
505        SplitRays(interior->GetPlane(),
506                          *tData.mRays,
507                          *frontData.mRays,
508                          *backData.mRays);
509
510        // subdivide polygons
511        SplitPolygons(interior->GetPlane(),
512                                  *tData.mPolygons,
513                      *frontData.mPolygons,
514                                  *backData.mPolygons,
515                                  coincident);
516
517
518        // how often was max cost ratio missed in this branch?
519        frontData.mMaxCostMisses = maxCostMisses;
520        backData.mMaxCostMisses = maxCostMisses;
521
522        // compute pvs
523        frontData.mPvs = ComputePvsSize(*frontData.mRays);
524        backData.mPvs = ComputePvsSize(*backData.mRays);
525
526        // split geometry and compute area
527        if (1)
528        {
529                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
530                                                                           *backData.mGeometry,
531                                                                           interior->GetPlane(),
532                                                                           mBox,
533                                                                           mEpsilon);
534
535                frontData.mArea = frontData.mGeometry->GetArea();
536                backData.mArea = backData.mGeometry->GetArea();
537        }
538
539        // compute accumulated ray length
540        //frontData.mAccRayLength = AccumulatedRayLength(*frontData.mRays);
541        //backData.mAccRayLength = AccumulatedRayLength(*backData.mRays);
542
543        //-- create front and back leaf
544
545        BspInterior *parent = leaf->GetParent();
546
547        // replace a link from node's parent
548        if (parent)
549        {
550                parent->ReplaceChildLink(leaf, interior);
551                interior->SetParent(parent);
552        }
553        else // new root
554        {
555                mRoot = interior;
556        }
557
558        // and setup child links
559        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
560
561        frontData.mNode = interior->GetFront();
562        backData.mNode = interior->GetBack();
563
564        //DEL_PTR(leaf);
565        return interior;
566}
567
568void VspBspTree::AddToPvs(BspLeaf *leaf,
569                                                  const RayInfoContainer &rays,
570                                                  int &sampleContributions,
571                                                  int &contributingSamples)
572{
573        sampleContributions = 0;
574        contributingSamples = 0;
575
576    RayInfoContainer::const_iterator it, it_end = rays.end();
577
578        ViewCell *vc = leaf->GetViewCell();
579
580        // add contributions from samples to the PVS
581        for (it = rays.begin(); it != it_end; ++ it)
582        {
583                int contribution = 0;
584                VssRay *ray = (*it).mRay;
585
586                if (ray->mTerminationObject)
587                        contribution += vc->GetPvs().AddSample(ray->mTerminationObject);
588
589                if (ray->mOriginObject)
590                        contribution += vc->GetPvs().AddSample(ray->mOriginObject);
591
592                if (contribution)
593                {
594                        sampleContributions += contribution;
595                        ++ contributingSamples;
596                }
597                //leaf->mVssRays.push_back(ray);
598        }
599}
600
601void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays, const int axis)
602{
603        mSplitCandidates->clear();
604
605        int requestedSize = 2 * (int)(rays.size());
606        // creates a sorted split candidates array
607        if (mSplitCandidates->capacity() > 500000 &&
608                requestedSize < (int)(mSplitCandidates->capacity()/10) )
609        {
610        delete mSplitCandidates;
611                mSplitCandidates = new vector<SortableEntry>;
612        }
613
614        mSplitCandidates->reserve(requestedSize);
615
616        // insert all queries
617        for(RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
618        {
619                bool positive = (*ri).mRay->HasPosDir(axis);
620                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
621                                                                                                  (*ri).ExtrapOrigin(axis), (*ri).mRay));
622
623                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
624                                                                                                  (*ri).ExtrapTermination(axis), (*ri).mRay));
625        }
626
627        stable_sort(mSplitCandidates->begin(), mSplitCandidates->end());
628}
629
630float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
631                                                                                  const AxisAlignedBox3 &box,
632                                                                                  const int pvsSize,
633                                                                                  const int &axis,
634                                          float &position)
635{
636        int raysBack;
637        int raysFront;
638        int pvsBack;
639        int pvsFront;
640
641        SortSplitCandidates(rays, axis);
642
643        // go through the lists, count the number of objects left and right
644        // and evaluate the following cost funcion:
645        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
646
647        int rl = 0, rr = (int)rays.size();
648        int pl = 0, pr = pvsSize;
649
650        float minBox = box.Min(axis);
651        float maxBox = box.Max(axis);
652        float sizeBox = maxBox - minBox;
653
654        float minBand = minBox + 0.1f*(maxBox - minBox);
655        float maxBand = minBox + 0.9f*(maxBox - minBox);
656
657        float sum = rr*sizeBox;
658        float minSum = 1e20f;
659
660        Intersectable::NewMail();
661
662        // set all object as belonging to the fron pvs
663        for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ++ ri)
664        {
665                if ((*ri).mRay->IsActive())
666                {
667                        Intersectable *object = (*ri).mRay->mTerminationObject;
668
669                        if (object)
670                        {
671                                if (!object->Mailed())
672                                {
673                                        object->Mail();
674                                        object->mCounter = 1;
675                                }
676                                else
677                                        ++ object->mCounter;
678                        }
679                }
680        }
681
682        Intersectable::NewMail();
683
684        for (vector<SortableEntry>::const_iterator ci = mSplitCandidates->begin();
685                ci < mSplitCandidates->end(); ++ ci)
686        {
687                VssRay *ray;
688
689                switch ((*ci).type)
690                {
691                        case SortableEntry::ERayMin:
692                                {
693                                        ++ rl;
694                                        ray = (VssRay *) (*ci).ray;
695
696                                        Intersectable *object = ray->mTerminationObject;
697
698                                        if (object && !object->Mailed())
699                                        {
700                                                object->Mail();
701                                                ++ pl;
702                                        }
703                                        break;
704                                }
705                        case SortableEntry::ERayMax:
706                                {
707                                        -- rr;
708                                        ray = (VssRay *) (*ci).ray;
709
710                                        Intersectable *object = ray->mTerminationObject;
711
712                                        if (object)
713                                        {
714                                                if (-- object->mCounter == 0)
715                                                        -- pr;
716                                        }
717
718                                        break;
719                                }
720                }
721
722                // Note: sufficient to compare size of bounding boxes of front and back side?
723                if ((*ci).value > minBand && (*ci).value < maxBand)
724                {
725                        sum = pl*((*ci).value - minBox) + pr*(maxBox - (*ci).value);
726
727                        //  cout<<"pos="<<(*ci).value<<"\t q=("<<ql<<","<<qr<<")\t r=("<<rl<<","<<rr<<")"<<endl;
728                        // cout<<"cost= "<<sum<<endl;
729
730                        if (sum < minSum)
731                        {
732                                minSum = sum;
733                                position = (*ci).value;
734
735                                raysBack = rl;
736                                raysFront = rr;
737
738                                pvsBack = pl;
739                                pvsFront = pr;
740
741                        }
742                }
743        }
744
745        float oldCost = (float)pvsSize;
746        float newCost = mCtDivCi + minSum / sizeBox;
747        float ratio = newCost / oldCost;
748
749        //Debug << "costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
750        //     <<"\t q=(" << queriesBack << "," << queriesFront << ")\t r=(" << raysBack << "," << raysFront << ")" << endl;
751
752        return ratio;
753}
754
755
756float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
757                                                                                 const VspBspTraversalData &tData,
758                                                                                 int &axis,
759                                                                                 float &position,
760                                                                                 int &raysBack,
761                                                                                 int &raysFront,
762                                                                                 int &pvsBack,
763                                                                                 int &pvsFront)
764{
765        AxisAlignedBox3 box;
766        box.Initialize();
767
768        // create bounding box of region
769        RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
770
771        for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
772                box.Include((*ri).ExtrapTermination());
773
774        const bool useCostHeuristics = false;
775
776        //-- regular split
777        float nPosition[3];
778        float nCostRatio[3];
779        int bestAxis = -1;
780
781        const int sAxis = box.Size().DrivingAxis();
782
783        for (axis = 0; axis < 3; ++ axis)
784        {
785                if (!mOnlyDrivingAxis || axis == sAxis)
786                {
787                        if (!useCostHeuristics)
788                        {
789                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
790                                Vector3 normal(0,0,0); normal[axis] = 1;
791
792                                nCostRatio[axis] = SplitPlaneCost(Plane3(normal, nPosition[axis]), tData);
793                        }
794                        else
795                        {
796                                nCostRatio[axis] =
797                                        BestCostRatioHeuristics(*tData.mRays,
798                                                                                    box,
799                                                                                        tData.mPvs,
800                                                                                        axis,
801                                                                                        nPosition[axis]);
802                        }
803
804                        if (bestAxis == -1)
805                        {
806                                bestAxis = axis;
807                        }
808
809                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
810                        {
811                                /*Debug << "pvs front " << nPvsBack[axis]
812                                          << " pvs back " << nPvsFront[axis]
813                                          << " overall pvs " << leaf->GetPvsSize() << endl;*/
814                                bestAxis = axis;
815                        }
816
817                }
818        }
819
820        //-- assign values
821        axis = bestAxis;
822        position = nPosition[bestAxis];
823
824        raysBack = 0;//nRaysBack[bestAxis];
825        raysFront = 0;//nRaysFront[bestAxis];
826
827        pvsBack = 0;//nPvsBack[bestAxis];
828        pvsFront = 0;//nPvsFront[bestAxis];
829
830        Vector3 normal(0,0,0); normal[bestAxis] = 1;
831        plane = Plane3(normal, nPosition[bestAxis]);
832       
833        return nCostRatio[bestAxis];
834}
835
836
837float VspBspTree::EvalCostRatio(const VspBspTraversalData &tData,
838                                                                const AxisAlignedBox3 &box,
839                                                                const int axis,
840                                                                const float position,
841                                                                int &raysBack,
842                                                                int &raysFront,
843                                                                int &pvsBack,
844                                                                int &pvsFront)
845{
846        raysBack = 0;
847        raysFront = 0;
848        pvsFront = 0;
849        pvsBack = 0;
850
851        Intersectable::NewMail(3);
852
853        // eval pvs size
854        const int pvsSize = tData.mPvs;
855
856        // create unique ids for pvs heuristics
857        GenerateUniqueIdsForPvs();
858
859        // this is the main ray classification loop!
860        for(RayInfoContainer::iterator ri = tData.mRays->begin();
861                        ri != tData.mRays->end(); ++ ri)
862        {
863                if (!(*ri).mRay->IsActive())
864                        continue;
865
866                // determine the side of this ray with respect to the plane
867                float t;
868                int side = (*ri).ComputeRayIntersection(axis, position, t);
869                       
870                if (side <= 0)
871                        ++ raysBack;
872
873                if (side >= 0)
874                        ++ raysFront;
875
876                AddObjToPvs((*ri).mRay->mTerminationObject, side, pvsBack, pvsFront);
877        }
878
879        //-- only one of these options should be one
880
881        if (0) //-- only pvs
882        {
883                const float sum = float(pvsBack + pvsFront);
884                const float oldCost = (float)pvsSize;
885
886                return sum / oldCost;
887        }
888
889        //-- pvs + probability heuristics
890        float pBack, pFront, pOverall;
891
892        if (0)
893        {
894                // box length substitute for probability
895                const float minBox = box.Min(axis);
896                const float maxBox = box.Max(axis);
897
898                pBack = position - minBox;
899                pFront = maxBox - position;
900                pOverall = maxBox - minBox;
901        }
902
903        if (1) //-- area substitute for probability
904        {
905               
906                const bool useMidSplit = true;
907                //const bool useMidSplit = false;
908                       
909                pOverall = box.SurfaceArea();
910                       
911                if (!useMidSplit)
912                {
913                        Vector3 pos = box.Max(); pos[axis] = position;
914                        pBack = AxisAlignedBox3(box.Min(), pos).SurfaceArea();
915
916                        pos = box.Min(); pos[axis] = position;
917                        pFront = AxisAlignedBox3(pos, box.Max()).SurfaceArea();
918                }
919                else
920                {
921                        //-- simplified computation for mid split
922                        const int axis2 = (axis + 1) % 3;
923                        const int axis3 = (axis + 2) % 3;
924
925                        const float faceArea =
926                                (box.Max(axis2) - box.Min(axis2)) *
927                                (box.Max(axis3) - box.Min(axis3));
928
929                        pBack = pFront = pOverall * 0.5f + faceArea;
930                }
931        }
932
933        //-- ray density substitute for probability
934        if (0)
935        {
936                pBack = (float)raysBack;
937                pFront = (float)raysFront;
938                pOverall = (float)tData.mRays->size();
939        }
940
941        //Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
942        //Debug << pFront << " " << pBack << " " << pOverall << endl;
943
944        // float sum = raysBack*(position - minBox) + raysFront*(maxBox - position);
945        const float newCost = pvsBack * pBack + pvsFront * pFront;
946        //  float oldCost = leaf->mRays.size();
947        const float oldCost = (float)pvsSize * pOverall;
948
949        return  (mCtDivCi + newCost) / oldCost;
950}
951
952
953
954bool VspBspTree::SelectPlane(Plane3 &plane,
955                                                         BspLeaf *leaf,
956                                                         VspBspTraversalData &data)
957{
958        // simplest strategy: just take next polygon
959        if (mSplitPlaneStrategy & RANDOM_POLYGON)
960        {
961        if (!data.mPolygons->empty())
962                {
963                        const int randIdx = (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
964                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
965
966                        plane = nextPoly->GetSupportingPlane();
967                        return true;
968                }
969        }
970
971        // use heuristics to find appropriate plane
972        return SelectPlaneHeuristics(plane, leaf, data);
973}
974
975
976Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
977{
978        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
979
980        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
981        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
982
983        const Vector3 pt = (maxPt + minPt) * 0.5;
984        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
985
986        return Plane3(normal, pt);
987}
988
989
990Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
991{
992        Vector3 pt[3];
993
994        int idx[3];
995        int cmaxT = 0;
996        int cminT = 0;
997        bool chooseMin = false;
998
999        for (int j = 0; j < 3; ++ j)
1000        {
1001                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1002
1003                if (idx[j] >= (int)rays.size())
1004                {
1005                        idx[j] -= (int)rays.size();
1006
1007                        chooseMin = (cminT < 2);
1008                }
1009                else
1010                        chooseMin = (cmaxT < 2);
1011
1012                RayInfo rayInf = rays[idx[j]];
1013                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1014        }
1015
1016        return Plane3(pt[0], pt[1], pt[2]);
1017}
1018
1019Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1020{
1021        Vector3 pt[3];
1022
1023        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1024        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1025
1026        // check if rays different
1027        if (idx1 == idx2)
1028                idx2 = (idx2 + 1) % (int)rays.size();
1029
1030        const RayInfo ray1 = rays[idx1];
1031        const RayInfo ray2 = rays[idx2];
1032
1033        // normal vector of the plane parallel to both lines
1034        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1035
1036        // vector from line 1 to line 2
1037        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1038
1039        // project vector on normal to get distance
1040        const float dist = DotProd(vd, norm);
1041
1042        // point on plane lies halfway between the two planes
1043        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1044
1045        return Plane3(norm, planePt);
1046}
1047
1048
1049bool VspBspTree::SelectPlaneHeuristics(Plane3 &bestPlane,
1050                                                                           BspLeaf *leaf,
1051                                                                           VspBspTraversalData &data)
1052{
1053        float lowestCost = MAX_FLOAT;
1054        // intermediate plane
1055        Plane3 plane;
1056        bool useAxisAlignedPlane = false;
1057
1058        const int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1059        int maxIdx = (int)data.mPolygons->size();
1060
1061        float candidateCost;
1062
1063        for (int i = 0; i < limit; ++ i)
1064        {
1065                //-- assure that no index is taken twice
1066                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1067                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1068
1069                // swap candidate to the end to avoid testing same plane
1070                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1071
1072                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1073
1074                // evaluate current candidate
1075                candidateCost = SplitPlaneCost(poly->GetSupportingPlane(), data);
1076
1077                if (candidateCost < lowestCost)
1078                {
1079                        bestPlane = poly->GetSupportingPlane();
1080                        lowestCost = candidateCost;
1081                }
1082        }
1083
1084        //-- axis aligned splits
1085        int axis;
1086        float position;
1087        int raysBack;
1088        int raysFront;
1089        int pvsFront;
1090        int pvsBack;
1091
1092        candidateCost = SelectAxisAlignedPlane(plane,
1093                                                                                   data,
1094                                                                                   axis,
1095                                                                                   position,
1096                                                                                   raysBack,
1097                                                                                   raysFront,
1098                                                                                   pvsFront,
1099                                                                                   pvsBack);
1100
1101        if (candidateCost < lowestCost)
1102        {       
1103                if (!useAxisAlignedPlane)
1104                {
1105                        useAxisAlignedPlane = true;
1106                        //if (data.mPolygons->size() > 0)
1107                        //      Debug << "haha" << endl;
1108                        //! error also computed if cost ratio is missed
1109                        ++ mStat.splits[axis];
1110                }
1111
1112                bestPlane = plane;
1113                lowestCost = candidateCost;
1114        }
1115
1116#ifdef _DEBUG
1117        Debug << "plane lowest cost: " << lowestCost << endl;
1118#endif
1119
1120        // cost ratio miss
1121        if (lowestCost > mTermMaxCostRatio)
1122                return false;
1123
1124        return true;
1125}
1126
1127
1128inline void VspBspTree::GenerateUniqueIdsForPvs()
1129{
1130        Intersectable::NewMail(); sBackId = ViewCell::sMailId;
1131        Intersectable::NewMail(); sFrontId = ViewCell::sMailId;
1132        Intersectable::NewMail(); sFrontAndBackId = ViewCell::sMailId;
1133}
1134
1135
1136float VspBspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1137                                                                 const VspBspTraversalData &data) const
1138{
1139        float cost = 0;
1140
1141        float sumBalancedRays = 0;
1142        float sumRaySplits = 0;
1143
1144        int frontPvs = 0;
1145        int backPvs = 0;
1146
1147        // probability that view point lies in child
1148        float pOverall = 0;
1149        float pFront = 0;
1150        float pBack = 0;
1151
1152        if (mSplitPlaneStrategy & PVS)
1153        {
1154                // create unique ids for pvs heuristics
1155                GenerateUniqueIdsForPvs();
1156
1157                if (mPvsUseArea) // use front and back cell areas to approximate volume
1158                {
1159                        // construct child geometry with regard to the candidate split plane
1160                        BspNodeGeometry frontCell;
1161                        BspNodeGeometry backCell;
1162
1163                        data.mGeometry->SplitGeometry(frontCell,
1164                                                                                  backCell,
1165                                                                                  candidatePlane,
1166                                                                                  mBox,
1167                                                                                  mEpsilon);
1168
1169                        pFront = frontCell.GetArea();
1170                        pBack = backCell.GetArea();
1171
1172                        pOverall = data.mArea;
1173                }
1174        }
1175
1176        int limit;
1177        bool useRand;
1178
1179        // choose test rays randomly if too much
1180        if ((int)data.mRays->size() > mMaxTests)
1181        {
1182                useRand = true;
1183                limit = mMaxTests;
1184        }
1185        else
1186        {
1187                useRand = false;
1188                limit = (int)data.mRays->size();
1189        }
1190
1191        for (int i = 0; i < limit; ++ i)
1192        {
1193                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1194                RayInfo rayInf = (*data.mRays)[testIdx];
1195
1196                VssRay *ray = rayInf.mRay;
1197                float t;
1198                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1199
1200                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1201                {
1202                        sumBalancedRays += cf;
1203                }
1204
1205                if (mSplitPlaneStrategy & BALANCED_RAYS)
1206                {
1207                        if (cf == 0)
1208                                ++ sumRaySplits;
1209                }
1210
1211                if (mSplitPlaneStrategy & PVS)
1212                {
1213                        // in case the ray intersects an object
1214                        // assure that we only count the object
1215                        // once for the front and once for the back side of the plane
1216                        AddObjToPvs(ray->mTerminationObject, cf, frontPvs, backPvs);
1217                        AddObjToPvs(ray->mOriginObject, cf, frontPvs, backPvs);
1218
1219                        // use number of rays to approximate volume
1220                        if (!mPvsUseArea)
1221                        {
1222                                pOverall = (float)data.mRays->size();
1223
1224                                if (cf >= 0)
1225                                        ++ pFront;
1226                                if (cf <= 0)
1227                                        ++ pBack;
1228                        }
1229                }
1230        }
1231
1232        const float raysSize = (float)data.mRays->size() + Limits::Small;
1233
1234        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1235                cost += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1236
1237        if (mSplitPlaneStrategy & BALANCED_RAYS)
1238                cost += mBalancedRaysFactor * fabs(sumBalancedRays) / raysSize;
1239
1240        // pvs criterium
1241        if (mSplitPlaneStrategy & PVS)
1242        {
1243                const float oldCost = pOverall * (float)data.mPvs + Limits::Small;
1244                cost += mPvsFactor * (frontPvs * pFront + backPvs * pBack) / oldCost;
1245
1246                //cost += mPvsFactor * 0.5 * (frontPvs * pFront + backPvs * pBack) / oldCost;
1247                //Debug << "new cost: " << cost << " over" << frontPvs * pFront + backPvs * pBack << " old cost " << oldCost << endl;
1248
1249                if (0) // give penalty to unbalanced split
1250                        if (((pFront * 0.2 + Limits::Small) > pBack) ||
1251                                (pFront < (pBack * 0.2 + Limits::Small)))
1252                                        cost += 0.5;
1253        }
1254
1255#ifdef _DEBUG
1256        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
1257                  << " frontpvs: " << frontPvs << " pFront: " << pFront
1258                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
1259#endif
1260
1261        // normalize cost by sum of linear factors
1262        return cost / (float)mCostNormalizer;
1263}
1264
1265void VspBspTree::AddObjToPvs(Intersectable *obj,
1266                                                         const int cf,
1267                                                         int &frontPvs,
1268                                                         int &backPvs) const
1269{
1270        if (!obj)
1271                return;
1272        // TODO: does this really belong to no pvs?
1273        //if (cf == Ray::COINCIDENT) return;
1274
1275        // object belongs to both PVS
1276        if (cf >= 0)
1277        {
1278                if ((obj->mMailbox != sFrontId) &&
1279                        (obj->mMailbox != sFrontAndBackId))
1280                {
1281                        ++ frontPvs;
1282
1283                        if (obj->mMailbox == sBackId)
1284                                obj->mMailbox = sFrontAndBackId;
1285                        else
1286                                obj->mMailbox = sFrontId;
1287                }
1288        }
1289
1290        if (cf <= 0)
1291        {
1292                if ((obj->mMailbox != sBackId) &&
1293                        (obj->mMailbox != sFrontAndBackId))
1294                {
1295                        ++ backPvs;
1296
1297                        if (obj->mMailbox == sFrontId)
1298                                obj->mMailbox = sFrontAndBackId;
1299                        else
1300                                obj->mMailbox = sBackId;
1301                }
1302        }
1303}
1304
1305
1306void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves) const
1307{
1308        stack<BspNode *> nodeStack;
1309        nodeStack.push(mRoot);
1310
1311        while (!nodeStack.empty())
1312        {
1313                BspNode *node = nodeStack.top();
1314                nodeStack.pop();
1315               
1316                if (node->IsLeaf())
1317                {
1318                        // test if this leaf is in valid view space
1319                        if (node->TreeValid())
1320                        {
1321                                BspLeaf *leaf = (BspLeaf *)node;
1322                                leaves.push_back(leaf);
1323                        }
1324                }
1325                else
1326                {
1327                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1328
1329                        nodeStack.push(interior->GetBack());
1330                        nodeStack.push(interior->GetFront());
1331                }
1332        }
1333}
1334
1335
1336AxisAlignedBox3 VspBspTree::GetBoundingBox() const
1337{
1338        return mBox;
1339}
1340
1341
1342BspNode *VspBspTree::GetRoot() const
1343{
1344        return mRoot;
1345}
1346
1347
1348BspViewCell *VspBspTree::GetOutOfBoundsCell() const
1349{
1350        return mOutOfBoundsCell;
1351}
1352
1353
1354void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
1355{
1356        // the node became a leaf -> evaluate stats for leafs
1357        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1358
1359        // store maximal and minimal depth
1360        if (data.mDepth > mStat.maxDepth)
1361                mStat.maxDepth = data.mDepth;
1362
1363        if (data.mPvs > mStat.maxPvs)
1364                mStat.maxPvs = data.mPvs;
1365        if (data.mDepth < mStat.minDepth)
1366                mStat.minDepth = data.mDepth;
1367        if (data.mDepth >= mTermMaxDepth)
1368                ++ mStat.maxDepthNodes;
1369
1370        if (data.mPvs < mTermMinPvs)
1371                ++ mStat.minPvsNodes;
1372
1373        if ((int)data.mRays->size() < mTermMinRays)
1374                ++ mStat.minRaysNodes;
1375
1376        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1377                ++ mStat.maxRayContribNodes;
1378
1379        if (data.mArea <= mTermMinArea)
1380        {
1381                //Debug << "area: " << data.mArea / mBox.SurfaceArea() << " min area: " << mTermMinArea / mBox.SurfaceArea() << endl;
1382                ++ mStat.minAreaNodes;
1383        }
1384        // accumulate depth to compute average depth
1385        mStat.accumDepth += data.mDepth;
1386
1387#ifdef _DEBUG
1388        Debug << "BSP stats: "
1389                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1390                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1391                  << "Area: " << data.mArea << " (min: " << mTermMinArea << "), "
1392                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1393                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1394                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1395#endif
1396}
1397
1398int VspBspTree::CastRay(Ray &ray)
1399{
1400        int hits = 0;
1401
1402        stack<BspRayTraversalData> tStack;
1403
1404        float maxt, mint;
1405
1406        if (!mBox.GetRaySegment(ray, mint, maxt))
1407                return 0;
1408
1409        Intersectable::NewMail();
1410
1411        Vector3 entp = ray.Extrap(mint);
1412        Vector3 extp = ray.Extrap(maxt);
1413
1414        BspNode *node = mRoot;
1415        BspNode *farChild = NULL;
1416
1417        while (1)
1418        {
1419                if (!node->IsLeaf())
1420                {
1421                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1422
1423                        Plane3 splitPlane = in->GetPlane();
1424                        const int entSide = splitPlane.Side(entp);
1425                        const int extSide = splitPlane.Side(extp);
1426
1427                        if (entSide < 0)
1428                        {
1429                                node = in->GetBack();
1430
1431                                if(extSide <= 0) // plane does not split ray => no far child
1432                                        continue;
1433
1434                                farChild = in->GetFront(); // plane splits ray
1435
1436                        } else if (entSide > 0)
1437                        {
1438                                node = in->GetFront();
1439
1440                                if (extSide >= 0) // plane does not split ray => no far child
1441                                        continue;
1442
1443                                farChild = in->GetBack(); // plane splits ray
1444                        }
1445                        else // ray and plane are coincident
1446                        {
1447                                // WHAT TO DO IN THIS CASE ?
1448                                //break;
1449                                node = in->GetFront();
1450                                continue;
1451                        }
1452
1453                        // push data for far child
1454                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
1455
1456                        // find intersection of ray segment with plane
1457                        float t;
1458                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
1459                        maxt *= t;
1460
1461                } else // reached leaf => intersection with view cell
1462                {
1463                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1464
1465                        if (!leaf->GetViewCell()->Mailed())
1466                        {
1467                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
1468                                leaf->GetViewCell()->Mail();
1469                                ++ hits;
1470                        }
1471
1472                        //-- fetch the next far child from the stack
1473                        if (tStack.empty())
1474                                break;
1475
1476                        entp = extp;
1477                        mint = maxt; // NOTE: need this?
1478
1479                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1480                                break;
1481
1482                        BspRayTraversalData &s = tStack.top();
1483
1484                        node = s.mNode;
1485                        extp = s.mExitPoint;
1486                        maxt = s.mMaxT;
1487
1488                        tStack.pop();
1489                }
1490        }
1491
1492        return hits;
1493}
1494
1495bool VspBspTree::Export(const string filename)
1496{
1497        Exporter *exporter = Exporter::GetExporter(filename);
1498
1499        if (exporter)
1500        {
1501                //exporter->ExportVspBspTree(*this);
1502                return true;
1503        }
1504
1505        return false;
1506}
1507
1508void VspBspTree::CollectViewCells(ViewCellContainer &viewCells) const
1509{
1510  stack<BspNode *> nodeStack;
1511
1512  if (!mRoot)
1513        return;
1514
1515  nodeStack.push(mRoot);
1516 
1517  ViewCell::NewMail();
1518
1519  while (!nodeStack.empty())
1520  {
1521          BspNode *node = nodeStack.top();
1522          nodeStack.pop();
1523         
1524          if (node->IsLeaf() && !mShowInvalidSpace && node->TreeValid())
1525          {
1526                  ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1527                 
1528                  if (!viewCell->Mailed())
1529                  {
1530                          viewCell->Mail();
1531                          viewCells.push_back(viewCell);
1532                  }
1533          }
1534          else
1535          {
1536                  BspInterior *interior = dynamic_cast<BspInterior *>(node);
1537                 
1538                  nodeStack.push(interior->GetFront());
1539                  nodeStack.push(interior->GetBack());
1540          }
1541  }
1542}
1543
1544
1545float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
1546{
1547        float len = 0;
1548
1549        RayInfoContainer::const_iterator it, it_end = rays.end();
1550
1551        for (it = rays.begin(); it != it_end; ++ it)
1552                len += (*it).SegmentLength();
1553
1554        return len;
1555}
1556
1557
1558int VspBspTree::SplitRays(const Plane3 &plane,
1559                                                  RayInfoContainer &rays,
1560                                                  RayInfoContainer &frontRays,
1561                                                  RayInfoContainer &backRays)
1562{
1563        int splits = 0;
1564
1565        while (!rays.empty())
1566        {
1567                RayInfo bRay = rays.back();
1568                rays.pop_back();
1569
1570                VssRay *ray = bRay.mRay;
1571                float t;
1572
1573                // get classification and receive new t
1574                const int cf = bRay.ComputeRayIntersection(plane, t);
1575
1576                switch (cf)
1577                {
1578                case -1:
1579                        backRays.push_back(bRay);
1580                        break;
1581                case 1:
1582                        frontRays.push_back(bRay);
1583                        break;
1584                case 0:
1585                        {
1586                                //-- split ray
1587                                //-- test if start point behind or in front of plane
1588                                const int side = plane.Side(bRay.ExtrapOrigin());
1589
1590                                if (side <= 0)
1591                                {
1592                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1593                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1594                                }
1595                                else
1596                                {
1597                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1598                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1599                                }
1600                        }
1601                        break;
1602                default:
1603                        Debug << "Should not come here" << endl;
1604                        break;
1605                }
1606        }
1607
1608        return splits;
1609}
1610
1611
1612void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
1613{
1614        BspNode *lastNode;
1615
1616        do
1617        {
1618                lastNode = n;
1619
1620                // want to get planes defining geometry of this node => don't take
1621                // split plane of node itself
1622                n = n->GetParent();
1623
1624                if (n)
1625                {
1626                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
1627                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
1628
1629            if (interior->GetFront() != lastNode)
1630                                halfSpace.ReverseOrientation();
1631
1632                        halfSpaces.push_back(halfSpace);
1633                }
1634        }
1635        while (n);
1636}
1637
1638
1639void VspBspTree::ConstructGeometry(BspNode *n,
1640                                                                   BspNodeGeometry &cell) const
1641{
1642        ConstructGeometry(n, cell.mPolys);
1643}
1644
1645
1646void VspBspTree::ConstructGeometry(BspNode *n,
1647                                                                   PolygonContainer &cell) const
1648{
1649        vector<Plane3> halfSpaces;
1650        ExtractHalfSpaces(n, halfSpaces);
1651
1652        PolygonContainer candidatePolys;
1653
1654        // bounded planes are added to the polygons (reverse polygons
1655        // as they have to be outfacing
1656        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
1657        {
1658                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
1659
1660                if (p->Valid(mEpsilon))
1661                {
1662                        candidatePolys.push_back(p->CreateReversePolygon());
1663                        DEL_PTR(p);
1664                }
1665        }
1666
1667        // add faces of bounding box (also could be faces of the cell)
1668        for (int i = 0; i < 6; ++ i)
1669        {
1670                VertexContainer vertices;
1671
1672                for (int j = 0; j < 4; ++ j)
1673                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
1674
1675                candidatePolys.push_back(new Polygon3(vertices));
1676        }
1677
1678        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
1679        {
1680                // polygon is split by all other planes
1681                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
1682                {
1683                        if (i == j) // polygon and plane are coincident
1684                                continue;
1685
1686                        VertexContainer splitPts;
1687                        Polygon3 *frontPoly, *backPoly;
1688
1689                        const int cf =
1690                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
1691                                                                                                 mEpsilon);
1692
1693                        switch (cf)
1694                        {
1695                                case Polygon3::SPLIT:
1696                                        frontPoly = new Polygon3();
1697                                        backPoly = new Polygon3();
1698
1699                                        candidatePolys[i]->Split(halfSpaces[j],
1700                                                                                         *frontPoly,
1701                                                                                         *backPoly,
1702                                                                                         mEpsilon);
1703
1704                                        DEL_PTR(candidatePolys[i]);
1705
1706                                        if (frontPoly->Valid(mEpsilon))
1707                                                candidatePolys[i] = frontPoly;
1708                                        else
1709                                                DEL_PTR(frontPoly);
1710
1711                                        DEL_PTR(backPoly);
1712                                        break;
1713                                case Polygon3::BACK_SIDE:
1714                                        DEL_PTR(candidatePolys[i]);
1715                                        break;
1716                                // just take polygon as it is
1717                                case Polygon3::FRONT_SIDE:
1718                                case Polygon3::COINCIDENT:
1719                                default:
1720                                        break;
1721                        }
1722                }
1723
1724                if (candidatePolys[i])
1725                        cell.push_back(candidatePolys[i]);
1726        }
1727}
1728
1729
1730void VspBspTree::ConstructGeometry(BspViewCell *vc,
1731                                                                   PolygonContainer &vcGeom) const
1732{
1733        vector<BspLeaf *> leaves = vc->mLeaves;
1734        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
1735
1736        for (it = leaves.begin(); it != it_end; ++ it)
1737                ConstructGeometry(*it, vcGeom);
1738}
1739
1740
1741int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
1742                                                   const bool onlyUnmailed) const
1743{
1744        PolygonContainer cell;
1745        ConstructGeometry(n, cell);
1746
1747        stack<BspNode *> nodeStack;
1748        nodeStack.push(mRoot);
1749
1750        // planes needed to verify that we found neighbor leaf.
1751        vector<Plane3> halfSpaces;
1752        ExtractHalfSpaces(n, halfSpaces);
1753
1754        while (!nodeStack.empty())
1755        {
1756                BspNode *node = nodeStack.top();
1757                nodeStack.pop();
1758
1759                if (node->IsLeaf())
1760                {       // test if this leaf is in valid view space
1761            if (node->TreeValid() &&
1762                                node != n &&
1763                                (!onlyUnmailed || !node->Mailed()))
1764                        {
1765                                // test all planes of current node if candidate really
1766                                // is neighbour
1767                                PolygonContainer neighborCandidate;
1768                                ConstructGeometry(node, neighborCandidate);
1769
1770                                bool isAdjacent = true;
1771                                for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
1772                                {
1773                                        const int cf =
1774                                                Polygon3::ClassifyPlane(neighborCandidate,
1775                                                                                                halfSpaces[i],
1776                                                                                                mEpsilon);
1777
1778                                        if (cf == Polygon3::BACK_SIDE)
1779                                                isAdjacent = false;
1780                                }
1781
1782                                if (isAdjacent)
1783                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
1784
1785                                CLEAR_CONTAINER(neighborCandidate);
1786                        }
1787                }
1788                else
1789                {
1790                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1791
1792                        const int cf = Polygon3::ClassifyPlane(cell,
1793                                                                                                   interior->GetPlane(),
1794                                                                                                   mEpsilon);
1795
1796                        if (cf == Polygon3::FRONT_SIDE)
1797                                nodeStack.push(interior->GetFront());
1798                        else
1799                                if (cf == Polygon3::BACK_SIDE)
1800                                        nodeStack.push(interior->GetBack());
1801                                else
1802                                {
1803                                        // random decision
1804                                        nodeStack.push(interior->GetBack());
1805                                        nodeStack.push(interior->GetFront());
1806                                }
1807                }
1808        }
1809
1810        CLEAR_CONTAINER(cell);
1811        return (int)neighbors.size();
1812}
1813
1814
1815BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
1816{
1817    stack<BspNode *> nodeStack;
1818        nodeStack.push(mRoot);
1819
1820        int mask = rand();
1821
1822        while (!nodeStack.empty())
1823        {
1824                BspNode *node = nodeStack.top();
1825                nodeStack.pop();
1826
1827                if (node->IsLeaf())
1828                {
1829                        return dynamic_cast<BspLeaf *>(node);
1830                }
1831                else
1832                {
1833                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1834
1835                        BspNode *next;
1836
1837                        PolygonContainer cell;
1838
1839                        // todo: not very efficient: constructs full cell everytime
1840                        ConstructGeometry(interior, cell);
1841
1842                        const int cf = Polygon3::ClassifyPlane(cell, halfspace, mEpsilon);
1843
1844                        if (cf == Polygon3::BACK_SIDE)
1845                                next = interior->GetFront();
1846                        else
1847                                if (cf == Polygon3::FRONT_SIDE)
1848                                        next = interior->GetFront();
1849                        else
1850                        {
1851                                // random decision
1852                                if (mask & 1)
1853                                        next = interior->GetBack();
1854                                else
1855                                        next = interior->GetFront();
1856                                mask = mask >> 1;
1857                        }
1858
1859                        nodeStack.push(next);
1860                }
1861        }
1862
1863        return NULL;
1864}
1865
1866BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
1867{
1868        stack<BspNode *> nodeStack;
1869
1870        nodeStack.push(mRoot);
1871
1872        int mask = rand();
1873
1874        while (!nodeStack.empty())
1875        {
1876                BspNode *node = nodeStack.top();
1877                nodeStack.pop();
1878
1879                if (node->IsLeaf())
1880                {
1881                        if ( (!onlyUnmailed || !node->Mailed()) )
1882                                return dynamic_cast<BspLeaf *>(node);
1883                }
1884                else
1885                {
1886                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1887
1888                        // random decision
1889                        if (mask & 1)
1890                                nodeStack.push(interior->GetBack());
1891                        else
1892                                nodeStack.push(interior->GetFront());
1893
1894                        mask = mask >> 1;
1895                }
1896        }
1897
1898        return NULL;
1899}
1900
1901int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
1902{
1903        int pvsSize = 0;
1904
1905        RayInfoContainer::const_iterator rit, rit_end = rays.end();
1906
1907        Intersectable::NewMail();
1908
1909        for (rit = rays.begin(); rit != rays.end(); ++ rit)
1910        {
1911                VssRay *ray = (*rit).mRay;
1912
1913                if (ray->mOriginObject)
1914                {
1915                        if (!ray->mOriginObject->Mailed())
1916                        {
1917                                ray->mOriginObject->Mail();
1918                                ++ pvsSize;
1919                        }
1920                }
1921                if (ray->mTerminationObject)
1922                {
1923                        if (!ray->mTerminationObject->Mailed())
1924                        {
1925                                ray->mTerminationObject->Mail();
1926                                ++ pvsSize;
1927                        }
1928                }
1929        }
1930
1931        return pvsSize;
1932}
1933
1934float VspBspTree::GetEpsilon() const
1935{
1936        return mEpsilon;
1937}
1938
1939
1940int VspBspTree::SplitPolygons(const Plane3 &plane,
1941                                                          PolygonContainer &polys,
1942                                                          PolygonContainer &frontPolys,
1943                                                          PolygonContainer &backPolys,
1944                                                          PolygonContainer &coincident) const
1945{
1946        int splits = 0;
1947
1948        while (!polys.empty())
1949        {
1950                Polygon3 *poly = polys.back();
1951                polys.pop_back();
1952
1953                // classify polygon
1954                const int cf = poly->ClassifyPlane(plane, mEpsilon);
1955
1956                switch (cf)
1957                {
1958                        case Polygon3::COINCIDENT:
1959                                coincident.push_back(poly);
1960                                break;
1961                        case Polygon3::FRONT_SIDE:
1962                                frontPolys.push_back(poly);
1963                                break;
1964                        case Polygon3::BACK_SIDE:
1965                                backPolys.push_back(poly);
1966                                break;
1967                        case Polygon3::SPLIT:
1968                                backPolys.push_back(poly);
1969                                frontPolys.push_back(poly);
1970                                ++ splits;
1971                                break;
1972                        default:
1973                Debug << "SHOULD NEVER COME HERE\n";
1974                                break;
1975                }
1976        }
1977
1978        return splits;
1979}
1980
1981
1982int VspBspTree::CastLineSegment(const Vector3 &origin,
1983                                                                const Vector3 &termination,
1984                                                                vector<ViewCell *> &viewcells)
1985{
1986        int hits = 0;
1987        stack<BspRayTraversalData> tStack;
1988
1989        float mint = 0.0f, maxt = 1.0f;
1990
1991        Intersectable::NewMail();
1992
1993        Vector3 entp = origin;
1994        Vector3 extp = termination;
1995
1996        BspNode *node = mRoot;
1997        BspNode *farChild = NULL;
1998
1999        float t;
2000        while (1)
2001        {
2002                if (!node->IsLeaf())
2003                {
2004                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2005
2006                        Plane3 splitPlane = in->GetPlane();
2007                       
2008                        const int entSide = splitPlane.Side(entp);
2009                        const int extSide = splitPlane.Side(extp);
2010
2011                        if (entSide < 0)
2012                        {
2013                                node = in->GetBack();
2014                                // plane does not split ray => no far child
2015                                if (extSide <= 0)
2016                                        continue;
2017
2018                                farChild = in->GetFront(); // plane splits ray
2019                        }
2020                        else if (entSide > 0)
2021                        {
2022                                node = in->GetFront();
2023
2024                                if (extSide >= 0) // plane does not split ray => no far child
2025                                        continue;
2026
2027                                farChild = in->GetBack(); // plane splits ray
2028                        }
2029                        else // ray end point on plane
2030                        {       // NOTE: what to do if ray is coincident with plane?
2031                                if (extSide < 0)
2032                                        node = in->GetBack();
2033                                else
2034                                        node = in->GetFront();
2035                                                               
2036                                continue; // no far child
2037                        }
2038
2039                        // push data for far child
2040                        tStack.push(BspRayTraversalData(farChild, extp));
2041
2042                        // find intersection of ray segment with plane
2043                        extp = splitPlane.FindIntersection(origin, extp, &t);
2044                }
2045                else
2046                {
2047                        // reached leaf => intersection with view cell
2048                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2049
2050                        if (!leaf->GetViewCell()->Mailed())
2051                        {
2052                                viewcells.push_back(leaf->GetViewCell());
2053                                leaf->GetViewCell()->Mail();
2054                                ++ hits;
2055                        }
2056
2057                        //-- fetch the next far child from the stack
2058                        if (tStack.empty())
2059                                break;
2060
2061                        entp = extp;
2062                       
2063                        BspRayTraversalData &s = tStack.top();
2064
2065                        node = s.mNode;
2066                        extp = s.mExitPoint;
2067
2068                        tStack.pop();
2069                }
2070        }
2071
2072        return hits;
2073}
2074
2075int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
2076{
2077        std::deque<BspNode *> path1;
2078        BspNode *p1 = n1;
2079
2080        // create path from node 1 to root
2081        while (p1)
2082        {
2083                if (p1 == n2) // second node on path
2084                        return (int)path1.size();
2085
2086                path1.push_front(p1);
2087                p1 = p1->GetParent();
2088        }
2089
2090        int depth = n2->GetDepth();
2091        int d = depth;
2092
2093        BspNode *p2 = n2;
2094
2095        // compare with same depth
2096        while (1)
2097        {
2098                if ((d < (int)path1.size()) && (p2 == path1[d]))
2099                        return (depth - d) + ((int)path1.size() - 1 - d);
2100
2101                -- d;
2102                p2 = p2->GetParent();
2103        }
2104
2105        return 0; // never come here
2106}
2107
2108BspNode *VspBspTree::CollapseTree(BspNode *node)
2109{
2110        if (node->IsLeaf())
2111                return node;
2112
2113        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2114
2115        BspNode *front = CollapseTree(interior->GetFront());
2116        BspNode *back = CollapseTree(interior->GetBack());
2117
2118        if (front->IsLeaf() && back->IsLeaf())
2119        {
2120                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
2121                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
2122
2123                //-- collapse tree
2124                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
2125                {
2126                        BspViewCell *vc = frontLeaf->GetViewCell();
2127
2128                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
2129                        leaf->SetTreeValid(frontLeaf->TreeValid());
2130
2131                        // replace a link from node's parent
2132                        if (leaf->GetParent())
2133                                leaf->GetParent()->ReplaceChildLink(node, leaf);
2134
2135                        delete interior;
2136
2137                        return leaf;
2138                }
2139        }
2140
2141        return node;
2142}
2143
2144
2145void VspBspTree::CollapseTree()
2146{
2147        CollapseTree(mRoot);
2148        // revalidate leaves
2149        RepairVcLeafLists();
2150}
2151
2152
2153void VspBspTree::RepairVcLeafLists()
2154{
2155        // list not valid anymore => clear
2156        stack<BspNode *> nodeStack;
2157        nodeStack.push(mRoot);
2158
2159        ViewCell::NewMail();
2160
2161        while (!nodeStack.empty())
2162        {
2163                BspNode *node = nodeStack.top();
2164                nodeStack.pop();
2165
2166                if (node->IsLeaf())
2167                {
2168                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2169
2170                        BspViewCell *viewCell = leaf->GetViewCell();
2171
2172                        if (!viewCell->Mailed())
2173                        {
2174                                viewCell->mLeaves.clear();
2175                                viewCell->Mail();
2176                        }
2177
2178                        viewCell->mLeaves.push_back(leaf);
2179                }
2180                else
2181                {
2182                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2183
2184                        nodeStack.push(interior->GetFront());
2185                        nodeStack.push(interior->GetBack());
2186                }
2187        }
2188}
2189
2190
2191bool VspBspTree::MergeViewCells(BspLeaf *l1, BspLeaf *l2) const
2192{
2193        //-- change pointer to view cells of all leaves associated
2194        //-- with the previous view cells
2195        BspViewCell *fVc = l1->GetViewCell();
2196        BspViewCell *bVc = l2->GetViewCell();
2197
2198        BspViewCell *vc = dynamic_cast<BspViewCell *>(
2199                mViewCellsManager->MergeViewCells(*fVc, *bVc));
2200
2201        // if merge was unsuccessful
2202        if (!vc) return false;
2203
2204        // set new size of view cell
2205        vc->SetArea(fVc->GetArea() + bVc->GetArea());
2206
2207        vector<BspLeaf *> fLeaves = fVc->mLeaves;
2208        vector<BspLeaf *> bLeaves = bVc->mLeaves;
2209
2210        vector<BspLeaf *>::const_iterator it;
2211
2212        //-- change view cells of all the other leaves the view cell belongs to
2213        for (it = fLeaves.begin(); it != fLeaves.end(); ++ it)
2214        {
2215                (*it)->SetViewCell(vc);
2216                vc->mLeaves.push_back(*it);
2217        }
2218
2219        for (it = bLeaves.begin(); it != bLeaves.end(); ++ it)
2220        {
2221                (*it)->SetViewCell(vc);
2222                vc->mLeaves.push_back(*it);
2223        }
2224
2225        vc->Mail();
2226
2227        // clean up old view cells
2228        DEL_PTR(fVc);
2229        DEL_PTR(bVc);
2230
2231        return true;
2232}
2233
2234
2235void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
2236{
2237        mViewCellsManager = vcm;
2238}
2239
2240
2241int VspBspTree::CollectMergeCandidates()
2242{
2243        vector<BspLeaf *> leaves;
2244
2245        // collect the leaves, e.g., the "voxels" that will build the view cells
2246        CollectLeaves(leaves);
2247        BspLeaf::NewMail();
2248
2249        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2250
2251        // find merge candidates and push them into queue
2252        for (it = leaves.begin(); it != it_end; ++ it)
2253        {
2254                BspLeaf *leaf = *it;
2255               
2256                /// create leaf pvs (needed for post processing
2257                leaf->mPvs = new ObjectPvs(leaf->GetViewCell()->GetPvs());
2258
2259                BspMergeCandidate::sOverallCost +=
2260                        leaf->mArea * leaf->mPvs->GetSize();
2261
2262                // the same leaves must not be part of two merge candidates
2263                leaf->Mail();
2264                vector<BspLeaf *> neighbors;
2265                FindNeighbors(leaf, neighbors, true);
2266
2267                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2268
2269                // TODO: test if at least one ray goes from one leaf to the other
2270                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2271                {                       
2272                        mMergeQueue.push(BspMergeCandidate(leaf, *nit));
2273                }
2274        }
2275
2276        return (int)leaves.size();
2277}
2278
2279
2280int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays)
2281{
2282        vector<BspRay *> bspRays;
2283
2284        ConstructBspRays(bspRays, rays);
2285        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2286
2287        vector<BspIntersection>::const_iterator iit;
2288
2289        int leaves = 0;
2290       
2291        BspLeaf::NewMail();
2292
2293        for (int i = 0; i < (int)bspRays.size(); ++ i)
2294        { 
2295                BspRay *ray = bspRays[i];
2296         
2297                // traverse leaves stored in the rays and compare and
2298                // merge consecutive leaves (i.e., the neighbors in the tree)
2299                if (ray->intersections.size() < 2)
2300                        continue;
2301         
2302                iit = ray->intersections.begin();
2303                BspLeaf *leaf = (*(iit ++)).mLeaf;
2304               
2305                // create leaf pvs (needed for post processing)
2306                if (!leaf->mPvs)
2307                {
2308                        leaf->mPvs =
2309                                new ObjectPvs(leaf->GetViewCell()->GetPvs());
2310
2311                        BspMergeCandidate::sOverallCost +=
2312                                leaf->mArea * leaf->mPvs->GetSize();
2313                       
2314                        ++ leaves;
2315                }
2316               
2317                // traverse intersections
2318                // consecutive leaves are neighbors => add them to queue
2319                for (; iit != ray->intersections.end(); ++ iit)
2320                {
2321                        // next pair
2322                        BspLeaf *prevLeaf = leaf;
2323            leaf = (*iit).mLeaf;
2324
2325                        // view space does not correspond to valid space
2326                        if (!leaf->TreeValid() || !prevLeaf->TreeValid())
2327                                continue;
2328
2329            // create leaf pvs (needed for post processing)
2330                        if (!leaf->mPvs)
2331                        {
2332                                leaf->mPvs =
2333                                        new ObjectPvs(leaf->GetViewCell()->GetPvs());
2334                               
2335                                BspMergeCandidate::sOverallCost +=
2336                                        leaf->mArea * leaf->mPvs->GetSize();
2337
2338                                ++ leaves;
2339                        }
2340               
2341                        vector<BspLeaf *> &neighbors = neighborMap[leaf];
2342                       
2343                        bool found = false;
2344
2345                        // both leaves inserted in queue already =>
2346                        // look if double pair already exists
2347                        if (leaf->Mailed() && prevLeaf->Mailed())
2348                        {
2349                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2350                               
2351                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2352                                        if (*it == prevLeaf)
2353                                                found = true; // already in queue
2354                        }
2355                       
2356                        if (!found)
2357                        {
2358                                // this pair is not in map already
2359                                // => insert into the neighbor map and the queue
2360                                neighbors.push_back(prevLeaf);
2361                                neighborMap[prevLeaf].push_back(leaf);
2362
2363                                leaf->Mail();
2364                                prevLeaf->Mail();
2365
2366                                mMergeQueue.push(BspMergeCandidate(leaf, prevLeaf));
2367                        }
2368        }
2369        }
2370        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2371        Debug << "mergequeue: " << (int)mMergeQueue.size() << endl;
2372        Debug << "leaves in queue: " << leaves << endl;
2373        Debug << "overall cost: " << BspMergeCandidate::sOverallCost << endl;
2374
2375        CLEAR_CONTAINER(bspRays);
2376
2377        return leaves;
2378}
2379
2380
2381void VspBspTree::ConstructBspRays(vector<BspRay *> &bspRays,
2382                                                                  const VssRayContainer &rays)
2383{
2384        VssRayContainer::const_iterator it, it_end = rays.end();
2385
2386        for (it = rays.begin(); it != rays.end(); ++ it)
2387        {
2388                VssRay *vssRay = *it;
2389                BspRay *ray = new BspRay(vssRay);
2390
2391                ViewCellContainer viewCells;
2392
2393                Ray hray(*vssRay);
2394                float tmin = 0, tmax = 1.0;
2395                // matt TODO: remove this!!
2396                //hray.Init(ray.GetOrigin(), ray.GetDir(), Ray::LINE_SEGMENT);
2397                if (!mBox.GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
2398                        continue;
2399
2400                Vector3 origin = hray.Extrap(tmin);
2401                Vector3 termination = hray.Extrap(tmax);
2402       
2403                // cast line segment to get intersections with bsp leaves
2404                CastLineSegment(origin, termination, viewCells);
2405
2406                ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
2407                for (vit = viewCells.begin(); vit != vit_end; ++ vit)
2408                {
2409                        BspViewCell *vc = dynamic_cast<BspViewCell *>(*vit);
2410                        vector<BspLeaf *>::const_iterator it, it_end = vc->mLeaves.end();
2411                        //NOTE: not sorted!
2412                        for (it = vc->mLeaves.begin(); it != it_end; ++ it)
2413                                ray->intersections.push_back(BspIntersection(0, *it));
2414                }
2415
2416                bspRays.push_back(ray);
2417        }
2418}
2419
2420
2421int VspBspTree::MergeViewCells(const VssRayContainer &rays)
2422{
2423        MergeStatistics mergeStats;
2424        mergeStats.Start();
2425        // TODO: REMOVE LATER for performance!
2426        const bool showMergeStats = true;
2427        //BspMergeCandidate::sOverallCost = mBox.SurfaceArea() * mStat.maxPvs;
2428        long startTime = GetTime();
2429
2430        if (mUseRaysForMerge)
2431                mergeStats.nodes = CollectMergeCandidates(rays);
2432        else
2433                mergeStats.nodes = CollectMergeCandidates();
2434
2435        mergeStats.collectTime = TimeDiff(startTime, GetTime());
2436        mergeStats.candidates = (int)mMergeQueue.size();
2437        startTime = GetTime();
2438
2439        int nViewCells = /*mergeStats.nodes*/ mStat.Leaves() - mStat.invalidLeaves;
2440
2441        //-- use priority queue to merge leaf pairs
2442        while (!mMergeQueue.empty() && (nViewCells > mMergeMinViewCells) &&
2443                   (mMergeQueue.top().GetMergeCost() <
2444                    mMergeMaxCostRatio * BspMergeCandidate::sOverallCost))
2445        {
2446                //Debug << "abs mergecost: " << mMergeQueue.top().GetMergeCost() << " rel mergecost: "
2447                //        << mMergeQueue.top().GetMergeCost() / BspMergeCandidate::sOverallCost
2448                //        << " max ratio: " << mMergeMaxCostRatio << endl;
2449                BspMergeCandidate mc = mMergeQueue.top();
2450                mMergeQueue.pop();
2451
2452                // both view cells equal!
2453                if (mc.GetLeaf1()->GetViewCell() == mc.GetLeaf2()->GetViewCell())
2454                        continue;
2455
2456                if (mc.Valid())
2457                {
2458                        ViewCell::NewMail();
2459                        MergeViewCells(mc.GetLeaf1(), mc.GetLeaf2());
2460                        -- nViewCells;
2461                       
2462                        ++ mergeStats.merged;
2463                       
2464                        // increase absolute merge cost
2465                        BspMergeCandidate::sOverallCost += mc.GetMergeCost();
2466
2467                        if (showMergeStats)
2468                        {
2469                                if (mc.GetLeaf1()->IsSibling(mc.GetLeaf2()))
2470                                        ++ mergeStats.siblings;
2471
2472                                const int dist =
2473                                        TreeDistance(mc.GetLeaf1(), mc.GetLeaf2());
2474                                if (dist > mergeStats.maxTreeDist)
2475                                        mergeStats.maxTreeDist = dist;
2476                                mergeStats.accTreeDist += dist;
2477                        }
2478                }
2479                // merge candidate not valid, because one of the leaves was already
2480                // merged with another one => validate and reinsert into queue
2481                else
2482                {
2483                        mc.SetValid();
2484                        mMergeQueue.push(mc);
2485                }
2486        }
2487
2488        mergeStats.mergeTime = TimeDiff(startTime, GetTime());
2489        mergeStats.Stop();
2490
2491        if (showMergeStats)
2492                Debug << mergeStats << endl << endl;
2493       
2494        //TODO: should return sample contributions?
2495        return mergeStats.merged;
2496}
2497
2498
2499ViewCell *
2500VspBspTree::GetViewCell(const Vector3 &point)
2501{
2502  if (mRoot == NULL)
2503        return NULL;
2504 
2505  stack<BspNode *> nodeStack;
2506  nodeStack.push(mRoot);
2507 
2508  ViewCell *viewcell = NULL;
2509 
2510  while (!nodeStack.empty())  {
2511        BspNode *node = nodeStack.top();
2512        nodeStack.pop();
2513       
2514        if (node->IsLeaf()) {
2515          viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2516          break;
2517        } else {
2518         
2519          BspInterior *interior = dynamic_cast<BspInterior *>(node);
2520               
2521          // random decision
2522          if (interior->GetPlane().Side(point) < 0)
2523                nodeStack.push(interior->GetBack());
2524          else
2525                nodeStack.push(interior->GetFront());
2526        }
2527  }
2528 
2529  return viewcell;
2530}
2531
2532
2533int VspBspTree::RefineViewCells(const VssRayContainer &rays)
2534{
2535        int shuffled = 0;
2536
2537        Debug << "refining " << (int)mMergeQueue.size() << " candidates " << endl;
2538        BspLeaf::NewMail();
2539
2540        // Use priority queue of remaining leaf pairs
2541        // These candidates either share the same view cells or
2542        // are border leaves which share a boundary.
2543        // We test if they can be shuffled, i.e.,
2544        // either one leaf is made part of one view cell or the other
2545        // leaf is made part of the other view cell. It is tested if the
2546        // remaining view cells are "better" than the old ones.
2547        while (!mMergeQueue.empty())
2548        {
2549                BspMergeCandidate mc = mMergeQueue.top();
2550                mMergeQueue.pop();
2551
2552                // both view cells equal or already shuffled
2553                if ((mc.GetLeaf1()->GetViewCell() == mc.GetLeaf2()->GetViewCell()) ||
2554                        (mc.GetLeaf1()->Mailed()) || (mc.GetLeaf2()->Mailed()))
2555                        continue;
2556               
2557                // candidate for shuffling
2558                const bool wasShuffled =
2559                        ShuffleLeaves(mc.GetLeaf1(), mc.GetLeaf2());
2560               
2561                //-- stats
2562                if (wasShuffled)
2563                        ++ shuffled;
2564        }
2565
2566        return shuffled;
2567}
2568
2569
2570inline int AddedPvsSize(ObjectPvs pvs1, const ObjectPvs &pvs2)
2571{
2572        return pvs1.AddPvs(pvs2);
2573}
2574
2575/*inline int SubtractedPvsSize(BspViewCell *vc, BspLeaf *l, const ObjectPvs &pvs2)
2576{
2577        ObjectPvs pvs;
2578        vector<BspLeaf *>::const_iterator it, it_end = vc->mLeaves.end();
2579        for (it = vc->mLeaves.begin(); it != vc->mLeaves.end(); ++ it)
2580                if (*it != l)
2581                        pvs.AddPvs(*(*it)->mPvs);
2582        return pvs.GetSize();
2583}*/
2584
2585inline int SubtractedPvsSize(ObjectPvs pvs1, const ObjectPvs &pvs2)
2586{
2587        return pvs1.SubtractPvs(pvs2);
2588}
2589
2590
2591float GetShuffledVcCost(BspLeaf *leaf, BspViewCell *vc1, BspViewCell *vc2)
2592{
2593        //const int pvs1 = SubtractedPvsSize(vc1, leaf, *leaf->mPvs);
2594        const int pvs1 = SubtractedPvsSize(vc1->GetPvs(), *leaf->mPvs);
2595        const int pvs2 = AddedPvsSize(vc2->GetPvs(), *leaf->mPvs);
2596
2597        const float area1 = vc1->GetArea() - leaf->mArea;
2598        const float area2 = vc2->GetArea() + leaf->mArea;
2599
2600        const float cost1 = pvs1 * area1;
2601        const float cost2 = pvs2 * area2;
2602
2603        return cost1 + cost2;
2604}
2605
2606
2607void VspBspTree::ShuffleLeaf(BspLeaf *leaf,
2608                                                         BspViewCell *vc1,
2609                                                         BspViewCell *vc2) const
2610{
2611        // compute new pvs and area
2612        vc1->GetPvs().SubtractPvs(*leaf->mPvs);
2613        vc2->GetPvs().AddPvs(*leaf->mPvs);
2614       
2615        vc1->SetArea(vc1->GetArea() - leaf->mArea);
2616        vc2->SetArea(vc2->GetArea() + leaf->mArea);
2617
2618        /// add to second view cell
2619        vc2->mLeaves.push_back(leaf);
2620
2621        // erase leaf from old view cell
2622        vector<BspLeaf *>::iterator it = vc1->mLeaves.begin();
2623
2624        for (; *it != leaf; ++ it);
2625        vc1->mLeaves.erase(it);
2626
2627        /*vc1->GetPvs().mEntries.clear();
2628        for (; it != vc1->mLeaves.end(); ++ it)
2629        {
2630                if (*it == leaf)
2631                        vc1->mLeaves.erase(it);
2632                else
2633                        vc1->GetPvs().AddPvs(*(*it)->mPvs);
2634        }*/
2635
2636        leaf->SetViewCell(vc2); // finally change view cell
2637       
2638        //Debug << "new pvs: " << vc1->GetPvs().GetSize() + vc2->GetPvs().GetSize()
2639        //        << " (" << vc1->GetPvs().GetSize() << ", " << vc2->GetPvs().GetSize() << ")" << endl;
2640
2641}
2642
2643
2644bool VspBspTree::ShuffleLeaves(BspLeaf *leaf1, BspLeaf *leaf2) const
2645{
2646        BspViewCell *vc1 = leaf1->GetViewCell();
2647        BspViewCell *vc2 = leaf2->GetViewCell();
2648
2649        const float cost1 = vc1->GetPvs().GetSize() * vc1->GetArea();
2650        const float cost2 = vc2->GetPvs().GetSize() * vc2->GetArea();
2651
2652        const float oldCost = cost1 + cost2;
2653       
2654        float shuffledCost1 = Limits::Infinity;
2655        float shuffledCost2 = Limits::Infinity;
2656
2657        // the view cell should not be empty after the shuffle
2658        if (vc1->mLeaves.size() > 1)
2659                shuffledCost1 = GetShuffledVcCost(leaf1, vc1, vc2);
2660        if (vc2->mLeaves.size() > 1)
2661                shuffledCost2 = GetShuffledVcCost(leaf2, vc2, vc1);
2662
2663        // shuffling unsuccessful
2664        if ((oldCost <= shuffledCost1) && (oldCost <= shuffledCost2))
2665                return false;
2666       
2667        if (shuffledCost1 < shuffledCost2)
2668        {
2669                //Debug << "old cost: " << oldCost << ", new cost: " << shuffledCost1 << endl;
2670                ShuffleLeaf(leaf1, vc1, vc2);
2671                leaf1->Mail();
2672        }
2673        else
2674        {
2675                //Debug << "old cost: " << oldCost << ", new cost: " << shuffledCost2 << endl;
2676                ShuffleLeaf(leaf2, vc2, vc1);
2677                leaf2->Mail();
2678        }
2679
2680        return true;
2681}
2682
2683bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
2684{
2685        BspNode *node = mRoot;
2686
2687        while (1)
2688        {
2689                // early exit
2690                if (node->TreeValid())
2691                        return true;
2692
2693                if (node->IsLeaf())
2694                        return false;
2695                       
2696                BspInterior *in = dynamic_cast<BspInterior *>(node);
2697                                       
2698                if (in->GetPlane().Side(viewPoint) <= 0)
2699                {
2700                        node = in->GetBack();
2701                }
2702                else
2703                {
2704                        node = in->GetFront();
2705                }
2706        }
2707
2708        // should never come here
2709        return false;
2710}
2711
2712
2713bool VspBspTree::CheckValid(const VspBspTraversalData &data) const
2714{
2715        return data.mPvs <= mMaxPvs;
2716}
2717
2718
2719void VspBspTree::PropagateUpValidity(BspNode *node)
2720{
2721        while (!node->IsRoot() && node->GetParent()->TreeValid())
2722        {
2723                node = node->GetParent();
2724                node->SetTreeValid(false);
2725        }
2726}
2727
2728
2729/************************************************************************/
2730/*                BspMergeCandidate implementation                      */
2731/************************************************************************/
2732
2733
2734BspMergeCandidate::BspMergeCandidate(BspLeaf *l1, BspLeaf *l2):
2735mMergeCost(0),
2736mLeaf1(l1),
2737mLeaf2(l2),
2738mLeaf1Id(l1->GetViewCell()->mMailbox),
2739mLeaf2Id(l2->GetViewCell()->mMailbox)
2740{
2741        EvalMergeCost();
2742}
2743
2744float BspMergeCandidate::GetCost(ViewCell *vc) const
2745{
2746        return vc->GetPvs().GetSize() * vc->GetArea();
2747}
2748
2749float BspMergeCandidate::GetLeaf1Cost() const
2750{
2751        BspViewCell *vc = mLeaf1->GetViewCell();
2752        return GetCost(vc);
2753}
2754
2755float BspMergeCandidate::GetLeaf2Cost() const
2756{
2757        BspViewCell *vc = mLeaf2->GetViewCell();
2758        return GetCost(vc);
2759}
2760
2761void BspMergeCandidate::EvalMergeCost()
2762{
2763        //-- compute pvs difference
2764        BspViewCell *vc1 = mLeaf1->GetViewCell();
2765        BspViewCell *vc2 = mLeaf2->GetViewCell();
2766
2767        const int diff1 = vc1->GetPvs().Diff(vc2->GetPvs());
2768        const int newPvs = diff1 + vc1->GetPvs().GetSize();
2769
2770        //-- compute ratio of old cost
2771        //-- (added size of left and right view cell times pvs size)
2772        //-- to new rendering cost (size of merged view cell times pvs size)
2773        const float oldCost = GetLeaf1Cost() + GetLeaf2Cost();
2774
2775        const float newCost =
2776                (float)newPvs * (vc1->GetArea() + vc2->GetArea());
2777
2778        mMergeCost = newCost - oldCost;
2779//      if (vcPvs > sMaxPvsSize) // strong penalty if pvs size too large
2780//              mMergeCost += 1.0;
2781}
2782
2783void BspMergeCandidate::SetLeaf1(BspLeaf *l)
2784{
2785        mLeaf1 = l;
2786}
2787
2788void BspMergeCandidate::SetLeaf2(BspLeaf *l)
2789{
2790        mLeaf2 = l;
2791}
2792
2793BspLeaf *BspMergeCandidate::GetLeaf1()
2794{
2795        return mLeaf1;
2796}
2797
2798BspLeaf *BspMergeCandidate::GetLeaf2()
2799{
2800        return mLeaf2;
2801}
2802
2803bool BspMergeCandidate::Valid() const
2804{
2805        return
2806                (mLeaf1->GetViewCell()->mMailbox == mLeaf1Id) &&
2807                (mLeaf2->GetViewCell()->mMailbox == mLeaf2Id);
2808}
2809
2810float BspMergeCandidate::GetMergeCost() const
2811{
2812        return mMergeCost;
2813}
2814
2815void BspMergeCandidate::SetValid()
2816{
2817        mLeaf1Id = mLeaf1->GetViewCell()->mMailbox;
2818        mLeaf2Id = mLeaf2->GetViewCell()->mMailbox;
2819
2820        EvalMergeCost();
2821}
2822
2823
2824/************************************************************************/
2825/*                  MergeStatistics implementation                      */
2826/************************************************************************/
2827
2828
2829void MergeStatistics::Print(ostream &app) const
2830{
2831        app << "===== Merge statistics ===============\n";
2832
2833        app << setprecision(4);
2834
2835        app << "#N_CTIME ( Overall time [s] )\n" << Time() << " \n";
2836
2837        app << "#N_CCTIME ( Collect candidates time [s] )\n" << collectTime * 1e-3f << " \n";
2838
2839        app << "#N_MTIME ( Merge time [s] )\n" << mergeTime * 1e-3f << " \n";
2840
2841        app << "#N_NODES ( Number of nodes before merge )\n" << nodes << "\n";
2842
2843        app << "#N_CANDIDATES ( Number of merge candidates )\n" << candidates << "\n";
2844
2845        app << "#N_MERGEDSIBLINGS ( Number of merged siblings )\n" << siblings << "\n";
2846        app << "#N_MERGEDNODES ( Number of merged nodes )\n" << merged << "\n";
2847
2848        app << "#MAX_TREEDIST ( Maximal distance in tree of merged leaves )\n" << maxTreeDist << "\n";
2849
2850        app << "#AVG_TREEDIST ( Average distance in tree of merged leaves )\n" << AvgTreeDist() << "\n";
2851
2852        app << "===== END OF BspTree statistics ==========\n";
2853}
Note: See TracBrowser for help on using the repository browser.