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

Revision 1934, 18.6 KB checked in by mattausch, 17 years ago (diff)

gvs preprocessor is basicly working

  • Property svn:executable set to *
Line 
1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
4#include "VssRay.h"
5#include "ViewCellsManager.h"
6#include "Triangle3.h"
7#include "IntersectableWrapper.h"
8#include "Plane3.h"
9#include "RayCaster.h"
10#include "Exporter.h"
11#include "SamplingStrategy.h"
12
13
14namespace GtpVisibilityPreprocessor
15{
16 
17#define GVS_DEBUG 0
18
19struct VizStruct
20{
21        Polygon3 *enlargedTriangle;
22        Triangle3 originalTriangle;
23        VssRay *ray;
24};
25
26static vector<VizStruct> vizContainer;
27
28GvsPreprocessor::GvsPreprocessor():
29Preprocessor(),
30//mSamplingType(SamplingStrategy::DIRECTION_BASED_DISTRIBUTION),
31mSamplingType(SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION)
32{
33        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
34        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
35        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.samplesPerPass", mSamplesPerPass);
36        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
37        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
38
39        char gvsStatsLog[100];
40        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
41        mGvsStatsStream.open(gvsStatsLog);
42
43        Debug << "Gvs preprocessor options" << endl;
44        Debug << "number of total samples: " << mTotalSamples << endl;
45        Debug << "number of initial samples: " << mInitialSamples << endl;
46        Debug << "number of samples per pass: " << mSamplesPerPass << endl;
47        Debug << "threshold: " << mThreshold << endl;
48        Debug << "epsilon: " << mEps << endl;
49        Debug << "stats: " << gvsStatsLog << endl;
50
51        if (0)
52                mOnlyRandomSampling = true;
53        else
54                mOnlyRandomSampling = false;
55
56        //mGvsStatsStream.open("gvspreprocessor.log");
57        mGvsStats.Reset();
58}
59
60
61bool GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
62                                                                                 const Triangle3 &hitTriangle,
63                                                                                 const VssRay &oldRay)
64{
65        // the predicted hitpoint: we expect to hit the same mesh again
66        const Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
67
68        const float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
69        const float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
70       
71        // distance large => this is likely to be a discontinuity
72#if 1
73        if ((predictedLen - len) > mThreshold)
74#else // rather use relative distance
75        if ((predictedLen / len) > mThreshold)
76#endif
77        {
78                //cout << "r";
79                // apply reverse sampling to find the gap
80                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
81
82                if (!newRay)
83                        return false;
84
85                // set flag for visualization
86                newRay->mFlags |= VssRay::ReverseSample;
87               
88                // if ray is not further processed => can delete ray
89                if (!HandleRay(newRay))
90                {
91                        delete newRay;
92                }
93                else if (GVS_DEBUG && (mVssRays.size() < 9))
94                {
95                        mVssRays.push_back(new VssRay(oldRay));
96                        mVssRays.push_back(new VssRay(currentRay));
97                        mVssRays.push_back(new VssRay(*newRay));
98                }
99
100                return true;
101        }
102
103        return false;
104}
105
106
107bool GvsPreprocessor::HandleRay(VssRay *vssRay)
108{
109        // compute the contribution to the view cells
110        const bool storeRaysForViz = GVS_DEBUG;
111
112        mViewCellsManager->ComputeSampleContribution(*vssRay,
113                                                                                                 true,
114                                                                                                 storeRaysForViz);
115
116        // some pvs contribution for this ray?
117        if (vssRay->mPvsContribution > 0)
118        {
119                // add new ray to ray queue
120                mRayQueue.push(vssRay);
121
122                if (storeRaysForViz)
123                {
124                        VssRay *nray = new VssRay(*vssRay);
125                        nray->mFlags = vssRay->mFlags;
126
127                        // store ray in contributing view cell
128                        ViewCellContainer::const_iterator vit, vit_end = vssRay->mViewCells.end();
129                        for (vit = vssRay->mViewCells.begin(); vit != vit_end; ++ vit)
130                        {                       
131                                (*vit)->GetOrCreateRays()->push_back(nray);                             
132                        }
133                }
134
135        ++ mGvsStats.mPassContribution;
136
137                return true;
138        }
139
140        return false;
141}
142
143
144/** Creates 3 new vertices for triangle vertex with specified index.
145*/
146void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
147                                                                                          const Triangle3 &hitTriangle,
148                                                                                          const VssRay &ray,
149                                                                                          const int index) const
150{
151        const int indexU = (index + 1) % 3;
152        const int indexL = (index == 0) ? 2 : index - 1;
153
154        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
155        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
156        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
157       
158        const float len = Magnitude(a);
159       
160        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
161        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
162        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
163                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
164
165        // compute the new three hit points
166        // pi, i + 1:  pi+ e·|pi-xp|·di, j
167        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
168        // pi, i - 1:  pi+ e·|pi-xp|·di, j
169    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
170        // pi, i:  pi+ e·|pi-xp|·di, j
171        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
172       
173        vertices.push_back(pt2);
174        vertices.push_back(pt3);
175        vertices.push_back(pt1);
176}
177
178
179void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
180                                                                          const Triangle3 &hitTriangle,
181                                                                          const VssRay &ray) const
182{
183        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
184        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
185        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
186}
187
188
189Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
190                                                                                           const Triangle3 &hitTriangle,
191                                                                                           const VssRay &oldRay) const
192{
193        // find the intersection of the plane induced by the
194        // hit triangle with the new ray
195        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
196
197        const Vector3 hitPt =
198                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
199       
200        return hitPt;
201}
202
203
204static bool EqualVisibility(const VssRay &a, const VssRay &b)
205{
206        return a.mTerminationObject == b.mTerminationObject;
207}
208
209
210int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
211                                                                   const Vector3 &p1,
212                                                                   const Vector3 &p2,
213                                                                   const VssRay &ray1,
214                                                                   const VssRay &ray2,
215                                                                   const VssRay &oldRay)
216{
217        CheckDiscontinuity(ray1, hitTriangle, oldRay);
218        CheckDiscontinuity(ray2, hitTriangle, oldRay);
219
220        if (EqualVisibility(ray1, ray2) || (Magnitude(p1 - p2) <= mEps))
221        {
222                return 0;
223        }
224        else
225        {
226                // the new subdivision point
227                const Vector3 p = (p1 + p2) * 0.5f;
228       
229                //cout << "tobj " << ray1.mTerminationObject << " " << ray2.mTerminationObject << " " << p1 << " " << p2 << endl;
230                //cout << "term " << ray1.mTermination << " " << ray2.mTermination << endl;
231
232                // cast ray into the new point
233                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
234       
235                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox());
236
237                if (!newRay) return 0;
238
239                newRay->mFlags |= VssRay::BorderSample;
240
241                // add new ray to queue
242                const bool enqueued = HandleRay(newRay);
243               
244                // subdivide further
245                const int samples1 = SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
246                const int samples2 = SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
247                       
248                // this ray will not be further processed
249                if (!enqueued)
250                        delete newRay;
251               
252                return samples1 + samples2 + 1;
253        }
254}
255
256
257int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
258{
259        Intersectable *tObj = currentRay.mTerminationObject;
260        Triangle3 hitTriangle;
261
262        // other types not implemented yet
263        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
264        {
265                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
266        }
267        else
268        {
269                cout << "not yet implemented" << endl;
270        }
271
272        VertexContainer enlargedTriangle;
273       
274        /// create 3 new hit points for each vertex
275        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
276       
277        /// create rays from sample points and handle them
278        SimpleRayContainer simpleRays;
279        simpleRays.reserve(9);
280
281        //cout << "currentRay: " << currentRay.mOrigin << " dir: " << currentRay.GetDir() << endl;
282
283        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
284
285        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
286        {
287                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
288                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
289                simpleRays.AddRay(sr);
290
291                //cout << "new: " << sr.mOrigin << " dist: " << sr.mDirection << endl;
292        }
293
294        if (0)
295        {
296                // visualize enlarged triangles
297                VizStruct dummy;
298                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
299                dummy.originalTriangle = hitTriangle;
300                vizContainer.push_back(dummy);
301        }
302
303        // cast rays to triangle vertices and determine visibility
304        VssRayContainer vssRays;
305
306        // don't cast double rays as we need only the forward rays
307        const bool castDoubleRays = false;
308        // cannot prune invalid rays because we have to
309        // compare adjacent  rays.
310        const bool pruneInvalidRays = false;
311
312        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
313
314        // set flags
315        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
316        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
317        {
318                (*rit)->mFlags |= VssRay::BorderSample;
319        }
320
321        // handle rays
322        EnqueueRays(vssRays);
323       
324        const int n = (int)enlargedTriangle.size();
325        int castRays = (int)vssRays.size();
326
327    // recursivly subdivide each edge
328        for (int i = 0; i < n; ++ i)
329        {
330                castRays += SubdivideEdge(hitTriangle,
331                                                                  enlargedTriangle[i],
332                                                                  enlargedTriangle[(i + 1) % n],
333                                                                  *vssRays[i],
334                                                                  *vssRays[(i + 1) % n],
335                                                                  currentRay);
336        }
337
338        mGvsStats.mBorderSamples += castRays;
339
340        return castRays;
341}
342
343
344/*Vector3 GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
345                                                                                 const Triangle3 &hitTriangle,
346                                                                                 const VssRay &oldRay) const
347{
348        //-- intersect triangle plane with plane spanned by current samples
349        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
350        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
351
352        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
353
354        // Evaluate new hitpoint just outside the triangle
355        const float factor = 0.95f;
356        const float t = triPlane.FindT(intersectLine);
357        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
358
359        return newPoint;
360}*/
361
362
363Vector3 GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
364                                                                                 const Triangle3 &occluder,
365                                                                                 const VssRay &oldRay) const
366{
367        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
368        //-- with the newly found occluder (xold is the previous ray from
369        //-- which x was generated). On the intersecting line, we select a point
370        //-- pnew which lies just outside of the new triangle so the ray
371        //-- just passes through the gap
372
373        const Plane3 plane(currentRay.GetOrigin(),
374                                           currentRay.GetTermination(),
375                                           oldRay.GetTermination());
376       
377        Vector3 pt1, pt2;
378
379        const bool intersects = occluder.GetPlaneIntersection(plane, pt1, pt2);
380
381        if (!intersects)
382                cerr << "big error!! no intersection" << endl;
383
384        // get the intersection point on the old ray
385        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
386
387        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
388        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
389
390        // Evaluate new hitpoint just outside the triangle
391        Vector3 newPoint;
392
393        const float eps = mEps;
394        // the point is chosen to be on the side closer to the original ray
395        if (Distance(pt1, pt3) < Distance(pt2, pt3))
396        {
397                newPoint = pt1 + eps * (pt1 - pt2);
398        }       
399        else
400        {
401                newPoint = pt2 + eps * (pt2 - pt1);
402        }
403
404        //cout << "passing point: " << newPoint << endl << endl;
405        return newPoint;
406}
407
408
409VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
410                                                                                 const Triangle3 &hitTriangle,
411                                                                                 const VssRay &oldRay)
412{
413        // get triangle occluding the path to the hit mesh
414        Triangle3 occluder;
415        Intersectable *tObj = currentRay.mTerminationObject;
416
417        // q: why can this happen?
418        if (!tObj)
419                return NULL;
420
421        // other types not implemented yet
422        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
423                occluder = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
424        else
425                cout << "not yet implemented" << endl;
426       
427        // get a point which is passing just outside of the occluder
428    const Vector3 newPoint = GetPassingPoint(currentRay, occluder, oldRay);
429        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
430
431        //-- Construct the mutated ray with xnew,
432        //-- dir = predicted(x)- pnew as direction vector
433        const Vector3 newDir = predicted - newPoint;
434
435        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
436        // difficult to say!!
437        const Vector3 newOrigin = newPoint + newDir * -5000.0f;
438
439        const SimpleRay simpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
440
441        VssRay *reverseRay =
442                mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox());
443
444    ++ mGvsStats.mReverseSamples;
445
446        return reverseRay;
447}
448
449
450int GvsPreprocessor::CastInitialSamples(const int numSamples,
451                                                                                const int sampleType)
452{       
453        const long startTime = GetTime();
454
455        // generate simple rays
456        SimpleRayContainer simpleRays;
457        GenerateRays(numSamples, sampleType, simpleRays);
458
459        // generate vss rays
460        VssRayContainer samples;
461        CastRays(simpleRays, samples, true);
462        // add to ray queue
463        EnqueueRays(samples);
464
465        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
466        return (int)samples.size();
467}
468
469
470void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
471{
472        // add samples to ray queue
473        VssRayContainer::const_iterator vit, vit_end = samples.end();
474        for (vit = samples.begin(); vit != vit_end; ++ vit)
475        {
476                HandleRay(*vit);
477        }
478}
479
480
481int GvsPreprocessor::Pass()
482{
483        // reset samples
484        int castSamples = 0;
485        mGvsStats.mPassContribution = 0;
486
487        while (castSamples < mSamplesPerPass)
488        {       
489                // Ray queue empty =>
490                // cast a number of uniform samples to fill ray queue
491                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
492
493                if (!mOnlyRandomSampling)
494                        castSamples += ProcessQueue();
495        }
496
497        mGvsStats.mTotalContribution += mGvsStats.mPassContribution;
498        return castSamples;
499}
500
501
502int GvsPreprocessor::ProcessQueue()
503{
504        int castSamples = 0;
505        ++ mGvsStats.mGvsPass;
506
507        while (!mRayQueue.empty())
508        {
509                // handle next ray
510                VssRay *ray = mRayQueue.top();
511                mRayQueue.pop();
512
513                castSamples += AdaptiveBorderSampling(*ray);
514                delete ray;
515        }
516       
517        return castSamples;
518}
519
520
521bool GvsPreprocessor::ComputeVisibility()
522{
523        cout << "Gvs Preprocessor started\n" << flush;
524        const long startTime = GetTime();
525
526        Randomize(0);
527       
528        mGvsStats.Reset();
529        mGvsStats.Start();
530
531        if (!mLoadViewCells)
532        {       
533                /// construct the view cells from the scratch
534                ConstructViewCells();
535                // reset pvs already gathered during view cells construction
536                mViewCellsManager->ResetPvs();
537                cout << "finished view cell construction" << endl;
538        }
539        else if (0)
540        {       
541                //-- test successful view cells loading by exporting them again
542                VssRayContainer dummies;
543                mViewCellsManager->Visualize(mObjects, dummies);
544                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
545        }
546
547        mGvsStats.Stop();
548        mGvsStats.Print(mGvsStatsStream);
549
550        while (mGvsStats.mTotalSamples < mTotalSamples)
551        {
552                ++ mPass;
553
554                mGvsStats.mTotalSamples += Pass();
555                               
556                ////////
557                //-- stats
558
559                cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
560                mGvsStats.mPass = mPass;
561                mGvsStats.Stop();
562                mGvsStats.Print(mGvsStatsStream);
563                //mViewCellsManager->PrintPvsStatistics(mGvsStats);
564
565                if (GVS_DEBUG)
566                {
567                        char str[64]; sprintf(str, "tmp/pass%04d-", mPass);
568               
569                        // visualization
570                        if (mGvsStats.mPassContribution > 0)
571                        {
572                                const bool exportRays = true;
573                                const bool exportPvs = true;
574
575                                mViewCellsManager->ExportSingleViewCells(mObjects,
576                                                                                                                 10,
577                                                                                                                 false,
578                                                                                                                 exportPvs,
579                                                                                                                 exportRays,
580                                                                                                                 1000,
581                                                                                                                 str);
582                        }
583
584                        // remove pass samples
585                        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
586                        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
587                        {
588                                (*vit)->DelRayRefs();
589                        }
590                }
591
592                // ComputeRenderError();
593        }
594
595        cout << "cast " << 2 * mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
596
597        if (GVS_DEBUG)
598        {
599                Visualize();
600                CLEAR_CONTAINER(mVssRays);
601        }
602
603        return true;
604}
605
606
607void GvsPreprocessor::Visualize()
608{
609        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
610
611        if (!exporter)
612                return;
613       
614        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
615        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
616        {
617                exporter->SetWireframe();
618                exporter->ExportPolygon((*vit).enlargedTriangle);
619                //Material m;
620                exporter->SetFilled();
621                Polygon3 poly = Polygon3((*vit).originalTriangle);
622                exporter->ExportPolygon(&poly);
623        }
624
625        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
626        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
627        {
628                Intersectable *obj = (*rit)->mTerminationObject;
629                exporter->ExportIntersectable(obj);
630        }
631
632        VssRayContainer vcRays, vcRays2, vcRays3;
633
634        // prepare some rays for output
635        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
636        {
637                const float p = RandomValue(0.0f, (float)mVssRays.size());
638                if (1)//(p < raysOut)
639                {
640                        if ((*rit)->mFlags & VssRay::BorderSample)
641                        {
642                                vcRays.push_back(*rit);
643                        }
644                        else if ((*rit)->mFlags & VssRay::ReverseSample)
645                        {
646                                vcRays2.push_back(*rit);
647                        }
648                        else
649                        {
650                                vcRays3.push_back(*rit);
651                        }       
652                }
653        }
654
655        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
656        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
657        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
658
659        //exporter->ExportRays(mVssRays);
660        delete exporter;
661}
662
663
664void GvsStatistics::Print(ostream &app) const
665{
666        app << "#Pass\n" << mPass << endl;
667        app << "#Time\n" << Time() << endl;
668        app << "#TotalSamples\n" << mTotalSamples << endl;
669        app << "#ScDiff\n" << mPassContribution << endl;
670        app     << "#SamplesContri\n" << mTotalContribution << endl;
671        app << "#ReverseSamples\n" << mReverseSamples << endl;
672        app << "#BorderSamples\n" << mBorderSamples << endl;           
673        app << "#GvsRuns\n" << mGvsPass << endl;
674}
675
676
677}
Note: See TracBrowser for help on using the repository browser.