source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp @ 611

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