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

Revision 1576, 14.3 KB checked in by mattausch, 18 years ago (diff)

added measurement for pvs entries size decrease during subdivision

  • 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 
17struct VizStruct
18{
19        Polygon3 *enlargedTriangle;
20        Triangle3 originalTriangle;
21        VssRay *ray;
22};
23
24static vector<VizStruct> vizContainer;
25
26GvsPreprocessor::GvsPreprocessor():
27Preprocessor(),
28//mSamplingType(SamplingStrategy::DIRECTION_BASED_DISTRIBUTION),
29mSamplingType(SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION),
30mSampleContriPerPass(0),
31mTotalSampleContri(0),
32mReverseSamples(0),
33mBorderSamples(0)
34{
35        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
36        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
37        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.samplesPerPass", mSamplesPerPass);
38        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
39        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
40
41        Debug << "Gvs preprocessor options" << endl;
42        Debug << "number of total samples: " << mTotalSamples << endl;
43        Debug << "number of initial samples: " << mInitialSamples << endl;
44        Debug << "number of samples per pass: " << mSamplesPerPass << endl;
45        Debug << "threshold: " << mThreshold << endl;
46        Debug << "eps: " << mEps << endl;
47
48        mStats.open("gvspreprocessor.log");
49}
50
51
52bool GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
53                                                                                 const Triangle3 &hitTriangle,
54                                                                                 const VssRay &oldRay)
55{
56        const float dist = Magnitude(oldRay.GetDir());
57        const float newDist = Magnitude(currentRay.GetDir());
58 
59#if 0
60        if ((dist - newDist) > mThresHold)
61#else
62        // rather take relative distance
63        if ((dist / newDist) > mThreshold)
64#endif
65        {
66                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
67                // set flag for visualization
68                newRay->mFlags |= VssRay::ReverseSample;
69                cout << "here9444 " << (int) newRay->mFlags << " " << newRay << endl;
70                // ray is not pushed into the queue => can delete ray
71                if (!HandleRay(newRay))
72                        delete newRay;
73               
74                return true;
75        }
76
77        return false;
78}
79
80
81bool GvsPreprocessor::HandleRay(VssRay *vssRay)
82{
83        cout << "x " << (int)vssRay->mFlags;
84        const bool storeRaysForViz = true;
85        mViewCellsManager->ComputeSampleContribution(*vssRay, true, storeRaysForViz);
86               
87        // some pvs contribution for this ray?
88        if (vssRay->mPvsContribution > 0)
89        {
90                mRayQueue.push(vssRay);
91
92                if (storeRaysForViz)
93                {
94                        ViewCellContainer::const_iterator vit, vit_end = vssRay->mViewCells.end();
95                        for (vit = vssRay->mViewCells.begin(); vit != vit_end; ++ vit)
96                        {
97                                VssRay *nray = new VssRay(*vssRay);
98                                nray->mFlags = vssRay->mFlags;
99                                (*vit)->mVssRays.push_back(nray);
100nray->mFlags = 10;
101                                cout << "\nhere58 " << (int)nray->mFlags << "  " << (int)vssRay->mFlags << endl;
102                        }
103                }
104                //mVssRays.push_back(new VssRay(*vssRay));
105        ++ mSampleContriPerPass;
106
107                return true;
108        }
109
110        return false;
111}
112
113
114/** Creates 3 new vertices for triangle vertex with specified index.
115*/
116static void CreateNewVertices(VertexContainer &vertices,
117                                                          const Triangle3 &hitTriangle,
118                                                          const VssRay &ray,
119                                                          const int index,
120                                                          const float eps)
121{
122        const int indexU = (index + 1) % 3;
123        const int indexL = (index == 0) ? 2 : index - 1;
124
125        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
126        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
127        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
128       
129        const float len = Magnitude(a);
130
131        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
132        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
133        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
134                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
135
136        // compute the new three hit points
137        // pi, i + 1:  pi+ e·|pi-xp|·di, j
138        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
139        // pi, i - 1:  pi+ e·|pi-xp|·di, j
140    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
141        // pi, i:  pi+ e·|pi-xp|·di, j
142        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
143       
144        vertices.push_back(pt2);
145        vertices.push_back(pt3);
146        vertices.push_back(pt1);
147}
148
149
150void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
151                                                                          const Triangle3 &hitTriangle,
152                                                                          const VssRay &ray)
153{
154        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
155        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
156        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
157}
158
159
160static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
161                                                                         const Triangle3 &hitTriangle,
162                                                                         const VssRay &oldRay)
163{
164        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
165
166        const Vector3 hitPt =
167                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
168       
169        return hitPt;
170}
171
172
173static bool EqualVisibility(const VssRay &a, const VssRay &b)
174{
175        return a.mTerminationObject == b.mTerminationObject;
176}
177
178
179int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
180                                                                   const Vector3 &p1,
181                                                                   const Vector3 &p2,
182                                                                   const VssRay &x,
183                                                                   const VssRay &y,
184                                                                   const VssRay &oldRay)
185{
186        // the predicted hitpoint expects to hit the same mesh again
187        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
188        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
189
190        CheckDiscontinuity(x, hitTriangle, oldRay);
191        CheckDiscontinuity(y, hitTriangle, oldRay);
192
193        if (EqualVisibility(x, y))
194        {
195                return 0;
196        }
197        else
198        {
199                cout << "s";
200                const Vector3 p = (p1 + p2) * 0.5f;
201                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin);
202       
203                // cast ray into the new subdivision point
204                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), false);
205               
206                if (!newRay) return 0;
207newRay->mFlags |= VssRay::BorderSample;
208                const bool enqueued = HandleRay(newRay);
209               
210                // subdivide further
211                const int s1 = SubdivideEdge(hitTriangle, p1, p, x, *newRay, oldRay);
212                const int s2 = SubdivideEdge(hitTriangle, p, p2, *newRay, y, oldRay);
213                               
214                if (!enqueued)
215                        delete newRay;
216               
217                return s1 + s2 + 1;
218        }
219}
220
221
222int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
223{
224        cout << "a";
225        Intersectable *tObj = currentRay.mTerminationObject;
226        Triangle3 hitTriangle;
227
228        // other types not implemented yet
229        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
230        {
231                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
232        }
233        else
234        {
235                cout << "not yet implemented" << endl;
236        }
237
238        VertexContainer enlargedTriangle;
239       
240        /// create 3 new hit points for each vertex
241        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
242       
243        /// create rays from sample points and handle them
244        SimpleRayContainer simpleRays;
245        simpleRays.reserve(9);
246
247        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
248
249        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
250        {
251                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
252                SimpleRay sr(currentRay.GetOrigin(), rayDir);
253                simpleRays.AddRay(sr);
254        }
255
256        if (0)
257        {
258                VizStruct dummy;
259                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
260                dummy.originalTriangle = hitTriangle;
261                //dummy.ray = new VssRay(currentRay);
262                vizContainer.push_back(dummy);
263        }
264
265        // cast rays to triangle vertices and determine visibility
266        VssRayContainer vssRays;
267        CastRays(simpleRays, vssRays, false, false);
268
269        // add to ray queue
270        EnqueueRays(vssRays);
271       
272        const int n = (int)enlargedTriangle.size();
273        int castRays = (int)vssRays.size();
274
275        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
276        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
277        {
278                (*rit)->mFlags |= VssRay::BorderSample;
279                cout << "here390 " << (int) (*rit)->mFlags << endl;
280        }
281
282#if 1
283    // recursivly subdivide each edge
284        for (int i = 0; i < n; ++ i)
285        {
286                castRays += SubdivideEdge(
287                        hitTriangle,
288                        enlargedTriangle[i],
289                        enlargedTriangle[(i + 1) % n],
290                        *vssRays[i],
291                        *vssRays[(i + 1) % n],
292                        currentRay);
293        }
294#endif
295
296        mBorderSamples += castRays;
297        return castRays;
298}
299
300
301static Vector3 GetPassingPoint(const VssRay &currentRay,
302                                                           const Triangle3 &hitTriangle,
303                                                           const VssRay &oldRay)
304{
305        // intersect triangle plane with plane spanned by current samples
306        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
307        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
308
309        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
310
311        // Evaluate new hitpoint just outside the triangle
312        const float factor = 0.95f;
313        float t = triPlane.FindT(intersectLine);
314        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
315
316        return newPoint;
317}
318
319
320VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
321                                                                                 const Triangle3 &hitTriangle,
322                                                                                 const VssRay &oldRay)
323{
324        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
325        //-- with the newly found triangle (xold is the previous ray from
326        //-- which x was generated). On the intersecting line, we select a point
327        //-- pnew which lies just outside of the new triangle so the ray
328        //-- just passes by inside the gap
329    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
330        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
331
332        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
333        //-- as direction vector
334        const Vector3 newDir = predicted - newPoint ;
335        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
336        // difficult to say!!
337        const Vector3 newOrigin = newDir * -5000.0f;
338
339        ++ mReverseSamples;
340
341        return new VssRay(currentRay);
342}
343
344
345int GvsPreprocessor::CastInitialSamples(const int numSamples,
346                                                                                const int sampleType)
347{       
348        const long startTime = GetTime();
349
350        // generate simple rays
351        SimpleRayContainer simpleRays;
352        GenerateRays(numSamples, sampleType, simpleRays);
353
354        // generate vss rays
355        VssRayContainer samples;
356        CastRays(simpleRays, samples, true);
357        // add to ray queue
358        EnqueueRays(samples);
359
360        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
361        return (int)samples.size();
362}
363
364
365void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
366{
367        // add samples to ray queue
368        VssRayContainer::const_iterator vit, vit_end = samples.end();
369        for (vit = samples.begin(); vit != vit_end; ++ vit)
370        {
371                HandleRay(*vit);
372        }
373}
374
375
376int GvsPreprocessor::Pass()
377{
378        // reset samples
379        int castSamples = 0;
380        mSampleContriPerPass = 0;
381
382        while (castSamples < mSamplesPerPass)
383        {       
384                // Ray queue empty =>
385                // cast a number of uniform samples to fill ray queue
386                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
387                castSamples += ProcessQueue();
388                //cout << "\ncast " << castSamples << " samples in a processing pass" << endl;
389        }
390
391        mTotalSampleContri += mSampleContriPerPass;
392        return castSamples;
393}
394
395
396int GvsPreprocessor::ProcessQueue()
397{
398        int castSamples = 0;
399        ++ mGvsPass;
400
401        while (!mRayQueue.empty())
402        {
403                // handle next ray
404                VssRay *ray = mRayQueue.top();
405                mRayQueue.pop();
406
407                castSamples += AdaptiveBorderSampling(*ray);
408                delete ray;
409        }
410       
411        return castSamples;
412}
413
414
415bool GvsPreprocessor::ComputeVisibility()
416{
417        cout << "Gvs Preprocessor started\n" << flush;
418        const long startTime = GetTime();
419
420        Randomize(0);
421       
422        mPass = 0;
423        mGvsPass = 0;
424        mSampleContriPerPass = 0;
425        mTotalSampleContri = 0;
426        mReverseSamples = 0;
427        mBorderSamples = 0;
428
429        int castSamples = 0;
430
431        if (!mLoadViewCells)
432        {       
433                /// construct the view cells from the scratch
434                ConstructViewCells();
435                cout << "finished view cell construction" << endl;
436        }
437        else if (0)
438        {       
439                //-- load view cells from file
440                //-- test successful view cells loading by exporting them again
441                VssRayContainer dummies;
442                mViewCellsManager->Visualize(mObjects, dummies);
443                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
444        }
445
446        while (castSamples < mTotalSamples)
447        {
448                castSamples += Pass();
449                               
450                ////////
451                //-- stats
452                cout << "\nPass " << mPass << " #samples: " << castSamples << " of " << mTotalSamples << endl;
453
454                //mVssRays.PrintStatistics(mStats);
455                mStats
456                        << "#Pass\n" << mPass << endl
457                        << "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl
458                        << "#TotalSamples\n" << castSamples << endl
459                        << "#ScDiff\n" << mSampleContriPerPass << endl
460                        << "#SamplesContri\n" << mTotalSampleContri << endl
461                        << "#ReverseSamples\n" << mReverseSamples << endl
462                        << "#BorderSamples\n" << mBorderSamples << endl                 
463                        << "#GvsRuns\n" << mGvsPass << endl;
464
465                mViewCellsManager->PrintPvsStatistics(mStats);
466
467                char str[64]; sprintf(str, "tmp/pass%04d-", mPass);
468               
469        // visualization
470                if (mSampleContriPerPass > 0)
471                {
472                        const bool exportRays = true;
473                        const bool exportPvs = true;
474
475                        mViewCellsManager->ExportSingleViewCells(mObjects, 10, false, exportPvs, exportRays, 1000, str);
476                }
477
478                // remove pass samples
479                ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
480                for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
481                {
482                        CLEAR_CONTAINER((*vit)->mVssRays);
483                }
484
485                CLEAR_CONTAINER(mVssRays);
486                // ComputeRenderError();
487                ++ mPass;
488        }
489
490        cout << 2 * castSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
491        Visualize();
492
493        return true;
494}
495
496
497void GvsPreprocessor::Visualize()
498{
499        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
500
501        if (!exporter)
502                return;
503       
504        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
505        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
506        {
507                exporter->SetWireframe();
508                exporter->ExportPolygon((*vit).enlargedTriangle);
509                //Material m;
510                exporter->SetFilled();
511                Polygon3 poly = Polygon3((*vit).originalTriangle);
512                exporter->ExportPolygon(&poly);
513        }
514
515        exporter->ExportRays(mVssRays);
516        delete exporter;
517}
518
519}
Note: See TracBrowser for help on using the repository browser.