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

Revision 590, 70.1 KB checked in by mattausch, 18 years ago (diff)

implemented some code for merge history loading

Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellBsp.h"
17#include "ViewCellsManager.h"
18#include "Beam.h"
19
20
21//-- static members
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a minimum number of ray splits.
25*/
26const float VspBspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for  balanced rays.
29*/
30const float VspBspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
31
32
33int VspBspTree::sFrontId = 0;
34int VspBspTree::sBackId = 0;
35int VspBspTree::sFrontAndBackId = 0;
36
37
38
39
40// pvs penalty can be different from pvs size
41inline float EvalPvsPenalty(const int pvs,
42                                                        const int lower,
43                                                        const int upper)
44{
45        // clamp to minmax values
46        if (pvs < lower)
47                return (float)lower;
48        if (pvs > upper)
49                return (float)upper;
50
51        return (float)pvs;
52}
53
54
55
56
57/**********************************************************************/
58/*                  class VspBspTree implementation                   */
59/**********************************************************************/
60
61
62VspBspTree::VspBspTree():
63mRoot(NULL),
64mUseAreaForPvs(false),
65mCostNormalizer(Limits::Small),
66mViewCellsManager(NULL),
67mOutOfBoundsCell(NULL),
68mStoreRays(false),
69mRenderCostWeight(0.5)
70{
71        bool randomize = false;
72        environment->GetBoolValue("VspBspTree.Construction.randomize", randomize);
73        if (randomize)
74                Randomize(); // initialise random generator for heuristics
75
76        //-- termination criteria for autopartition
77        environment->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
78        environment->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
79        environment->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
80        environment->GetFloatValue("VspBspTree.Termination.minProbability", mTermMinProbability);
81        environment->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
82        environment->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
83        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
84        environment->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
85        environment->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
86        //-- max cost ratio for early tree termination
87        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
88
89        //-- factors for bsp tree split plane heuristics
90        environment->GetFloatValue("VspBspTree.Factor.balancedRays", mBalancedRaysFactor);
91        environment->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
92        environment->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
93
94
95        //-- partition criteria
96        environment->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
97        environment->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
98        environment->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
99
100        environment->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
101        environment->GetIntValue("VspBspTree.maxTests", mMaxTests);
102
103        // if only the driving axis is used for axis aligned split
104        environment->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
105       
106        //-- termination criteria for axis aligned split
107        environment->GetFloatValue("VspBspTree.Termination.AxisAligned.maxRayContribution",
108                mTermMaxRayContriForAxisAligned);
109        environment->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
110                mTermMinRaysForAxisAligned);
111
112        //environment->GetFloatValue("VspBspTree.maxTotalMemory", mMaxTotalMemory);
113        environment->GetFloatValue("VspBspTree.maxStaticMemory", mMaxMemory);
114
115        environment->GetFloatValue("VspBspTree.Construction.renderCostWeight", mRenderCostWeight);
116
117
118
119
120        //-- debug output
121
122        Debug << "******* VSP BSP options ******** " << endl;
123    Debug << "max depth: " << mTermMaxDepth << endl;
124        Debug << "min PVS: " << mTermMinPvs << endl;
125        Debug << "min probabiliy: " << mTermMinProbability << endl;
126        Debug << "min rays: " << mTermMinRays << endl;
127        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
128        //Debug << "VSP BSP mininam accumulated ray lenght: ", mTermMinAccRayLength) << endl;
129        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
130        Debug << "miss tolerance: " << mTermMissTolerance << endl;
131        Debug << "max view cells: " << mMaxViewCells << endl;
132        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
133        Debug << "max plane candidates: " << mMaxRayCandidates << endl;
134        Debug << "randomize: " << randomize << endl;
135
136        Debug << "using area for pvs: " << mUseAreaForPvs << endl;
137        Debug << "render cost weight: " << mRenderCostWeight << endl;
138        Debug << "Split plane strategy: ";
139
140        if (mSplitPlaneStrategy & RANDOM_POLYGON)
141        {
142                Debug << "random polygon ";
143        }
144        if (mSplitPlaneStrategy & AXIS_ALIGNED)
145        {
146                Debug << "axis aligned ";
147        }
148        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
149        {
150                mCostNormalizer += mLeastRaySplitsFactor;
151                Debug << "least ray splits ";
152        }
153        if (mSplitPlaneStrategy & BALANCED_RAYS)
154        {
155                mCostNormalizer += mBalancedRaysFactor;
156                Debug << "balanced rays ";
157        }
158        if (mSplitPlaneStrategy & PVS)
159        {
160                mCostNormalizer += mPvsFactor;
161                Debug << "pvs";
162        }
163
164
165        mSplitCandidates = new vector<SortableEntry>;
166
167        Debug << endl;
168}
169
170
171BspViewCell *VspBspTree::GetOutOfBoundsCell()
172{
173        return mOutOfBoundsCell;
174}
175
176
177BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
178{
179        if (!mOutOfBoundsCell)
180        {
181                mOutOfBoundsCell = new BspViewCell();
182                mOutOfBoundsCell->SetId(-1);
183                mOutOfBoundsCell->SetValid(false);
184        }
185
186        return mOutOfBoundsCell;
187}
188
189
190const BspTreeStatistics &VspBspTree::GetStatistics() const
191{
192        return mBspStats;
193}
194
195
196VspBspTree::~VspBspTree()
197{
198        DEL_PTR(mRoot);
199        DEL_PTR(mSplitCandidates);
200}
201
202
203int VspBspTree::AddMeshToPolygons(Mesh *mesh,
204                                                                  PolygonContainer &polys,
205                                                                  MeshInstance *parent)
206{
207        FaceContainer::const_iterator fi;
208
209        // copy the face data to polygons
210        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
211        {
212                Polygon3 *poly = new Polygon3((*fi), mesh);
213
214                if (poly->Valid(mEpsilon))
215                {
216                        poly->mParent = parent; // set parent intersectable
217                        polys.push_back(poly);
218                }
219                else
220                        DEL_PTR(poly);
221        }
222        return (int)mesh->mFaces.size();
223}
224
225
226int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
227                                                          PolygonContainer &polys,
228                                                          int maxObjects)
229{
230        int limit = (maxObjects > 0) ?
231                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
232
233        int polysSize = 0;
234
235        for (int i = 0; i < limit; ++ i)
236        {
237                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
238                {
239                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
240                        polysSize +=
241                                AddMeshToPolygons(viewCells[i]->GetMesh(),
242                                                                  polys,
243                                                                  viewCells[i]);
244                }
245        }
246
247        return polysSize;
248}
249
250
251int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
252                                                                 PolygonContainer &polys,
253                                                                 int maxObjects)
254{
255        int limit = (maxObjects > 0) ?
256                Min((int)objects.size(), maxObjects) : (int)objects.size();
257
258        for (int i = 0; i < limit; ++i)
259        {
260                Intersectable *object = objects[i];//*it;
261                Mesh *mesh = NULL;
262
263                switch (object->Type()) // extract the meshes
264                {
265                case Intersectable::MESH_INSTANCE:
266                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
267                        break;
268                case Intersectable::VIEW_CELL:
269                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
270                        break;
271                        // TODO: handle transformed mesh instances
272                default:
273                        Debug << "intersectable type not supported" << endl;
274                        break;
275                }
276
277        if (mesh) // copy the mesh data to polygons
278                {
279                        mBox.Include(object->GetBox()); // add to BSP tree aabb
280                        AddMeshToPolygons(mesh, polys, NULL);
281                }
282        }
283
284        return (int)polys.size();
285}
286
287
288void VspBspTree::Construct(const VssRayContainer &sampleRays,
289                                                   AxisAlignedBox3 *forcedBoundingBox)
290{
291        mBspStats.nodes = 1;
292        mBox.Initialize();      // initialise BSP tree bounding box
293
294        if (forcedBoundingBox)
295                mBox = *forcedBoundingBox;
296       
297        PolygonContainer polys;
298        RayInfoContainer *rays = new RayInfoContainer();
299
300        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
301
302        long startTime = GetTime();
303
304        cout << "Extracting polygons from rays ... ";
305
306        Intersectable::NewMail();
307
308        int numObj = 0;
309
310        //-- extract polygons intersected by the rays
311        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
312        {
313                VssRay *ray = *rit;
314
315                if ((mBox.IsInside(ray->mTermination) || !forcedBoundingBox) &&
316                        ray->mTerminationObject &&
317                        !ray->mTerminationObject->Mailed())
318                {
319                        ray->mTerminationObject->Mail();
320                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mTerminationObject);
321                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
322                        ++ numObj;
323                        //-- compute bounding box
324                        if (!forcedBoundingBox)
325                                mBox.Include(ray->mTermination);
326                }
327
328                if ((mBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
329                        ray->mOriginObject &&
330                        !ray->mOriginObject->Mailed())
331                {
332                        ray->mOriginObject->Mail();
333                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
334                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
335                        ++ numObj;
336
337                        //-- compute bounding box
338                        if (!forcedBoundingBox)
339                                mBox.Include(ray->mOrigin);
340                }
341        }
342       
343        Debug << "maximal pvs (i.e., pvs still considered as valid) : " << mViewCellsManager->GetMaxPvsSize() << endl;
344
345        //-- store rays
346        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
347        {
348                VssRay *ray = *rit;
349
350                float minT, maxT;
351
352                static Ray hray;
353                hray.Init(*ray);
354
355                // TODO: not very efficient to implictly cast between rays types
356                if (mBox.GetRaySegment(hray, minT, maxT))
357                {
358                        float len = ray->Length();
359
360                        if (!len)
361                                len = Limits::Small;
362
363                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
364                }
365        }
366
367        // normalize
368        if (mUseAreaForPvs)
369                mTermMinProbability *= mBox.SurfaceArea();
370        else
371                mTermMinProbability *= mBox.GetVolume();
372
373        mBspStats.polys = (int)polys.size();
374
375        cout << "finished" << endl;
376
377        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
378                  << (int)sampleRays.size() << " rays in "
379                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
380
381        Construct(polys, rays);
382
383        // clean up polygons
384        CLEAR_CONTAINER(polys);
385}
386
387
388// return memory usage in MB
389float VspBspTree::GetMemUsage(/*const VspBspTraversalStack &tstack*/) const
390{
391        return
392                (sizeof(VspBspTree) +
393                 (float)mBspStats.Leaves() * sizeof(BspLeaf) +
394                 // the nodes in the stack is the minimal additional number of leaves
395                 //(float)tstack.size() * sizeof(BspLeaf) +
396                 mBspStats.Interior() * sizeof(BspInterior) +
397                 mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
398}
399
400
401
402void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
403{
404        VspBspTraversalStack tStack;
405
406        mRoot = new BspLeaf();
407
408        // constrruct root node geometry
409        BspNodeGeometry *geom = new BspNodeGeometry();
410        ConstructGeometry(mRoot, *geom);
411
412        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
413
414        VspBspTraversalData tData(mRoot,
415                                                          new PolygonContainer(polys),
416                                                          0,
417                                                          rays,
418                              ComputePvsSize(*rays),
419                                                          prop,
420                                                          geom);
421
422        // first node is kd node, i.e. an axis aligned box
423        if (1)
424        tData.mIsKdNode = true;
425        else
426                tData.mIsKdNode = false;
427
428        tStack.push(tData);
429
430        mBspStats.Start();
431        cout << "Contructing vsp bsp tree ... \n";
432
433        long startTime = GetTime();     
434
435        // used for intermediate time measurements and progress
436        long interTime = GetTime();     
437
438        mOutOfMemory = false;
439
440        int nleaves = 500;
441
442        while (!tStack.empty())
443        {
444                tData = tStack.top();
445            tStack.pop();               
446
447                if (0 && !mOutOfMemory)
448                {
449                        float mem = GetMemUsage();
450
451                        if (mem > mMaxMemory)
452                        {
453                                mOutOfMemory = true;
454                                Debug << "memory limit reached: " << mem << endl;
455                        }
456                }
457
458                // subdivide leaf node
459                BspNode *r = Subdivide(tStack, tData);
460
461                if (r == mRoot)
462                        Debug << "VSP BSP tree construction time spent at root: "
463                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
464
465                if (mBspStats.Leaves() >= nleaves)
466                {
467                        nleaves += 500;
468                               
469                        cout << "leaves=" << mBspStats.Leaves() << endl;
470                        Debug << "needed "
471                                  << TimeDiff(interTime, GetTime())*1e-3
472                                  << " secs to create 500 leaves" << endl;
473                        interTime = GetTime();
474                }
475        }
476
477        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
478        cout << "finished\n";
479
480        mBspStats.Stop();
481}
482
483
484bool VspBspTree::TerminationCriteriaMet(const VspBspTraversalData &data) const
485{
486        return
487                (((int)data.mRays->size() <= mTermMinRays) ||
488                 (data.mPvs <= mTermMinPvs)   ||
489                 (data.mProbability <= mTermMinProbability) ||
490                 (mBspStats.Leaves() >= mMaxViewCells) ||
491                 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
492                 (data.mDepth >= mTermMaxDepth));
493}
494
495
496BspNode *VspBspTree::Subdivide(VspBspTraversalStack &tStack,
497                                                           VspBspTraversalData &tData)
498{
499        BspNode *newNode = tData.mNode;
500
501        if (!mOutOfMemory && !TerminationCriteriaMet(tData))
502        {
503                PolygonContainer coincident;
504
505                VspBspTraversalData tFrontData;
506                VspBspTraversalData tBackData;
507
508                // create new interior node and two leaf nodes
509                // or return leaf as it is (if maxCostRatio missed)
510                newNode = SubdivideNode(tData, tFrontData, tBackData, coincident);
511
512                if (!newNode->IsLeaf()) //-- continue subdivision
513                {
514                        // push the children on the stack
515                        tStack.push(tFrontData);
516                        tStack.push(tBackData);
517
518                        // delete old leaf node
519                        DEL_PTR(tData.mNode);
520                }
521        }
522
523        //-- terminate traversal and create new view cell
524        if (newNode->IsLeaf())
525        {
526                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
527                BspViewCell *viewCell = new BspViewCell();
528               
529                leaf->SetViewCell(viewCell);
530       
531                //-- update pvs
532                int conSamp = 0;
533                float sampCon = 0.0f;
534                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
535
536                mBspStats.contributingSamples += conSamp;
537                mBspStats.sampleContributions +=(int) sampCon;
538
539                //-- store additional info
540                if (mStoreRays)
541                {
542                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
543                        for (it = tData.mRays->begin(); it != it_end; ++ it)
544                                leaf->mVssRays.push_back((*it).mRay);
545                }
546                // should I check here?
547                if (0 && !mViewCellsManager->CheckValidity(viewCell, 0, mViewCellsManager->GetMaxPvsSize()))
548                {
549                        viewCell->SetValid(false);
550                        leaf->SetTreeValid(false);
551                        PropagateUpValidity(leaf);
552
553                        ++ mBspStats.invalidLeaves;
554                }
555               
556        viewCell->mLeaf = leaf;
557
558                if (mUseAreaForPvs)
559                        viewCell->SetArea(tData.mProbability);
560                else
561                        viewCell->SetVolume(tData.mProbability);
562
563                leaf->mProbability = tData.mProbability;
564
565                EvaluateLeafStats(tData);               
566        }
567
568        //-- cleanup
569        tData.Clear();
570
571        return newNode;
572}
573
574
575BspNode *VspBspTree::SubdivideNode(VspBspTraversalData &tData,
576                                                                   VspBspTraversalData &frontData,
577                                                                   VspBspTraversalData &backData,
578                                                                   PolygonContainer &coincident)
579{
580        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
581       
582        // select subdivision plane
583        Plane3 splitPlane;
584       
585        int maxCostMisses = tData.mMaxCostMisses;
586
587        const bool success =
588                SelectPlane(splitPlane, leaf, tData, frontData, backData);
589
590        if (!success)
591        {
592                ++ maxCostMisses;
593
594                if (maxCostMisses > mTermMissTolerance)
595                {
596                        // terminate branch because of max cost
597                        ++ mBspStats.maxCostNodes;
598            return leaf;
599                }
600        }
601
602        mBspStats.nodes += 2;
603
604        //-- subdivide further
605        BspInterior *interior = new BspInterior(splitPlane);
606
607#ifdef _DEBUG
608        Debug << interior << endl;
609#endif
610
611        //-- the front and back traversal data is filled with the new values
612        frontData.mDepth = tData.mDepth + 1;
613        frontData.mPolygons = new PolygonContainer();
614        frontData.mRays = new RayInfoContainer();
615       
616        backData.mDepth = tData.mDepth + 1;
617        backData.mPolygons = new PolygonContainer();
618        backData.mRays = new RayInfoContainer();
619       
620        // subdivide rays
621        SplitRays(interior->GetPlane(),
622                          *tData.mRays,
623                          *frontData.mRays,
624                          *backData.mRays);
625
626        // subdivide polygons
627        SplitPolygons(interior->GetPlane(),
628                                  *tData.mPolygons,
629                      *frontData.mPolygons,
630                                  *backData.mPolygons,
631                                  coincident);
632
633
634        // how often was max cost ratio missed in this branch?
635        frontData.mMaxCostMisses = maxCostMisses;
636        backData.mMaxCostMisses = maxCostMisses;
637
638        // compute pvs
639        frontData.mPvs = ComputePvsSize(*frontData.mRays);
640        backData.mPvs = ComputePvsSize(*backData.mRays);
641
642        // split front and back node geometry and compute area
643       
644        // if geometry was not already computed
645        if (!frontData.mGeometry && !backData.mGeometry)
646        {
647                frontData.mGeometry = new BspNodeGeometry();
648                backData.mGeometry = new BspNodeGeometry();
649
650                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
651                                                                           *backData.mGeometry,
652                                                                           interior->GetPlane(),
653                                                                           mBox,
654                                                                           mEpsilon);
655               
656                if (mUseAreaForPvs)
657                {
658                        frontData.mProbability = frontData.mGeometry->GetArea();
659                        backData.mProbability = backData.mGeometry->GetArea();
660                }
661                else
662                {
663                        frontData.mProbability = frontData.mGeometry->GetVolume();
664                        backData.mProbability = backData.mGeometry->GetVolume();
665                }
666        }
667       
668
669        //-- create front and back leaf
670
671        BspInterior *parent = leaf->GetParent();
672
673        // replace a link from node's parent
674        if (parent)
675        {
676                parent->ReplaceChildLink(leaf, interior);
677                interior->SetParent(parent);
678        }
679        else // new root
680        {
681                mRoot = interior;
682        }
683
684        // and setup child links
685        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
686
687        frontData.mNode = interior->GetFront();
688        backData.mNode = interior->GetBack();
689
690        //DEL_PTR(leaf);
691        return interior;
692}
693
694
695void VspBspTree::AddToPvs(BspLeaf *leaf,
696                                                  const RayInfoContainer &rays,
697                                                  float &sampleContributions,
698                                                  int &contributingSamples)
699{
700  sampleContributions = 0;
701  contributingSamples = 0;
702 
703  RayInfoContainer::const_iterator it, it_end = rays.end();
704 
705  ViewCell *vc = leaf->GetViewCell();
706 
707  // add contributions from samples to the PVS
708  for (it = rays.begin(); it != it_end; ++ it)
709        {
710          float sc = 0.0f;
711          VssRay *ray = (*it).mRay;
712          bool madeContrib = false;
713          float contribution;
714          if (ray->mTerminationObject) {
715                if (vc->GetPvs().AddSample(ray->mTerminationObject, ray->mPdf, contribution))
716                  madeContrib = true;
717                sc += contribution;
718          }
719         
720          if (ray->mOriginObject) {
721                if (vc->GetPvs().AddSample(ray->mOriginObject, ray->mPdf, contribution))
722                  madeContrib = true;
723                sc += contribution;
724          }
725         
726          sampleContributions += sc;
727          if (madeContrib)
728                  ++ contributingSamples;
729               
730          //leaf->mVssRays.push_back(ray);
731        }
732}
733
734
735void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays, const int axis)
736{
737        mSplitCandidates->clear();
738
739        int requestedSize = 2 * (int)(rays.size());
740        // creates a sorted split candidates array
741        if (mSplitCandidates->capacity() > 500000 &&
742                requestedSize < (int)(mSplitCandidates->capacity()/10) )
743        {
744        delete mSplitCandidates;
745                mSplitCandidates = new vector<SortableEntry>;
746        }
747
748        mSplitCandidates->reserve(requestedSize);
749
750        // insert all queries
751        for(RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
752        {
753                bool positive = (*ri).mRay->HasPosDir(axis);
754                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
755                                                                                                  (*ri).ExtrapOrigin(axis), (*ri).mRay));
756
757                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
758                                                                                                  (*ri).ExtrapTermination(axis), (*ri).mRay));
759        }
760
761        stable_sort(mSplitCandidates->begin(), mSplitCandidates->end());
762}
763
764
765float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
766                                                                                  const AxisAlignedBox3 &box,
767                                                                                  const int pvsSize,
768                                                                                  const int &axis,
769                                          float &position)
770{
771        int raysBack;
772        int raysFront;
773        int pvsBack;
774        int pvsFront;
775
776        SortSplitCandidates(rays, axis);
777
778        // go through the lists, count the number of objects left and right
779        // and evaluate the following cost funcion:
780        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
781
782        int rl = 0, rr = (int)rays.size();
783        int pl = 0, pr = pvsSize;
784
785        float minBox = box.Min(axis);
786        float maxBox = box.Max(axis);
787        float sizeBox = maxBox - minBox;
788
789        float minBand = minBox + 0.1f*(maxBox - minBox);
790        float maxBand = minBox + 0.9f*(maxBox - minBox);
791
792        float sum = rr*sizeBox;
793        float minSum = 1e20f;
794
795        Intersectable::NewMail();
796
797        // set all object as belonging to the fron pvs
798        for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ++ ri)
799        {
800                if ((*ri).mRay->IsActive())
801                {
802                        Intersectable *object = (*ri).mRay->mTerminationObject;
803
804                        if (object)
805                        {
806                                if (!object->Mailed())
807                                {
808                                        object->Mail();
809                                        object->mCounter = 1;
810                                }
811                                else
812                                        ++ object->mCounter;
813                        }
814                }
815        }
816
817        Intersectable::NewMail();
818
819        for (vector<SortableEntry>::const_iterator ci = mSplitCandidates->begin();
820                ci < mSplitCandidates->end(); ++ ci)
821        {
822                VssRay *ray;
823
824                switch ((*ci).type)
825                {
826                        case SortableEntry::ERayMin:
827                                {
828                                        ++ rl;
829                                        ray = (VssRay *) (*ci).ray;
830
831                                        Intersectable *object = ray->mTerminationObject;
832
833                                        if (object && !object->Mailed())
834                                        {
835                                                object->Mail();
836                                                ++ pl;
837                                        }
838                                        break;
839                                }
840                        case SortableEntry::ERayMax:
841                                {
842                                        -- rr;
843                                        ray = (VssRay *) (*ci).ray;
844
845                                        Intersectable *object = ray->mTerminationObject;
846
847                                        if (object)
848                                        {
849                                                if (-- object->mCounter == 0)
850                                                        -- pr;
851                                        }
852
853                                        break;
854                                }
855                }
856
857                // Note: sufficient to compare size of bounding boxes of front and back side?
858                if ((*ci).value > minBand && (*ci).value < maxBand)
859                {
860                        sum = pl*((*ci).value - minBox) + pr*(maxBox - (*ci).value);
861
862                        //  cout<<"pos="<<(*ci).value<<"\t q=("<<ql<<","<<qr<<")\t r=("<<rl<<","<<rr<<")"<<endl;
863                        // cout<<"cost= "<<sum<<endl;
864
865                        if (sum < minSum)
866                        {
867                                minSum = sum;
868                                position = (*ci).value;
869
870                                raysBack = rl;
871                                raysFront = rr;
872
873                                pvsBack = pl;
874                                pvsFront = pr;
875
876                        }
877                }
878        }
879
880        float oldCost = (float)pvsSize;
881        float newCost = mCtDivCi + minSum / sizeBox;
882        float ratio = newCost / oldCost;
883
884        //Debug << "costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
885        //     <<"\t q=(" << queriesBack << "," << queriesFront << ")\t r=(" << raysBack << "," << raysFront << ")" << endl;
886
887        return ratio;
888}
889
890
891float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
892                                                                                 const VspBspTraversalData &tData,
893                                                                                 int &axis,
894                                                                                 BspNodeGeometry **frontGeom,
895                                                                                 BspNodeGeometry **backGeom,
896                                                                                 float &pFront,
897                                                                                 float &pBack,
898                                                                                 const bool useKdSplit)
899{
900        const bool useCostHeuristics = false;
901
902        //-- regular split
903        float nPosition[3];
904        float nCostRatio[3];
905        float nProbFront[3];
906        float nProbBack[3];
907
908        BspNodeGeometry *nFrontGeom[3];
909        BspNodeGeometry *nBackGeom[3];
910
911        int bestAxis = -1;
912
913        // create bounding box of node geometry
914        AxisAlignedBox3 box;
915        box.Initialize();
916       
917        //TODO: for kd split geometry already is box => only take minmax vertices
918        if (1)
919        {
920                PolygonContainer::const_iterator it, it_end = tData.mGeometry->mPolys.end();
921
922                for(it = tData.mGeometry->mPolys.begin(); it < it_end; ++ it)
923                        box.Include(*(*it));
924        }
925        else
926        {
927                RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
928
929                for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
930                        box.Include((*ri).ExtrapTermination());
931        }
932
933        const int sAxis = box.Size().DrivingAxis();
934
935        for (axis = 0; axis < 3; ++ axis)
936        {
937                nFrontGeom[axis] = new BspNodeGeometry();
938                nBackGeom[axis] = new BspNodeGeometry();
939
940                if (!mOnlyDrivingAxis || (axis == sAxis))
941                {
942                        if (!useCostHeuristics)
943                        {
944                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
945                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
946
947                                // allows faster split because we have axis aligned kd tree boxes
948                                if (useKdSplit)
949                                {
950                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
951                                                                                                                                box,
952                                                                                                                                axis,
953                                                                                                                                nPosition[axis],
954                                                                                                                                nProbFront[axis],
955                                                                                                                                nProbBack[axis]);
956                                       
957                                        Vector3 pos;
958                                       
959                                        pos = box.Max(); pos[axis] = nPosition[axis];
960                                        AxisAlignedBox3 bBox(box.Min(), pos);
961                                        bBox.ExtractPolys(nBackGeom[axis]->mPolys);
962                                       
963                                        pos = box.Min(); pos[axis] = nPosition[axis];
964                                        AxisAlignedBox3 fBox(pos, box.Max());
965                                        fBox.ExtractPolys(nFrontGeom[axis]->mPolys);
966                                }
967                                else
968                                {
969                                        nCostRatio[axis] =
970                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
971                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
972                                                                                   nProbFront[axis], nProbBack[axis]);
973                                }
974                        }
975                        else
976                        {
977                                nCostRatio[axis] =
978                                        BestCostRatioHeuristics(*tData.mRays,
979                                                                                    box,
980                                                                                        tData.mPvs,
981                                                                                        axis,
982                                                                                        nPosition[axis]);
983                        }
984
985                        if (bestAxis == -1)
986                        {
987                                bestAxis = axis;
988                        }
989
990                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
991                        {
992                                bestAxis = axis;
993                        }
994
995                }
996        }
997
998        //-- assign values
999        axis = bestAxis;
1000        pFront = nProbFront[bestAxis];
1001        pBack = nProbBack[bestAxis];
1002
1003        // assign best split nodes geometry
1004        *frontGeom = nFrontGeom[bestAxis];
1005        *backGeom = nBackGeom[bestAxis];
1006
1007        // and delete other geometry
1008        delete nFrontGeom[(bestAxis + 1) % 3];
1009        delete nBackGeom[(bestAxis + 2) % 3];
1010
1011        //-- split plane
1012    Vector3 normal(0,0,0); normal[bestAxis] = 1;
1013        plane = Plane3(normal, nPosition[bestAxis]);
1014
1015        return nCostRatio[bestAxis];
1016}
1017
1018
1019bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1020                                                         BspLeaf *leaf,
1021                                                         VspBspTraversalData &data,
1022                                                         VspBspTraversalData &frontData,
1023                                                         VspBspTraversalData &backData)
1024{
1025        // simplest strategy: just take next polygon
1026        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1027        {
1028        if (!data.mPolygons->empty())
1029                {
1030                        const int randIdx =
1031                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1032                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
1033
1034                        bestPlane = nextPoly->GetSupportingPlane();
1035                        return true;
1036                }
1037        }
1038
1039        //-- use heuristics to find appropriate plane
1040
1041        // intermediate plane
1042        Plane3 plane;
1043        float lowestCost = MAX_FLOAT;
1044       
1045        // decides if the first few splits should be only axisAligned
1046        const bool onlyAxisAligned  =
1047                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1048                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1049                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1050       
1051        const int limit = onlyAxisAligned ? 0 :
1052                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1053
1054        float candidateCost;
1055
1056        int maxIdx = (int)data.mPolygons->size();
1057
1058        for (int i = 0; i < limit; ++ i)
1059        {
1060                // the already taken candidates are stored behind maxIdx
1061                // => assure that no index is taken twice
1062                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1063                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1064
1065                // swap candidate to the end to avoid testing same plane
1066                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1067                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1068
1069                // evaluate current candidate
1070                BspNodeGeometry fGeom, bGeom;
1071                float fArea, bArea;
1072                plane = poly->GetSupportingPlane();
1073                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
1074               
1075                if (candidateCost < lowestCost)
1076                {
1077                        bestPlane = plane;
1078                        lowestCost = candidateCost;
1079                }
1080        }
1081
1082        //-- evaluate axis aligned splits
1083        int axis;
1084        BspNodeGeometry *fGeom, *bGeom;
1085        float pFront, pBack;
1086
1087        candidateCost = SelectAxisAlignedPlane(plane, data, axis,
1088                                                                                   &fGeom, &bGeom,
1089                                                                                   pFront, pBack,
1090                                                                                   data.mIsKdNode);     
1091
1092        bool isAxisAlignedSplit = false;
1093
1094        if (candidateCost < lowestCost)
1095        {       
1096                bestPlane = plane;
1097                lowestCost = candidateCost;
1098
1099                // assign already computed values
1100                // we can do this because we always save the
1101                // computed values from the axis aligned splits         
1102                frontData.mGeometry = fGeom;
1103                backData.mGeometry = bGeom;
1104       
1105                frontData.mProbability = pFront;
1106                backData.mProbability = pBack;
1107               
1108                //! error also computed if cost ratio is missed
1109                ++ mBspStats.splits[axis];
1110                isAxisAlignedSplit = true;
1111        }
1112        else
1113        {
1114                DEL_PTR(fGeom);
1115                DEL_PTR(bGeom);
1116        }
1117
1118        frontData.mIsKdNode = backData.mIsKdNode = (data.mIsKdNode && isAxisAlignedSplit);
1119
1120#ifdef _DEBUG
1121        Debug << "plane lowest cost: " << lowestCost << endl;
1122#endif
1123
1124        // cost ratio miss
1125        if (lowestCost > mTermMaxCostRatio)
1126                return false;
1127
1128        return true;
1129}
1130
1131
1132Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
1133{
1134        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1135
1136        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1137        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1138
1139        const Vector3 pt = (maxPt + minPt) * 0.5;
1140        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1141
1142        return Plane3(normal, pt);
1143}
1144
1145
1146Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
1147{
1148        Vector3 pt[3];
1149
1150        int idx[3];
1151        int cmaxT = 0;
1152        int cminT = 0;
1153        bool chooseMin = false;
1154
1155        for (int j = 0; j < 3; ++ j)
1156        {
1157                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1158
1159                if (idx[j] >= (int)rays.size())
1160                {
1161                        idx[j] -= (int)rays.size();
1162
1163                        chooseMin = (cminT < 2);
1164                }
1165                else
1166                        chooseMin = (cmaxT < 2);
1167
1168                RayInfo rayInf = rays[idx[j]];
1169                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1170        }
1171
1172        return Plane3(pt[0], pt[1], pt[2]);
1173}
1174
1175
1176Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1177{
1178        Vector3 pt[3];
1179
1180        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1181        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1182
1183        // check if rays different
1184        if (idx1 == idx2)
1185                idx2 = (idx2 + 1) % (int)rays.size();
1186
1187        const RayInfo ray1 = rays[idx1];
1188        const RayInfo ray2 = rays[idx2];
1189
1190        // normal vector of the plane parallel to both lines
1191        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1192
1193        // vector from line 1 to line 2
1194        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1195
1196        // project vector on normal to get distance
1197        const float dist = DotProd(vd, norm);
1198
1199        // point on plane lies halfway between the two planes
1200        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1201
1202        return Plane3(norm, planePt);
1203}
1204
1205
1206inline void VspBspTree::GenerateUniqueIdsForPvs()
1207{
1208        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1209        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1210        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
1211}
1212
1213
1214float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1215                                                                         const VspBspTraversalData &data,
1216                                                                         BspNodeGeometry &geomFront,
1217                                                                         BspNodeGeometry &geomBack,
1218                                                                         float &pFront,
1219                                                                         float &pBack) const
1220{
1221        float cost = 0;
1222
1223        float sumBalancedRays = 0;
1224        float sumRaySplits = 0;
1225
1226        int pvsFront = 0;
1227        int pvsBack = 0;
1228
1229        // probability that view point lies in back / front node
1230        float pOverall = 0;
1231        pFront = 0;
1232        pBack = 0;
1233
1234        int raysFront = 0;
1235        int raysBack = 0;
1236        int totalPvs = 0;
1237
1238        int limit;
1239        bool useRand;
1240
1241        // choose test rays randomly if too much
1242        if ((int)data.mRays->size() > mMaxTests)
1243        {
1244                useRand = true;
1245                limit = mMaxTests;
1246        }
1247        else
1248        {
1249                useRand = false;
1250                limit = (int)data.mRays->size();
1251        }
1252       
1253        for (int i = 0; i < limit; ++ i)
1254        {
1255                const int testIdx = useRand ?
1256                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
1257                RayInfo rayInf = (*data.mRays)[testIdx];
1258
1259                float t;
1260                VssRay *ray = rayInf.mRay;
1261                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1262
1263        if (0)
1264                {
1265                        if (cf >= 0)
1266                                ++ raysFront;
1267                        if (cf <= 0)
1268                                ++ raysBack;
1269                }
1270
1271                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1272                {
1273                        sumBalancedRays += cf;
1274                }
1275
1276                if (mSplitPlaneStrategy & BALANCED_RAYS)
1277                {
1278                        if (cf == 0)
1279                                ++ sumRaySplits;
1280                }
1281
1282                if (mSplitPlaneStrategy & PVS)
1283                {
1284                        // find front and back pvs for origing and termination object
1285                        AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1286                        AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1287                }
1288        }
1289
1290        const float raysSize = (float)data.mRays->size() + Limits::Small;
1291
1292        if (mSplitPlaneStrategy & PVS)
1293        {
1294                // create unique ids for pvs heuristics
1295                GenerateUniqueIdsForPvs();
1296
1297                // construct child geometry with regard to the candidate split plane
1298                data.mGeometry->SplitGeometry(geomFront,
1299                                                                          geomBack,
1300                                                                          candidatePlane,
1301                                                                          mBox,
1302                                                                          mEpsilon);
1303
1304                pOverall = data.mProbability;
1305
1306                if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1307                {
1308                        pFront = geomFront.GetVolume();
1309                        pBack = pOverall - geomFront.GetVolume();
1310                }
1311                else
1312                {
1313                        pFront = geomFront.GetArea();
1314                        pBack = geomBack.GetArea();
1315                }
1316        }
1317
1318
1319        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1320                cost += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1321
1322        if (mSplitPlaneStrategy & BALANCED_RAYS)
1323                cost += mBalancedRaysFactor * fabs(sumBalancedRays) / raysSize;
1324
1325        // -- pvs rendering heuristics
1326        if (mSplitPlaneStrategy & PVS)
1327        {
1328                const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1329                const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1330
1331                // only render cost heuristics or combined with standard deviation
1332                if (1)
1333                {
1334                        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1335                const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1336                        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1337                       
1338                        const float oldRenderCost = pOverall * (float)penaltyOld + Limits::Small;
1339                        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1340
1341                        float oldCost, newCost;
1342
1343                        if (1)
1344                        {
1345                                oldCost = oldRenderCost;
1346                                newCost = newRenderCost;
1347                        }
1348                        else
1349                        {
1350                                // standard deviation is difference of back and front pvs
1351                                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
1352
1353                                const float newDeviation = 0.5f *
1354                                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
1355
1356                const float oldDeviation = penaltyOld + Limits::Small;
1357
1358                                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
1359                                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
1360                        }
1361
1362                        cost += mPvsFactor * newCost / oldCost;
1363                }
1364                else
1365                {
1366                        //-- compute weighted sum of expected render cost and standard deviation
1367                       
1368                        //-- first compute expected render cost         
1369                        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1370                const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1371                        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1372                       
1373                        const float renderCostFront = penaltyFront * pFront;
1374                        const float renderCostBack = penaltyBack * pBack;
1375
1376                        const float oldRenderCost = pOverall * (float)penaltyOld + Limits::Small;
1377                        const float newRenderCost = renderCostFront + renderCostBack;
1378
1379
1380                        //-- compute standard deviation
1381                        const float expectedCost = 0.5f * (renderCostBack + renderCostFront);
1382
1383                        const float devFront = fabs(renderCostFront - expectedCost);
1384                       
1385                        const float devBack = fabs(renderCostBack - expectedCost);
1386
1387                        const float newDev = 0.5f * (devFront + devBack);
1388                        const float oldDev = oldRenderCost * oldRenderCost;
1389
1390                        const float newCost = newRenderCost * mRenderCostWeight + newDev * (1.0f - mRenderCostWeight);
1391                        const float oldCost = oldRenderCost * mRenderCostWeight + oldDev * (1.0f - mRenderCostWeight);
1392
1393                        cost += mPvsFactor * newCost / oldCost;
1394
1395                        // also try to equalize render differences between front and back pvs
1396                        //const float oldCost = pOverall + Limits::Small;
1397                        //float newCost = (float)abs(pvsFront - pvsBack);
1398                       
1399                }
1400        }
1401
1402#ifdef _DEBUG
1403        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
1404                  << " frontpvs: " << pvsFront << " pFront: " << pFront
1405                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
1406#endif
1407
1408        // normalize cost by sum of linear factors
1409        if(0)
1410                return cost / (float)mCostNormalizer;
1411        else
1412                return cost;
1413}
1414
1415
1416float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
1417                                                                                   const AxisAlignedBox3 &box,
1418                                                                                   const int axis,
1419                                                                                   const float &position,                                                                                 
1420                                                                                   float &pFront,
1421                                                                                   float &pBack) const
1422{
1423        int pvsTotal = 0;
1424        int pvsFront = 0;
1425        int pvsBack = 0;
1426       
1427        // create unique ids for pvs heuristics
1428        GenerateUniqueIdsForPvs();
1429
1430        const int pvsSize = data.mPvs;
1431
1432        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1433
1434        // this is the main ray classification loop!
1435        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
1436        {
1437                //if (!(*rit).mRay->IsActive()) continue;
1438
1439                // determine the side of this ray with respect to the plane
1440                float t;
1441                const int side = (*rit).ComputeRayIntersection(axis, position, t);
1442       
1443                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
1444                AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
1445        }
1446
1447        //-- pvs heuristics
1448        float pOverall;
1449
1450        //-- compute heurstics
1451        //   we take simplified computation for mid split
1452               
1453        pOverall = data.mProbability;
1454
1455        if (!mUseAreaForPvs)
1456        {   // volume
1457                pBack = pFront = pOverall * 0.5f;
1458               
1459#if 0
1460                // box length substitute for probability
1461                const float minBox = box.Min(axis);
1462                const float maxBox = box.Max(axis);
1463
1464                pBack = position - minBox;
1465                pFront = maxBox - position;
1466                pOverall = maxBox - minBox;
1467#endif
1468        }
1469        else //-- area substitute for probability
1470        {
1471                const int axis2 = (axis + 1) % 3;
1472                const int axis3 = (axis + 2) % 3;
1473
1474                const float faceArea =
1475                        (box.Max(axis2) - box.Min(axis2)) *
1476                        (box.Max(axis3) - box.Min(axis3));
1477
1478                pBack = pFront = pOverall * 0.5f + faceArea;
1479        }
1480
1481#ifdef _DEBUG
1482        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
1483        Debug << pFront << " " << pBack << " " << pOverall << endl;
1484#endif
1485
1486       
1487        const float newCost = pvsBack * pBack + pvsFront * pFront;
1488        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
1489
1490        return  (mCtDivCi + newCost) / oldCost;
1491}
1492
1493
1494void VspBspTree::AddObjToPvs(Intersectable *obj,
1495                                                         const int cf,
1496                                                         int &frontPvs,
1497                                                         int &backPvs,
1498                                                         int &totalPvs) const
1499{
1500        if (!obj)
1501                return;
1502       
1503        if ((obj->mMailbox != sFrontId) &&
1504                (obj->mMailbox != sBackId) &&
1505                (obj->mMailbox != sFrontAndBackId))
1506        {
1507                ++ totalPvs;
1508        }
1509
1510        // TODO: does this really belong to no pvs?
1511        //if (cf == Ray::COINCIDENT) return;
1512
1513        // object belongs to both PVS
1514        if (cf >= 0)
1515        {
1516                if ((obj->mMailbox != sFrontId) &&
1517                        (obj->mMailbox != sFrontAndBackId))
1518                {
1519                        ++ frontPvs;
1520               
1521                        if (obj->mMailbox == sBackId)
1522                                obj->mMailbox = sFrontAndBackId;
1523                        else
1524                                obj->mMailbox = sFrontId;
1525                }
1526        }
1527
1528        if (cf <= 0)
1529        {
1530                if ((obj->mMailbox != sBackId) &&
1531                        (obj->mMailbox != sFrontAndBackId))
1532                {
1533                        ++ backPvs;
1534               
1535                        if (obj->mMailbox == sFrontId)
1536                                obj->mMailbox = sFrontAndBackId;
1537                        else
1538                                obj->mMailbox = sBackId;
1539                }
1540        }
1541}
1542
1543
1544void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
1545                                                           const bool onlyUnmailed,
1546                                                           const int maxPvsSize) const
1547{
1548        stack<BspNode *> nodeStack;
1549        nodeStack.push(mRoot);
1550
1551        while (!nodeStack.empty())
1552        {
1553                BspNode *node = nodeStack.top();
1554                nodeStack.pop();
1555               
1556                if (node->IsLeaf())
1557                {
1558                        // test if this leaf is in valid view space
1559                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1560                        if (leaf->TreeValid() &&
1561                                (!onlyUnmailed || !leaf->Mailed()) &&
1562                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
1563                        {
1564                                leaves.push_back(leaf);
1565                        }
1566                }
1567                else
1568                {
1569                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1570
1571                        nodeStack.push(interior->GetBack());
1572                        nodeStack.push(interior->GetFront());
1573                }
1574        }
1575}
1576
1577
1578AxisAlignedBox3 VspBspTree::GetBoundingBox() const
1579{
1580        return mBox;
1581}
1582
1583
1584BspNode *VspBspTree::GetRoot() const
1585{
1586        return mRoot;
1587}
1588
1589
1590void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
1591{
1592        // the node became a leaf -> evaluate stats for leafs
1593        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1594
1595        // store maximal and minimal depth
1596        if (data.mDepth > mBspStats.maxDepth)
1597                mBspStats.maxDepth = data.mDepth;
1598
1599        if (data.mPvs > mBspStats.maxPvs)
1600                mBspStats.maxPvs = data.mPvs;
1601       
1602        if (data.mDepth < mBspStats.minDepth)
1603                mBspStats.minDepth = data.mDepth;
1604
1605        if (data.mDepth >= mTermMaxDepth)
1606                ++ mBspStats.maxDepthNodes;
1607        // accumulate rays to compute rays /  leaf
1608        mBspStats.accumRays += (int)data.mRays->size();
1609
1610        if (data.mPvs < mTermMinPvs)
1611                ++ mBspStats.minPvsNodes;
1612
1613        if ((int)data.mRays->size() < mTermMinRays)
1614                ++ mBspStats.minRaysNodes;
1615
1616        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1617                ++ mBspStats.maxRayContribNodes;
1618
1619        if (data.mProbability <= mTermMinProbability)
1620                ++ mBspStats.minProbabilityNodes;
1621       
1622        // accumulate depth to compute average depth
1623        mBspStats.accumDepth += data.mDepth;
1624
1625#ifdef _DEBUG
1626        Debug << "BSP stats: "
1627                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1628                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1629          //              << "Area: " << data.mProbability << " (min: " << mTermMinProbability << "), "
1630                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1631                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1632                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1633#endif
1634}
1635
1636int VspBspTree::CastRay(Ray &ray)
1637{
1638        int hits = 0;
1639
1640        stack<BspRayTraversalData> tStack;
1641
1642        float maxt, mint;
1643
1644        if (!mBox.GetRaySegment(ray, mint, maxt))
1645                return 0;
1646
1647        Intersectable::NewMail();
1648
1649        Vector3 entp = ray.Extrap(mint);
1650        Vector3 extp = ray.Extrap(maxt);
1651
1652        BspNode *node = mRoot;
1653        BspNode *farChild = NULL;
1654
1655        while (1)
1656        {
1657                if (!node->IsLeaf())
1658                {
1659                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1660
1661                        Plane3 splitPlane = in->GetPlane();
1662                        const int entSide = splitPlane.Side(entp);
1663                        const int extSide = splitPlane.Side(extp);
1664
1665                        if (entSide < 0)
1666                        {
1667                                node = in->GetBack();
1668
1669                                if(extSide <= 0) // plane does not split ray => no far child
1670                                        continue;
1671
1672                                farChild = in->GetFront(); // plane splits ray
1673
1674                        } else if (entSide > 0)
1675                        {
1676                                node = in->GetFront();
1677
1678                                if (extSide >= 0) // plane does not split ray => no far child
1679                                        continue;
1680
1681                                farChild = in->GetBack(); // plane splits ray
1682                        }
1683                        else // ray and plane are coincident
1684                        {
1685                                // WHAT TO DO IN THIS CASE ?
1686                                //break;
1687                                node = in->GetFront();
1688                                continue;
1689                        }
1690
1691                        // push data for far child
1692                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
1693
1694                        // find intersection of ray segment with plane
1695                        float t;
1696                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
1697                        maxt *= t;
1698
1699                } else // reached leaf => intersection with view cell
1700                {
1701                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1702
1703                        if (!leaf->GetViewCell()->Mailed())
1704                        {
1705                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
1706                                leaf->GetViewCell()->Mail();
1707                                ++ hits;
1708                        }
1709
1710                        //-- fetch the next far child from the stack
1711                        if (tStack.empty())
1712                                break;
1713
1714                        entp = extp;
1715                        mint = maxt; // NOTE: need this?
1716
1717                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1718                                break;
1719
1720                        BspRayTraversalData &s = tStack.top();
1721
1722                        node = s.mNode;
1723                        extp = s.mExitPoint;
1724                        maxt = s.mMaxT;
1725
1726                        tStack.pop();
1727                }
1728        }
1729
1730        return hits;
1731}
1732
1733
1734void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
1735{
1736        ViewCell::NewMail();
1737       
1738        CollectViewCells(mRoot, onlyValid, viewCells, true);
1739}
1740
1741
1742void VspBspTree::CollapseViewCells()
1743{
1744// TODO
1745#if VC_HISTORY
1746        stack<BspNode *> nodeStack;
1747
1748        if (!mRoot)
1749                return;
1750
1751        nodeStack.push(mRoot);
1752       
1753        while (!nodeStack.empty())
1754        {
1755                BspNode *node = nodeStack.top();
1756                nodeStack.pop();
1757               
1758                if (node->IsLeaf())
1759        {
1760                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1761
1762                        if (!viewCell->GetValid())
1763                        {
1764                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1765       
1766                                ViewCellContainer leaves;
1767                                mViewCellsTree->CollectLeaves(viewCell, leaves);
1768
1769                                ViewCellContainer::const_iterator it, it_end = leaves.end();
1770
1771                                for (it = leaves.begin(); it != it_end; ++ it)
1772                                {
1773                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
1774                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
1775                                        ++ mBspStats.invalidLeaves;
1776                                }
1777
1778                                // add to unbounded view cell
1779                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
1780                                DEL_PTR(viewCell);
1781                        }
1782                }
1783                else
1784                {
1785                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1786               
1787                        nodeStack.push(interior->GetFront());
1788                        nodeStack.push(interior->GetBack());
1789                }
1790        }
1791
1792        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
1793#endif
1794}
1795
1796
1797void VspBspTree::ValidateTree()
1798{
1799        stack<BspNode *> nodeStack;
1800
1801        if (!mRoot)
1802                return;
1803
1804        nodeStack.push(mRoot);
1805       
1806        mBspStats.invalidLeaves = 0;
1807        while (!nodeStack.empty())
1808        {
1809                BspNode *node = nodeStack.top();
1810                nodeStack.pop();
1811               
1812                if (node->IsLeaf())
1813                {
1814                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1815
1816                        if (!leaf->GetViewCell()->GetValid())
1817                                ++ mBspStats.invalidLeaves;
1818
1819                        // validity flags don't match => repair
1820                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
1821                        {
1822                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
1823                                PropagateUpValidity(leaf);
1824                        }
1825                }
1826                else
1827                {
1828                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1829               
1830                        nodeStack.push(interior->GetFront());
1831                        nodeStack.push(interior->GetBack());
1832                }
1833        }
1834
1835        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
1836}
1837
1838
1839
1840void VspBspTree::CollectViewCells(BspNode *root,
1841                                                                  bool onlyValid,
1842                                                                  ViewCellContainer &viewCells,
1843                                                                  bool onlyUnmailed) const
1844{
1845        stack<BspNode *> nodeStack;
1846
1847        if (!root)
1848                return;
1849
1850        nodeStack.push(root);
1851       
1852        while (!nodeStack.empty())
1853        {
1854                BspNode *node = nodeStack.top();
1855                nodeStack.pop();
1856               
1857                if (node->IsLeaf())
1858                {
1859                        if (!onlyValid || node->TreeValid())
1860                        {
1861                                ViewCell *viewCell =
1862                                        mViewCellsTree->GetActiveViewCell(dynamic_cast<BspLeaf *>(node)->GetViewCell());
1863                                               
1864                                if (!onlyUnmailed || !viewCell->Mailed())
1865                                {
1866                                        viewCell->Mail();
1867                                        viewCells.push_back(viewCell);
1868                                }
1869                        }
1870                }
1871                else
1872                {
1873                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1874               
1875                        nodeStack.push(interior->GetFront());
1876                        nodeStack.push(interior->GetBack());
1877                }
1878        }
1879
1880}
1881
1882
1883float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
1884{
1885        float len = 0;
1886
1887        RayInfoContainer::const_iterator it, it_end = rays.end();
1888
1889        for (it = rays.begin(); it != it_end; ++ it)
1890                len += (*it).SegmentLength();
1891
1892        return len;
1893}
1894
1895
1896int VspBspTree::SplitRays(const Plane3 &plane,
1897                                                  RayInfoContainer &rays,
1898                                                  RayInfoContainer &frontRays,
1899                                                  RayInfoContainer &backRays)
1900{
1901        int splits = 0;
1902
1903        RayInfoContainer::const_iterator it, it_end = rays.end();
1904
1905        for (it = rays.begin(); it != it_end; ++ it)
1906        {
1907                RayInfo bRay = *it;
1908               
1909                VssRay *ray = bRay.mRay;
1910                float t;
1911
1912                // get classification and receive new t
1913                const int cf = bRay.ComputeRayIntersection(plane, t);
1914
1915                switch (cf)
1916                {
1917                case -1:
1918                        backRays.push_back(bRay);
1919                        break;
1920                case 1:
1921                        frontRays.push_back(bRay);
1922                        break;
1923                case 0:
1924                        {
1925                                //-- split ray
1926                                //-- test if start point behind or in front of plane
1927                                const int side = plane.Side(bRay.ExtrapOrigin());
1928
1929                                if (side <= 0)
1930                                {
1931                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1932                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1933                                }
1934                                else
1935                                {
1936                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1937                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1938                                }
1939                        }
1940                        break;
1941                default:
1942                        Debug << "Should not come here" << endl;
1943                        break;
1944                }
1945        }
1946
1947        return splits;
1948}
1949
1950
1951void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
1952{
1953        BspNode *lastNode;
1954
1955        do
1956        {
1957                lastNode = n;
1958
1959                // want to get planes defining geometry of this node => don't take
1960                // split plane of node itself
1961                n = n->GetParent();
1962
1963                if (n)
1964                {
1965                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
1966                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
1967
1968            if (interior->GetFront() != lastNode)
1969                                halfSpace.ReverseOrientation();
1970
1971                        halfSpaces.push_back(halfSpace);
1972                }
1973        }
1974        while (n);
1975}
1976
1977
1978void VspBspTree::ConstructGeometry(BspNode *n,
1979                                                                   BspNodeGeometry &geom) const
1980{
1981        vector<Plane3> halfSpaces;
1982        ExtractHalfSpaces(n, halfSpaces);
1983
1984        PolygonContainer candidatePolys;
1985
1986        // bounded planes are added to the polygons (reverse polygons
1987        // as they have to be outfacing
1988        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
1989        {
1990                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
1991
1992                if (p->Valid(mEpsilon))
1993                {
1994                        candidatePolys.push_back(p->CreateReversePolygon());
1995                        DEL_PTR(p);
1996                }
1997        }
1998
1999        // add faces of bounding box (also could be faces of the cell)
2000        for (int i = 0; i < 6; ++ i)
2001        {
2002                VertexContainer vertices;
2003
2004                for (int j = 0; j < 4; ++ j)
2005                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2006
2007                candidatePolys.push_back(new Polygon3(vertices));
2008        }
2009
2010        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2011        {
2012                // polygon is split by all other planes
2013                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2014                {
2015                        if (i == j) // polygon and plane are coincident
2016                                continue;
2017
2018                        VertexContainer splitPts;
2019                        Polygon3 *frontPoly, *backPoly;
2020
2021                        const int cf =
2022                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2023                                                                                                 mEpsilon);
2024
2025                        switch (cf)
2026                        {
2027                                case Polygon3::SPLIT:
2028                                        frontPoly = new Polygon3();
2029                                        backPoly = new Polygon3();
2030
2031                                        candidatePolys[i]->Split(halfSpaces[j],
2032                                                                                         *frontPoly,
2033                                                                                         *backPoly,
2034                                                                                         mEpsilon);
2035
2036                                        DEL_PTR(candidatePolys[i]);
2037
2038                                        if (frontPoly->Valid(mEpsilon))
2039                                                candidatePolys[i] = frontPoly;
2040                                        else
2041                                                DEL_PTR(frontPoly);
2042
2043                                        DEL_PTR(backPoly);
2044                                        break;
2045                                case Polygon3::BACK_SIDE:
2046                                        DEL_PTR(candidatePolys[i]);
2047                                        break;
2048                                // just take polygon as it is
2049                                case Polygon3::FRONT_SIDE:
2050                                case Polygon3::COINCIDENT:
2051                                default:
2052                                        break;
2053                        }
2054                }
2055
2056                if (candidatePolys[i])
2057                        geom.mPolys.push_back(candidatePolys[i]);
2058        }
2059}
2060
2061
2062void VspBspTree::ConstructGeometry(ViewCell *vc,
2063                                                                   BspNodeGeometry &vcGeom) const
2064{
2065        ViewCellContainer leaves;
2066       
2067        mViewCellsTree->CollectLeaves(vc, leaves);
2068
2069        ViewCellContainer::const_iterator it, it_end = leaves.end();
2070
2071        for (it = leaves.begin(); it != it_end; ++ it)
2072        {
2073                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2074               
2075                ConstructGeometry(l, vcGeom);
2076        }
2077}
2078
2079
2080typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2081
2082
2083int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2084                                                          const bool onlyUnmailed) const
2085{
2086        stack<bspNodePair> nodeStack;
2087       
2088        BspNodeGeometry nodeGeom;
2089        ConstructGeometry(n, nodeGeom);
2090       
2091        // split planes from the root to this node
2092        // needed to verify that we found neighbor leaf
2093        // TODO: really needed?
2094        vector<Plane3> halfSpaces;
2095        ExtractHalfSpaces(n, halfSpaces);
2096
2097
2098        BspNodeGeometry *rgeom = new BspNodeGeometry();
2099        ConstructGeometry(mRoot, *rgeom);
2100
2101        nodeStack.push(bspNodePair(mRoot, rgeom));
2102
2103        while (!nodeStack.empty())
2104        {
2105                BspNode *node = nodeStack.top().first;
2106                BspNodeGeometry *geom = nodeStack.top().second;
2107       
2108                nodeStack.pop();
2109
2110                if (node->IsLeaf())
2111                {
2112                        // test if this leaf is in valid view space
2113                        if (node->TreeValid() &&
2114                                (node != n) &&
2115                                (!onlyUnmailed || !node->Mailed()))
2116                        {
2117                                bool isAdjacent = true;
2118
2119                                if (1)
2120                                {
2121                                        // test all planes of current node if still adjacent
2122                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2123                                        {
2124                                                const int cf =
2125                                                        Polygon3::ClassifyPlane(geom->mPolys,
2126                                                                                                        halfSpaces[i],
2127                                                                                                        mEpsilon);
2128
2129                                                if (cf == Polygon3::BACK_SIDE)
2130                                                {
2131                                                        isAdjacent = false;
2132                                                }
2133                                        }
2134                                }
2135                                else
2136                                {
2137                                        // TODO: why is this wrong??
2138                                        // test all planes of current node if still adjacent
2139                                        for (int i = 0; (i < (int)nodeGeom.mPolys.size()) && isAdjacent; ++ i)
2140                                        {
2141                                                Polygon3 *poly = nodeGeom.mPolys[i];
2142
2143                                                const int cf =
2144                                                        Polygon3::ClassifyPlane(geom->mPolys,
2145                                                                                                        poly->GetSupportingPlane(),
2146                                                                                                        mEpsilon);
2147
2148                                                if (cf == Polygon3::BACK_SIDE)
2149                                                {
2150                                                        isAdjacent = false;
2151                                                }
2152                                        }
2153                                }
2154                                // neighbor was found
2155                                if (isAdjacent)
2156                                {       
2157                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2158                                }
2159                        }
2160                }
2161                else
2162                {
2163                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2164
2165                        const int cf = Polygon3::ClassifyPlane(nodeGeom.mPolys,
2166                                                                                                   interior->GetPlane(),
2167                                                                                                   mEpsilon);
2168                       
2169                        BspNode *front = interior->GetFront();
2170                        BspNode *back = interior->GetBack();
2171           
2172                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2173                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2174
2175                        geom->SplitGeometry(*fGeom,
2176                                                                *bGeom,
2177                                                                interior->GetPlane(),
2178                                                                mBox,
2179                                                                mEpsilon);
2180               
2181                        if (cf == Polygon3::FRONT_SIDE)
2182                        {
2183                                nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2184                                DEL_PTR(bGeom);
2185                        }
2186                        else
2187                        {
2188                                if (cf == Polygon3::BACK_SIDE)
2189                                {
2190                                        nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2191                                        DEL_PTR(fGeom);
2192                                }
2193                                else
2194                                {       // random decision
2195                                        nodeStack.push(bspNodePair(front, fGeom));
2196                                        nodeStack.push(bspNodePair(back, bGeom));
2197                                }
2198                        }
2199                }
2200       
2201                DEL_PTR(geom);
2202        }
2203
2204        return (int)neighbors.size();
2205}
2206
2207
2208BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
2209{
2210    stack<BspNode *> nodeStack;
2211        nodeStack.push(mRoot);
2212
2213        int mask = rand();
2214
2215        while (!nodeStack.empty())
2216        {
2217                BspNode *node = nodeStack.top();
2218                nodeStack.pop();
2219
2220                if (node->IsLeaf())
2221                {
2222                        return dynamic_cast<BspLeaf *>(node);
2223                }
2224                else
2225                {
2226                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2227                        BspNode *next;
2228                        BspNodeGeometry geom;
2229
2230                        // todo: not very efficient: constructs full cell everytime
2231                        ConstructGeometry(interior, geom);
2232
2233                        const int cf =
2234                                Polygon3::ClassifyPlane(geom.mPolys, halfspace, mEpsilon);
2235
2236                        if (cf == Polygon3::BACK_SIDE)
2237                                next = interior->GetFront();
2238                        else
2239                                if (cf == Polygon3::FRONT_SIDE)
2240                                        next = interior->GetFront();
2241                        else
2242                        {
2243                                // random decision
2244                                if (mask & 1)
2245                                        next = interior->GetBack();
2246                                else
2247                                        next = interior->GetFront();
2248                                mask = mask >> 1;
2249                        }
2250
2251                        nodeStack.push(next);
2252                }
2253        }
2254
2255        return NULL;
2256}
2257
2258BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
2259{
2260        stack<BspNode *> nodeStack;
2261
2262        nodeStack.push(mRoot);
2263
2264        int mask = rand();
2265
2266        while (!nodeStack.empty())
2267        {
2268                BspNode *node = nodeStack.top();
2269                nodeStack.pop();
2270
2271                if (node->IsLeaf())
2272                {
2273                        if ( (!onlyUnmailed || !node->Mailed()) )
2274                                return dynamic_cast<BspLeaf *>(node);
2275                }
2276                else
2277                {
2278                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2279
2280                        // random decision
2281                        if (mask & 1)
2282                                nodeStack.push(interior->GetBack());
2283                        else
2284                                nodeStack.push(interior->GetFront());
2285
2286                        mask = mask >> 1;
2287                }
2288        }
2289
2290        return NULL;
2291}
2292
2293int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
2294{
2295        int pvsSize = 0;
2296
2297        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2298
2299        Intersectable::NewMail();
2300
2301        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2302        {
2303                VssRay *ray = (*rit).mRay;
2304
2305                if (ray->mOriginObject)
2306                {
2307                        if (!ray->mOriginObject->Mailed())
2308                        {
2309                                ray->mOriginObject->Mail();
2310                                ++ pvsSize;
2311                        }
2312                }
2313                if (ray->mTerminationObject)
2314                {
2315                        if (!ray->mTerminationObject->Mailed())
2316                        {
2317                                ray->mTerminationObject->Mail();
2318                                ++ pvsSize;
2319                        }
2320                }
2321        }
2322
2323        return pvsSize;
2324}
2325
2326float VspBspTree::GetEpsilon() const
2327{
2328        return mEpsilon;
2329}
2330
2331
2332int VspBspTree::SplitPolygons(const Plane3 &plane,
2333                                                          PolygonContainer &polys,
2334                                                          PolygonContainer &frontPolys,
2335                                                          PolygonContainer &backPolys,
2336                                                          PolygonContainer &coincident) const
2337{
2338        int splits = 0;
2339
2340        PolygonContainer::const_iterator it, it_end = polys.end();
2341
2342        for (it = polys.begin(); it != polys.end(); ++ it)     
2343        {
2344                Polygon3 *poly = *it;
2345
2346                // classify polygon
2347                const int cf = poly->ClassifyPlane(plane, mEpsilon);
2348
2349                switch (cf)
2350                {
2351                        case Polygon3::COINCIDENT:
2352                                coincident.push_back(poly);
2353                                break;
2354                        case Polygon3::FRONT_SIDE:
2355                                frontPolys.push_back(poly);
2356                                break;
2357                        case Polygon3::BACK_SIDE:
2358                                backPolys.push_back(poly);
2359                                break;
2360                        case Polygon3::SPLIT:
2361                                backPolys.push_back(poly);
2362                                frontPolys.push_back(poly);
2363                                ++ splits;
2364                                break;
2365                        default:
2366                Debug << "SHOULD NEVER COME HERE\n";
2367                                break;
2368                }
2369        }
2370
2371        return splits;
2372}
2373
2374
2375int VspBspTree::CastLineSegment(const Vector3 &origin,
2376                                                                const Vector3 &termination,
2377                                                                vector<ViewCell *> &viewcells)
2378{
2379        int hits = 0;
2380        stack<BspRayTraversalData> tStack;
2381
2382        float mint = 0.0f, maxt = 1.0f;
2383
2384        Intersectable::NewMail();
2385
2386        Vector3 entp = origin;
2387        Vector3 extp = termination;
2388
2389        BspNode *node = mRoot;
2390        BspNode *farChild = NULL;
2391
2392        float t;
2393        while (1)
2394        {
2395                if (!node->IsLeaf())
2396                {
2397                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2398
2399                        Plane3 splitPlane = in->GetPlane();
2400                       
2401                        const int entSide = splitPlane.Side(entp);
2402                        const int extSide = splitPlane.Side(extp);
2403
2404                        if (entSide < 0)
2405                        {
2406                          node = in->GetBack();
2407                          // plane does not split ray => no far child
2408                          if (extSide <= 0)
2409                                continue;
2410                         
2411                          farChild = in->GetFront(); // plane splits ray
2412                        }
2413                        else if (entSide > 0)
2414                        {
2415                          node = in->GetFront();
2416
2417                          if (extSide >= 0) // plane does not split ray => no far child
2418                                continue;
2419
2420                                farChild = in->GetBack(); // plane splits ray
2421                        }
2422                        else // ray end point on plane
2423                        {       // NOTE: what to do if ray is coincident with plane?
2424                                if (extSide < 0)
2425                                        node = in->GetBack();
2426                                else
2427                                        node = in->GetFront();
2428                                                               
2429                                continue; // no far child
2430                        }
2431
2432                        // push data for far child
2433                        tStack.push(BspRayTraversalData(farChild, extp));
2434
2435                        // find intersection of ray segment with plane
2436                        extp = splitPlane.FindIntersection(origin, extp, &t);
2437                }
2438                else
2439                {
2440                        // reached leaf => intersection with view cell
2441                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2442
2443                        ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2444                        if (!viewCell->Mailed())
2445                        {
2446                                viewcells.push_back(viewCell);
2447                                viewCell->Mail();
2448                                ++ hits;
2449                        }
2450
2451                        //-- fetch the next far child from the stack
2452                        if (tStack.empty())
2453                                break;
2454
2455                        entp = extp;
2456                       
2457                        BspRayTraversalData &s = tStack.top();
2458
2459                        node = s.mNode;
2460                        extp = s.mExitPoint;
2461
2462                        tStack.pop();
2463                }
2464        }
2465
2466        return hits;
2467}
2468
2469
2470
2471
2472int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
2473{
2474        std::deque<BspNode *> path1;
2475        BspNode *p1 = n1;
2476
2477        // create path from node 1 to root
2478        while (p1)
2479        {
2480                if (p1 == n2) // second node on path
2481                        return (int)path1.size();
2482
2483                path1.push_front(p1);
2484                p1 = p1->GetParent();
2485        }
2486
2487        int depth = n2->GetDepth();
2488        int d = depth;
2489
2490        BspNode *p2 = n2;
2491
2492        // compare with same depth
2493        while (1)
2494        {
2495                if ((d < (int)path1.size()) && (p2 == path1[d]))
2496                        return (depth - d) + ((int)path1.size() - 1 - d);
2497
2498                -- d;
2499                p2 = p2->GetParent();
2500        }
2501
2502        return 0; // never come here
2503}
2504
2505
2506BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
2507{
2508// TODO
2509#if VC_HISTORY
2510        if (node->IsLeaf())
2511                return node;
2512
2513        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2514
2515        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
2516        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
2517
2518        if (front->IsLeaf() && back->IsLeaf())
2519        {
2520                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
2521                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
2522
2523                //-- collapse tree
2524                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
2525                {
2526                        BspViewCell *vc = frontLeaf->GetViewCell();
2527
2528                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
2529                        leaf->SetTreeValid(frontLeaf->TreeValid());
2530
2531                        // replace a link from node's parent
2532                        if (leaf->GetParent())
2533                                leaf->GetParent()->ReplaceChildLink(node, leaf);
2534                        else
2535                                mRoot = leaf;
2536
2537                        ++ collapsed;
2538                        delete interior;
2539
2540                        return leaf;
2541                }
2542        }
2543#endif
2544        return node;
2545}
2546
2547
2548int VspBspTree::CollapseTree()
2549{
2550        int collapsed = 0;
2551        //TODO
2552#if VC_HISTORY
2553        (void)CollapseTree(mRoot, collapsed);
2554
2555        // revalidate leaves
2556        RepairViewCellsLeafLists();
2557#endif
2558        return collapsed;
2559}
2560
2561
2562void VspBspTree::RepairViewCellsLeafLists()
2563{
2564// TODO
2565#if VC_HISTORY
2566        // list not valid anymore => clear
2567        stack<BspNode *> nodeStack;
2568        nodeStack.push(mRoot);
2569
2570        ViewCell::NewMail();
2571
2572        while (!nodeStack.empty())
2573        {
2574                BspNode *node = nodeStack.top();
2575                nodeStack.pop();
2576
2577                if (node->IsLeaf())
2578                {
2579                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2580
2581                        BspViewCell *viewCell = leaf->GetViewCell();
2582
2583                        if (!viewCell->Mailed())
2584                        {
2585                                viewCell->mLeaves.clear();
2586                                viewCell->Mail();
2587                        }
2588       
2589                        viewCell->mLeaves.push_back(leaf);
2590
2591                }
2592                else
2593                {
2594                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2595
2596                        nodeStack.push(interior->GetFront());
2597                        nodeStack.push(interior->GetBack());
2598                }
2599        }
2600// TODO
2601#endif
2602}
2603
2604
2605typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2606
2607
2608int VspBspTree::CastBeam(Beam &beam)
2609{
2610    stack<bspNodePair> nodeStack;
2611        BspNodeGeometry *rgeom = new BspNodeGeometry();
2612        ConstructGeometry(mRoot, *rgeom);
2613
2614        nodeStack.push(bspNodePair(mRoot, rgeom));
2615 
2616        ViewCell::NewMail();
2617
2618        while (!nodeStack.empty())
2619        {
2620                BspNode *node = nodeStack.top().first;
2621                BspNodeGeometry *geom = nodeStack.top().second;
2622                nodeStack.pop();
2623               
2624                AxisAlignedBox3 box;
2625                box.Initialize();
2626                geom->IncludeInBox(box);
2627
2628                const int side = beam.ComputeIntersection(box);
2629               
2630                switch (side)
2631                {
2632                case -1:
2633                        CollectViewCells(node, true, beam.mViewCells, true);
2634                        break;
2635                case 0:
2636                       
2637                        if (node->IsLeaf())
2638                        {
2639                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2640                       
2641                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2642                                {
2643                                        leaf->GetViewCell()->Mail();
2644                                        beam.mViewCells.push_back(leaf->GetViewCell());
2645                                }
2646                        }
2647                        else
2648                        {
2649                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2650                       
2651                                BspNode *first = interior->GetFront();
2652                                BspNode *second = interior->GetBack();
2653           
2654                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2655                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2656
2657                                geom->SplitGeometry(*firstGeom,
2658                                                                        *secondGeom,
2659                                                                        interior->GetPlane(),
2660                                                                        mBox,
2661                                                                        mEpsilon);
2662
2663                                // decide on the order of the nodes
2664                                if (DotProd(beam.mPlanes[0].mNormal,
2665                                        interior->GetPlane().mNormal) > 0)
2666                                {
2667                                        swap(first, second);
2668                                        swap(firstGeom, secondGeom);
2669                                }
2670
2671                                nodeStack.push(bspNodePair(first, firstGeom));
2672                                nodeStack.push(bspNodePair(second, secondGeom));
2673                        }
2674                       
2675                        break;
2676                default:
2677                        // default: cull
2678                        break;
2679                }
2680               
2681                DEL_PTR(geom);
2682               
2683        }
2684
2685        return (int)beam.mViewCells.size();
2686}
2687
2688
2689void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
2690{
2691        mViewCellsManager = vcm;
2692}
2693
2694
2695int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
2696                                                                           vector<MergeCandidate> &candidates)
2697{
2698        BspLeaf::NewMail();
2699       
2700        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2701
2702        int numCandidates = 0;
2703
2704        // find merge candidates and push them into queue
2705        for (it = leaves.begin(); it != it_end; ++ it)
2706        {
2707                BspLeaf *leaf = *it;
2708               
2709                // the same leaves must not be part of two merge candidates
2710                leaf->Mail();
2711                vector<BspLeaf *> neighbors;
2712                FindNeighbors(leaf, neighbors, true);
2713
2714                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2715
2716                // TODO: test if at least one ray goes from one leaf to the other
2717                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2718                {
2719                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
2720                        {
2721                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
2722                                candidates.push_back(mc);
2723
2724                                ++ numCandidates;
2725                                if ((numCandidates % 1000) == 0)
2726                                {
2727                                        cout << "collected " << numCandidates << " merge candidates" << endl;
2728                                }
2729                        }
2730                }
2731        }
2732
2733        Debug << "merge queue: " << (int)candidates.size() << endl;
2734        Debug << "leaves in queue: " << numCandidates << endl;
2735       
2736
2737        return (int)leaves.size();
2738}
2739
2740
2741int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
2742                                                                           vector<MergeCandidate> &candidates)
2743{
2744        ViewCell::NewMail();
2745        long startTime = GetTime();
2746       
2747        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2748        ViewCellContainer::const_iterator iit;
2749
2750        int numLeaves = 0;
2751       
2752        BspLeaf::NewMail();
2753
2754        for (int i = 0; i < (int)rays.size(); ++ i)
2755        { 
2756                VssRay *ray = rays[i];
2757       
2758                // traverse leaves stored in the rays and compare and
2759                // merge consecutive leaves (i.e., the neighbors in the tree)
2760                if (ray->mViewCells.size() < 2)
2761                        continue;
2762//TODO viewcellhierarchy
2763                iit = ray->mViewCells.begin();
2764                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
2765                BspLeaf *leaf = bspVc->mLeaf;
2766               
2767                // traverse intersections
2768                // consecutive leaves are neighbors => add them to queue
2769                for (; iit != ray->mViewCells.end(); ++ iit)
2770                {
2771                        // next pair
2772                        BspLeaf *prevLeaf = leaf;
2773                        bspVc = dynamic_cast<BspViewCell *>(*iit);
2774            leaf = bspVc->mLeaf;
2775
2776                        // view space not valid or same view cell
2777                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
2778                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
2779                                continue;
2780
2781                vector<BspLeaf *> &neighbors = neighborMap[leaf];
2782                       
2783                        bool found = false;
2784
2785                        // both leaves inserted in queue already =>
2786                        // look if double pair already exists
2787                        if (leaf->Mailed() && prevLeaf->Mailed())
2788                        {
2789                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2790                               
2791                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2792                                        if (*it == prevLeaf)
2793                                                found = true; // already in queue
2794                        }
2795               
2796                        if (!found)
2797                        {
2798                                // this pair is not in map yet
2799                                // => insert into the neighbor map and the queue
2800                                neighbors.push_back(prevLeaf);
2801                                neighborMap[prevLeaf].push_back(leaf);
2802
2803                                leaf->Mail();
2804                                prevLeaf->Mail();
2805               
2806                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
2807                               
2808                                candidates.push_back(mc);
2809
2810                                if (((int)candidates.size() % 1000) == 0)
2811                                {
2812                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
2813                                }
2814                        }
2815        }
2816        }
2817
2818        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2819        Debug << "merge queue: " << (int)candidates.size() << endl;
2820        Debug << "leaves in queue: " << numLeaves << endl;
2821
2822
2823        //-- collect the leaves which haven't been found by ray casting
2824        if (0)
2825        {
2826                cout << "finding additional merge candidates using geometry" << endl;
2827                vector<BspLeaf *> leaves;
2828                CollectLeaves(leaves, true);
2829                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
2830                CollectMergeCandidates(leaves, candidates);
2831        }
2832
2833        return numLeaves;
2834}
2835
2836
2837
2838
2839ViewCell *VspBspTree::GetViewCell(const Vector3 &point)
2840{
2841  if (mRoot == NULL)
2842        return NULL;
2843 
2844  stack<BspNode *> nodeStack;
2845  nodeStack.push(mRoot);
2846 
2847  ViewCell *viewcell = NULL;
2848 
2849  while (!nodeStack.empty())  {
2850        BspNode *node = nodeStack.top();
2851        nodeStack.pop();
2852       
2853        if (node->IsLeaf()) {
2854          viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2855          break;
2856        } else {
2857         
2858          BspInterior *interior = dynamic_cast<BspInterior *>(node);
2859               
2860          // random decision
2861          if (interior->GetPlane().Side(point) < 0)
2862                nodeStack.push(interior->GetBack());
2863          else
2864                nodeStack.push(interior->GetFront());
2865        }
2866  }
2867 
2868  return viewcell;
2869}
2870
2871
2872bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
2873{
2874        BspNode *node = mRoot;
2875
2876        while (1)
2877        {
2878                // early exit
2879                if (node->TreeValid())
2880                        return true;
2881
2882                if (node->IsLeaf())
2883                        return false;
2884                       
2885                BspInterior *in = dynamic_cast<BspInterior *>(node);
2886                                       
2887                if (in->GetPlane().Side(viewPoint) <= 0)
2888                {
2889                        node = in->GetBack();
2890                }
2891                else
2892                {
2893                        node = in->GetFront();
2894                }
2895        }
2896
2897        // should never come here
2898        return false;
2899}
2900
2901
2902void VspBspTree::PropagateUpValidity(BspNode *node)
2903{
2904        const bool isValid = node->TreeValid();
2905
2906        // propagative up invalid flag until only invalid nodes exist over this node
2907        if (!isValid)
2908        {
2909                while (!node->IsRoot() && node->GetParent()->TreeValid())
2910                {
2911                        node = node->GetParent();
2912                        node->SetTreeValid(false);
2913                }
2914        }
2915        else
2916        {
2917                // propagative up valid flag until one of the subtrees is invalid
2918                while (!node->IsRoot() && !node->TreeValid())
2919                {
2920            node = node->GetParent();
2921                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2922                       
2923                        // the parent is valid iff both leaves are valid
2924                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
2925                                                           interior->GetFront()->TreeValid());
2926                }
2927        }
2928}
2929
2930
2931bool VspBspTree::Export(ofstream &stream)
2932{
2933        ExportNode(mRoot, stream);
2934
2935        return true;
2936}
2937
2938
2939void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
2940{
2941        if (node->IsLeaf())
2942        {
2943                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2944                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2945
2946                int id = -1;
2947                if (viewCell != mOutOfBoundsCell)
2948                        id = viewCell->GetId();
2949
2950                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
2951        }
2952        else
2953        {
2954                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2955       
2956                Plane3 plane = interior->GetPlane();
2957                stream << "<Interior plane=\"" << plane.mNormal.x << " "
2958                           << plane.mNormal.y << " " << plane.mNormal.z << " "
2959                           << plane.mD << "\">" << endl;
2960
2961                ExportNode(interior->GetBack(), stream);
2962                ExportNode(interior->GetFront(), stream);
2963
2964                stream << "</Interior>" << endl;
2965        }
2966}
Note: See TracBrowser for help on using the repository browser.