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

Revision 498, 68.0 KB checked in by mattausch, 19 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellBsp.h"
17#include "ViewCellsManager.h"
18
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())
1525                {
1526                        if (!mShowInvalidSpace && node->TreeValid())
1527                        {
1528                                ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1529                       
1530                                if (!viewCell->Mailed())
1531                                {
1532                                        viewCell->Mail();
1533                                        viewCells.push_back(viewCell);
1534                                }
1535                        }
1536                }
1537                else
1538                {
1539                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1540                       
1541                        nodeStack.push(interior->GetFront());
1542                        nodeStack.push(interior->GetBack());
1543                }
1544        }
1545}
1546
1547
1548float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
1549{
1550        float len = 0;
1551
1552        RayInfoContainer::const_iterator it, it_end = rays.end();
1553
1554        for (it = rays.begin(); it != it_end; ++ it)
1555                len += (*it).SegmentLength();
1556
1557        return len;
1558}
1559
1560
1561int VspBspTree::SplitRays(const Plane3 &plane,
1562                                                  RayInfoContainer &rays,
1563                                                  RayInfoContainer &frontRays,
1564                                                  RayInfoContainer &backRays)
1565{
1566        int splits = 0;
1567
1568        while (!rays.empty())
1569        {
1570                RayInfo bRay = rays.back();
1571                rays.pop_back();
1572
1573                VssRay *ray = bRay.mRay;
1574                float t;
1575
1576                // get classification and receive new t
1577                const int cf = bRay.ComputeRayIntersection(plane, t);
1578
1579                switch (cf)
1580                {
1581                case -1:
1582                        backRays.push_back(bRay);
1583                        break;
1584                case 1:
1585                        frontRays.push_back(bRay);
1586                        break;
1587                case 0:
1588                        {
1589                                //-- split ray
1590                                //-- test if start point behind or in front of plane
1591                                const int side = plane.Side(bRay.ExtrapOrigin());
1592
1593                                if (side <= 0)
1594                                {
1595                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1596                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1597                                }
1598                                else
1599                                {
1600                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1601                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1602                                }
1603                        }
1604                        break;
1605                default:
1606                        Debug << "Should not come here" << endl;
1607                        break;
1608                }
1609        }
1610
1611        return splits;
1612}
1613
1614
1615void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
1616{
1617        BspNode *lastNode;
1618
1619        do
1620        {
1621                lastNode = n;
1622
1623                // want to get planes defining geometry of this node => don't take
1624                // split plane of node itself
1625                n = n->GetParent();
1626
1627                if (n)
1628                {
1629                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
1630                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
1631
1632            if (interior->GetFront() != lastNode)
1633                                halfSpace.ReverseOrientation();
1634
1635                        halfSpaces.push_back(halfSpace);
1636                }
1637        }
1638        while (n);
1639}
1640
1641
1642void VspBspTree::ConstructGeometry(BspNode *n,
1643                                                                   BspNodeGeometry &cell) const
1644{
1645        ConstructGeometry(n, cell.mPolys);
1646}
1647
1648
1649void VspBspTree::ConstructGeometry(BspNode *n,
1650                                                                   PolygonContainer &cell) const
1651{
1652        vector<Plane3> halfSpaces;
1653        ExtractHalfSpaces(n, halfSpaces);
1654
1655        PolygonContainer candidatePolys;
1656
1657        // bounded planes are added to the polygons (reverse polygons
1658        // as they have to be outfacing
1659        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
1660        {
1661                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
1662
1663                if (p->Valid(mEpsilon))
1664                {
1665                        candidatePolys.push_back(p->CreateReversePolygon());
1666                        DEL_PTR(p);
1667                }
1668        }
1669
1670        // add faces of bounding box (also could be faces of the cell)
1671        for (int i = 0; i < 6; ++ i)
1672        {
1673                VertexContainer vertices;
1674
1675                for (int j = 0; j < 4; ++ j)
1676                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
1677
1678                candidatePolys.push_back(new Polygon3(vertices));
1679        }
1680
1681        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
1682        {
1683                // polygon is split by all other planes
1684                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
1685                {
1686                        if (i == j) // polygon and plane are coincident
1687                                continue;
1688
1689                        VertexContainer splitPts;
1690                        Polygon3 *frontPoly, *backPoly;
1691
1692                        const int cf =
1693                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
1694                                                                                                 mEpsilon);
1695
1696                        switch (cf)
1697                        {
1698                                case Polygon3::SPLIT:
1699                                        frontPoly = new Polygon3();
1700                                        backPoly = new Polygon3();
1701
1702                                        candidatePolys[i]->Split(halfSpaces[j],
1703                                                                                         *frontPoly,
1704                                                                                         *backPoly,
1705                                                                                         mEpsilon);
1706
1707                                        DEL_PTR(candidatePolys[i]);
1708
1709                                        if (frontPoly->Valid(mEpsilon))
1710                                                candidatePolys[i] = frontPoly;
1711                                        else
1712                                                DEL_PTR(frontPoly);
1713
1714                                        DEL_PTR(backPoly);
1715                                        break;
1716                                case Polygon3::BACK_SIDE:
1717                                        DEL_PTR(candidatePolys[i]);
1718                                        break;
1719                                // just take polygon as it is
1720                                case Polygon3::FRONT_SIDE:
1721                                case Polygon3::COINCIDENT:
1722                                default:
1723                                        break;
1724                        }
1725                }
1726
1727                if (candidatePolys[i])
1728                        cell.push_back(candidatePolys[i]);
1729        }
1730}
1731
1732
1733void VspBspTree::ConstructGeometry(BspViewCell *vc,
1734                                                                   PolygonContainer &vcGeom) const
1735{
1736        vector<BspLeaf *> leaves = vc->mLeaves;
1737        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
1738
1739        for (it = leaves.begin(); it != it_end; ++ it)
1740                ConstructGeometry(*it, vcGeom);
1741}
1742
1743
1744int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
1745                                                   const bool onlyUnmailed) const
1746{
1747        PolygonContainer geom;
1748        ConstructGeometry(n, geom);
1749
1750        stack<BspNode *> nodeStack;
1751        nodeStack.push(mRoot);
1752
1753        // planes needed to verify that we found neighbor leaf.
1754        vector<Plane3> halfSpaces;
1755        ExtractHalfSpaces(n, halfSpaces);
1756
1757        while (!nodeStack.empty())
1758        {
1759                BspNode *node = nodeStack.top();
1760                nodeStack.pop();
1761
1762                if (node->IsLeaf())
1763
1764                {       // test if this leaf is in valid view space
1765            if (node->TreeValid() &&
1766                                node != n &&
1767                                (!onlyUnmailed || !node->Mailed()))
1768                        {
1769                                // test all planes of current node if candidate really
1770                                // is neighbour
1771                                PolygonContainer neighborCandidate;
1772                                ConstructGeometry(node, neighborCandidate);
1773
1774                                bool isAdjacent = true;
1775                                for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
1776                                {
1777                                        const int cf =
1778                                                Polygon3::ClassifyPlane(neighborCandidate,
1779                                                                                                halfSpaces[i],
1780                                                                                                mEpsilon);
1781
1782                                        if (cf == Polygon3::BACK_SIDE)
1783                                                isAdjacent = false;
1784                                }
1785
1786                                if (isAdjacent)
1787                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
1788
1789                                CLEAR_CONTAINER(neighborCandidate);
1790                        }
1791                }
1792                else
1793                {
1794                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1795
1796                        const int cf = Polygon3::ClassifyPlane(geom,
1797                                                                                                   interior->GetPlane(),
1798                                                                                                   mEpsilon);
1799
1800                        if (cf == Polygon3::FRONT_SIDE)
1801                                nodeStack.push(interior->GetFront());
1802                        else
1803                                if (cf == Polygon3::BACK_SIDE)
1804                                        nodeStack.push(interior->GetBack());
1805                                else
1806                                {
1807                                        // random decision
1808                                        nodeStack.push(interior->GetBack());
1809                                        nodeStack.push(interior->GetFront());
1810                                }
1811                }
1812        }
1813
1814        CLEAR_CONTAINER(geom);
1815        return (int)neighbors.size();
1816}
1817
1818
1819BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
1820{
1821    stack<BspNode *> nodeStack;
1822        nodeStack.push(mRoot);
1823
1824        int mask = rand();
1825
1826        while (!nodeStack.empty())
1827        {
1828                BspNode *node = nodeStack.top();
1829                nodeStack.pop();
1830
1831                if (node->IsLeaf())
1832                {
1833                        return dynamic_cast<BspLeaf *>(node);
1834                }
1835                else
1836                {
1837                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1838
1839                        BspNode *next;
1840
1841                        PolygonContainer geom;
1842
1843                        // todo: not very efficient: constructs full cell everytime
1844                        ConstructGeometry(interior, geom);
1845
1846                        const int cf = Polygon3::ClassifyPlane(geom, halfspace, mEpsilon);
1847
1848                        if (cf == Polygon3::BACK_SIDE)
1849                                next = interior->GetFront();
1850                        else
1851                                if (cf == Polygon3::FRONT_SIDE)
1852                                        next = interior->GetFront();
1853                        else
1854                        {
1855                                // random decision
1856                                if (mask & 1)
1857                                        next = interior->GetBack();
1858                                else
1859                                        next = interior->GetFront();
1860                                mask = mask >> 1;
1861                        }
1862
1863                        nodeStack.push(next);
1864                }
1865        }
1866
1867        return NULL;
1868}
1869
1870BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
1871{
1872        stack<BspNode *> nodeStack;
1873
1874        nodeStack.push(mRoot);
1875
1876        int mask = rand();
1877
1878        while (!nodeStack.empty())
1879        {
1880                BspNode *node = nodeStack.top();
1881                nodeStack.pop();
1882
1883                if (node->IsLeaf())
1884                {
1885                        if ( (!onlyUnmailed || !node->Mailed()) )
1886                                return dynamic_cast<BspLeaf *>(node);
1887                }
1888                else
1889                {
1890                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1891
1892                        // random decision
1893                        if (mask & 1)
1894                                nodeStack.push(interior->GetBack());
1895                        else
1896                                nodeStack.push(interior->GetFront());
1897
1898                        mask = mask >> 1;
1899                }
1900        }
1901
1902        return NULL;
1903}
1904
1905int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
1906{
1907        int pvsSize = 0;
1908
1909        RayInfoContainer::const_iterator rit, rit_end = rays.end();
1910
1911        Intersectable::NewMail();
1912
1913        for (rit = rays.begin(); rit != rays.end(); ++ rit)
1914        {
1915                VssRay *ray = (*rit).mRay;
1916
1917                if (ray->mOriginObject)
1918                {
1919                        if (!ray->mOriginObject->Mailed())
1920                        {
1921                                ray->mOriginObject->Mail();
1922                                ++ pvsSize;
1923                        }
1924                }
1925                if (ray->mTerminationObject)
1926                {
1927                        if (!ray->mTerminationObject->Mailed())
1928                        {
1929                                ray->mTerminationObject->Mail();
1930                                ++ pvsSize;
1931                        }
1932                }
1933        }
1934
1935        return pvsSize;
1936}
1937
1938float VspBspTree::GetEpsilon() const
1939{
1940        return mEpsilon;
1941}
1942
1943
1944int VspBspTree::SplitPolygons(const Plane3 &plane,
1945                                                          PolygonContainer &polys,
1946                                                          PolygonContainer &frontPolys,
1947                                                          PolygonContainer &backPolys,
1948                                                          PolygonContainer &coincident) const
1949{
1950        int splits = 0;
1951
1952        while (!polys.empty())
1953        {
1954                Polygon3 *poly = polys.back();
1955                polys.pop_back();
1956
1957                // classify polygon
1958                const int cf = poly->ClassifyPlane(plane, mEpsilon);
1959
1960                switch (cf)
1961                {
1962                        case Polygon3::COINCIDENT:
1963                                coincident.push_back(poly);
1964                                break;
1965                        case Polygon3::FRONT_SIDE:
1966                                frontPolys.push_back(poly);
1967                                break;
1968                        case Polygon3::BACK_SIDE:
1969                                backPolys.push_back(poly);
1970                                break;
1971                        case Polygon3::SPLIT:
1972                                backPolys.push_back(poly);
1973                                frontPolys.push_back(poly);
1974                                ++ splits;
1975                                break;
1976                        default:
1977                Debug << "SHOULD NEVER COME HERE\n";
1978                                break;
1979                }
1980        }
1981
1982        return splits;
1983}
1984
1985
1986int VspBspTree::CastLineSegment(const Vector3 &origin,
1987                                                                const Vector3 &termination,
1988                                                                vector<ViewCell *> &viewcells)
1989{
1990        int hits = 0;
1991        stack<BspRayTraversalData> tStack;
1992
1993        float mint = 0.0f, maxt = 1.0f;
1994
1995        Intersectable::NewMail();
1996
1997        Vector3 entp = origin;
1998        Vector3 extp = termination;
1999
2000        BspNode *node = mRoot;
2001        BspNode *farChild = NULL;
2002
2003        float t;
2004        while (1)
2005        {
2006                if (!node->IsLeaf())
2007                {
2008                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2009
2010                        Plane3 splitPlane = in->GetPlane();
2011                       
2012                        const int entSide = splitPlane.Side(entp);
2013                        const int extSide = splitPlane.Side(extp);
2014
2015                        if (entSide < 0)
2016                        {
2017                                node = in->GetBack();
2018                                // plane does not split ray => no far child
2019                                if (extSide <= 0)
2020                                        continue;
2021
2022                                farChild = in->GetFront(); // plane splits ray
2023                        }
2024                        else if (entSide > 0)
2025                        {
2026                                node = in->GetFront();
2027
2028                                if (extSide >= 0) // plane does not split ray => no far child
2029                                        continue;
2030
2031                                farChild = in->GetBack(); // plane splits ray
2032                        }
2033                        else // ray end point on plane
2034                        {       // NOTE: what to do if ray is coincident with plane?
2035                                if (extSide < 0)
2036                                        node = in->GetBack();
2037                                else
2038                                        node = in->GetFront();
2039                                                               
2040                                continue; // no far child
2041                        }
2042
2043                        // push data for far child
2044                        tStack.push(BspRayTraversalData(farChild, extp));
2045
2046                        // find intersection of ray segment with plane
2047                        extp = splitPlane.FindIntersection(origin, extp, &t);
2048                }
2049                else
2050                {
2051                        // reached leaf => intersection with view cell
2052                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2053
2054                        if (!leaf->GetViewCell()->Mailed())
2055                        {
2056                                viewcells.push_back(leaf->GetViewCell());
2057                                leaf->GetViewCell()->Mail();
2058                                ++ hits;
2059                        }
2060
2061                        //-- fetch the next far child from the stack
2062                        if (tStack.empty())
2063                                break;
2064
2065                        entp = extp;
2066                       
2067                        BspRayTraversalData &s = tStack.top();
2068
2069                        node = s.mNode;
2070                        extp = s.mExitPoint;
2071
2072                        tStack.pop();
2073                }
2074        }
2075
2076        return hits;
2077}
2078
2079int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
2080{
2081        std::deque<BspNode *> path1;
2082        BspNode *p1 = n1;
2083
2084        // create path from node 1 to root
2085        while (p1)
2086        {
2087                if (p1 == n2) // second node on path
2088                        return (int)path1.size();
2089
2090                path1.push_front(p1);
2091                p1 = p1->GetParent();
2092        }
2093
2094        int depth = n2->GetDepth();
2095        int d = depth;
2096
2097        BspNode *p2 = n2;
2098
2099        // compare with same depth
2100        while (1)
2101        {
2102                if ((d < (int)path1.size()) && (p2 == path1[d]))
2103                        return (depth - d) + ((int)path1.size() - 1 - d);
2104
2105                -- d;
2106                p2 = p2->GetParent();
2107        }
2108
2109        return 0; // never come here
2110}
2111
2112BspNode *VspBspTree::CollapseTree(BspNode *node)
2113{
2114        if (node->IsLeaf())
2115                return node;
2116
2117        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2118
2119        BspNode *front = CollapseTree(interior->GetFront());
2120        BspNode *back = CollapseTree(interior->GetBack());
2121
2122        if (front->IsLeaf() && back->IsLeaf())
2123        {
2124                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
2125                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
2126
2127                //-- collapse tree
2128                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
2129                {
2130                        BspViewCell *vc = frontLeaf->GetViewCell();
2131
2132                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
2133                        leaf->SetTreeValid(frontLeaf->TreeValid());
2134
2135                        // replace a link from node's parent
2136                        if (leaf->GetParent())
2137                                leaf->GetParent()->ReplaceChildLink(node, leaf);
2138
2139                        delete interior;
2140
2141                        return leaf;
2142                }
2143        }
2144
2145        return node;
2146}
2147
2148
2149void VspBspTree::CollapseTree()
2150{
2151        CollapseTree(mRoot);
2152        // revalidate leaves
2153        RepairVcLeafLists();
2154}
2155
2156
2157void VspBspTree::RepairVcLeafLists()
2158{
2159        // list not valid anymore => clear
2160        stack<BspNode *> nodeStack;
2161        nodeStack.push(mRoot);
2162
2163        ViewCell::NewMail();
2164
2165        while (!nodeStack.empty())
2166        {
2167                BspNode *node = nodeStack.top();
2168                nodeStack.pop();
2169
2170                if (node->IsLeaf())
2171                {
2172                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2173
2174                        BspViewCell *viewCell = leaf->GetViewCell();
2175
2176                        if (!viewCell->Mailed())
2177                        {
2178                                viewCell->mLeaves.clear();
2179                                viewCell->Mail();
2180                        }
2181
2182                        viewCell->mLeaves.push_back(leaf);
2183                }
2184                else
2185                {
2186                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2187
2188                        nodeStack.push(interior->GetFront());
2189                        nodeStack.push(interior->GetBack());
2190                }
2191        }
2192}
2193
2194
2195bool VspBspTree::MergeViewCells(BspLeaf *l1, BspLeaf *l2) const
2196{
2197        //-- change pointer to view cells of all leaves associated
2198        //-- with the previous view cells
2199        BspViewCell *fVc = l1->GetViewCell();
2200        BspViewCell *bVc = l2->GetViewCell();
2201
2202        BspViewCell *vc = dynamic_cast<BspViewCell *>(
2203                mViewCellsManager->MergeViewCells(*fVc, *bVc));
2204
2205        // if merge was unsuccessful
2206        if (!vc) return false;
2207
2208        // set new size of view cell
2209        vc->SetArea(fVc->GetArea() + bVc->GetArea());
2210
2211        vector<BspLeaf *> fLeaves = fVc->mLeaves;
2212        vector<BspLeaf *> bLeaves = bVc->mLeaves;
2213
2214        vector<BspLeaf *>::const_iterator it;
2215
2216        //-- change view cells of all the other leaves the view cell belongs to
2217        for (it = fLeaves.begin(); it != fLeaves.end(); ++ it)
2218        {
2219                (*it)->SetViewCell(vc);
2220                vc->mLeaves.push_back(*it);
2221        }
2222
2223        for (it = bLeaves.begin(); it != bLeaves.end(); ++ it)
2224        {
2225                (*it)->SetViewCell(vc);
2226                vc->mLeaves.push_back(*it);
2227        }
2228
2229        vc->Mail();
2230
2231        // clean up old view cells
2232        DEL_PTR(fVc);
2233        DEL_PTR(bVc);
2234
2235        return true;
2236}
2237
2238
2239void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
2240{
2241        mViewCellsManager = vcm;
2242}
2243
2244
2245int VspBspTree::CollectMergeCandidates()
2246{
2247        vector<BspLeaf *> leaves;
2248
2249        // collect the leaves, e.g., the "voxels" that will build the view cells
2250        CollectLeaves(leaves);
2251        BspLeaf::NewMail();
2252
2253        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2254
2255        // find merge candidates and push them into queue
2256        for (it = leaves.begin(); it != it_end; ++ it)
2257        {
2258                BspLeaf *leaf = *it;
2259               
2260                /// create leaf pvs (needed for post processing
2261                leaf->mPvs = new ObjectPvs(leaf->GetViewCell()->GetPvs());
2262
2263                BspMergeCandidate::sOverallCost +=
2264                        leaf->mArea * leaf->mPvs->GetSize();
2265
2266                // the same leaves must not be part of two merge candidates
2267                leaf->Mail();
2268                vector<BspLeaf *> neighbors;
2269                FindNeighbors(leaf, neighbors, true);
2270
2271                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2272
2273                // TODO: test if at least one ray goes from one leaf to the other
2274                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2275                {                       
2276                        mMergeQueue.push(BspMergeCandidate(leaf, *nit));
2277                }
2278        }
2279
2280        return (int)leaves.size();
2281}
2282
2283
2284int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays)
2285{
2286        vector<BspRay *> bspRays;
2287
2288        ConstructBspRays(bspRays, rays);
2289        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2290
2291        vector<BspIntersection>::const_iterator iit;
2292
2293        int leaves = 0;
2294       
2295        BspLeaf::NewMail();
2296
2297        for (int i = 0; i < (int)bspRays.size(); ++ i)
2298        { 
2299                BspRay *ray = bspRays[i];
2300         
2301                // traverse leaves stored in the rays and compare and
2302                // merge consecutive leaves (i.e., the neighbors in the tree)
2303                if (ray->intersections.size() < 2)
2304                        continue;
2305         
2306                iit = ray->intersections.begin();
2307                BspLeaf *leaf = (*(iit ++)).mLeaf;
2308               
2309                // create leaf pvs (needed for post processing)
2310                if (!leaf->mPvs)
2311                {
2312                        leaf->mPvs =
2313                                new ObjectPvs(leaf->GetViewCell()->GetPvs());
2314
2315                        BspMergeCandidate::sOverallCost +=
2316                                leaf->mArea * leaf->mPvs->GetSize();
2317                       
2318                        ++ leaves;
2319                }
2320               
2321                // traverse intersections
2322                // consecutive leaves are neighbors => add them to queue
2323                for (; iit != ray->intersections.end(); ++ iit)
2324                {
2325                        // next pair
2326                        BspLeaf *prevLeaf = leaf;
2327            leaf = (*iit).mLeaf;
2328
2329                        // view space not valid
2330                        if (!leaf->TreeValid() || !prevLeaf->TreeValid())
2331                                continue;
2332
2333            // create leaf pvs (needed for post processing)
2334                        if (!leaf->mPvs)
2335                        {
2336                                leaf->mPvs =
2337                                        new ObjectPvs(leaf->GetViewCell()->GetPvs());
2338                               
2339                                BspMergeCandidate::sOverallCost +=
2340                                        leaf->mArea * leaf->mPvs->GetSize();
2341
2342                                ++ leaves;
2343                        }
2344               
2345                        vector<BspLeaf *> &neighbors = neighborMap[leaf];
2346                       
2347                        bool found = false;
2348
2349                        // both leaves inserted in queue already =>
2350                        // look if double pair already exists
2351                        if (leaf->Mailed() && prevLeaf->Mailed())
2352                        {
2353                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2354                               
2355                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2356                                        if (*it == prevLeaf)
2357                                                found = true; // already in queue
2358                        }
2359                       
2360                        if (!found)
2361                        {
2362                                // this pair is not in map already
2363                                // => insert into the neighbor map and the queue
2364                                neighbors.push_back(prevLeaf);
2365                                neighborMap[prevLeaf].push_back(leaf);
2366
2367                                leaf->Mail();
2368                                prevLeaf->Mail();
2369
2370                                mMergeQueue.push(BspMergeCandidate(leaf, prevLeaf));
2371                        }
2372        }
2373        }
2374        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2375        Debug << "mergequeue: " << (int)mMergeQueue.size() << endl;
2376        Debug << "leaves in queue: " << leaves << endl;
2377        Debug << "overall cost: " << BspMergeCandidate::sOverallCost << endl;
2378
2379        CLEAR_CONTAINER(bspRays);
2380
2381        return leaves;
2382}
2383
2384
2385void VspBspTree::ConstructBspRays(vector<BspRay *> &bspRays,
2386                                                                  const VssRayContainer &rays)
2387{
2388        VssRayContainer::const_iterator it, it_end = rays.end();
2389
2390        for (it = rays.begin(); it != rays.end(); ++ it)
2391        {
2392                VssRay *vssRay = *it;
2393                BspRay *ray = new BspRay(vssRay);
2394
2395                ViewCellContainer viewCells;
2396
2397                Ray hray(*vssRay);
2398                float tmin = 0, tmax = 1.0;
2399                // matt TODO: remove this!!
2400                //hray.Init(ray.GetOrigin(), ray.GetDir(), Ray::LINE_SEGMENT);
2401                if (!mBox.GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
2402                        continue;
2403
2404                Vector3 origin = hray.Extrap(tmin);
2405                Vector3 termination = hray.Extrap(tmax);
2406       
2407                // cast line segment to get intersections with bsp leaves
2408                CastLineSegment(origin, termination, viewCells);
2409
2410                ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
2411                for (vit = viewCells.begin(); vit != vit_end; ++ vit)
2412                {
2413                        BspViewCell *vc = dynamic_cast<BspViewCell *>(*vit);
2414                        vector<BspLeaf *>::const_iterator it, it_end = vc->mLeaves.end();
2415                        //NOTE: not sorted!
2416                        for (it = vc->mLeaves.begin(); it != it_end; ++ it)
2417                                ray->intersections.push_back(BspIntersection(0, *it));
2418                }
2419
2420                bspRays.push_back(ray);
2421        }
2422}
2423
2424
2425int VspBspTree::MergeViewCells(const VssRayContainer &rays)
2426{
2427        MergeStatistics mergeStats;
2428        mergeStats.Start();
2429        // TODO: REMOVE LATER for performance!
2430        const bool showMergeStats = true;
2431        //BspMergeCandidate::sOverallCost = mBox.SurfaceArea() * mStat.maxPvs;
2432        long startTime = GetTime();
2433
2434        if (mUseRaysForMerge)
2435                mergeStats.nodes = CollectMergeCandidates(rays);
2436        else
2437                mergeStats.nodes = CollectMergeCandidates();
2438
2439        mergeStats.collectTime = TimeDiff(startTime, GetTime());
2440        mergeStats.candidates = (int)mMergeQueue.size();
2441        startTime = GetTime();
2442
2443        int nViewCells = /*mergeStats.nodes*/ mStat.Leaves() - mStat.invalidLeaves;
2444
2445        //-- use priority queue to merge leaf pairs
2446        while (!mMergeQueue.empty() && (nViewCells > mMergeMinViewCells) &&
2447                   (mMergeQueue.top().GetMergeCost() <
2448                    mMergeMaxCostRatio * BspMergeCandidate::sOverallCost))
2449        {
2450                //Debug << "abs mergecost: " << mMergeQueue.top().GetMergeCost() << " rel mergecost: "
2451                //        << mMergeQueue.top().GetMergeCost() / BspMergeCandidate::sOverallCost
2452                //        << " max ratio: " << mMergeMaxCostRatio << endl;
2453                BspMergeCandidate mc = mMergeQueue.top();
2454                mMergeQueue.pop();
2455
2456                // both view cells equal!
2457                if (mc.GetLeaf1()->GetViewCell() == mc.GetLeaf2()->GetViewCell())
2458                        continue;
2459
2460                if (mc.Valid())
2461                {
2462                        ViewCell::NewMail();
2463                        MergeViewCells(mc.GetLeaf1(), mc.GetLeaf2());
2464                        -- nViewCells;
2465                       
2466                        ++ mergeStats.merged;
2467                       
2468                        // increase absolute merge cost
2469                        BspMergeCandidate::sOverallCost += mc.GetMergeCost();
2470
2471                        if (showMergeStats)
2472                        {
2473                                if (mc.GetLeaf1()->IsSibling(mc.GetLeaf2()))
2474                                        ++ mergeStats.siblings;
2475
2476                                const int dist =
2477                                        TreeDistance(mc.GetLeaf1(), mc.GetLeaf2());
2478                                if (dist > mergeStats.maxTreeDist)
2479                                        mergeStats.maxTreeDist = dist;
2480                                mergeStats.accTreeDist += dist;
2481                        }
2482                }
2483                // merge candidate not valid, because one of the leaves was already
2484                // merged with another one => validate and reinsert into queue
2485                else
2486                {
2487                        mc.SetValid();
2488                        mMergeQueue.push(mc);
2489                }
2490        }
2491
2492        mergeStats.mergeTime = TimeDiff(startTime, GetTime());
2493        mergeStats.Stop();
2494
2495        if (showMergeStats)
2496                Debug << mergeStats << endl << endl;
2497       
2498        //TODO: should return sample contributions?
2499        return mergeStats.merged;
2500}
2501
2502
2503ViewCell *
2504VspBspTree::GetViewCell(const Vector3 &point)
2505{
2506  if (mRoot == NULL)
2507        return NULL;
2508 
2509  stack<BspNode *> nodeStack;
2510  nodeStack.push(mRoot);
2511 
2512  ViewCell *viewcell = NULL;
2513 
2514  while (!nodeStack.empty())  {
2515        BspNode *node = nodeStack.top();
2516        nodeStack.pop();
2517       
2518        if (node->IsLeaf()) {
2519          viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2520          break;
2521        } else {
2522         
2523          BspInterior *interior = dynamic_cast<BspInterior *>(node);
2524               
2525          // random decision
2526          if (interior->GetPlane().Side(point) < 0)
2527                nodeStack.push(interior->GetBack());
2528          else
2529                nodeStack.push(interior->GetFront());
2530        }
2531  }
2532 
2533  return viewcell;
2534}
2535
2536
2537int VspBspTree::RefineViewCells(const VssRayContainer &rays)
2538{
2539        int shuffled = 0;
2540
2541        Debug << "refining " << (int)mMergeQueue.size() << " candidates " << endl;
2542        BspLeaf::NewMail();
2543
2544        // Use priority queue of remaining leaf pairs
2545        // These candidates either share the same view cells or
2546        // are border leaves which share a boundary.
2547        // We test if they can be shuffled, i.e.,
2548        // either one leaf is made part of one view cell or the other
2549        // leaf is made part of the other view cell. It is tested if the
2550        // remaining view cells are "better" than the old ones.
2551        while (!mMergeQueue.empty())
2552        {
2553                BspMergeCandidate mc = mMergeQueue.top();
2554                mMergeQueue.pop();
2555
2556                // both view cells equal or already shuffled
2557                if ((mc.GetLeaf1()->GetViewCell() == mc.GetLeaf2()->GetViewCell()) ||
2558                        (mc.GetLeaf1()->Mailed()) || (mc.GetLeaf2()->Mailed()))
2559                        continue;
2560               
2561                // candidate for shuffling
2562                const bool wasShuffled =
2563                        ShuffleLeaves(mc.GetLeaf1(), mc.GetLeaf2());
2564               
2565                //-- stats
2566                if (wasShuffled)
2567                        ++ shuffled;
2568        }
2569
2570        return shuffled;
2571}
2572
2573
2574inline int AddedPvsSize(ObjectPvs pvs1, const ObjectPvs &pvs2)
2575{
2576        return pvs1.AddPvs(pvs2);
2577}
2578
2579/*inline int SubtractedPvsSize(BspViewCell *vc, BspLeaf *l, const ObjectPvs &pvs2)
2580{
2581        ObjectPvs pvs;
2582        vector<BspLeaf *>::const_iterator it, it_end = vc->mLeaves.end();
2583        for (it = vc->mLeaves.begin(); it != vc->mLeaves.end(); ++ it)
2584                if (*it != l)
2585                        pvs.AddPvs(*(*it)->mPvs);
2586        return pvs.GetSize();
2587}*/
2588
2589inline int SubtractedPvsSize(ObjectPvs pvs1, const ObjectPvs &pvs2)
2590{
2591        return pvs1.SubtractPvs(pvs2);
2592}
2593
2594
2595float GetShuffledVcCost(BspLeaf *leaf, BspViewCell *vc1, BspViewCell *vc2)
2596{
2597        //const int pvs1 = SubtractedPvsSize(vc1, leaf, *leaf->mPvs);
2598        const int pvs1 = SubtractedPvsSize(vc1->GetPvs(), *leaf->mPvs);
2599        const int pvs2 = AddedPvsSize(vc2->GetPvs(), *leaf->mPvs);
2600
2601        const float area1 = vc1->GetArea() - leaf->mArea;
2602        const float area2 = vc2->GetArea() + leaf->mArea;
2603
2604        const float cost1 = pvs1 * area1;
2605        const float cost2 = pvs2 * area2;
2606
2607        return cost1 + cost2;
2608}
2609
2610
2611void VspBspTree::ShuffleLeaf(BspLeaf *leaf,
2612                                                         BspViewCell *vc1,
2613                                                         BspViewCell *vc2) const
2614{
2615        // compute new pvs and area
2616        vc1->GetPvs().SubtractPvs(*leaf->mPvs);
2617        vc2->GetPvs().AddPvs(*leaf->mPvs);
2618       
2619        vc1->SetArea(vc1->GetArea() - leaf->mArea);
2620        vc2->SetArea(vc2->GetArea() + leaf->mArea);
2621
2622        /// add to second view cell
2623        vc2->mLeaves.push_back(leaf);
2624
2625        // erase leaf from old view cell
2626        vector<BspLeaf *>::iterator it = vc1->mLeaves.begin();
2627
2628        for (; *it != leaf; ++ it);
2629        vc1->mLeaves.erase(it);
2630
2631        /*vc1->GetPvs().mEntries.clear();
2632        for (; it != vc1->mLeaves.end(); ++ it)
2633        {
2634                if (*it == leaf)
2635                        vc1->mLeaves.erase(it);
2636                else
2637                        vc1->GetPvs().AddPvs(*(*it)->mPvs);
2638        }*/
2639
2640        leaf->SetViewCell(vc2); // finally change view cell
2641       
2642        //Debug << "new pvs: " << vc1->GetPvs().GetSize() + vc2->GetPvs().GetSize()
2643        //        << " (" << vc1->GetPvs().GetSize() << ", " << vc2->GetPvs().GetSize() << ")" << endl;
2644
2645}
2646
2647
2648bool VspBspTree::ShuffleLeaves(BspLeaf *leaf1, BspLeaf *leaf2) const
2649{
2650        BspViewCell *vc1 = leaf1->GetViewCell();
2651        BspViewCell *vc2 = leaf2->GetViewCell();
2652
2653        const float cost1 = vc1->GetPvs().GetSize() * vc1->GetArea();
2654        const float cost2 = vc2->GetPvs().GetSize() * vc2->GetArea();
2655
2656        const float oldCost = cost1 + cost2;
2657       
2658        float shuffledCost1 = Limits::Infinity;
2659        float shuffledCost2 = Limits::Infinity;
2660
2661        // the view cell should not be empty after the shuffle
2662        if (vc1->mLeaves.size() > 1)
2663                shuffledCost1 = GetShuffledVcCost(leaf1, vc1, vc2);
2664        if (vc2->mLeaves.size() > 1)
2665                shuffledCost2 = GetShuffledVcCost(leaf2, vc2, vc1);
2666
2667        // shuffling unsuccessful
2668        if ((oldCost <= shuffledCost1) && (oldCost <= shuffledCost2))
2669                return false;
2670       
2671        if (shuffledCost1 < shuffledCost2)
2672        {
2673                //Debug << "old cost: " << oldCost << ", new cost: " << shuffledCost1 << endl;
2674                ShuffleLeaf(leaf1, vc1, vc2);
2675                leaf1->Mail();
2676        }
2677        else
2678        {
2679                //Debug << "old cost: " << oldCost << ", new cost: " << shuffledCost2 << endl;
2680                ShuffleLeaf(leaf2, vc2, vc1);
2681                leaf2->Mail();
2682        }
2683
2684        return true;
2685}
2686
2687bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
2688{
2689        BspNode *node = mRoot;
2690
2691        while (1)
2692        {
2693                // early exit
2694                if (node->TreeValid())
2695                        return true;
2696
2697                if (node->IsLeaf())
2698                        return false;
2699                       
2700                BspInterior *in = dynamic_cast<BspInterior *>(node);
2701                                       
2702                if (in->GetPlane().Side(viewPoint) <= 0)
2703                {
2704                        node = in->GetBack();
2705                }
2706                else
2707                {
2708                        node = in->GetFront();
2709                }
2710        }
2711
2712        // should never come here
2713        return false;
2714}
2715
2716
2717bool VspBspTree::CheckValid(const VspBspTraversalData &data) const
2718{
2719        return data.mPvs <= mMaxPvs;
2720}
2721
2722
2723void VspBspTree::PropagateUpValidity(BspNode *node)
2724{
2725        while (!node->IsRoot() && node->GetParent()->TreeValid())
2726        {
2727                node = node->GetParent();
2728                node->SetTreeValid(false);
2729        }
2730}
2731
2732
2733/************************************************************************/
2734/*                BspMergeCandidate implementation                      */
2735/************************************************************************/
2736
2737
2738BspMergeCandidate::BspMergeCandidate(BspLeaf *l1, BspLeaf *l2):
2739mMergeCost(0),
2740mLeaf1(l1),
2741mLeaf2(l2),
2742mLeaf1Id(l1->GetViewCell()->mMailbox),
2743mLeaf2Id(l2->GetViewCell()->mMailbox)
2744{
2745        EvalMergeCost();
2746}
2747
2748float BspMergeCandidate::GetCost(ViewCell *vc) const
2749{
2750        return vc->GetPvs().GetSize() * vc->GetArea();
2751}
2752
2753float BspMergeCandidate::GetLeaf1Cost() const
2754{
2755        BspViewCell *vc = mLeaf1->GetViewCell();
2756        return GetCost(vc);
2757}
2758
2759float BspMergeCandidate::GetLeaf2Cost() const
2760{
2761        BspViewCell *vc = mLeaf2->GetViewCell();
2762        return GetCost(vc);
2763}
2764
2765void BspMergeCandidate::EvalMergeCost()
2766{
2767        //-- compute pvs difference
2768        BspViewCell *vc1 = mLeaf1->GetViewCell();
2769        BspViewCell *vc2 = mLeaf2->GetViewCell();
2770
2771        const int diff1 = vc1->GetPvs().Diff(vc2->GetPvs());
2772        const int newPvs = diff1 + vc1->GetPvs().GetSize();
2773
2774        //-- compute ratio of old cost
2775        //-- (added size of left and right view cell times pvs size)
2776        //-- to new rendering cost (size of merged view cell times pvs size)
2777        const float oldCost = GetLeaf1Cost() + GetLeaf2Cost();
2778
2779        const float newCost =
2780                (float)newPvs * (vc1->GetArea() + vc2->GetArea());
2781
2782        mMergeCost = newCost - oldCost;
2783//      if (vcPvs > sMaxPvsSize) // strong penalty if pvs size too large
2784//              mMergeCost += 1.0;
2785}
2786
2787void BspMergeCandidate::SetLeaf1(BspLeaf *l)
2788{
2789        mLeaf1 = l;
2790}
2791
2792void BspMergeCandidate::SetLeaf2(BspLeaf *l)
2793{
2794        mLeaf2 = l;
2795}
2796
2797BspLeaf *BspMergeCandidate::GetLeaf1()
2798{
2799        return mLeaf1;
2800}
2801
2802BspLeaf *BspMergeCandidate::GetLeaf2()
2803{
2804        return mLeaf2;
2805}
2806
2807bool BspMergeCandidate::Valid() const
2808{
2809        return
2810                (mLeaf1->GetViewCell()->mMailbox == mLeaf1Id) &&
2811                (mLeaf2->GetViewCell()->mMailbox == mLeaf2Id);
2812}
2813
2814float BspMergeCandidate::GetMergeCost() const
2815{
2816        return mMergeCost;
2817}
2818
2819void BspMergeCandidate::SetValid()
2820{
2821        mLeaf1Id = mLeaf1->GetViewCell()->mMailbox;
2822        mLeaf2Id = mLeaf2->GetViewCell()->mMailbox;
2823
2824        EvalMergeCost();
2825}
2826
2827
2828/************************************************************************/
2829/*                  MergeStatistics implementation                      */
2830/************************************************************************/
2831
2832
2833void MergeStatistics::Print(ostream &app) const
2834{
2835        app << "===== Merge statistics ===============\n";
2836
2837        app << setprecision(4);
2838
2839        app << "#N_CTIME ( Overall time [s] )\n" << Time() << " \n";
2840
2841        app << "#N_CCTIME ( Collect candidates time [s] )\n" << collectTime * 1e-3f << " \n";
2842
2843        app << "#N_MTIME ( Merge time [s] )\n" << mergeTime * 1e-3f << " \n";
2844
2845        app << "#N_NODES ( Number of nodes before merge )\n" << nodes << "\n";
2846
2847        app << "#N_CANDIDATES ( Number of merge candidates )\n" << candidates << "\n";
2848
2849        app << "#N_MERGEDSIBLINGS ( Number of merged siblings )\n" << siblings << "\n";
2850        app << "#N_MERGEDNODES ( Number of merged nodes )\n" << merged << "\n";
2851
2852        app << "#MAX_TREEDIST ( Maximal distance in tree of merged leaves )\n" << maxTreeDist << "\n";
2853
2854        app << "#AVG_TREEDIST ( Average distance in tree of merged leaves )\n" << AvgTreeDist() << "\n";
2855
2856        app << "===== END OF BspTree statistics ==========\n";
2857}
Note: See TracBrowser for help on using the repository browser.