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

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