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

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