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

Revision 2127, 16.8 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;
10int numCameras = 0;
11
12Color *colors = NULL;
13
14int **histogram = NULL;
15GLuint *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
30int 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::updateHWAcceleration(Change *c) {
177   
178#ifdef VERTEX_ARRAY_INTERLEAVE
179    if (interleave != NULL) free(interleave);
180    interleave = setupInterleave(mesh, colors);
181#endif
182#ifdef VERTEX_ARRAY
183    updateVertexArray(mesh, c);
184#endif
185#ifdef VERTEX_BUFFER_OBJECTS
186    updateVertexBufferObjects(mesh, c);
187#endif
188
189}
190
191void VMI::setOrthographicProjection(void) {
192    // Switch to projection mode
193    glMatrixMode(GL_PROJECTION);
194    // Save previous matrix which contains the
195    // settings for the perspective projection
196    glPushMatrix();
197    // Reset matrix
198    glLoadIdentity();
199    glOrtho(0.0, (GLdouble)HISTOGRAM_SIZE, 0.0, (GLdouble)height, -1.0, 1.0);
200    glMatrixMode(GL_MODELVIEW);
201    glLoadIdentity();
202}
203
204void VMI::resetPerspectiveProjection(void) {
205    // Set the current matrix to GL_PROJECTION
206    glMatrixMode(GL_PROJECTION);
207    // Restore previous settings
208    glPopMatrix();
209    // Get back to GL_MODELVIEW matrix
210    glMatrixMode(GL_MODELVIEW);
211    glLoadIdentity();
212}
213
214void VMI::renderBitmapString(float x, float y, void *font, char *string) {
215    char *c;
216    // Set position to start drawing fonts
217    glRasterPos2f(x, y);
218    // Loop all the characters in the string
219    for (c=string; *c != '\0'; c++)
220        glutBitmapCharacter(font, *c);
221}
222
223void VMI::renderGeometry(void) {
224#ifdef IMMEDIATE_MODE
225    int i, v1, v2, v3;
226
227    // Immediate mode
228    glBegin (GL_TRIANGLES);
229    for (i=0; i<mesh->numTriangles; i++) {
230        if (mesh->triangles[i].enable == TRUE) {
231           
232            v1= mesh->triangles[i].indices[0];
233            v2= mesh->triangles[i].indices[1];
234            v3= mesh->triangles[i].indices[2];
235           
236            glColor4ub(colors[i].r, colors[i].g, colors[i].b, colors[i].a);
237            glVertex3f(mesh->vertices[v1].x, mesh->vertices[v1].y, mesh->vertices[v1].z);
238            glVertex3f(mesh->vertices[v2].x, mesh->vertices[v2].y, mesh->vertices[v2].z);
239            glVertex3f(mesh->vertices[v3].x, mesh->vertices[v3].y, mesh->vertices[v3].z);
240        }
241    }
242    glEnd();
243#else
244#ifdef VERTEX_ARRAY
245    glDrawArrays(GL_TRIANGLES, 0, mesh->numTriangles * 3);
246#endif
247#ifdef VERTEX_ARRAY_INTERLEAVE
248    glInterleavedArrays (GL_T2F_C4UB_V3F, 0, intertwined);
249    glDrawArrays(GL_TRIANGLES, 0, mesh->currentNumTriangles * 3);
250#endif
251#ifdef VERTEX_BUFFER_OBJECTS
252    glDrawArrays(GL_TRIANGLES, 0, mesh->numTriangles * 3);
253#endif
254
255#endif
256}
257void VMI::drawTexture(void) {
258
259    // Clear color and depth buffers
260    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
261
262    setOrthographicProjection();
263
264    glEnable(GL_TEXTURE_2D);
265    glBindTexture(GL_TEXTURE_2D, color_tex);
266    glBegin(GL_QUADS);
267   
268    glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f);
269    glTexCoord2f(1.0f, 0.0f); glVertex2f(width, 0.0f);
270    glTexCoord2f(1.0f, 1.0f); glVertex2f(width, height);
271    glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, height);
272
273    glEnd();
274    glFlush();
275    glDisable(GL_TEXTURE_2D);
276
277    resetPerspectiveProjection();
278
279    glutSwapBuffers();
280}
281
282void VMI::resetProjectedAreas(int **histogram, int numCameras) {
283    int i = 0;
284
285    // Reset the projected areas for all cameras
286    for (i=0; i<numCameras; i++)
287        resetSWHistogram(histogram[i], mesh->numTriangles);
288}
289
290void VMI::getProjectedAreas(int **histogram, int numCameras)
291{
292    int i;
293
294    // draw to the frame buffer
295    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
296
297    //glDrawBuffer(GL_BACK);
298    //glReadBuffer(GL_BACK);
299
300    // Get the projected areas for all cameras
301    for (i=0; i<numCameras; i++) {
302       
303        // Clear color and depth buffers
304        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
305       
306        glMatrixMode(GL_MODELVIEW);
307        glLoadIdentity();
308       
309        // Camera  i
310        gluLookAt(cameras[i].eyeX, cameras[i].eyeY, cameras[i].eyeZ,
311                  cameras[i].centerX, cameras[i].centerY, cameras[i].centerZ,
312                  cameras[i].upX, cameras[i].upY, cameras[i].upZ);
313       
314        renderGeometry();
315        glFlush();
316       
317        ///////////////////////////////////////////////////////////////////////////
318       
319        resetSWHistogram(histogram[i], mesh->numTriangles);
320       
321#ifdef USE_OCCLUSION_QUERY
322        getSWHistoByOcclusionQuery(mesh, colors, histogram[i]);
323#else // HYBRID_HW_SW_HISTOGRAM
324        getSWHistogram(histogram[i], pixels);
325#endif
326    }
327
328    // draw to the window, reading from the color texture
329    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
330
331    if (!bEnableOffScreen) drawTexture();
332   
333    ///////////////////////////////////////////////////////////////////////////
334}
335void VMI::getProjectedAreasWin(int **histogram, int numCameras, Change *c)
336{
337    int i, j, t, background;
338    int del_area, mod_area;
339    GLfloat min[3], max[3];
340
341    // draw to the frame buffer
342    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
343
344    //printChange(c);
345    getBoundingBox(c, min, max);
346    //printf("\n(%f,%f,%f)-(%f,%f,%f)\n", min[0], min[1], min[2], max[0], max[1], max[2]);
347   
348    // Update HW acceleration OpenGL Technique
349    updateHWAcceleration(c);
350
351    //glDrawBuffer(GL_BACK);
352    //glReadBuffer(GL_BACK);
353
354    // Get the projected areas for all cameras
355    for (i=0; i<numCameras; i++) {
356       
357        // Clear color and depth buffers
358        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
359       
360        glMatrixMode(GL_MODELVIEW);
361        glLoadIdentity();
362       
363        // Camera  i
364        gluLookAt(cameras[i].eyeX, cameras[i].eyeY, cameras[i].eyeZ,
365                  cameras[i].centerX, cameras[i].centerY, cameras[i].centerZ,
366                  cameras[i].upX, cameras[i].upY, cameras[i].upZ);
367       
368        renderGeometry();
369        glFlush();
370       
371        ///////////////////////////////////////////////////////////////////////////
372        background = histogram[i][0];
373        //printf("b: %d\n", histogram[i][0]);
374
375        del_area = 0;
376        mod_area = 0;
377
378        for (j=0; j<c->numDel; j++) {
379            t = c->deleted[j].id;
380            del_area += histogram[i][t + 1];
381
382            histogram[i][t + 1] = 0;
383        }
384
385        for (j=0; j<c->numMod; j++) {
386            t = c->modified[j].id;
387            del_area += histogram[i][t + 1];
388
389            histogram[i][t + 1] = 0;
390        }
391       
392        getSWHistogramWin(histogram[i], pixels, min, max, c);
393
394        for (j=0; j<c->numMod; j++) {
395            t = c->modified[j].id;
396            mod_area += histogram[i][t + 1];
397
398            //printf("t%d: %d\n",t, histogram[i][t + 1]);
399        }
400        histogram[i][0] = background + (del_area - mod_area);
401        //printf("b: %d\n", histogram[i][0]);
402    }
403    //getchar();
404
405    // draw to the window, reading from the color texture
406    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
407
408    if (!bEnableOffScreen) drawTexture();
409   
410    ///////////////////////////////////////////////////////////////////////////
411}
412
413void VMI::freeMemory(void) {
414
415          // Free memory
416    deleteMesh(mesh);
417
418    //glmDelete(pmodel);
419
420    free(pixels);
421
422    free(cameras);
423
424    free(colors);
425   
426    deleteHistogram(histogram, numCameras);
427
428    free(initialIs);
429   
430    glDeleteRenderbuffersEXT(1, &depth_rb);
431   
432    glDeleteRenderbuffersEXT(1, &color_tex);
433   
434    glDeleteFramebuffersEXT(1, &fb);
435#ifdef USE_OCCLUSION_QUERY
436    glDeleteQueriesARB(mesh->currentNumTriangles, queries);
437#endif
438
439                if (vmiWin != 0)
440                {
441                        glutDestroyWindow(vmiWin);
442                }
443
444#ifdef VERTEX_BUFFER_OBJECTS
445    glDeleteBuffersARB(1, &vertex_buf);
446   
447    glDeleteBuffersARB(1, &color_buf);
448
449    //free(pbuf_vertices);
450    //free(pbuf_colors);
451
452                buf_vertices = NULL;
453    buf_colors = NULL;
454
455#endif
456#ifdef VERTEX_ARRAY
457    //free(pbuf_vertices);
458    //free(pbuf_colors);
459
460                buf_vertices = NULL;
461    buf_colors = NULL;
462#endif
463
464        pmodel = NULL; // The .obj model
465
466        pixels = NULL;
467
468        cameras = NULL;
469        numCameras = 0;
470
471        colors = NULL;
472
473        histogram = NULL;
474  queries = NULL;
475
476        mesh = NULL;
477
478        initialIs = NULL;
479
480        vmiWin = 0;
481}
482
483void VMI::display(void)
484{
485        clock_t start, finish;
486        GLdouble timeElapsed = 0.0;
487        char s[MAX_CHAR];
488
489        // Clear color and depth buffers
490        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
491        glutSwapBuffers();
492
493        start = clock();
494
495        // Apply HW acceleration OpenGL Technique
496  applyHWAcceleration();
497
498        getProjectedAreas(histogram, numCameras);
499        //printFullHistogram(histogram, numCameras, currentNumTriangles);
500
501#ifdef SALIENCY
502        printf("\nComputing Saliency Map...");
503        computeSaliency(mesh, histogram, numCameras);
504        printf("Ok\n");
505        //getchar();
506        //exit(1);
507#endif
508
509#ifdef KL // Kullback-Leibler
510        printf("\nComputing viewpoint KL divergences...\n");
511#endif
512#ifdef MI // Mutual Information
513        printf("\nComputing viewpoint Mutual Informations...\n");
514#endif
515#ifdef HE // Hellinger
516        printf("\nComputing viewpoint HE divergences...\n");
517#endif
518#ifdef CS // Chi-Square
519        printf("\nComputing viewpoint CS divergences...\n");
520#endif
521
522        computeCameraIs(histogram, numCameras, initialIs);
523
524        printf("Ok\n");
525
526        simplifyModel(mesh, numDemandedTriangles);
527
528        finish = clock();
529        timeElapsed = (GLdouble)(finish - start)/ CLOCKS_PER_SEC;
530        printf("Time: %f\n", timeElapsed);
531
532        glFlush();
533
534#ifdef SALIENCY
535    sprintf(s,"%s_%d_%d_%s_S.obj", filename, numCameras, mesh->currentNumTriangles, EXT);
536#else
537    sprintf(s,"%s_%d_%d_%s.obj", filename, numCameras, mesh->currentNumTriangles, EXT);
538#endif
539
540        //saveModel(s, pmodel, mesh);
541}
542
543void reshape(int w, int h)
544{
545        if (h != 0)
546        {
547                glViewport(0, 0, w, h);      // Set the viewport
548                glMatrixMode(GL_PROJECTION); // Select the projection matrix
549                glLoadIdentity();            // Reset The Projection Matrix
550                //printf("Width: %d Height: %d\n", w, h);
551                gluPerspective(fov, (GLdouble)w/h, 0.1, 40.0);
552                //width = w;
553                //height = h;
554                glMatrixMode(GL_MODELVIEW);  // Switch back to the modelview matrix
555                glLoadIdentity();
556        }
557}
558
559void keyboard(unsigned char key, int x, int y)
560{
561        switch (key)
562        {
563                case 27:
564                        exit(0);
565                default:
566                        break;
567        }
568
569        glutPostRedisplay();
570}
571
572/*  Main Loop
573 *  Open window with initial window size, title bar,
574 *  RGBA display mode, and handle input events.
575 */
576/*int main(int argc, char** argv)
577{
578    char s[MAX_CHAR];
579
580    process_cmdline(argc, argv);
581   
582    // Load a .obj model
583    pmodel = glmReadOBJ(argv[argc-1]);
584    if (!pmodel) exit(0);
585    glmUnitize(pmodel);
586    if (bRemoveRedundantVertices == GL_TRUE)
587        glmWeld(pmodel, 0.00001);
588    //glmFacetNormals(pmodel);
589    //glmVertexNormals(pmodel, 90.0);
590
591    mesh = initMesh(pmodel);
592    //printMesh(mesh);
593    //getchar();
594
595    if ((numDemandedTriangles == 0) || (numDemandedTriangles >= mesh->numTriangles))
596        usage_error("Illegal number of triangles.");
597
598    printf("w: %d h: %d\n", width, height);
599    printf("t: %d c: %d o: %d r: %f\n", numDemandedTriangles, cameraType, bEnableOffScreen, radius);
600    //getchar();
601
602    // Get a filename without extension
603    strncpy(filename, argv[argc - 1], strlen(argv[argc - 1]) - 4);
604   
605    glutInit(&argc, argv);
606    glutInitDisplayMode(GLUT_DEPTH | GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA); // RGB and Alpha
607    glutInitWindowSize(width, height);
608    glutInitWindowPosition(100, 100);
609
610    sprintf(s, "%sW - [%s]", EXT, argv[argc-1]);
611   
612    glutCreateWindow(s);
613
614    glewInit();
615
616    init();
617
618    if (bLoadCamerasFromFile == GL_FALSE)
619        cameras = setCameras(radius, cameraType, &numCameras);
620    else {
621        sprintf(s,"%s.cam", filename);
622       
623        cameras = loadCameras(radius, s, &numCameras);
624        //getchar();
625    }
626
627    histogram = initHistogram(mesh->numTriangles, numCameras);
628
629    initialIs = initIs(numCameras);
630   
631    // Allocate memory for colors
632    colors = initColors(mesh->numTriangles);
633
634    // Set a different color for every triangle
635    setColors4(colors, mesh->numTriangles);
636
637    if (!bEnableOffScreen){
638        glutReshapeFunc(reshape);
639        glutKeyboardFunc(keyboard);
640        glutDisplayFunc(display);
641
642        glutMainLoop();
643    } else display();
644
645    return 0;
646}*/
Note: See TracBrowser for help on using the repository browser.