source: nanovis/tags/1.2.2/nanovis.cpp @ 6307

Last change on this file since 6307 was 5500, checked in by ldelgass, 9 years ago

fix merge problem from r5489

  • Property svn:eol-style set to native
File size: 31.7 KB
Line 
1/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 * ----------------------------------------------------------------------
4 * Nanovis: Visualization of Nanoelectronics Data
5 *
6 * ======================================================================
7 *  AUTHOR:  Wei Qiao <qiaow@purdue.edu>
8 *           Michael McLennan <mmclennan@purdue.edu>
9 *           Purdue Rendering and Perceptualization Lab (PURPL)
10 *
11 *  Copyright (c) 2004-2013  HUBzero Foundation, LLC
12 *
13 *  See the file "license.terms" for information on usage and
14 *  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 * ======================================================================
16 */
17
18#include <sys/time.h>
19#include <cassert>
20#include <cstdio>
21#include <cmath> // for fmod()
22
23#include <GL/glew.h>
24#include <GL/glut.h>
25
26#include <graphics/RenderContext.h>
27#include <vrmath/BBox.h>
28#include <vrmath/Vector3f.h>
29
30#include <util/FilePath.h>
31#include <util/Fonts.h>
32
33#include <BMPImageLoaderImpl.h>
34#include <ImageLoaderFactory.h>
35
36#include "config.h"
37#include "nanovis.h"
38#include "nanovisServer.h"
39#include "define.h"
40
41#include "Flow.h"
42#include "Grid.h"
43#include "HeightMap.h"
44#include "Camera.h"
45#include "LIC.h"
46#include "Shader.h"
47#include "OrientationIndicator.h"
48#include "PlaneRenderer.h"
49#include "PPMWriter.h"
50#include "Texture2D.h"
51#include "Trace.h"
52#include "TransferFunction.h"
53#include "Unirect.h"
54#include "VelocityArrowsSlice.h"
55#include "Volume.h"
56#include "VolumeInterpolator.h"
57#include "VolumeRenderer.h"
58
59using namespace nv;
60using namespace nv::graphics;
61using namespace nv::util;
62using namespace vrmath;
63
64// STATIC MEMBER DATA
65
66Tcl_Interp *NanoVis::interp = NULL;
67
68bool NanoVis::redrawPending = false;
69bool NanoVis::debugFlag = false;
70bool NanoVis::axisOn = true;
71
72int NanoVis::winWidth = NPIX;
73int NanoVis::winHeight = NPIX;
74int NanoVis::renderWindow = 0;
75unsigned char *NanoVis::screenBuffer = NULL;
76Texture2D *NanoVis::legendTexture = NULL;
77Fonts *NanoVis::fonts;
78Camera *NanoVis::_camera = NULL;
79RenderContext *NanoVis::renderContext = NULL;
80
81NanoVis::TransferFunctionHashmap NanoVis::tfTable;
82NanoVis::VolumeHashmap NanoVis::volumeTable;
83NanoVis::FlowHashmap NanoVis::flowTable;
84NanoVis::HeightMapHashmap NanoVis::heightMapTable;
85
86float NanoVis::xMin = FLT_MAX;
87float NanoVis::xMax = -FLT_MAX;
88float NanoVis::yMin = FLT_MAX;
89float NanoVis::yMax = -FLT_MAX;
90float NanoVis::zMin = FLT_MAX;
91float NanoVis::zMax = -FLT_MAX;
92BBox NanoVis::sceneBounds;
93
94VolumeRenderer *NanoVis::volRenderer = NULL;
95VelocityArrowsSlice *NanoVis::velocityArrowsSlice = NULL;
96LIC *NanoVis::licRenderer = NULL;
97PlaneRenderer *NanoVis::planeRenderer = NULL;
98OrientationIndicator *NanoVis::orientationIndicator = NULL;
99Grid *NanoVis::grid = NULL;
100
101//frame buffer for final rendering
102GLuint NanoVis::_finalFbo = 0;
103GLuint NanoVis::_finalColorTex = 0;
104GLuint NanoVis::_finalDepthRb = 0;
105
106// Default camera location.
107Vector3f def_eye(0.0f, 0.0f, 2.5f);
108
109void
110NanoVis::removeAllData()
111{
112    TRACE("Enter");
113
114    if (grid != NULL) {
115        TRACE("Deleting grid");
116        delete grid;
117    }
118    if (_camera != NULL) {
119        TRACE("Deleting camera");
120        delete _camera;
121    }
122    if (volRenderer != NULL) {
123        TRACE("Deleting volRenderer");
124        delete volRenderer;
125    }
126    if (planeRenderer != NULL) {
127        TRACE("Deleting planeRenderer");
128        delete planeRenderer;
129    }
130    if (legendTexture != NULL) {
131        TRACE("Deleting legendTexture");
132        delete legendTexture;
133    }
134    TRACE("Deleting flows");
135    deleteFlows(interp);
136    if (licRenderer != NULL) {
137        TRACE("Deleting licRenderer");
138        delete licRenderer;
139    }
140    if (velocityArrowsSlice != NULL) {
141        TRACE("Deleting velocityArrowsSlice");
142        delete velocityArrowsSlice;
143    }
144    if (renderContext != NULL) {
145        TRACE("Deleting renderContext");
146        delete renderContext;
147    }
148    if (screenBuffer != NULL) {
149        TRACE("Deleting screenBuffer");
150        delete [] screenBuffer;
151        screenBuffer = NULL;
152    }
153    if (fonts != NULL) {
154        TRACE("Deleting fonts");
155        delete fonts;
156    }
157    TRACE("Leave");
158}
159
160void
161NanoVis::eventuallyRedraw()
162{
163    if (!redrawPending) {
164        glutPostRedisplay();
165        redrawPending = true;
166    }
167}
168
169void
170NanoVis::panCamera(float dx, float dy)
171{
172    /* Move the camera and its target by equal amounts along the x and y
173     * axes. */
174    TRACE("pan: x=%f, y=%f", dx, dy);
175
176    _camera->x(def_eye.x - dx);
177    _camera->y(def_eye.y + dy);
178    TRACE("set eye to %f %f", _camera->x(), _camera->y());
179}
180
181void
182NanoVis::zoomCamera(float z)
183{
184    /* Move the camera and its target by equal amounts along the x and y
185     * axes. */
186    TRACE("zoom: z=%f", z);
187
188    _camera->z(def_eye.z / z);
189    TRACE("set camera z to %f", _camera->z());
190
191    collectBounds();
192
193    _camera->resetClippingRange(sceneBounds.min, sceneBounds.max);
194}
195
196void
197NanoVis::rotateCamera(float phi, float theta, float psi)
198{
199    _camera->orient(phi, theta, psi);
200}
201
202void
203NanoVis::orientCamera(double *quat)
204{
205    _camera->orient(quat);
206}
207
208void
209NanoVis::setCameraPosition(Vector3f pos)
210{
211    _camera->setPosition(pos);
212}
213
214void
215NanoVis::setCameraUpdir(Camera::AxisDirection dir)
216{
217    _camera->setUpdir(dir);
218}
219
220void
221NanoVis::resetCamera(bool resetOrientation)
222{
223    TRACE("Resetting all=%d", resetOrientation ? 1 : 0);
224
225    collectBounds();
226    _camera->reset(sceneBounds.min, sceneBounds.max, resetOrientation);
227
228    def_eye = _camera->getPosition();
229}
230
231/** \brief Load a 3D volume
232 *
233 * \param name Volume ID
234 * \param width Number of samples in X direction
235 * \param height Number of samples in Y direction
236 * \param depth Number of samples in Z direction
237 * \param numComponents the number of scalars for each space point. All component
238 * scalars for a point are placed consequtively in data array
239 * width, height and depth: number of points in each dimension
240 * \param data Array of floats
241 * \param vmin Min value of field
242 * \param vmax Max value of field
243 * \param nonZeroMin Minimum non-zero value of field
244 * \param data pointer to an array of floats.
245 */
246Volume *
247NanoVis::loadVolume(const char *name, int width, int height, int depth,
248                    int numComponents, float *data, double vmin, double vmax,
249                    double nonZeroMin)
250{
251    VolumeHashmap::iterator itr = volumeTable.find(name);
252    if (itr != volumeTable.end()) {
253        WARN("volume \"%s\" already exists", name);
254        removeVolume(itr->second);
255    }
256
257    Volume *volume = new Volume(width, height, depth,
258                                numComponents,
259                                data, vmin, vmax, nonZeroMin);
260    Volume::updatePending = true;
261    volume->name(name);
262    volumeTable[name] = volume;
263
264    return volume;
265}
266
267// Gets a colormap 1D texture by name.
268TransferFunction *
269NanoVis::getTransferFunction(const TransferFunctionId& id)
270{
271    TransferFunctionHashmap::iterator itr = tfTable.find(id);
272    if (itr == tfTable.end()) {
273        TRACE("No transfer function named \"%s\" found", id.c_str());
274        return NULL;
275    } else {
276        return itr->second;
277    }
278}
279
280// Creates of updates a colormap 1D texture by name.
281TransferFunction *
282NanoVis::defineTransferFunction(const TransferFunctionId& id,
283                                size_t n, float *data)
284{
285    TransferFunction *tf = getTransferFunction(id);
286    if (tf == NULL) {
287        TRACE("Creating new transfer function \"%s\"", id.c_str());
288        tf = new TransferFunction(id.c_str(), n, data);
289        tfTable[id] = tf;
290    } else {
291        TRACE("Updating existing transfer function \"%s\"", id.c_str());
292        tf->update(n, data);
293    }
294    return tf;
295}
296
297int
298NanoVis::renderLegend(TransferFunction *tf, double min, double max,
299                      int width, int height, const char *volArg)
300{
301    TRACE("Enter");
302
303    int old_width = winWidth;
304    int old_height = winHeight;
305
306    planeRenderer->setScreenSize(width, height);
307    resizeOffscreenBuffer(width, height);
308
309    // generate data for the legend
310    float data[512];
311    for (int i=0; i < 256; i++) {
312        data[i] = data[i+256] = (float)(i/255.0);
313    }
314    legendTexture = new Texture2D(256, 2, GL_FLOAT, GL_LINEAR, 1, data);
315    int index = planeRenderer->addPlane(legendTexture, tf);
316    planeRenderer->setActivePlane(index);
317
318    bindOffscreenBuffer();
319    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear screen
320    planeRenderer->render();
321
322    glPixelStorei(GL_PACK_ALIGNMENT, 1);
323    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, screenBuffer);
324    {
325        char prefix[200];
326
327        TRACE("Sending ppm legend image %s min:%g max:%g", volArg, min, max);
328        sprintf(prefix, "nv>legend %s %g %g", volArg, min, max);
329#ifdef USE_THREADS
330        queuePPM(g_queue, prefix, screenBuffer, width, height);
331#else
332        writePPM(g_fdOut, prefix, screenBuffer, width, height);
333#endif
334    }
335    planeRenderer->removePlane(index);
336    resizeOffscreenBuffer(old_width, old_height);
337
338    delete legendTexture;
339    legendTexture = NULL;
340    TRACE("Leave");
341    return TCL_OK;
342}
343
344//initialize frame buffer objects for offscreen rendering
345bool
346NanoVis::initOffscreenBuffer()
347{
348    TRACE("Enter");
349    assert(_finalFbo == 0);
350    // Initialize a fbo for final display.
351    glGenFramebuffersEXT(1, &_finalFbo);
352
353    glGenTextures(1, &_finalColorTex);
354    glBindTexture(GL_TEXTURE_2D, _finalColorTex);
355    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
356    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
357#if defined(HAVE_FLOAT_TEXTURES) && defined(USE_HALF_FLOAT)
358    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, winWidth, winHeight, 0,
359                 GL_RGB, GL_INT, NULL);
360#elif defined(HAVE_FLOAT_TEXTURES)
361    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, winWidth, winHeight, 0,
362                 GL_RGB, GL_INT, NULL);
363#else
364    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, winWidth, winHeight, 0,
365                 GL_RGB, GL_INT, NULL);
366#endif
367
368    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _finalFbo);
369    glGenRenderbuffersEXT(1, &_finalDepthRb);
370    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _finalDepthRb);
371    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,
372                             winWidth, winHeight);
373    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
374                              GL_TEXTURE_2D, _finalColorTex, 0);
375    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
376                                 GL_RENDERBUFFER_EXT, _finalDepthRb);
377
378    GLenum status;
379    if (!CheckFBO(&status)) {
380        PrintFBOStatus(status, "finalFbo");
381        return false;
382    }
383
384    TRACE("Leave");
385    return true;
386}
387
388//resize the offscreen buffer
389bool
390NanoVis::resizeOffscreenBuffer(int w, int h)
391{
392    TRACE("Enter (%d, %d)", w, h);
393    if ((w == winWidth) && (h == winHeight)) {
394        return true;
395    }
396    winWidth = w;
397    winHeight = h;
398
399    if (fonts) {
400        fonts->resize(w, h);
401    }
402    TRACE("screenBuffer size: %d %d", w, h);
403
404    if (screenBuffer != NULL) {
405        delete [] screenBuffer;
406        screenBuffer = NULL;
407    }
408
409    screenBuffer = new unsigned char[3*winWidth*winHeight];
410    assert(screenBuffer != NULL);
411
412    //delete the current render buffer resources
413    glDeleteTextures(1, &_finalColorTex);
414    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _finalDepthRb);
415    glDeleteRenderbuffersEXT(1, &_finalDepthRb);
416
417    TRACE("before deleteframebuffers");
418    glDeleteFramebuffersEXT(1, &_finalFbo);
419
420    TRACE("reinitialize FBO");
421    //Reinitialize final fbo for final display
422    glGenFramebuffersEXT(1, &_finalFbo);
423
424    glGenTextures(1, &_finalColorTex);
425    glBindTexture(GL_TEXTURE_2D, _finalColorTex);
426    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
427    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
428#if defined(HAVE_FLOAT_TEXTURES) && defined(USE_HALF_FLOAT)
429    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, winWidth, winHeight, 0,
430                 GL_RGB, GL_INT, NULL);
431#elif defined(HAVE_FLOAT_TEXTURES)
432    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, winWidth, winHeight, 0,
433                 GL_RGB, GL_INT, NULL);
434#else
435    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, winWidth, winHeight, 0,
436                 GL_RGB, GL_INT, NULL);
437#endif
438
439    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _finalFbo);
440    glGenRenderbuffersEXT(1, &_finalDepthRb);
441    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _finalDepthRb);
442    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,
443                             winWidth, winHeight);
444    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
445                              GL_TEXTURE_2D, _finalColorTex, 0);
446    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
447                                 GL_RENDERBUFFER_EXT, _finalDepthRb);
448
449    GLenum status;
450    if (!CheckFBO(&status)) {
451        PrintFBOStatus(status, "finalFbo");
452        return false;
453    }
454
455    TRACE("change camera");
456    //change the camera setting
457    _camera->setViewport(0, 0, winWidth, winHeight);
458    planeRenderer->setScreenSize(winWidth, winHeight);
459
460    TRACE("Leave (%d, %d)", w, h);
461    return true;
462}
463
464bool NanoVis::init(const char* path)
465{
466    // print OpenGL driver information
467    TRACE("-----------------------------------------------------------");
468    TRACE("OpenGL version: %s", glGetString(GL_VERSION));
469    TRACE("OpenGL vendor: %s", glGetString(GL_VENDOR));
470    TRACE("OpenGL renderer: %s", glGetString(GL_RENDERER));
471    TRACE("-----------------------------------------------------------");
472
473    if (path == NULL) {
474        ERROR("No path defined for shaders or resources");
475        return false;
476    }
477    GLenum err = glewInit();
478    if (GLEW_OK != err) {
479        ERROR("Can't init GLEW: %s", glewGetErrorString(err));
480        return false;
481    }
482    TRACE("Using GLEW %s", glewGetString(GLEW_VERSION));
483
484    // OpenGL 2.1 includes VBOs, PBOs, MRT, NPOT textures, point parameters, point sprites,
485    // GLSL 1.2, and occlusion queries.
486    if (!GLEW_VERSION_2_1) {
487        ERROR("OpenGL version 2.1 or greater is required");
488        return false;
489    }
490
491    // NVIDIA driver may report OpenGL 2.1, but not support PBOs in
492    // indirect GLX contexts
493    if (!GLEW_ARB_pixel_buffer_object) {
494        ERROR("Pixel buffer objects are not supported by driver, please check that the user running nanovis has permissions to create a direct rendering context (e.g. user has read/write access to /dev/nvidia* device nodes in Linux).");
495        return false;
496    }
497
498    // Additional extensions not in 2.1 core
499
500    // Framebuffer objects were promoted in 3.0
501    if (!GLEW_EXT_framebuffer_object) {
502        ERROR("EXT_framebuffer_oject extension is required");
503        return false;
504    }
505    // Rectangle textures were promoted in 3.1
506    // FIXME: can use NPOT in place of rectangle textures
507    if (!GLEW_ARB_texture_rectangle) {
508        ERROR("ARB_texture_rectangle extension is required");
509        return false;
510    }
511#ifdef HAVE_FLOAT_TEXTURES
512    // Float color buffers and textures were promoted in 3.0
513    if (!GLEW_ARB_texture_float ||
514        !GLEW_ARB_color_buffer_float) {
515        ERROR("ARB_texture_float and ARB_color_buffer_float extensions are required");
516        return false;
517    }
518#endif
519    // FIXME: should use GLSL for portability
520#ifdef USE_ARB_PROGRAMS
521    if (!GLEW_ARB_vertex_program ||
522        !GLEW_ARB_fragment_program) {
523        ERROR("ARB_vertex_program and ARB_fragment_program extensions are required");
524        return false;
525    }
526#else
527    if (!GLEW_NV_vertex_program3 ||
528        !GLEW_NV_fragment_program2) {
529        ERROR("NV_vertex_program3 and NV_fragment_program2 extensions are required");
530        return false;
531    }
532#endif
533
534    if (!FilePath::getInstance()->setPath(path)) {
535        ERROR("can't set file path to %s", path);
536        return false;
537    }
538
539    ImageLoaderFactory::getInstance()->addLoaderImpl("bmp", new BMPImageLoaderImpl());
540
541    return true;
542}
543
544bool
545NanoVis::initGL()
546{
547    TRACE("in initGL");
548    //buffer to store data read from the screen
549    if (screenBuffer) {
550        delete[] screenBuffer;
551        screenBuffer = NULL;
552    }
553    screenBuffer = new unsigned char[3*winWidth*winHeight];
554    assert(screenBuffer != NULL);
555
556    //create the camera with default setting
557    _camera = new Camera(0, 0, winWidth, winHeight);
558    _camera->setPosition(def_eye);
559
560    glEnable(GL_TEXTURE_2D);
561    glShadeModel(GL_FLAT);
562    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
563    glClearColor(0, 0, 0, 1);
564    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
565
566    //initialize lighting
567    GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0};
568    GLfloat mat_shininess[] = {30.0};
569    GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0};
570
571    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
572    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
573    glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);
574    glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);
575    glLightfv(GL_LIGHT1, GL_DIFFUSE, white_light);
576    glLightfv(GL_LIGHT1, GL_SPECULAR, white_light);
577
578    //frame buffer object for offscreen rendering
579    if (!initOffscreenBuffer()) {
580        return false;
581    }
582
583    fonts = new Fonts();
584    fonts->addFont("verdana", "verdana.fnt");
585    fonts->setFont("verdana");
586
587    renderContext = new RenderContext();
588
589    volRenderer = new VolumeRenderer();
590
591    planeRenderer = new PlaneRenderer(winWidth, winHeight);
592
593    velocityArrowsSlice = new VelocityArrowsSlice();
594
595    licRenderer = new LIC();
596
597#ifdef USE_ORIENTATION_INDICATOR
598    orientationIndicator = new OrientationIndicator();
599#endif
600
601    grid = new Grid();
602    grid->setFont(fonts);
603
604    //assert(glGetError()==0);
605
606    TRACE("leaving initGL");
607
608    return true;
609}
610
611void
612NanoVis::draw3dAxis()
613{
614    if (!axisOn)
615        return;
616
617    glPushAttrib(GL_ENABLE_BIT);
618
619    glDisable(GL_TEXTURE_2D);
620    glEnable(GL_DEPTH_TEST);
621    glEnable(GL_COLOR_MATERIAL);
622    glDisable(GL_BLEND);
623
624    //draw axes
625    GLUquadric *obj;
626
627    obj = gluNewQuadric();
628
629    int segments = 50;
630
631    glColor3f(0.8, 0.8, 0.8);
632    glPushMatrix();
633    glTranslatef(0.4, 0., 0.);
634    glRotatef(90, 1, 0, 0);
635    glRotatef(180, 0, 1, 0);
636    glScalef(0.0005, 0.0005, 0.0005);
637    glutStrokeCharacter(GLUT_STROKE_ROMAN, 'x');
638    glPopMatrix();
639
640    glPushMatrix();
641    glTranslatef(0., 0.4, 0.);
642    glRotatef(90, 1, 0, 0);
643    glRotatef(180, 0, 1, 0);
644    glScalef(0.0005, 0.0005, 0.0005);
645    glutStrokeCharacter(GLUT_STROKE_ROMAN, 'y');
646    glPopMatrix();
647
648    glPushMatrix();
649    glTranslatef(0., 0., 0.4);
650    glRotatef(90, 1, 0, 0);
651    glRotatef(180, 0, 1, 0);
652    glScalef(0.0005, 0.0005, 0.0005);
653    glutStrokeCharacter(GLUT_STROKE_ROMAN, 'z');
654    glPopMatrix();
655
656    glEnable(GL_LIGHTING);
657    glEnable(GL_LIGHT0);
658
659    //glColor3f(0.2, 0.2, 0.8);
660    glPushMatrix();
661    glutSolidSphere(0.02, segments, segments );
662    glPopMatrix();
663
664    glPushMatrix();
665    glRotatef(-90, 1, 0, 0);
666    gluCylinder(obj, 0.01, 0.01, 0.3, segments, segments);
667    glPopMatrix();
668
669    glPushMatrix();
670    glTranslatef(0., 0.3, 0.);
671    glRotatef(-90, 1, 0, 0);
672    gluCylinder(obj, 0.02, 0.0, 0.06, segments, segments);
673    glPopMatrix();
674
675    glPushMatrix();
676    glRotatef(90, 0, 1, 0);
677    gluCylinder(obj, 0.01, 0.01, 0.3, segments, segments);
678    glPopMatrix();
679
680    glPushMatrix();
681    glTranslatef(0.3, 0., 0.);
682    glRotatef(90, 0, 1, 0);
683    gluCylinder(obj, 0.02, 0.0, 0.06, segments, segments);
684    glPopMatrix();
685
686    glPushMatrix();
687    gluCylinder(obj, 0.01, 0.01, 0.3, segments, segments);
688    glPopMatrix();
689
690    glPushMatrix();
691    glTranslatef(0., 0., 0.3);
692    gluCylinder(obj, 0.02, 0.0, 0.06, segments, segments);
693    glPopMatrix();
694
695    gluDeleteQuadric(obj);
696
697    glPopAttrib();
698}
699
700void NanoVis::update()
701{
702    VolumeInterpolator *volInterp = volRenderer->getVolumeInterpolator();
703    if (volInterp->isStarted()) {
704        struct timeval clock;
705        gettimeofday(&clock, NULL);
706        double elapsed_time = clock.tv_sec + clock.tv_usec/1000000.0 -
707            volInterp->getStartTime();
708
709        TRACE("%g %g", elapsed_time,
710              volInterp->getInterval());
711        double fraction;
712        double f = fmod(elapsed_time, volInterp->getInterval());
713        if (f == 0.0) {
714            fraction = 0.0;
715        } else {
716            fraction = f / volInterp->getInterval();
717        }
718        TRACE("fraction : %g", fraction);
719        volInterp->update((float)fraction);
720    }
721}
722
723/**
724 * \brief Called when new volumes are added to update ranges
725 */
726void
727NanoVis::setVolumeRanges()
728{
729    TRACE("Enter");
730
731    double xMin, xMax, yMin, yMax, zMin, zMax;
732    xMin = yMin = zMin = DBL_MAX;
733    xMax = yMax = zMax = -DBL_MAX;
734    double valueMin = DBL_MAX, valueMax = -DBL_MAX;
735    VolumeHashmap::iterator itr;
736    for (itr = volumeTable.begin();
737         itr != volumeTable.end(); ++itr) {
738        Volume *volume = itr->second;
739        if (xMin > volume->xAxis.min()) {
740            xMin = volume->xAxis.min();
741        }
742        if (xMax < volume->xAxis.max()) {
743            xMax = volume->xAxis.max();
744        }
745        if (yMin > volume->yAxis.min()) {
746            yMin = volume->yAxis.min();
747        }
748        if (yMax < volume->yAxis.max()) {
749            yMax = volume->yAxis.max();
750        }
751        if (zMin > volume->zAxis.min()) {
752            zMin = volume->zAxis.min();
753        }
754        if (zMax < volume->zAxis.max()) {
755            zMax = volume->zAxis.max();
756        }
757        if (valueMin > volume->wAxis.min()) {
758            valueMin = volume->wAxis.min();
759        }
760        if (valueMax < volume->wAxis.max()) {
761            valueMax = volume->wAxis.max();
762        }
763    }
764    if ((xMin < DBL_MAX) && (xMax > -DBL_MAX)) {
765        grid->xAxis.setScale(xMin, xMax);
766    }
767    if ((yMin < DBL_MAX) && (yMax > -DBL_MAX)) {
768        grid->yAxis.setScale(yMin, yMax);
769    }
770    if ((zMin < DBL_MAX) && (zMax > -DBL_MAX)) {
771        grid->zAxis.setScale(zMin, zMax);
772    }
773    if ((valueMin < DBL_MAX) && (valueMax > -DBL_MAX)) {
774        Volume::valueMin = valueMin;
775        Volume::valueMax = valueMax;
776    }
777    Volume::updatePending = false;
778    TRACE("Leave");
779}
780
781/**
782 * \brief Called when new heightmaps are added to update ranges
783 */
784void
785NanoVis::setHeightmapRanges()
786{
787    TRACE("Enter");
788
789    double xMin, xMax, yMin, yMax, zMin, zMax;
790    xMin = yMin = zMin = DBL_MAX;
791    xMax = yMax = zMax = -DBL_MAX;
792    double valueMin = DBL_MAX, valueMax = -DBL_MAX;
793    HeightMapHashmap::iterator itr;
794    for (itr = heightMapTable.begin();
795         itr != heightMapTable.end(); ++itr) {
796        HeightMap *heightMap = itr->second;
797        if (xMin > heightMap->xAxis.min()) {
798            xMin = heightMap->xAxis.min();
799        }
800        if (xMax < heightMap->xAxis.max()) {
801            xMax = heightMap->xAxis.max();
802        }
803        if (yMin > heightMap->yAxis.min()) {
804            yMin = heightMap->yAxis.min();
805        }
806        if (yMax < heightMap->yAxis.max()) {
807            yMax = heightMap->yAxis.max();
808        }
809        if (zMin > heightMap->zAxis.min()) {
810            zMin = heightMap->zAxis.min();
811        }
812        if (zMax < heightMap->zAxis.max()) {
813            zMax = heightMap->zAxis.max();
814        }
815        if (valueMin > heightMap->wAxis.min()) {
816            valueMin = heightMap->wAxis.min();
817        }
818        if (valueMax < heightMap->wAxis.max()) {
819            valueMax = heightMap->wAxis.max();
820        }
821    }
822    if ((xMin < DBL_MAX) && (xMax > -DBL_MAX)) {
823        grid->xAxis.setScale(xMin, xMax);
824    }
825    if ((yMin < DBL_MAX) && (yMax > -DBL_MAX)) {
826        grid->yAxis.setScale(yMin, yMax);
827    }
828    if ((zMin < DBL_MAX) && (zMax > -DBL_MAX)) {
829        grid->zAxis.setScale(zMin, zMax);
830    }
831    if ((valueMin < DBL_MAX) && (valueMax > -DBL_MAX)) {
832        HeightMap::valueMin = valueMin;
833        HeightMap::valueMax = valueMax;
834    }
835    for (HeightMapHashmap::iterator itr = heightMapTable.begin();
836         itr != heightMapTable.end(); ++itr) {
837        itr->second->mapToGrid(grid);
838    }
839    HeightMap::updatePending = false;
840    TRACE("Leave");
841}
842
843void
844NanoVis::collectBounds(bool onlyVisible)
845{
846    if (Flow::updatePending) {
847        setFlowRanges();
848        grid->xAxis.setScale(xMin, xMax);
849        grid->yAxis.setScale(yMin, yMax);
850        grid->zAxis.setScale(zMin, zMax);
851    }
852
853    sceneBounds.makeEmpty();
854
855    for (VolumeHashmap::iterator itr = volumeTable.begin();
856         itr != volumeTable.end(); ++itr) {
857        Volume *volume = itr->second;
858
859        if (onlyVisible && !volume->visible())
860            continue;
861
862        BBox bbox;
863        volume->getWorldSpaceBounds(bbox.min, bbox.max);
864        sceneBounds.extend(bbox);
865    }
866
867    for (HeightMapHashmap::iterator itr = heightMapTable.begin();
868         itr != heightMapTable.end(); ++itr) {
869        HeightMap *heightMap = itr->second;
870
871        if (onlyVisible && !heightMap->isVisible())
872            continue;
873
874        BBox bbox;
875        heightMap->getWorldSpaceBounds(bbox.min, bbox.max);
876        sceneBounds.extend(bbox);
877    }
878
879    for (FlowHashmap::iterator itr = flowTable.begin();
880         itr != flowTable.end(); ++itr) {
881        Flow *flow = itr->second;
882
883        BBox bbox;
884        flow->getBounds(bbox.min, bbox.max, onlyVisible);
885        sceneBounds.extend(bbox);
886    }
887
888#if 0
889    if (!onlyVisible || grid->isVisible()) {
890        BBox bbox;
891        grid->getBounds(bbox.min, bbox.max);
892        sceneBounds.extend(bbox);
893    }
894#endif
895
896    if (sceneBounds.isEmpty()) {
897        sceneBounds.min.set(-0.5, -0.5, -0.5);
898        sceneBounds.max.set( 0.5,  0.5,  0.5);
899    }
900
901    TRACE("Scene bounds: (%g,%g,%g) - (%g,%g,%g)",
902          sceneBounds.min.x, sceneBounds.min.y, sceneBounds.min.z,
903          sceneBounds.max.x, sceneBounds.max.y, sceneBounds.max.z);
904}
905
906void
907NanoVis::setBgColor(float color[3])
908{
909    TRACE("Setting bgcolor to %g %g %g", color[0], color[1], color[2]);
910    glClearColor(color[0], color[1], color[2], 1);
911}
912
913void
914NanoVis::removeVolume(Volume *volume)
915{
916    VolumeHashmap::iterator itr = volumeTable.find(volume->name());
917    if (itr != volumeTable.end()) {
918        volumeTable.erase(itr);
919    }
920    delete volume;
921}
922
923Flow *
924NanoVis::getFlow(const char *name)
925{
926    FlowHashmap::iterator itr = flowTable.find(name);
927    if (itr == flowTable.end()) {
928        TRACE("Can't find flow '%s'", name);
929        return NULL;
930    }
931    return itr->second;
932}
933
934Flow *
935NanoVis::createFlow(Tcl_Interp *interp, const char *name)
936{
937    FlowHashmap::iterator itr = flowTable.find(name);
938    if (itr != flowTable.end()) {
939        ERROR("Flow '%s' already exists", name);
940        return NULL;
941    }
942    Flow *flow = new Flow(interp, name);
943    flowTable[name] = flow;
944    return flow;
945}
946
947/**
948 * \brief Delete flow object and hash table entry
949 *
950 * This is called by the flow command instance delete callback
951 */
952void
953NanoVis::deleteFlow(const char *name)
954{
955    FlowHashmap::iterator itr = flowTable.find(name);
956    if (itr != flowTable.end()) {
957        delete itr->second;
958        flowTable.erase(itr);
959    }
960}
961
962/**
963 * \brief Delete all flow object commands
964 *
965 * This will also delete the flow objects and hash table entries
966 */
967void
968NanoVis::deleteFlows(Tcl_Interp *interp)
969{
970    FlowHashmap::iterator itr;
971    for (itr = flowTable.begin();
972         itr != flowTable.end(); ++itr) {
973        Tcl_DeleteCommandFromToken(interp, itr->second->getCommandToken());
974    }
975    flowTable.clear();
976}
977
978/**
979 * \brief Called when new flows are added to update ranges
980 */
981bool
982NanoVis::setFlowRanges()
983{
984    TRACE("Enter");
985
986    /*
987     * Step 1. Get the overall min and max magnitudes of all the
988     *         flow vectors.
989     */
990    Flow::magMin = DBL_MAX;
991    Flow::magMax = -DBL_MAX;
992
993    for (FlowHashmap::iterator itr = flowTable.begin();
994         itr != flowTable.end(); ++itr) {
995        Flow *flow = itr->second;
996        if (!flow->isDataLoaded()) {
997            continue;
998        }
999        Unirect3d *data = flow->data();
1000        double range[2];
1001        range[0] = data->magMin();
1002        range[1] = data->magMax();
1003        if (range[0] < Flow::magMin) {
1004            Flow::magMin = range[0];
1005        }
1006        if (range[1] > Flow::magMax) {
1007            Flow::magMax = range[1];
1008        }
1009        if (data->xMin() < xMin) {
1010            xMin = data->xMin();
1011        }
1012        if (data->yMin() < yMin) {
1013            yMin = data->yMin();
1014        }
1015        if (data->zMin() < zMin) {
1016            zMin = data->zMin();
1017        }
1018        if (data->xMax() > xMax) {
1019            xMax = data->xMax();
1020        }
1021        if (data->yMax() > yMax) {
1022            yMax = data->yMax();
1023        }
1024        if (data->zMax() > zMax) {
1025            zMax = data->zMax();
1026        }
1027    }
1028
1029    TRACE("magMin=%g magMax=%g", Flow::magMin, Flow::magMax);
1030
1031    /*
1032     * Step 2. Generate the vector field from each data set.
1033     */
1034    for (FlowHashmap::iterator itr = flowTable.begin();
1035         itr != flowTable.end(); ++itr) {
1036        Flow *flow = itr->second;
1037        if (!flow->isDataLoaded()) {
1038            continue; // Flow exists, but no data has been loaded yet.
1039        }
1040        if (flow->visible()) {
1041            flow->initializeParticles();
1042        }
1043        if (!flow->scaleVectorField()) {
1044            return false;
1045        }
1046        // FIXME: This doesn't work when there is more than one flow.
1047        licRenderer->setSlicePosition(flow->getRelativePosition());
1048        velocityArrowsSlice->setSlicePosition(flow->getRelativePosition());
1049    }
1050    advectFlows();
1051
1052    Flow::updatePending = false;
1053    return true;
1054}
1055
1056void
1057NanoVis::renderFlows()
1058{
1059    for (FlowHashmap::iterator itr = flowTable.begin();
1060         itr != flowTable.end(); ++itr) {
1061        Flow *flow = itr->second;
1062        if (flow->isDataLoaded() && flow->visible()) {
1063            flow->render();
1064        }
1065    }
1066}
1067
1068void
1069NanoVis::resetFlows()
1070{
1071    NanoVis::licRenderer->reset();
1072    for (FlowHashmap::iterator itr = flowTable.begin();
1073         itr != flowTable.end(); ++itr) {
1074        Flow *flow = itr->second;
1075        if (flow->isDataLoaded()) {
1076            flow->resetParticles();
1077        }
1078    }
1079}   
1080
1081void
1082NanoVis::advectFlows()
1083{
1084    TRACE("Enter");
1085    for (FlowHashmap::iterator itr = flowTable.begin();
1086         itr != flowTable.end(); ++itr) {
1087        Flow *flow = itr->second;
1088        if (flow->isDataLoaded()) {
1089            flow->advect();
1090        }
1091    }
1092}
1093
1094void
1095NanoVis::render()
1096{
1097    TRACE("Enter");
1098
1099    if (Flow::updatePending) {
1100        setFlowRanges();
1101        grid->xAxis.setScale(xMin, xMax);
1102        grid->yAxis.setScale(yMin, yMax);
1103        grid->zAxis.setScale(zMin, zMax);
1104    }
1105    if (HeightMap::updatePending) {
1106        setHeightmapRanges();
1107    }
1108    if (Volume::updatePending) {
1109        setVolumeRanges();
1110    }
1111
1112    // Start final rendering
1113
1114    // Need to reset fbo since it may have been changed to default (0)
1115    bindOffscreenBuffer();
1116
1117    // Clear screen
1118    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1119
1120    glEnable(GL_DEPTH_TEST);
1121    glEnable(GL_COLOR_MATERIAL);
1122
1123    // Emit modelview and projection matrices
1124    _camera->initialize();
1125
1126    // Rotate for updir if required
1127    glPushMatrix();
1128
1129    switch (_camera->getUpdir()) {
1130    case Camera::X_POS:
1131        glRotatef(90, 0, 0, 1);
1132        glRotatef(90, 1, 0, 0);
1133        break;
1134    case Camera::Y_POS:
1135        // this is the default
1136        break;
1137    case Camera::Z_POS:
1138        glRotatef(-90, 1, 0, 0);
1139        glRotatef(-90, 0, 0, 1);
1140        break;
1141    case Camera::X_NEG:
1142        glRotatef(-90, 0, 0, 1);
1143        break;
1144    case Camera::Y_NEG:
1145        glRotatef(180, 0, 0, 1);
1146        glRotatef(-90, 0, 1, 0);
1147        break;
1148    case Camera::Z_NEG:
1149        glRotatef(90, 1, 0, 0);
1150        break;
1151    }
1152
1153    // Now render things in the scene
1154#ifdef USE_ORIENTATION_INDICATOR
1155    orientationIndicator->setPosition(sceneBounds.getCenter());
1156    orientationIndicator->setScale(sceneBounds.getSize());
1157    orientationIndicator->render();
1158#else
1159    draw3dAxis();
1160#endif
1161
1162    grid->render();
1163
1164    licRenderer->render();
1165
1166    velocityArrowsSlice->render();
1167
1168    renderFlows();
1169
1170    volRenderer->renderAll();
1171
1172    for (HeightMapHashmap::iterator itr = heightMapTable.begin();
1173         itr != heightMapTable.end(); ++itr) {
1174        itr->second->render(renderContext);
1175    }
1176    glPopMatrix();
1177
1178    CHECK_FRAMEBUFFER_STATUS();
1179    TRACE("Leave");
1180    redrawPending = false;
1181}
Note: See TracBrowser for help on using the repository browser.