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

Revision 882, 80.7 KB checked in by mattausch, 18 years ago (diff)

added new active view cell concept

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