source: trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp @ 444

Revision 444, 48.2 KB checked in by mattausch, 19 years ago (diff)

fixed error in ray to vssray conversion

Line 
1#include "Plane3.h"
2#include "VspBspTree.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 <stack>
11#include <time.h>
12#include <iomanip>
13#include "Exporter.h"
14#include "Plane3.h"
15
16//-- static members
17/** Evaluates split plane classification with respect to the plane's
18        contribution for a minimum number of ray splits.
19*/
20const float VspBspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
21/** Evaluates split plane classification with respect to the plane's
22        contribution for balanced rays.
23*/
24const float VspBspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
25
26int VspBspNode::sMailId = 1;
27
28int VspBspTree::sFrontId = 0;
29int VspBspTree::sBackId = 0;
30int VspBspTree::sFrontAndBackId = 0;
31
32/****************************************************************/
33/*                  class VspBspNode implementation                */
34/****************************************************************/
35
36VspBspNode::VspBspNode():
37mParent(NULL)
38{}
39
40VspBspNode::VspBspNode(VspBspInterior *parent):
41mParent(parent)
42{}
43
44
45bool VspBspNode::IsRoot() const
46{
47        return mParent == NULL;
48}
49
50VspBspInterior *VspBspNode::GetParent()
51{
52        return mParent;
53}
54
55void VspBspNode::SetParent(VspBspInterior *parent)
56{
57        mParent = parent;
58}
59
60/****************************************************************/
61/*              class VspBspInterior implementation                */
62/****************************************************************/
63
64
65VspBspInterior::VspBspInterior(const Plane3 &plane):
66mPlane(plane), mFront(NULL), mBack(NULL)
67{}
68
69VspBspInterior::~VspBspInterior()
70{
71        DEL_PTR(mFront);
72        DEL_PTR(mBack);
73}
74
75bool VspBspInterior::IsLeaf() const
76{
77        return false;
78}
79
80VspBspNode *VspBspInterior::GetBack()
81{
82        return mBack;
83}
84
85VspBspNode *VspBspInterior::GetFront()
86{
87        return mFront;
88}
89
90Plane3 *VspBspInterior::GetPlane()
91{
92        return &mPlane;
93}
94
95void VspBspInterior::ReplaceChildLink(VspBspNode *oldChild, VspBspNode *newChild)
96{
97        if (mBack == oldChild)
98                mBack = newChild;
99        else
100                mFront = newChild;
101}
102
103void VspBspInterior::SetupChildLinks(VspBspNode *b, VspBspNode *f)
104{
105    mBack = b;
106    mFront = f;
107}
108
109int VspBspInterior::SplitPolygons(PolygonContainer &polys,
110                                                                  PolygonContainer &frontPolys,
111                                                                  PolygonContainer &backPolys,
112                                                                  PolygonContainer &coincident)
113{
114        int splits = 0;
115
116        while (!polys.empty())
117        {
118                Polygon3 *poly = polys.back();
119                polys.pop_back();
120
121                // classify polygon
122                const int cf = poly->ClassifyPlane(mPlane);
123
124                switch (cf)
125                {
126                        case Polygon3::COINCIDENT:
127                                coincident.push_back(poly);
128                                break;                 
129                        case Polygon3::FRONT_SIDE:     
130                                frontPolys.push_back(poly);
131                                break;
132                        case Polygon3::BACK_SIDE:
133                                backPolys.push_back(poly);
134                                break;
135                        case Polygon3::SPLIT:
136                                backPolys.push_back(poly);
137                                frontPolys.push_back(poly);
138                                ++ splits;
139                                break;
140                        default:
141                Debug << "SHOULD NEVER COME HERE\n";
142                                break;
143                }
144        }
145
146        return splits;
147}
148
149/****************************************************************/
150/*                  class VspBspLeaf implementation                */
151/****************************************************************/
152VspBspLeaf::VspBspLeaf(): mViewCell(NULL)
153{
154}
155
156VspBspLeaf::VspBspLeaf(BspViewCell *viewCell):
157mViewCell(viewCell)
158{
159}
160
161VspBspLeaf::VspBspLeaf(VspBspInterior *parent):
162VspBspNode(parent), mViewCell(NULL)
163{}
164
165VspBspLeaf::VspBspLeaf(VspBspInterior *parent, BspViewCell *viewCell):
166VspBspNode(parent), mViewCell(viewCell)
167{
168}
169
170BspViewCell *VspBspLeaf::GetViewCell() const
171{
172        return mViewCell;
173}
174
175void VspBspLeaf::SetViewCell(BspViewCell *viewCell)
176{
177        mViewCell = viewCell;
178}
179
180bool VspBspLeaf::IsLeaf() const
181{
182        return true;
183}
184
185void VspBspLeaf::AddToPvs(const RayInfoContainer &rays,
186                                                  int &sampleContributions,
187                                                  int &contributingSamples,
188                                                  bool storeLeavesWithRays)
189{
190        sampleContributions = 0;
191        contributingSamples = 0;
192
193    RayInfoContainer::const_iterator it, it_end = rays.end();
194
195        // add contributions from samples to the PVS
196        for (it = rays.begin(); it != it_end; ++ it)
197        {
198                int contribution = 0;
199                VssRay *ray = (*it).mRay;
200                       
201                if (ray->mTerminationObject)
202                        contribution += mViewCell->GetPvs().AddSample(ray->mTerminationObject);
203               
204                if (ray->mOriginObject)
205                        contribution += mViewCell->GetPvs().AddSample(ray->mOriginObject);
206
207                if (contribution > 0)
208                {
209                        sampleContributions += contribution;
210                        ++ contributingSamples;
211                }
212        }
213}
214
215
216/****************************************************************/
217/*                  class VspBspTree implementation             */
218/****************************************************************/
219
220VspBspTree::VspBspTree():
221mRoot(NULL),
222mPvsUseArea(true)
223{
224        mRootCell = new BspViewCell();
225
226        Randomize(); // initialise random generator for heuristics
227
228        //-- termination criteria for autopartition
229        environment->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
230        environment->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
231        environment->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
232        environment->GetFloatValue("VspBspTree.Termination.minArea", mTermMinArea);     
233        environment->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
234        environment->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
235
236        //-- factors for bsp tree split plane heuristics
237        environment->GetFloatValue("VspBspTree.Factor.balancedRays", mBalancedRaysFactor);
238        environment->GetFloatValue("VspBspTree.Factor.pvsFactor", mPvsFactor);
239        environment->GetFloatValue("VspBspTree.Factor.leastSplits" , mLeastSplitsFactor);
240        environment->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
241
242        //-- termination criteria for axis aligned split
243        environment->GetFloatValue("VspBspTree.Termination.AxisAligned.ct_div_ci", mAaCtDivCi);
244        environment->GetFloatValue("VspBspTree.Termination.AxisAligned.maxCostRatio", mMaxCostRatio);
245       
246        environment->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
247                                                         mTermMinRaysForAxisAligned);
248       
249        //-- partition criteria
250        environment->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
251        environment->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
252        environment->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
253        environment->GetFloatValue("VspBspTree.AxisAligned.splitBorder", mSplitBorder);
254
255        environment->GetFloatValue("VspBspTree.Construction.sideTolerance", Vector3::sDistTolerance);
256        Vector3::sDistToleranceSqrt = Vector3::sDistTolerance * Vector3::sDistTolerance;
257
258        // post processing stuff
259        environment->GetIntValue("ViewCells.PostProcessing.minPvsDif", mMinPvsDif);
260        environment->GetIntValue("ViewCells.PostProcessing.minPvs", mMinPvs);
261        environment->GetIntValue("ViewCells.PostProcessing.maxPvs", mMaxPvs);
262
263    Debug << "BSP max depth: " << mTermMaxDepth << endl;
264        Debug << "BSP min PVS: " << mTermMinPvs << endl;
265        Debug << "BSP min area: " << mTermMinArea << endl;
266        Debug << "BSP min rays: " << mTermMinRays << endl;
267        Debug << "BSP max polygon candidates: " << mMaxPolyCandidates << endl;
268        Debug << "BSP max plane candidates: " << mMaxRayCandidates << endl;
269
270        Debug << "Split plane strategy: ";
271        if (mSplitPlaneStrategy & RANDOM_POLYGON)
272                Debug << "random polygon ";
273        if (mSplitPlaneStrategy & AXIS_ALIGNED)
274                Debug << "axis aligned ";
275        if (mSplitPlaneStrategy & LEAST_SPLITS)     
276                Debug << "least splits ";
277        if (mSplitPlaneStrategy & VERTICAL_AXIS)
278                Debug << "vertical axis ";
279        if (mSplitPlaneStrategy & BLOCKED_RAYS)
280                Debug << "blocked rays ";
281        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
282                Debug << "least ray splits ";
283        if (mSplitPlaneStrategy & BALANCED_RAYS)
284                Debug << "balanced rays ";
285        if (mSplitPlaneStrategy & PVS)
286                Debug << "pvs";
287
288        Debug << endl;
289}
290
291
292const VspBspTreeStatistics &VspBspTree::GetStatistics() const
293{
294        return mStat;
295}
296
297void VspBspTreeStatistics::Print(ostream &app) const
298{
299        app << "===== VspBspTree statistics ===============\n";
300
301        app << setprecision(4);
302
303        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
304
305        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
306
307        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
308
309        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
310
311        app << "#N_SPLITS ( Number of splits )\n" << splits << "\n";
312
313        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
314                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
315
316        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
317                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
318
319        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
320                << minPvsNodes * 100 / (double)Leaves() << endl;
321
322        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
323                <<      minRaysNodes * 100 / (double)Leaves() << endl;
324
325        app << "#N_PMINAREALEAVES  ( Percentage of leaves with mininum area )\n"
326                << minAreaNodes * 100 / (double)Leaves() << endl;
327
328        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
329                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
330
331        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
332
333        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
334
335        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
336
337        app << "#N_INPUT_POLYGONS (number of input polygons )\n" <<     polys << endl;
338
339        //app << "#N_PVS: " << pvs << endl;
340
341        app << "#N_ROUTPUT_INPUT_POLYGONS ( ratio polygons after subdivision / input polygons )\n" <<
342                 (polys + splits) / (double)polys << endl;
343       
344        app << "===== END OF VspBspTree statistics ==========\n";
345}
346
347
348VspBspTree::~VspBspTree()
349{
350        DEL_PTR(mRoot);
351        DEL_PTR(mRootCell);
352}
353
354int VspBspTree::AddMeshToPolygons(Mesh *mesh, PolygonContainer &polys, MeshInstance *parent)
355{
356        FaceContainer::const_iterator fi;
357       
358        // copy the face data to polygons
359        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
360        {
361                Polygon3 *poly = new Polygon3((*fi), mesh);
362               
363                if (poly->Valid())
364                {
365                        poly->mParent = parent; // set parent intersectable
366                        polys.push_back(poly);
367                }
368                else
369                        DEL_PTR(poly);
370        }
371        return (int)mesh->mFaces.size();
372}
373
374int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
375                                                          PolygonContainer &polys,
376                                                          int maxObjects)
377{
378        int limit = (maxObjects > 0) ?
379                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
380 
381        int polysSize = 0;
382
383        for (int i = 0; i < limit; ++ i)
384        {
385                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
386                {
387                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
388                        polysSize += AddMeshToPolygons(viewCells[i]->GetMesh(), polys, viewCells[i]);
389                }
390        }
391
392        return polysSize;
393}
394
395int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects, PolygonContainer &polys, int maxObjects)
396{
397        int limit = (maxObjects > 0) ? Min((int)objects.size(), maxObjects) : (int)objects.size();
398 
399        for (int i = 0; i < limit; ++i)
400        {
401                Intersectable *object = objects[i];//*it;
402                Mesh *mesh = NULL;
403
404                switch (object->Type()) // extract the meshes
405                {
406                case Intersectable::MESH_INSTANCE:
407                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
408                        break;
409                case Intersectable::VIEW_CELL:
410                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
411                        break;
412                        // TODO: handle transformed mesh instances
413                default:
414                        Debug << "intersectable type not supported" << endl;
415                        break;
416                }
417               
418        if (mesh) // copy the mesh data to polygons
419                {
420                        mBox.Include(object->GetBox()); // add to BSP tree aabb
421                        AddMeshToPolygons(mesh, polys, mRootCell);
422                }
423        }
424
425        return (int)polys.size();
426}
427
428void VspBspTree::Construct(const VssRayContainer &sampleRays)
429{
430    mStat.nodes = 1;
431        mBox.Initialize();      // initialise BSP tree bounding box
432       
433        PolygonContainer polys;
434        RayInfoContainer *rays = new RayInfoContainer();
435
436        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
437
438        long startTime = GetTime();
439
440        Debug << "**** Extracting polygons from rays ****\n";
441
442        //-- extract polygons intersected by the rays
443        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
444        {
445                VssRay *ray = *rit;
446       
447                if (ray->mTerminationObject)
448                {
449                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mTerminationObject);
450                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
451                }
452
453                if (ray->mOriginObject)
454                {
455                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
456                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
457                }
458        }
459
460        //-- store rays
461        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
462        {
463                rays->push_back(RayInfo(*rit));
464        }
465
466        mStat.polys = (int)polys.size();
467
468        Debug << "**** Finished polygon extraction ****" << endl;
469        Debug << (int)polys.size() << " polys extracted from " << (int)sampleRays.size() << " rays" << endl;
470        Debug << "extraction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
471
472        Construct(new PolygonContainer(polys), rays);
473
474        // clean up polygons because they are not deleted in the tree
475        CLEAR_CONTAINER(polys);
476}
477
478void VspBspTree::Construct(PolygonContainer *polys, RayInfoContainer *rays)
479{
480        std::stack<VspBspTraversalData> tStack;
481
482        mRoot = new VspBspLeaf();
483
484        VspBspNodeGeometry *cell = new VspBspNodeGeometry();
485        ConstructGeometry(mRoot, *cell);
486
487        VspBspTraversalData tData(mRoot, polys, 0, mRootCell, rays,
488                                                   ComputePvsSize(*rays), cell->GetArea(), cell);
489
490        tStack.push(tData);
491
492        mStat.Start();
493        cout << "Contructing bsp tree ... ";
494        long startTime = GetTime();
495        while (!tStack.empty())
496        {
497                tData = tStack.top();
498
499            tStack.pop();
500
501                // subdivide leaf node
502                VspBspNode *r = Subdivide(tStack, tData);
503
504                if (r == mRoot)
505                        Debug << "BSP tree construction time spent at root: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
506        }
507
508        cout << "finished\n";
509
510        mStat.Stop();
511}
512
513bool VspBspTree::TerminationCriteriaMet(const VspBspTraversalData &data) const
514{
515        return
516                (((int)data.mRays->size() <= mTermMinRays) ||
517                 (data.mPvs <= mTermMinPvs) ||
518                 (data.mArea <= mTermMinArea) ||
519                 (data.GetAvgRayContribution() >= mTermMaxRayContribution) ||
520                 (data.mDepth >= mTermMaxDepth));
521}
522
523VspBspNode *VspBspTree::Subdivide(VspBspTraversalStack &tStack, VspBspTraversalData &tData)
524{
525        //-- terminate traversal 
526        if (TerminationCriteriaMet(tData))             
527        {
528                VspBspLeaf *leaf = dynamic_cast<VspBspLeaf *>(tData.mNode);
529       
530                BspViewCell *viewCell = new BspViewCell();
531               
532                leaf->SetViewCell(viewCell);
533                //TODO viewCell->mVspBspLeaves.push_back(leaf);
534
535                //-- add pvs
536                if (viewCell != mRootCell)
537                {
538                        int conSamp = 0, sampCon = 0;
539                        leaf->AddToPvs(*tData.mRays, conSamp, sampCon);
540                       
541                        mStat.contributingSamples += conSamp;
542                        mStat.sampleContributions += sampCon;
543                }
544
545                EvaluateLeafStats(tData);
546               
547                //-- clean up
548
549                DEL_PTR(tData.mPolygons);
550                DEL_PTR(tData.mRays);
551                DEL_PTR(tData.mGeometry);
552               
553                return leaf;
554        }
555
556        //-- continue subdivision
557        PolygonContainer coincident;
558       
559        VspBspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mRootCell,
560                                                                new RayInfoContainer(), 0, 0, new VspBspNodeGeometry());
561        VspBspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mRootCell,
562                                                           new RayInfoContainer(), 0, 0, new VspBspNodeGeometry());
563
564        // create new interior node and two leaf nodes
565        VspBspInterior *interior =
566                SubdivideNode(tData, tFrontData, tBackData, coincident);
567
568#ifdef _DEBUG   
569        if (frontPolys->empty() && backPolys->empty() && (coincident.size() > 2))
570        {       for (PolygonContainer::iterator it = coincident.begin(); it != coincident.end(); ++it)
571                        Debug << (*it) << " " << (*it)->GetArea() << " " << (*it)->mParent << endl ;
572                Debug << endl;}
573#endif
574
575        // don't need coincident polygons anymory
576        CLEAR_CONTAINER(coincident);
577
578        // push the children on the stack
579        tStack.push(tFrontData);
580        tStack.push(tBackData);
581
582        // cleanup
583        DEL_PTR(tData.mNode);
584        DEL_PTR(tData.mPolygons);
585        DEL_PTR(tData.mRays);
586        DEL_PTR(tData.mGeometry);               
587
588        return interior;
589}
590
591VspBspInterior *VspBspTree::SubdivideNode(VspBspTraversalData &tData,
592                                                                        VspBspTraversalData &frontData,
593                                                                        VspBspTraversalData &backData,
594                                                                        PolygonContainer &coincident)
595{
596        mStat.nodes += 2;
597       
598        VspBspLeaf *leaf = dynamic_cast<VspBspLeaf *>(tData.mNode);
599        // select subdivision plane
600        VspBspInterior *interior =
601                new VspBspInterior(SelectPlane(leaf, tData));
602
603#ifdef _DEBUG
604        Debug << interior << endl;
605#endif
606       
607        // subdivide rays into front and back rays
608        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
609       
610        // subdivide polygons with plane
611        mStat.splits += interior->SplitPolygons(*tData.mPolygons,
612                                                    *frontData.mPolygons,
613                                                                                        *backData.mPolygons,
614                                                                                        coincident);
615
616    // compute pvs
617        frontData.mPvs = ComputePvsSize(*frontData.mRays);
618        backData.mPvs = ComputePvsSize(*backData.mRays);
619
620        // split geometry and compute area
621        if (1)
622        {
623                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
624                                                                           *backData.mGeometry,
625                                                                           *this,
626                                                                           interior->mPlane);
627       
628               
629                frontData.mArea = frontData.mGeometry->GetArea();
630                backData.mArea = backData.mGeometry->GetArea();
631        }
632
633        // compute accumulated ray length
634        //frontData.mAccRayLength = AccumulatedRayLength(*frontData.mRays);
635        //backData.mAccRayLength = AccumulatedRayLength(*backData.mRays);
636
637        //-- create front and back leaf
638
639        VspBspInterior *parent = leaf->GetParent();
640
641        // replace a link from node's parent
642        if (!leaf->IsRoot())
643        {
644                parent->ReplaceChildLink(leaf, interior);
645                interior->SetParent(parent);
646        }
647        else // new root
648        {
649                mRoot = interior;
650        }
651
652        // and setup child links
653        interior->SetupChildLinks(new VspBspLeaf(interior), new VspBspLeaf(interior));
654       
655        frontData.mNode = interior->mFront;
656        backData.mNode = interior->mBack;
657       
658        //DEL_PTR(leaf);
659        return interior;
660}
661
662void VspBspTree::SortSplitCandidates(const PolygonContainer &polys,
663                                                                  const int axis,
664                                                                  vector<SortableEntry> &splitCandidates) const
665{
666  splitCandidates.clear();
667 
668  int requestedSize = 2 * (int)polys.size();
669  // creates a sorted split candidates array 
670  splitCandidates.reserve(requestedSize);
671 
672  PolygonContainer::const_iterator it, it_end = polys.end();
673
674  AxisAlignedBox3 box;
675
676  // insert all queries
677  for(it = polys.begin(); it != it_end; ++ it)
678  {
679          box.Initialize();
680          box.Include(*(*it));
681         
682          splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MIN, box.Min(axis), *it));
683      splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MAX, box.Max(axis), *it));
684  }
685 
686  stable_sort(splitCandidates.begin(), splitCandidates.end());
687}
688
689
690float VspBspTree::BestCostRatio(const PolygonContainer &polys,
691                                                         const AxisAlignedBox3 &box,
692                                                         const int axis,
693                                                         float &position,
694                                                         int &objectsBack,
695                                                         int &objectsFront) const
696{
697        vector<SortableEntry> splitCandidates;
698
699        SortSplitCandidates(polys, axis, splitCandidates);
700       
701        // go through the lists, count the number of objects left and right
702        // and evaluate the following cost funcion:
703        // C = ct_div_ci  + (ol + or)/queries
704       
705        int objectsLeft = 0, objectsRight = (int)polys.size();
706       
707        float minBox = box.Min(axis);
708        float maxBox = box.Max(axis);
709        float boxArea = box.SurfaceArea();
710 
711        float minBand = minBox + mSplitBorder * (maxBox - minBox);
712        float maxBand = minBox + (1.0f - mSplitBorder) * (maxBox - minBox);
713       
714        float minSum = 1e20f;
715        vector<SortableEntry>::const_iterator ci, ci_end = splitCandidates.end();
716
717        for(ci = splitCandidates.begin(); ci != ci_end; ++ ci)
718        {
719                switch ((*ci).type)
720                {
721                        case SortableEntry::POLY_MIN:
722                                ++ objectsLeft;
723                                break;
724                        case SortableEntry::POLY_MAX:
725                            -- objectsRight;
726                                break;
727                        default:
728                                break;
729                }
730               
731                if ((*ci).value > minBand && (*ci).value < maxBand)
732                {
733                        AxisAlignedBox3 lbox = box;
734                        AxisAlignedBox3 rbox = box;
735                        lbox.SetMax(axis, (*ci).value);
736                        rbox.SetMin(axis, (*ci).value);
737
738                        float sum = objectsLeft * lbox.SurfaceArea() +
739                                                objectsRight * rbox.SurfaceArea();
740     
741                        if (sum < minSum)
742                        {
743                                minSum = sum;
744                                position = (*ci).value;
745
746                                objectsBack = objectsLeft;
747                                objectsFront = objectsRight;
748                        }
749                }
750        }
751 
752        float oldCost = (float)polys.size();
753        float newCost = mAaCtDivCi + minSum / boxArea;
754        float ratio = newCost / oldCost;
755
756
757#if 0
758  Debug << "====================" << endl;
759  Debug << "costRatio=" << ratio << " pos=" << position<<" t=" << (position - minBox)/(maxBox - minBox)
760      << "\t o=(" << objectsBack << "," << objectsFront << ")" << endl;
761#endif
762  return ratio;
763}
764
765bool VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
766                                                                         const PolygonContainer &polys) const
767{
768        AxisAlignedBox3 box;
769        box.Initialize();
770       
771        // create bounding box of region
772        Polygon3::IncludeInBox(polys, box);
773       
774        int objectsBack = 0, objectsFront = 0;
775        int axis = 0;
776        float costRatio = MAX_FLOAT;
777        Vector3 position;
778
779        //-- area subdivision
780        for (int i = 0; i < 3; ++ i)
781        {
782                float p = 0;
783                float r = BestCostRatio(polys, box, i, p, objectsBack, objectsFront);
784               
785                if (r < costRatio)
786                {
787                        costRatio = r;
788                        axis = i;
789                        position = p;
790                }
791        }
792       
793        if (costRatio >= mMaxCostRatio)
794                return false;
795
796        Vector3 norm(0,0,0); norm[axis] = 1.0f;
797        plane = Plane3(norm, position);
798
799        return true;
800}
801
802Plane3 VspBspTree::SelectPlane(VspBspLeaf *leaf, VspBspTraversalData &data)
803{
804        if ((mSplitPlaneStrategy & AXIS_ALIGNED) &&
805                ((int)data.mRays->size() > mTermMinRaysForAxisAligned))
806        {
807                Plane3 plane;
808                if (SelectAxisAlignedPlane(plane, *data.mPolygons)) // TODO: should be rays
809                        return plane;
810        }
811
812        // simplest strategy: just take next polygon
813        if (mSplitPlaneStrategy & RANDOM_POLYGON)
814        {
815        if (!data.mPolygons->empty())
816                {
817                        Polygon3 *nextPoly = (*data.mPolygons)[Random((int)data.mPolygons->size())];
818                        return nextPoly->GetSupportingPlane();
819                }
820                else
821                {
822                        //-- choose plane on midpoint of a ray
823                        const int candidateIdx = Random((int)data.mRays->size());
824                                                               
825                        const Vector3 minPt = (*data.mRays)[candidateIdx].ExtrapOrigin();
826                        const Vector3 maxPt = (*data.mRays)[candidateIdx].ExtrapTermination();
827
828                        const Vector3 pt = (maxPt + minPt) * 0.5;
829
830                        const Vector3 normal =  (*data.mRays)[candidateIdx].mRay->GetDir();
831                       
832                        return Plane3(normal, pt);
833                }
834
835                return Plane3();
836        }
837
838        // use heuristics to find appropriate plane
839        return SelectPlaneHeuristics(leaf, data);
840}
841
842Plane3 VspBspTree::SelectPlaneHeuristics(VspBspLeaf *leaf, VspBspTraversalData &data)
843{
844        float lowestCost = MAX_FLOAT;
845        Plane3 bestPlane;
846        Plane3 plane;
847
848        int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
849       
850        int candidateIdx = limit;
851
852        for (int i = 0; i < limit; ++ i)
853        {
854                candidateIdx = GetNextCandidateIdx(candidateIdx, *data.mPolygons);
855               
856                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
857                // evaluate current candidate
858                const float candidateCost =
859                        SplitPlaneCost(poly->GetSupportingPlane(), data);
860
861                if (candidateCost < lowestCost)
862                {
863                        bestPlane = poly->GetSupportingPlane();
864                        lowestCost = candidateCost;
865                }
866        }
867       
868        //Debug << "lowest: " << lowestCost << endl;
869
870        //-- choose candidate planes extracted from rays
871        // we currently use different two methods chosen with
872        // equal probability
873       
874        RayInfoContainer *rays = data.mRays;
875        // take 3 ray endpoints, where two are minimum and one a maximum
876        // point or the other way round
877        for (int i = 0; i < mMaxRayCandidates / 2; ++ i)
878        {
879                candidateIdx = Random((int)rays->size());
880       
881                RayInfo rayInf = (*rays)[candidateIdx];
882                const Vector3 minPt = rayInf.ExtrapOrigin();
883                const Vector3 maxPt = rayInf.ExtrapTermination();
884
885                const Vector3 pt = (maxPt + minPt) * 0.5;
886                const Vector3 normal = Normalize(rayInf.mRay->GetDir());
887
888                plane = Plane3(normal, pt);
889       
890                const float candidateCost = SplitPlaneCost(plane, data);
891
892                if (candidateCost < lowestCost)
893                {
894                        bestPlane = plane;     
895                        lowestCost = candidateCost;
896                }
897        }
898
899        // take plane normal as plane normal and the midpoint of the ray.
900        // PROBLEM: does not resemble any point where visibility is likely to change
901        //Debug << "lowest: " << lowestCost << endl;
902        for (int i = 0; i < mMaxRayCandidates / 2; ++ i)
903        {
904                Vector3 pt[3];
905                int idx[3];
906                int cmaxT = 0;
907                int cminT = 0;
908                bool chooseMin = false;
909
910                for (int j = 0; j < 3; j ++)
911                {
912                        idx[j] = Random((int)rays->size() * 2);
913                               
914                        if (idx[j] >= (int)rays->size())
915                        {
916                                idx[j] -= (int)rays->size();
917                               
918                                chooseMin = (cminT < 2);
919                        }
920                        else
921                                chooseMin = (cmaxT < 2);
922
923                        RayInfo rayInf = (*rays)[idx[j]];
924                        pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
925                }       
926                       
927                plane = Plane3(pt[0], pt[1], pt[2]);
928
929                const float candidateCost = SplitPlaneCost(plane, data);
930
931                if (candidateCost < lowestCost)
932                {
933                        //Debug << "choose ray plane 2: " << candidateCost << endl;
934                        bestPlane = plane;
935                       
936                        lowestCost = candidateCost;
937                }
938        }       
939
940#ifdef _DEBUG
941        Debug << "plane lowest cost: " << lowestCost << endl;
942#endif
943        return bestPlane;
944}
945
946int VspBspTree::GetNextCandidateIdx(int currentIdx, PolygonContainer &polys)
947{
948        const int candidateIdx = Random(currentIdx --);
949
950        // swap candidates to avoid testing same plane 2 times
951        std::swap(polys[currentIdx], polys[candidateIdx]);
952       
953        return currentIdx;
954        //return Random((int)polys.size());
955}
956
957
958bool VspBspTree::BoundRay(const Ray &ray, float &minT, float &maxT) const
959{
960        maxT = 1e6;
961        minT = 0;
962       
963        // test with tree bounding box
964        if (!mBox.GetMinMaxT(ray, &minT, &maxT))
965                return false;
966
967        if (minT < 0) // start ray from origin
968                minT = 0;
969
970        // bound ray or line segment
971        if ((ray.GetType() == Ray::LOCAL_RAY) &&
972            !ray.intersections.empty() &&
973                (ray.intersections[0].mT <= maxT))
974        {
975                maxT = ray.intersections[0].mT;
976        }
977
978        return true;
979}
980
981inline void VspBspTree::GenerateUniqueIdsForPvs()
982{
983        Intersectable::NewMail(); sBackId = ViewCell::sMailId;
984        Intersectable::NewMail(); sFrontId = ViewCell::sMailId;
985        Intersectable::NewMail(); sFrontAndBackId = ViewCell::sMailId;
986}
987
988float VspBspTree::SplitPlaneCost(const Plane3 &candidatePlane,
989                                                                 const VspBspTraversalData &data)
990{
991        float val = 0;
992
993        float sumBalancedRays = 0;
994        float sumRaySplits = 0;
995       
996        int backId = 0;
997        int frontId = 0;
998        int frontAndBackId = 0;
999
1000        int frontPvs = 0;
1001        int backPvs = 0;
1002
1003        // probability that view point lies in child
1004        float pOverall = 0;
1005        float pFront = 0;
1006        float pBack = 0;
1007
1008        const bool pvsUseLen = false;
1009
1010        if (mSplitPlaneStrategy & PVS)
1011        {
1012                // create unique ids for pvs heuristics
1013                GenerateUniqueIdsForPvs();
1014       
1015                if (mPvsUseArea) // use front and back cell areas to approximate volume
1016                {       
1017                        // construct child geometry with regard to the candidate split plane
1018                        VspBspNodeGeometry frontCell;
1019                        VspBspNodeGeometry backCell;
1020
1021                        data.mGeometry->SplitGeometry(frontCell, backCell, *this, candidatePlane);
1022               
1023                        pFront = frontCell.GetArea();
1024                        pBack = backCell.GetArea();
1025
1026                        pOverall = data.mArea;
1027                }
1028        }
1029                       
1030        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1031
1032        for (rit = data.mRays->begin(); rit != data.mRays->end(); ++ rit)
1033        {
1034                VssRay *ray = (*rit).mRay;
1035                const int cf = (*rit).ComputeRayIntersection(candidatePlane, (*rit).mRay->mT);
1036
1037                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1038                {
1039                        sumBalancedRays += cf;
1040                }
1041               
1042                if (mSplitPlaneStrategy & BALANCED_RAYS)
1043                {
1044                        if (cf == 0)
1045                                ++ sumRaySplits;
1046                }
1047
1048                if (mSplitPlaneStrategy & PVS)
1049                {
1050                        // in case the ray intersects an object
1051                        // assure that we only count the object
1052                        // once for the front and once for the back side of the plane
1053                       
1054                        // add the termination object
1055                        AddObjToPvs(ray->mTerminationObject, cf, frontPvs, backPvs);
1056                       
1057                        // add the source object
1058                        AddObjToPvs(ray->mOriginObject, cf, frontPvs, backPvs);
1059                       
1060                        // use number or length of rays to approximate volume
1061                        if (!mPvsUseArea)
1062                        {
1063                                float len = 1;
1064
1065                                if (pvsUseLen) // use length of rays
1066                                        len = (*rit).SqrSegmentLength();
1067                       
1068                                pOverall += len;
1069
1070                                if (cf == 1)
1071                                        pFront += len;
1072                                if (cf == -1)
1073                                        pBack += len;
1074                                if (cf == 0)
1075                                {
1076                                        // use length of rays to approximate volume
1077                                        if (pvsUseLen)
1078                                        {
1079                                                float newLen = len *
1080                                                        ((*rit).GetMaxT() - (*rit).mRay->mT) /
1081                                                        ((*rit).GetMaxT() - (*rit).GetMinT());
1082               
1083                                                if (candidatePlane.Side((*rit).ExtrapOrigin()) <= 0)
1084                                                {
1085                                                        pBack += newLen;
1086                                                        pFront += len - newLen;
1087                                                }
1088                                                else
1089                                                {
1090                                                        pFront += newLen;
1091                                                        pBack += len - newLen;
1092                                                }
1093                                        }
1094                                        else
1095                                        {
1096                                                ++ pFront;
1097                                                ++ pBack;
1098                                        }
1099                                }
1100                        }
1101                }
1102        }
1103
1104        const float raysSize = (float)data.mRays->size() + Limits::Small;
1105
1106        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1107                val += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1108
1109        if (mSplitPlaneStrategy & BALANCED_RAYS)
1110                val += mBalancedRaysFactor * fabs(sumBalancedRays) /  raysSize;
1111
1112        const float denom = pOverall * (float)data.mPvs * 2.0f + Limits::Small;
1113
1114        if (mSplitPlaneStrategy & PVS)
1115        {
1116                val += mPvsFactor * (frontPvs * pFront + (backPvs * pBack)) / denom;
1117
1118                // give penalty to unbalanced split
1119                if (0)
1120                if (((pFront * 0.2 + Limits::Small) > pBack) ||
1121                        (pFront < (pBack * 0.2 + Limits::Small)))
1122                        val += 0.5;
1123        }
1124
1125#ifdef _DEBUG
1126        Debug << "totalpvs: " << pvs << " ptotal: " << pOverall
1127                  << " frontpvs: " << frontPvs << " pFront: " << pFront
1128                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
1129#endif
1130        return val;
1131}
1132
1133void VspBspTree::AddObjToPvs(Intersectable *obj,
1134                                                  const int cf,
1135                                                  int &frontPvs,
1136                                                  int &backPvs) const
1137{
1138        if (!obj)
1139                return;
1140        // TODO: does this really belong to no pvs?
1141        //if (cf == Ray::COINCIDENT) return;
1142
1143        // object belongs to both PVS
1144        if (cf >= 0)
1145        {
1146                if ((obj->mMailbox != sFrontId) &&
1147                        (obj->mMailbox != sFrontAndBackId))
1148                {
1149                        ++ frontPvs;
1150
1151                        if (obj->mMailbox == sBackId)
1152                                obj->mMailbox = sFrontAndBackId;       
1153                        else
1154                                obj->mMailbox = sFrontId;                                                               
1155                }
1156        }
1157       
1158        if (cf <= 0)
1159        {
1160                if ((obj->mMailbox != sBackId) &&
1161                        (obj->mMailbox != sFrontAndBackId))
1162                {
1163                        ++ backPvs;
1164
1165                        if (obj->mMailbox == sFrontId)
1166                                obj->mMailbox = sFrontAndBackId;
1167                        else
1168                                obj->mMailbox = sBackId;                               
1169                }
1170        }
1171}
1172
1173void VspBspTree::CollectLeaves(vector<VspBspLeaf *> &leaves) const
1174{
1175        stack<VspBspNode *> nodeStack;
1176        nodeStack.push(mRoot);
1177 
1178        while (!nodeStack.empty())
1179        {
1180                VspBspNode *node = nodeStack.top();
1181   
1182                nodeStack.pop();
1183   
1184                if (node->IsLeaf())
1185                {
1186                        VspBspLeaf *leaf = (VspBspLeaf *)node;         
1187                        leaves.push_back(leaf);
1188                }
1189                else
1190                {
1191                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(node);
1192
1193                        nodeStack.push(interior->GetBack());
1194                        nodeStack.push(interior->GetFront());
1195                }
1196        }
1197}
1198
1199AxisAlignedBox3 VspBspTree::GetBoundingBox() const
1200{
1201        return mBox;
1202}
1203
1204VspBspNode *VspBspTree::GetRoot() const
1205{
1206        return mRoot;
1207}
1208
1209void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
1210{
1211        // the node became a leaf -> evaluate stats for leafs
1212        VspBspLeaf *leaf = dynamic_cast<VspBspLeaf *>(data.mNode);
1213
1214        // store maximal and minimal depth
1215        if (data.mDepth > mStat.maxDepth)
1216                mStat.maxDepth = data.mDepth;
1217
1218        if (data.mDepth < mStat.minDepth)
1219                mStat.minDepth = data.mDepth;
1220
1221        // accumulate depth to compute average depth
1222        mStat.accumDepth += data.mDepth;
1223       
1224
1225        if (data.mDepth >= mTermMaxDepth)
1226                ++ mStat.maxDepthNodes;
1227
1228        if (data.mPvs < mTermMinPvs)
1229                ++ mStat.minPvsNodes;
1230
1231        if ((int)data.mRays->size() < mTermMinRays)
1232                ++ mStat.minRaysNodes;
1233
1234        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1235                ++ mStat.maxRayContribNodes;
1236       
1237        if (data.mGeometry->GetArea() <= mTermMinArea)
1238                ++ mStat.minAreaNodes;
1239
1240#ifdef _DEBUG
1241        Debug << "BSP stats: "
1242                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1243                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1244                  << "Area: " << data.mArea << " (min: " << mTermMinArea << "), "
1245                  << "#polygons: " << (int)data.mPolygons->size() << " (max: " << mTermMinPolys << "), "
1246                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1247                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1248                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1249#endif
1250}
1251
1252int VspBspTree::CastRay(Ray &ray)
1253{
1254        int hits = 0;
1255 
1256        stack<VspBspRayTraversalData> tStack;
1257 
1258        float maxt, mint;
1259
1260        if (!BoundRay(ray, mint, maxt))
1261                return 0;
1262
1263        Intersectable::NewMail();
1264
1265        Vector3 entp = ray.Extrap(mint);
1266        Vector3 extp = ray.Extrap(maxt);
1267 
1268        VspBspNode *node = mRoot;
1269        VspBspNode *farChild = NULL;
1270       
1271        while (1)
1272        {
1273                if (!node->IsLeaf())
1274                {
1275                        VspBspInterior *in = (VspBspInterior *) node;
1276                       
1277                        Plane3 *splitPlane = in->GetPlane();
1278
1279                        int entSide = splitPlane->Side(entp);
1280                        int extSide = splitPlane->Side(extp);
1281
1282                        Vector3 intersection;
1283
1284                        if (entSide < 0)
1285                        {
1286                                node = in->GetBack();
1287
1288                                if(extSide <= 0) // plane does not split ray => no far child
1289                                        continue;
1290                                       
1291                                farChild = in->GetFront(); // plane splits ray
1292
1293                        } else if (entSide > 0)
1294                        {
1295                                node = in->GetFront();
1296
1297                                if (extSide >= 0) // plane does not split ray => no far child
1298                                        continue;
1299
1300                                farChild = in->GetBack(); // plane splits ray                   
1301                        }
1302                        else // ray and plane are coincident
1303                        {
1304                                // WHAT TO DO IN THIS CASE ?
1305                                //break;
1306                                node = in->GetFront();
1307                                continue;
1308                        }
1309
1310                        // push data for far child
1311                        tStack.push(VspBspRayTraversalData(farChild, extp, maxt));
1312
1313                        // find intersection of ray segment with plane
1314                        float t;
1315                        extp = splitPlane->FindIntersection(ray.GetLoc(), extp, &t);
1316                        maxt *= t;
1317                       
1318                } else // reached leaf => intersection with view cell
1319                {
1320                        VspBspLeaf *leaf = dynamic_cast<VspBspLeaf *>(node);
1321     
1322                        if (!leaf->mViewCell->Mailed())
1323                        {
1324                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
1325                                leaf->mViewCell->Mail();
1326                                ++ hits;
1327                        }
1328                       
1329                        //-- fetch the next far child from the stack
1330                        if (tStack.empty())
1331                                break;
1332     
1333                        entp = extp;
1334                        mint = maxt; // NOTE: need this?
1335
1336                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1337                                break;
1338
1339                        VspBspRayTraversalData &s = tStack.top();
1340
1341                        node = s.mNode;
1342                        extp = s.mExitPoint;
1343                        maxt = s.mMaxT;
1344
1345                        tStack.pop();
1346                }
1347        }
1348
1349        return hits;
1350}
1351
1352bool VspBspTree::Export(const string filename)
1353{
1354        Exporter *exporter = Exporter::GetExporter(filename);
1355
1356        if (exporter)
1357        {
1358                //exporter->ExportVspBspTree(*this);
1359                return true;
1360        }       
1361
1362        return false;
1363}
1364
1365void VspBspTree::CollectViewCells(ViewCellContainer &viewCells) const
1366{
1367        stack<VspBspNode *> nodeStack;
1368        nodeStack.push(mRoot);
1369
1370        ViewCell::NewMail();
1371
1372        while (!nodeStack.empty())
1373        {
1374                VspBspNode *node = nodeStack.top();
1375                nodeStack.pop();
1376
1377                if (node->IsLeaf())
1378                {
1379                        ViewCell *viewCell = dynamic_cast<VspBspLeaf *>(node)->mViewCell;
1380
1381                        if (!viewCell->Mailed())
1382                        {
1383                                viewCell->Mail();
1384                                viewCells.push_back(viewCell);
1385                        }
1386                }
1387                else
1388                {
1389                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(node);
1390
1391                        nodeStack.push(interior->mFront);
1392                        nodeStack.push(interior->mBack);
1393                }
1394        }
1395}
1396
1397void VspBspTree::EvaluateViewCellsStats(VspBspViewCellsStatistics &stat) const
1398{
1399        stat.Reset();
1400
1401        stack<VspBspNode *> nodeStack;
1402        nodeStack.push(mRoot);
1403
1404        ViewCell::NewMail();
1405
1406        // exclude root cell
1407        mRootCell->Mail();
1408
1409        while (!nodeStack.empty())
1410        {
1411                VspBspNode *node = nodeStack.top();
1412                nodeStack.pop();
1413
1414                if (node->IsLeaf())
1415                {
1416                        ++ stat.bspLeaves;
1417
1418                        BspViewCell *viewCell = dynamic_cast<VspBspLeaf *>(node)->mViewCell;
1419
1420                        if (!viewCell->Mailed())
1421                        {
1422                                viewCell->Mail();
1423                               
1424                                ++ stat.viewCells;
1425                                const int pvsSize = viewCell->GetPvs().GetSize();
1426
1427                stat.pvs += pvsSize;
1428
1429                                if (pvsSize < 1)
1430                                        ++ stat.emptyPvs;
1431
1432                                if (pvsSize > stat.maxPvs)
1433                                        stat.maxPvs = pvsSize;
1434
1435                                if (pvsSize < stat.minPvs)
1436                                        stat.minPvs = pvsSize;
1437
1438                                //TODO
1439                                //if ((int)viewCell->mVspBspLeaves.size() > stat.maxVspBspLeaves)
1440                                //      stat.maxVspBspLeaves = (int)viewCell->mVspBspLeaves.size();             
1441                        }
1442                }
1443                else
1444                {
1445                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(node);
1446
1447                        nodeStack.push(interior->mFront);
1448                        nodeStack.push(interior->mBack);
1449                }
1450        }
1451}
1452
1453bool VspBspTree::MergeViewCells(VspBspLeaf *front, VspBspLeaf *back) const
1454{
1455        BspViewCell *viewCell =
1456        NULL;//TODO     dynamic_cast<BspViewCell *>(ViewCell::Merge(*front->mViewCell, *back->mViewCell));
1457       
1458        if (!viewCell)
1459                return false;
1460
1461        // change view cells of all leaves associated with the previous view cells
1462        BspViewCell *fVc = front->mViewCell;
1463        BspViewCell *bVc = back->mViewCell;
1464
1465        //TODO
1466        /*
1467        vector<VspBspLeaf *> fLeaves = fVc->mVspBspLeaves;
1468        vector<VspBspLeaf *> bLeaves = bVc->mVspBspLeaves;
1469
1470        vector<VspBspLeaf *>::const_iterator it;
1471       
1472        for (it = fLeaves.begin(); it != fLeaves.end(); ++ it)
1473        {
1474                (*it)->SetViewCell(viewCell);
1475                viewCell->mVspBspLeaves.push_back(*it);
1476        }
1477        for (it = bLeaves.begin(); it != bLeaves.end(); ++ it)
1478        {
1479                (*it)->SetViewCell(viewCell);
1480                viewCell->mVspBspLeaves.push_back(*it);
1481        }
1482       
1483        DEL_PTR(fVc);
1484        DEL_PTR(bVc);
1485*/
1486        return true;
1487}
1488
1489bool VspBspTree::ShouldMerge(VspBspLeaf *front, VspBspLeaf *back) const
1490{
1491        ViewCell *fvc = front->mViewCell;
1492        ViewCell *bvc = back->mViewCell;
1493
1494        if ((fvc == mRootCell) || (bvc == mRootCell) || (fvc == bvc))
1495                return false;
1496
1497        int fdiff = fvc->GetPvs().Diff(bvc->GetPvs());
1498
1499        if (fvc->GetPvs().GetSize() + fdiff < mMaxPvs)
1500        {
1501                if ((fvc->GetPvs().GetSize() < mMinPvs) ||     
1502                        (bvc->GetPvs().GetSize() < mMinPvs) ||
1503                        ((fdiff < mMinPvsDif) && (bvc->GetPvs().Diff(fvc->GetPvs()) < mMinPvsDif)))
1504                {
1505                        return true;
1506                }
1507        }
1508       
1509        return false;
1510}
1511
1512
1513VspBspTreeStatistics &VspBspTree::GetStat()
1514{
1515        return mStat;
1516}
1517
1518float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
1519{
1520        float len = 0;
1521
1522        RayInfoContainer::const_iterator it, it_end = rays.end();
1523
1524        for (it = rays.begin(); it != it_end; ++ it)
1525                len += (*it).SegmentLength();
1526
1527        return len;
1528}
1529
1530int VspBspTree::SplitRays(const Plane3 &plane,
1531                                           RayInfoContainer &rays,
1532                                           RayInfoContainer &frontRays,
1533                                           RayInfoContainer &backRays)
1534{
1535        int splits = 0;
1536
1537        while (!rays.empty())
1538        {
1539                RayInfo bRay = rays.back();
1540                VssRay *ray = bRay.mRay;
1541
1542                rays.pop_back();
1543       
1544                // get classification and receive new t
1545                const int cf =  bRay.ComputeRayIntersection(plane, ray->mT);
1546
1547                switch(cf)
1548                {
1549                case -1:
1550                        backRays.push_back(bRay);
1551                        break;
1552                case 1:
1553                        break;
1554                        frontRays.push_back(bRay);
1555                case 0:
1556                        //-- split ray
1557
1558                        // if start point behind plane
1559                        if (plane.Side(bRay.ExtrapOrigin()) <= 0)
1560                        {
1561                                backRays.push_back(RayInfo(ray, bRay.GetMinT(), ray->mT));
1562                                frontRays.push_back(RayInfo(ray, ray->mT, bRay.GetMaxT()));
1563                        }
1564                        else
1565                        {
1566                                frontRays.push_back(RayInfo(ray, bRay.GetMinT(), ray->mT));
1567                                backRays.push_back(RayInfo(ray, ray->mT, bRay.GetMaxT()));
1568                        }
1569                        break;
1570                default:
1571                        Debug << "Should not come here 4" << endl;
1572                        break;
1573                }
1574        }
1575
1576        return splits;
1577}
1578
1579void VspBspTree::ExtractHalfSpaces(VspBspNode *n, vector<Plane3> &halfSpaces) const
1580{
1581        VspBspNode *lastNode;
1582        do
1583        {
1584                lastNode = n;
1585
1586                // want to get planes defining geometry of this node => don't take
1587                // split plane of node itself
1588                n = n->GetParent();
1589               
1590                if (n)
1591                {
1592                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(n);
1593                        Plane3 halfSpace = *dynamic_cast<VspBspInterior *>(interior)->GetPlane();
1594
1595            if (interior->mFront != lastNode)
1596                                halfSpace.ReverseOrientation();
1597
1598                        halfSpaces.push_back(halfSpace);
1599                }
1600        }
1601        while (n);
1602}
1603
1604void VspBspTree::ConstructGeometry(VspBspNode *n, VspBspNodeGeometry &cell) const
1605{
1606        PolygonContainer polys;
1607        ConstructGeometry(n, polys);
1608        cell.mPolys = polys;
1609}
1610
1611void VspBspTree::ConstructGeometry(VspBspNode *n, PolygonContainer &cell) const
1612{
1613        vector<Plane3> halfSpaces;
1614        ExtractHalfSpaces(n, halfSpaces);
1615
1616        PolygonContainer candidatePolys;
1617
1618        // bounded planes are added to the polygons (reverse polygons
1619        // as they have to be outfacing
1620        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
1621        {
1622                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
1623               
1624                if (p->Valid())
1625                {
1626                        candidatePolys.push_back(p->CreateReversePolygon());
1627                        DEL_PTR(p);
1628                }
1629        }
1630
1631        // add faces of bounding box (also could be faces of the cell)
1632        for (int i = 0; i < 6; ++ i)
1633        {
1634                VertexContainer vertices;
1635       
1636                for (int j = 0; j < 4; ++ j)
1637                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
1638
1639                candidatePolys.push_back(new Polygon3(vertices));
1640        }
1641
1642        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
1643        {
1644                // polygon is split by all other planes
1645                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
1646                {
1647                        if (i == j) // polygon and plane are coincident
1648                                continue;
1649
1650                        VertexContainer splitPts;
1651                        Polygon3 *frontPoly, *backPoly;
1652
1653                        const int cf = candidatePolys[i]->ClassifyPlane(halfSpaces[j]);
1654                       
1655                        switch (cf)
1656                        {
1657                                case Polygon3::SPLIT:
1658                                        frontPoly = new Polygon3();
1659                                        backPoly = new Polygon3();
1660
1661                                        candidatePolys[i]->Split(halfSpaces[j],
1662                                                                                         *frontPoly,
1663                                                                                         *backPoly);
1664
1665                                        DEL_PTR(candidatePolys[i]);
1666
1667                                        if (frontPoly->Valid())
1668                                                candidatePolys[i] = frontPoly;
1669                                        else
1670                                                DEL_PTR(frontPoly);
1671
1672                                        DEL_PTR(backPoly);
1673                                        break;
1674                                case Polygon3::BACK_SIDE:
1675                                        DEL_PTR(candidatePolys[i]);
1676                                        break;
1677                                // just take polygon as it is
1678                                case Polygon3::FRONT_SIDE:
1679                                case Polygon3::COINCIDENT:
1680                                default:
1681                                        break;
1682                        }
1683                }
1684               
1685                if (candidatePolys[i])
1686                        cell.push_back(candidatePolys[i]);
1687        }
1688}
1689
1690void VspBspTree::ConstructGeometry(BspViewCell *vc, PolygonContainer &cell) const
1691{
1692        /*
1693        TODO
1694        vector<VspBspLeaf *> leaves = vc->mBspLeaves;
1695
1696        vector<VspBspLeaf *>::const_iterator it, it_end = leaves.end();
1697
1698        for (it = leaves.begin(); it != it_end; ++ it)
1699                ConstructGeometry(*it, vcGeom);*/
1700}
1701
1702int VspBspTree::FindNeighbors(VspBspNode *n, vector<VspBspLeaf *> &neighbors,
1703                                                   const bool onlyUnmailed) const
1704{
1705        PolygonContainer cell;
1706
1707        ConstructGeometry(n, cell);
1708
1709        stack<VspBspNode *> nodeStack;
1710        nodeStack.push(mRoot);
1711               
1712        // planes needed to verify that we found neighbor leaf.
1713        vector<Plane3> halfSpaces;
1714        ExtractHalfSpaces(n, halfSpaces);
1715
1716        while (!nodeStack.empty())
1717        {
1718                VspBspNode *node = nodeStack.top();
1719                nodeStack.pop();
1720
1721                if (node->IsLeaf())
1722                {
1723            if (node != n && (!onlyUnmailed || !node->Mailed()))
1724                        {
1725                                // test all planes of current node if candidate really
1726                                // is neighbour
1727                                PolygonContainer neighborCandidate;
1728                                ConstructGeometry(node, neighborCandidate);
1729                               
1730                                bool isAdjacent = true;
1731                                for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
1732                                {
1733                                        const int cf =
1734                                                Polygon3::ClassifyPlane(neighborCandidate, halfSpaces[i]);
1735
1736                                        if (cf == Polygon3::BACK_SIDE)
1737                                                isAdjacent = false;
1738                                }
1739
1740                                if (isAdjacent)
1741                                        neighbors.push_back(dynamic_cast<VspBspLeaf *>(node));
1742
1743                                CLEAR_CONTAINER(neighborCandidate);
1744                        }
1745                }
1746                else
1747                {
1748                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(node);
1749       
1750                        const int cf = Polygon3::ClassifyPlane(cell, interior->mPlane);
1751
1752                        if (cf == Polygon3::FRONT_SIDE)
1753                                nodeStack.push(interior->mFront);
1754                        else
1755                                if (cf == Polygon3::BACK_SIDE)
1756                                        nodeStack.push(interior->mBack);
1757                                else
1758                                {
1759                                        // random decision
1760                                        nodeStack.push(interior->mBack);
1761                                        nodeStack.push(interior->mFront);
1762                                }
1763                }
1764        }
1765       
1766        CLEAR_CONTAINER(cell);
1767        return (int)neighbors.size();
1768}
1769
1770VspBspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
1771{
1772    stack<VspBspNode *> nodeStack;
1773        nodeStack.push(mRoot);
1774       
1775        int mask = rand();
1776 
1777        while (!nodeStack.empty())
1778        {
1779                VspBspNode *node = nodeStack.top();
1780                nodeStack.pop();
1781         
1782                if (node->IsLeaf())
1783                {
1784                        return dynamic_cast<VspBspLeaf *>(node);
1785                }
1786                else
1787                {
1788                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(node);
1789                       
1790                        VspBspNode *next;
1791       
1792                        PolygonContainer cell;
1793
1794                        // todo: not very efficient: constructs full cell everytime
1795                        ConstructGeometry(interior, cell);
1796
1797                        const int cf = Polygon3::ClassifyPlane(cell, halfspace);
1798
1799                        if (cf == Polygon3::BACK_SIDE)
1800                                next = interior->mFront;
1801                        else
1802                                if (cf == Polygon3::FRONT_SIDE)
1803                                        next = interior->mFront;
1804                        else
1805                        {
1806                                // random decision
1807                                if (mask & 1)
1808                                        next = interior->mBack;
1809                                else
1810                                        next = interior->mFront;
1811                                mask = mask >> 1;
1812                        }
1813
1814                        nodeStack.push(next);
1815                }
1816        }
1817       
1818        return NULL;
1819}
1820
1821VspBspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
1822{
1823        stack<VspBspNode *> nodeStack;
1824       
1825        nodeStack.push(mRoot);
1826
1827        int mask = rand();
1828       
1829        while (!nodeStack.empty())
1830        {
1831                VspBspNode *node = nodeStack.top();
1832                nodeStack.pop();
1833               
1834                if (node->IsLeaf())
1835                {
1836                        if ( (!onlyUnmailed || !node->Mailed()) )
1837                                return dynamic_cast<VspBspLeaf *>(node);
1838                }
1839                else
1840                {
1841                        VspBspInterior *interior = dynamic_cast<VspBspInterior *>(node);
1842
1843                        // random decision
1844                        if (mask & 1)
1845                                nodeStack.push(interior->mBack);
1846                        else
1847                                nodeStack.push(interior->mFront);
1848
1849                        mask = mask >> 1;
1850                }
1851        }
1852       
1853        return NULL;
1854}
1855
1856int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
1857{
1858        int pvsSize = 0;
1859
1860        RayInfoContainer::const_iterator rit, rit_end = rays.end();
1861
1862        Intersectable::NewMail();
1863
1864        for (rit = rays.begin(); rit != rays.end(); ++ rit)
1865        {
1866                VssRay *ray = (*rit).mRay;
1867               
1868                if (ray->mOriginObject)
1869                {
1870                        if (!ray->mOriginObject->Mailed())
1871                        {
1872                                ray->mOriginObject->Mail();
1873                                ++ pvsSize;
1874                        }
1875                }
1876                if (ray->mTerminationObject)
1877                {
1878                        if (!ray->mTerminationObject->Mailed())
1879                        {
1880                                ray->mTerminationObject->Mail();
1881                                ++ pvsSize;
1882                        }
1883                }
1884        }
1885
1886        return pvsSize;
1887}
1888
1889/*************************************************************
1890 *            VspBspNodeGeometry Implementation                 *
1891 *************************************************************/
1892
1893VspBspNodeGeometry::~VspBspNodeGeometry()
1894{
1895        CLEAR_CONTAINER(mPolys);
1896}
1897
1898float VspBspNodeGeometry::GetArea() const
1899{
1900        return Polygon3::GetArea(mPolys);
1901}
1902
1903void VspBspNodeGeometry::SplitGeometry(VspBspNodeGeometry &front,
1904                                                                        VspBspNodeGeometry &back,
1905                                                                        const VspBspTree &tree,                                         
1906                                                                        const Plane3 &splitPlane) const
1907{       
1908        // get cross section of new polygon
1909        Polygon3 *planePoly = tree.GetBoundingBox().CrossSection(splitPlane);
1910
1911        planePoly = SplitPolygon(planePoly, tree);
1912
1913        //-- plane poly splits all other cell polygons
1914        for (int i = 0; i < (int)mPolys.size(); ++ i)
1915        {
1916                const int cf = mPolys[i]->ClassifyPlane(splitPlane, 0.00001f);
1917                       
1918                // split new polygon with all previous planes
1919                switch (cf)
1920                {
1921                        case Polygon3::SPLIT:
1922                                {
1923                                        Polygon3 *poly = new Polygon3(mPolys[i]->mVertices);
1924
1925                                        Polygon3 *frontPoly = new Polygon3();
1926                                        Polygon3 *backPoly = new Polygon3();
1927                               
1928                                        poly->Split(splitPlane, *frontPoly, *backPoly);
1929
1930                                        DEL_PTR(poly);
1931
1932                                        if (frontPoly->Valid())
1933                                                front.mPolys.push_back(frontPoly);
1934                                        if (backPoly->Valid())
1935                                                back.mPolys.push_back(backPoly);
1936                                }
1937                               
1938                                break;
1939                        case Polygon3::BACK_SIDE:
1940                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));                     
1941                                break;
1942                        case Polygon3::FRONT_SIDE:
1943                                front.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));     
1944                                break;
1945                        case Polygon3::COINCIDENT:
1946                                //front.mPolys.push_back(CreateReversePolygon(mPolys[i]));
1947                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));
1948                                break;
1949                        default:
1950                                break;
1951                }
1952        }
1953
1954        //-- finally add the new polygon to the child cells
1955        if (planePoly)
1956        {
1957                // add polygon with normal pointing into positive half space to back cell
1958                back.mPolys.push_back(planePoly);
1959                // add polygon with reverse orientation to front cell
1960                front.mPolys.push_back(planePoly->CreateReversePolygon());
1961        }
1962
1963        //Debug << "returning new geometry " << mPolys.size() << " f: " << front.mPolys.size() << " b: " << back.mPolys.size() << endl;
1964        //Debug << "old area " << GetArea() << " f: " << front.GetArea() << " b: " << back.GetArea() << endl;
1965}
1966
1967Polygon3 *VspBspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
1968                                                                                const VspBspTree &tree) const
1969{
1970        // polygon is split by all other planes
1971        for (int i = 0; (i < (int)mPolys.size()) && planePoly; ++ i)
1972        {
1973                Plane3 plane = mPolys[i]->GetSupportingPlane();
1974
1975                const int cf =
1976                        planePoly->ClassifyPlane(plane, 0.00001f);
1977                       
1978                // split new polygon with all previous planes
1979                switch (cf)
1980                {
1981                        case Polygon3::SPLIT:
1982                                {
1983                                        Polygon3 *frontPoly = new Polygon3();
1984                                        Polygon3 *backPoly = new Polygon3();
1985
1986                                        planePoly->Split(plane, *frontPoly, *backPoly);
1987                                        DEL_PTR(planePoly);
1988
1989                                        if (backPoly->Valid())
1990                                                planePoly = backPoly;
1991                                        else
1992                                                DEL_PTR(backPoly);
1993                                }
1994                                break;
1995                        case Polygon3::FRONT_SIDE:
1996                                DEL_PTR(planePoly);
1997                break;
1998                        // polygon is taken as it is
1999                        case Polygon3::BACK_SIDE:
2000                        case Polygon3::COINCIDENT:
2001                        default:
2002                                break;
2003                }
2004        }
2005
2006        return planePoly;
2007}
2008
2009void VspBspViewCellsStatistics::Print(ostream &app) const
2010{
2011        app << "===== VspBspViewCells statistics ===============\n";
2012
2013        app << setprecision(4);
2014
2015        //app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
2016
2017        app << "#N_OVERALLPVS ( objects in PVS )\n" << pvs << endl;
2018
2019        app << "#N_PMAXPVS ( largest PVS )\n" << maxPvs << endl;
2020
2021        app << "#N_PMINPVS ( smallest PVS )\n" << minPvs << endl;
2022
2023        app << "#N_PAVGPVS ( average PVS )\n" << AvgPvs() << endl;
2024
2025        app << "#N_PEMPTYPVS ( view cells with PVS smaller 2 )\n" << emptyPvs << endl;
2026
2027        app << "#N_VIEWCELLS ( number of view cells)\n" << viewCells << endl;
2028
2029        app << "#N_AVGBSPLEAVES (average number of BSP leaves per view cell )\n" << AvgVspBspLeaves() << endl;
2030
2031        app << "#N_MAXBSPLEAVES ( maximal number of BSP leaves per view cell )\n" << maxVspBspLeaves << endl;
2032       
2033        app << "===== END OF VspBspViewCells statistics ==========\n";
2034}
2035
2036BspViewCell *VspBspTree::GetRootCell() const
2037{
2038        return mRootCell;
2039}
Note: See TracBrowser for help on using the repository browser.