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

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