source: nanovis/branches/1.2/nanovis.cpp @ 5497

Last change on this file since 5497 was 5489, checked in by ldelgass, 9 years ago

Move cumulative flow min/max magnitude to Flow.

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