source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp @ 667

Revision 667, 77.3 KB checked in by mattausch, 18 years ago (diff)

test version
build script for testing. code is set uo for testing also

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