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

Revision 649, 77.2 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include "Plane3.h"
2#include "ViewCellBsp.h"
3#include "Mesh.h"
4#include "common.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "Polygon3.h"
8#include "Ray.h"
9#include "AxisAlignedBox3.h"
10#include "Triangle3.h"
11#include "Tetrahedron3.h"
12#include "ViewCellsManager.h"
13#include "Exporter.h"
14#include "Plane3.h"
15#include <stack>
16
17
18
19//-- static members
20
21int BspNode::sMailId = 1;
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a minimum number splits in the tree.
25*/
26const float BspTree::sLeastPolySplitsTable[] = {0, 0, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for a balanced tree.
29*/
30const float BspTree::sBalancedPolysTable[] = {1, -1, 0, 0};
31
32/** Evaluates split plane classification with respect to the plane's
33        contribution for a minimum number of ray splits.
34*/
35const float BspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
36/** Evaluates split plane classification with respect to the plane's
37        contribution for balanced rays.
38*/
39const float BspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
40
41int BspTree::sFrontId = 0;
42int BspTree::sBackId = 0;
43int BspTree::sFrontAndBackId = 0;
44
45
46/****************************************************************/
47/*                  class BspNode implementation                */
48/****************************************************************/
49
50
51BspNode::BspNode():
52mParent(NULL), mTreeValid(true), mTimeStamp(0)
53{}
54
55BspNode::BspNode(BspInterior *parent):
56mParent(parent), mTreeValid(true)
57{}
58
59
60bool BspNode::IsRoot() const
61{
62        return mParent == NULL;
63}
64
65
66BspInterior *BspNode::GetParent()
67{
68        return mParent;
69}
70
71
72void BspNode::SetParent(BspInterior *parent)
73{
74        mParent = parent;
75}
76
77
78bool BspNode::IsSibling(BspNode *n) const
79{
80        return  ((this != n) && mParent &&
81                         (mParent->GetFront() == n) || (mParent->GetBack() == n));
82}
83
84
85int BspNode::GetDepth() const
86{
87        int depth = 0;
88        BspNode *p = mParent;
89       
90        while (p)
91        {
92                p = p->mParent;
93                ++ depth;
94        }
95
96        return depth;
97}
98
99
100bool BspNode::TreeValid() const
101{
102        return mTreeValid;
103}
104
105
106void BspNode::SetTreeValid(const bool v)
107{
108        mTreeValid = v;
109}
110
111
112/****************************************************************/
113/*              class BspInterior implementation                */
114/****************************************************************/
115
116
117BspInterior::BspInterior(const Plane3 &plane):
118mPlane(plane), mFront(NULL), mBack(NULL)
119{}
120
121BspInterior::~BspInterior()
122{
123        DEL_PTR(mFront);
124        DEL_PTR(mBack);
125}
126
127bool BspInterior::IsLeaf() const
128{
129        return false;
130}
131
132BspNode *BspInterior::GetBack()
133{
134        return mBack;
135}
136
137BspNode *BspInterior::GetFront()
138{
139        return mFront;
140}
141
142Plane3 BspInterior::GetPlane() const
143{
144        return mPlane;
145}
146
147void BspInterior::ReplaceChildLink(BspNode *oldChild, BspNode *newChild)
148{
149        if (mBack == oldChild)
150                mBack = newChild;
151        else
152                mFront = newChild;
153}
154
155void BspInterior::SetupChildLinks(BspNode *b, BspNode *f)
156{
157    mBack = b;
158    mFront = f;
159}
160
161/****************************************************************/
162/*                  class BspLeaf implementation                */
163/****************************************************************/
164
165
166BspLeaf::BspLeaf(): mViewCell(NULL), mPvs(NULL)
167{
168}
169
170
171BspLeaf::~BspLeaf()
172{
173        DEL_PTR(mPvs);
174}
175
176
177BspLeaf::BspLeaf(ViewCell *viewCell):
178mViewCell(viewCell)
179{
180}
181
182
183BspLeaf::BspLeaf(BspInterior *parent):
184BspNode(parent), mViewCell(NULL), mPvs(NULL)
185{}
186
187
188
189BspLeaf::BspLeaf(BspInterior *parent, ViewCell *viewCell):
190BspNode(parent), mViewCell(viewCell), mPvs(NULL)
191{
192}
193
194ViewCell *BspLeaf::GetViewCell() const
195{
196        return mViewCell;
197}
198
199void BspLeaf::SetViewCell(ViewCell *viewCell)
200{
201        mViewCell = viewCell;
202}
203
204
205bool BspLeaf::IsLeaf() const
206{
207        return true;
208}
209
210
211/*********************************************************************/
212/*                       class BspTree implementation                */
213/*********************************************************************/
214
215BspTree::BspTree(): 
216mRoot(NULL),
217mUseAreaForPvs(false),
218mGenerateViewCells(true),
219mTimeStamp(0)
220{
221        Randomize(); // initialise random generator for heuristics
222
223        mOutOfBoundsCell = GetOrCreateOutOfBoundsCell();
224
225        //-- termination criteria for autopartition
226        environment->GetIntValue("BspTree.Termination.maxDepth", mTermMaxDepth);
227        environment->GetIntValue("BspTree.Termination.minPvs", mTermMinPvs);
228        environment->GetIntValue("BspTree.Termination.minPolygons", mTermMinPolys);
229        environment->GetIntValue("BspTree.Termination.minRays", mTermMinRays);
230        environment->GetFloatValue("BspTree.Termination.minProbability", mTermMinProbability); 
231        environment->GetFloatValue("BspTree.Termination.maxRayContribution", mTermMaxRayContribution);
232        environment->GetFloatValue("BspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
233
234        //-- factors for bsp tree split plane heuristics
235        environment->GetFloatValue("BspTree.Factor.verticalSplits", mVerticalSplitsFactor);
236        environment->GetFloatValue("BspTree.Factor.largestPolyArea", mLargestPolyAreaFactor);
237        environment->GetFloatValue("BspTree.Factor.blockedRays", mBlockedRaysFactor);
238        environment->GetFloatValue("BspTree.Factor.leastRaySplits", mLeastRaySplitsFactor);
239        environment->GetFloatValue("BspTree.Factor.balancedRays", mBalancedRaysFactor);
240        environment->GetFloatValue("BspTree.Factor.pvs", mPvsFactor);
241        environment->GetFloatValue("BspTree.Factor.leastSplits" , mLeastSplitsFactor);
242        environment->GetFloatValue("BspTree.Factor.balancedPolys", mBalancedPolysFactor);
243        environment->GetFloatValue("BspTree.Factor.balancedViewCells", mBalancedViewCellsFactor);
244        environment->GetFloatValue("BspTree.Termination.ct_div_ci", mCtDivCi);
245
246        //-- termination criteria for axis aligned split
247        environment->GetFloatValue("BspTree.Termination.AxisAligned.ct_div_ci", mAxisAlignedCtDivCi);
248        environment->GetFloatValue("BspTree.Termination.maxCostRatio", mMaxCostRatio);
249        environment->GetIntValue("BspTree.Termination.AxisAligned.minPolys",
250                                                         mTermMinPolysForAxisAligned);
251        environment->GetIntValue("BspTree.Termination.AxisAligned.minRays",
252                                                         mTermMinRaysForAxisAligned);
253        environment->GetIntValue("BspTree.Termination.AxisAligned.minObjects",
254                                                         mTermMinObjectsForAxisAligned);
255        //-- partition criteria
256        environment->GetIntValue("BspTree.maxPolyCandidates", mMaxPolyCandidates);
257        environment->GetIntValue("BspTree.maxRayCandidates", mMaxRayCandidates);
258        environment->GetIntValue("BspTree.splitPlaneStrategy", mSplitPlaneStrategy);
259        environment->GetFloatValue("BspTree.AxisAligned.splitBorder", mSplitBorder);
260        environment->GetIntValue("BspTree.maxTests", mMaxTests);
261        environment->GetIntValue("BspTree.Termination.maxViewCells", mMaxViewCells);
262
263        environment->GetFloatValue("BspTree.Construction.epsilon", mEpsilon);
264
265        mSubdivisionStats.open("subdivisionStats.log");
266
267    Debug << "BSP max depth: " << mTermMaxDepth << endl;
268        Debug << "BSP min PVS: " << mTermMinPvs << endl;
269        Debug << "BSP min probability: " << mTermMinProbability << endl;
270        Debug << "BSP max polys: " << mTermMinPolys << endl;
271        Debug << "BSP max rays: " << mTermMinRays << endl;
272        Debug << "BSP max polygon candidates: " << mMaxPolyCandidates << endl;
273        Debug << "BSP max plane candidates: " << mMaxRayCandidates << endl;
274
275        Debug << "Split plane strategy: ";
276        if (mSplitPlaneStrategy & RANDOM_POLYGON)
277                Debug << "random polygon ";
278        if (mSplitPlaneStrategy & AXIS_ALIGNED)
279                Debug << "axis aligned ";
280        if (mSplitPlaneStrategy & LEAST_SPLITS)     
281                Debug << "least splits ";
282        if (mSplitPlaneStrategy & BALANCED_POLYS)
283                Debug << "balanced polygons ";
284        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
285                Debug << "balanced view cells ";
286        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
287                Debug << "largest polygon area ";
288        if (mSplitPlaneStrategy & VERTICAL_AXIS)
289                Debug << "vertical axis ";
290        if (mSplitPlaneStrategy & BLOCKED_RAYS)
291                Debug << "blocked rays ";
292        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
293                Debug << "least ray splits ";
294        if (mSplitPlaneStrategy & BALANCED_RAYS)
295                Debug << "balanced rays ";
296        if (mSplitPlaneStrategy & PVS)
297                Debug << "pvs";
298
299        Debug << endl;
300}
301
302
303const BspTreeStatistics &BspTree::GetStatistics() const
304{
305        return mStat;
306}
307
308
309int BspTree::SplitPolygons(const Plane3 &plane,
310                                                   PolygonContainer &polys,
311                                                   PolygonContainer &frontPolys,
312                                                   PolygonContainer &backPolys,
313                                                   PolygonContainer &coincident) const
314{
315        int splits = 0;
316
317#ifdef _Debug
318        Debug << "splitting polygons of node " << this << " with plane " << mPlane << endl;
319#endif
320
321        PolygonContainer::const_iterator it, it_end = polys.end();
322
323        for (it = polys.begin(); it != polys.end(); ++ it)     
324        {
325                Polygon3 *poly = *it;
326       
327                //-- classify polygon
328                const int cf = poly->ClassifyPlane(plane, mEpsilon);
329
330                switch (cf)
331                {
332                        case Polygon3::COINCIDENT:
333                                coincident.push_back(poly);
334                                break;                 
335                        case Polygon3::FRONT_SIDE:     
336                                frontPolys.push_back(poly);
337                                break;
338                        case Polygon3::BACK_SIDE:
339                                backPolys.push_back(poly);
340                                break;
341                        case Polygon3::SPLIT:
342                                {
343                                        Polygon3 *front_piece = new Polygon3(poly->mParent);
344                                        Polygon3 *back_piece = new Polygon3(poly->mParent);
345
346                                        //-- split polygon into front and back part
347                                        poly->Split(plane,
348                                                                *front_piece,
349                                                                *back_piece,
350                                                                mEpsilon);
351                                       
352                                        ++ splits; // increase number of splits
353
354                                        //-- inherit rays from parent polygon for blocked ray criterium
355                                        poly->InheritRays(*front_piece, *back_piece);
356                               
357                                        // check if polygons still valid
358                                        if (front_piece->Valid(mEpsilon))
359                                                frontPolys.push_back(front_piece);
360                                        else
361                                                DEL_PTR(front_piece);
362                               
363                                        if (back_piece->Valid(mEpsilon))
364                                                backPolys.push_back(back_piece);
365                                        else                           
366                                                DEL_PTR(back_piece);
367                               
368#ifdef _DEBUG
369                                        Debug << "split " << *poly << endl << *front_piece << endl << *back_piece << endl;
370#endif
371                                        DEL_PTR(poly);
372                                }
373                                break;
374                        default:
375                Debug << "SHOULD NEVER COME HERE\n";
376                                break;
377                }
378        }
379
380        return splits;
381}
382
383
384void BspTreeStatistics::Print(ostream &app) const
385{
386        app << "===== BspTree statistics ===============\n";
387
388        app << setprecision(4);
389
390        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
391
392        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
393
394        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
395
396        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
397
398        app << "#N_POLYSPLITS ( Number of polygon splits )\n" << polySplits << "\n";
399
400        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits[0] + splits[1] + splits[2] << endl;
401
402        app << "#N_SPLITS ( Number of splits in axes x y z\n";
403
404        for (int i = 0; i < 3; ++ i)
405                app << splits[i] << " ";
406        app << endl;
407
408        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
409                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
410
411        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
412                << minPvsNodes * 100 / (double)Leaves() << endl;
413
414        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
415                << minRaysNodes * 100 / (double)Leaves() << endl;
416
417        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
418                << maxCostNodes * 100 / (double)Leaves() << endl;
419
420        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
421                << minProbabilityNodes * 100 / (double)Leaves() << endl;
422
423        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
424                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
425
426        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
427
428        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
429
430        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
431
432        app << "#N_INPUTPOLYGONS (number of input polygons )\n" << polys << endl;
433
434        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
435
436        app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl;
437        //app << "#N_PVS: " << pvs << endl;
438
439        app << "#N_ROUTPUT_INPUT_POLYGONS ( ratio polygons after subdivision / input polygons )\n" <<
440                 (polys + polySplits) / (double)polys << endl;
441       
442        app << "===== END OF BspTree statistics ==========\n";
443}
444
445
446BspTree::~BspTree()
447{
448        DEL_PTR(mRoot);
449
450        // TODO must be deleted if used!!
451        //if (mGenerateViewCells) DEL_PTR(mOutOfBoundsCell);
452}
453
454BspViewCell *BspTree::GetOutOfBoundsCell()
455{
456        return mOutOfBoundsCell;
457}
458
459
460BspNode *BspTree::GetRoot() const
461{
462        return mRoot;
463}
464
465BspViewCell *BspTree::GetOrCreateOutOfBoundsCell()
466{
467        if (!mOutOfBoundsCell)
468        {
469                mOutOfBoundsCell = new BspViewCell();
470                mOutOfBoundsCell->SetId(-1);
471                mOutOfBoundsCell->SetValid(false);
472        }
473
474        return mOutOfBoundsCell;
475}
476
477
478void BspTree::InsertViewCell(ViewCell *viewCell)
479{
480        PolygonContainer *polys = new PolygonContainer();
481
482        // don't generate new view cell, insert this one
483        mGenerateViewCells = false;
484        // extract polygons that guide the split process
485        mStat.polys += AddMeshToPolygons(viewCell->GetMesh(), *polys, viewCell);
486        mBox.Include(viewCell->GetBox()); // add to BSP aabb
487
488        InsertPolygons(polys);
489}
490
491
492void BspTree::InsertPolygons(PolygonContainer *polys)
493{       
494        BspTraversalStack tStack;
495
496        // traverse existing tree or create new tree
497    if (!mRoot)
498                mRoot = new BspLeaf();
499
500        tStack.push(BspTraversalData(mRoot,
501                                                                 polys,
502                                                                 0,
503                                                                 mOutOfBoundsCell,
504                                                                 new BoundedRayContainer(),
505                                                                 0,
506                                                                 mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
507                                                                 new BspNodeGeometry()));
508
509        while (!tStack.empty())
510        {
511                // filter polygons donw the tree
512                BspTraversalData tData = tStack.top();
513            tStack.pop();
514                       
515                if (!tData.mNode->IsLeaf())
516                {
517                        BspInterior *interior = dynamic_cast<BspInterior *>(tData.mNode);
518
519                        //-- filter view cell polygons down the tree until a leaf is reached
520                        if (!tData.mPolygons->empty())
521                        {
522                                PolygonContainer *frontPolys = new PolygonContainer();
523                                PolygonContainer *backPolys = new PolygonContainer();
524                                PolygonContainer coincident;
525
526                                int splits = 0;
527               
528                                // split viewcell polygons with respect to split plane
529                                splits += SplitPolygons(interior->GetPlane(),
530                                                                                *tData.mPolygons,
531                                                                                *frontPolys,
532                                                                                *backPolys,
533                                                                                coincident);
534                               
535                                // extract view cells associated with the split polygons
536                                ViewCell *frontViewCell = GetOrCreateOutOfBoundsCell();
537                                ViewCell *backViewCell = GetOrCreateOutOfBoundsCell();
538                       
539                                BspTraversalData frontData(interior->GetFront(),
540                                                                                   frontPolys,
541                                                                                   tData.mDepth + 1,
542                                                                                   mOutOfBoundsCell,   
543                                                                                   tData.mRays,
544                                                                                   tData.mPvs,
545                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
546                                                                                   new BspNodeGeometry());
547
548                                BspTraversalData backData(interior->GetBack(),
549                                                                                  backPolys,
550                                                                                  tData.mDepth + 1,
551                                                                                  mOutOfBoundsCell,     
552                                                                                  tData.mRays,
553                                                                                  tData.mPvs,
554                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
555                                                                                  new BspNodeGeometry());
556
557                                if (!mGenerateViewCells)
558                                {
559                                        ExtractViewCells(frontData,
560                                                                         backData,
561                                                                         coincident,
562                                                                         interior->mPlane);
563                                }
564
565                                // don't need coincident polygons anymore
566                                CLEAR_CONTAINER(coincident);
567
568                                mStat.polySplits += splits;
569
570                                // push the children on the stack
571                                tStack.push(frontData);
572                                tStack.push(backData);
573                        }
574
575                        // cleanup
576                        DEL_PTR(tData.mPolygons);
577                        DEL_PTR(tData.mRays);
578                }
579                else
580                {
581                        // reached leaf => subdivide current viewcell
582                        BspNode *subRoot = Subdivide(tStack, tData);
583                }
584        }
585}
586
587int BspTree::AddMeshToPolygons(Mesh *mesh,
588                                                           PolygonContainer &polys,
589                                                           MeshInstance *parent)
590{
591        FaceContainer::const_iterator fi;
592       
593        // copy the face data to polygons
594        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
595        {
596                Polygon3 *poly = new Polygon3((*fi), mesh);
597               
598                if (poly->Valid(mEpsilon))
599                {
600                        poly->mParent = parent; // set parent intersectable
601                        polys.push_back(poly);
602                }
603                else
604                        DEL_PTR(poly);
605        }
606        return (int)mesh->mFaces.size();
607}
608
609
610int BspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
611                                                          PolygonContainer &polys,
612                                                          int maxObjects)
613{
614        int limit = (maxObjects > 0) ?
615                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
616 
617        int polysSize = 0;
618
619        for (int i = 0; i < limit; ++ i)
620        {
621                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
622                {
623                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
624                        polysSize += AddMeshToPolygons(viewCells[i]->GetMesh(), polys, viewCells[i]);
625                }
626        }
627
628        return polysSize;
629}
630
631
632int BspTree::AddToPolygonSoup(const ObjectContainer &objects,
633                                                          PolygonContainer &polys,
634                                                          int maxObjects,
635                                                          bool addToBbox)
636{
637        int limit = (maxObjects > 0) ?
638                Min((int)objects.size(), maxObjects) : (int)objects.size();
639 
640        for (int i = 0; i < limit; ++i)
641        {
642                Intersectable *object = objects[i];//*it;
643                Mesh *mesh = NULL;
644
645                switch (object->Type()) // extract the meshes
646                {
647                case Intersectable::MESH_INSTANCE:
648                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
649                        break;
650                case Intersectable::VIEW_CELL:
651                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
652                        break;
653                        // TODO: handle transformed mesh instances
654                default:
655                        Debug << "intersectable type not supported" << endl;
656                        break;
657                }
658               
659        if (mesh) // copy the mesh data to polygons
660                {
661                        if (addToBbox)
662                        {
663                                mBox.Include(object->GetBox()); // add to BSP tree aabb
664                        }
665               
666                        AddMeshToPolygons(mesh, polys, mOutOfBoundsCell);
667                }
668        }
669
670        return (int)polys.size();
671}
672
673
674void BspTree::Construct(const ViewCellContainer &viewCells)
675{
676        mStat.nodes = 1;
677        mBox.Initialize();      // initialise bsp tree bounding box
678
679        // copy view cell meshes into one big polygon soup
680        PolygonContainer *polys = new PolygonContainer();
681        mStat.polys = AddToPolygonSoup(viewCells, *polys);
682
683        // view cells are given
684        mGenerateViewCells = false;
685        // construct tree from the view cell polygons
686        Construct(polys, new BoundedRayContainer());
687}
688
689
690void BspTree::Construct(const ObjectContainer &objects)
691{
692        mStat.nodes = 1;
693        mBox.Initialize();      // initialise bsp tree bounding box
694       
695        PolygonContainer *polys = new PolygonContainer();
696
697        mGenerateViewCells = true;
698        // copy mesh instance polygons into one big polygon soup
699        mStat.polys = AddToPolygonSoup(objects, *polys);
700
701        // construct tree from polygon soup
702        Construct(polys, new BoundedRayContainer());
703}
704
705
706void BspTree::PreprocessPolygons(PolygonContainer &polys)
707{
708        // preprocess: throw out polygons coincident to the view space box (not needed)
709        PolygonContainer boxPolys;
710        mBox.ExtractPolys(boxPolys);
711        vector<Plane3> boxPlanes;
712
713        PolygonContainer::iterator pit, pit_end = boxPolys.end();
714
715        // extract planes of box
716        // TODO: can be done more elegantly than first extracting polygons
717        // and take their planes
718        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
719        {
720                boxPlanes.push_back((*pit)->GetSupportingPlane());
721        }
722
723        pit_end = polys.end();
724
725        for (pit = polys.begin(); pit != pit_end; ++ pit)
726        {
727                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
728               
729                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
730                {
731                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
732
733                        if (cf == Polygon3::COINCIDENT)
734                        {
735                                DEL_PTR(*pit);
736                                //Debug << "coincident!!" << endl;
737                        }
738                }
739        }
740
741        // remove deleted entries
742        for (int i = 0; i < (int)polys.size(); ++ i)
743        {
744                while (!polys[i] && (i < (int)polys.size()))
745                {
746                        swap(polys[i], polys.back());
747                        polys.pop_back();
748                }
749        }
750}
751
752
753
754void BspTree::Construct(const RayContainer &sampleRays,
755                                                AxisAlignedBox3 *forcedBoundingBox)
756{
757    mStat.nodes = 1;
758        mBox.Initialize();      // initialise BSP tree bounding box
759       
760        if (forcedBoundingBox)
761                mBox = *forcedBoundingBox;
762
763        PolygonContainer *polys = new PolygonContainer();
764        BoundedRayContainer *rays = new BoundedRayContainer();
765
766        RayContainer::const_iterator rit, rit_end = sampleRays.end();
767
768        // generate view cells
769        mGenerateViewCells = true;
770
771        long startTime = GetTime();
772
773        Debug << "**** Extracting polygons from rays ****\n";
774
775        std::map<Face *, Polygon3 *> facePolyMap;
776
777        //-- extract polygons intersected by the rays
778        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
779        {
780                Ray *ray = *rit;
781       
782                // get ray-face intersection. Store polygon representing the rays together
783                // with rays intersecting the face.
784                if (!ray->intersections.empty())
785                {
786                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->intersections[0].mObject);
787                        Face *face = obj->GetMesh()->mFaces[ray->intersections[0].mFace];
788
789                        std::map<Face *, Polygon3 *>::iterator it = facePolyMap.find(face);
790
791                        if (it != facePolyMap.end())
792                        {
793                                //store rays if needed for heuristics
794                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
795                                        (*it).second->mPiercingRays.push_back(ray);
796                        }
797                        else
798                        {       //store rays if needed for heuristics
799                                Polygon3 *poly = new Polygon3(face, obj->GetMesh());
800                                poly->mParent = obj;
801                                polys->push_back(poly);
802
803                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
804                                        poly->mPiercingRays.push_back(ray);
805
806                                facePolyMap[face] = poly;
807                        }
808                }
809        }
810       
811        facePolyMap.clear();
812
813        // compute bounding box
814        if (!forcedBoundingBox)
815                Polygon3::IncludeInBox(*polys, mBox);
816
817        //-- store rays
818        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
819        {
820                Ray *ray = *rit;
821        ray->SetId(-1); // reset id
822
823                float minT, maxT;
824                if (mBox.GetRaySegment(*ray, minT, maxT))
825                        rays->push_back(new BoundedRay(ray, minT, maxT));
826        }
827
828        // throw out bad polygons
829        PreprocessPolygons(*polys);
830
831        mStat.polys = (int)polys->size();
832
833        Debug << "**** Finished polygon extraction ****" << endl;
834        Debug << (int)polys->size() << " polys extracted from " << (int)sampleRays.size() << " rays" << endl;
835        Debug << "extraction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
836
837        Construct(polys, rays);
838}
839
840
841void BspTree::Construct(const ObjectContainer &objects,
842                                                const RayContainer &sampleRays,
843                                                AxisAlignedBox3 *forcedBoundingBox)
844{
845    mStat.nodes = 1;
846        mBox.Initialize();      // initialise BSP tree bounding box
847       
848        if (forcedBoundingBox)
849                mBox = *forcedBoundingBox;
850
851        BoundedRayContainer *rays = new BoundedRayContainer();
852        PolygonContainer *polys = new PolygonContainer();
853       
854        mGenerateViewCells = true;
855
856        // copy mesh instance polygons into one big polygon soup
857        mStat.polys = AddToPolygonSoup(objects, *polys, 0, !forcedBoundingBox);
858
859
860        RayContainer::const_iterator rit, rit_end = sampleRays.end();
861
862        //-- store rays
863        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
864        {
865                Ray *ray = *rit;
866        ray->SetId(-1); // reset id
867
868                float minT, maxT;
869                if (mBox.GetRaySegment(*ray, minT, maxT))
870                        rays->push_back(new BoundedRay(ray, minT, maxT));
871        }
872
873        PreprocessPolygons(*polys);
874        Debug << "tree has " << (int)polys->size() << " polys, " << (int)sampleRays.size() << " rays" << endl;
875        Construct(polys, rays);
876}
877
878
879void BspTree::Construct(PolygonContainer *polys, BoundedRayContainer *rays)
880{
881        BspTraversalStack tStack;
882
883        mRoot = new BspLeaf();
884
885        // constrruct root node geometry
886        BspNodeGeometry *geom = new BspNodeGeometry();
887        ConstructGeometry(mRoot, *geom);
888
889        BspTraversalData tData(mRoot,
890                                                   polys,
891                                                   0,
892                                                   GetOrCreateOutOfBoundsCell(),
893                                                   rays,
894                                                   ComputePvsSize(*rays),
895                                                   mUseAreaForPvs ? geom->GetArea() : geom->GetVolume(),
896                                                   geom);
897
898        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
899        mTotalPvsSize = tData.mPvs;
900       
901        mSubdivisionStats
902                        << "#ViewCells\n1\n" <<  endl
903                        << "#RenderCostDecrease\n0\n" << endl
904                        << "#TotalRenderCost\n" << mTotalCost << endl
905                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
906
907        tStack.push(tData);
908
909        // used for intermediate time measurements and progress
910        long interTime = GetTime();     
911        int nleaves = 500;
912
913        mStat.Start();
914        cout << "Contructing bsp tree ...\n";
915        long startTime = GetTime();
916        while (!tStack.empty())
917        {
918                tData = tStack.top();
919
920            tStack.pop();
921
922                // subdivide leaf node
923                BspNode *r = Subdivide(tStack, tData);
924
925                if (r == mRoot)
926            Debug << "BSP tree construction time spent at root: "
927                                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl;
928
929                if (mStat.Leaves() >= nleaves)
930                {
931                        nleaves += 500;
932                       
933                        cout << "leaves=" << mStat.Leaves() << endl;
934                        Debug << "needed "
935                                  << TimeDiff(interTime, GetTime())*1e-3
936                                  << " secs to create 500 leaves" << endl;
937                        interTime = GetTime();
938                }
939        }
940
941        cout << "finished\n";
942
943        mStat.Stop();
944}
945
946
947bool BspTree::TerminationCriteriaMet(const BspTraversalData &data) const
948{
949        return
950                (((int)data.mPolygons->size() <= mTermMinPolys) ||
951                 ((int)data.mRays->size() <= mTermMinRays) ||
952                 (data.mPvs <= mTermMinPvs) ||
953                 (data.mProbability <= mTermMinProbability) ||
954                 (data.mDepth >= mTermMaxDepth) ||
955                 (mStat.Leaves() >= mMaxViewCells) ||
956                 (data.GetAvgRayContribution() > mTermMaxRayContribution));
957}
958
959
960BspNode *BspTree::Subdivide(BspTraversalStack &tStack, BspTraversalData &tData)
961{
962        //-- terminate traversal 
963        if (TerminationCriteriaMet(tData))             
964        {
965                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
966       
967                BspViewCell *viewCell;
968
969                // generate new view cell for each leaf
970                if (mGenerateViewCells)
971                        viewCell = new BspViewCell();
972                else
973                        // add view cell to leaf
974                        viewCell = dynamic_cast<BspViewCell *>(tData.mViewCell);
975               
976                leaf->SetViewCell(viewCell);
977                viewCell->mLeaf = leaf;
978
979                if (mUseAreaForPvs)
980                        viewCell->SetArea(tData.mProbability);
981                else
982                        viewCell->SetVolume(tData.mProbability);
983               
984                //-- add pvs
985                if (viewCell != mOutOfBoundsCell)
986                {
987                        int conSamp = 0, sampCon = 0;
988                        AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
989                       
990                        mStat.contributingSamples += conSamp;
991                        mStat.sampleContributions += sampCon;
992                }
993
994                EvaluateLeafStats(tData);
995               
996                //-- clean up
997               
998                // discard polygons
999                CLEAR_CONTAINER(*tData.mPolygons);
1000                // discard rays
1001                CLEAR_CONTAINER(*tData.mRays);
1002
1003                DEL_PTR(tData.mPolygons);
1004                DEL_PTR(tData.mRays);
1005                DEL_PTR(tData.mGeometry);
1006
1007                return leaf;
1008        }
1009
1010        //-- continue subdivision
1011        PolygonContainer coincident;
1012       
1013        BspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1014                                                                new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1015        BspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1016                                                           new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1017
1018
1019        // create new interior node and two leaf nodes
1020        BspInterior *interior =
1021                SubdivideNode(tData, tFrontData, tBackData, coincident);
1022
1023
1024        if (1)
1025        {
1026                int pvsData = tData.mPvs;
1027
1028                float cData = (float)pvsData * tData.mProbability;
1029                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
1030                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
1031
1032                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
1033               
1034                mTotalCost += costDecr;
1035                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - pvsData;
1036
1037                mSubdivisionStats
1038                        << "#ViewCells\n" << mStat.Leaves() << endl
1039                        << "#RenderCostDecrease\n" << -costDecr << endl
1040                        << "#TotalRenderCost\n" << mTotalCost << endl
1041                        << "#AvgRenderCost\n" << mTotalPvsSize / mStat.Leaves() << endl;
1042        }
1043
1044        // extract view cells from coincident polygons according to plane normal
1045    // only if front or back polygons are empty
1046        if (!mGenerateViewCells)
1047        {
1048                ExtractViewCells(tFrontData,
1049                                                 tBackData,
1050                                                 coincident,
1051                                                 interior->mPlane);                     
1052        }
1053
1054        // don't need coincident polygons anymory
1055        CLEAR_CONTAINER(coincident);
1056
1057        // push the children on the stack
1058        tStack.push(tFrontData);
1059        tStack.push(tBackData);
1060
1061        // cleanup
1062        DEL_PTR(tData.mNode);
1063
1064        DEL_PTR(tData.mPolygons);
1065        DEL_PTR(tData.mRays);
1066        DEL_PTR(tData.mGeometry);               
1067       
1068        return interior;
1069}
1070
1071
1072void BspTree::ExtractViewCells(BspTraversalData &frontData,
1073                                                           BspTraversalData &backData,
1074                                                           const PolygonContainer &coincident,
1075                                                           const Plane3 &splitPlane) const
1076{
1077        // if not empty, tree is further subdivided => don't have to find view cell
1078        bool foundFront = !frontData.mPolygons->empty();
1079        bool foundBack = !frontData.mPolygons->empty();
1080
1081        PolygonContainer::const_iterator it =
1082                coincident.begin(), it_end = coincident.end();
1083
1084        //-- find first view cells in front and back leafs
1085        for (; !(foundFront && foundBack) && (it != it_end); ++ it)
1086        {
1087                if (DotProd((*it)->GetNormal(), splitPlane.mNormal) > 0)
1088                {
1089                        backData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1090                        foundBack = true;
1091                }
1092                else
1093                {
1094                        frontData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1095                        foundFront = true;
1096                }
1097        }
1098}
1099
1100
1101BspInterior *BspTree::SubdivideNode(BspTraversalData &tData,
1102                                                                        BspTraversalData &frontData,
1103                                                                        BspTraversalData &backData,
1104                                                                        PolygonContainer &coincident)
1105{
1106        mStat.nodes += 2;
1107       
1108        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1109
1110       
1111       
1112        // select subdivision plane
1113        BspInterior *interior =
1114                new BspInterior(SelectPlane(leaf, tData));
1115       
1116       
1117#ifdef _DEBUG
1118        Debug << interior << endl;
1119#endif
1120       
1121
1122        // subdivide rays into front and back rays
1123        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
1124       
1125       
1126
1127        // subdivide polygons with plane
1128        mStat.polySplits += SplitPolygons(interior->GetPlane(),
1129                                                                          *tData.mPolygons,
1130                                                                          *frontData.mPolygons,
1131                                                                          *backData.mPolygons,
1132                                                                          coincident);
1133
1134       
1135
1136    // compute pvs
1137        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1138        backData.mPvs = ComputePvsSize(*backData.mRays);
1139
1140        // split geometry and compute area
1141        if (1)
1142        {
1143                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1144                                                                           *backData.mGeometry,
1145                                                                           interior->mPlane,
1146                                                                           mBox,
1147                                                                           //0.000000000001);
1148                                                                           mEpsilon);
1149       
1150               
1151                if (mUseAreaForPvs)
1152                {
1153                        frontData.mProbability = frontData.mGeometry->GetArea();
1154                        backData.mProbability = backData.mGeometry->GetArea();
1155                }
1156                else
1157                {
1158                        frontData.mProbability = frontData.mGeometry->GetVolume();
1159                        backData.mProbability = tData.mProbability - frontData.mProbability;
1160                }
1161        }
1162
1163        //-- create front and back leaf
1164
1165        BspInterior *parent = leaf->GetParent();
1166
1167        // replace a link from node's parent
1168        if (!leaf->IsRoot())
1169        {
1170                parent->ReplaceChildLink(leaf, interior);
1171                interior->SetParent(parent);
1172        }
1173        else // new root
1174        {
1175                mRoot = interior;
1176        }
1177
1178        // and setup child links
1179        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1180       
1181        frontData.mNode = interior->GetFront();
1182        backData.mNode = interior->GetBack();
1183       
1184        interior->mTimeStamp = leaf->mTimeStamp;
1185        frontData.mNode->mTimeStamp = mTimeStamp;
1186        backData.mNode->mTimeStamp = mTimeStamp ++;
1187
1188        Debug << "time stamp: " << mTimeStamp << endl;
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        while (1)
2090        {
2091                if (!node->IsLeaf()) 
2092                {
2093                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2094               
2095                        Plane3 splitPlane = in->GetPlane();
2096                       
2097                        const int entSide = splitPlane.Side(entp);
2098                        const int extSide = splitPlane.Side(extp);
2099
2100                        if (entSide < 0)
2101                        {
2102                                node = in->GetBack();
2103               
2104                                if(extSide <= 0) // plane does not split ray => no far child
2105                                        continue;
2106               
2107                                farChild = in->GetFront(); // plane splits ray
2108               
2109                        }
2110                        else if (entSide > 0)
2111                        {
2112                                node = in->GetFront();
2113                       
2114                                if (extSide >= 0) // plane does not split ray => no far child
2115                                        continue;
2116                       
2117                                farChild = in->GetBack(); // plane splits ray                   
2118                        }
2119                        else // ray and plane are coincident
2120                        {
2121                                // NOTE: what to do if ray is coincident with plane?
2122                                if (extSide < 0)
2123                                        node = in->GetBack();
2124                                else
2125                                        node = in->GetFront();
2126                                                               
2127                                continue; // no far child
2128                        }
2129               
2130                        // push data for far child
2131                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
2132               
2133                        // find intersection of ray segment with plane
2134                        float t;
2135                        extp = splitPlane.FindIntersection(origin, extp, &t);
2136                        maxt *= t; 
2137                }
2138                else
2139                {
2140                        // reached leaf => intersection with view cell
2141                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2142               
2143                        if (!leaf->mViewCell->Mailed())
2144                        {
2145                                viewcells.push_back(leaf->mViewCell);
2146                                leaf->mViewCell->Mail();
2147                                hits++;
2148                        }
2149               
2150                        //-- fetch the next far child from the stack
2151                        if (tStack.empty())
2152                                break;
2153           
2154                        entp = extp;
2155                        mint = maxt; // NOTE: need this?
2156               
2157                        BspRayTraversalData &s = tStack.top();
2158               
2159                        node = s.mNode;
2160                        extp = s.mExitPoint;
2161                        maxt = s.mMaxT;
2162               
2163                        tStack.pop();
2164                }
2165        }
2166        return hits;
2167}
2168
2169
2170void BspTree::CollectViewCells(ViewCellContainer &viewCells) const
2171{
2172        stack<BspNode *> nodeStack;
2173        nodeStack.push(mRoot);
2174
2175        ViewCell::NewMail();
2176
2177        while (!nodeStack.empty())
2178        {
2179                BspNode *node = nodeStack.top();
2180                nodeStack.pop();
2181
2182                if (node->IsLeaf())
2183                {
2184                        ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->mViewCell;
2185
2186                        if (!viewCell->Mailed())
2187                        {
2188                                viewCell->Mail();
2189                                viewCells.push_back(viewCell);
2190                        }
2191                }
2192                else
2193                {
2194                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2195
2196                        nodeStack.push(interior->GetFront());
2197                        nodeStack.push(interior->GetBack());
2198                }
2199        }
2200}
2201
2202
2203BspTreeStatistics &BspTree::GetStat()
2204{
2205        return mStat;
2206}
2207
2208
2209float BspTree::AccumulatedRayLength(BoundedRayContainer &rays) const
2210{
2211        float len = 0;
2212
2213        BoundedRayContainer::const_iterator it, it_end = rays.end();
2214
2215        for (it = rays.begin(); it != it_end; ++ it)
2216        {
2217                len += SqrDistance((*it)->mRay->Extrap((*it)->mMinT),
2218                                                   (*it)->mRay->Extrap((*it)->mMaxT));
2219        }
2220
2221        return len;
2222}
2223
2224
2225int BspTree::SplitRays(const Plane3 &plane,
2226                                           BoundedRayContainer &rays,
2227                                           BoundedRayContainer &frontRays,
2228                                           BoundedRayContainer &backRays)
2229{
2230        int splits = 0;
2231       
2232        while (!rays.empty())
2233        {
2234                BoundedRay *bRay = rays.back();
2235                Ray *ray = bRay->mRay;
2236                float minT = bRay->mMinT;
2237                float maxT = bRay->mMaxT;
2238
2239                rays.pop_back();
2240       
2241                Vector3 entP, extP;
2242
2243                const int cf =
2244                        ray->ClassifyPlane(plane, minT, maxT, entP, extP);
2245               
2246                // set id to ray classification
2247                ray->SetId(cf);
2248
2249                switch (cf)
2250                {
2251                case Ray::COINCIDENT: // TODO: should really discard ray?
2252                        frontRays.push_back(bRay);
2253                        //DEL_PTR(bRay);
2254                        break;
2255                case Ray::BACK:
2256                        backRays.push_back(bRay);
2257                        break;
2258                case Ray::FRONT:
2259                        frontRays.push_back(bRay);
2260                        break;
2261                case Ray::FRONT_BACK:
2262                        {
2263                                // find intersection of ray segment with plane
2264                                const float t = plane.FindT(ray->GetLoc(), extP);
2265                               
2266                                const float newT = t * maxT;
2267
2268                                frontRays.push_back(new BoundedRay(ray, minT, newT));
2269                                backRays.push_back(new BoundedRay(ray, newT, maxT));
2270
2271                                DEL_PTR(bRay);
2272                        }
2273                        break;
2274                case Ray::BACK_FRONT:
2275                        {
2276                                // find intersection of ray segment with plane
2277                                const float t = plane.FindT(ray->GetLoc(), extP);
2278                                const float newT = t * bRay->mMaxT;
2279
2280                                backRays.push_back(new BoundedRay(ray, minT, newT));
2281                                frontRays.push_back(new BoundedRay(ray, newT, maxT));
2282
2283                                DEL_PTR(bRay);
2284
2285                                ++ splits;
2286                        }
2287                        break;
2288                default:
2289                        Debug << "Should not come here 4" << endl;
2290                        break;
2291                }
2292        }
2293
2294        return splits;
2295}
2296
2297void BspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2298{
2299        BspNode *lastNode;
2300        do
2301        {
2302                lastNode = n;
2303
2304                // want to get planes defining geometry of this node => don't take
2305                // split plane of node itself
2306                n = n->GetParent();
2307               
2308                if (n)
2309                {
2310                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2311                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2312
2313            if (interior->GetFront() != lastNode)
2314                                halfSpace.ReverseOrientation();
2315
2316                        halfSpaces.push_back(halfSpace);
2317                }
2318        }
2319        while (n);
2320}
2321
2322
2323
2324void BspTree::ConstructGeometry(ViewCell *vc,
2325                                                                BspNodeGeometry &vcGeom) const
2326{
2327        ViewCellContainer leaves;
2328        mViewCellsTree->CollectLeaves(vc, leaves);
2329
2330        ViewCellContainer::const_iterator it, it_end = leaves.end();
2331
2332        for (it = leaves.begin(); it != it_end; ++ it)
2333        {
2334                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2335                ConstructGeometry(l, vcGeom);
2336        }
2337}
2338
2339
2340void BspTree::SetViewCellsManager(ViewCellsManager *vcm)
2341{
2342        mViewCellsManager = vcm;
2343}
2344
2345
2346void BspTree::ConstructGeometry(BspNode *n, BspNodeGeometry &geom) const
2347{
2348        vector<Plane3> halfSpaces;
2349        ExtractHalfSpaces(n, halfSpaces);
2350
2351        PolygonContainer candidates;
2352
2353        // bounded planes are added to the polygons (reverse polygons
2354        // as they have to be outfacing
2355        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
2356        {
2357                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
2358               
2359                if (p->Valid(mEpsilon))
2360                {
2361                        candidates.push_back(p->CreateReversePolygon());
2362                        DEL_PTR(p);
2363                }
2364        }
2365
2366        // add faces of bounding box (also could be faces of the cell)
2367        for (int i = 0; i < 6; ++ i)
2368        {
2369                VertexContainer vertices;
2370       
2371                for (int j = 0; j < 4; ++ j)
2372                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2373
2374                candidates.push_back(new Polygon3(vertices));
2375        }
2376
2377        for (int i = 0; i < (int)candidates.size(); ++ i)
2378        {
2379                // polygon is split by all other planes
2380                for (int j = 0; (j < (int)halfSpaces.size()) && candidates[i]; ++ j)
2381                {
2382                        if (i == j) // polygon and plane are coincident
2383                                continue;
2384
2385                        VertexContainer splitPts;
2386                        Polygon3 *frontPoly, *backPoly;
2387
2388                        const int cf = candidates[i]->
2389                                ClassifyPlane(halfSpaces[j], mEpsilon);
2390                       
2391                        switch (cf)
2392                        {
2393                                case Polygon3::SPLIT:
2394                                        frontPoly = new Polygon3();
2395                                        backPoly = new Polygon3();
2396
2397                                        candidates[i]->Split(halfSpaces[j],
2398                                                                                 *frontPoly,
2399                                                                                 *backPoly,
2400                                                                                 mEpsilon);
2401
2402                                        DEL_PTR(candidates[i]);
2403
2404                                        if (frontPoly->Valid(mEpsilon))
2405                                                candidates[i] = frontPoly;
2406                                        else
2407                                                DEL_PTR(frontPoly);
2408
2409                                        DEL_PTR(backPoly);
2410                                        break;
2411                                case Polygon3::BACK_SIDE:
2412                                        DEL_PTR(candidates[i]);
2413                                        break;
2414                                // just take polygon as it is
2415                                case Polygon3::FRONT_SIDE:
2416                                case Polygon3::COINCIDENT:
2417                                default:
2418                                        break;
2419                        }
2420                }
2421               
2422                if (candidates[i])
2423                        geom.mPolys.push_back(candidates[i]);
2424        }
2425}
2426
2427
2428typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2429
2430
2431int BspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2432                                                   const bool onlyUnmailed) const
2433{
2434        stack<bspNodePair> nodeStack;
2435       
2436        BspNodeGeometry nodeGeom;
2437        ConstructGeometry(n, nodeGeom);
2438       
2439        // split planes from the root to this node
2440        // needed to verify that we found neighbor leaf
2441        // TODO: really needed?
2442        vector<Plane3> halfSpaces;
2443        ExtractHalfSpaces(n, halfSpaces);
2444
2445
2446        BspNodeGeometry *rgeom = new BspNodeGeometry();
2447        ConstructGeometry(mRoot, *rgeom);
2448
2449        nodeStack.push(bspNodePair(mRoot, rgeom));
2450
2451        while (!nodeStack.empty())
2452        {
2453                BspNode *node = nodeStack.top().first;
2454                BspNodeGeometry *geom = nodeStack.top().second;
2455       
2456                nodeStack.pop();
2457
2458                if (node->IsLeaf())
2459                {
2460                        // test if this leaf is in valid view space
2461                        if (node->TreeValid() &&
2462                                (node != n) &&
2463                                (!onlyUnmailed || !node->Mailed()))
2464                        {
2465                                bool isAdjacent = true;
2466
2467                                if (1)
2468                                {
2469                                        // test all planes of current node if still adjacent
2470                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2471                                        {
2472                                                const int cf =
2473                                                        Polygon3::ClassifyPlane(geom->mPolys,
2474                                                                                                        halfSpaces[i],
2475                                                                                                        mEpsilon);
2476
2477                                                if (cf == Polygon3::BACK_SIDE)
2478                                                {
2479                                                        isAdjacent = false;
2480                                                }
2481                                        }
2482                                }
2483                                else
2484                                {
2485                                        // TODO: why is this wrong??
2486                                        // test all planes of current node if still adjacent
2487                                        for (int i = 0; (i < (int)nodeGeom.mPolys.size()) && isAdjacent; ++ i)
2488                                        {
2489                                                Polygon3 *poly = nodeGeom.mPolys[i];
2490
2491                                                const int cf =
2492                                                        Polygon3::ClassifyPlane(geom->mPolys,
2493                                                                                                        poly->GetSupportingPlane(),
2494                                                                                                        mEpsilon);
2495
2496                                                if (cf == Polygon3::BACK_SIDE)
2497                                                {
2498                                                        isAdjacent = false;
2499                                                }
2500                                        }
2501                                }
2502                                // neighbor was found
2503                                if (isAdjacent)
2504                                {       
2505                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2506                                }
2507                        }
2508                }
2509                else
2510                {
2511                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2512
2513                        const int cf = Polygon3::ClassifyPlane(nodeGeom.mPolys,
2514                                                                                                   interior->GetPlane(),
2515                                                                                                   mEpsilon);
2516                       
2517                        BspNode *front = interior->GetFront();
2518                        BspNode *back = interior->GetBack();
2519           
2520                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2521                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2522
2523                        geom->SplitGeometry(*fGeom,
2524                                                                *bGeom,
2525                                                                interior->GetPlane(),
2526                                                                mBox,
2527                                                                mEpsilon);
2528               
2529                        if (cf == Polygon3::FRONT_SIDE)
2530                        {
2531                                nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2532                                DEL_PTR(bGeom);
2533                        }
2534                        else
2535                        {
2536                                if (cf == Polygon3::BACK_SIDE)
2537                                {
2538                                        nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2539                                        DEL_PTR(fGeom);
2540                                }
2541                                else
2542                                {       // random decision
2543                                        nodeStack.push(bspNodePair(front, fGeom));
2544                                        nodeStack.push(bspNodePair(back, bGeom));
2545                                }
2546                        }
2547                }
2548       
2549                DEL_PTR(geom);
2550        }
2551
2552        return (int)neighbors.size();
2553}
2554
2555
2556BspLeaf *BspTree::GetRandomLeaf(const Plane3 &halfspace)
2557{
2558    stack<BspNode *> nodeStack;
2559        nodeStack.push(mRoot);
2560       
2561        int mask = rand();
2562 
2563        while (!nodeStack.empty())
2564        {
2565                BspNode *node = nodeStack.top();
2566                nodeStack.pop();
2567         
2568                if (node->IsLeaf())
2569                {
2570                        return dynamic_cast<BspLeaf *>(node);
2571                }
2572                else
2573                {
2574                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2575                        BspNode *next;
2576       
2577                        BspNodeGeometry geom;
2578                        // todo: not very efficient: constructs full cell everytime
2579                        ConstructGeometry(interior, geom);
2580
2581                        const int cf = Polygon3::ClassifyPlane(geom.mPolys,
2582                                                                                                   halfspace,
2583                                                                                                   mEpsilon);
2584
2585                        if (cf == Polygon3::BACK_SIDE)
2586                                next = interior->GetFront();
2587                        else
2588                                if (cf == Polygon3::FRONT_SIDE)
2589                                        next = interior->GetFront();
2590                        else
2591                        {
2592                                // random decision
2593                                if (mask & 1)
2594                                        next = interior->GetBack();
2595                                else
2596                                        next = interior->GetFront();
2597                                mask = mask >> 1;
2598                        }
2599
2600                        nodeStack.push(next);
2601                }
2602        }
2603       
2604        return NULL;
2605}
2606
2607
2608BspLeaf *BspTree::GetRandomLeaf(const bool onlyUnmailed)
2609{
2610        stack<BspNode *> nodeStack;
2611       
2612        nodeStack.push(mRoot);
2613
2614        int mask = rand();
2615       
2616        while (!nodeStack.empty())
2617        {
2618                BspNode *node = nodeStack.top();
2619                nodeStack.pop();
2620               
2621                if (node->IsLeaf())
2622                {
2623                        if ( (!onlyUnmailed || !node->Mailed()) )
2624                                return dynamic_cast<BspLeaf *>(node);
2625                }
2626                else
2627                {
2628                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2629
2630                        // random decision
2631                        if (mask & 1)
2632                                nodeStack.push(interior->GetBack());
2633                        else
2634                                nodeStack.push(interior->GetFront());
2635
2636                        mask = mask >> 1;
2637                }
2638        }
2639       
2640        return NULL;
2641}
2642
2643
2644void BspTree::AddToPvs(BspLeaf *leaf,
2645                                           const BoundedRayContainer &rays,
2646                                           int &sampleContributions,
2647                                           int &contributingSamples)
2648{
2649        sampleContributions = 0;
2650        contributingSamples = 0;
2651
2652    BoundedRayContainer::const_iterator it, it_end = rays.end();
2653
2654        ViewCell *vc = leaf->GetViewCell();
2655
2656        // add contributions from samples to the PVS
2657        for (it = rays.begin(); it != it_end; ++ it)
2658        {
2659                int contribution = 0;
2660                Ray *ray = (*it)->mRay;
2661                float relContribution;
2662                if (!ray->intersections.empty())
2663                  contribution += vc->GetPvs().AddSample(ray->intersections[0].mObject,
2664                                                                                                 1.0f,
2665                                                                                                 relContribution);
2666               
2667                if (ray->sourceObject.mObject)
2668                        contribution += vc->GetPvs().AddSample(ray->sourceObject.mObject,
2669                                                                                                   1.0f,
2670                                                                                                   relContribution);
2671               
2672                if (contribution)
2673                {
2674                        sampleContributions += contribution;
2675                        ++ contributingSamples;
2676                }
2677
2678                //if (ray->mFlags & Ray::STORE_BSP_INTERSECTIONS)
2679                //      ray->bspIntersections.push_back(Ray::BspIntersection((*it)->mMinT, this));
2680        }
2681}
2682
2683
2684int BspTree::ComputePvsSize(const BoundedRayContainer &rays) const
2685{
2686        int pvsSize = 0;
2687
2688        BoundedRayContainer::const_iterator rit, rit_end = rays.end();
2689
2690        Intersectable::NewMail();
2691
2692        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2693        {
2694                Ray *ray = (*rit)->mRay;
2695               
2696                if (!ray->intersections.empty())
2697                {
2698                        if (!ray->intersections[0].mObject->Mailed())
2699                        {
2700                                ray->intersections[0].mObject->Mail();
2701                                ++ pvsSize;
2702                        }
2703                }
2704                if (ray->sourceObject.mObject)
2705                {
2706                        if (!ray->sourceObject.mObject->Mailed())
2707                        {
2708                                ray->sourceObject.mObject->Mail();
2709                                ++ pvsSize;
2710                        }
2711                }
2712        }
2713
2714        return pvsSize;
2715}
2716
2717
2718float BspTree::GetEpsilon() const
2719{
2720        return mEpsilon;
2721}
2722
2723
2724int BspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
2725                                                                        vector<MergeCandidate> &candidates)
2726{
2727        BspLeaf::NewMail();
2728       
2729        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2730
2731        int numCandidates = 0;
2732
2733        // find merge candidates and push them into queue
2734        for (it = leaves.begin(); it != it_end; ++ it)
2735        {
2736                BspLeaf *leaf = *it;
2737               
2738                // the same leaves must not be part of two merge candidates
2739                leaf->Mail();
2740                vector<BspLeaf *> neighbors;
2741                FindNeighbors(leaf, neighbors, true);
2742
2743                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2744
2745                // TODO: test if at least one ray goes from one leaf to the other
2746                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2747                {
2748                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
2749                        {
2750                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
2751                                candidates.push_back(mc);
2752
2753                                ++ numCandidates;
2754                                if ((numCandidates % 1000) == 0)
2755                                {
2756                                        cout << "collected " << numCandidates << " merge candidates" << endl;
2757                                }
2758                        }
2759                }
2760        }
2761
2762        Debug << "merge queue: " << (int)candidates.size() << endl;
2763        Debug << "leaves in queue: " << numCandidates << endl;
2764       
2765
2766        return (int)leaves.size();
2767}
2768
2769
2770int BspTree::CollectMergeCandidates(const VssRayContainer &rays,
2771                                                                        vector<MergeCandidate> &candidates)
2772{
2773        ViewCell::NewMail();
2774        long startTime = GetTime();
2775       
2776        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2777        ViewCellContainer::const_iterator iit;
2778
2779        int numLeaves = 0;
2780       
2781        BspLeaf::NewMail();
2782
2783        for (int i = 0; i < (int)rays.size(); ++ i)
2784        { 
2785                VssRay *ray = rays[i];
2786       
2787                // traverse leaves stored in the rays and compare and
2788                // merge consecutive leaves (i.e., the neighbors in the tree)
2789                if (ray->mViewCells.size() < 2)
2790                        continue;
2791
2792                iit = ray->mViewCells.begin();
2793                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
2794                BspLeaf *leaf = bspVc->mLeaf;
2795               
2796                // traverse intersections
2797                // consecutive leaves are neighbors => add them to queue
2798                for (; iit != ray->mViewCells.end(); ++ iit)
2799                {
2800                        // next pair
2801                        BspLeaf *prevLeaf = leaf;
2802                        bspVc = dynamic_cast<BspViewCell *>(*iit);
2803            leaf = bspVc->mLeaf;
2804
2805                        // view space not valid or same view cell
2806                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
2807                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
2808                                continue;
2809
2810                vector<BspLeaf *> &neighbors = neighborMap[leaf];
2811                       
2812                        bool found = false;
2813
2814                        // both leaves inserted in queue already =>
2815                        // look if double pair already exists
2816                        if (leaf->Mailed() && prevLeaf->Mailed())
2817                        {
2818                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2819                               
2820                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2821                                        if (*it == prevLeaf)
2822                                                found = true; // already in queue
2823                        }
2824               
2825                        if (!found)
2826                        {
2827                                // this pair is not in map yet
2828                                // => insert into the neighbor map and the queue
2829                                neighbors.push_back(prevLeaf);
2830                                neighborMap[prevLeaf].push_back(leaf);
2831
2832                                leaf->Mail();
2833                                prevLeaf->Mail();
2834               
2835                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
2836                               
2837                                candidates.push_back(mc);
2838
2839                                if (((int)candidates.size() % 1000) == 0)
2840                                {
2841                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
2842                                }
2843                        }
2844        }
2845        }
2846
2847        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2848        Debug << "merge queue: " << (int)candidates.size() << endl;
2849        Debug << "leaves in queue: " << numLeaves << endl;
2850
2851
2852        //-- collect the leaves which haven't been found by ray casting
2853#if 0
2854        cout << "finding additional merge candidates using geometry" << endl;
2855        vector<BspLeaf *> leaves;
2856        CollectLeaves(leaves, true);
2857        Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
2858        CollectMergeCandidates(leaves, candidates);
2859#endif
2860
2861        return numLeaves;
2862}
2863
2864
2865
2866
2867/***************************************************************/
2868/*              BspNodeGeometry Implementation                 */
2869/***************************************************************/
2870
2871
2872BspNodeGeometry::BspNodeGeometry(const BspNodeGeometry &rhs)
2873{
2874        mPolys.reserve(rhs.mPolys.size());
2875       
2876        PolygonContainer::const_iterator it, it_end = rhs.mPolys.end();
2877        for (it = rhs.mPolys.begin(); it != it_end; ++ it)
2878        {
2879                Polygon3 *poly = *it;
2880                mPolys.push_back(new Polygon3(*poly));
2881        }
2882}
2883
2884
2885BspNodeGeometry::~BspNodeGeometry()
2886{
2887        CLEAR_CONTAINER(mPolys);
2888}
2889
2890
2891float BspNodeGeometry::GetArea() const
2892{
2893        return Polygon3::GetArea(mPolys);
2894}
2895
2896
2897float BspNodeGeometry::GetVolume() const
2898{
2899        //-- compute volume using tetrahedralization of the geometry
2900        //   and adding the volume of the single tetrahedrons
2901        float volume = 0;
2902        const float f = 1.0f / 6.0f;
2903
2904        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2905
2906        // note: can take arbitrary point, e.g., the origin. However,
2907        // we rather take the center of mass to prevents precision errors
2908        const Vector3 center = CenterOfMass();
2909
2910        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2911        {
2912                Polygon3 *poly = *pit;
2913                const Vector3 v0 = poly->mVertices[0] - center;
2914
2915                for (int i = 1; i < (int)poly->mVertices.size() - 1; ++ i)
2916                {
2917                        const Vector3 v1 = poly->mVertices[i] - center;
2918                        const Vector3 v2 = poly->mVertices[i + 1] - center;
2919
2920                        volume += f * (DotProd(v0, CrossProd(v1, v2)));
2921                }
2922        }
2923
2924        return volume;
2925}
2926
2927
2928Vector3 BspNodeGeometry::CenterOfMass() const
2929{
2930        int n = 0;
2931
2932        Vector3 center(0,0,0);
2933
2934        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2935
2936        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2937        {
2938                Polygon3 *poly = *pit;
2939               
2940                VertexContainer::const_iterator vit, vit_end = poly->mVertices.end();
2941
2942                for(vit = poly->mVertices.begin(); vit != vit_end; ++ vit)
2943                {
2944                        center += *vit;
2945                        ++ n;
2946                }
2947        }
2948
2949        return center / (float)n;
2950}
2951
2952
2953void BspNodeGeometry::AddToMesh(Mesh &mesh)
2954{
2955        PolygonContainer::const_iterator it, it_end = mPolys.end();
2956       
2957        for (it = mPolys.begin(); it != mPolys.end(); ++ it)
2958        {
2959                (*it)->AddToMesh(mesh);
2960        }
2961}
2962
2963
2964void BspNodeGeometry::SplitGeometry(BspNodeGeometry &front,
2965                                                                        BspNodeGeometry &back,
2966                                                                        const Plane3 &splitPlane,
2967                                                                        const AxisAlignedBox3 &box,
2968                                                                        const float epsilon) const
2969{       
2970        // get cross section of new polygon
2971        Polygon3 *planePoly = box.CrossSection(splitPlane);
2972
2973        // split polygon with all other polygons
2974        planePoly = SplitPolygon(planePoly, epsilon);
2975
2976        //-- new polygon splits all other polygons
2977        for (int i = 0; i < (int)mPolys.size(); ++ i)
2978        {
2979                /// don't use epsilon here to get exact split planes
2980                const int cf =
2981                        mPolys[i]->ClassifyPlane(splitPlane, Limits::Small);
2982                       
2983                switch (cf)
2984                {
2985                        case Polygon3::SPLIT:
2986                                {
2987                                        Polygon3 *poly = new Polygon3(mPolys[i]->mVertices);
2988
2989                                        Polygon3 *frontPoly = new Polygon3();
2990                                        Polygon3 *backPoly = new Polygon3();
2991                               
2992                                        poly->Split(splitPlane,
2993                                                                *frontPoly,
2994                                                                *backPoly,
2995                                                                epsilon);
2996
2997                                        DEL_PTR(poly);
2998
2999                                        if (frontPoly->Valid(epsilon))
3000                                                front.mPolys.push_back(frontPoly);
3001                                        else
3002                                                DEL_PTR(frontPoly);
3003
3004                                        if (backPoly->Valid(epsilon))
3005                                                back.mPolys.push_back(backPoly);
3006                                        else
3007                                                DEL_PTR(backPoly);
3008                                }
3009                               
3010                                break;
3011                        case Polygon3::BACK_SIDE:
3012                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));                     
3013                                break;
3014                        case Polygon3::FRONT_SIDE:
3015                                front.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));     
3016                                break;
3017                        case Polygon3::COINCIDENT:
3018                                //front.mPolys.push_back(CreateReversePolygon(mPolys[i]));
3019                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));
3020                                break;
3021                        default:
3022                                break;
3023                }
3024        }
3025
3026        //-- finally add the new polygon to the child node geometries
3027        if (planePoly)
3028        {
3029                // add polygon with normal pointing into positive half space to back cell
3030                back.mPolys.push_back(planePoly);
3031                // add polygon with reverse orientation to front cell
3032                front.mPolys.push_back(planePoly->CreateReversePolygon());
3033        }
3034}
3035
3036
3037Polygon3 *BspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
3038                                                                                const float epsilon) const
3039{
3040        if (!planePoly->Valid(epsilon))
3041                DEL_PTR(planePoly);
3042
3043        // polygon is split by all other planes
3044        for (int i = 0; (i < (int)mPolys.size()) && planePoly; ++ i)
3045        {
3046                Plane3 plane = mPolys[i]->GetSupportingPlane();
3047
3048                /// don't use epsilon here to get exact split planes
3049                const int cf =
3050                        planePoly->ClassifyPlane(plane, Limits::Small);
3051                       
3052                // split new polygon with all previous planes
3053                switch (cf)
3054                {
3055                        case Polygon3::SPLIT:
3056                                {
3057                                        Polygon3 *frontPoly = new Polygon3();
3058                                        Polygon3 *backPoly = new Polygon3();
3059
3060                                        planePoly->Split(plane,
3061                                                                         *frontPoly,
3062                                                                         *backPoly,
3063                                                                         epsilon);
3064                                       
3065                                        // don't need anymore
3066                                        DEL_PTR(planePoly);
3067                                        DEL_PTR(frontPoly);
3068
3069                                        // back polygon is belonging to geometry
3070                                        if (backPoly->Valid(epsilon))
3071                                                planePoly = backPoly;
3072                                        else
3073                                                DEL_PTR(backPoly);
3074                                }
3075                                break;
3076                        case Polygon3::FRONT_SIDE:
3077                                DEL_PTR(planePoly);
3078                break;
3079                        // polygon is taken as it is
3080                        case Polygon3::BACK_SIDE:
3081                        case Polygon3::COINCIDENT:
3082                        default:
3083                                break;
3084                }
3085        }
3086
3087        return planePoly;
3088}
3089
3090
3091ViewCell *
3092BspTree::GetViewCell(const Vector3 &point)
3093{
3094  if (mRoot == NULL)
3095        return NULL;
3096 
3097
3098  stack<BspNode *> nodeStack;
3099  nodeStack.push(mRoot);
3100 
3101  ViewCell *viewcell = NULL;
3102 
3103  while (!nodeStack.empty())  {
3104        BspNode *node = nodeStack.top();
3105        nodeStack.pop();
3106       
3107        if (node->IsLeaf()) {
3108          viewcell = dynamic_cast<BspLeaf *>(node)->mViewCell;
3109          break;
3110        } else {
3111         
3112          BspInterior *interior = dynamic_cast<BspInterior *>(node);
3113               
3114          // random decision
3115          if (interior->GetPlane().Side(point) < 0)
3116                nodeStack.push(interior->GetBack());
3117          else
3118                nodeStack.push(interior->GetFront());
3119        }
3120  }
3121 
3122  return viewcell;
3123}
3124
3125
3126void BspNodeGeometry::IncludeInBox(AxisAlignedBox3 &box)
3127{
3128        Polygon3::IncludeInBox(mPolys, box);
3129}
3130
3131
3132bool BspTree::Export(ofstream &stream)
3133{
3134        ExportNode(mRoot, stream);
3135
3136        return true;
3137}
3138
3139
3140void BspTree::ExportNode(BspNode *node, ofstream &stream)
3141{
3142        if (node->IsLeaf())
3143        {
3144                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3145                       
3146                int id = -1;
3147                if (leaf->GetViewCell() != mOutOfBoundsCell)
3148                        id = leaf->GetViewCell()->GetId();
3149
3150                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3151        }
3152        else
3153        {
3154                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3155       
3156                Plane3 plane = interior->GetPlane();
3157                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3158                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3159                           << plane.mD << "\">" << endl;
3160
3161                ExportNode(interior->GetBack(), stream);
3162                ExportNode(interior->GetFront(), stream);
3163
3164                stream << "</Interior>" << endl;
3165        }
3166}
Note: See TracBrowser for help on using the repository browser.