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

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