source: GTP/trunk/Lib/Vis/Preprocessing/src/GvsPreprocessor.cpp @ 2705

Revision 2705, 36.6 KB checked in by mattausch, 16 years ago (diff)

enabled view cell visualization

  • Property svn:executable set to *
RevLine 
[1460]1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
[1473]4#include "VssRay.h"
5#include "ViewCellsManager.h"
[1486]6#include "Triangle3.h"
[1489]7#include "IntersectableWrapper.h"
[1500]8#include "Plane3.h"
[1521]9#include "RayCaster.h"
[1522]10#include "Exporter.h"
[1545]11#include "SamplingStrategy.h"
[1990]12#include "BvHierarchy.h"
[2116]13#include "Polygon3.h"
[2643]14#include "IntersectableWrapper.h"
[1460]15
[1473]16
[2643]17
[1460]18namespace GtpVisibilityPreprocessor
19{
20 
[2633]21#define GVS_DEBUG 0
[2669]22#define NOT_ACCOUNTED_OBJECT 0
23#define ACCOUNTED_OBJECT 2
[1934]24
[2705]25
[2669]26static const float MIN_DIST = 0.001f;
27
28static ObjectContainer myobjects;
29
30
31/** Visualization structure for the GVS algorithm.
32*/
[1522]33struct VizStruct
34{
35        Polygon3 *enlargedTriangle;
36        Triangle3 originalTriangle;
37        VssRay *ray;
38};
[1460]39
[2669]40static vector<VizStruct> vizContainer;
[2048]41
[1990]42
[1522]43
[2648]44
[1533]45GvsPreprocessor::GvsPreprocessor():
[1545]46Preprocessor(),
[1996]47mProcessedViewCells(0),
[2625]48mCurrentViewCell(NULL),
[2691]49mCurrentViewPoint(Vector3(0.0f, 0.0f, 0.0f)),
50mOnlyRandomSampling(false)
51//mOnlyRandomSampling(true)
[1460]52{
[1486]53        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
54        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
[2048]55        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.gvsSamplesPerPass", mGvsSamplesPerPass);
[1996]56        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.minContribution", mMinContribution);
[1486]57        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
[1500]58        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
[1990]59        Environment::GetSingleton()->GetBoolValue("GvsPreprocessor.perViewCell", mPerViewCell);
[1996]60        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.maxViewCells", mMaxViewCells);
[1473]61
[2048]62        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluatePixelError", mEvaluatePixelError);
63
[2615]64        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
65
66
[1934]67        char gvsStatsLog[100];
68        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
69        mGvsStatsStream.open(gvsStatsLog);
70
[2677]71        cout << "number of gvs samples per pass: " << mGvsSamplesPerPass << endl;
72        cout << "number of samples per pass: " << mSamplesPerPass << endl;
[2691]73        cout << "only random sampling: " << mOnlyRandomSampling << endl;
[2677]74
[1486]75        Debug << "Gvs preprocessor options" << endl;
76        Debug << "number of total samples: " << mTotalSamples << endl;
77        Debug << "number of initial samples: " << mInitialSamples << endl;
[1501]78        Debug << "threshold: " << mThreshold << endl;
[1934]79        Debug << "epsilon: " << mEps << endl;
80        Debug << "stats: " << gvsStatsLog << endl;
[1996]81        Debug << "per view cell: " << mPerViewCell << endl;
82        Debug << "max view cells: " << mMaxViewCells << endl;
83        Debug << "min contribution: " << mMinContribution << endl;
[1486]84
[2691]85        mDistribution = new ViewCellBasedDistribution(*this, NULL);
[1934]86
87        mGvsStats.Reset();
[2643]88
[2695]89        // hack: some generic statistical values that can be used
[2648]90        // by an application using the preprocessor
[2691]91        for (int i = 0; i < 2; ++ i)
92                mGenericStats[i] = 0;
[1460]93}
94
[1473]95
[1990]96GvsPreprocessor::~GvsPreprocessor()
97{
[2691]98        delete mDistribution;
[1996]99        ClearRayQueue();
100}
101
102
103void GvsPreprocessor::ClearRayQueue()
104{
[1990]105        // clean ray queue
106        while (!mRayQueue.empty())
107        {
108                // handle next ray
109                VssRay *ray = mRayQueue.top();
110                mRayQueue.pop();
111
[2695]112                // note: deletion of the ray is handled by ray pool
[1990]113        }
114}
115
116
[2625]117ViewCell *GvsPreprocessor::NextViewCell()
[1982]118{
[1996]119        if (mProcessedViewCells == (int)mViewCells.size())
[2625]120                return NULL; // no more view cells
[1982]121
[2625]122        ViewCell *vc = mViewCells[mProcessedViewCells];
[1982]123
[2625]124   if (!vc->GetMesh())
125                mViewCellsManager->CreateMesh(vc);
[1990]126
[2625]127        mGvsStats.mViewCellId = vc->GetId();
[1996]128
[2625]129        Debug << "vc: " << vc->GetId() << endl;
[1996]130
131        ++ mProcessedViewCells;
[1982]132   
[2625]133        return vc;
[1982]134}
135
136
[1996]137int GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
138                                                                                const Triangle3 &hitTriangle,
139                                                                                const VssRay &oldRay)
[1460]140{
[1932]141        // the predicted hitpoint: we expect to hit the same mesh again
142        const Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
143
144        const float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
145        const float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
146       
[2695]147#if 1
[1932]148        // distance large => this is likely to be a discontinuity
149        if ((predictedLen - len) > mThreshold)
[2695]150#else
151        // q: rather use relative distance?
[1933]152        if ((predictedLen / len) > mThreshold)
153#endif
[1500]154        {
[1933]155                // apply reverse sampling to find the gap
[1500]156                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
[1933]157
[2695]158                // check if reverse sampling was successful
159                if (newRay)
160                {
161                        // set flag for visualization
162                        if (0) newRay->mFlags |= VssRay::ReverseSample;
163               
164                        // check if ray can be processed further
165                        // note: ray deletion handled by ray pool)
166                        HandleRay(newRay);
167
[1996]168                        return 1;
[2695]169                }
[1500]170        }
171
[1996]172        return 0;
[1486]173}
[1473]174
[2053]175
[2705]176int GvsPreprocessor::CountObject(Intersectable *triObj)
[2669]177{
[2705]178        int numObjects = 0;
179
[2687]180        if ((triObj->mCounter != (NOT_ACCOUNTED_OBJECT + 1)) &&
181                (triObj->mCounter != (ACCOUNTED_OBJECT + 1)))
[2669]182        {
183                ++ triObj->mCounter;
[2705]184                ++ numObjects;
[2669]185        }
[2705]186
187        mGenericStats[1] += numObjects;
188
189        return numObjects;
[2669]190}
191
192
193void GvsPreprocessor::UpdateStatsForVisualization(KdIntersectable *kdInt)
194{
195        // count new objects in pvs due to kd node conversion   
196        myobjects.clear();
[2705]197        // also gather duplicates to avoid mailing
198        mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
[2669]199
[2705]200        int numObj;
201
[2669]202        ObjectContainer::const_iterator oit, oit_end = myobjects.end();
203
204        for (oit = myobjects.begin(); oit != oit_end; ++ oit)
[2705]205                numObj = CountObject(*oit);
206
207        mViewCellsManager->UpdateStatsForViewCell(mCurrentViewCell, kdInt, numObj);
[2669]208}       
209
210
[1999]211bool GvsPreprocessor::HasContribution(VssRay &ray)
[1486]212{
[1999]213        if (!ray.mTerminationObject)
214                return false;
[1933]215
[1999]216        bool result;
217
[1977]218        if (!mPerViewCell)
219        {
[1999]220                // store the rays + the intersected view cells
221                const bool storeViewCells = false; //GVS_DEBUG;
222
223                mViewCellsManager->ComputeSampleContribution(ray,
[1977]224                                                                                                         true,
[1999]225                                                                                                         storeViewCells,
[1990]226                                                                                                         true);
[1999]227
228                result = ray.mPvsContribution > 0;
[1977]229        }
[2625]230        else // original per view cell gvs
[1977]231        {
[1999]232                Intersectable *obj = ray.mTerminationObject;
233
[2692]234                // test if triangle was accounted for yet
[2691]235                result = AddTriangleObject(obj);
236               
237                if (mUseKdPvs && (1 || result))
[1999]238                {
[2669]239                        // exchange the triangle with the node in the pvs for kd pvs
[2691]240                        KdNode *node = mKdTree->GetPvsNode(ray.mTermination);
241
242                        //KdNode *node = mKdTree->GetPvsNodeCheck(ray.mTermination, obj);
[2694]243                        //if (!node) cerr << "e " << obj->GetBox() << " " << ray.mTermination << endl; else
[2691]244                        if (!node->Mailed())
[2694]245                        {//cout<<"o ";
[2691]246                                // add to pvs
247                                node->Mail();
248                                KdIntersectable *kdInt = mKdTree->GetOrCreateKdIntersectable(node);
249                                mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
[1999]250
[2705]251                                if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
[2615]252                        }
[1999]253                }
[1977]254        }
[1932]255
[1999]256        return result;
257}
258
259
260bool GvsPreprocessor::HandleRay(VssRay *vssRay)
261{
262        if (!HasContribution(*vssRay))
[1977]263                return false;
264
[2005]265        if (0 && GVS_DEBUG)
[1990]266                mVssRays.push_back(new VssRay(*vssRay));
267
[1977]268        // add new ray to ray queue
269        mRayQueue.push(vssRay);
270
[1990]271        ++ mGvsStats.mTotalContribution;
[1533]272
[1977]273        return true;
[1460]274}
275
[1500]276
277/** Creates 3 new vertices for triangle vertex with specified index.
[1489]278*/
[1932]279void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
280                                                                                          const Triangle3 &hitTriangle,
281                                                                                          const VssRay &ray,
282                                                                                          const int index) const
[1460]283{
[1486]284        const int indexU = (index + 1) % 3;
285        const int indexL = (index == 0) ? 2 : index - 1;
286
[1524]287        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
[1486]288        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
289        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
[1492]290       
[1533]291        const float len = Magnitude(a);
[1932]292       
[1523]293        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
294        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
[1524]295        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
296                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
[1492]297
[1486]298        // compute the new three hit points
[1500]299        // pi, i + 1:  pi+ e·|pi-xp|·di, j
[1932]300        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
[1500]301        // pi, i - 1:  pi+ e·|pi-xp|·di, j
[1932]302    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
[1500]303        // pi, i:  pi+ e·|pi-xp|·di, j
[1932]304        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
[1489]305       
[1524]306        vertices.push_back(pt2);
307        vertices.push_back(pt3);
[1500]308        vertices.push_back(pt1);
[1489]309}
310
311
[1500]312void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
313                                                                          const Triangle3 &hitTriangle,
[1932]314                                                                          const VssRay &ray) const
[1500]315{
[1932]316        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
317        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
318        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
[1500]319}
[1492]320
[1500]321
[1932]322Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
323                                                                                           const Triangle3 &hitTriangle,
324                                                                                           const VssRay &oldRay) const
[1489]325{
[1932]326        // find the intersection of the plane induced by the
327        // hit triangle with the new ray
[1500]328        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
329
330        const Vector3 hitPt =
331                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
332       
333        return hitPt;
334}
335
336
337static bool EqualVisibility(const VssRay &a, const VssRay &b)
338{
339        return a.mTerminationObject == b.mTerminationObject;
340}
341
342
343int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
344                                                                   const Vector3 &p1,
345                                                                   const Vector3 &p2,
[1932]346                                                                   const VssRay &ray1,
347                                                                   const VssRay &ray2,
[1500]348                                                                   const VssRay &oldRay)
[2048]349{
350        //cout <<"y"<<Magnitude(p1 - p2) << " ";
[1996]351        int castRays = 0;
352
[1990]353        // cast reverse rays if necessary
[1996]354        castRays += CheckDiscontinuity(ray1, hitTriangle, oldRay);
355        castRays += CheckDiscontinuity(ray2, hitTriangle, oldRay);
[1500]356
[2017]357        if (EqualVisibility(ray1, ray2) || (SqrMagnitude(p1 - p2) <= MIN_DIST))
[1500]358        {
[1996]359                return castRays;
[1500]360        }
[1932]361       
[1990]362        // the new subdivision point
363        const Vector3 p = (p1 + p2) * 0.5f;
[2017]364        //cout << "p: " << p << " " << p1 << " " << p2 << endl;
[1990]365        // cast ray into the new point
366        SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
[1932]367
[1996]368        VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
369       
370        ++ castRays;
[1580]371
[1996]372        if (!newRay) return castRays;
[1580]373
[2053]374        //newRay->mFlags |= VssRay::BorderSample;
[1990]375
376        // add new ray to queue
377        const bool enqueued = HandleRay(newRay);
378
379        // subdivide further
[1996]380        castRays += SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
381        castRays += SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
[1990]382
383        // this ray will not be further processed
[2692]384        // note: ray deletion is handled by ray pool
[1990]385
[1996]386        return castRays;
[1500]387}
388
389
390int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
391{
392        Intersectable *tObj = currentRay.mTerminationObject;
[2597]393        // q matt: can this be possible
394        if (!tObj) return 0;
395
[1486]396        Triangle3 hitTriangle;
[1489]397
398        // other types not implemented yet
399        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
[2017]400                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
[1522]401        else
[2601]402                cout << "border sampling: " << Intersectable::GetTypeName(tObj) << " not yet implemented" << endl;
[1489]403
[2601]404        //cout << "type: " << Intersectable::GetTypeName(tObj) << endl;
405
[1500]406        VertexContainer enlargedTriangle;
407       
408        /// create 3 new hit points for each vertex
409        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
410       
411        /// create rays from sample points and handle them
[1492]412        SimpleRayContainer simpleRays;
413        simpleRays.reserve(9);
[1486]414
[1500]415        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
[1486]416
[1500]417        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
418        {
419                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
[1990]420
[1883]421                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
[1990]422                simpleRays.AddRay(sr); 
[1500]423        }
[1522]424
[1566]425        if (0)
426        {
[1932]427                // visualize enlarged triangles
[1566]428                VizStruct dummy;
429                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
430                dummy.originalTriangle = hitTriangle;
431                vizContainer.push_back(dummy);
432        }
433
[1524]434        // cast rays to triangle vertices and determine visibility
[1489]435        VssRayContainer vssRays;
[1533]436
[1932]437        // don't cast double rays as we need only the forward rays
[1996]438        const bool castDoubleRays = !mPerViewCell;
[1990]439        // cannot prune invalid rays because we have to compare adjacent  rays.
[1932]440        const bool pruneInvalidRays = false;
441
[1996]442
443        //////////
444        //-- fill up simple rays with random rays so we can cast 16
445
446        //const int numRandomRays = 0;
447        const int numRandomRays = 16 - (int)simpleRays.size();
448
[2691]449        GenerateRays(numRandomRays, *mDistribution, simpleRays);
[1996]450
[2053]451
[1996]452        /////////////////////
453
[1990]454        // keep origin for per view cell sampling
[1996]455        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
[1932]456
[1996]457        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
[2648]458
459#if 0
[1580]460        // set flags
[2648]461        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
[1996]462        for (rit = vssRays.begin(); rit != rit_end; ++ rit, ++ i)
[2053]463                (*rit)->mFlags |= VssRay::BorderSample;
[2648]464#endif
465
[1999]466        int castRays = (int)simpleRays.size();
467
468        VssRayContainer invalidSamples;
469
[1932]470        // handle rays
[1999]471        EnqueueRays(vssRays, invalidSamples);
472
[1500]473    // recursivly subdivide each edge
[1996]474        for (int i = 0; i < numBorderSamples; ++ i)
[1500]475        {
[1932]476                castRays += SubdivideEdge(hitTriangle,
477                                                                  enlargedTriangle[i],
[1996]478                                                                  enlargedTriangle[(i + 1) % numBorderSamples],
[1932]479                                                                  *vssRays[i],
[1996]480                                                                  *vssRays[(i + 1) % numBorderSamples],
[1932]481                                                                  currentRay);
[1500]482        }
[1999]483       
[1934]484        mGvsStats.mBorderSamples += castRays;
[1932]485
[2053]486        //CLEAR_CONTAINER(invalidSamples);
[2048]487       
[2687]488        //cout << "here3 cast rays: " << castRays << endl;
[1533]489        return castRays;
[1473]490}
491
492
[1996]493bool GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
494                                                                          const Triangle3 &occluder,
495                                                                          const VssRay &oldRay,
496                                                                          Vector3 &newPoint) const
[1933]497{
498        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
499        //-- with the newly found occluder (xold is the previous ray from
500        //-- which x was generated). On the intersecting line, we select a point
501        //-- pnew which lies just outside of the new triangle so the ray
502        //-- just passes through the gap
503
504        const Plane3 plane(currentRay.GetOrigin(),
505                                           currentRay.GetTermination(),
506                                           oldRay.GetTermination());
507       
508        Vector3 pt1, pt2;
509
510        const bool intersects = occluder.GetPlaneIntersection(plane, pt1, pt2);
511
512        if (!intersects)
[1996]513        {
[1999]514                //cerr << "big error!! no intersection " << pt1 << " " << pt2 << endl;
[1996]515                return false;
516        }
[1933]517
518        // get the intersection point on the old ray
519        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
520
521        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
522        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
523
[2695]524        // evaluate new hitpoint just outside the triangle
[1933]525        // the point is chosen to be on the side closer to the original ray
526        if (Distance(pt1, pt3) < Distance(pt2, pt3))
[2695]527                newPoint = pt1 + mEps * (pt1 - pt2);
[1933]528        else
[2695]529                newPoint = pt2 + mEps * (pt2 - pt1);
[1933]530
[1934]531        //cout << "passing point: " << newPoint << endl << endl;
[1996]532        return true;
[1500]533}
534
535
536VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
537                                                                                 const Triangle3 &hitTriangle,
538                                                                                 const VssRay &oldRay)
539{
[1933]540        // get triangle occluding the path to the hit mesh
541        Triangle3 occluder;
542        Intersectable *tObj = currentRay.mTerminationObject;
[1934]543
[1933]544        // q: why can this happen?
545        if (!tObj)
546                return NULL;
547
548        // other types not implemented yet
549        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
[2048]550        {
[2017]551                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
[2048]552        }
[1933]553        else
[2048]554        {
555                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
556        }
[1933]557        // get a point which is passing just outside of the occluder
[1996]558    Vector3 newPoint;
559
[2695]560        // q: why is there sometimes no intersecton found?
[1996]561        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
562                return NULL;
563
[1500]564        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
565
[1990]566        Vector3 newDir, newOrigin;
567
[1932]568        //-- Construct the mutated ray with xnew,
569        //-- dir = predicted(x)- pnew as direction vector
[1990]570        newDir = predicted - newPoint;
[1932]571
[1933]572        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
[1500]573        // difficult to say!!
[1935]574        const float offset = 0.5f;
[1990]575        newOrigin = newPoint - newDir * offset;
576       
[2694]577
[1990]578        //////////////
579        //-- for per view cell sampling, we must check for intersection
580        //-- with the current view cell
[1500]581
[1990]582    if (mPerViewCell)
583        {
584                // send ray to view cell
585                static Ray ray;
586                ray.Clear();
587                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
588               
589                //cout << "z";
590                // check if ray intersects view cell
591                if (!mCurrentViewCell->CastRay(ray))
592                        return NULL;
[1981]593
[1990]594                Ray::Intersection &hit = ray.intersections[0];
595       
596                //cout << "q";
597                // the ray starts from the view cell
598                newOrigin = ray.Extrap(hit.mT);
599        }
[1981]600
[2695]601        ++ mGvsStats.mReverseSamples;
602
[1933]603        const SimpleRay simpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
[1571]604
[1933]605        VssRay *reverseRay =
[1996]606                mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
[1933]607
608        return reverseRay;
[1473]609}
610
[1489]611
[2691]612int GvsPreprocessor::CastInitialSamples(int numSamples)
[1489]613{       
[1473]614        const long startTime = GetTime();
[1595]615
[1489]616        // generate simple rays
617        SimpleRayContainer simpleRays;
[1990]618       
[2691]619        ViewCellBorderBasedDistribution vcStrat(*this, mCurrentViewCell);
620    GenerateRays(numSamples, *mDistribution, simpleRays);
[1990]621
622        //cout << "sr: " << simpleRays.size() << endl;
[1489]623        // generate vss rays
[1473]624        VssRayContainer samples;
[1990]625       
[1996]626        const bool castDoubleRays = !mPerViewCell;
[1990]627        const bool pruneInvalidRays = true;
628       
[1996]629        CastRays(simpleRays, samples, castDoubleRays, pruneInvalidRays);
630       
[1999]631        VssRayContainer invalidSamples;
632
[1489]633        // add to ray queue
[1999]634        EnqueueRays(samples, invalidSamples);
[1533]635
[2053]636        //CLEAR_CONTAINER(invalidSamples);
[2633]637        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
[1990]638        return (int)simpleRays.size();
[1489]639}
640
641
[1999]642void GvsPreprocessor::EnqueueRays(VssRayContainer &samples, VssRayContainer &invalidSamples)
[1489]643{
[1486]644        // add samples to ray queue
[1473]645        VssRayContainer::const_iterator vit, vit_end = samples.end();
[1576]646        for (vit = samples.begin(); vit != vit_end; ++ vit)
[1473]647        {
[1999]648                VssRay *ray = *vit;
649
[2053]650                HandleRay(ray);
[2633]651                //if (!HandleRay(ray)) invalidSamples.push_back(ray);
[1460]652        }
653}
654
[1473]655
[1990]656int GvsPreprocessor::ProcessQueue()
[1460]657{
[2695]658        ++ mGvsStats.mGvsRuns;
[1545]659
[2687]660        int castSamples = 0;
661
[2048]662        while (!mRayQueue.empty())//&& (mGvsStats.mTotalSamples + castSamples < mTotalSamples) )
[2690]663        {
[1990]664                // handle next ray
665                VssRay *ray = mRayQueue.top();
666                mRayQueue.pop();
[1996]667               
[1990]668                const int newSamples = AdaptiveBorderSampling(*ray);
[1934]669
[1990]670                castSamples += newSamples;
[2687]671                // note: don't have to delete because handled by ray pool
[1473]672        }
673
[2161]674        /*if (mRayCaster->mVssRayPool.mIndex > mSamplesPerPass)
[2048]675        {
676                cout << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
677                Debug << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
[2161]678        }*/
[2048]679
[1533]680        return castSamples;
[1460]681}
682
[1473]683
[1990]684void ExportVssRays(Exporter *exporter, const VssRayContainer &vssRays)
[1460]685{
[1990]686        VssRayContainer vcRays, vcRays2, vcRays3;
[1473]687
[1990]688        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
689
690        // prepare some rays for output
691        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
[1473]692        {
[1990]693                //const float p = RandomValue(0.0f, (float)vssRays.size());
[1545]694
[1990]695                if (1)//(p < raysOut)
696                {
697                        if ((*rit)->mFlags & VssRay::BorderSample)
698                        {
699                                vcRays.push_back(*rit);
700                        }
701                        else if ((*rit)->mFlags & VssRay::ReverseSample)
702                        {
703                                vcRays2.push_back(*rit);
704                        }
705                        else
706                        {
707                                vcRays3.push_back(*rit);
708                        }       
709                }
[1460]710        }
[1990]711
[2005]712        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
713        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
[2003]714        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
[1990]715}
716
717
[1999]718void GvsPreprocessor::VisualizeViewCell(const ObjectContainer &objects)
[1990]719{
720    Intersectable::NewMail();
721        Material m;
[1528]722       
[1996]723        char str[64]; sprintf(str, "pass%06d.wrl", mProcessedViewCells);
[1990]724
725        Exporter *exporter = Exporter::GetExporter(str);
726        if (!exporter)
727                return;
728
[1999]729        ObjectContainer::const_iterator oit, oit_end = objects.end();
730
731        for (oit = objects.begin(); oit != oit_end; ++ oit)
732        {
733                Intersectable *intersect = *oit;
734               
735                m = RandomMaterial();
736                exporter->SetForcedMaterial(m);
737                exporter->ExportIntersectable(intersect);
[1990]738        }
739
740        cout << "vssrays: " << (int)mVssRays.size() << endl;
741        ExportVssRays(exporter, mVssRays);
742
[2597]743
[1990]744        /////////////////
745        //-- export view cell geometry
746
[2597]747        //exporter->SetWireframe();
[1990]748
749        m.mDiffuseColor = RgbColor(0, 1, 0);
750        exporter->SetForcedMaterial(m);
751
[1999]752        AxisAlignedBox3 bbox = mCurrentViewCell->GetMesh()->mBox;
753        exporter->ExportBox(bbox);
[1990]754        //exporter->SetFilled();
755
[2053]756        delete exporter;
[1460]757}
758
759
[1982]760void GvsPreprocessor::VisualizeViewCells()
761{
[1996]762        char str[64]; sprintf(str, "tmp/pass%06d_%04d-", mProcessedViewCells, mPass);
[1982]763                       
764        // visualization
765        if (mGvsStats.mPassContribution > 0)
766        {
767                const bool exportRays = true;
768                const bool exportPvs = true;
769
770                mViewCellsManager->ExportSingleViewCells(mObjects,
771                                                                                                 10,
772                                                                                                 false,
773                                                                                                 exportPvs,
774                                                                                                 exportRays,
775                                                                                                 1000,
776                                                                                                 str);
777        }
778
779        // remove pass samples
780        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
781
782        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
783        {
784                (*vit)->DelRayRefs();
785        }
786}
787
788
[2687]789void GvsPreprocessor::CompileViewCellsFromPointList()
[1996]790{
[2687]791        ViewCell::NewMail();
792
[2648]793        // Receive list of view cells from view cells manager
[2598]794        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
[2687]795
796        vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
797
798        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
[2048]799        {
[2687]800                ViewCellPoints *vp = *vit;
[2048]801
[2687]802                if (vp->first) // view cell  specified
[2648]803                {
[2687]804                        ViewCell *viewCell = vp->first;
[2048]805
[2687]806                        if (!viewCell->Mailed())
807                        {
808                                viewCell->Mail();
809                                mViewCells.push_back(viewCell);
810
811                                if (mViewCells.size() >= mMaxViewCells)
812                                        break;
813                        }
[2662]814                }
[2687]815                else // no view cell specified => compute view cells using view point
816                {
817                        SimpleRayContainer::const_iterator rit, rit_end = vp->second.end();
818
819                        for (rit = vp->second.begin(); rit != rit_end; ++ rit)
820                        {
821                                SimpleRay ray = *rit;
822
823                                ViewCell *viewCell = mViewCellsManager->GetViewCell(ray.mOrigin);
824
825                                if (viewCell && !viewCell->Mailed())
826                                {
827                                        viewCell->Mail();
828                                        mViewCells.push_back(viewCell);
829
830                                        if (mViewCells.size() >= mMaxViewCells)
831                                                break;
832                                }
833                        }
834                }
[2048]835        }
[2687]836}
837
838
839void GvsPreprocessor::CompileViewCellsList()
840{
841        if (!mViewCellsManager->GetViewCellPointsList()->empty())
842        {
843                cout << "processing view point list" << endl;
844                CompileViewCellsFromPointList();
845        }
[2662]846        else
847        {
[2687]848                ViewCell::NewMail();
849
[2662]850                while ((int)mViewCells.size() < mMaxViewCells)
[1996]851                {
[2662]852                        const int tries = 10000;
853                        int i = 0;
[1996]854
[2662]855                        for (i = 0; i < tries; ++ i)
[1996]856                        {
[2662]857                                const int idx = (int)RandomValue(0.0f, (float)mViewCellsManager->GetNumViewCells() - 0.5f);
858
859                                ViewCell *viewCell = mViewCellsManager->GetViewCell(idx);
860
861                                if (!viewCell->Mailed())
862                                {
863                                        viewCell->Mail();
864                                        break;
865                                }
866
867                                mViewCells.push_back(viewCell);
[1999]868                        }
[2597]869
[2662]870                        if (i == tries)
871                        {
872                                cerr << "big error! no view cell found" << endl;
873                                break;
874                        }
[1999]875                }
876        }
[2662]877
878        cout << "\ncomputing list of " << mViewCells.size() << " view cells" << endl;
[1999]879}
[1996]880
[2669]881
[2705]882void GvsPreprocessor::ComputeViewCellGeometryIntersection()
[2687]883{
[2691]884        AxisAlignedBox3 box = mCurrentViewCell->GetBox();
[2687]885
[2691]886        int oldTrianglePvs = (int)mTrianglePvs.size();
887        int newKdObj = 0;
888
[2687]889        // compute pvs kd nodes that intersect view cell
890        ObjectContainer kdobjects;
[2691]891
892        // find intersecting objects not in pvs (i.e., only unmailed)
[2687]893        mKdTree->CollectKdObjects(box, kdobjects);
894
895        ObjectContainer pvsKdObjects;
896
897        ObjectContainer::const_iterator oit, oit_end = kdobjects.end();
898
899        for (oit = kdobjects.begin(); oit != oit_end; ++ oit)
900        {
901        KdIntersectable *kdInt = static_cast<KdIntersectable *>(*oit);
902       
903                myobjects.clear();
[2691]904                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
[2687]905
906                // account for kd object pvs
907                bool addkdobj = false;
908
909                ObjectContainer::const_iterator oit, oit_end = myobjects.end();
910
911                for (oit = myobjects.begin(); oit != oit_end; ++ oit)
912                {
913                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
[2691]914             
915                        // test if the triangle itself intersects
[2687]916                        if (box.Intersects(triObj->GetItem()))
[2691]917                                addkdobj = AddTriangleObject(triObj);
[2687]918                }
919               
[2691]920                // add node to kd pvs
921                if (1 && addkdobj)
922                {
923                        ++ newKdObj;
924                        mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
925                        //mCurrentViewCell->GetPvs().AddSampleDirtyCheck(kdInt, 1.0f);
[2705]926                        if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
[2691]927                }
[2687]928        }
929
[2691]930        cout << "added " << (int)mTrianglePvs.size() - oldTrianglePvs << " triangles (" << newKdObj << " objects) by intersection" << endl;
[2687]931}
932
[2691]933
[1990]934void GvsPreprocessor::PerViewCellComputation()
[1982]935{
[2690]936        while (mCurrentViewCell = NextViewCell())
[1999]937        {
[2625]938                // hack: reset counters
939                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
[2615]940
[2625]941                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
[2669]942                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[1982]943
[2691]944                mDistribution->SetViewCell(mCurrentViewCell);
[2690]945        ComputeViewCell();
[2625]946        }
947}
[1990]948
[1996]949
[2625]950void GvsPreprocessor::PerViewCellComputation2()
951{
952        while (1)
953        {
954                if (!mRendererWidget)
955                        continue;
[1990]956
[2690]957        mCurrentViewCell = mViewCellsManager->GetViewCell(mRendererWidget->GetViewPoint());
[2601]958
[2625]959                // no valid view cell or view cell already computed
[2690]960                if (!mCurrentViewCell || !mCurrentViewCell->GetPvs().Empty() || !mRendererWidget->mComputeGVS)
[2625]961                        continue;
[2615]962
[2643]963                mRendererWidget->mComputeGVS = false;
[2625]964                // hack: reset counters
965                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
[2615]966
[2625]967                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
[2669]968                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[2601]969
[2690]970                ComputeViewCell();
[2625]971                ++ mProcessedViewCells;
972        }
973}
[1999]974
[1982]975
[2048]976void GvsPreprocessor::StorePvs(const ObjectContainer &objectPvs)
977{
978        ObjectContainer::const_iterator oit, oit_end = objectPvs.end();
979
980        for (oit = objectPvs.begin(); oit != oit_end; ++ oit)
981        {
982                mCurrentViewCell->GetPvs().AddSample(*oit, 1);
983        }
984}
985
986
[1990]987void GvsPreprocessor::UpdatePvs(ViewCell *currentViewCell)
988{
989        ObjectPvs newPvs;
990        BvhLeaf::NewMail();
991
992        ObjectPvsIterator pit = currentViewCell->GetPvs().GetIterator();
993
994        // output PVS of view cell
995        while (pit.HasMoreEntries())
996        {               
[2117]997                Intersectable *intersect = pit.Next();
[1990]998
999                BvhLeaf *bv = intersect->mBvhLeaf;
1000
1001                if (!bv || bv->Mailed())
1002                        continue;
1003               
1004                bv->Mail();
1005
1006                //m.mDiffuseColor = RgbColor(1, 0, 0);
1007                newPvs.AddSampleDirty(bv, 1.0f);
[1982]1008        }
[1990]1009
1010        newPvs.SimpleSort();
1011
1012        currentViewCell->SetPvs(newPvs);
[1982]1013}
1014
[1999]1015 
1016void GvsPreprocessor::GetObjectPvs(ObjectContainer &objectPvs) const
1017{
[2695]1018        BvhLeaf::NewMail();
1019
[2053]1020        objectPvs.reserve((int)mTrianglePvs.size());
1021
[1999]1022        ObjectContainer::const_iterator oit, oit_end = mTrianglePvs.end();
1023
1024        for (oit = mTrianglePvs.begin(); oit != oit_end; ++ oit)
1025        {
1026                Intersectable *intersect = *oit;
1027       
1028                BvhLeaf *bv = intersect->mBvhLeaf;
1029
[2053]1030                // hack: reset counter
[2669]1031                (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[2053]1032
[1999]1033                if (!bv || bv->Mailed())
1034                        continue;
[2615]1035
[1999]1036                bv->Mail();
1037                objectPvs.push_back(bv);
1038        }
1039}
1040
1041
[1990]1042void GvsPreprocessor::GlobalComputation()
1043{
1044        int passSamples = 0;
1045        int oldContribution = 0;
1046
1047        while (mGvsStats.mTotalSamples < mTotalSamples)
1048        {
[2048]1049                mRayCaster->InitPass();
[2691]1050
[1990]1051                // Ray queue empty =>
1052                // cast a number of uniform samples to fill ray queue
[2691]1053                int newSamples = CastInitialSamples(mInitialSamples);
[1990]1054
1055                if (!mOnlyRandomSampling)
1056                        newSamples += ProcessQueue();
1057
1058                passSamples += newSamples;
1059                mGvsStats.mTotalSamples += newSamples;
1060
[2048]1061                if (passSamples % (mGvsSamplesPerPass + 1) == mGvsSamplesPerPass)
[1990]1062                {
1063                        ++ mPass;
1064
1065                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1066
1067                        ////////
1068                        //-- stats
1069
1070                        //cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
1071                        mGvsStats.mPass = mPass;
1072                        mGvsStats.Stop();
1073                        mGvsStats.Print(mGvsStatsStream);
1074
1075                        // reset
1076                        oldContribution = mGvsStats.mTotalContribution;
1077                        mGvsStats.mPassContribution = 0;
1078                        passSamples = 0;
1079
1080                        if (GVS_DEBUG)
1081                                VisualizeViewCells();
1082                }
1083        }
1084}
1085
1086
[1489]1087bool GvsPreprocessor::ComputeVisibility()
[1460]1088{
[1533]1089        cout << "Gvs Preprocessor started\n" << flush;
[1545]1090        const long startTime = GetTime();
[1533]1091
[1990]1092        //Randomize(0);
[1934]1093        mGvsStats.Reset();
1094        mGvsStats.Start();
[1545]1095
[1486]1096        if (!mLoadViewCells)
[1563]1097        {       
1098                /// construct the view cells from the scratch
1099                ConstructViewCells();
[1580]1100                // reset pvs already gathered during view cells construction
1101                mViewCellsManager->ResetPvs();
[1563]1102                cout << "finished view cell construction" << endl;
[1486]1103        }
[1460]1104
[1982]1105        if (mPerViewCell)
[1473]1106        {
[2648]1107#if 1
[2597]1108                // provide list of view cells to compute
[1996]1109                CompileViewCellsList();
[2686]1110
[2597]1111                // start per view cell gvs
[2048]1112                PerViewCellComputation();
[2625]1113#else
1114                PerViewCellComputation2();
1115
1116#endif
[1460]1117        }
[1982]1118        else
1119        {
1120                GlobalComputation();
1121        }
[1460]1122
[2687]1123        cout << "cast " << mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M single rays/s" << endl;
[1545]1124
[1934]1125        if (GVS_DEBUG)
1126        {
1127                Visualize();
1128                CLEAR_CONTAINER(mVssRays);
1129        }
[2048]1130       
1131        // export the preprocessed information to a file
1132        if (0 && mExportVisibility)
1133        {
1134                ExportPreprocessedData(mVisibilityFileName);
1135        }
[2648]1136       
1137        // compute the pixel error of this visibility solution
1138        if (mEvaluatePixelError)
1139        {
1140                ComputeRenderError();
1141        }
[1934]1142
[1473]1143        return true;
[1460]1144}
1145
[1522]1146
[2048]1147void GvsPreprocessor::DeterminePvsObjects(VssRayContainer &rays)
1148{
[2187]1149        // store triangle directly
[2048]1150        mViewCellsManager->DeterminePvsObjects(rays, true);
1151}
1152
1153
[1522]1154void GvsPreprocessor::Visualize()
1155{
1156        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
1157
1158        if (!exporter)
1159                return;
1160       
1161        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
[1999]1162       
[1522]1163        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
1164        {
[1524]1165                exporter->SetWireframe();
[1522]1166                exporter->ExportPolygon((*vit).enlargedTriangle);
1167                //Material m;
[1524]1168                exporter->SetFilled();
1169                Polygon3 poly = Polygon3((*vit).originalTriangle);
1170                exporter->ExportPolygon(&poly);
[1522]1171        }
1172
[1933]1173        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
[1999]1174
[1933]1175        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
1176        {
1177                Intersectable *obj = (*rit)->mTerminationObject;
1178                exporter->ExportIntersectable(obj);
1179        }
1180
[1990]1181        ExportVssRays(exporter, mVssRays);
1182       
[1522]1183        delete exporter;
[1460]1184}
[1522]1185
[1934]1186
1187void GvsStatistics::Print(ostream &app) const
1188{
[2003]1189        app << "#ViewCells\n" << mViewCells << endl;
[2648]1190        app << "#Id\n" << mViewCellId << endl;
1191        app << "#Time\n" << mTimePerViewCell << endl;;
[2690]1192        app << "#TriPvs\n" << mTrianglePvs << endl;
[2648]1193        app << "#ObjectPvs\n" << mPerViewCellPvs << endl;
[2687]1194        app << "#UpdatedPvs\n" << (int)mPvsCost << endl;
[2003]1195
[2677]1196        app << "#PerViewCellSamples\n" << mPerViewCellSamples << endl;
1197        app << "#RaysPerSec\n" << RaysPerSec() << endl;
1198       
[2003]1199        app << "#TotalPvs\n" << mTotalPvs << endl;
[2648]1200        app << "#TotalTime\n" << mTotalTime << endl;
[1934]1201        app << "#TotalSamples\n" << mTotalSamples << endl;
[2677]1202
[2648]1203        app << "#TotalTrianglePvs\n" << mTotalTrianglePvs << endl;
1204       
[2677]1205        if (0)
1206        {
1207                app << "#ReverseSamples\n" << mReverseSamples << endl;
1208                app << "#BorderSamples\n" << mBorderSamples << endl;
[2648]1209
[2677]1210                app << "#Pass\n" << mPass << endl;
1211                app << "#ScDiff\n" << mPassContribution << endl;
[2695]1212                app << "#GvsRuns\n" << mGvsRuns << endl;       
[2003]1213
[2677]1214                app     << "#SamplesContri\n" << mTotalContribution << endl;
1215        }
[2003]1216
1217        app << endl;
[1883]1218}
[1934]1219
1220
[2690]1221void GvsPreprocessor::ComputeViewCell()
[2625]1222{
[2696]1223        //if (mCurrentViewCell->GetId() != 499) return;
[2695]1224
1225        // clean up
1226        mTrianglePvs.clear();
1227
[2691]1228        mCurrentViewCell->GetMesh()->ComputeBoundingBox();
1229
[2643]1230        KdNode::NewMail();
[2625]1231
[2670]1232        const long startTime = GetTime();
1233
[2625]1234        cout << "\n***********************\n"
[2643]1235                << "computing view cell " << mProcessedViewCells
[2625]1236                << " (id: " << mCurrentViewCell->GetId() << ")" << endl;
[2691]1237        cout << "bb: " << mCurrentViewCell->GetBox() << endl;
[2625]1238
[2690]1239        mGvsStats.mPerViewCellSamples = 0;
1240
[2695]1241        int oldContribution = 0;
[2690]1242        int passSamples = 0;
[2695]1243       
[2691]1244        for (int i = 0; i < 0; ++ i)
1245                mGenericStats[i] = 0;
[2690]1246
1247        while (1)
1248        {
[2691]1249                int oldPvsSize = mCurrentViewCell->GetPvs().GetSize();
[2695]1250               
[2690]1251                mRayCaster->InitPass();
1252
1253                // Ray queue empty =>
1254                // cast a number of uniform samples to fill ray queue
[2691]1255                int newSamples = CastInitialSamples(mInitialSamples);
[2690]1256
1257                if (!mOnlyRandomSampling)
1258                {
1259                        int samplesPerRun = ProcessQueue();
1260                        newSamples += samplesPerRun;
1261                        //if (samplesPerRun > 0) cout << "spr: " << samplesPerRun << " ";
1262                }
1263
1264                passSamples += newSamples;
1265        mGvsStats.mPerViewCellSamples += newSamples;
1266
1267                if (passSamples >= mGvsSamplesPerPass)
1268                {
1269                        if (GVS_DEBUG) VisualizeViewCell(mTrianglePvs);
1270
[2691]1271                        //const bool convertPerPass = true;
[2690]1272                        const bool convertPerPass = false;
1273
1274                        if (convertPerPass)
1275                        {       
1276                                int newObjects = ConvertObjectPvs();
1277
1278                                cout << "added " << newObjects << " triangles to triangle pvs" << endl;
1279                                mGvsStats.mTotalContribution += newObjects;
1280                        }
1281
1282                        ++ mPass;
1283                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1284
1285
1286                        ////////
1287                        //-- stats
1288
1289                        mGvsStats.mPass = mPass;
1290
1291                        cout << "\nPass " << mPass << " #samples: " << mGvsStats.mPerViewCellSamples << endl;
1292                        cout << "contribution=" << mGvsStats.mPassContribution << " (of " << mMinContribution << ")" << endl;
1293                        cout << "obj contri=" << mCurrentViewCell->GetPvs().GetSize() - oldPvsSize << " (of " << mMinContribution << ")" << endl;
1294
1295                        // termination criterium
1296                        if (mGvsStats.mPassContribution < mMinContribution)
1297                                break;
1298
[2695]1299                        // reset stats
[2690]1300                        oldContribution = mGvsStats.mTotalContribution;
1301                        mGvsStats.mPassContribution = 0;
1302                        passSamples = 0;
1303                }
1304        }
[2677]1305       
[2691]1306        // at last compute objects that directly intersect view cell
[2705]1307        ComputeViewCellGeometryIntersection();
[2690]1308
1309               
[2677]1310        ////////
1311        //-- stats
[2625]1312
[2690]1313        // timing
1314        mGvsStats.mTimePerViewCell = TimeDiff(startTime, GetTime()) * 1e-3f;
1315
1316        ComputeStats();
1317}
1318
1319
1320void GvsPreprocessor::ComputeStats()
1321{
[2677]1322        // compute pvs size using larger (bvh objects)
1323        // note: for kd pvs we had to do this during gvs computation
1324
[2625]1325        if (!mUseKdPvs)
1326        {
1327                ObjectContainer objectPvs;
1328
1329                // optain object pvs
1330                GetObjectPvs(objectPvs);
1331
1332                // add pvs
1333                ObjectContainer::const_iterator it, it_end = objectPvs.end();
1334
1335                for (it = objectPvs.begin(); it != it_end; ++ it)
1336                {
1337                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1338                }
1339
1340                cout << "triangle pvs of " << (int)mTrianglePvs.size()
1341                        << " was converted to object pvs of " << (int)objectPvs.size() << endl;
1342
1343                mGvsStats.mPerViewCellPvs = (int)objectPvs.size();
[2677]1344                mGvsStats.mPvsCost = 0; // todo objectPvs.EvalPvsCost();
[2625]1345        }
[2691]1346        else if (0)
[2625]1347        {
[2691]1348                //KdNode::NewMail();
1349
1350                // compute pvs kd nodes that intersect view cell
1351                ObjectContainer mykdobjects;
1352
1353                // extract kd pvs
1354                ObjectContainer::const_iterator it, it_end = mTrianglePvs.end();
1355
1356                for (it = mTrianglePvs.begin(); it != it_end; ++ it)
1357                {
1358                        Intersectable *obj = *it;
1359                        // find intersecting objects not yet in pvs (i.e., only unmailed)
1360                        mKdTree->CollectKdObjects(obj->GetBox(), mykdobjects);
1361                }
1362
1363                // add pvs
1364                it_end = mykdobjects.end();
1365
1366                for (it = mykdobjects.begin(); it != it_end; ++ it)
1367                {
1368                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1369                }
1370
1371                cout << "added " << (int)mykdobjects.size() << " new objects " << endl;
1372
[2643]1373                mGvsStats.mPerViewCellPvs = mCurrentViewCell->GetPvs().GetSize();
[2648]1374                mGvsStats.mPvsCost = mCurrentViewCell->GetPvs().EvalPvsCost();
[2643]1375
[2625]1376        }
1377
[2677]1378        mGvsStats.mTrianglePvs = (int)mTrianglePvs.size();
[2625]1379
1380
[2677]1381        ////////////////
1382        // global values
1383
[2690]1384        mGvsStats.mViewCells = mProcessedViewCells;
[2677]1385        mGvsStats.mTotalTrianglePvs += mGvsStats.mTrianglePvs;
1386        mGvsStats.mTotalTime += mGvsStats.mTimePerViewCell;
1387    mGvsStats.mTotalPvs += mGvsStats.mPerViewCellPvs;
[2625]1388        mGvsStats.mTotalSamples += mGvsStats.mPerViewCellSamples;
1389
1390        mGvsStats.Stop();
1391        mGvsStats.Print(mGvsStatsStream);
1392
[2677]1393        cout << "id: " << mCurrentViewCell->GetId() << " pvs cost: "
[2690]1394             << mGvsStats.mPvsCost << " pvs tri: " << mTrianglePvs.size() << endl;
1395}
[2677]1396
1397
[2690]1398ObjectContainer triangles;
1399
1400int GvsPreprocessor::ConvertObjectPvs()
1401{
1402        int newObjects = 0;
1403
1404        ObjectPvsIterator pit = mCurrentViewCell->GetPvs().GetIterator();
1405
1406        triangles.clear();
1407
1408        // output PVS of view cell
1409        while (pit.HasMoreEntries())
1410        {               
1411                KdIntersectable *kdInt = static_cast<KdIntersectable *>(pit.Next());
1412
1413                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), triangles);
1414
1415                ObjectContainer::const_iterator oit, oit_end = triangles.end();
1416
1417                for (oit = triangles.begin(); oit != oit_end; ++ oit)
1418                {
1419                        if (AddTriangleObject(*oit))
1420                                ++ newObjects;
1421                }
1422        }
1423
1424        return newObjects;
[1934]1425}
[2625]1426
[2690]1427
1428bool GvsPreprocessor::AddTriangleObject(Intersectable *triObj)
1429{
1430        if ((triObj->mCounter < ACCOUNTED_OBJECT))
1431        {
1432                triObj->mCounter += ACCOUNTED_OBJECT;
1433
1434                mTrianglePvs.push_back(triObj);
[2695]1435                //mDummyBuffer.push_back(mGvsStats.mGvsRuns);
[2691]1436                mGenericStats[0] = (int)mTrianglePvs.size();
[2690]1437                return true;
1438        }
1439
1440        return false;
[2625]1441}
[2690]1442
[2691]1443
1444
[2690]1445}
Note: See TracBrowser for help on using the repository browser.