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

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