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

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