source: GTP/trunk/Lib/Geom/shared/GTGeometry/src/libs/vmi/src/main.cpp @ 2090

Revision 2090, 16.1 KB checked in by gumbau, 17 years ago (diff)
Line 
1#include "../include/vmi_simplifier.h"
2
3namespace VMI
4{
5GLMmodel *pmodel = NULL; // The .obj model
6
7GLubyte *pixels = NULL;
8
9Camera *cameras = NULL;
10GLuint numCameras = 0;
11
12Color *colors = NULL;
13
14GLuint **histogram = NULL,
15        *queries = NULL;
16
17Mesh *mesh = NULL;
18
19GLdouble *initialIs = NULL;
20
21GLsizei width  = 256,
22        height = 256;
23
24GLboolean bEnableOffScreen = GL_TRUE,
25          bBeQuiet         = GL_FALSE,
26          bSaveLog         = GL_FALSE,
27          bLoadCamerasFromFile = GL_FALSE,
28          bRemoveRedundantVertices = GL_TRUE;
29
30GLuint cameraType = 0,
31       numDemandedTriangles = 0;
32
33GLdouble radius = 1.3, fov = 60.0;
34
35char filename[MAX_CHAR] = {'\0'};
36
37GLuint fb, depth_rb, color_tex;
38
39int vmiWin = 0;
40
41//      For progress update.
42Geometry::TIPOFUNC      mUPB;
43
44}
45
46using namespace VMI;
47
48void VMI::init(void)
49{
50    // Clear color
51    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
52   
53    // Initialize viewing values
54    glMatrixMode(GL_PROJECTION);
55    glLoadIdentity();
56    gluPerspective(fov, (GLdouble)width / height, 0.1, 40.0);
57   
58    //glPixelStorei(GL_PACK_ALIGNMENT, 1);
59    //glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
60   
61    glShadeModel(GL_FLAT);
62   
63    glDisable(GL_BLEND);
64
65    glEnable(GL_CULL_FACE); // important
66
67    glEnable(GL_DEPTH_TEST);
68
69    if (GL_TRUE != glewIsSupported((const char*) "GL_EXT_framebuffer_object"))
70    {
71        fprintf(stderr,"GL_EXT_framebuffer_object extension is not available!\n");
72        exit(1);
73    } else {
74         // create objects
75        glGenFramebuffersEXT(1, &fb);        // frame buffer
76        glGenTextures(1, &color_tex);        // texture
77        glGenRenderbuffersEXT(1, &depth_rb); // render buffer
78        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
79
80        // initialize color texture
81        glBindTexture(GL_TEXTURE_2D, color_tex);
82        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
83                     GL_RGBA, GL_UNSIGNED_BYTE, NULL);
84        // texture parameters
85        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
86        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
87
88        // attach texture to framebuffer color buffer
89        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
90                                  GL_COLOR_ATTACHMENT0_EXT,
91                                  GL_TEXTURE_2D, color_tex, 0);
92        // initialize depth renderbuffer
93        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_rb);
94        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
95                                 GL_DEPTH_COMPONENT24, width, height);
96        // attach renderbuffer to framebuffer depth buffer
97        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
98                                     GL_DEPTH_ATTACHMENT_EXT,
99                                     GL_RENDERBUFFER_EXT, depth_rb);
100
101        // Check framebuffer completeness at the end of initialization.
102        CHECK_FRAMEBUFFER_STATUS();
103    }
104    /*if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_fragment_shader"))
105    {
106        fprintf(stderr,"GL_ARB_fragment_shader extension is not available!\n");
107    }
108    if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_vertex_shader"))
109    {
110        fprintf(stderr,"GL_ARB_vertex_shader extension is not available!\n");
111    }
112    if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_shader_objects"))
113    {
114        fprintf(stderr,"GL_ARB_shader_objects extension is not available!\n");
115    }*/
116    if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_vertex_buffer_object"))
117    {
118        fprintf(stderr,"GL_ARB_vertex_buffer_object extension is not available!\n");
119    } else {
120#ifdef VERTEX_BUFFER_OBJECTS
121       
122        glGenBuffersARB(1, &vertex_buf);
123       
124        glGenBuffersARB(1, &color_buf);
125#endif
126    }
127    if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_occlusion_query"))
128    {
129        fprintf(stderr,"GL_ARB_occlusion_query extension is not available!\n");
130    } else {
131#ifdef USE_OCCLUSION_QUERY
132        // Generate a list of occlusion queries
133        queries = (GLuint *)malloc(mesh->currentNumTriangles * sizeof(GLuint));
134        glGenQueriesARB(mesh->currentNumTriangles, queries);y
135#endif
136    }
137    if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_imaging"))
138    {
139        fprintf(stderr,"GL_ARB_imaging extension is not available!\n");
140    }
141    if (GL_TRUE != glewIsSupported((const char*) "GL_ARB_multitexture"))
142    {
143        fprintf(stderr,"GL_ARB_multitexture extension is not available!\n");
144    }
145#ifdef _WIN32
146    if (GL_TRUE != wglewIsSupported((const char*) "WGL_EXT_swap_control"))
147    {
148        fprintf(stderr,"WGL_EXT_swap_control extension is not available!\n");
149    }
150#endif
151   
152    // Allocate memory for the image pixels
153    pixels = (GLubyte *)malloc(width * height * 4 * sizeof(GLubyte));
154   
155    // Allocate memory for colors
156    colors = initColors(mesh->currentNumTriangles);
157
158    // Set a different color for every triangle
159    setColors4(colors, mesh->currentNumTriangles);
160}
161
162void VMI::applyHWAcceleration(void) {
163   
164#ifdef VERTEX_ARRAY_INTERLEAVE
165    setupInterleave(mesh, colors);
166#endif
167#ifdef VERTEX_ARRAY
168    setupVertexArray(mesh, colors);
169#endif
170#ifdef VERTEX_BUFFER_OBJECTS
171    setupVertexBufferObjects(mesh, colors);
172#endif
173
174}
175
176void VMI::setOrthographicProjection(void) {
177    // Switch to projection mode
178    glMatrixMode(GL_PROJECTION);
179    // Save previous matrix which contains the
180    // settings for the perspective projection
181    glPushMatrix();
182    // Reset matrix
183    glLoadIdentity();
184    glOrtho(0.0, (GLdouble)HISTOGRAM_SIZE, 0.0, (GLdouble)height, -1.0, 1.0);
185    glMatrixMode(GL_MODELVIEW);
186    glLoadIdentity();
187}
188
189void VMI::resetPerspectiveProjection(void) {
190    // Set the current matrix to GL_PROJECTION
191    glMatrixMode(GL_PROJECTION);
192    // Restore previous settings
193    glPopMatrix();
194    // Get back to GL_MODELVIEW matrix
195    glMatrixMode(GL_MODELVIEW);
196    glLoadIdentity();
197}
198
199void VMI::renderBitmapString(float x, float y, void *font, char *string) {
200    char *c;
201    // Set position to start drawing fonts
202    glRasterPos2f(x, y);
203    // Loop all the characters in the string
204    for (c=string; *c != '\0'; c++)
205        glutBitmapCharacter(font, *c);
206}
207
208void VMI::renderGeometry(void) {
209#ifdef IMMEDIATE_MODE
210    GLuint i, v1, v2, v3;
211
212    // Immediate mode
213    glBegin (GL_TRIANGLES);
214    for (i=0; i<mesh->numTriangles; i++) {
215        if (mesh->triangles[i].enable == TRUE) {
216           
217            v1= mesh->triangles[i].indices[0];
218            v2= mesh->triangles[i].indices[1];
219            v3= mesh->triangles[i].indices[2];
220           
221            glColor4ub(colors[i].r, colors[i].g, colors[i].b, colors[i].a);
222            glVertex3f(mesh->vertices[v1].x, mesh->vertices[v1].y, mesh->vertices[v1].z);
223            glVertex3f(mesh->vertices[v2].x, mesh->vertices[v2].y, mesh->vertices[v2].z);
224            glVertex3f(mesh->vertices[v3].x, mesh->vertices[v3].y, mesh->vertices[v3].z);
225        }
226    }
227    glEnd();
228#else
229#ifdef VERTEX_ARRAY
230    glDrawArrays(GL_TRIANGLES, 0, mesh->currentNumTriangles * 3);
231#endif
232#ifdef VERTEX_ARRAY_INTERLEAVE
233    glInterleavedArrays (GL_T2F_C4UB_V3F, 0, intertwined);
234    glDrawArrays(GL_TRIANGLES, 0, mesh->currentNumTriangles * 3);
235#endif
236#ifdef VERTEX_BUFFER_OBJECTS
237    glDrawArrays(GL_TRIANGLES, 0, mesh->currentNumTriangles * 3);
238#endif
239
240#endif
241}
242void VMI::drawTexture(void) {
243
244    // Clear color and depth buffers
245    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
246
247    setOrthographicProjection();
248
249    glEnable(GL_TEXTURE_2D);
250    glBindTexture(GL_TEXTURE_2D, color_tex);
251    glBegin(GL_QUADS);
252   
253    glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f);
254    glTexCoord2f(1.0f, 0.0f); glVertex2f(width, 0.0f);
255    glTexCoord2f(1.0f, 1.0f); glVertex2f(width, height);
256    glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, height);
257
258    glEnd();
259    glFlush();
260    glDisable(GL_TEXTURE_2D);
261
262    resetPerspectiveProjection();
263
264    glutSwapBuffers();
265}
266void VMI::renderScene(GLuint **histogram, GLuint numCameras)
267{
268    GLuint i;
269
270    // draw to the frame buffer
271    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
272       
273    // Apply HW acceleration OpenGL Technique
274    applyHWAcceleration();
275
276    glDrawBuffer(GL_BACK);
277    glReadBuffer(GL_BACK);
278
279    // Get the projected areas for all cameras
280    for (i=0; i<numCameras; i++) {
281       
282        // Clear color and depth buffers
283        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
284       
285        glMatrixMode(GL_MODELVIEW);
286        glLoadIdentity();
287       
288        // Camera  i
289        gluLookAt(cameras[i].eyeX, cameras[i].eyeY, cameras[i].eyeZ,
290                  cameras[i].centerX, cameras[i].centerY, cameras[i].centerZ,
291                  cameras[i].upX, cameras[i].upY, cameras[i].upZ);
292       
293        renderGeometry();
294        glFlush();
295       
296        ///////////////////////////////////////////////////////////////////////////
297       
298        resetSWHistogram(histogram[i], mesh->numTriangles);
299       
300#ifdef USE_OCCLUSION_QUERY
301        getSWHistoByOcclusionQuery(mesh, colors, histogram[i]);
302#else // HYBRID_HW_SW_HISTOGRAM
303        getSWHistogram(histogram[i], pixels);
304#endif
305    }
306
307    // draw to the window, reading from the color texture
308    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
309
310    if (!bEnableOffScreen) drawTexture();
311   
312    ///////////////////////////////////////////////////////////////////////////
313}
314void VMI::renderSceneWin(GLuint **histogram, GLuint numCameras, Change *c)
315{
316    GLuint i, j, t, background;
317    int del_area, mod_area;
318    GLfloat min[3], max[3];
319
320    // draw to the frame buffer
321    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
322
323    //printChange(c);
324    getBoundingBox(c, min, max);
325    //printf("\n(%f,%f,%f)-(%f,%f,%f)\n", min[0], min[1], min[2], max[0], max[1], max[2]);
326   
327    // Apply HW acceleration OpenGL Technique
328    applyHWAcceleration();
329
330    glDrawBuffer(GL_BACK);
331    glReadBuffer(GL_BACK);
332
333    // Get the projected areas for all cameras
334    for (i=0; i<numCameras; i++) {
335       
336        // Clear color and depth buffers
337        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
338       
339        glMatrixMode(GL_MODELVIEW);
340        glLoadIdentity();
341       
342        // Camera  i
343        gluLookAt(cameras[i].eyeX, cameras[i].eyeY, cameras[i].eyeZ,
344                  cameras[i].centerX, cameras[i].centerY, cameras[i].centerZ,
345                  cameras[i].upX, cameras[i].upY, cameras[i].upZ);
346       
347        renderGeometry();
348        glFlush();
349       
350        ///////////////////////////////////////////////////////////////////////////
351        background = histogram[i][0];
352        //printf("b: %d\n", histogram[i][0]);
353
354        del_area = 0;
355        mod_area = 0;
356
357        for (j=0; j<( GLuint)c->numDel; j++) {
358            t = c->deleted[j].id;
359            del_area += histogram[i][t + 1];
360
361            histogram[i][t + 1] = 0;
362        }
363
364        for (j=0; j<( GLuint)c->numMod; j++) {
365            t = c->modified[j].id;
366            del_area += histogram[i][t + 1];
367
368            histogram[i][t + 1] = 0;
369        }
370       
371        getSWHistogramWin(histogram[i], pixels, min, max, c);
372
373        for (j=0; j<( GLuint)c->numMod; j++) {
374            t = c->modified[j].id;
375            mod_area += histogram[i][t + 1];
376
377            //printf("t%d: %d\n",t, histogram[i][t + 1]);
378        }
379        histogram[i][0] = background + (del_area - mod_area);
380        //printf("b: %d\n", histogram[i][0]);
381    }
382    //getchar();
383
384    // draw to the window, reading from the color texture
385    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
386
387    if (!bEnableOffScreen) drawTexture();
388   
389    ///////////////////////////////////////////////////////////////////////////
390}
391
392void VMI::freeMemory(void) {
393
394          // Free memory
395    deleteMesh(mesh);
396
397    //glmDelete(pmodel);
398
399    free(pixels);
400
401    free(cameras);
402
403    free(colors);
404   
405    deleteHistogram(histogram, numCameras);
406
407    free(initialIs);
408   
409    glDeleteRenderbuffersEXT(1, &depth_rb);
410   
411    glDeleteRenderbuffersEXT(1, &color_tex);
412   
413    glDeleteFramebuffersEXT(1, &fb);
414#ifdef USE_OCCLUSION_QUERY
415    glDeleteQueriesARB(mesh->currentNumTriangles, queries);
416#endif
417
418                if (vmiWin != 0)
419                {
420                        glutDestroyWindow(vmiWin);
421                }
422
423#ifdef VERTEX_BUFFER_OBJECTS
424    glDeleteBuffersARB(1, &vertex_buf);
425   
426    glDeleteBuffersARB(1, &color_buf);
427#endif
428
429        pmodel = NULL; // The .obj model
430
431        pixels = NULL;
432
433        cameras = NULL;
434        numCameras = 0;
435
436        colors = NULL;
437
438        histogram = NULL;
439  queries = NULL;
440
441        mesh = NULL;
442
443        initialIs = NULL;
444
445        vmiWin = 0;
446}
447
448void VMI::display(void)
449{
450        clock_t start, finish;
451        GLdouble timeElapsed = 0.0;
452        char s[MAX_CHAR];
453
454        // Clear color and depth buffers
455        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
456        glutSwapBuffers();
457
458        start = clock();
459
460        getProjectedAreas(histogram, numCameras);
461        //printFullHistogram(histogram, numCameras, currentNumTriangles);
462
463#ifdef SALIENCY
464        printf("\nComputing Saliency Map...");
465        computeSaliency(mesh, histogram, numCameras);
466        printf("Ok\n");
467        //getchar();
468        //exit(1);
469#endif
470
471#ifdef KL // Kullback-Leibler
472        printf("\nComputing viewpoint KL divergences...\n");
473#endif
474#ifdef MI // Mutual Information
475        printf("\nComputing viewpoint Mutual Informations...\n");
476#endif
477#ifdef HE // Hellinger
478        printf("\nComputing viewpoint HE divergences...\n");
479#endif
480#ifdef CS // Chi-Square
481        printf("\nComputing viewpoint CS divergences...\n");
482#endif
483
484        computeCameraIs(histogram, numCameras, initialIs);
485
486        printf("Ok\n");
487
488        simplifyModel(mesh, numDemandedTriangles);
489
490        finish = clock();
491        timeElapsed = (GLdouble)(finish - start)/ CLOCKS_PER_SEC;
492        printf("Time: %f\n", timeElapsed);
493
494        glFlush();
495
496#ifdef SALIENCY
497    sprintf(s,"%s_%d_%d_%s_S.obj", filename, numCameras, mesh->currentNumTriangles, EXT);
498#else
499    sprintf(s,"%s_%d_%d_%s.obj", filename, numCameras, mesh->currentNumTriangles, EXT);
500#endif
501
502        //saveModel(s, pmodel, mesh);
503}
504
505void reshape(int w, int h)
506{
507        if (h != 0)
508        {
509                glViewport(0, 0, w, h);      // Set the viewport
510                glMatrixMode(GL_PROJECTION); // Select the projection matrix
511                glLoadIdentity();            // Reset The Projection Matrix
512                //printf("Width: %d Height: %d\n", w, h);
513                gluPerspective(fov, (GLdouble)w/h, 0.1, 40.0);
514                //width = w;
515                //height = h;
516                glMatrixMode(GL_MODELVIEW);  // Switch back to the modelview matrix
517                glLoadIdentity();
518        }
519}
520
521void keyboard(unsigned char key, int x, int y)
522{
523        switch (key)
524        {
525                case 27:
526                        exit(0);
527                default:
528                        break;
529        }
530
531        glutPostRedisplay();
532}
533
534/*  Main Loop
535 *  Open window with initial window size, title bar,
536 *  RGBA display mode, and handle input events.
537 */
538/*int main(int argc, char** argv)
539{
540    char s[MAX_CHAR];
541
542    process_cmdline(argc, argv);
543   
544    // Load a .obj model
545    pmodel = glmReadOBJ(argv[argc-1]);
546    if (!pmodel) exit(0);
547    glmUnitize(pmodel);
548    if (bRemoveRedundantVertices == GL_TRUE)
549        glmWeld(pmodel, 0.00001);
550    //glmFacetNormals(pmodel);
551    //glmVertexNormals(pmodel, 90.0);
552
553    mesh = initMesh(pmodel);
554    //printMesh(mesh);
555    //getchar();
556
557    if ((numDemandedTriangles == 0) || (numDemandedTriangles >= mesh->numTriangles))
558        usage_error("Illegal number of triangles.");
559
560    printf("w: %d h: %d\n", width, height);
561    printf("t: %d c: %d o: %d r: %f\n", numDemandedTriangles, cameraType, bEnableOffScreen, radius);
562    //getchar();
563
564    // Get a filename without extension
565    strncpy(filename, argv[argc - 1], strlen(argv[argc - 1]) - 4);
566   
567    glutInit(&argc, argv);
568    glutInitDisplayMode(GLUT_DEPTH | GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA); // RGB and Alpha
569    glutInitWindowSize(width, height);
570    glutInitWindowPosition(100, 100);
571
572    sprintf(s, "%sW - [%s]", EXT, argv[argc-1]);
573   
574    glutCreateWindow(s);
575
576    glewInit();
577
578    init();
579
580    if (bLoadCamerasFromFile == GL_FALSE)
581        cameras = setCameras(radius, cameraType, &numCameras);
582    else {
583        sprintf(s,"%s.cam", filename);
584       
585        cameras = loadCameras(radius, s, &numCameras);
586        //getchar();
587    }
588
589    histogram = initHistogram(mesh->numTriangles, numCameras);
590
591    initialIs = initIs(numCameras);
592   
593    // Allocate memory for colors
594    colors = initColors(mesh->numTriangles);
595
596    // Set a different color for every triangle
597    setColors4(colors, mesh->numTriangles);
598
599    if (!bEnableOffScreen){
600        glutReshapeFunc(reshape);
601        glutKeyboardFunc(keyboard);
602        glutDisplayFunc(display);
603
604        glutMainLoop();
605    } else display();
606
607    return 0;
608}*/
Note: See TracBrowser for help on using the repository browser.