source: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp @ 1023

Revision 1023, 96.3 KB checked in by mattausch, 18 years ago (diff)
RevLine 
[478]1#include <stack>
2#include <time.h>
3#include <iomanip>
4
[463]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"
[478]17#include "ViewCellsManager.h"
[532]18#include "Beam.h"
[463]19
[863]20namespace GtpVisibilityPreprocessor {
[860]21
[639]22#define USE_FIXEDPOINT_T 0
[1020]23#define COUNT_ORIGIN_OBJECTS 1
[590]24
[1020]25       
[463]26//-- static members
[508]27
[482]28int VspBspTree::sFrontId = 0;
[463]29int VspBspTree::sBackId = 0;
30int VspBspTree::sFrontAndBackId = 0;
31
[1020]32
33
[697]34typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
[463]35
[557]36
[579]37// pvs penalty can be different from pvs size
[882]38inline static float EvalPvsPenalty(const int pvs,
39                                                                   const int lower,
40                                                                   const int upper)
[579]41{
42        // clamp to minmax values
43        if (pvs < lower)
44                return (float)lower;
45        if (pvs > upper)
46                return (float)upper;
[578]47
[579]48        return (float)pvs;
49}
[463]50
[557]51
[579]52
53
[601]54/******************************************************************************/
55/*                       class VspBspTree implementation                      */
56/******************************************************************************/
[579]57
58
[1004]59VspBspTree::VspBspTree():
[463]60mRoot(NULL),
[547]61mUseAreaForPvs(false),
[478]62mCostNormalizer(Limits::Small),
63mViewCellsManager(NULL),
[497]64mOutOfBoundsCell(NULL),
[643]65mStoreRays(false),
[605]66mRenderCostWeight(0.5),
[610]67mUseRandomAxis(false),
[650]68mTimeStamp(1)
[463]69{
[486]70        bool randomize = false;
[1004]71        Environment::GetSingleton()->GetBoolValue("VspBspTree.Construction.randomize", randomize);
[1011]72        if (randomize) Randomize(); // initialise random generator for heuristics
[463]73
74        //-- termination criteria for autopartition
[1004]75        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
76        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
77        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
78        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minProbability", mTermMinProbability);
79        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
80        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
[1023]81       
[1004]82        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
83        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
[666]84
[564]85        //-- max cost ratio for early tree termination
[1004]86        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
[610]87
[1004]88        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
89        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
[610]90
[463]91        //-- factors for bsp tree split plane heuristics
[1004]92        Environment::GetSingleton()->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
93        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
[463]94
[482]95
[463]96        //-- partition criteria
[1004]97        Environment::GetSingleton()->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
98        Environment::GetSingleton()->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
99        Environment::GetSingleton()->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
[463]100
[1004]101        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
102        Environment::GetSingleton()->GetIntValue("VspBspTree.maxTests", mMaxTests);
[463]103
[564]104        // if only the driving axis is used for axis aligned split
[1004]105        Environment::GetSingleton()->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
[580]106       
[508]107        //-- termination criteria for axis aligned split
[1004]108        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.AxisAligned.maxRayContribution",
[665]109                                                                mTermMaxRayContriForAxisAligned);
[1004]110        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
[665]111                                                         mTermMinRaysForAxisAligned);
[487]112
[1004]113        //Environment::GetSingleton()->GetFloatValue("VspBspTree.maxTotalMemory", mMaxTotalMemory);
114        Environment::GetSingleton()->GetFloatValue("VspBspTree.maxStaticMemory", mMaxMemory);
[508]115
[1004]116        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.renderCostWeight", mRenderCostWeight);
[1020]117        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
[1004]118        Environment::GetSingleton()->GetBoolValue("VspBspTree.usePolygonSplitIfAvailable", mUsePolygonSplitIfAvailable);
[547]119
[1004]120        Environment::GetSingleton()->GetBoolValue("VspBspTree.useCostHeuristics", mUseCostHeuristics);
121        Environment::GetSingleton()->GetBoolValue("VspBspTree.useSplitCostQueue", mUseSplitCostQueue);
122        Environment::GetSingleton()->GetBoolValue("VspBspTree.simulateOctree", mCirculatingAxis);
123        Environment::GetSingleton()->GetBoolValue("VspBspTree.useRandomAxis", mUseRandomAxis);
124        Environment::GetSingleton()->GetIntValue("VspBspTree.nodePriorityQueueType", mNodePriorityQueueType);
[580]125
[676]126       
[660]127        char subdivisionStatsLog[100];
[1004]128        Environment::GetSingleton()->GetStringValue("VspBspTree.subdivisionStats", subdivisionStatsLog);
[660]129        mSubdivisionStats.open(subdivisionStatsLog);
[612]130
[1004]131        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.minBand", mMinBand);
132        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.maxBand", mMaxBand);
[1006]133        Environment::GetSingleton()->GetBoolValue("VspBspTree.Construction.useDrivingAxisForMaxCost", mUseDrivingAxisIfMaxCostViolated);
[801]134
[478]135        //-- debug output
[580]136
[473]137        Debug << "******* VSP BSP options ******** " << endl;
138    Debug << "max depth: " << mTermMaxDepth << endl;
139        Debug << "min PVS: " << mTermMinPvs << endl;
[547]140        Debug << "min probabiliy: " << mTermMinProbability << endl;
[473]141        Debug << "min rays: " << mTermMinRays << endl;
142        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
143        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
144        Debug << "miss tolerance: " << mTermMissTolerance << endl;
145        Debug << "max view cells: " << mMaxViewCells << endl;
146        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
[663]147        //Debug << "max plane candidates: " << mMaxRayCandidates << endl;
[486]148        Debug << "randomize: " << randomize << endl;
[582]149
[551]150        Debug << "using area for pvs: " << mUseAreaForPvs << endl;
[580]151        Debug << "render cost weight: " << mRenderCostWeight << endl;
[663]152        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
153        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
154        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
155        Debug << "max memory: " << mMaxMemory << endl;
156        Debug << "use poly split if available: " << mUsePolygonSplitIfAvailable << endl;
157        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
158        Debug << "use split cost queue: " << mUseSplitCostQueue << endl;
159        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
[664]160        Debug << "use random axis: " << mUseRandomAxis << endl;
[735]161        Debug << "priority queue type: " << mNodePriorityQueueType << endl;
[822]162        Debug << "circulating axis: " << mCirculatingAxis << endl;
[801]163        Debug << "minband: " << mMinBand << endl;
164        Debug << "maxband: " << mMaxBand << endl;
[1006]165        Debug << "use driving axis for max cost: " << mUseDrivingAxisIfMaxCostViolated << endl;
[1020]166        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
[663]167
[463]168        Debug << "Split plane strategy: ";
[564]169
[463]170        if (mSplitPlaneStrategy & RANDOM_POLYGON)
[474]171        {
[463]172                Debug << "random polygon ";
[474]173        }
[463]174        if (mSplitPlaneStrategy & AXIS_ALIGNED)
[472]175        {
[463]176                Debug << "axis aligned ";
[472]177        }
[665]178        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
[472]179        {
[474]180                mCostNormalizer += mLeastRaySplitsFactor;
[463]181                Debug << "least ray splits ";
[472]182        }
[463]183        if (mSplitPlaneStrategy & BALANCED_RAYS)
[472]184        {
[474]185                mCostNormalizer += mBalancedRaysFactor;
[463]186                Debug << "balanced rays ";
[472]187        }
[463]188        if (mSplitPlaneStrategy & PVS)
[472]189        {
[474]190                mCostNormalizer += mPvsFactor;
[463]191                Debug << "pvs";
[665]192        }
[482]193
[489]194
[1020]195        mLocalSplitCandidates = new vector<SortableEntry>;
[463]196
197        Debug << endl;
198}
[1004]199/*
[870]200VspBspTree::VspBspTree():
201mRoot(NULL),
202mUseAreaForPvs(false),
203mCostNormalizer(Limits::Small),
204mViewCellsManager(NULL),
205mOutOfBoundsCell(NULL),
206mStoreRays(false),
207mRenderCostWeight(0.5),
208mUseRandomAxis(false),
209mTimeStamp(1),
210mEpsilon(1e-6f)
211{
[1004]212}*/
[580]213
[508]214BspViewCell *VspBspTree::GetOutOfBoundsCell()
215{
216        return mOutOfBoundsCell;
217}
[463]218
[508]219
[489]220BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
221{
222        if (!mOutOfBoundsCell)
[508]223        {
[489]224                mOutOfBoundsCell = new BspViewCell();
[508]225                mOutOfBoundsCell->SetId(-1);
[547]226                mOutOfBoundsCell->SetValid(false);
[508]227        }
[547]228
[489]229        return mOutOfBoundsCell;
230}
231
232
[482]233const BspTreeStatistics &VspBspTree::GetStatistics() const
[463]234{
[574]235        return mBspStats;
[463]236}
237
238
239VspBspTree::~VspBspTree()
240{
241        DEL_PTR(mRoot);
[1020]242        DEL_PTR(mLocalSplitCandidates);
[463]243}
244
[579]245
[482]246int VspBspTree::AddMeshToPolygons(Mesh *mesh,
247                                                                  PolygonContainer &polys,
[463]248                                                                  MeshInstance *parent)
249{
250        FaceContainer::const_iterator fi;
[482]251
[463]252        // copy the face data to polygons
253        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
254        {
255                Polygon3 *poly = new Polygon3((*fi), mesh);
[482]256
[463]257                if (poly->Valid(mEpsilon))
258                {
259                        poly->mParent = parent; // set parent intersectable
260                        polys.push_back(poly);
261                }
262                else
263                        DEL_PTR(poly);
264        }
265        return (int)mesh->mFaces.size();
266}
267
[580]268
[482]269int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
[882]270                                                                 PolygonContainer &polys,
271                                                                 int maxObjects)
[463]272{
[482]273        int limit = (maxObjects > 0) ?
[463]274                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
[482]275
[463]276        int polysSize = 0;
277
278        for (int i = 0; i < limit; ++ i)
279        {
280                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
281                {
282                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
[482]283                        polysSize +=
284                                AddMeshToPolygons(viewCells[i]->GetMesh(),
285                                                                  polys,
[463]286                                                                  viewCells[i]);
287                }
288        }
289
290        return polysSize;
291}
292
[580]293
[482]294int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
295                                                                 PolygonContainer &polys,
[463]296                                                                 int maxObjects)
297{
[482]298        int limit = (maxObjects > 0) ?
[463]299                Min((int)objects.size(), maxObjects) : (int)objects.size();
[482]300
[463]301        for (int i = 0; i < limit; ++i)
302        {
303                Intersectable *object = objects[i];//*it;
304                Mesh *mesh = NULL;
305
306                switch (object->Type()) // extract the meshes
307                {
308                case Intersectable::MESH_INSTANCE:
309                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
310                        break;
311                case Intersectable::VIEW_CELL:
312                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
313                        break;
[1001]314                case Intersectable::TRANSFORMED_MESH_INSTANCE:
315                        {
316                                TransformedMeshInstance *mi = dynamic_cast<TransformedMeshInstance *>(object);
317
[1002]318                                if (!mi->GetMesh())     
[1001]319                                        break;
[1002]320                                mesh = new Mesh();
321                                mi->GetTransformedMesh(*mesh);
322                               
[1001]323                break;
324                        }
[463]325                default:
326                        Debug << "intersectable type not supported" << endl;
327                        break;
328                }
[482]329
[463]330        if (mesh) // copy the mesh data to polygons
331                {
332                        mBox.Include(object->GetBox()); // add to BSP tree aabb
[485]333                        AddMeshToPolygons(mesh, polys, NULL);
[1001]334
335                        // cleanup
336                        if (object->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
337                                DEL_PTR(mesh);
[463]338                }
339        }
340
341        return (int)polys.size();
342}
343
[580]344
[483]345void VspBspTree::Construct(const VssRayContainer &sampleRays,
346                                                   AxisAlignedBox3 *forcedBoundingBox)
[463]347{
[574]348        mBspStats.nodes = 1;
[463]349        mBox.Initialize();      // initialise BSP tree bounding box
[482]350
[484]351        if (forcedBoundingBox)
352                mBox = *forcedBoundingBox;
353       
[463]354        PolygonContainer polys;
355        RayInfoContainer *rays = new RayInfoContainer();
356
357        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
358
359        long startTime = GetTime();
360
[480]361        cout << "Extracting polygons from rays ... ";
[463]362
363        Intersectable::NewMail();
364
[511]365        int numObj = 0;
[542]366
[463]367        //-- extract polygons intersected by the rays
368        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
369        {
370                VssRay *ray = *rit;
[1002]371                Intersectable *obj = ray->mTerminationObject;
[482]372
[484]373                if ((mBox.IsInside(ray->mTermination) || !forcedBoundingBox) &&
[1002]374                        obj && !obj->Mailed())
[463]375                {
[1002]376                        obj->Mail();
377
378                        // transformed mesh instance and mesh instance handle mesh differently
379                        if (obj->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
380                        {
381                                Mesh mesh;
382                               
383                                TransformedMeshInstance *tmobj =
384                                        dynamic_cast<TransformedMeshInstance *>(obj);
385                               
386                                tmobj->GetTransformedMesh(mesh);
387                                AddMeshToPolygons(&mesh, polys, tmobj);
388                        }
389                        else // MeshInstance
390                        {
391                                MeshInstance *mobj = dynamic_cast<MeshInstance *>(obj);
392                                AddMeshToPolygons(mobj->GetMesh(), polys, mobj);
393                        }
394
[511]395                        ++ numObj;
[648]396
[484]397                        //-- compute bounding box
398                        if (!forcedBoundingBox)
399                                mBox.Include(ray->mTermination);
[463]400                }
401
[484]402                if ((mBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
403                        ray->mOriginObject &&
404                        !ray->mOriginObject->Mailed())
[463]405                {
406                        ray->mOriginObject->Mail();
407                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
408                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
[511]409                        ++ numObj;
410
[484]411                        //-- compute bounding box
412                        if (!forcedBoundingBox)
413                                mBox.Include(ray->mOrigin);
[463]414                }
415        }
[535]416       
[653]417        Debug << "maximal pvs (i.e., pvs still considered as valid) : "
418                  << mViewCellsManager->GetMaxPvsSize() << endl;
[580]419
[463]420        //-- store rays
421        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
422        {
423                VssRay *ray = *rit;
[482]424
[463]425                float minT, maxT;
426
[564]427                static Ray hray;
428                hray.Init(*ray);
[562]429
[483]430                // TODO: not very efficient to implictly cast between rays types
[564]431                if (mBox.GetRaySegment(hray, minT, maxT))
[463]432                {
433                        float len = ray->Length();
[482]434
435                        if (!len)
[463]436                                len = Limits::Small;
[482]437
[463]438                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
439                }
440        }
441
[587]442        // normalize
[547]443        if (mUseAreaForPvs)
[587]444                mTermMinProbability *= mBox.SurfaceArea();
[547]445        else
446                mTermMinProbability *= mBox.GetVolume();
447
[648]448        // throw out unnecessary polygons
449        PreprocessPolygons(polys);
450
[574]451        mBspStats.polys = (int)polys.size();
[654]452        mGlobalCostMisses = 0;
453
[475]454        cout << "finished" << endl;
[463]455
[482]456        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
[475]457                  << (int)sampleRays.size() << " rays in "
458                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
459
[655]460        // use split cost priority queue
461        if (mUseSplitCostQueue)
462        {
[654]463                ConstructWithSplitQueue(polys, rays);
[655]464        }
[654]465        else
[655]466        {
[654]467                Construct(polys, rays);
[655]468        }
[463]469
470        // clean up polygons
471        CLEAR_CONTAINER(polys);
472}
473
[508]474
[612]475// TODO: return memory usage in MB
[656]476float VspBspTree::GetMemUsage() const
[508]477{
[656]478        return (float)
479                 (sizeof(VspBspTree) +
480                  mBspStats.Leaves() * sizeof(BspLeaf) +
481                  mCreatedViewCells * sizeof(BspViewCell) +
482                  mBspStats.pvs * sizeof(ObjectPvsData) +
483                  mBspStats.Interior() * sizeof(BspInterior) +
484                  mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
[508]485}
486
487
[463]488void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
489{
[600]490        VspBspTraversalQueue tQueue;
[463]491
[1016]492        /// create new vsp tree
[463]493        mRoot = new BspLeaf();
494
495        // constrruct root node geometry
496        BspNodeGeometry *geom = new BspNodeGeometry();
497        ConstructGeometry(mRoot, *geom);
498
[1016]499        /// we use the overall probability as normalizer
500        /// either the overall area or the volume
[547]501        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
502
[1020]503        /// first traversal data
[482]504        VspBspTraversalData tData(mRoot,
505                                                          new PolygonContainer(polys),
[463]506                                                          0,
[482]507                                                          rays,
508                              ComputePvsSize(*rays),
[547]509                                                          prop,
[463]510                                                          geom);
[663]511
[664]512        EvalPriority(tData);
[663]513
514
[578]515        // first node is kd node, i.e. an axis aligned box
[710]516        if (1)
[578]517        tData.mIsKdNode = true;
518        else
519                tData.mIsKdNode = false;
[562]520
[600]521        tQueue.push(tData);
[463]522
[609]523
[605]524        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
[607]525        mTotalPvsSize = tData.mPvs;
526       
[1020]527        // first subdivison statistics
528        AddSubdivisionStats(1, 0, 0, mTotalCost, (float)mTotalPvsSize);
529   
[574]530        mBspStats.Start();
[667]531        cout << "Constructing vsp bsp tree ... \n";
[463]532
[1016]533        const long startTime = GetTime();       
534        // used for intermediate time measurements and progress
535        long interTime = GetTime();
536
[664]537        int nLeaves = 500;
538        int nViewCells = 500;
[587]539
[542]540        mOutOfMemory = false;
[612]541        mCreatedViewCells = 0;
542       
[600]543        while (!tQueue.empty())
[463]544        {
[600]545                tData = tQueue.top();
546            tQueue.pop();               
[463]547
[508]548                if (0 && !mOutOfMemory)
549                {
550                        float mem = GetMemUsage();
[478]551
[508]552                        if (mem > mMaxMemory)
553                        {
554                                mOutOfMemory = true;
555                                Debug << "memory limit reached: " << mem << endl;
556                        }
557                }
558
[587]559                // subdivide leaf node
[1016]560                const BspNode *r = Subdivide(tQueue, tData);
[463]561
562                if (r == mRoot)
[482]563                        Debug << "VSP BSP tree construction time spent at root: "
[542]564                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
565
[654]566                if (mBspStats.Leaves() >= nLeaves)
[542]567                {
[612]568                        nLeaves += 500;
569
[574]570                        cout << "leaves=" << mBspStats.Leaves() << endl;
[542]571                        Debug << "needed "
[587]572                                  << TimeDiff(interTime, GetTime())*1e-3
[612]573                                  << " secs to create 500 view cells" << endl;
[542]574                        interTime = GetTime();
575                }
[612]576
[664]577                if (mCreatedViewCells >= nViewCells)
[612]578                {
579                        nViewCells += 500;
580
581                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
582                }
[463]583        }
584
[542]585        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
[1020]586        cout << "finished in " << TimeDiff(startTime, GetTime())*1e-3 << "secs" << endl;
[463]587
[574]588        mBspStats.Stop();
[463]589}
590
[508]591
[653]592
[654]593void VspBspTree::ConstructWithSplitQueue(const PolygonContainer &polys,
[653]594                                                                                          RayInfoContainer *rays)
595{
596        VspBspSplitQueue tQueue;
597
598        mRoot = new BspLeaf();
599
600        // constrruct root node geometry
601        BspNodeGeometry *geom = new BspNodeGeometry();
602        ConstructGeometry(mRoot, *geom);
603
604        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
605
606        VspBspTraversalData tData(mRoot,
607                                                          new PolygonContainer(polys),
608                                                          0,
609                                                          rays,
610                              ComputePvsSize(*rays),
611                                                          prop,
612                                                          geom);
613
[663]614
[660]615        // compute first split candidate
[653]616        VspBspSplitCandidate splitCandidate;
617        EvalSplitCandidate(tData, splitCandidate);
618
619        tQueue.push(splitCandidate);
620
621        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
622        mTotalPvsSize = tData.mPvs;
623       
[1020]624        // first subdivison statistics
625        AddSubdivisionStats(1, 0, 0, mTotalCost, (float)mTotalPvsSize);
626   
627    mBspStats.Start();
[667]628        cout << "Constructing vsp bsp tree ... \n";
[653]629
630        long startTime = GetTime();     
[666]631        int nLeaves = 500;
632        int nViewCells = 500;
[653]633
634        // used for intermediate time measurements and progress
635        long interTime = GetTime();     
636
637        mOutOfMemory = false;
638
639        mCreatedViewCells = 0;
640       
641        while (!tQueue.empty())
642        {
643                splitCandidate = tQueue.top();
644            tQueue.pop();               
645
[654]646                // cost ratio of cost decrease / totalCost
[1020]647                float costRatio = splitCandidate.GetPriority() / mTotalCost;
[654]648
[655]649                //Debug << "cost ratio: " << costRatio << endl;
[654]650
651                if (costRatio < mTermMinGlobalCostRatio)
652                        ++ mGlobalCostMisses;
[655]653               
[653]654                if (0 && !mOutOfMemory)
655                {
656                        float mem = GetMemUsage();
657
658                        if (mem > mMaxMemory)
659                        {
660                                mOutOfMemory = true;
661                                Debug << "memory limit reached: " << mem << endl;
662                        }
663                }
664
665                // subdivide leaf node
666                BspNode *r = Subdivide(tQueue, splitCandidate);
667
668                if (r == mRoot)
669                        Debug << "VSP BSP tree construction time spent at root: "
670                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
671
[654]672                if (mBspStats.Leaves() >= nLeaves)
[653]673                {
674                        nLeaves += 500;
675
676                        cout << "leaves=" << mBspStats.Leaves() << endl;
677                        Debug << "needed "
678                                  << TimeDiff(interTime, GetTime())*1e-3
679                                  << " secs to create 500 view cells" << endl;
680                        interTime = GetTime();
681                }
682
683                if (mCreatedViewCells == nViewCells)
684                {
685                        nViewCells += 500;
686
687                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
688                }
689        }
690
691        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
692        cout << "finished\n";
693
694        mBspStats.Stop();
695}
696
697
[654]698bool VspBspTree::LocalTerminationCriteriaMet(const VspBspTraversalData &data) const
[463]699{
[482]700        return
[463]701                (((int)data.mRays->size() <= mTermMinRays) ||
[473]702                 (data.mPvs <= mTermMinPvs)   ||
[547]703                 (data.mProbability <= mTermMinProbability) ||
[535]704                 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
[463]705                 (data.mDepth >= mTermMaxDepth));
706}
707
[508]708
[1020]709void VspBspTree::AddSubdivisionStats(const int viewCells,
710                                                                         const float renderCostDecr,
711                                                                         const float splitCandidateCost,
712                                                                         const float totalRenderCost,
713                                                                         const float avgRenderCost)
714{
715        mSubdivisionStats
716                        << "#ViewCells\n" << viewCells << endl
717                        << "#RenderCostDecrease\n" << renderCostDecr << endl
718                        << "#SplitCandidateCost\n" << splitCandidateCost << endl
719                        << "#TotalRenderCost\n" << totalRenderCost << endl
720                        << "#AvgRenderCost\n" << avgRenderCost << endl;
721}
722
723
[654]724bool VspBspTree::GlobalTerminationCriteriaMet(const VspBspTraversalData &data) const
725{
726        return
727                (mOutOfMemory
728                || (mBspStats.Leaves() >= mMaxViewCells)
729                || (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
730                 );
731}
732
733
[600]734BspNode *VspBspTree::Subdivide(VspBspTraversalQueue &tQueue,
[463]735                                                           VspBspTraversalData &tData)
736{
[473]737        BspNode *newNode = tData.mNode;
738
[654]739        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
[473]740        {
741                PolygonContainer coincident;
[482]742
[473]743                VspBspTraversalData tFrontData;
744                VspBspTraversalData tBackData;
[612]745
[473]746                // create new interior node and two leaf nodes
747                // or return leaf as it is (if maxCostRatio missed)
[653]748                int splitAxis;
749                bool splitFurther = true;
750                int maxCostMisses = tData.mMaxCostMisses;
751               
752                Plane3 splitPlane;
753                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
[726]754               
755                // choose next split plane
[653]756                if (!SelectPlane(splitPlane, leaf, tData, tFrontData, tBackData, splitAxis))
[473]757                {
[653]758                        ++ maxCostMisses;
759
760                        if (maxCostMisses > mTermMissTolerance)
761                        {
762                                // terminate branch because of max cost
763                                ++ mBspStats.maxCostNodes;
764                                splitFurther = false;
765                        }
766                }
767       
[726]768                // if this a valid split => subdivide this node further
[653]769                if (splitFurther) //-- continue subdivision
770                {
771                        newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
772
773                        if (splitAxis < 3)
774                                ++ mBspStats.splits[splitAxis];
775                        else
776                                ++ mBspStats.polySplits;
777
[822]778                        // if it was a kd node (i.e., a box) and the split axis is axis aligned, it is still a kd node
[710]779                        tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
[726]780                        tFrontData.mAxis = tBackData.mAxis = splitAxis;
[663]781
[653]782                        // how often was max cost ratio missed in this branch?
783                        tFrontData.mMaxCostMisses = maxCostMisses;
784                        tBackData.mMaxCostMisses = maxCostMisses;
785
[664]786                        EvalPriority(tFrontData);
787                        EvalPriority(tBackData);
[663]788
[726]789                        // evaluate subdivision stats
[600]790                        if (1)
791                        {
[1020]792                                const float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
793                                const float cBack = (float)tBackData.mPvs * tBackData.mProbability;
794                                const float cData = (float)tData.mPvs * tData.mProbability;;
[605]795
[1020]796                const float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
[607]797
[600]798                                mTotalCost += costDecr;
[607]799                                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
[600]800
[1020]801                                AddSubdivisionStats(mBspStats.Leaves(),
802                                                                    -costDecr,
803                                                                        0,
804                                                                        mTotalCost,
805                                                                        (float)mTotalPvsSize / (float)mBspStats.Leaves());
[600]806                        }
807
[473]808                        // push the children on the stack
[600]809                        tQueue.push(tFrontData);
810                        tQueue.push(tBackData);
[473]811
812                        // delete old leaf node
[482]813                        DEL_PTR(tData.mNode);
[473]814                }
815        }
[482]816
[478]817        //-- terminate traversal and create new view cell
[473]818        if (newNode->IsLeaf())
[463]819        {
[473]820                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
[1020]821               
[547]822                BspViewCell *viewCell = new BspViewCell();
[463]823                leaf->SetViewCell(viewCell);
[487]824       
825                //-- update pvs
[556]826                int conSamp = 0;
827                float sampCon = 0.0f;
828                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
[487]829
[1002]830                // update scalar pvs size lookup
831                mViewCellsManager->SetScalarPvsSize(viewCell, viewCell->GetPvs().GetSize());
832       
[752]833
[574]834                mBspStats.contributingSamples += conSamp;
835                mBspStats.sampleContributions +=(int) sampCon;
[487]836
837                //-- store additional info
[478]838                if (mStoreRays)
839                {
840                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
841                        for (it = tData.mRays->begin(); it != it_end; ++ it)
[639]842                        {
843                                (*it).mRay->Ref();                     
[478]844                                leaf->mVssRays.push_back((*it).mRay);
[639]845                        }
[478]846                }
[612]847
[564]848                // should I check here?
[562]849                if (0 && !mViewCellsManager->CheckValidity(viewCell, 0, mViewCellsManager->GetMaxPvsSize()))
[547]850                {
851                        viewCell->SetValid(false);
852                        leaf->SetTreeValid(false);
853                        PropagateUpValidity(leaf);
[463]854
[574]855                        ++ mBspStats.invalidLeaves;
[547]856                }
857               
[580]858        viewCell->mLeaf = leaf;
[547]859
860                if (mUseAreaForPvs)
861                        viewCell->SetArea(tData.mProbability);
862                else
863                        viewCell->SetVolume(tData.mProbability);
864
865                leaf->mProbability = tData.mProbability;
866
[1020]867                // finally evaluate stats until this leaf
[487]868                EvaluateLeafStats(tData);               
[463]869        }
[482]870
[473]871        //-- cleanup
[478]872        tData.Clear();
[463]873
[472]874        return newNode;
[463]875}
876
[726]877// subdivide using a split plane queue
[653]878BspNode *VspBspTree::Subdivide(VspBspSplitQueue &tQueue,
879                                                           VspBspSplitCandidate &splitCandidate)
880{
881        VspBspTraversalData &tData = splitCandidate.mParentData;
882
883        BspNode *newNode = tData.mNode;
884
[654]885        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
[666]886        {       
[653]887                PolygonContainer coincident;
888
889                VspBspTraversalData tFrontData;
890                VspBspTraversalData tBackData;
891
892                //-- continue subdivision
[726]893               
[653]894                // create new interior node and two leaf node
895                const Plane3 splitPlane = splitCandidate.mSplitPlane;
[654]896                               
[653]897                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
[666]898       
[660]899                const int splitAxis = splitCandidate.mSplitAxis;
900                const int maxCostMisses = splitCandidate.mMaxCostMisses;
901
[654]902                if (splitAxis < 3)
903                        ++ mBspStats.splits[splitAxis];
904                else
905                        ++ mBspStats.polySplits;
[653]906
[710]907                tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
[726]908                tFrontData.mAxis = tBackData.mAxis = splitAxis;
909
[654]910                // how often was max cost ratio missed in this branch?
911                tFrontData.mMaxCostMisses = maxCostMisses;
912                tBackData.mMaxCostMisses = maxCostMisses;
[664]913                       
[1020]914                // statistics
[653]915                if (1)
916                {
917                        float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
918                        float cBack = (float)tBackData.mPvs * tBackData.mProbability;
[675]919                        float cData = (float)tData.mPvs * tData.mProbability;
[653]920
[675]921                       
[653]922                        float costDecr =
923                                (cFront + cBack - cData) / mBox.GetVolume();
924
925                        mTotalCost += costDecr;
926                        mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
927
[1020]928                        AddSubdivisionStats(mBspStats.Leaves(),
929                                                                -costDecr, 
930                                                                splitCandidate.GetPriority(),
931                                                                mTotalCost,
932                                                                (float)mTotalPvsSize / (float)mBspStats.Leaves());
[653]933                }
934
[666]935       
[653]936                //-- push the new split candidates on the stack
937                VspBspSplitCandidate frontCandidate;
938                VspBspSplitCandidate backCandidate;
939
[654]940                EvalSplitCandidate(tFrontData, frontCandidate);
941                EvalSplitCandidate(tBackData, backCandidate);
942       
[653]943                tQueue.push(frontCandidate);
944                tQueue.push(backCandidate);
[666]945       
[653]946                // delete old leaf node
947                DEL_PTR(tData.mNode);
948        }
949
[654]950
[653]951        //-- terminate traversal and create new view cell
952        if (newNode->IsLeaf())
953        {
954                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
[1020]955
[653]956                BspViewCell *viewCell = new BspViewCell();
[710]957        leaf->SetViewCell(viewCell);
[653]958               
959                //-- update pvs
960                int conSamp = 0;
961                float sampCon = 0.0f;
962                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
963
[1002]964                // update scalar pvs size value
965                mViewCellsManager->SetScalarPvsSize(viewCell, viewCell->GetPvs().GetSize());
[752]966
[653]967                mBspStats.contributingSamples += conSamp;
968                mBspStats.sampleContributions +=(int) sampCon;
969
970                //-- store additional info
971                if (mStoreRays)
972                {
973                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
974                        for (it = tData.mRays->begin(); it != it_end; ++ it)
975                        {
976                                (*it).mRay->Ref();                     
977                                leaf->mVssRays.push_back((*it).mRay);
978                        }
979                }
980
[1020]981               
[653]982                viewCell->mLeaf = leaf;
983
984                if (mUseAreaForPvs)
985                        viewCell->SetArea(tData.mProbability);
986                else
987                        viewCell->SetVolume(tData.mProbability);
988
[675]989        leaf->mProbability = tData.mProbability;
[653]990
[1020]991                // finally evaluate stats until this leaf
[653]992                EvaluateLeafStats(tData);               
993        }
994
995        //-- cleanup
996        tData.Clear();
997
998        return newNode;
999}
1000
1001
[664]1002void VspBspTree::EvalPriority(VspBspTraversalData &tData) const
1003{
[735]1004    switch (mNodePriorityQueueType)
1005        {
1006        case BREATH_FIRST:
[734]1007                tData.mPriority = (float)-tData.mDepth;
[735]1008                break;
1009        case DEPTH_FIRST:
[734]1010                tData.mPriority = (float)tData.mDepth;
[735]1011                break;
1012        default:
[734]1013                tData.mPriority = tData.mPvs * tData.mProbability;
[735]1014                //Debug << "priority: " << tData.mPriority << endl;
1015                break;
1016        }
[664]1017}
1018
1019
[652]1020void VspBspTree::EvalSplitCandidate(VspBspTraversalData &tData,
1021                                                                        VspBspSplitCandidate &splitData)
1022{
1023        VspBspTraversalData frontData;
1024        VspBspTraversalData backData;
1025
1026        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
[654]1027
1028        // compute locally best split plane
[726]1029    bool success = SelectPlane(splitData.mSplitPlane, leaf, tData,
[666]1030                                                           frontData, backData, splitData.mSplitAxis);
[652]1031
1032        // TODO: reuse
1033        DEL_PTR(frontData.mGeometry);
1034        DEL_PTR(backData.mGeometry);
1035       
[654]1036        // compute global decrease in render cost
[1020]1037        splitData.mPriority = EvalRenderCostDecrease(splitData.mSplitPlane, tData);
[652]1038        splitData.mParentData = tData;
[660]1039        splitData.mMaxCostMisses = success ? tData.mMaxCostMisses : tData.mMaxCostMisses + 1;
[652]1040}
1041
1042
[653]1043BspInterior *VspBspTree::SubdivideNode(const Plane3 &splitPlane,
1044                                                                           VspBspTraversalData &tData,
1045                                                                           VspBspTraversalData &frontData,
1046                                                                           VspBspTraversalData &backData,
1047                                                                           PolygonContainer &coincident)
[463]1048{
1049        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
[508]1050       
[473]1051        //-- the front and back traversal data is filled with the new values
1052        frontData.mDepth = tData.mDepth + 1;
[508]1053        frontData.mPolygons = new PolygonContainer();
[473]1054        frontData.mRays = new RayInfoContainer();
[508]1055       
[473]1056        backData.mDepth = tData.mDepth + 1;
[508]1057        backData.mPolygons = new PolygonContainer();
[473]1058        backData.mRays = new RayInfoContainer();
[508]1059       
[653]1060
1061        //-- subdivide rays
[652]1062        SplitRays(splitPlane,
[482]1063                          *tData.mRays,
1064                          *frontData.mRays,
[463]1065                          *backData.mRays);
[482]1066
[463]1067
[472]1068        // compute pvs
[463]1069        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1070        backData.mPvs = ComputePvsSize(*backData.mRays);
1071
[508]1072        // split front and back node geometry and compute area
[547]1073       
1074        // if geometry was not already computed
[602]1075        if (!frontData.mGeometry && !backData.mGeometry)
[463]1076        {
[547]1077                frontData.mGeometry = new BspNodeGeometry();
1078                backData.mGeometry = new BspNodeGeometry();
[482]1079
[547]1080                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1081                                                                           *backData.mGeometry,
[652]1082                                                                           splitPlane,
[547]1083                                                                           mBox,
[679]1084                                                                           //0.0f);
1085                                                                           mEpsilon);
[508]1086               
[547]1087                if (mUseAreaForPvs)
1088                {
1089                        frontData.mProbability = frontData.mGeometry->GetArea();
1090                        backData.mProbability = backData.mGeometry->GetArea();
[508]1091                }
[547]1092                else
1093                {
1094                        frontData.mProbability = frontData.mGeometry->GetVolume();
[654]1095                        backData.mProbability = tData.mProbability - frontData.mProbability;
[676]1096
[744]1097                        // should never come here: wrong volume !!!
[676]1098                        if (0)
1099                        {
[744]1100                                if (frontData.mProbability < -0.00001)
1101                                        Debug << "fatal error f: " << frontData.mProbability << endl;
1102                                if (backData.mProbability < -0.00001)
1103                                        Debug << "fatal error b: " << backData.mProbability << endl;
1104
1105                                // clamp because of precision issues
[676]1106                                if (frontData.mProbability < 0) frontData.mProbability = 0;
1107                                if (backData.mProbability < 0) backData.mProbability = 0;
1108                        }
[547]1109                }
[463]1110        }
[663]1111
[547]1112       
[652]1113    // subdivide polygons
1114        SplitPolygons(splitPlane,
1115                                  *tData.mPolygons,
1116                      *frontData.mPolygons,
1117                                  *backData.mPolygons,
1118                                  coincident);
[463]1119
[652]1120
1121
[653]1122        ///////////////////////////////////////
1123        // subdivide further
[652]1124
[711]1125        // store maximal and minimal depth
1126        if (tData.mDepth > mBspStats.maxDepth)
1127        {
1128                Debug << "max depth increases to " << tData.mDepth << " at " << mBspStats.Leaves() << " leaves" << endl;
1129                mBspStats.maxDepth = tData.mDepth;
1130        }
1131
[652]1132        mBspStats.nodes += 2;
1133
[711]1134   
[652]1135        BspInterior *interior = new BspInterior(splitPlane);
1136
1137#ifdef _DEBUG
1138        Debug << interior << endl;
1139#endif
1140
[711]1141
[463]1142        //-- create front and back leaf
1143
1144        BspInterior *parent = leaf->GetParent();
1145
1146        // replace a link from node's parent
[487]1147        if (parent)
[463]1148        {
1149                parent->ReplaceChildLink(leaf, interior);
1150                interior->SetParent(parent);
1151        }
1152        else // new root
1153        {
1154                mRoot = interior;
1155        }
1156
1157        // and setup child links
1158        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
[482]1159
[463]1160        frontData.mNode = interior->GetFront();
1161        backData.mNode = interior->GetBack();
[473]1162
[650]1163        interior->mTimeStamp = mTimeStamp ++;
[652]1164       
[711]1165
[463]1166        //DEL_PTR(leaf);
1167        return interior;
1168}
1169
[508]1170
[463]1171void VspBspTree::AddToPvs(BspLeaf *leaf,
[482]1172                                                  const RayInfoContainer &rays,
[556]1173                                                  float &sampleContributions,
[463]1174                                                  int &contributingSamples)
1175{
[1002]1176        sampleContributions = 0;
1177        contributingSamples = 0;
[556]1178 
[1002]1179        RayInfoContainer::const_iterator it, it_end = rays.end();
[556]1180 
[1002]1181        ViewCellLeaf *vc = leaf->GetViewCell();
[556]1182 
[1002]1183        // add contributions from samples to the PVS
1184        for (it = rays.begin(); it != it_end; ++ it)
[463]1185        {
[1002]1186                float sc = 0.0f;
1187                VssRay *ray = (*it).mRay;
1188
1189                bool madeContrib = false;
1190                float contribution;
1191
1192                if (ray->mTerminationObject)
1193                {
1194                        if (vc->AddPvsSample(ray->mTerminationObject, ray->mPdf, contribution))
1195                                madeContrib = true;
1196                        sc += contribution;
1197                }
[556]1198         
[1006]1199                // only count termination objects?
[1020]1200                if (COUNT_ORIGIN_OBJECTS && ray->mOriginObject)
[1002]1201                {
1202                        if (vc->AddPvsSample(ray->mOriginObject, ray->mPdf, contribution))
1203                                madeContrib = true;
[1020]1204
[1002]1205                        sc += contribution;
1206                }
[556]1207         
1208          sampleContributions += sc;
[1002]1209
[556]1210          if (madeContrib)
1211                  ++ contributingSamples;
1212               
1213          //leaf->mVssRays.push_back(ray);
[463]1214        }
1215}
1216
[580]1217
[710]1218void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays,
1219                                                                         const int axis,
1220                                                                         float minBand,
1221                                                                         float maxBand)
[463]1222{
[1020]1223        mLocalSplitCandidates->clear();
[463]1224
[480]1225        int requestedSize = 2 * (int)(rays.size());
1226        // creates a sorted split candidates array
[1020]1227        if (mLocalSplitCandidates->capacity() > 500000 &&
1228                requestedSize < (int)(mLocalSplitCandidates->capacity() / 10) )
[480]1229        {
[1020]1230        delete mLocalSplitCandidates;
1231                mLocalSplitCandidates = new vector<SortableEntry>;
[480]1232        }
[463]1233
[1020]1234        mLocalSplitCandidates->reserve(requestedSize);
[480]1235
[710]1236        float pos;
1237
1238        // float values => don't compare with exact values
1239        if (0)
1240        {
1241                minBand += Limits::Small;
1242                maxBand -= Limits::Small;
1243        }
1244
[480]1245        // insert all queries
[612]1246        for (RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
[473]1247        {
[612]1248                const bool positive = (*ri).mRay->HasPosDir(axis);
[710]1249                               
1250                pos = (*ri).ExtrapOrigin(axis);
1251                // clamp to min / max band
1252                if (0) ClipValue(pos, minBand, maxBand);
1253               
[1020]1254                mLocalSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
[810]1255                                                                        pos, (*ri).mRay));
[480]1256
[710]1257                pos = (*ri).ExtrapTermination(axis);
1258                // clamp to min / max band
1259                if (0) ClipValue(pos, minBand, maxBand);
1260
[1020]1261                mLocalSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
[810]1262                                                                        pos, (*ri).mRay));
[473]1263        }
[480]1264
[1020]1265        stable_sort(mLocalSplitCandidates->begin(), mLocalSplitCandidates->end());
[463]1266}
1267
[580]1268
[480]1269float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
1270                                                                                  const AxisAlignedBox3 &box,
1271                                                                                  const int pvsSize,
[710]1272                                                                                  const int axis,
[480]1273                                          float &position)
[463]1274{
[710]1275        const float minBox = box.Min(axis);
1276        const float maxBox = box.Max(axis);
[822]1277
[710]1278        const float sizeBox = maxBox - minBox;
[480]1279
[801]1280        const float minBand = minBox + mMinBand * sizeBox;
1281        const float maxBand = minBox + mMaxBand * sizeBox;
[710]1282
1283        SortSplitCandidates(rays, axis, minBand, maxBand);
1284
[463]1285        // go through the lists, count the number of objects left and right
1286        // and evaluate the following cost funcion:
[480]1287        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
1288
[810]1289        int pvsl = 0;
1290        int pvsr = pvsSize;
[480]1291
[612]1292        int pvsBack = pvsl;
1293        int pvsFront = pvsr;
1294
1295        float sum = (float)pvsSize * sizeBox;
[463]1296        float minSum = 1e20f;
1297
[822]1298       
[710]1299        // if no border can be found, take mid split
1300        position = minBox + 0.5f * sizeBox;
[822]1301       
1302        // the relative cost ratio
[837]1303        float ratio = /*Limits::Infinity;*/99999999.0f;
[822]1304        bool splitPlaneFound = false;
[710]1305
[480]1306        Intersectable::NewMail();
1307
[612]1308        RayInfoContainer::const_iterator ri, ri_end = rays.end();
1309
1310        // set all object as belonging to the front pvs
1311        for(ri = rays.begin(); ri != ri_end; ++ ri)
[463]1312        {
[612]1313                Intersectable *oObject = (*ri).mRay->mOriginObject;
1314                Intersectable *tObject = (*ri).mRay->mTerminationObject;
1315
[1020]1316                if (COUNT_ORIGIN_OBJECTS && oObject)
[463]1317                {
[612]1318                        if (!oObject->Mailed())
[482]1319                        {
[612]1320                                oObject->Mail();
1321                                oObject->mCounter = 1;
[482]1322                        }
[612]1323                        else
1324                        {
1325                                ++ oObject->mCounter;
1326                        }
[463]1327                }
[1020]1328
[612]1329                if (tObject)
1330                {
1331                        if (!tObject->Mailed())
1332                        {
1333                                tObject->Mail();
1334                                tObject->mCounter = 1;
1335                        }
1336                        else
1337                        {
1338                                ++ tObject->mCounter;
1339                        }
1340                }
[480]1341        }
1342
1343        Intersectable::NewMail();
1344
[1020]1345        vector<SortableEntry>::const_iterator ci, ci_end = mLocalSplitCandidates->end();
[612]1346
[1020]1347        for (ci = mLocalSplitCandidates->begin(); ci != ci_end; ++ ci)
[480]1348        {
1349                VssRay *ray;
[612]1350                ray = (*ci).ray;
1351               
1352                Intersectable *oObject = ray->mOriginObject;
1353                Intersectable *tObject = ray->mTerminationObject;
1354               
[480]1355
1356                switch ((*ci).type)
[463]1357                {
[480]1358                        case SortableEntry::ERayMin:
1359                                {
[1020]1360                                        if (COUNT_ORIGIN_OBJECTS && oObject && !oObject->Mailed())
[480]1361                                        {
[612]1362                                                oObject->Mail();
1363                                                ++ pvsl;
[480]1364                                        }
[1020]1365
[612]1366                                        if (tObject && !tObject->Mailed())
1367                                        {
1368                                                tObject->Mail();
1369                                                ++ pvsl;
1370                                        }
[1020]1371
[480]1372                                        break;
1373                                }
1374                        case SortableEntry::ERayMax:
1375                                {
[1020]1376                                        if (COUNT_ORIGIN_OBJECTS && oObject)
[612]1377                                        {
1378                                                if (-- oObject->mCounter == 0)
1379                                                        -- pvsr;
1380                                        }
[463]1381
[612]1382                                        if (tObject)
[480]1383                                        {
[612]1384                                                if (-- tObject->mCounter == 0)
1385                                                        -- pvsr;
[480]1386                                        }
1387
1388                                        break;
1389                                }
1390                }
[822]1391               
1392               
[1020]1393                // Note: we compare size of bounding boxes of front and back side because
1394                // of efficiency reasons (otherwise a new geometry would have to be computed
1395                // in each step and incremential evaluation would be difficult.
1396                // but then errors happen if the geometry is not an axis aligned box
1397                // (i.e., if a geometry aligned split was taken before)
1398                // question: is it sufficient to make this approximation?
[710]1399                if (((*ci).value >= minBand) && ((*ci).value <= maxBand))
[480]1400                {
[612]1401                        sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value);
[480]1402
[822]1403                        //Debug  << "pos=" << (*ci).value << "\t pvs=(" <<  pvsl << "," << pvsr << ")" << endl;
1404                        //Debug << "cost= " << sum << endl;
[480]1405
1406                        if (sum < minSum)
[463]1407                        {
[822]1408                                splitPlaneFound = true;
1409
[463]1410                                minSum = sum;
1411                                position = (*ci).value;
[710]1412                               
[612]1413                                pvsBack = pvsl;
1414                                pvsFront = pvsr;
[463]1415                        }
1416                }
1417        }
[710]1418       
[822]1419       
[612]1420        // -- compute cost
1421        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1422        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1423
1424        const float pOverall = sizeBox;
1425
1426        const float pBack = position - minBox;
1427        const float pFront = maxBox - position;
1428       
1429        const float penaltyOld = EvalPvsPenalty(pvsSize, lowerPvsLimit, upperPvsLimit);
1430    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1431        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1432       
1433        const float oldRenderCost = penaltyOld * pOverall;
1434        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1435
[822]1436        if (splitPlaneFound)
1437        {
1438                ratio = mPvsFactor * newRenderCost / (oldRenderCost + Limits::Small);
1439        }
1440        //if (axis != 1)
1441        //Debug << "axis=" << axis << " costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
1442         //    <<"\t pb=(" << pvsBack << ")\t pf=(" << pvsFront << ")" << endl;
[612]1443
[480]1444        return ratio;
[463]1445}
1446
[480]1447
[482]1448float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
[491]1449                                                                                 const VspBspTraversalData &tData,
[495]1450                                                                                 int &axis,
[508]1451                                                                                 BspNodeGeometry **frontGeom,
1452                                                                                 BspNodeGeometry **backGeom,
[547]1453                                                                                 float &pFront,
1454                                                                                 float &pBack,
[710]1455                                                                                 const bool isKdNode)
[463]1456{
[508]1457        float nPosition[3];
1458        float nCostRatio[3];
[547]1459        float nProbFront[3];
1460        float nProbBack[3];
[508]1461
1462        BspNodeGeometry *nFrontGeom[3];
1463        BspNodeGeometry *nBackGeom[3];
1464
[822]1465        // set to NULL, so I can find out which gemetry was stored
[612]1466        for (int i = 0; i < 3; ++ i)
1467        {
1468                nFrontGeom[i] = NULL;
1469                nBackGeom[i] = NULL;
1470        }
1471
[545]1472        // create bounding box of node geometry
[463]1473        AxisAlignedBox3 box;
[710]1474               
[562]1475        //TODO: for kd split geometry already is box => only take minmax vertices
[551]1476        if (1)
[509]1477        {
[822]1478                // get bounding box from geometry
[710]1479                tData.mGeometry->GetBoundingBox(box);
[509]1480        }
1481        else
1482        {
[710]1483                box.Initialize();
[509]1484                RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
[480]1485
[509]1486                for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
1487                        box.Include((*ri).ExtrapTermination());
1488        }
[663]1489
1490        int sAxis = 0;
[822]1491        int bestAxis;
1492
[837]1493        // if max cost ratio is exceeded, take split along longest axis instead
1494        const float maxCostRatioForArbitraryAxis = 0.9f;
1495
[1006]1496        if (mUseDrivingAxisIfMaxCostViolated)
[822]1497                bestAxis = box.Size().DrivingAxis();
1498        else
1499                bestAxis = -1;
1500
[978]1501#if 0
1502        // maximum cost ratio for axis to be valid:
[822]1503        // if exceeded, spatial mid split is used instead
[978]1504        const maxCostRatioForHeur = 0.99f;
1505#endif
[822]1506
[978]1507        // if we use some kind of specialised fixed axis
[837]1508    const bool useSpecialAxis =
1509                mOnlyDrivingAxis || mUseRandomAxis || mCirculatingAxis;
[663]1510
[801]1511        if (mUseRandomAxis)
[663]1512                sAxis = Random(3);
[801]1513        else if (mCirculatingAxis)
[726]1514                sAxis = (tData.mAxis + 1) % 3;
[822]1515        else if (mOnlyDrivingAxis)
[801]1516                sAxis = box.Size().DrivingAxis();
1517
[664]1518               
[670]1519        //Debug << "use special axis: " << useSpecialAxis << endl;
1520        //Debug << "axis: " << sAxis << " drivingaxis: " << box.Size().DrivingAxis();
[663]1521
[822]1522        for (axis = 0; axis < 3 ; ++ axis)
[480]1523        {
[663]1524                if (!useSpecialAxis || (axis == sAxis))
[463]1525                {
[822]1526                        //-- place split plane using heuristics
1527
1528                        if (mUseCostHeuristics)
[480]1529                        {
[822]1530                                nCostRatio[axis] =
1531                                        BestCostRatioHeuristics(*tData.mRays,
1532                                                                                    box,
1533                                                                                        tData.mPvs,
1534                                                                                        axis,
1535                                                                                        nPosition[axis]);                       
1536                        }
[1006]1537                        else //-- split plane position is spatial median
[822]1538                        {
1539
[480]1540                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
[543]1541                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
[547]1542
1543                                // allows faster split because we have axis aligned kd tree boxes
[822]1544                                if (isKdNode)
[542]1545                                {
1546                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
1547                                                                                                                                box,
1548                                                                                                                                axis,
[547]1549                                                                                                                                nPosition[axis],
1550                                                                                                                                nProbFront[axis],
1551                                                                                                                                nProbBack[axis]);
[542]1552                                       
[543]1553                                        Vector3 pos;
[542]1554                                       
[710]1555                                        // create back geometry from box
[822]1556                                        // NOTE: the geometry is saved when possible
[543]1557                                        pos = box.Max(); pos[axis] = nPosition[axis];
[547]1558                                        AxisAlignedBox3 bBox(box.Min(), pos);
[710]1559                                        PolygonContainer fPolys;
1560                                        bBox.ExtractPolys(fPolys);
1561
1562                                        nBackGeom[axis] = new BspNodeGeometry(fPolys);
1563       
[822]1564                                        //-- create front geometry from box
[542]1565                                        pos = box.Min(); pos[axis] = nPosition[axis];
[547]1566                                        AxisAlignedBox3 fBox(pos, box.Max());
[710]1567
1568                                        PolygonContainer bPolys;
1569                                        fBox.ExtractPolys(bPolys);
1570                                        nFrontGeom[axis] = new BspNodeGeometry(bPolys);
[542]1571                                }
1572                                else
1573                                {
[710]1574                                        nFrontGeom[axis] = new BspNodeGeometry();
1575                                        nBackGeom[axis] = new BspNodeGeometry();
1576
[573]1577                                        nCostRatio[axis] =
1578                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1579                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1580                                                                                   nProbFront[axis], nProbBack[axis]);
[542]1581                                }
[480]1582                        }
[822]1583                                               
[978]1584                       
[1006]1585                        if (mUseDrivingAxisIfMaxCostViolated)
[480]1586                        {
[978]1587                                // we take longest axis split if cost ratio exceeds threshold
1588                                if (nCostRatio[axis] < min(maxCostRatioForArbitraryAxis, nCostRatio[bestAxis]))
[822]1589                                {
1590                                        bestAxis = axis;
1591                                }
1592                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
[978]1593                                        Debug << "taking split along longest axis (" << bestAxis << ") instead of  (" << axis << ")" << endl;
1594                               
1595                        }
1596                        else
1597                        {
1598                                if (bestAxis == -1)
[822]1599                                {
1600                                        bestAxis = axis;
1601                                }
[978]1602                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
[822]1603                                {
1604                                        bestAxis = axis;
1605                                }
[978]1606                        }
[463]1607                }
1608        }
1609
[495]1610        //-- assign values
1611        axis = bestAxis;
[547]1612        pFront = nProbFront[bestAxis];
1613        pBack = nProbBack[bestAxis];
[495]1614
[508]1615        // assign best split nodes geometry
1616        *frontGeom = nFrontGeom[bestAxis];
1617        *backGeom = nBackGeom[bestAxis];
[542]1618
[508]1619        // and delete other geometry
[612]1620        DEL_PTR(nFrontGeom[(bestAxis + 1) % 3]);
1621        DEL_PTR(nBackGeom[(bestAxis + 2) % 3]);
[495]1622
[508]1623        //-- split plane
1624    Vector3 normal(0,0,0); normal[bestAxis] = 1;
[480]1625        plane = Plane3(normal, nPosition[bestAxis]);
[508]1626
[822]1627        //Debug << "best axis: " << bestAxis << " pos " << nPosition[bestAxis] << endl;
1628        //Debug << "!!!!!!!!!!!!!!" << endl;
[480]1629        return nCostRatio[bestAxis];
[463]1630}
1631
[480]1632
[508]1633bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1634                                                         BspLeaf *leaf,
[652]1635                                                         VspBspTraversalData &data,                                                     
[508]1636                                                         VspBspTraversalData &frontData,
[612]1637                                                         VspBspTraversalData &backData,
1638                                                         int &splitAxis)
[491]1639{
[810]1640        // HACK matt: subdivide regularily to certain depth
[801]1641        if (data.mDepth < 0)   
1642        {
1643                cout << "d: " << data.mDepth << endl;
1644                // return axis aligned split
1645                AxisAlignedBox3 box;
1646                box.Initialize();
1647       
1648                // create bounding box of region
1649                data.mGeometry->GetBoundingBox(box);
1650       
1651                const int axis = box.Size().DrivingAxis();
1652                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1653
1654                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1655                bestPlane = Plane3(norm, position);
1656                splitAxis = axis;
1657                return true;
1658        }
1659
[508]1660        // simplest strategy: just take next polygon
1661        if (mSplitPlaneStrategy & RANDOM_POLYGON)
[491]1662        {
[508]1663        if (!data.mPolygons->empty())
1664                {
1665                        const int randIdx =
1666                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1667                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
[491]1668
[508]1669                        bestPlane = nextPoly->GetSupportingPlane();
1670                        return true;
1671                }
[491]1672        }
1673
[508]1674        //-- use heuristics to find appropriate plane
[491]1675
[508]1676        // intermediate plane
1677        Plane3 plane;
1678        float lowestCost = MAX_FLOAT;
[517]1679       
1680        // decides if the first few splits should be only axisAligned
[508]1681        const bool onlyAxisAligned  =
1682                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1683                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1684                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1685       
1686        const int limit = onlyAxisAligned ? 0 :
1687                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
[491]1688
[508]1689        float candidateCost;
[491]1690
[508]1691        int maxIdx = (int)data.mPolygons->size();
[491]1692
[508]1693        for (int i = 0; i < limit; ++ i)
[491]1694        {
[562]1695                // the already taken candidates are stored behind maxIdx
1696                // => assure that no index is taken twice
[508]1697                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1698                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
[491]1699
[508]1700                // swap candidate to the end to avoid testing same plane
1701                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1702                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
[491]1703
[508]1704                // evaluate current candidate
1705                BspNodeGeometry fGeom, bGeom;
1706                float fArea, bArea;
1707                plane = poly->GetSupportingPlane();
[573]1708                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
[491]1709               
[508]1710                if (candidateCost < lowestCost)
[491]1711                {
[508]1712                        bestPlane = plane;
1713                        lowestCost = candidateCost;
[491]1714                }
1715        }
1716
[1006]1717
[508]1718        //-- evaluate axis aligned splits
[1006]1719       
[508]1720        int axis;
1721        BspNodeGeometry *fGeom, *bGeom;
[547]1722        float pFront, pBack;
[491]1723
[653]1724        candidateCost = 99999999.0f;
[491]1725
[1006]1726        // as a variant, we take axis aligned split only if there is
1727        // more polygon available to guide the split
[653]1728        if (!mUsePolygonSplitIfAvailable || data.mPolygons->empty())
1729        {
1730                candidateCost = SelectAxisAlignedPlane(plane,
1731                                                                                           data,
1732                                                                                           axis,
1733                                                                                           &fGeom,
1734                                                                                           &bGeom,
1735                                                                                           pFront,
1736                                                                                           pBack,
1737                                                                                           data.mIsKdNode);     
1738        }
1739
[612]1740        splitAxis = 3;
[562]1741
[508]1742        if (candidateCost < lowestCost)
1743        {       
1744                bestPlane = plane;
1745                lowestCost = candidateCost;
[612]1746                splitAxis = axis;
[653]1747       
[542]1748                // assign already computed values
1749                // we can do this because we always save the
[562]1750                // computed values from the axis aligned splits         
[653]1751
[612]1752                if (fGeom && bGeom)
1753                {
1754                        frontData.mGeometry = fGeom;
1755                        backData.mGeometry = bGeom;
[547]1756       
[612]1757                        frontData.mProbability = pFront;
1758                        backData.mProbability = pBack;
1759                }
[508]1760        }
1761        else
[463]1762        {
[508]1763                DEL_PTR(fGeom);
1764                DEL_PTR(bGeom);
[463]1765        }
[678]1766   
[679]1767#ifdef _DEBUG
[508]1768        Debug << "plane lowest cost: " << lowestCost << endl;
[679]1769#endif
[508]1770
[801]1771        // exeeded relative max cost ratio
[508]1772        if (lowestCost > mTermMaxCostRatio)
[611]1773        {
[508]1774                return false;
[611]1775        }
[508]1776
1777        return true;
[463]1778}
1779
[480]1780
[473]1781Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
[482]1782{
[473]1783        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
[482]1784
[473]1785        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1786        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1787
1788        const Vector3 pt = (maxPt + minPt) * 0.5;
1789        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1790
1791        return Plane3(normal, pt);
1792}
1793
[480]1794
[473]1795Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
[482]1796{
[473]1797        Vector3 pt[3];
[482]1798
[473]1799        int idx[3];
1800        int cmaxT = 0;
1801        int cminT = 0;
1802        bool chooseMin = false;
1803
1804        for (int j = 0; j < 3; ++ j)
1805        {
1806                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
[482]1807
[473]1808                if (idx[j] >= (int)rays.size())
1809                {
1810                        idx[j] -= (int)rays.size();
[482]1811
[473]1812                        chooseMin = (cminT < 2);
1813                }
1814                else
1815                        chooseMin = (cmaxT < 2);
1816
1817                RayInfo rayInf = rays[idx[j]];
1818                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
[482]1819        }
[473]1820
1821        return Plane3(pt[0], pt[1], pt[2]);
1822}
1823
[580]1824
[473]1825Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
[482]1826{
[473]1827        Vector3 pt[3];
[482]1828
[473]1829        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1830        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1831
1832        // check if rays different
1833        if (idx1 == idx2)
1834                idx2 = (idx2 + 1) % (int)rays.size();
1835
1836        const RayInfo ray1 = rays[idx1];
1837        const RayInfo ray2 = rays[idx2];
1838
1839        // normal vector of the plane parallel to both lines
1840        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1841
1842        // vector from line 1 to line 2
[479]1843        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
[482]1844
[473]1845        // project vector on normal to get distance
1846        const float dist = DotProd(vd, norm);
1847
1848        // point on plane lies halfway between the two planes
1849        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1850
1851        return Plane3(norm, planePt);
1852}
1853
[495]1854
[463]1855inline void VspBspTree::GenerateUniqueIdsForPvs()
1856{
[580]1857        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1858        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1859        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
[463]1860}
1861
[495]1862
[652]1863float VspBspTree::EvalRenderCostDecrease(const Plane3 &candidatePlane,
1864                                                                                 const VspBspTraversalData &data) const
1865{
[729]1866        float pvsFront = 0;
1867        float pvsBack = 0;
1868        float totalPvs = 0;
[652]1869
1870        // probability that view point lies in back / front node
1871        float pOverall = data.mProbability;
1872        float pFront = 0;
1873        float pBack = 0;
1874
1875
1876        // create unique ids for pvs heuristics
1877        GenerateUniqueIdsForPvs();
1878       
1879        for (int i = 0; i < data.mRays->size(); ++ i)
1880        {
1881                RayInfo rayInf = (*data.mRays)[i];
1882
1883                float t;
1884                VssRay *ray = rayInf.mRay;
1885                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1886
1887                // find front and back pvs for origing and termination object
1888                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
[1020]1889
1890                if (COUNT_ORIGIN_OBJECTS)
1891                        AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
[652]1892        }
1893
1894
1895        BspNodeGeometry geomFront;
1896        BspNodeGeometry geomBack;
1897
1898        // construct child geometry with regard to the candidate split plane
1899        data.mGeometry->SplitGeometry(geomFront,
1900                                                                  geomBack,
1901                                                                  candidatePlane,
1902                                                                  mBox,
[679]1903                                                                  //0.0f);
1904                                                                  mEpsilon);
[652]1905
1906        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1907        {
1908                pFront = geomFront.GetVolume();
1909                pBack = pOverall - pFront;
[675]1910
[729]1911                // something is wrong with the volume
[679]1912                if ((pFront < 0.0) || (pBack < 0.0))
[676]1913                {
[752]1914                        Debug << "ERROR in volume:\n"
1915                                  << "volume f :" << pFront << " b: " << pBack << " p: " << pOverall
1916                                  << ", real volume f: " << pFront << " b: " << geomBack.GetVolume()
1917                                  << ", #polygons f: " << geomFront.Size() << " b: " << geomBack.Size() << " p: " << data.mGeometry->Size() << endl;
[676]1918                }
[652]1919        }
1920        else
1921        {
1922                pFront = geomFront.GetArea();
1923                pBack = geomBack.GetArea();
1924        }
1925       
1926
1927        // -- pvs rendering heuristics
[1020]1928
1929        // upper and lower bounds
[652]1930        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1931        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1932
[1020]1933        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
1934    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
1935        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
[652]1936                       
1937        const float oldRenderCost = pOverall * penaltyOld;
1938        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1939
[654]1940        //Debug << "decrease: " << oldRenderCost - newRenderCost << endl;
[752]1941        const float renderCostDecrease = (oldRenderCost - newRenderCost) / mBox.GetVolume();
1942       
[1020]1943        const float weight = mRenderCostDecreaseWeight;
[1006]1944        // take render cost of node into account to avoid being stuck in a local minimum
[752]1945        const float normalizedOldRenderCost = oldRenderCost / mBox.GetVolume();
[1006]1946       
[1020]1947        //Debug << "rendercostdecr: " << weight * renderCostDecrease << " old render cost: " << (1.0f - weight) * normalizedOldRenderCost << endl;
1948        return weight * renderCostDecrease + (1.0f - weight) * normalizedOldRenderCost;
[652]1949}
1950
1951
[573]1952float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1953                                                                         const VspBspTraversalData &data,
1954                                                                         BspNodeGeometry &geomFront,
1955                                                                         BspNodeGeometry &geomBack,
1956                                                                         float &pFront,
1957                                                                         float &pBack) const
[463]1958{
[729]1959        float totalPvs = 0;
1960        float pvsFront = 0;
1961        float pvsBack = 0;
[652]1962       
[1006]1963        // overall probability is used as normalizer
[463]1964        float pOverall = 0;
[1006]1965
1966        // probability that view point lies in back / front node
[547]1967        pFront = 0;
1968        pBack = 0;
[463]1969
[1020]1970        int numTests; // the number of tests
[508]1971
[1020]1972        // if random samples shold be taken instead of testing all the rays
1973        bool useRand;
[463]1974
1975        if ((int)data.mRays->size() > mMaxTests)
1976        {
1977                useRand = true;
[1020]1978                numTests = mMaxTests;
[463]1979        }
1980        else
1981        {
1982                useRand = false;
[1020]1983                numTests = (int)data.mRays->size();
[463]1984        }
[508]1985       
[1020]1986        // create unique ids for pvs heuristics
1987        GenerateUniqueIdsForPvs();
1988
1989        for (int i = 0; i < numTests; ++ i)
[463]1990        {
[508]1991                const int testIdx = useRand ?
1992                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
[463]1993                RayInfo rayInf = (*data.mRays)[testIdx];
1994
1995                float t;
[508]1996                VssRay *ray = rayInf.mRay;
[463]1997                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1998
[652]1999                // find front and back pvs for origing and termination object
2000                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
[1020]2001
2002                if (COUNT_ORIGIN_OBJECTS)
2003                        AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
[652]2004        }
[508]2005
[652]2006        // construct child geometry with regard to the candidate split plane
[679]2007        bool splitSuccessFull = data.mGeometry->SplitGeometry(geomFront,
2008                                                                                                                  geomBack,
2009                                                                                                                  candidatePlane,
2010                                                                                                                  mBox,
2011                                                                                                                  //0.0f);
2012                                                                                                                  mEpsilon);
[675]2013
[652]2014        pOverall = data.mProbability;
[463]2015
[652]2016        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
2017        {
2018                pFront = geomFront.GetVolume();
2019                pBack = pOverall - pFront;
[675]2020               
[729]2021                // HACK: precision issues possible for unbalanced split => don't take this split!
[685]2022                if (1 &&
[682]2023                        (!splitSuccessFull || (pFront <= 0) || (pBack <= 0) ||
2024                        !geomFront.Valid() || !geomBack.Valid()))
[676]2025                {
[752]2026                        //Debug << "error f: " << pFront << " b: " << pBack << endl;
2027                        // high penalty for this split
[711]2028                        return 99999.9f;
[676]2029                }
[463]2030        }
[652]2031        else
[542]2032        {
[652]2033                pFront = geomFront.GetArea();
2034                pBack = geomBack.GetArea();
[542]2035        }
[652]2036       
[542]2037
[580]2038        // -- pvs rendering heuristics
[652]2039        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
2040        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
[580]2041
[652]2042        // only render cost heuristics or combined with standard deviation
[752]2043        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
2044    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
2045        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
[579]2046                       
[652]2047        const float oldRenderCost = pOverall * penaltyOld;
2048        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
[579]2049
[652]2050        float oldCost, newCost;
[580]2051
[652]2052        // only render cost
2053        if (1)
2054        {
2055                oldCost = oldRenderCost;
2056                newCost = newRenderCost;
2057        }
2058        else // also considering standard deviation
2059        {
2060                // standard deviation is difference of back and front pvs
2061                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
[580]2062
[652]2063                const float newDeviation = 0.5f *
2064                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
[580]2065
[652]2066                const float oldDeviation = penaltyOld;
[580]2067
[652]2068                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
2069                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
2070        }
[580]2071
[1020]2072        const float cost = mPvsFactor * newCost / (oldCost + Limits::Small);
[607]2073               
[463]2074
2075#ifdef _DEBUG
[474]2076        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
[508]2077                  << " frontpvs: " << pvsFront << " pFront: " << pFront
2078                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
[600]2079        Debug << "cost: " << cost << endl;
[463]2080#endif
[482]2081
[652]2082        return cost;
[463]2083}
2084
[508]2085
[697]2086int VspBspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2087                                                                                ViewCellContainer &viewCells) const
2088{
2089        stack<bspNodePair> nodeStack;
2090        BspNodeGeometry *rgeom = new BspNodeGeometry();
2091
2092        ConstructGeometry(mRoot, *rgeom);
2093
2094        nodeStack.push(bspNodePair(mRoot, rgeom));
2095 
2096        ViewCell::NewMail();
2097
2098        while (!nodeStack.empty())
2099        {
2100                BspNode *node = nodeStack.top().first;
2101                BspNodeGeometry *geom = nodeStack.top().second;
2102                nodeStack.pop();
2103
2104                const int side = geom->ComputeIntersection(box);
2105               
2106                switch (side)
2107                {
2108                case -1:
2109                        // node geometry is contained in box
2110                        CollectViewCells(node, true, viewCells, true);
2111                        break;
2112
2113                case 0:
2114                        if (node->IsLeaf())
2115                        {
2116                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2117                       
2118                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2119                                {
2120                                        leaf->GetViewCell()->Mail();
2121                                        viewCells.push_back(leaf->GetViewCell());
2122                                }
2123                        }
2124                        else
2125                        {
2126                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2127                       
2128                                BspNode *first = interior->GetFront();
2129                                BspNode *second = interior->GetBack();
2130           
2131                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2132                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2133
2134                                geom->SplitGeometry(*firstGeom,
2135                                                                        *secondGeom,
2136                                                                        interior->GetPlane(),
2137                                                                        mBox,
2138                                                                        //0.0000001f);
2139                                                                        mEpsilon);
2140
2141                                nodeStack.push(bspNodePair(first, firstGeom));
2142                                nodeStack.push(bspNodePair(second, secondGeom));
2143                        }
2144                       
2145                        break;
2146                default:
2147                        // default: cull
2148                        break;
2149                }
2150               
2151                DEL_PTR(geom);
2152               
2153        }
2154
2155        return (int)viewCells.size();
2156}
2157
2158
[580]2159float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
2160                                                                                   const AxisAlignedBox3 &box,
2161                                                                                   const int axis,
2162                                                                                   const float &position,                                                                                 
2163                                                                                   float &pFront,
2164                                                                                   float &pBack) const
2165{
[729]2166        float pvsTotal = 0;
2167        float pvsFront = 0;
2168        float pvsBack = 0;
[580]2169       
2170        // create unique ids for pvs heuristics
2171        GenerateUniqueIdsForPvs();
2172
2173        const int pvsSize = data.mPvs;
[726]2174
[580]2175        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
2176
2177        // this is the main ray classification loop!
2178        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
2179        {
2180                // determine the side of this ray with respect to the plane
2181                float t;
2182                const int side = (*rit).ComputeRayIntersection(axis, position, t);
2183       
2184                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
[1020]2185
2186                if (COUNT_ORIGIN_OBJECTS)
2187                        AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
[580]2188        }
2189
[1020]2190
[580]2191        //-- pvs heuristics
2192
[1020]2193        float pOverall = data.mProbability;
[580]2194
[1020]2195        // note: we use a simplified computation assuming that we always do a
2196        // spatial mid split   
2197       
[580]2198        if (!mUseAreaForPvs)
[1020]2199        {   
2200                // volume
[580]2201                pBack = pFront = pOverall * 0.5f;
2202#if 0
2203                // box length substitute for probability
2204                const float minBox = box.Min(axis);
2205                const float maxBox = box.Max(axis);
2206
2207                pBack = position - minBox;
2208                pFront = maxBox - position;
2209                pOverall = maxBox - minBox;
2210#endif
2211        }
2212        else //-- area substitute for probability
2213        {
2214                const int axis2 = (axis + 1) % 3;
2215                const int axis3 = (axis + 2) % 3;
2216
2217                const float faceArea =
2218                        (box.Max(axis2) - box.Min(axis2)) *
2219                        (box.Max(axis3) - box.Min(axis3));
2220
2221                pBack = pFront = pOverall * 0.5f + faceArea;
2222        }
2223
2224#ifdef _DEBUG
2225        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
2226        Debug << pFront << " " << pBack << " " << pOverall << endl;
2227#endif
2228
2229       
2230        const float newCost = pvsBack * pBack + pvsFront * pFront;
2231        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
2232
2233        return  (mCtDivCi + newCost) / oldCost;
2234}
2235
2236
[463]2237void VspBspTree::AddObjToPvs(Intersectable *obj,
2238                                                         const int cf,
[729]2239                                                         float &frontPvs,
2240                                                         float &backPvs,
2241                                                         float &totalPvs) const
[463]2242{
2243        if (!obj)
2244                return;
[728]2245
[744]2246        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
2247
[654]2248        // new object
[508]2249        if ((obj->mMailbox != sFrontId) &&
2250                (obj->mMailbox != sBackId) &&
2251                (obj->mMailbox != sFrontAndBackId))
2252        {
[744]2253                totalPvs += renderCost;
[508]2254        }
2255
[463]2256        // TODO: does this really belong to no pvs?
2257        //if (cf == Ray::COINCIDENT) return;
2258
2259        // object belongs to both PVS
2260        if (cf >= 0)
2261        {
[482]2262                if ((obj->mMailbox != sFrontId) &&
[463]2263                        (obj->mMailbox != sFrontAndBackId))
2264                {
[744]2265                        frontPvs += renderCost;
[508]2266               
[463]2267                        if (obj->mMailbox == sBackId)
[482]2268                                obj->mMailbox = sFrontAndBackId;
[463]2269                        else
[482]2270                                obj->mMailbox = sFrontId;
[463]2271                }
2272        }
[482]2273
[463]2274        if (cf <= 0)
2275        {
2276                if ((obj->mMailbox != sBackId) &&
2277                        (obj->mMailbox != sFrontAndBackId))
2278                {
[744]2279                        backPvs += renderCost;
[508]2280               
[463]2281                        if (obj->mMailbox == sFrontId)
[482]2282                                obj->mMailbox = sFrontAndBackId;
[463]2283                        else
[482]2284                                obj->mMailbox = sBackId;
[463]2285                }
2286        }
2287}
2288
[491]2289
[503]2290void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
2291                                                           const bool onlyUnmailed,
2292                                                           const int maxPvsSize) const
[463]2293{
2294        stack<BspNode *> nodeStack;
2295        nodeStack.push(mRoot);
[482]2296
2297        while (!nodeStack.empty())
[463]2298        {
2299                BspNode *node = nodeStack.top();
2300                nodeStack.pop();
[489]2301               
[482]2302                if (node->IsLeaf())
[463]2303                {
[490]2304                        // test if this leaf is in valid view space
[503]2305                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2306                        if (leaf->TreeValid() &&
[508]2307                                (!onlyUnmailed || !leaf->Mailed()) &&
[503]2308                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
[490]2309                        {
2310                                leaves.push_back(leaf);
2311                        }
[482]2312                }
2313                else
[463]2314                {
2315                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2316
2317                        nodeStack.push(interior->GetBack());
2318                        nodeStack.push(interior->GetFront());
2319                }
2320        }
2321}
2322
[489]2323
[463]2324AxisAlignedBox3 VspBspTree::GetBoundingBox() const
2325{
2326        return mBox;
2327}
2328
[489]2329
[463]2330BspNode *VspBspTree::GetRoot() const
2331{
2332        return mRoot;
2333}
2334
[489]2335
[463]2336void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
2337{
2338        // the node became a leaf -> evaluate stats for leafs
2339        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
2340
2341
[574]2342        if (data.mPvs > mBspStats.maxPvs)
[711]2343        {
[574]2344                mBspStats.maxPvs = data.mPvs;
[711]2345        }
2346
[656]2347        mBspStats.pvs += data.mPvs;
2348
[574]2349        if (data.mDepth < mBspStats.minDepth)
[711]2350        {
[574]2351                mBspStats.minDepth = data.mDepth;
[711]2352        }
[656]2353       
[463]2354        if (data.mDepth >= mTermMaxDepth)
[711]2355        {
[744]2356        ++ mBspStats.maxDepthNodes;
2357                //Debug << "new max depth: " << mBspStats.maxDepthNodes << endl;
[711]2358        }
[611]2359
[508]2360        // accumulate rays to compute rays /  leaf
[574]2361        mBspStats.accumRays += (int)data.mRays->size();
[463]2362
[437]2363        if (data.mPvs < mTermMinPvs)
[574]2364                ++ mBspStats.minPvsNodes;
[437]2365
2366        if ((int)data.mRays->size() < mTermMinRays)
[574]2367                ++ mBspStats.minRaysNodes;
[437]2368
2369        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
[574]2370                ++ mBspStats.maxRayContribNodes;
[482]2371
[547]2372        if (data.mProbability <= mTermMinProbability)
[574]2373                ++ mBspStats.minProbabilityNodes;
[508]2374       
[474]2375        // accumulate depth to compute average depth
[574]2376        mBspStats.accumDepth += data.mDepth;
[463]2377
[612]2378        ++ mCreatedViewCells;
[656]2379
[463]2380#ifdef _DEBUG
2381        Debug << "BSP stats: "
2382                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
2383                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
[587]2384          //              << "Area: " << data.mProbability << " (min: " << mTermMinProbability << "), "
[482]2385                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
[463]2386                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
2387                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
2388#endif
2389}
2390
[612]2391
[463]2392int VspBspTree::CastRay(Ray &ray)
2393{
2394        int hits = 0;
[482]2395
[600]2396        stack<BspRayTraversalData> tQueue;
[482]2397
[463]2398        float maxt, mint;
2399
2400        if (!mBox.GetRaySegment(ray, mint, maxt))
2401                return 0;
2402
2403        Intersectable::NewMail();
[600]2404        ViewCell::NewMail();
[1012]2405
[463]2406        Vector3 entp = ray.Extrap(mint);
2407        Vector3 extp = ray.Extrap(maxt);
[482]2408
[463]2409        BspNode *node = mRoot;
2410        BspNode *farChild = NULL;
[482]2411
[463]2412        while (1)
2413        {
[482]2414                if (!node->IsLeaf())
[463]2415                {
2416                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2417
2418                        Plane3 splitPlane = in->GetPlane();
2419                        const int entSide = splitPlane.Side(entp);
2420                        const int extSide = splitPlane.Side(extp);
2421
2422                        if (entSide < 0)
2423                        {
2424                                node = in->GetBack();
2425
2426                                if(extSide <= 0) // plane does not split ray => no far child
2427                                        continue;
[482]2428
[463]2429                                farChild = in->GetFront(); // plane splits ray
2430
2431                        } else if (entSide > 0)
2432                        {
2433                                node = in->GetFront();
2434
2435                                if (extSide >= 0) // plane does not split ray => no far child
2436                                        continue;
2437
[482]2438                                farChild = in->GetBack(); // plane splits ray
[463]2439                        }
2440                        else // ray and plane are coincident
2441                        {
[1012]2442                                // matt: WHAT TO DO IN THIS CASE ?
[463]2443                                //break;
2444                                node = in->GetFront();
2445                                continue;
2446                        }
2447
2448                        // push data for far child
[600]2449                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
[463]2450
2451                        // find intersection of ray segment with plane
2452                        float t;
2453                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2454                        maxt *= t;
[482]2455
[463]2456                } else // reached leaf => intersection with view cell
2457                {
2458                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
[482]2459
[463]2460                        if (!leaf->GetViewCell()->Mailed())
2461                        {
2462                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2463                                leaf->GetViewCell()->Mail();
2464                                ++ hits;
2465                        }
[482]2466
[463]2467                        //-- fetch the next far child from the stack
[600]2468                        if (tQueue.empty())
[463]2469                                break;
[482]2470
[463]2471                        entp = extp;
2472                        mint = maxt; // NOTE: need this?
2473
2474                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2475                                break;
2476
[600]2477                        BspRayTraversalData &s = tQueue.top();
[463]2478
2479                        node = s.mNode;
2480                        extp = s.mExitPoint;
2481                        maxt = s.mMaxT;
2482
[600]2483                        tQueue.pop();
[463]2484                }
2485        }
2486
2487        return hits;
2488}
2489
[532]2490
[547]2491void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
[463]2492{
[532]2493        ViewCell::NewMail();
[551]2494       
2495        CollectViewCells(mRoot, onlyValid, viewCells, true);
[532]2496}
2497
2498
[574]2499void VspBspTree::CollapseViewCells()
[542]2500{
[590]2501// TODO
[728]2502#if HAS_TO_BE_REDONE
[542]2503        stack<BspNode *> nodeStack;
2504
2505        if (!mRoot)
2506                return;
2507
2508        nodeStack.push(mRoot);
2509       
2510        while (!nodeStack.empty())
2511        {
2512                BspNode *node = nodeStack.top();
2513                nodeStack.pop();
2514               
2515                if (node->IsLeaf())
[574]2516        {
2517                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
[542]2518
[574]2519                        if (!viewCell->GetValid())
[542]2520                        {
2521                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
[580]2522       
2523                                ViewCellContainer leaves;
[590]2524                                mViewCellsTree->CollectLeaves(viewCell, leaves);
[580]2525
2526                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2527
2528                                for (it = leaves.begin(); it != it_end; ++ it)
[542]2529                                {
[580]2530                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
[574]2531                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2532                                        ++ mBspStats.invalidLeaves;
2533                                }
[542]2534
[574]2535                                // add to unbounded view cell
2536                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2537                                DEL_PTR(viewCell);
2538                        }
2539                }
2540                else
2541                {
2542                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2543               
2544                        nodeStack.push(interior->GetFront());
2545                        nodeStack.push(interior->GetBack());
2546                }
2547        }
[542]2548
[574]2549        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
[590]2550#endif
[574]2551}
2552
2553
[639]2554void VspBspTree::CollectRays(VssRayContainer &rays)
2555{
2556        vector<BspLeaf *> leaves;
2557
2558        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2559
2560        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2561        {
2562                BspLeaf *leaf = *lit;
2563                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2564
2565                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2566                        rays.push_back(*rit);
2567        }
2568}
2569
2570
[574]2571void VspBspTree::ValidateTree()
2572{
2573        stack<BspNode *> nodeStack;
2574
2575        if (!mRoot)
2576                return;
2577
2578        nodeStack.push(mRoot);
2579       
2580        mBspStats.invalidLeaves = 0;
2581        while (!nodeStack.empty())
2582        {
2583                BspNode *node = nodeStack.top();
2584                nodeStack.pop();
2585               
2586                if (node->IsLeaf())
2587                {
2588                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2589
2590                        if (!leaf->GetViewCell()->GetValid())
2591                                ++ mBspStats.invalidLeaves;
2592
2593                        // validity flags don't match => repair
2594                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2595                        {
2596                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2597                                PropagateUpValidity(leaf);
[542]2598                        }
2599                }
2600                else
2601                {
2602                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2603               
2604                        nodeStack.push(interior->GetFront());
2605                        nodeStack.push(interior->GetBack());
2606                }
2607        }
[562]2608
[574]2609        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
[542]2610}
2611
[547]2612
[574]2613
[547]2614void VspBspTree::CollectViewCells(BspNode *root,
2615                                                                  bool onlyValid,
[532]2616                                                                  ViewCellContainer &viewCells,
2617                                                                  bool onlyUnmailed) const
2618{
[498]2619        stack<BspNode *> nodeStack;
[463]2620
[538]2621        if (!root)
[508]2622                return;
[463]2623
[538]2624        nodeStack.push(root);
[498]2625       
2626        while (!nodeStack.empty())
2627        {
2628                BspNode *node = nodeStack.top();
2629                nodeStack.pop();
2630               
2631                if (node->IsLeaf())
2632                {
[564]2633                        if (!onlyValid || node->TreeValid())
[498]2634                        {
[882]2635                                ViewCellLeaf *leafVc = dynamic_cast<BspLeaf *>(node)->GetViewCell();
[727]2636
2637                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
[590]2638                                               
[532]2639                                if (!onlyUnmailed || !viewCell->Mailed())
[498]2640                                {
2641                                        viewCell->Mail();
2642                                        viewCells.push_back(viewCell);
2643                                }
2644                        }
2645                }
2646                else
2647                {
2648                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
[508]2649               
[498]2650                        nodeStack.push(interior->GetFront());
2651                        nodeStack.push(interior->GetBack());
2652                }
2653        }
[590]2654
[463]2655}
2656
2657
[648]2658void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2659{
2660        // preprocess: throw out polygons coincident to the view space box (not needed)
2661        PolygonContainer boxPolys;
[1002]2662        /*mBox.ExtractPolys(boxPolys);
[648]2663        vector<Plane3> boxPlanes;
2664
2665        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2666
2667        // extract planes of box
2668        // TODO: can be done more elegantly than first extracting polygons
2669        // and take their planes
2670        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2671        {
2672                boxPlanes.push_back((*pit)->GetSupportingPlane());
2673        }
2674
2675        pit_end = polys.end();
2676
2677        for (pit = polys.begin(); pit != pit_end; ++ pit)
2678        {
2679                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2680               
2681                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2682                {
2683                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2684
2685                        if (cf == Polygon3::COINCIDENT)
2686                        {
2687                                DEL_PTR(*pit);
2688                                //Debug << "coincident!!" << endl;
2689                        }
2690                }
2691        }
2692
[1002]2693        // remove deleted entries after swapping them to end of vector
[648]2694        for (int i = 0; i < (int)polys.size(); ++ i)
2695        {
2696                while (!polys[i] && (i < (int)polys.size()))
2697                {
2698                        swap(polys[i], polys.back());
2699                        polys.pop_back();
2700                }
[1002]2701        }*/
[648]2702}
2703
2704
[463]2705float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2706{
2707        float len = 0;
2708
2709        RayInfoContainer::const_iterator it, it_end = rays.end();
2710
2711        for (it = rays.begin(); it != it_end; ++ it)
2712                len += (*it).SegmentLength();
2713
2714        return len;
2715}
2716
[479]2717
[463]2718int VspBspTree::SplitRays(const Plane3 &plane,
[482]2719                                                  RayInfoContainer &rays,
2720                                                  RayInfoContainer &frontRays,
[639]2721                                                  RayInfoContainer &backRays) const
[463]2722{
2723        int splits = 0;
2724
[574]2725        RayInfoContainer::const_iterator it, it_end = rays.end();
2726
2727        for (it = rays.begin(); it != it_end; ++ it)
[463]2728        {
[574]2729                RayInfo bRay = *it;
2730               
[463]2731                VssRay *ray = bRay.mRay;
[473]2732                float t;
[463]2733
[485]2734                // get classification and receive new t
[463]2735                const int cf = bRay.ComputeRayIntersection(plane, t);
[482]2736
[463]2737                switch (cf)
2738                {
2739                case -1:
2740                        backRays.push_back(bRay);
2741                        break;
2742                case 1:
2743                        frontRays.push_back(bRay);
2744                        break;
[482]2745                case 0:
2746                        {
[485]2747                                //-- split ray
[639]2748                                //   test if start point behind or in front of plane
[485]2749                                const int side = plane.Side(bRay.ExtrapOrigin());
2750
[1011]2751                                ++ splits;
2752
[485]2753                                if (side <= 0)
2754                                {
2755                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2756                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2757                                }
2758                                else
2759                                {
2760                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2761                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2762                                }
[463]2763                        }
2764                        break;
2765                default:
[485]2766                        Debug << "Should not come here" << endl;
[463]2767                        break;
2768                }
2769        }
2770
2771        return splits;
2772}
2773
[479]2774
[463]2775void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2776{
2777        BspNode *lastNode;
2778
2779        do
2780        {
2781                lastNode = n;
2782
2783                // want to get planes defining geometry of this node => don't take
2784                // split plane of node itself
2785                n = n->GetParent();
[482]2786
[463]2787                if (n)
2788                {
2789                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2790                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2791
[683]2792            if (interior->GetBack() != lastNode)
[463]2793                                halfSpace.ReverseOrientation();
2794
2795                        halfSpaces.push_back(halfSpace);
2796                }
2797        }
2798        while (n);
2799}
2800
[485]2801
[482]2802void VspBspTree::ConstructGeometry(BspNode *n,
[503]2803                                                                   BspNodeGeometry &geom) const
[463]2804{
[437]2805        vector<Plane3> halfSpaces;
2806        ExtractHalfSpaces(n, halfSpaces);
2807
2808        PolygonContainer candidatePolys;
[678]2809        vector<Plane3> candidatePlanes;
[437]2810
[719]2811        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2812
[683]2813        // bounded planes are added to the polygons
[719]2814        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
[437]2815        {
[719]2816                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
[482]2817
[448]2818                if (p->Valid(mEpsilon))
[437]2819                {
[683]2820                        candidatePolys.push_back(p);
[719]2821                        candidatePlanes.push_back(*pit);
[437]2822                }
2823        }
2824
2825        // add faces of bounding box (also could be faces of the cell)
2826        for (int i = 0; i < 6; ++ i)
2827        {
2828                VertexContainer vertices;
[482]2829
[437]2830                for (int j = 0; j < 4; ++ j)
2831                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2832
[678]2833                Polygon3 *poly = new Polygon3(vertices);
2834
2835                candidatePolys.push_back(poly);
2836                candidatePlanes.push_back(poly->GetSupportingPlane());
[437]2837        }
2838
2839        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2840        {
2841                // polygon is split by all other planes
2842                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2843                {
2844                        if (i == j) // polygon and plane are coincident
2845                                continue;
2846
2847                        VertexContainer splitPts;
2848                        Polygon3 *frontPoly, *backPoly;
2849
[482]2850                        const int cf =
[448]2851                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2852                                                                                                 mEpsilon);
[482]2853
[437]2854                        switch (cf)
2855                        {
2856                                case Polygon3::SPLIT:
2857                                        frontPoly = new Polygon3();
2858                                        backPoly = new Polygon3();
2859
[482]2860                                        candidatePolys[i]->Split(halfSpaces[j],
2861                                                                                         *frontPoly,
[448]2862                                                                                         *backPoly,
2863                                                                                         mEpsilon);
[437]2864
2865                                        DEL_PTR(candidatePolys[i]);
2866
[683]2867                                        if (backPoly->Valid(mEpsilon))
2868                                                candidatePolys[i] = backPoly;
[437]2869                                        else
[683]2870                                                DEL_PTR(backPoly);
[437]2871
[683]2872                                        // outside, don't need this
2873                                        DEL_PTR(frontPoly);
[437]2874                                        break;
[683]2875                                // polygon outside of halfspace
2876                                case Polygon3::FRONT_SIDE:
[437]2877                                        DEL_PTR(candidatePolys[i]);
2878                                        break;
2879                                // just take polygon as it is
[683]2880                                case Polygon3::BACK_SIDE:
[437]2881                                case Polygon3::COINCIDENT:
2882                                default:
2883                                        break;
2884                        }
2885                }
[482]2886
[437]2887                if (candidatePolys[i])
[678]2888                {
2889                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2890                        //      geom.mPolys.push_back(candidates[i]);
2891                }
[437]2892        }
[463]2893}
2894
[485]2895
[582]2896void VspBspTree::ConstructGeometry(ViewCell *vc,
[503]2897                                                                   BspNodeGeometry &vcGeom) const
[589]2898{
[580]2899        ViewCellContainer leaves;
[590]2900       
2901        mViewCellsTree->CollectLeaves(vc, leaves);
[463]2902
[580]2903        ViewCellContainer::const_iterator it, it_end = leaves.end();
2904
[463]2905        for (it = leaves.begin(); it != it_end; ++ it)
[580]2906        {
2907                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
[590]2908               
[580]2909                ConstructGeometry(l, vcGeom);
2910        }
[463]2911}
2912
[485]2913
[482]2914int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
[562]2915                                                          const bool onlyUnmailed) const
[463]2916{
[551]2917        stack<bspNodePair> nodeStack;
2918       
2919        BspNodeGeometry nodeGeom;
2920        ConstructGeometry(n, nodeGeom);
[801]2921//      const float eps = 0.5f;
[752]2922        const float eps = 0.01f;
[500]2923        // split planes from the root to this node
2924        // needed to verify that we found neighbor leaf
[557]2925        // TODO: really needed?
[463]2926        vector<Plane3> halfSpaces;
2927        ExtractHalfSpaces(n, halfSpaces);
2928
[551]2929
2930        BspNodeGeometry *rgeom = new BspNodeGeometry();
2931        ConstructGeometry(mRoot, *rgeom);
2932
2933        nodeStack.push(bspNodePair(mRoot, rgeom));
2934
[482]2935        while (!nodeStack.empty())
[463]2936        {
[551]2937                BspNode *node = nodeStack.top().first;
2938                BspNodeGeometry *geom = nodeStack.top().second;
[562]2939       
[463]2940                nodeStack.pop();
2941
[557]2942                if (node->IsLeaf())
[562]2943                {
[557]2944                        // test if this leaf is in valid view space
2945                        if (node->TreeValid() &&
2946                                (node != n) &&
2947                                (!onlyUnmailed || !node->Mailed()))
2948                        {
2949                                bool isAdjacent = true;
[551]2950
[570]2951                                if (1)
[557]2952                                {
[562]2953                                        // test all planes of current node if still adjacent
2954                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2955                                        {
2956                                                const int cf =
[678]2957                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
[562]2958                                                                                                        halfSpaces[i],
[752]2959                                                                                                        eps);
[482]2960
[683]2961                                                if (cf == Polygon3::FRONT_SIDE)
[562]2962                                                {
2963                                                        isAdjacent = false;
2964                                                }
[557]2965                                        }
2966                                }
[562]2967                                else
[557]2968                                {
[562]2969                                        // TODO: why is this wrong??
2970                                        // test all planes of current node if still adjacent
[678]2971                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
[562]2972                                        {
[678]2973                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
[555]2974
[562]2975                                                const int cf =
[678]2976                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
[562]2977                                                                                                        poly->GetSupportingPlane(),
[752]2978                                                                                                        eps);
[557]2979
[683]2980                                                if (cf == Polygon3::FRONT_SIDE)
[562]2981                                                {
2982                                                        isAdjacent = false;
2983                                                }
[557]2984                                        }
[570]2985                                }
[557]2986                                // neighbor was found
2987                                if (isAdjacent)
[562]2988                                {       
[551]2989                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
[562]2990                                }
[463]2991                        }
[562]2992                }
2993                else
2994                {
2995                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
[482]2996
[678]2997                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
[562]2998                                                                                                   interior->GetPlane(),
[752]2999                                                                                                   eps);
[551]3000                       
[562]3001                        BspNode *front = interior->GetFront();
3002                        BspNode *back = interior->GetBack();
[551]3003           
[562]3004                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3005                        BspNodeGeometry *bGeom = new BspNodeGeometry();
[463]3006
[562]3007                        geom->SplitGeometry(*fGeom,
3008                                                                *bGeom,
3009                                                                interior->GetPlane(),
3010                                                                mBox,
[675]3011                                                                //0.0000001f);
[752]3012                                                                eps);
[551]3013               
[683]3014                        if (cf == Polygon3::BACK_SIDE)
[562]3015                        {
[683]3016                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3017                                DEL_PTR(fGeom);
[562]3018                        }
3019                        else
3020                        {
[683]3021                                if (cf == Polygon3::FRONT_SIDE)
[551]3022                                {
[683]3023                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3024                                        DEL_PTR(bGeom);
[551]3025                                }
[482]3026                                else
[562]3027                                {       // random decision
3028                                        nodeStack.push(bspNodePair(front, fGeom));
3029                                        nodeStack.push(bspNodePair(back, bGeom));
[463]3030                                }
[551]3031                        }
[463]3032                }
[562]3033       
[551]3034                DEL_PTR(geom);
[463]3035        }
[482]3036
[463]3037        return (int)neighbors.size();
3038}
3039
[489]3040
[600]3041
[710]3042int VspBspTree::FindApproximateNeighbors(BspNode *n,
3043                                                                                 vector<BspLeaf *> &neighbors,
[600]3044                                                                                 const bool onlyUnmailed) const
3045{
3046        stack<bspNodePair> nodeStack;
3047       
3048        BspNodeGeometry nodeGeom;
3049        ConstructGeometry(n, nodeGeom);
3050       
[752]3051        float eps = 0.01f;
[600]3052        // split planes from the root to this node
3053        // needed to verify that we found neighbor leaf
3054        // TODO: really needed?
3055        vector<Plane3> halfSpaces;
3056        ExtractHalfSpaces(n, halfSpaces);
3057
3058
3059        BspNodeGeometry *rgeom = new BspNodeGeometry();
3060        ConstructGeometry(mRoot, *rgeom);
3061
3062        nodeStack.push(bspNodePair(mRoot, rgeom));
3063
3064        while (!nodeStack.empty())
3065        {
3066                BspNode *node = nodeStack.top().first;
3067                BspNodeGeometry *geom = nodeStack.top().second;
3068       
3069                nodeStack.pop();
3070
3071                if (node->IsLeaf())
3072                {
3073                        // test if this leaf is in valid view space
3074                        if (node->TreeValid() &&
3075                                (node != n) &&
3076                                (!onlyUnmailed || !node->Mailed()))
3077                        {
3078                                bool isAdjacent = true;
3079
3080                                // neighbor was found
3081                                if (isAdjacent)
3082                                {       
3083                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
3084                                }
3085                        }
3086                }
3087                else
3088                {
3089                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3090
[678]3091                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
[600]3092                                                                                                   interior->GetPlane(),
[752]3093                                                                                                   eps);
[600]3094                       
3095                        BspNode *front = interior->GetFront();
3096                        BspNode *back = interior->GetBack();
3097           
3098                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3099                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3100
3101                        geom->SplitGeometry(*fGeom,
3102                                                                *bGeom,
3103                                                                interior->GetPlane(),
3104                                                                mBox,
[675]3105                                                                //0.0000001f);
[752]3106                                                                eps);
[600]3107               
[683]3108                        if (cf == Polygon3::BACK_SIDE)
[600]3109                        {
[683]3110                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3111                                DEL_PTR(fGeom);
[710]3112                                }
[600]3113                        else
3114                        {
[683]3115                                if (cf == Polygon3::FRONT_SIDE)
[600]3116                                {
[683]3117                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3118                                        DEL_PTR(bGeom);
[600]3119                                }
3120                                else
3121                                {       // random decision
3122                                        nodeStack.push(bspNodePair(front, fGeom));
3123                                        nodeStack.push(bspNodePair(back, bGeom));
3124                                }
3125                        }
3126                }
3127       
3128                DEL_PTR(geom);
3129        }
3130
3131        return (int)neighbors.size();
3132}
3133
3134
3135
[463]3136BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
3137{
3138    stack<BspNode *> nodeStack;
3139        nodeStack.push(mRoot);
[482]3140
[463]3141        int mask = rand();
[482]3142
3143        while (!nodeStack.empty())
[463]3144        {
3145                BspNode *node = nodeStack.top();
3146                nodeStack.pop();
[482]3147
3148                if (node->IsLeaf())
[463]3149                {
3150                        return dynamic_cast<BspLeaf *>(node);
[482]3151                }
3152                else
[463]3153                {
3154                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3155                        BspNode *next;
[503]3156                        BspNodeGeometry geom;
[482]3157
[463]3158                        // todo: not very efficient: constructs full cell everytime
[498]3159                        ConstructGeometry(interior, geom);
[463]3160
[503]3161                        const int cf =
[678]3162                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
[463]3163
3164                        if (cf == Polygon3::BACK_SIDE)
3165                                next = interior->GetFront();
3166                        else
3167                                if (cf == Polygon3::FRONT_SIDE)
3168                                        next = interior->GetFront();
[482]3169                        else
[463]3170                        {
3171                                // random decision
3172                                if (mask & 1)
3173                                        next = interior->GetBack();
3174                                else
3175                                        next = interior->GetFront();
3176                                mask = mask >> 1;
3177                        }
3178
3179                        nodeStack.push(next);
3180                }
3181        }
[482]3182
[463]3183        return NULL;
3184}
3185
[694]3186
[463]3187BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3188{
3189        stack<BspNode *> nodeStack;
[482]3190
[463]3191        nodeStack.push(mRoot);
3192
3193        int mask = rand();
[482]3194
3195        while (!nodeStack.empty())
[463]3196        {
3197                BspNode *node = nodeStack.top();
3198                nodeStack.pop();
[482]3199
3200                if (node->IsLeaf())
[463]3201                {
3202                        if ( (!onlyUnmailed || !node->Mailed()) )
3203                                return dynamic_cast<BspLeaf *>(node);
3204                }
[482]3205                else
[463]3206                {
3207                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3208
3209                        // random decision
3210                        if (mask & 1)
3211                                nodeStack.push(interior->GetBack());
3212                        else
3213                                nodeStack.push(interior->GetFront());
3214
3215                        mask = mask >> 1;
3216                }
3217        }
[482]3218
[463]3219        return NULL;
3220}
3221
[694]3222
[463]3223int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3224{
3225        int pvsSize = 0;
3226
3227        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3228
3229        Intersectable::NewMail();
3230
3231        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3232        {
3233                VssRay *ray = (*rit).mRay;
[482]3234
[1020]3235                if (COUNT_ORIGIN_OBJECTS && ray->mOriginObject)
[463]3236                {
3237                        if (!ray->mOriginObject->Mailed())
3238                        {
3239                                ray->mOriginObject->Mail();
3240                                ++ pvsSize;
3241                        }
3242                }
[1020]3243
[463]3244                if (ray->mTerminationObject)
3245                {
3246                        if (!ray->mTerminationObject->Mailed())
3247                        {
3248                                ray->mTerminationObject->Mail();
3249                                ++ pvsSize;
3250                        }
3251                }
3252        }
3253
3254        return pvsSize;
3255}
3256
[694]3257
[463]3258float VspBspTree::GetEpsilon() const
3259{
3260        return mEpsilon;
3261}
3262
3263
3264int VspBspTree::SplitPolygons(const Plane3 &plane,
[482]3265                                                          PolygonContainer &polys,
3266                                                          PolygonContainer &frontPolys,
3267                                                          PolygonContainer &backPolys,
[463]3268                                                          PolygonContainer &coincident) const
3269{
3270        int splits = 0;
3271
[574]3272        PolygonContainer::const_iterator it, it_end = polys.end();
3273
3274        for (it = polys.begin(); it != polys.end(); ++ it)     
[463]3275        {
[574]3276                Polygon3 *poly = *it;
[463]3277
3278                // classify polygon
3279                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3280
3281                switch (cf)
3282                {
3283                        case Polygon3::COINCIDENT:
3284                                coincident.push_back(poly);
[482]3285                                break;
3286                        case Polygon3::FRONT_SIDE:
[463]3287                                frontPolys.push_back(poly);
3288                                break;
3289                        case Polygon3::BACK_SIDE:
3290                                backPolys.push_back(poly);
3291                                break;
3292                        case Polygon3::SPLIT:
3293                                backPolys.push_back(poly);
3294                                frontPolys.push_back(poly);
3295                                ++ splits;
3296                                break;
3297                        default:
3298                Debug << "SHOULD NEVER COME HERE\n";
3299                                break;
3300                }
3301        }
3302
3303        return splits;
3304}
[466]3305
3306
[469]3307int VspBspTree::CastLineSegment(const Vector3 &origin,
3308                                                                const Vector3 &termination,
[882]3309                                                                ViewCellContainer &viewcells)
[466]3310{
[469]3311        int hits = 0;
[719]3312        stack<BspRayTraversalData> tStack;
[482]3313
[469]3314        float mint = 0.0f, maxt = 1.0f;
[482]3315
[469]3316        Intersectable::NewMail();
[600]3317        ViewCell::NewMail();
[482]3318
[469]3319        Vector3 entp = origin;
3320        Vector3 extp = termination;
[482]3321
[469]3322        BspNode *node = mRoot;
3323        BspNode *farChild = NULL;
[482]3324
[485]3325        float t;
[752]3326        const float thresh = 1e-6f; // matt: change this to adjustable value
[694]3327       
[482]3328        while (1)
[469]3329        {
[482]3330                if (!node->IsLeaf())
[469]3331                {
3332                        BspInterior *in = dynamic_cast<BspInterior *>(node);
[482]3333
[469]3334                        Plane3 splitPlane = in->GetPlane();
[485]3335                       
[666]3336                        const int entSide = splitPlane.Side(entp, thresh);
3337                        const int extSide = splitPlane.Side(extp, thresh);
[482]3338
[485]3339                        if (entSide < 0)
[469]3340                        {
[666]3341                                node = in->GetBack();
3342                               
3343                                // plane does not split ray => no far child
3344                                if (extSide <= 0)
3345                                        continue;
3346 
3347                                farChild = in->GetFront(); // plane splits ray
[485]3348                        }
3349                        else if (entSide > 0)
[469]3350                        {
[666]3351                                node = in->GetFront();
[482]3352
[666]3353                                if (extSide >= 0) // plane does not split ray => no far child
3354                                        continue;
[482]3355
3356                                farChild = in->GetBack(); // plane splits ray
[469]3357                        }
[694]3358                        else // one of the ray end points is on the plane
[1020]3359                        {       
3360                                // NOTE: what to do if ray is coincident with plane?
[485]3361                                if (extSide < 0)
3362                                        node = in->GetBack();
[694]3363                                else //if (extSide > 0)
[485]3364                                        node = in->GetFront();
[694]3365                                //else break; // coincident => count no intersections
3366
[485]3367                                continue; // no far child
[469]3368                        }
[482]3369
[469]3370                        // push data for far child
[719]3371                        tStack.push(BspRayTraversalData(farChild, extp));
[482]3372
[469]3373                        // find intersection of ray segment with plane
3374                        extp = splitPlane.FindIntersection(origin, extp, &t);
[485]3375                }
3376                else
[469]3377                {
3378                        // reached leaf => intersection with view cell
3379                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
[666]3380                        ViewCell *viewCell;
3381                       
[1020]3382                        // question: always contribute to leaf or to currently active view cell?
[708]3383                        if (0)
3384                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3385                        else
3386                                viewCell = leaf->GetViewCell();
[482]3387
[590]3388                        if (!viewCell->Mailed())
[469]3389                        {
[590]3390                                viewcells.push_back(viewCell);
3391                                viewCell->Mail();
[469]3392                                ++ hits;
3393                        }
[482]3394
[469]3395                        //-- fetch the next far child from the stack
[719]3396                        if (tStack.empty())
[469]3397                                break;
[482]3398
[469]3399                        entp = extp;
[485]3400                       
[719]3401                        const BspRayTraversalData &s = tStack.top();
[482]3402
[469]3403                        node = s.mNode;
3404                        extp = s.mExitPoint;
[482]3405
[719]3406                        tStack.pop();
[469]3407                }
[466]3408        }
[487]3409
[469]3410        return hits;
[466]3411}
[478]3412
[576]3413
3414
3415
[485]3416int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
[482]3417{
3418        std::deque<BspNode *> path1;
3419        BspNode *p1 = n1;
[479]3420
[482]3421        // create path from node 1 to root
3422        while (p1)
3423        {
3424                if (p1 == n2) // second node on path
3425                        return (int)path1.size();
3426
3427                path1.push_front(p1);
3428                p1 = p1->GetParent();
3429        }
3430
3431        int depth = n2->GetDepth();
3432        int d = depth;
3433
3434        BspNode *p2 = n2;
3435
3436        // compare with same depth
3437        while (1)
3438        {
3439                if ((d < (int)path1.size()) && (p2 == path1[d]))
3440                        return (depth - d) + ((int)path1.size() - 1 - d);
3441
3442                -- d;
3443                p2 = p2->GetParent();
3444        }
3445
3446        return 0; // never come here
3447}
3448
[580]3449
[501]3450BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
[479]3451{
[590]3452// TODO
[728]3453#if HAS_TO_BE_REDONE
[495]3454        if (node->IsLeaf())
[479]3455                return node;
3456
[492]3457        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3458
[501]3459        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3460        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
[492]3461
[479]3462        if (front->IsLeaf() && back->IsLeaf())
3463        {
3464                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
3465                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
3466
3467                //-- collapse tree
3468                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3469                {
3470                        BspViewCell *vc = frontLeaf->GetViewCell();
3471
3472                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
[489]3473                        leaf->SetTreeValid(frontLeaf->TreeValid());
[482]3474
[479]3475                        // replace a link from node's parent
3476                        if (leaf->GetParent())
3477                                leaf->GetParent()->ReplaceChildLink(node, leaf);
[517]3478                        else
3479                                mRoot = leaf;
3480
[501]3481                        ++ collapsed;
[479]3482                        delete interior;
3483
3484                        return leaf;
3485                }
3486        }
[590]3487#endif
[495]3488        return node;
3489}
3490
3491
[501]3492int VspBspTree::CollapseTree()
[495]3493{
[501]3494        int collapsed = 0;
[580]3495        //TODO
[728]3496#if HAS_TO_BE_REDONE
[501]3497        (void)CollapseTree(mRoot, collapsed);
[517]3498
[485]3499        // revalidate leaves
[517]3500        RepairViewCellsLeafLists();
[580]3501#endif
[501]3502        return collapsed;
[479]3503}
3504
3505
[517]3506void VspBspTree::RepairViewCellsLeafLists()
[492]3507{
[590]3508// TODO
[728]3509#if HAS_TO_BE_REDONE
[479]3510        // list not valid anymore => clear
[492]3511        stack<BspNode *> nodeStack;
3512        nodeStack.push(mRoot);
3513
3514        ViewCell::NewMail();
3515
3516        while (!nodeStack.empty())
3517        {
3518                BspNode *node = nodeStack.top();
3519                nodeStack.pop();
3520
3521                if (node->IsLeaf())
3522                {
3523                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3524
3525                        BspViewCell *viewCell = leaf->GetViewCell();
[590]3526
[492]3527                        if (!viewCell->Mailed())
3528                        {
3529                                viewCell->mLeaves.clear();
3530                                viewCell->Mail();
3531                        }
[580]3532       
[492]3533                        viewCell->mLeaves.push_back(leaf);
[590]3534
[492]3535                }
3536                else
3537                {
3538                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3539
3540                        nodeStack.push(interior->GetFront());
3541                        nodeStack.push(interior->GetBack());
3542                }
[479]3543        }
[590]3544// TODO
3545#endif
[479]3546}
3547
3548
[532]3549int VspBspTree::CastBeam(Beam &beam)
3550{
3551    stack<bspNodePair> nodeStack;
3552        BspNodeGeometry *rgeom = new BspNodeGeometry();
3553        ConstructGeometry(mRoot, *rgeom);
3554
3555        nodeStack.push(bspNodePair(mRoot, rgeom));
3556 
3557        ViewCell::NewMail();
3558
3559        while (!nodeStack.empty())
3560        {
3561                BspNode *node = nodeStack.top().first;
3562                BspNodeGeometry *geom = nodeStack.top().second;
3563                nodeStack.pop();
3564               
3565                AxisAlignedBox3 box;
[697]3566                geom->GetBoundingBox(box);
[532]3567
[535]3568                const int side = beam.ComputeIntersection(box);
[532]3569               
3570                switch (side)
3571                {
3572                case -1:
[547]3573                        CollectViewCells(node, true, beam.mViewCells, true);
[532]3574                        break;
3575                case 0:
[535]3576                       
[532]3577                        if (node->IsLeaf())
3578                        {
[535]3579                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3580                       
[532]3581                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
[535]3582                                {
3583                                        leaf->GetViewCell()->Mail();
[532]3584                                        beam.mViewCells.push_back(leaf->GetViewCell());
[535]3585                                }
[532]3586                        }
3587                        else
3588                        {
3589                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
[535]3590                       
[538]3591                                BspNode *first = interior->GetFront();
3592                                BspNode *second = interior->GetBack();
[535]3593           
3594                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3595                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3596
[538]3597                                geom->SplitGeometry(*firstGeom,
3598                                                                        *secondGeom,
3599                                                                        interior->GetPlane(),
3600                                                                        mBox,
[675]3601                                                                        //0.0000001f);
[538]3602                                                                        mEpsilon);
[535]3603
[532]3604                                // decide on the order of the nodes
3605                                if (DotProd(beam.mPlanes[0].mNormal,
3606                                        interior->GetPlane().mNormal) > 0)
3607                                {
3608                                        swap(first, second);
[535]3609                                        swap(firstGeom, secondGeom);
[532]3610                                }
3611
[535]3612                                nodeStack.push(bspNodePair(first, firstGeom));
3613                                nodeStack.push(bspNodePair(second, secondGeom));
[532]3614                        }
[535]3615                       
[532]3616                        break;
[538]3617                default:
[532]3618                        // default: cull
[538]3619                        break;
[532]3620                }
[538]3621               
[532]3622                DEL_PTR(geom);
[535]3623               
[532]3624        }
3625
[538]3626        return (int)beam.mViewCells.size();
[532]3627}
3628
3629
[485]3630void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
[478]3631{
[485]3632        mViewCellsManager = vcm;
3633}
3634
3635
[580]3636int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3637                                                                           vector<MergeCandidate> &candidates)
[485]3638{
[478]3639        BspLeaf::NewMail();
[508]3640       
[478]3641        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3642
[580]3643        int numCandidates = 0;
[509]3644
[478]3645        // find merge candidates and push them into queue
3646        for (it = leaves.begin(); it != it_end; ++ it)
3647        {
3648                BspLeaf *leaf = *it;
[485]3649               
3650                // the same leaves must not be part of two merge candidates
3651                leaf->Mail();
[650]3652               
[485]3653                vector<BspLeaf *> neighbors;
[710]3654               
3655                // appoximate neighbor search has slightl relaxed constraints
[694]3656                if (1)
[650]3657                        FindNeighbors(leaf, neighbors, true);
3658                else
3659                        FindApproximateNeighbors(leaf, neighbors, true);
[710]3660
[485]3661                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3662
3663                // TODO: test if at least one ray goes from one leaf to the other
3664                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
[508]3665                {
3666                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
[509]3667                        {
[580]3668                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
[564]3669
[1006]3670                                if (!leaf->GetViewCell()->GetPvs().Empty() ||
[710]3671                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
[676]3672                    leaf->IsSibling(*nit))
3673                                {
3674                                        candidates.push_back(mc);
3675                                }
3676
[580]3677                                ++ numCandidates;
3678                                if ((numCandidates % 1000) == 0)
[566]3679                                {
[580]3680                                        cout << "collected " << numCandidates << " merge candidates" << endl;
[566]3681                                }
[509]3682                        }
[485]3683                }
3684        }
3685
[580]3686        Debug << "merge queue: " << (int)candidates.size() << endl;
3687        Debug << "leaves in queue: " << numCandidates << endl;
3688       
[508]3689
[485]3690        return (int)leaves.size();
3691}
3692
3693
[580]3694int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3695                                                                           vector<MergeCandidate> &candidates)
[485]3696{
[547]3697        ViewCell::NewMail();
[503]3698        long startTime = GetTime();
[574]3699       
[485]3700        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
[574]3701        ViewCellContainer::const_iterator iit;
[485]3702
[503]3703        int numLeaves = 0;
[485]3704       
3705        BspLeaf::NewMail();
3706
[574]3707        for (int i = 0; i < (int)rays.size(); ++ i)
[485]3708        { 
[574]3709                VssRay *ray = rays[i];
[547]3710       
[485]3711                // traverse leaves stored in the rays and compare and
3712                // merge consecutive leaves (i.e., the neighbors in the tree)
[574]3713                if (ray->mViewCells.size() < 2)
[485]3714                        continue;
[580]3715//TODO viewcellhierarchy
[574]3716                iit = ray->mViewCells.begin();
3717                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
[580]3718                BspLeaf *leaf = bspVc->mLeaf;
[485]3719               
3720                // traverse intersections
[489]3721                // consecutive leaves are neighbors => add them to queue
[574]3722                for (; iit != ray->mViewCells.end(); ++ iit)
[485]3723                {
[489]3724                        // next pair
3725                        BspLeaf *prevLeaf = leaf;
[574]3726                        bspVc = dynamic_cast<BspViewCell *>(*iit);
[580]3727            leaf = bspVc->mLeaf;
[489]3728
[508]3729                        // view space not valid or same view cell
3730                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3731                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
[489]3732                                continue;
3733
[580]3734                vector<BspLeaf *> &neighbors = neighborMap[leaf];
[485]3735                       
3736                        bool found = false;
[478]3737
[485]3738                        // both leaves inserted in queue already =>
3739                        // look if double pair already exists
3740                        if (leaf->Mailed() && prevLeaf->Mailed())
[478]3741                        {
[485]3742                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3743                               
3744                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3745                                        if (*it == prevLeaf)
3746                                                found = true; // already in queue
3747                        }
[547]3748               
[485]3749                        if (!found)
3750                        {
[564]3751                                // this pair is not in map yet
[485]3752                                // => insert into the neighbor map and the queue
3753                                neighbors.push_back(prevLeaf);
3754                                neighborMap[prevLeaf].push_back(leaf);
[478]3755
[485]3756                                leaf->Mail();
3757                                prevLeaf->Mail();
[547]3758               
[580]3759                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3760                               
3761                                candidates.push_back(mc);
[564]3762
[580]3763                                if (((int)candidates.size() % 1000) == 0)
[564]3764                                {
[580]3765                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
[564]3766                                }
[478]3767                        }
[485]3768        }
3769        }
[564]3770
[485]3771        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
[580]3772        Debug << "merge queue: " << (int)candidates.size() << endl;
[503]3773        Debug << "leaves in queue: " << numLeaves << endl;
[485]3774
[580]3775
[503]3776        //-- collect the leaves which haven't been found by ray casting
[542]3777        if (0)
3778        {
[551]3779                cout << "finding additional merge candidates using geometry" << endl;
[542]3780                vector<BspLeaf *> leaves;
[547]3781                CollectLeaves(leaves, true);
[542]3782                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
[580]3783                CollectMergeCandidates(leaves, candidates);
[542]3784        }
[503]3785
3786        return numLeaves;
[485]3787}
3788
3789
3790
3791
[879]3792ViewCell *VspBspTree::GetViewCell(const Vector3 &point, const bool active)
[492]3793{
[879]3794        if (mRoot == NULL)
3795                return NULL;
3796
3797        stack<BspNode *> nodeStack;
3798        nodeStack.push(mRoot);
[492]3799 
[882]3800        ViewCellLeaf *viewcell = NULL;
[492]3801 
[879]3802        while (!nodeStack.empty()) 
3803        {
3804                BspNode *node = nodeStack.top();
3805                nodeStack.pop();
[492]3806       
[879]3807                if (node->IsLeaf())
3808                {
3809                        viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
3810                        break;
3811                }
3812                else   
3813                {       
3814                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3815       
3816                        // random decision
3817                        if (interior->GetPlane().Side(point) < 0)
3818                                nodeStack.push(interior->GetBack());
3819                        else
3820                                nodeStack.push(interior->GetFront());
3821                }
[492]3822        }
3823 
[879]3824        if (active)
3825                return mViewCellsTree->GetActiveViewCell(viewcell);
3826        else
3827                return viewcell;
[492]3828}
3829
3830
[487]3831bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3832{
3833        BspNode *node = mRoot;
[485]3834
[487]3835        while (1)
3836        {
3837                // early exit
3838                if (node->TreeValid())
3839                        return true;
3840
3841                if (node->IsLeaf())
3842                        return false;
3843                       
3844                BspInterior *in = dynamic_cast<BspInterior *>(node);
[490]3845                                       
3846                if (in->GetPlane().Side(viewPoint) <= 0)
[487]3847                {
3848                        node = in->GetBack();
3849                }
3850                else
3851                {
3852                        node = in->GetFront();
3853                }
3854        }
3855
3856        // should never come here
3857        return false;
3858}
3859
3860
3861void VspBspTree::PropagateUpValidity(BspNode *node)
3862{
[574]3863        const bool isValid = node->TreeValid();
3864
3865        // propagative up invalid flag until only invalid nodes exist over this node
3866        if (!isValid)
[487]3867        {
[574]3868                while (!node->IsRoot() && node->GetParent()->TreeValid())
3869                {
3870                        node = node->GetParent();
3871                        node->SetTreeValid(false);
3872                }
[487]3873        }
[574]3874        else
3875        {
3876                // propagative up valid flag until one of the subtrees is invalid
3877                while (!node->IsRoot() && !node->TreeValid())
3878                {
3879            node = node->GetParent();
3880                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3881                       
3882                        // the parent is valid iff both leaves are valid
3883                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3884                                                           interior->GetFront()->TreeValid());
3885                }
3886        }
[487]3887}
3888
[971]3889#if ZIPPED_VIEWCELLS
3890bool VspBspTree::Export(ogzstream &stream)
3891#else
[508]3892bool VspBspTree::Export(ofstream &stream)
[971]3893#endif
[503]3894{
[508]3895        ExportNode(mRoot, stream);
[487]3896
[503]3897        return true;
3898}
3899
[971]3900#if ZIPPED_VIEWCELLS
3901void VspBspTree::ExportNode(BspNode *node, ogzstream &stream)
3902#else
[508]3903void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
[971]3904#endif
[508]3905{
3906        if (node->IsLeaf())
[503]3907        {
[508]3908                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
[590]3909                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3910
[508]3911                int id = -1;
[590]3912                if (viewCell != mOutOfBoundsCell)
3913                        id = viewCell->GetId();
[503]3914
[508]3915                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
[503]3916        }
[508]3917        else
[503]3918        {
[508]3919                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3920       
3921                Plane3 plane = interior->GetPlane();
3922                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3923                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3924                           << plane.mD << "\">" << endl;
[503]3925
[508]3926                ExportNode(interior->GetBack(), stream);
3927                ExportNode(interior->GetFront(), stream);
[503]3928
[508]3929                stream << "</Interior>" << endl;
[503]3930        }
3931}
[860]3932
3933}
Note: See TracBrowser for help on using the repository browser.