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

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