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

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