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

Revision 424, 62.2 KB checked in by mattausch, 19 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 <stack>
11#include <time.h>
12#include <iomanip>
13#include "Exporter.h"
14#include "Plane3.h"
15
16//-- static members
17
18int BspNode::sMailId = 1;
19
20/** Evaluates split plane classification with respect to the plane's
21        contribution for a minimum number splits in the tree.
22*/
23const float BspTree::sLeastPolySplitsTable[] = {0, 0, 1, 0};
24/** Evaluates split plane classification with respect to the plane's
25        contribution for a balanced tree.
26*/
27const float BspTree::sBalancedPolysTable[] = {1, -1, 0, 0};
28
29/** Evaluates split plane classification with respect to the plane's
30        contribution for a minimum number of ray splits.
31*/
32const float BspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
33/** Evaluates split plane classification with respect to the plane's
34        contribution for balanced rays.
35*/
36const float BspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
37
38int BspTree::sConstructionMethod = FROM_INPUT_VIEW_CELLS;
39
40
41/****************************************************************/
42/*                  class BspNode implementation                */
43/****************************************************************/
44
45BspNode::BspNode():
46mParent(NULL)
47{}
48
49BspNode::BspNode(BspInterior *parent):
50mParent(parent)
51{}
52
53
54bool BspNode::IsRoot() const
55{
56        return mParent == NULL;
57}
58
59BspInterior *BspNode::GetParent()
60{
61        return mParent;
62}
63
64void BspNode::SetParent(BspInterior *parent)
65{
66        mParent = parent;
67}
68
69/****************************************************************/
70/*              class BspInterior implementation                */
71/****************************************************************/
72
73
74BspInterior::BspInterior(const Plane3 &plane):
75mPlane(plane), mFront(NULL), mBack(NULL)
76{}
77
78BspInterior::~BspInterior()
79{
80        DEL_PTR(mFront);
81        DEL_PTR(mBack);
82}
83
84bool BspInterior::IsLeaf() const
85{
86        return false;
87}
88
89BspNode *BspInterior::GetBack()
90{
91        return mBack;
92}
93
94BspNode *BspInterior::GetFront()
95{
96        return mFront;
97}
98
99Plane3 *BspInterior::GetPlane()
100{
101        return &mPlane;
102}
103
104void BspInterior::ReplaceChildLink(BspNode *oldChild, BspNode *newChild)
105{
106        if (mBack == oldChild)
107                mBack = newChild;
108        else
109                mFront = newChild;
110}
111
112void BspInterior::SetupChildLinks(BspNode *b, BspNode *f)
113{
114    mBack = b;
115    mFront = f;
116}
117
118int BspInterior::SplitPolygons(PolygonContainer &polys,
119                                                           PolygonContainer &frontPolys,
120                                                           PolygonContainer &backPolys,
121                                                           PolygonContainer &coincident)
122{
123        Polygon3 *splitPoly = NULL;
124
125        int splits = 0;
126
127#ifdef _Debug
128        Debug << "splitting polygons of node " << this << " with plane " << mPlane << endl;
129#endif
130        while (!polys.empty())
131        {
132                Polygon3 *poly = polys.back();
133                polys.pop_back();
134
135                //Debug << "New polygon with plane: " << poly->GetSupportingPlane() << "\n";
136
137                // classify polygon
138                const int cf = poly->ClassifyPlane(mPlane);
139
140                Polygon3 *front_piece = NULL;
141                Polygon3 *back_piece = NULL;
142       
143                VertexContainer splitVertices;
144
145                switch (cf)
146                {
147                        case Polygon3::COINCIDENT:
148                                coincident.push_back(poly);
149                                break;                 
150                        case Polygon3::FRONT_SIDE:     
151                                frontPolys.push_back(poly);
152                                break;
153                        case Polygon3::BACK_SIDE:
154                                backPolys.push_back(poly);
155                                break;
156                        case Polygon3::SPLIT:
157                                front_piece = new Polygon3(poly->mParent);
158                                back_piece = new Polygon3(poly->mParent);
159
160                                //-- split polygon into front and back part
161                                poly->Split(mPlane,
162                                                        *front_piece,
163                                                        *back_piece,
164                                                        splitVertices);
165                                       
166                                ++ splits; // increase number of splits
167
168                                //-- inherit rays from parent polygon for blocked ray criterium
169                                poly->InheritRays(*front_piece, *back_piece);
170                                //Debug << "p: " << poly->mPiercingRays.size() << " f: " << front_piece->mPiercingRays.size() << " b: " << back_piece->mPiercingRays.size() << endl;
171                               
172                                // check if polygons still valid
173                                if (front_piece->Valid())
174                                        frontPolys.push_back(front_piece);
175                                else
176                                        DEL_PTR(front_piece);
177                               
178                                if (back_piece->Valid())
179                                        backPolys.push_back(back_piece);
180                                else                           
181                                        DEL_PTR(back_piece);
182                               
183#ifdef _DEBUG
184                                Debug << "split " << *poly << endl << *front_piece << endl << *back_piece << endl;
185#endif
186                                DEL_PTR(poly);                 
187                                break;
188                        default:
189                Debug << "SHOULD NEVER COME HERE\n";
190                                break;
191                }
192        }
193
194        return splits;
195}
196
197/****************************************************************/
198/*                  class BspLeaf implementation                */
199/****************************************************************/
200BspLeaf::BspLeaf(): mViewCell(NULL)
201{
202}
203
204BspLeaf::BspLeaf(BspViewCell *viewCell):
205mViewCell(viewCell)
206{
207}
208
209BspLeaf::BspLeaf(BspInterior *parent):
210BspNode(parent), mViewCell(NULL)
211{}
212
213BspLeaf::BspLeaf(BspInterior *parent, BspViewCell *viewCell):
214BspNode(parent), mViewCell(viewCell)
215{
216}
217
218BspViewCell *BspLeaf::GetViewCell() const
219{
220        return mViewCell;
221}
222
223void BspLeaf::SetViewCell(BspViewCell *viewCell)
224{
225        mViewCell = viewCell;
226}
227
228bool BspLeaf::IsLeaf() const
229{
230        return true;
231}
232
233void BspLeaf::AddToPvs(const BoundedRayContainer &rays,
234                                           int &sampleContributions,
235                                           int &contributingSamples,
236                                           bool storeLeavesWithRays)
237{
238        sampleContributions = 0;
239        contributingSamples = 0;
240
241    BoundedRayContainer::const_iterator it, it_end = rays.end();
242
243        // add contributions from samples to the PVS
244        for (it = rays.begin(); it != it_end; ++ it)
245        {
246                int contribution = 0;
247                Ray *ray = (*it)->mRay;
248                       
249                if (!ray->intersections.empty())
250                        contribution += mViewCell->GetPvs().AddSample(ray->intersections[0].mObject);
251               
252                if (ray->sourceObject.mObject)
253                        contribution += mViewCell->GetPvs().AddSample(ray->sourceObject.mObject);
254
255                if (contribution > 0)
256                {
257                        sampleContributions += contribution;
258                        ++ contributingSamples;
259                }
260               
261                if (storeLeavesWithRays)
262                        // warning: intersections not ordered
263                        ray->bspIntersections.push_back(Ray::BspIntersection((*it)->mMinT, this));
264        }
265}
266
267
268/****************************************************************/
269/*                  class BspTree implementation                */
270/****************************************************************/
271
272BspTree::BspTree(BspViewCell *viewCell):
273mRootCell(viewCell),
274mRoot(NULL),
275mGenerateViewCells(false),
276mStoreLeavesWithRays(false),
277mPvsUseArea(true)
278{
279        Randomize(); // initialise random generator for heuristics
280
281        //-- termination criteria for autopartition
282        environment->GetIntValue("BspTree.Termination.maxDepth", mTermMaxDepth);
283        environment->GetIntValue("BspTree.Termination.minPvs", mTermMinPvs);
284        environment->GetIntValue("BspTree.Termination.maxPolygons", mTermMaxPolygons);
285        environment->GetIntValue("BspTree.Termination.maxRays", mTermMaxRays);
286        environment->GetFloatValue("BspTree.Termination.minArea", mTermMinArea);       
287        environment->GetFloatValue("BspTree.Termination.maxRayContribution", mTermMaxRayContribution);
288        environment->GetFloatValue("BspTree.Termination.maxAccRayLenght", mTermMaxAccRayLength);
289
290        //-- factors for bsp tree split plane heuristics
291        environment->GetFloatValue("BspTree.Factor.verticalSplits", mVerticalSplitsFactor);
292        environment->GetFloatValue("BspTree.Factor.largestPolyArea", mLargestPolyAreaFactor);
293        environment->GetFloatValue("BspTree.Factor.blockedRays", mBlockedRaysFactor);
294        environment->GetFloatValue("BspTree.Factor.leastRaySplits", mLeastRaySplitsFactor);
295        environment->GetFloatValue("BspTree.Factor.balancedRays", mBalancedRaysFactor);
296        environment->GetFloatValue("BspTree.Factor.pvsFactor", mPvsFactor);
297        environment->GetFloatValue("BspTree.Factor.leastSplits" , mLeastSplitsFactor);
298        environment->GetFloatValue("BspTree.Factor.balancedPolys", mBalancedPolysFactor);
299        environment->GetFloatValue("BspTree.Factor.balancedViewCells", mBalancedViewCellsFactor);
300        environment->GetFloatValue("BspTree.Termination.ct_div_ci", mCtDivCi);
301
302        //-- termination criteria for axis aligned split
303        environment->GetFloatValue("BspTree.Termination.AxisAligned.ct_div_ci", mAaCtDivCi);
304        environment->GetFloatValue("BspTree.Termination.AxisAligned.maxCostRatio", mMaxCostRatio);
305        environment->GetIntValue("BspTree.Termination.AxisAligned.maxPolys",
306                                                         mTermMaxPolysForAxisAligned);
307        environment->GetIntValue("BspTree.Termination.AxisAligned.maxRays",
308                                                         mTermMaxRaysForAxisAligned);
309        environment->GetIntValue("BspTree.Termination.AxisAligned.maxObjects",
310                                                         mTermMaxObjectsForAxisAligned);
311        //-- partition criteria
312        environment->GetIntValue("BspTree.maxPolyCandidates", mMaxPolyCandidates);
313        environment->GetIntValue("BspTree.maxRayCandidates", mMaxRayCandidates);
314        environment->GetIntValue("BspTree.splitPlaneStrategy", mSplitPlaneStrategy);
315        environment->GetFloatValue("BspTree.AxisAligned.splitBorder", mSplitBorder);
316
317        environment->GetFloatValue("BspTree.Construction.sideTolerance", Vector3::sDistTolerance);
318        Vector3::sDistToleranceSqrt = Vector3::sDistTolerance * Vector3::sDistTolerance;
319
320        // post processing stuff
321        environment->GetIntValue("ViewCells.PostProcessing.minPvsDif", mMinPvsDif);
322        environment->GetIntValue("ViewCells.PostProcessing.minPvs", mMinPvs);
323        environment->GetIntValue("ViewCells.PostProcessing.maxPvs", mMaxPvs);
324
325    Debug << "BSP max depth: " << mTermMaxDepth << endl;
326        Debug << "BSP min PVS: " << mTermMinPvs << endl;
327        Debug << "BSP min area: " << mTermMinArea << endl;
328        Debug << "BSP max polys: " << mTermMaxPolygons << endl;
329        Debug << "BSP max rays: " << mTermMaxRays << endl;
330        Debug << "BSP max polygon candidates: " << mMaxPolyCandidates << endl;
331        Debug << "BSP max plane candidates: " << mMaxRayCandidates << endl;
332
333        Debug << "Split plane strategy: ";
334        if (mSplitPlaneStrategy & RANDOM_POLYGON)
335                Debug << "random polygon ";
336        if (mSplitPlaneStrategy & AXIS_ALIGNED)
337                Debug << "axis aligned ";
338        if (mSplitPlaneStrategy & LEAST_SPLITS)     
339                Debug << "least splits ";
340        if (mSplitPlaneStrategy & BALANCED_POLYS)
341                Debug << "balanced polygons ";
342        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
343                Debug << "balanced view cells ";
344        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
345                Debug << "largest polygon area ";
346        if (mSplitPlaneStrategy & VERTICAL_AXIS)
347                Debug << "vertical axis ";
348        if (mSplitPlaneStrategy & BLOCKED_RAYS)
349                Debug << "blocked rays ";
350        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
351                Debug << "least ray splits ";
352        if (mSplitPlaneStrategy & BALANCED_RAYS)
353                Debug << "balanced rays ";
354        if (mSplitPlaneStrategy & PVS)
355                Debug << "pvs";
356
357        Debug << endl;
358}
359
360void BspTree::ParseEnvironment()
361{
362        //-- parse bsp cell tree construction method
363        char constructionMethodStr[60];
364       
365        environment->GetStringValue("BspTree.Construction.input", constructionMethodStr);
366
367        sConstructionMethod = FROM_INPUT_VIEW_CELLS;
368       
369        if (strcmp(constructionMethodStr, "fromViewCells") == 0)
370                sConstructionMethod = FROM_INPUT_VIEW_CELLS;
371        else if (strcmp(constructionMethodStr, "fromSceneGeometry") == 0)
372                sConstructionMethod = FROM_SCENE_GEOMETRY;
373        else if (strcmp(constructionMethodStr, "fromSamples") == 0)
374                sConstructionMethod = FROM_SAMPLES;
375        else
376        {
377                cerr << "Wrong construction method " << constructionMethodStr << endl;
378                exit(1);
379    }
380
381        Debug << "Construction method: " << constructionMethodStr << endl;
382}
383
384const BspTreeStatistics &BspTree::GetStatistics() const
385{
386        return mStat;
387}
388
389void BspTreeStatistics::Print(ostream &app) const
390{
391        app << "===== BspTree statistics ===============\n";
392
393        app << setprecision(4);
394
395        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
396
397        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
398
399        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
400
401        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
402
403        app << "#N_SPLITS ( Number of splits )\n" << splits << "\n";
404
405        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maxdepth )\n"<<
406        maxDepthNodes * 100 / (double)Leaves() << endl;
407
408        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
409
410        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
411
412        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
413
414        app << "#N_INPUT_POLYGONS (number of input polygons )\n" <<     polys << endl;
415
416        //app << "#N_PVS: " << pvs << endl;
417
418        app << "#N_ROUTPUT_INPUT_POLYGONS ( ratio polygons after subdivision / input polygons )\n" <<
419                 (polys + splits) / (double)polys << endl;
420       
421        app << "===== END OF BspTree statistics ==========\n";
422}
423
424
425BspTree::~BspTree()
426{
427        DEL_PTR(mRoot);
428}
429
430void BspTree::InsertViewCell(ViewCell *viewCell)
431{
432        PolygonContainer *polys = new PolygonContainer();
433
434        // extract polygons that guide the split process
435        mStat.polys += AddMeshToPolygons(viewCell->GetMesh(), *polys, viewCell);
436        mBox.Include(viewCell->GetBox()); // add to BSP aabb
437
438        InsertPolygons(polys);
439}
440
441void BspTree::InsertPolygons(PolygonContainer *polys)
442{       
443        std::stack<BspTraversalData> tStack;
444       
445        // traverse existing tree or create new tree
446    if (!mRoot)
447                mRoot = new BspLeaf();
448
449        tStack.push(BspTraversalData(mRoot, polys, 0, mRootCell, new BoundedRayContainer(), 0,
450                                                                 mBox.SurfaceArea(), new BspNodeGeometry()));
451
452        while (!tStack.empty())
453        {
454                // filter polygons donw the tree
455                BspTraversalData tData = tStack.top();
456            tStack.pop();
457                       
458                if (!tData.mNode->IsLeaf())
459                {
460                        BspInterior *interior = dynamic_cast<BspInterior *>(tData.mNode);
461
462                        //-- filter view cell polygons down the tree until a leaf is reached
463                        if (!tData.mPolygons->empty())
464                        {
465                                PolygonContainer *frontPolys = new PolygonContainer();
466                                PolygonContainer *backPolys = new PolygonContainer();
467                                PolygonContainer coincident;
468
469                                int splits = 0;
470               
471                                // split viewcell polygons with respect to split plane
472                                splits += interior->SplitPolygons(*tData.mPolygons,
473                                                                                                  *frontPolys,
474                                                                                                  *backPolys,
475                                                                                                  coincident);
476                               
477                                // extract view cells associated with the split polygons
478                                ViewCell *frontViewCell = mRootCell;
479                                ViewCell *backViewCell = mRootCell;
480                       
481                                BspTraversalData frontData(interior->GetFront(),
482                                                                                   frontPolys,
483                                                                                   tData.mDepth + 1,
484                                                                                   mRootCell,   
485                                                                                   tData.mRays,
486                                                                                   tData.mPvs,
487                                                                                   mBox.SurfaceArea(),
488                                                                                   new BspNodeGeometry());
489
490                                BspTraversalData backData(interior->GetBack(),
491                                                                                  backPolys,
492                                                                                  tData.mDepth + 1,
493                                                                                  mRootCell,   
494                                                                                  tData.mRays,
495                                                                                  tData.mPvs,
496                                                                                  mBox.SurfaceArea(),
497                                                                                  new BspNodeGeometry());
498
499                                if (!mGenerateViewCells)
500                                {
501                                        ExtractViewCells(frontData,
502                                                                         backData,
503                                                                         coincident,
504                                                                         interior->mPlane);
505                                }
506
507                                // don't need coincident polygons anymore
508                                CLEAR_CONTAINER(coincident);
509
510                                mStat.splits += splits;
511
512                                // push the children on the stack
513                                tStack.push(frontData);
514                                tStack.push(backData);
515                        }
516
517                        // cleanup
518                        DEL_PTR(tData.mPolygons);
519                }
520                else
521                {
522                        // reached leaf => subdivide current viewcell
523                        BspNode *subRoot = Subdivide(tStack, tData);
524                }
525        }
526}
527
528int BspTree::AddMeshToPolygons(Mesh *mesh, PolygonContainer &polys, MeshInstance *parent)
529{
530        FaceContainer::const_iterator fi;
531       
532        // copy the face data to polygons
533        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
534        {
535                Polygon3 *poly = new Polygon3((*fi), mesh);
536               
537                if (poly->Valid())
538                {
539                        poly->mParent = parent; // set parent intersectable
540                        polys.push_back(poly);
541                }
542                else
543                        DEL_PTR(poly);
544        }
545        return (int)mesh->mFaces.size();
546}
547
548int BspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
549                                                          PolygonContainer &polys,
550                                                          int maxObjects)
551{
552        int limit = (maxObjects > 0) ?
553                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
554 
555        int polysSize = 0;
556
557        for (int i = 0; i < limit; ++ i)
558        {
559                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
560                {
561                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
562                        polysSize += AddMeshToPolygons(viewCells[i]->GetMesh(), polys, viewCells[i]);
563                }
564        }
565
566        return polysSize;
567}
568
569int BspTree::AddToPolygonSoup(const ObjectContainer &objects, PolygonContainer &polys, int maxObjects)
570{
571        int limit = (maxObjects > 0) ? Min((int)objects.size(), maxObjects) : (int)objects.size();
572 
573        for (int i = 0; i < limit; ++i)
574        {
575                Intersectable *object = objects[i];//*it;
576                Mesh *mesh = NULL;
577
578                switch (object->Type()) // extract the meshes
579                {
580                case Intersectable::MESH_INSTANCE:
581                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
582                        break;
583                case Intersectable::VIEW_CELL:
584                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
585                        break;
586                        // TODO: handle transformed mesh instances
587                default:
588                        Debug << "intersectable type not supported" << endl;
589                        break;
590                }
591               
592        if (mesh) // copy the mesh data to polygons
593                {
594                        mBox.Include(object->GetBox()); // add to BSP tree aabb
595                        AddMeshToPolygons(mesh, polys, mRootCell);
596                }
597        }
598
599        return (int)polys.size();
600}
601
602void BspTree::Construct(const ViewCellContainer &viewCells)
603{
604        mStat.nodes = 1;
605        mBox.Initialize();      // initialise bsp tree bounding box
606
607        // copy view cell meshes into one big polygon soup
608        PolygonContainer *polys = new PolygonContainer();
609        mStat.polys = AddToPolygonSoup(viewCells, *polys);
610
611        // construct tree from the view cell polygons
612        Construct(polys, new BoundedRayContainer());
613}
614
615
616void BspTree::Construct(const ObjectContainer &objects)
617{
618        mStat.nodes = 1;
619        mBox.Initialize();      // initialise bsp tree bounding box
620       
621        PolygonContainer *polys = new PolygonContainer();
622       
623        // copy mesh instance polygons into one big polygon soup
624        mStat.polys = AddToPolygonSoup(objects, *polys);
625
626        // construct tree from polygon soup
627        Construct(polys, new BoundedRayContainer());
628}
629
630void BspTree::Construct(const RayContainer &sampleRays)
631{
632    mStat.nodes = 1;
633        mBox.Initialize();      // initialise BSP tree bounding box
634       
635        PolygonContainer *polys = new PolygonContainer();
636        BoundedRayContainer *rays = new BoundedRayContainer();
637
638        RayContainer::const_iterator rit, rit_end = sampleRays.end();
639
640        long startTime = GetTime();
641
642        Debug << "**** Extracting polygons from rays ****\n";
643
644        std::map<Face *, Polygon3 *> facePolyMap;
645
646        //-- extract polygons intersected by the rays
647        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
648        {
649                Ray *ray = *rit;
650       
651                // get ray-face intersection. Store polygon representing the rays together
652                // with rays intersecting the face.
653                if (!ray->intersections.empty())
654                {
655                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->intersections[0].mObject);
656                        Face *face = obj->GetMesh()->mFaces[ray->intersections[0].mFace];
657
658                        std::map<Face *, Polygon3 *>::iterator it = facePolyMap.find(face);
659
660                        if (it != facePolyMap.end())
661                        {
662                                //store rays if needed for heuristics
663                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
664                                        (*it).second->mPiercingRays.push_back(ray);
665                        }
666                        else
667                        {       //store rays if needed for heuristics
668                                Polygon3 *poly = new Polygon3(face, obj->GetMesh());
669                                poly->mParent = obj;
670                                polys->push_back(poly);
671
672                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
673                                        poly->mPiercingRays.push_back(ray);
674
675                                facePolyMap[face] = poly;
676                        }
677                }
678        }
679       
680        facePolyMap.clear();
681
682        // compue bounding box
683        Polygon3::IncludeInBox(*polys, mBox);
684
685        //-- store rays
686        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
687        {
688                Ray *ray = *rit;
689        ray->SetId(-1); // reset id
690
691                float minT, maxT;
692                if (BoundRay(*ray, minT, maxT))
693                        rays->push_back(new BoundedRay(ray, minT, maxT));
694        }
695
696        mStat.polys = (int)polys->size();
697
698        Debug << "**** Finished polygon extraction ****" << endl;
699        Debug << (int)polys->size() << " polys extracted from " << (int)sampleRays.size() << " rays" << endl;
700        Debug << "extraction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
701
702        Construct(polys, rays);
703}
704
705void BspTree::Construct(PolygonContainer *polys, BoundedRayContainer *rays)
706{
707        std::stack<BspTraversalData> tStack;
708
709        mRoot = new BspLeaf();
710
711        BspNodeGeometry *cell = new BspNodeGeometry();
712        ConstructGeometry(mRoot, *cell);
713
714        BspTraversalData tData(mRoot, polys, 0, mRootCell, rays,
715                                                   ComputePvsSize(*rays), cell->GetArea(), cell);
716
717        tStack.push(tData);
718
719        mStat.Start();
720        cout << "**** Contructing bsp tree ****\n";
721
722        while (!tStack.empty())
723        {
724                tData = tStack.top();
725            tStack.pop();
726
727                // subdivide leaf node
728                BspNode *subRoot = Subdivide(tStack, tData);
729        }
730
731        mStat.Stop();
732}
733
734bool BspTree::TerminationCriteriaMet(const BspTraversalData &data) const
735{
736        return
737                (((int)data.mPolygons->size() <= mTermMaxPolygons) ||
738                 ((int)data.mRays->size() <= mTermMaxRays) ||
739                 (data.mPvs <= mTermMinPvs) ||
740                 (data.mArea <= mTermMinArea) ||
741                 (data.mDepth >= mTermMaxDepth) ||
742                 (data.GetAvgRayContribution() < mTermMaxRayContribution));
743}
744
745BspNode *BspTree::Subdivide(BspTraversalStack &tStack, BspTraversalData &tData)
746{
747        //-- terminate traversal 
748        if (TerminationCriteriaMet(tData))             
749        {
750                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
751       
752                BspViewCell *viewCell;
753
754                // generate new view cell for each leaf
755                if (mGenerateViewCells)
756                {
757                        viewCell = dynamic_cast<BspViewCell *>(ViewCell::Generate());
758                }
759                else
760                {
761                        // add view cell to leaf
762                        viewCell = dynamic_cast<BspViewCell *>(tData.mViewCell);
763                }
764
765                leaf->SetViewCell(viewCell);
766                viewCell->mBspLeaves.push_back(leaf);
767
768                //-- add pvs
769                if (viewCell != mRootCell)
770                {
771                        int conSamp = 0, sampCon = 0;
772                        leaf->AddToPvs(*tData.mRays, conSamp, sampCon);
773                       
774                        mStat.contributingSamples += conSamp;
775                        mStat.sampleContributions += sampCon;
776                }
777
778                EvaluateLeafStats(tData);
779               
780                //-- clean up
781               
782                // discard polygons
783                CLEAR_CONTAINER(*tData.mPolygons);
784                // discard rays
785                CLEAR_CONTAINER(*tData.mRays);
786
787                DEL_PTR(tData.mPolygons);
788                DEL_PTR(tData.mRays);
789                DEL_PTR(tData.mGeometry);
790               
791                return leaf;
792        }
793
794        //-- continue subdivision
795        PolygonContainer coincident;
796       
797        PolygonContainer *frontPolys = new PolygonContainer();
798        PolygonContainer *backPolys = new PolygonContainer();
799
800        BoundedRayContainer *frontRays = new BoundedRayContainer();
801        BoundedRayContainer *backRays = new BoundedRayContainer();
802       
803        BspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mRootCell,
804                                                                new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
805        BspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mRootCell,
806                                                           new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
807
808        // create new interior node and two leaf nodes
809        BspInterior *interior = SubdivideNode(tData,
810                                                                                  tFrontData,
811                                                                                  tBackData,
812                                                                                  coincident);
813
814#ifdef _DEBUG   
815        if (frontPolys->empty() && backPolys->empty() && (coincident.size() > 2))
816        {       for (PolygonContainer::iterator it = coincident.begin(); it != coincident.end(); ++it)
817                        Debug << (*it) << " " << (*it)->GetArea() << " " << (*it)->mParent << endl ;
818                Debug << endl;}
819#endif
820
821        // extract view cells from coincident polygons according to plane normal
822    // only if front or back polygons are empty
823        if (!mGenerateViewCells)
824        {
825                ExtractViewCells(tFrontData,
826                                                 tBackData,
827                                                 coincident,
828                                                 interior->mPlane);                     
829        }
830
831        // don't need coincident polygons anymory
832        CLEAR_CONTAINER(coincident);
833
834        // push the children on the stack
835        tStack.push(tFrontData);
836        tStack.push(tBackData);
837
838        // cleanup
839        DEL_PTR(tData.mNode);
840        DEL_PTR(tData.mPolygons);
841        DEL_PTR(tData.mRays);
842        DEL_PTR(tData.mGeometry);               
843
844        return interior;
845}
846
847void BspTree::ExtractViewCells(BspTraversalData &frontData,
848                                                           BspTraversalData &backData,
849                                                           const PolygonContainer &coincident,
850                                                           const Plane3 splitPlane) const
851{
852        // if not empty, tree is further subdivided => don't have to find view cell
853        bool foundFront = !frontData.mPolygons->empty();
854        bool foundBack = !frontData.mPolygons->empty();
855
856        PolygonContainer::const_iterator it =
857                coincident.begin(), it_end = coincident.end();
858
859        //-- find first view cells in front and back leafs
860        for (; !(foundFront && foundBack) && (it != it_end); ++ it)
861        {
862                if (DotProd((*it)->GetNormal(), splitPlane.mNormal) > 0)
863                {
864                        backData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
865                        foundBack = true;
866                }
867                else
868                {
869                        frontData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
870                        foundFront = true;
871                }
872        }
873}
874
875BspInterior *BspTree::SubdivideNode(BspTraversalData &tData,
876                                                                        BspTraversalData &frontData,
877                                                                        BspTraversalData &backData,
878                                                                        PolygonContainer &coincident)
879{
880        mStat.nodes += 2;
881       
882        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
883        // select subdivision plane
884        BspInterior *interior =
885                new BspInterior(SelectPlane(leaf, tData));
886
887#ifdef _DEBUG
888        Debug << interior << endl;
889#endif
890       
891        // subdivide rays into front and back rays
892        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
893       
894        // subdivide polygons with plane
895        mStat.splits += interior->SplitPolygons(*tData.mPolygons,
896                                                    *frontData.mPolygons,
897                                                                                        *backData.mPolygons,
898                                                                                        coincident);
899
900    // compute pvs
901        frontData.mPvs = ComputePvsSize(*frontData.mRays);
902        backData.mPvs = ComputePvsSize(*backData.mRays);
903
904        // split geometry and compute area
905        if (1)
906        {
907                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
908                                                                           *backData.mGeometry,
909                                                                           *this,
910                                                                           interior->mPlane);
911       
912               
913                frontData.mArea = frontData.mGeometry->GetArea();
914                backData.mArea = backData.mGeometry->GetArea();
915        }
916
917        // compute accumulated ray length
918        //frontData.mAccRayLength = AccumulatedRayLength(*frontData.mRays);
919        //backData.mAccRayLength = AccumulatedRayLength(*backData.mRays);
920
921        //-- create front and back leaf
922
923        BspInterior *parent = leaf->GetParent();
924
925        // replace a link from node's parent
926        if (!leaf->IsRoot())
927        {
928                parent->ReplaceChildLink(leaf, interior);
929                interior->SetParent(parent);
930        }
931        else // new root
932        {
933                mRoot = interior;
934        }
935
936        // and setup child links
937        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
938       
939        frontData.mNode = interior->mFront;
940        backData.mNode = interior->mBack;
941       
942        //DEL_PTR(leaf);
943        return interior;
944}
945
946void BspTree::SortSplitCandidates(const PolygonContainer &polys,
947                                                                  const int axis,
948                                                                  vector<SortableEntry> &splitCandidates) const
949{
950  splitCandidates.clear();
951 
952  int requestedSize = 2 * (int)polys.size();
953  // creates a sorted split candidates array 
954  splitCandidates.reserve(requestedSize);
955 
956  PolygonContainer::const_iterator it, it_end = polys.end();
957
958  AxisAlignedBox3 box;
959
960  // insert all queries
961  for(it = polys.begin(); it != it_end; ++ it)
962  {
963          box.Initialize();
964          box.Include(*(*it));
965         
966          splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MIN, box.Min(axis), *it));
967      splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MAX, box.Max(axis), *it));
968  }
969 
970  stable_sort(splitCandidates.begin(), splitCandidates.end());
971}
972
973
974float BspTree::BestCostRatio(const PolygonContainer &polys,
975                                                         const AxisAlignedBox3 &box,
976                                                         const int axis,
977                                                         float &position,
978                                                         int &objectsBack,
979                                                         int &objectsFront) const
980{
981        vector<SortableEntry> splitCandidates;
982
983        SortSplitCandidates(polys, axis, splitCandidates);
984       
985        // go through the lists, count the number of objects left and right
986        // and evaluate the following cost funcion:
987        // C = ct_div_ci  + (ol + or)/queries
988       
989        int objectsLeft = 0, objectsRight = (int)polys.size();
990       
991        float minBox = box.Min(axis);
992        float maxBox = box.Max(axis);
993        float boxArea = box.SurfaceArea();
994 
995        float minBand = minBox + mSplitBorder * (maxBox - minBox);
996        float maxBand = minBox + (1.0f - mSplitBorder) * (maxBox - minBox);
997       
998        float minSum = 1e20f;
999        vector<SortableEntry>::const_iterator ci, ci_end = splitCandidates.end();
1000
1001        for(ci = splitCandidates.begin(); ci != ci_end; ++ ci)
1002        {
1003                switch ((*ci).type)
1004                {
1005                        case SortableEntry::POLY_MIN:
1006                                ++ objectsLeft;
1007                                break;
1008                        case SortableEntry::POLY_MAX:
1009                            -- objectsRight;
1010                                break;
1011                        default:
1012                                break;
1013                }
1014               
1015                if ((*ci).value > minBand && (*ci).value < maxBand)
1016                {
1017                        AxisAlignedBox3 lbox = box;
1018                        AxisAlignedBox3 rbox = box;
1019                        lbox.SetMax(axis, (*ci).value);
1020                        rbox.SetMin(axis, (*ci).value);
1021
1022                        float sum = objectsLeft * lbox.SurfaceArea() +
1023                                                objectsRight * rbox.SurfaceArea();
1024     
1025                        if (sum < minSum)
1026                        {
1027                                minSum = sum;
1028                                position = (*ci).value;
1029
1030                                objectsBack = objectsLeft;
1031                                objectsFront = objectsRight;
1032                        }
1033                }
1034        }
1035 
1036        float oldCost = (float)polys.size();
1037        float newCost = mAaCtDivCi + minSum / boxArea;
1038        float ratio = newCost / oldCost;
1039
1040
1041#if 0
1042  Debug << "====================" << endl;
1043  Debug << "costRatio=" << ratio << " pos=" << position<<" t=" << (position - minBox)/(maxBox - minBox)
1044      << "\t o=(" << objectsBack << "," << objectsFront << ")" << endl;
1045#endif
1046  return ratio;
1047}
1048
1049bool BspTree::SelectAxisAlignedPlane(Plane3 &plane,
1050                                                                         const PolygonContainer &polys) const
1051{
1052        AxisAlignedBox3 box;
1053        box.Initialize();
1054       
1055        // create bounding box of region
1056        Polygon3::IncludeInBox(polys, box);
1057       
1058        int objectsBack = 0, objectsFront = 0;
1059        int axis = 0;
1060        float costRatio = MAX_FLOAT;
1061        Vector3 position;
1062
1063        //-- area subdivision
1064        for (int i = 0; i < 3; ++ i)
1065        {
1066                float p = 0;
1067                float r = BestCostRatio(polys, box, i, p, objectsBack, objectsFront);
1068               
1069                if (r < costRatio)
1070                {
1071                        costRatio = r;
1072                        axis = i;
1073                        position = p;
1074                }
1075        }
1076       
1077        if (costRatio >= mMaxCostRatio)
1078                return false;
1079
1080        Vector3 norm(0,0,0); norm[axis] = 1.0f;
1081        plane = Plane3(norm, position);
1082
1083        return true;
1084}
1085
1086Plane3 BspTree::SelectPlane(BspLeaf *leaf, BspTraversalData &data)
1087{
1088        if (data.mPolygons->empty() && data.mRays->empty())
1089        {
1090                Debug << "Warning: No autopartition polygon candidate available\n";
1091       
1092                // return axis aligned split
1093                AxisAlignedBox3 box;
1094                box.Initialize();
1095       
1096                // create bounding box of region
1097                Polygon3::IncludeInBox(*data.mPolygons, box);
1098
1099                const int axis = box.Size().DrivingAxis();
1100                const Vector3 position = (box.Min()[axis] + box.Max()[axis])*0.5f;
1101
1102                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1103                return Plane3(norm, position);
1104        }
1105       
1106        if ((mSplitPlaneStrategy & AXIS_ALIGNED) &&
1107                ((int)data.mPolygons->size() > mTermMaxPolysForAxisAligned) &&
1108                ((int)data.mRays->size() > mTermMaxRaysForAxisAligned) &&
1109                ((mTermMaxObjectsForAxisAligned < 0) ||
1110                  (Polygon3::ParentObjectsSize(*data.mPolygons) > mTermMaxObjectsForAxisAligned)))
1111        {
1112                Plane3 plane;
1113                if (SelectAxisAlignedPlane(plane, *data.mPolygons))
1114                        return plane;
1115        }
1116
1117        // simplest strategy: just take next polygon
1118        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1119        {
1120        if (!data.mPolygons->empty())
1121                {
1122                        Polygon3 *nextPoly = (*data.mPolygons)[Random((int)data.mPolygons->size())];
1123                        return nextPoly->GetSupportingPlane();
1124                }
1125                else
1126                {
1127                        const int candidateIdx = Random((int)data.mRays->size());
1128                        BoundedRay *bRay = (*data.mRays)[candidateIdx];
1129
1130                        Ray *ray = bRay->mRay;
1131                                               
1132                        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1133                        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1134
1135                        const Vector3 pt = (maxPt + minPt) * 0.5;
1136
1137                        const Vector3 normal = ray->GetDir();
1138                       
1139                        return Plane3(normal, pt);
1140                }
1141
1142                return Plane3();
1143        }
1144
1145        // use heuristics to find appropriate plane
1146        return SelectPlaneHeuristics(leaf, data);
1147}
1148
1149Plane3 BspTree::SelectPlaneHeuristics(BspLeaf *leaf, BspTraversalData &data)
1150{
1151        float lowestCost = MAX_FLOAT;
1152        Plane3 bestPlane;
1153        Plane3 plane;
1154
1155        int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1156       
1157        int candidateIdx = limit;
1158
1159        for (int i = 0; i < limit; ++ i)
1160        {
1161                candidateIdx = GetNextCandidateIdx(candidateIdx, *data.mPolygons);
1162               
1163                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1164                // evaluate current candidate
1165                const float candidateCost =
1166                        SplitPlaneCost(poly->GetSupportingPlane(), data);
1167
1168                if (candidateCost < lowestCost)
1169                {
1170                        bestPlane = poly->GetSupportingPlane();
1171                        lowestCost = candidateCost;
1172                }
1173        }
1174       
1175        //Debug << "lowest: " << lowestCost << endl;
1176
1177        //-- choose candidate planes extracted from rays
1178        // we currently use two methods
1179        // 1) take 3 ray endpoints, where two are minimum and one a maximum
1180        //    point or the other way round
1181        // 2) take plane normal as plane normal and the midpoint of the ray.
1182        //    PROBLEM: does not resemble any point where visibility is likely to change
1183        const BoundedRayContainer *rays = data.mRays;
1184
1185        for (int i = 0; i < mMaxRayCandidates / 2; ++ i)
1186        {
1187                candidateIdx = Random((int)rays->size());
1188                BoundedRay *bRay = (*rays)[candidateIdx];
1189
1190                Ray *ray = bRay->mRay;
1191                                               
1192                const Vector3 minPt = ray->Extrap(bRay->mMinT);
1193                const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1194
1195                const Vector3 pt = (maxPt + minPt) * 0.5;
1196
1197                const Vector3 normal = ray->GetDir();
1198                       
1199                plane = Plane3(normal, pt);
1200       
1201                const float candidateCost = SplitPlaneCost(plane, data);
1202
1203                if (candidateCost < lowestCost)
1204                {
1205                        bestPlane = plane;
1206                       
1207                        lowestCost = candidateCost;
1208                }
1209        }
1210
1211        //Debug << "lowest: " << lowestCost << endl;
1212        for (int i = 0; i < mMaxRayCandidates / 2; ++ i)
1213        {
1214                Vector3 pt[3];
1215                int idx[3];
1216                int cmaxT = 0;
1217                int cminT = 0;
1218                bool chooseMin = false;
1219
1220                for (int j = 0; j < 3; j ++)
1221                {
1222                        idx[j] = Random((int)rays->size() * 2);
1223                               
1224                        if (idx[j] >= (int)rays->size())
1225                        {
1226                                idx[j] -= (int)rays->size();
1227                               
1228                                chooseMin = (cminT < 2);
1229                        }
1230                        else
1231                                chooseMin = (cmaxT < 2);
1232
1233                        BoundedRay *bRay = (*rays)[idx[j]];
1234                        pt[j] = chooseMin ? bRay->mRay->Extrap(bRay->mMinT) : bRay->mRay->Extrap(bRay->mMaxT);
1235                }       
1236                       
1237                plane = Plane3(pt[0], pt[1], pt[2]);
1238
1239                const float candidateCost = SplitPlaneCost(plane, data);
1240
1241                if (candidateCost < lowestCost)
1242                {
1243                        //Debug << "choose ray plane 2: " << candidateCost << endl;
1244                        bestPlane = plane;
1245                       
1246                        lowestCost = candidateCost;
1247                }
1248        }       
1249
1250#ifdef _DEBUG
1251        Debug << "plane lowest cost: " << lowestCost << endl;
1252#endif
1253        return bestPlane;
1254}
1255
1256int BspTree::GetNextCandidateIdx(int currentIdx, PolygonContainer &polys)
1257{
1258        const int candidateIdx = Random(currentIdx --);
1259
1260        // swap candidates to avoid testing same plane 2 times
1261        std::swap(polys[currentIdx], polys[candidateIdx]);
1262       
1263        return currentIdx;
1264        //return Random((int)polys.size());
1265}
1266
1267float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1268                                                          const PolygonContainer &polys) const
1269{
1270        float val = 0;
1271
1272        float sumBalancedPolys = 0;
1273        float sumSplits = 0;
1274        float sumPolyArea = 0;
1275        float sumBalancedViewCells = 0;
1276        float sumBlockedRays = 0;
1277        float totalBlockedRays = 0;
1278        //float totalArea = 0;
1279        int totalViewCells = 0;
1280
1281        // need three unique ids for each type of view cell
1282        // for balanced view cells criterium
1283        ViewCell::NewMail();
1284        const int backId = ViewCell::sMailId;
1285        ViewCell::NewMail();
1286        const int frontId = ViewCell::sMailId;
1287        ViewCell::NewMail();
1288        const int frontAndBackId = ViewCell::sMailId;
1289
1290        PolygonContainer::const_iterator it, it_end = polys.end();
1291
1292        for (it = polys.begin(); it != it_end; ++ it)
1293        {
1294                const int classification = (*it)->ClassifyPlane(candidatePlane);
1295
1296                if (mSplitPlaneStrategy & BALANCED_POLYS)
1297                        sumBalancedPolys += sBalancedPolysTable[classification];
1298               
1299                if (mSplitPlaneStrategy & LEAST_SPLITS)
1300                        sumSplits += sLeastPolySplitsTable[classification];
1301
1302                if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1303                {
1304                        if (classification == Polygon3::COINCIDENT)
1305                                sumPolyArea += (*it)->GetArea();
1306                        //totalArea += area;
1307                }
1308               
1309                if (mSplitPlaneStrategy & BLOCKED_RAYS)
1310                {
1311                        const float blockedRays = (float)(*it)->mPiercingRays.size();
1312               
1313                        if (classification == Polygon3::COINCIDENT)
1314                                sumBlockedRays += blockedRays;
1315                       
1316                        totalBlockedRays += blockedRays;
1317                }
1318
1319                // assign view cells to back or front according to classificaion
1320                if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1321                {
1322                        MeshInstance *viewCell = (*it)->mParent;
1323               
1324                        // assure that we only count a view cell
1325                        // once for the front and once for the back side of the plane
1326                        if (classification == Polygon3::FRONT_SIDE)
1327                        {
1328                                if ((viewCell->mMailbox != frontId) &&
1329                                        (viewCell->mMailbox != frontAndBackId))
1330                                {
1331                                        sumBalancedViewCells += 1.0;
1332
1333                                        if (viewCell->mMailbox != backId)
1334                                                viewCell->mMailbox = frontId;
1335                                        else
1336                                                viewCell->mMailbox = frontAndBackId;
1337                                       
1338                                        ++ totalViewCells;
1339                                }
1340                        }
1341                        else if (classification == Polygon3::BACK_SIDE)
1342                        {
1343                                if ((viewCell->mMailbox != backId) &&
1344                                    (viewCell->mMailbox != frontAndBackId))
1345                                {
1346                                        sumBalancedViewCells -= 1.0;
1347
1348                                        if (viewCell->mMailbox != frontId)
1349                                                viewCell->mMailbox = backId;
1350                                        else
1351                                                viewCell->mMailbox = frontAndBackId;
1352
1353                                        ++ totalViewCells;
1354                                }
1355                        }
1356                }
1357        }
1358
1359        const float polysSize = (float)polys.size() + Limits::Small;
1360
1361        // all values should be approx. between 0 and 1 so they can be combined
1362        // and scaled with the factors according to their importance
1363        if (mSplitPlaneStrategy & BALANCED_POLYS)
1364                val += mBalancedPolysFactor * fabs(sumBalancedPolys) / polysSize;
1365       
1366        if (mSplitPlaneStrategy & LEAST_SPLITS) 
1367                val += mLeastSplitsFactor * sumSplits / polysSize;
1368
1369        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1370                // HACK: polys.size should be total area so scaling is between 0 and 1
1371                val += mLargestPolyAreaFactor * (float)polys.size() / sumPolyArea;
1372
1373        if (mSplitPlaneStrategy & BLOCKED_RAYS)
1374                if (totalBlockedRays != 0)
1375                        val += mBlockedRaysFactor * (totalBlockedRays - sumBlockedRays) / totalBlockedRays;
1376
1377        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1378                val += mBalancedViewCellsFactor * fabs(sumBalancedViewCells) /
1379                        ((float)totalViewCells + Limits::Small);
1380       
1381        return val;
1382}
1383
1384bool BspTree::BoundRay(const Ray &ray, float &minT, float &maxT) const
1385{
1386        maxT = 1e6;
1387        minT = 0;
1388       
1389        // test with tree bounding box
1390        if (!mBox.GetMinMaxT(ray, &minT, &maxT))
1391                return false;
1392
1393        if (minT < 0) // start ray from origin
1394                minT = 0;
1395
1396        // bound ray or line segment
1397        if ((ray.GetType() == Ray::LOCAL_RAY) &&
1398            !ray.intersections.empty() &&
1399                (ray.intersections[0].mT <= maxT))
1400        {
1401                maxT = ray.intersections[0].mT;
1402        }
1403
1404        return true;
1405}
1406
1407float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1408                                                          const BoundedRayContainer &rays,
1409                                                          const int pvs,
1410                                                          const float area,
1411                                                          const BspNodeGeometry &cell) const
1412{
1413        float val = 0;
1414
1415        float sumBalancedRays = 0;
1416        float sumRaySplits = 0;
1417       
1418        int backId = 0;
1419        int frontId = 0;
1420        int frontAndBackId = 0;
1421
1422        int frontPvs = 0;
1423        int backPvs = 0;
1424
1425        // probability that view point lies in child
1426        float pOverall = 0;
1427        float pFront = 0;
1428        float pBack = 0;
1429
1430        if (mSplitPlaneStrategy & PVS)
1431        {
1432                // create three unique ids for pvs heuristics
1433                Intersectable::NewMail(); backId = ViewCell::sMailId;
1434                Intersectable::NewMail(); frontId = ViewCell::sMailId;
1435                Intersectable::NewMail(); frontAndBackId = ViewCell::sMailId;
1436
1437                if (mPvsUseArea) // use front and back cell areas to approximate volume
1438                {       
1439                        // construct child geometry with regard to the candidate split plane
1440                        BspNodeGeometry frontCell;
1441                        BspNodeGeometry backCell;
1442
1443                        cell.SplitGeometry(frontCell, backCell, *this, candidatePlane);
1444               
1445                        pFront = frontCell.GetArea();
1446                        pBack = backCell.GetArea();
1447
1448                        pOverall = area;
1449                }
1450        }
1451                       
1452        BoundedRayContainer::const_iterator rit, rit_end = rays.end();
1453
1454        for (rit = rays.begin(); rit != rays.end(); ++ rit)
1455        {
1456                Ray *ray = (*rit)->mRay;
1457                const float minT = (*rit)->mMinT;
1458                const float maxT = (*rit)->mMaxT;
1459
1460                Vector3 entP, extP;
1461
1462                const int cf =
1463                        ray->ClassifyPlane(candidatePlane, minT, maxT, entP, extP);
1464
1465                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1466                {
1467                        sumBalancedRays += sBalancedRaysTable[cf];
1468                }
1469               
1470                if (mSplitPlaneStrategy & BALANCED_RAYS)
1471                {
1472                        sumRaySplits += sLeastRaySplitsTable[cf];
1473                }
1474
1475                if (mSplitPlaneStrategy & PVS)
1476                {
1477                        if (!ray->intersections.empty())
1478                        {
1479                                // in case the ray intersects an objcrs
1480                                // assure that we only count a object
1481                                // once for the front and once for the back side of the plane
1482                                IncPvs(*ray->intersections[0].mObject, frontPvs, backPvs,
1483                                           cf, frontId, backId, frontAndBackId);
1484                        }
1485
1486                        // the source object in the origin of the ray
1487                        if (ray->sourceObject.mObject)
1488                        {
1489                                IncPvs(*ray->sourceObject.mObject, frontPvs, backPvs,
1490                                           cf, frontId, backId, frontAndBackId);
1491                        }
1492
1493                        if (!mPvsUseArea) // use front and back cell areas to approximate volume
1494                        {       
1495                                float len = Distance(entP, extP);
1496                                pOverall += len;
1497
1498                                // use length of rays to approximate volume
1499                                switch (cf)
1500                                {
1501                                        case Ray::COINCIDENT:
1502                                                pBack += len;
1503                                                pFront += len;                                         
1504                                                break;
1505                                        case Ray::BACK:
1506                                                pBack += len;
1507                                                break;
1508                                        case Ray::FRONT:
1509                                                pFront += len;
1510                                                break;
1511                                        case Ray::FRONT_BACK:
1512                                                {
1513                                                        // find intersection of ray segment with plane
1514                                                        const Vector3 extp = ray->Extrap(maxT);
1515                                                        const float t = candidatePlane.FindT(ray->GetLoc(), extp);
1516                                       
1517                                                        const float newT = t * maxT;
1518                                                        float newLen = Distance(ray->Extrap(newT), extp);
1519
1520                                                        pFront += len - newLen;
1521                                                        pBack += newLen;
1522                                                }
1523                                                break;
1524                                        case Ray::BACK_FRONT:
1525                                                {
1526                                                        // find intersection of ray segment with plane
1527                                                        const Vector3 extp = ray->Extrap(maxT);
1528                                                        const float t = candidatePlane.FindT(ray->GetLoc(), extp);
1529                                       
1530                                                        const float newT = t * maxT;
1531                                                        float newLen = Distance(ray->Extrap(newT), extp);
1532
1533                                                        pFront += len;
1534                                                        pBack += len - newLen;
1535                                                }
1536                                                break;
1537                                        default:
1538                                                Debug << "Should not come here" << endl;
1539                                                break;
1540                                }
1541                        }
1542                }
1543        }
1544
1545        const float raysSize = (float)rays.size() + Limits::Small;
1546        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1547                val += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1548
1549        if (mSplitPlaneStrategy & BALANCED_RAYS)
1550                val += mBalancedRaysFactor * fabs(sumBalancedRays) /  raysSize;
1551
1552        float denom = pOverall * (float)pvs * 2.0f + Limits::Small;
1553        if ((mSplitPlaneStrategy & PVS) && area && pvs)
1554        {
1555                val += mPvsFactor * (frontPvs * pFront + (backPvs * pBack)) / denom;
1556
1557                // give penalty to unbalanced split
1558                if (0)
1559                if (((pFront * 0.2 + Limits::Small) > pBack) || (pFront < (pBack * 0.2 + Limits::Small)))
1560                        val += 0.5;
1561        }
1562
1563#ifdef _DEBUG
1564        Debug << "totalpvs: " << pvs << " ptotal: " << pOverall
1565                  << " frontpvs: " << frontPvs << " pFront: " << pFront
1566                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
1567#endif
1568        return val;
1569}
1570
1571void BspTree::IncPvs(Intersectable &obj,
1572                                         int &frontPvs,
1573                                         int &backPvs,
1574                                         const int cf,
1575                                         const int frontId,
1576                                         const int backId,
1577                                         const int frontAndBackId) const
1578{
1579        // TODO: does this really belong to no pvs?
1580        //if (cf == Ray::COINCIDENT) return;
1581
1582        if (cf == Ray::FRONT)
1583        {
1584                if ((obj.mMailbox != frontId) &&
1585                        (obj.mMailbox != frontAndBackId))
1586                {
1587                        ++ frontPvs;
1588
1589                        if (obj.mMailbox != backId)
1590                                obj.mMailbox = frontId;
1591                        else
1592                                obj.mMailbox = frontAndBackId;                                 
1593                }
1594        }
1595        else if (cf == Ray::BACK)
1596        {
1597                if ((obj.mMailbox != backId) &&
1598                        (obj.mMailbox != frontAndBackId))
1599                {
1600                        ++ backPvs;
1601
1602                        if (obj.mMailbox != frontId)
1603                                obj.mMailbox = backId;
1604                        else
1605                                obj.mMailbox = frontAndBackId;
1606                }
1607        }
1608        // object belongs to both PVS
1609        else if ((cf == Ray::FRONT_BACK) || (cf == Ray::BACK_FRONT) ||(cf == Ray::COINCIDENT))
1610        {
1611                if (obj.mMailbox !=  frontAndBackId)
1612                {
1613                        if (obj.mMailbox != frontId)
1614                                ++ frontPvs;
1615                        if (obj.mMailbox != backId)
1616                                ++ backPvs;
1617               
1618                        obj.mMailbox = frontAndBackId;
1619                }
1620        }
1621}
1622
1623float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1624                                                          BspTraversalData &data) const
1625{
1626        float val = 0;
1627
1628        if (mSplitPlaneStrategy & VERTICAL_AXIS)
1629        {
1630                Vector3 tinyAxis(0,0,0); tinyAxis[mBox.Size().TinyAxis()] = 1.0f;
1631                // we put a penalty on the dot product between the "tiny" vertical axis
1632                // and the split plane axis
1633                val += mVerticalSplitsFactor *
1634                           fabs(DotProd(candidatePlane.mNormal, tinyAxis));
1635        }
1636
1637        // the following criteria loop over all polygons to find the cost value
1638        if ((mSplitPlaneStrategy & BALANCED_POLYS)      ||
1639                (mSplitPlaneStrategy & LEAST_SPLITS)        ||
1640                (mSplitPlaneStrategy & LARGEST_POLY_AREA)   ||
1641                (mSplitPlaneStrategy & BALANCED_VIEW_CELLS) ||
1642                (mSplitPlaneStrategy & BLOCKED_RAYS))
1643        {
1644                val += SplitPlaneCost(candidatePlane, *data.mPolygons);
1645        }
1646
1647        // the following criteria loop over all rays to find the cost value
1648        if ((mSplitPlaneStrategy & BALANCED_RAYS)      ||
1649                (mSplitPlaneStrategy & LEAST_RAY_SPLITS)   ||
1650                (mSplitPlaneStrategy & PVS))
1651        {
1652                val += SplitPlaneCost(candidatePlane, *data.mRays, data.mPvs,
1653                                                          data.mArea, *data.mGeometry);
1654        }
1655
1656        // return linear combination of the sums
1657        return val;
1658}
1659
1660void BspTree::CollectLeaves(vector<BspLeaf *> &leaves) const
1661{
1662        stack<BspNode *> nodeStack;
1663        nodeStack.push(mRoot);
1664 
1665        while (!nodeStack.empty())
1666        {
1667                BspNode *node = nodeStack.top();
1668   
1669                nodeStack.pop();
1670   
1671                if (node->IsLeaf())
1672                {
1673                        BspLeaf *leaf = (BspLeaf *)node;               
1674                        leaves.push_back(leaf);
1675                }
1676                else
1677                {
1678                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1679
1680                        nodeStack.push(interior->GetBack());
1681                        nodeStack.push(interior->GetFront());
1682                }
1683        }
1684}
1685
1686AxisAlignedBox3 BspTree::GetBoundingBox() const
1687{
1688        return mBox;
1689}
1690
1691BspNode *BspTree::GetRoot() const
1692{
1693        return mRoot;
1694}
1695
1696void BspTree::EvaluateLeafStats(const BspTraversalData &data)
1697{
1698        // the node became a leaf -> evaluate stats for leafs
1699        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1700
1701        if (data.mDepth >= mTermMaxDepth)
1702                ++ mStat.maxDepthNodes;
1703       
1704        // store maximal and minimal depth
1705        if (data.mDepth > mStat.maxDepth)
1706                mStat.maxDepth = data.mDepth;
1707
1708        if (data.mDepth < mStat.minDepth)
1709                mStat.minDepth = data.mDepth;
1710
1711        // accumulate depth to compute average depth
1712        mStat.accumDepth += data.mDepth;
1713       
1714#ifdef _DEBUG
1715        Debug << "BSP stats: "
1716                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1717                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1718                  << "Area: " << data.mArea << " (min: " << mTermMinArea << "), "
1719                  << "#polygons: " << (int)data.mPolygons->size() << " (max: " << mTermMaxPolygons << "), "
1720                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMaxRays << "), "
1721                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1722                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1723#endif
1724}
1725
1726int BspTree::CastRay(Ray &ray)
1727{
1728        int hits = 0;
1729 
1730        stack<BspRayTraversalData> tStack;
1731 
1732        float maxt, mint;
1733
1734        if (!BoundRay(ray, mint, maxt))
1735                return 0;
1736
1737        Intersectable::NewMail();
1738
1739        Vector3 entp = ray.Extrap(mint);
1740        Vector3 extp = ray.Extrap(maxt);
1741 
1742        BspNode *node = mRoot;
1743        BspNode *farChild = NULL;
1744       
1745        while (1)
1746        {
1747                if (!node->IsLeaf())
1748                {
1749                        BspInterior *in = (BspInterior *) node;
1750                       
1751                        Plane3 *splitPlane = in->GetPlane();
1752
1753                        int entSide = splitPlane->Side(entp);
1754                        int extSide = splitPlane->Side(extp);
1755
1756                        Vector3 intersection;
1757
1758                        if (entSide < 0)
1759                        {
1760                                node = in->GetBack();
1761
1762                                if(extSide <= 0) // plane does not split ray => no far child
1763                                        continue;
1764                                       
1765                                farChild = in->GetFront(); // plane splits ray
1766
1767                        } else if (entSide > 0)
1768                        {
1769                                node = in->GetFront();
1770
1771                                if (extSide >= 0) // plane does not split ray => no far child
1772                                        continue;
1773
1774                                farChild = in->GetBack(); // plane splits ray                   
1775                        }
1776                        else // ray and plane are coincident
1777                        {
1778                                // WHAT TO DO IN THIS CASE ?
1779                                //break;
1780                                node = in->GetFront();
1781                                continue;
1782                        }
1783
1784                        // push data for far child
1785                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
1786
1787                        // find intersection of ray segment with plane
1788                        float t;
1789                        extp = splitPlane->FindIntersection(ray.GetLoc(), extp, &t);
1790                        maxt *= t;
1791                       
1792                } else // reached leaf => intersection with view cell
1793                {
1794                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1795     
1796                        if (!leaf->mViewCell->Mailed())
1797                        {
1798                                ray.bspIntersections.push_back(Ray::BspIntersection(maxt, leaf));
1799                                leaf->mViewCell->Mail();
1800                                ++ hits;
1801                        }
1802                       
1803                        //-- fetch the next far child from the stack
1804                        if (tStack.empty())
1805                                break;
1806     
1807                        entp = extp;
1808                        mint = maxt; // NOTE: need this?
1809
1810                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1811                                break;
1812
1813                        BspRayTraversalData &s = tStack.top();
1814
1815                        node = s.mNode;
1816                        extp = s.mExitPoint;
1817                        maxt = s.mMaxT;
1818
1819                        tStack.pop();
1820                }
1821        }
1822
1823        return hits;
1824}
1825
1826bool BspTree::Export(const string filename)
1827{
1828        Exporter *exporter = Exporter::GetExporter(filename);
1829
1830        if (exporter)
1831        {
1832                exporter->ExportBspTree(*this);
1833                return true;
1834        }       
1835
1836        return false;
1837}
1838
1839void BspTree::CollectViewCells(ViewCellContainer &viewCells) const
1840{
1841        stack<BspNode *> nodeStack;
1842        nodeStack.push(mRoot);
1843
1844        ViewCell::NewMail();
1845
1846        while (!nodeStack.empty())
1847        {
1848                BspNode *node = nodeStack.top();
1849                nodeStack.pop();
1850
1851                if (node->IsLeaf())
1852                {
1853                        ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->mViewCell;
1854
1855                        if (!viewCell->Mailed())
1856                        {
1857                                viewCell->Mail();
1858                                viewCells.push_back(viewCell);
1859                        }
1860                }
1861                else
1862                {
1863                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1864
1865                        nodeStack.push(interior->mFront);
1866                        nodeStack.push(interior->mBack);
1867                }
1868        }
1869}
1870
1871void BspTree::EvaluateViewCellsStats(BspViewCellsStatistics &stat) const
1872{
1873        stat.Reset();
1874
1875        stack<BspNode *> nodeStack;
1876        nodeStack.push(mRoot);
1877
1878        ViewCell::NewMail();
1879
1880        // exclude root cell
1881        mRootCell->Mail();
1882
1883        while (!nodeStack.empty())
1884        {
1885                BspNode *node = nodeStack.top();
1886                nodeStack.pop();
1887
1888                if (node->IsLeaf())
1889                {
1890                        ++ stat.bspLeaves;
1891
1892                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->mViewCell;
1893
1894                        if (!viewCell->Mailed())
1895                        {
1896                                viewCell->Mail();
1897                               
1898                                ++ stat.viewCells;
1899                                const int pvsSize = viewCell->GetPvs().GetSize();
1900
1901                stat.pvs += pvsSize;
1902
1903                                if (pvsSize < 1)
1904                                        ++ stat.emptyPvs;
1905
1906                                if (pvsSize > stat.maxPvs)
1907                                        stat.maxPvs = pvsSize;
1908
1909                                if (pvsSize < stat.minPvs)
1910                                        stat.minPvs = pvsSize;
1911
1912                                if ((int)viewCell->mBspLeaves.size() > stat.maxBspLeaves)
1913                                        stat.maxBspLeaves = (int)viewCell->mBspLeaves.size();           
1914                        }
1915                }
1916                else
1917                {
1918                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1919
1920                        nodeStack.push(interior->mFront);
1921                        nodeStack.push(interior->mBack);
1922                }
1923        }
1924}
1925
1926bool BspTree::MergeViewCells(BspLeaf *front, BspLeaf *back) const
1927{
1928        BspViewCell *viewCell =
1929                dynamic_cast<BspViewCell *>(ViewCell::Merge(*front->mViewCell, *back->mViewCell));
1930       
1931        if (!viewCell)
1932                return false;
1933
1934        // change view cells of all leaves associated with the
1935        // previous view cells
1936
1937        BspViewCell *fVc = front->mViewCell;
1938        BspViewCell *bVc = back->mViewCell;
1939
1940        vector<BspLeaf *> fLeaves = fVc->mBspLeaves;
1941        vector<BspLeaf *> bLeaves = bVc->mBspLeaves;
1942
1943        vector<BspLeaf *>::const_iterator it;
1944       
1945        for (it = fLeaves.begin(); it != fLeaves.end(); ++ it)
1946        {
1947                (*it)->SetViewCell(viewCell);
1948                viewCell->mBspLeaves.push_back(*it);
1949        }
1950        for (it = bLeaves.begin(); it != bLeaves.end(); ++ it)
1951        {
1952                (*it)->SetViewCell(viewCell);
1953                viewCell->mBspLeaves.push_back(*it);
1954        }
1955       
1956        DEL_PTR(fVc);
1957        DEL_PTR(bVc);
1958
1959        return true;
1960}
1961
1962bool BspTree::ShouldMerge(BspLeaf *front, BspLeaf *back) const
1963{
1964        ViewCell *fvc = front->mViewCell;
1965        ViewCell *bvc = back->mViewCell;
1966
1967        if ((fvc == mRootCell) || (bvc == mRootCell) || (fvc == bvc))
1968                return false;
1969
1970        int fdiff = fvc->GetPvs().Diff(bvc->GetPvs());
1971
1972        if (fvc->GetPvs().GetSize() + fdiff < mMaxPvs)
1973        {
1974                if ((fvc->GetPvs().GetSize() < mMinPvs) ||     
1975                        (bvc->GetPvs().GetSize() < mMinPvs) ||
1976                        ((fdiff < mMinPvsDif) && (bvc->GetPvs().Diff(fvc->GetPvs()) < mMinPvsDif)))
1977                {
1978                        return true;
1979                }
1980        }
1981       
1982        return false;
1983}
1984
1985void BspTree::SetGenerateViewCells(int generateViewCells)
1986{
1987        mGenerateViewCells = generateViewCells;
1988}
1989
1990BspTreeStatistics &BspTree::GetStat()
1991{
1992        return mStat;
1993}
1994
1995float BspTree::AccumulatedRayLength(BoundedRayContainer &rays) const
1996{
1997        float len = 0;
1998
1999        BoundedRayContainer::const_iterator it, it_end = rays.end();
2000
2001        for (it = rays.begin(); it != it_end; ++ it)
2002        {
2003                len += SqrDistance((*it)->mRay->Extrap((*it)->mMinT),
2004                                                   (*it)->mRay->Extrap((*it)->mMaxT));
2005        }
2006
2007        return len;
2008}
2009
2010int BspTree::SplitRays(const Plane3 &plane,
2011                                           BoundedRayContainer &rays,
2012                                           BoundedRayContainer &frontRays,
2013                                           BoundedRayContainer &backRays)
2014{
2015        int splits = 0;
2016
2017        while (!rays.empty())
2018        {
2019                BoundedRay *bRay = rays.back();
2020                Ray *ray = bRay->mRay;
2021                float minT = bRay->mMinT;
2022                float maxT = bRay->mMaxT;
2023
2024                rays.pop_back();
2025       
2026                Vector3 entP, extP;
2027
2028                const int cf =
2029                        ray->ClassifyPlane(plane, minT, maxT, entP, extP);
2030               
2031                // set id to ray classification
2032                ray->SetId(cf);
2033
2034                switch (cf)
2035                {
2036                case Ray::COINCIDENT: // TODO: should really discard ray?
2037                        frontRays.push_back(bRay);
2038                        //DEL_PTR(bRay);
2039                        break;
2040                case Ray::BACK:
2041                        backRays.push_back(bRay);
2042                        break;
2043                case Ray::FRONT:
2044                        frontRays.push_back(bRay);
2045                        break;
2046                case Ray::FRONT_BACK:
2047                        {
2048                                // find intersection of ray segment with plane
2049                                const float t = plane.FindT(ray->GetLoc(), extP);
2050                               
2051                                const float newT = t * maxT;
2052
2053                                frontRays.push_back(new BoundedRay(ray, minT, newT));
2054                                backRays.push_back(new BoundedRay(ray, newT, maxT));
2055
2056                                DEL_PTR(bRay);
2057                        }
2058                        break;
2059                case Ray::BACK_FRONT:
2060                        {
2061                                // find intersection of ray segment with plane
2062                                const float t = plane.FindT(ray->GetLoc(), extP);
2063                                const float newT = t * bRay->mMaxT;
2064
2065                                backRays.push_back(new BoundedRay(ray, bRay->mMinT, newT));
2066                                frontRays.push_back(new BoundedRay(ray, newT, bRay->mMaxT));
2067                                DEL_PTR(bRay);
2068
2069                                ++ splits;
2070                        }
2071                        break;
2072                default:
2073                        Debug << "Should not come here" << endl;
2074                        break;
2075                }
2076        }
2077
2078        return splits;
2079}
2080
2081void BspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2082{
2083        BspNode *lastNode;
2084        do
2085        {
2086                lastNode = n;
2087
2088                // want to get planes defining geometry of this node => don't take
2089                // split plane of node itself
2090                n = n->GetParent();
2091               
2092                if (n)
2093                {
2094                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2095                        Plane3 halfSpace = *dynamic_cast<BspInterior *>(interior)->GetPlane();
2096
2097            if (interior->mFront != lastNode)
2098                                halfSpace.ReverseOrientation();
2099
2100                        halfSpaces.push_back(halfSpace);
2101                }
2102        }
2103        while (n);
2104}
2105
2106void BspTree::ConstructGeometry(BspNode *n, BspNodeGeometry &cell) const
2107{
2108        PolygonContainer polys;
2109        ConstructGeometry(n, polys);
2110        cell.mPolys = polys;
2111}
2112
2113void BspTree::ConstructGeometry(BspViewCell *vc, PolygonContainer &cell) const
2114{
2115        vector<BspLeaf *> leaves = vc->mBspLeaves;
2116
2117        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2118
2119        for (it = leaves.begin(); it != it_end; ++ it)
2120                ConstructGeometry(*it, cell);
2121}
2122
2123
2124void BspTree::ConstructGeometry(BspNode *n, PolygonContainer &cell) const
2125{
2126        vector<Plane3> halfSpaces;
2127        ExtractHalfSpaces(n, halfSpaces);
2128
2129        PolygonContainer candidatePolys;
2130
2131        // bounded planes are added to the polygons (reverse polygons
2132        // as they have to be outfacing
2133        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
2134        {
2135                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
2136               
2137                if (p->Valid())
2138                {
2139                        candidatePolys.push_back(p->CreateReversePolygon());
2140                        DEL_PTR(p);
2141                }
2142        }
2143
2144        // add faces of bounding box (also could be faces of the cell)
2145        for (int i = 0; i < 6; ++ i)
2146        {
2147                VertexContainer vertices;
2148       
2149                for (int j = 0; j < 4; ++ j)
2150                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2151
2152                candidatePolys.push_back(new Polygon3(vertices));
2153        }
2154
2155        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2156        {
2157                // polygon is split by all other planes
2158                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2159                {
2160                        if (i == j) // polygon and plane are coincident
2161                                continue;
2162
2163                        VertexContainer splitPts;
2164                        Polygon3 *frontPoly, *backPoly;
2165
2166                        const int cf = candidatePolys[i]->ClassifyPlane(halfSpaces[j]);
2167                       
2168                        switch (cf)
2169                        {
2170                                case Polygon3::SPLIT:
2171                                        frontPoly = new Polygon3();
2172                                        backPoly = new Polygon3();
2173
2174                                        candidatePolys[i]->Split(halfSpaces[j], *frontPoly,
2175                                                                                         *backPoly, splitPts);
2176
2177                                        DEL_PTR(candidatePolys[i]);
2178
2179                                        if (frontPoly->Valid())
2180                                                candidatePolys[i] = frontPoly;
2181                                        else
2182                                                DEL_PTR(frontPoly);
2183
2184                                        DEL_PTR(backPoly);
2185                                        break;
2186                                case Polygon3::BACK_SIDE:
2187                                        DEL_PTR(candidatePolys[i]);
2188                                        break;
2189                                // just take polygon as it is
2190                                case Polygon3::FRONT_SIDE:
2191                                case Polygon3::COINCIDENT:
2192                                default:
2193                                        break;
2194                        }
2195                }
2196               
2197                if (candidatePolys[i])
2198                        cell.push_back(candidatePolys[i]);
2199        }
2200}
2201
2202
2203int BspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2204                                                   const bool onlyUnmailed) const
2205{
2206        PolygonContainer cell;
2207
2208        ConstructGeometry(n, cell);
2209
2210        stack<BspNode *> nodeStack;
2211        nodeStack.push(mRoot);
2212               
2213        // planes needed to verify that we found neighbor leaf.
2214        vector<Plane3> halfSpaces;
2215        ExtractHalfSpaces(n, halfSpaces);
2216
2217        while (!nodeStack.empty())
2218        {
2219                BspNode *node = nodeStack.top();
2220                nodeStack.pop();
2221
2222                if (node->IsLeaf())
2223                {
2224            if (node != n && (!onlyUnmailed || !node->Mailed()))
2225                        {
2226                                // test all planes of current node if candidate really
2227                                // is neighbour
2228                                PolygonContainer neighborCandidate;
2229                                ConstructGeometry(node, neighborCandidate);
2230                               
2231                                bool isAdjacent = true;
2232                                for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2233                                {
2234                                        const int cf =
2235                                                Polygon3::ClassifyPlane(neighborCandidate, halfSpaces[i]);
2236
2237                                        if (cf == Polygon3::BACK_SIDE)
2238                                                isAdjacent = false;
2239                                }
2240
2241                                if (isAdjacent)
2242                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2243
2244                                CLEAR_CONTAINER(neighborCandidate);
2245                        }
2246                }
2247                else
2248                {
2249                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2250       
2251                        const int cf = Polygon3::ClassifyPlane(cell, interior->mPlane);
2252
2253                        if (cf == Polygon3::FRONT_SIDE)
2254                                nodeStack.push(interior->mFront);
2255                        else
2256                                if (cf == Polygon3::BACK_SIDE)
2257                                        nodeStack.push(interior->mBack);
2258                                else
2259                                {
2260                                        // random decision
2261                                        nodeStack.push(interior->mBack);
2262                                        nodeStack.push(interior->mFront);
2263                                }
2264                }
2265        }
2266       
2267        CLEAR_CONTAINER(cell);
2268        return (int)neighbors.size();
2269}
2270
2271BspLeaf *BspTree::GetRandomLeaf(const Plane3 &halfspace)
2272{
2273    stack<BspNode *> nodeStack;
2274        nodeStack.push(mRoot);
2275       
2276        int mask = rand();
2277 
2278        while (!nodeStack.empty())
2279        {
2280                BspNode *node = nodeStack.top();
2281                nodeStack.pop();
2282         
2283                if (node->IsLeaf())
2284                {
2285                        return dynamic_cast<BspLeaf *>(node);
2286                }
2287                else
2288                {
2289                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2290                       
2291                        BspNode *next;
2292       
2293                        PolygonContainer cell;
2294
2295                        // todo: not very efficient: constructs full cell everytime
2296                        ConstructGeometry(interior, cell);
2297
2298                        const int cf = Polygon3::ClassifyPlane(cell, halfspace);
2299
2300                        if (cf == Polygon3::BACK_SIDE)
2301                                next = interior->mFront;
2302                        else
2303                                if (cf == Polygon3::FRONT_SIDE)
2304                                        next = interior->mFront;
2305                        else
2306                        {
2307                                // random decision
2308                                if (mask & 1)
2309                                        next = interior->mBack;
2310                                else
2311                                        next = interior->mFront;
2312                                mask = mask >> 1;
2313                        }
2314
2315                        nodeStack.push(next);
2316                }
2317        }
2318       
2319        return NULL;
2320}
2321
2322BspLeaf *BspTree::GetRandomLeaf(const bool onlyUnmailed)
2323{
2324        stack<BspNode *> nodeStack;
2325       
2326        nodeStack.push(mRoot);
2327
2328        int mask = rand();
2329       
2330        while (!nodeStack.empty())
2331        {
2332                BspNode *node = nodeStack.top();
2333                nodeStack.pop();
2334               
2335                if (node->IsLeaf())
2336                {
2337                        if ( (!onlyUnmailed || !node->Mailed()) )
2338                                return dynamic_cast<BspLeaf *>(node);
2339                }
2340                else
2341                {
2342                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2343
2344                        // random decision
2345                        if (mask & 1)
2346                                nodeStack.push(interior->mBack);
2347                        else
2348                                nodeStack.push(interior->mFront);
2349
2350                        mask = mask >> 1;
2351                }
2352        }
2353       
2354        return NULL;
2355}
2356
2357int BspTree::ComputePvsSize(const BoundedRayContainer &rays) const
2358{
2359        int pvsSize = 0;
2360
2361        BoundedRayContainer::const_iterator rit, rit_end = rays.end();
2362
2363        Intersectable::NewMail();
2364
2365        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2366        {
2367                Ray *ray = (*rit)->mRay;
2368               
2369                if (!ray->intersections.empty())
2370                {
2371                        if (!ray->intersections[0].mObject->Mailed())
2372                        {
2373                                ray->intersections[0].mObject->Mail();
2374                                ++ pvsSize;
2375                        }
2376                }
2377                if (ray->sourceObject.mObject)
2378                {
2379                        if (!ray->sourceObject.mObject->Mailed())
2380                        {
2381                                ray->sourceObject.mObject->Mail();
2382                                ++ pvsSize;
2383                        }
2384                }
2385        }
2386
2387        return pvsSize;
2388}
2389
2390/*************************************************************
2391 *            BspNodeGeometry Implementation                 *
2392 *************************************************************/
2393
2394BspNodeGeometry::~BspNodeGeometry()
2395{
2396        CLEAR_CONTAINER(mPolys);
2397}
2398
2399float BspNodeGeometry::GetArea() const
2400{
2401        return Polygon3::GetArea(mPolys);
2402}
2403
2404void BspNodeGeometry::SplitGeometry(BspNodeGeometry &front,
2405                                                                        BspNodeGeometry &back,
2406                                                                        const BspTree &tree,                                             
2407                                                                        const Plane3 &splitPlane) const
2408{       
2409        // get cross section of new polygon
2410        Polygon3 *planePoly = tree.GetBoundingBox().CrossSection(splitPlane);
2411
2412        planePoly = SplitPolygon(planePoly, tree);
2413
2414        //-- plane poly splits all other cell polygons
2415        for (int i = 0; i < (int)mPolys.size(); ++ i)
2416        {
2417                const int cf = mPolys[i]->ClassifyPlane(splitPlane, 0.00001f);
2418                       
2419                // split new polygon with all previous planes
2420                switch (cf)
2421                {
2422                        case Polygon3::SPLIT:
2423                                {
2424                                        Polygon3 *poly = new Polygon3(mPolys[i]->mVertices);
2425
2426                                        Polygon3 *frontPoly = new Polygon3();
2427                                        Polygon3 *backPoly = new Polygon3();
2428                               
2429                                        VertexContainer splitPts;
2430                                               
2431                                        poly->Split(splitPlane, *frontPoly, *backPoly, splitPts);
2432
2433                                        DEL_PTR(poly);
2434
2435                                        if (frontPoly->Valid())
2436                                                front.mPolys.push_back(frontPoly);
2437                                        if (backPoly->Valid())
2438                                                back.mPolys.push_back(backPoly);
2439                                }
2440                               
2441                                break;
2442                        case Polygon3::BACK_SIDE:
2443                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));                     
2444                                break;
2445                        case Polygon3::FRONT_SIDE:
2446                                front.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));     
2447                                break;
2448                        case Polygon3::COINCIDENT:
2449                                //front.mPolys.push_back(CreateReversePolygon(mPolys[i]));
2450                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));
2451                                break;
2452                        default:
2453                                break;
2454                }
2455        }
2456
2457        //-- finally add the new polygon to the child cells
2458        if (planePoly)
2459        {
2460                // add polygon with normal pointing into positive half space to back cell
2461                back.mPolys.push_back(planePoly);
2462                // add polygon with reverse orientation to front cell
2463                front.mPolys.push_back(planePoly->CreateReversePolygon());
2464        }
2465
2466        //Debug << "returning new geometry " << mPolys.size() << " f: " << front.mPolys.size() << " b: " << back.mPolys.size() << endl;
2467        //Debug << "old area " << GetArea() << " f: " << front.GetArea() << " b: " << back.GetArea() << endl;
2468}
2469
2470Polygon3 *BspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
2471                                                                                const BspTree &tree) const
2472{
2473        // polygon is split by all other planes
2474        for (int i = 0; (i < (int)mPolys.size()) && planePoly; ++ i)
2475        {
2476                Plane3 plane = mPolys[i]->GetSupportingPlane();
2477
2478                const int cf =
2479                        planePoly->ClassifyPlane(plane, 0.00001f);
2480                       
2481                // split new polygon with all previous planes
2482                switch (cf)
2483                {
2484                        case Polygon3::SPLIT:
2485                                {
2486                                        VertexContainer splitPts;
2487                               
2488                                        Polygon3 *frontPoly = new Polygon3();
2489                                        Polygon3 *backPoly = new Polygon3();
2490
2491                                        planePoly->Split(plane, *frontPoly, *backPoly, splitPts);
2492                                        DEL_PTR(planePoly);
2493
2494                                        if (backPoly->Valid())
2495                                                planePoly = backPoly;
2496                                        else
2497                                                DEL_PTR(backPoly);
2498                                }
2499                                break;
2500                        case Polygon3::FRONT_SIDE:
2501                                DEL_PTR(planePoly);
2502                break;
2503                        // polygon is taken as it is
2504                        case Polygon3::BACK_SIDE:
2505                        case Polygon3::COINCIDENT:
2506                        default:
2507                                break;
2508                }
2509        }
2510
2511        return planePoly;
2512}
2513
2514void BspViewCellsStatistics::Print(ostream &app) const
2515{
2516        app << "===== BspViewCells statistics ===============\n";
2517
2518        app << setprecision(4);
2519
2520        //app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
2521
2522        app << "#N_OVERALLPVS ( objects in PVS )\n" << pvs << endl;
2523
2524        app << "#N_PMAXPVS ( largest PVS )\n" << maxPvs << endl;
2525
2526        app << "#N_PMINPVS ( smallest PVS )\n" << minPvs << endl;
2527
2528        app << "#N_PAVGPVS ( average PVS )\n" << AvgPvs() << endl;
2529
2530        app << "#N_PEMPTYPVS ( view cells with PVS smaller 2 )\n" << emptyPvs << endl;
2531
2532        app << "#N_VIEWCELLS ( number of view cells)\n" << viewCells << endl;
2533
2534        app << "#N_AVGBSPLEAVES (average number of BSP leaves per view cell )\n" << AvgBspLeaves() << endl;
2535
2536        app << "#N_MAXBSPLEAVES ( maximal number of BSP leaves per view cell )\n" << maxBspLeaves << endl;
2537       
2538        app << "===== END OF BspViewCells statistics ==========\n";
2539}
Note: See TracBrowser for help on using the repository browser.