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

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