source: branches/1.4/gui/scripts/nanovisviewer.tcl @ 5288

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

Bring volume settings tab look in line with trunk. Also, disable application
of volume component opacity style setting, since some tools erronenously set
this to 1.

File size: 80.4 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: nanovisviewer - 3D volume rendering
4#
5#  This widget performs volume rendering on 3D scalar/vector datasets.
6#  It connects to the Nanovis server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17package require Img
18
19#
20# FIXME:
21#       Need to Add DX readers this client to examine the data before
22#       it's sent to the server.  This will eliminate 90% of the insanity in
23#       computing the limits of all the volumes.  I can rip out all the
24#       "receive data" "send transfer function" event crap.
25#
26#       This means we can compute the transfer function (relative values) and
27#       draw the legend min/max values without waiting for the information to
28#       come from the server.  This will also prevent the flashing that occurs
29#       when a new volume is drawn (using the default transfer function) and
30#       then when the correct transfer function has been sent and linked to
31#       the volume.
32#
33option add *NanovisViewer.width 4i widgetDefault
34option add *NanovisViewer*cursor crosshair widgetDefault
35option add *NanovisViewer.height 4i widgetDefault
36option add *NanovisViewer.foreground black widgetDefault
37option add *NanovisViewer.controlBackground gray widgetDefault
38option add *NanovisViewer.controlDarkBackground #999999 widgetDefault
39option add *NanovisViewer.plotBackground black widgetDefault
40option add *NanovisViewer.plotForeground white widgetDefault
41option add *NanovisViewer.plotOutline gray widgetDefault
42option add *NanovisViewer.font \
43    -*-helvetica-medium-r-normal-*-12-* widgetDefault
44
45# must use this name -- plugs into Rappture::resources::load
46proc NanovisViewer_init_resources {} {
47    Rappture::resources::register \
48        nanovis_server Rappture::NanovisViewer::SetServerList
49}
50
51itcl::class Rappture::NanovisViewer {
52    inherit Rappture::VisViewer
53
54    itk_option define -plotforeground plotForeground Foreground ""
55    itk_option define -plotbackground plotBackground Background ""
56    itk_option define -plotoutline plotOutline PlotOutline ""
57
58    constructor { hostlist args } {
59        Rappture::VisViewer::constructor $hostlist
60    } {
61        # defined below
62    }
63    destructor {
64        # defined below
65    }
66    public proc SetServerList { namelist } {
67        Rappture::VisViewer::SetServerList "nanovis" $namelist
68    }
69    public method add {dataobj {settings ""}}
70    public method camera {option args}
71    public method delete {args}
72    public method disconnect {}
73    public method download {option args}
74    public method get {args}
75    public method isconnected {}
76    public method parameters {title args} {
77        # do nothing
78    }
79    public method scale {args}
80    public method updateTransferFunctions {}
81
82    # The following methods are only used by this class.
83    private method AddNewMarker { x y }
84    private method AdjustSetting {what {value ""}}
85    private method BuildCameraTab {}
86    private method BuildCutplanesTab {}
87    private method BuildViewTab {}
88    private method BuildVolumeComponents {}
89    private method BuildVolumeTab {}
90    private method ComputeAlphamap { cname }
91    private method ComputeTransferFunction { cname }
92    private method Connect {}
93    private method CurrentDatasets {{what -all}}
94    private method Disconnect {}
95    private method DoResize {}
96    private method DrawLegend { cname }
97    private method EventuallyRedrawLegend { }
98    private method EventuallyResize { w h }
99    private method FixLegend {}
100    private method GetColormap { cname color }
101    private method GetDatasetsWithComponent { cname }
102    private method GetVolumeInfo { w }
103    private method HideAllMarkers {}
104    private method InitComponentSettings { cname }
105    private method InitSettings { args }
106    private method NameTransferFunction { dataobj comp }
107    private method Pan {option x y}
108    private method PanCamera {}
109    private method ParseLevelsOption { cname levels }
110    private method ParseMarkersOption { cname markers }
111    private method QuaternionToView { q } {
112        foreach { _view(-qw) _view(-qx) _view(-qy) _view(-qz) } $q break
113    }
114    private method Rebuild {}
115    private method ReceiveData { args }
116    private method ReceiveImage { args }
117    private method ReceiveLegend { tf vmin vmax size }
118    private method RemoveMarker { x y }
119    private method ResetColormap { cname color }
120    private method Rotate {option x y}
121    private method SendTransferFunctions {}
122    private method SetObjectStyle { dataobj cname }
123    private method SetOrientation { side }
124    private method Slice {option args}
125    private method SlicerTip {axis}
126    private method SwitchComponent { cname }
127    private method ToggleVolume { tag name }
128    private method ViewToQuaternion {} {
129        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
130    }
131    private method Zoom {option}
132
133    private variable _arcball ""
134
135    private variable _dlist ""         ;# list of data objects
136    private variable _obj2ovride       ;# maps dataobj => style override
137    private variable _serverDatasets   ;# contains all the dataobj-component
138                                       ;# to volumes in the server
139    private variable _recvdDatasets    ;# list of data objs to send to server
140
141    private variable _reset 1          ;# Connection to server has been reset.
142    private variable _click            ;# Info used for rotate operations.
143    private variable _limits           ;# Autoscale min/max for all axes
144    private variable _view             ;# View params for 3D view
145    private variable _parsedFunction
146    private variable _transferFunctionEditors
147    private variable _settings
148    private variable _widget
149
150    private variable _first ""         ;# This is the topmost volume.
151    private variable _current ""       ;# Currently selected component
152    private variable _volcomponents    ;# Array of components found
153    private variable _componentsList   ;# Array of components found
154    private variable _cname2transferFunction
155    private variable _cname2defaultcolormap
156
157    common _downloadPopup              ;# download options from popup
158    private common _hardcopy
159    private variable _width 0
160    private variable _height 0
161    private variable _resizePending 0
162    private variable _resizeLegendPending 0
163}
164
165itk::usual NanovisViewer {
166    keep -background -foreground -cursor -font
167    keep -plotbackground -plotforeground
168}
169
170# ----------------------------------------------------------------------
171# CONSTRUCTOR
172# ----------------------------------------------------------------------
173itcl::body Rappture::NanovisViewer::constructor {hostlist args} {
174    set _serverType "nanovis"
175
176    # Draw legend event
177    $_dispatcher register !legend
178    $_dispatcher dispatch $this !legend "[itcl::code $this FixLegend]; list"
179
180    # Send transfer functions event
181    $_dispatcher register !send_transfunc
182    $_dispatcher dispatch $this !send_transfunc \
183        "[itcl::code $this SendTransferFunctions]; list"
184
185    # Rebuild event
186    $_dispatcher register !rebuild
187    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
188
189    # Resize event
190    $_dispatcher register !resize
191    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
192
193    #
194    # Populate parser with commands handle incoming requests
195    #
196    $_parser alias image [itcl::code $this ReceiveImage]
197    $_parser alias legend [itcl::code $this ReceiveLegend]
198    $_parser alias data [itcl::code $this ReceiveData]
199
200    # Initialize the view to some default parameters.
201    array set _view {
202        -qw      0.853553
203        -qx      -0.353553
204        -qy      0.353553
205        -qz      0.146447
206        -xpan    0
207        -ypan    0
208        -zoom    1.0
209    }
210    set _arcball [blt::arcball create 100 100]
211    $_arcball quaternion [ViewToQuaternion]
212
213    set _limits(v) [list 0.0 1.0]
214    set _reset 1
215
216    array set _settings {
217        -axesvisible            1
218        -background             black
219        -colormap               "default"
220        -cutplanesvisible       0
221        -gridvisible            0
222        -isosurfaceshading      0
223        -legendvisible          1
224        -light                  40
225        -light2side             1
226        -outlinevisible         0
227        -qw                     0.853553
228        -qx                     -0.353553
229        -qy                     0.353553
230        -qz                     0.146447
231        -thickness              350
232        -volume                 1
233        -volumeopacity          0.5
234        -volumevisible          1
235        -xcutplaneposition      50
236        -xcutplanevisible       1
237        -xpan                   0
238        -ycutplaneposition      50
239        -ycutplanevisible       1
240        -ypan                   0
241        -zcutplaneposition      50
242        -zcutplanevisible       1
243        -zoom                   1.0
244    }
245    array set _widget {
246        -volumeopacity          50
247    }
248    itk_component add 3dview {
249        label $itk_component(plotarea).view -image $_image(plot) \
250            -highlightthickness 0 -borderwidth 0
251    } {
252        usual
253        ignore -highlightthickness -borderwidth  -background
254    }
255    bind $itk_component(3dview) <Control-F1> [itcl::code $this ToggleConsole]
256
257    set f [$itk_component(main) component controls]
258    itk_component add reset {
259        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
260            -highlightthickness 0 \
261            -image [Rappture::icon reset-view] \
262            -command [itcl::code $this Zoom reset]
263    } {
264        usual
265        ignore -highlightthickness
266    }
267    pack $itk_component(reset) -side top -padx 2 -pady 2
268    Rappture::Tooltip::for $itk_component(reset) \
269        "Reset the view to the default zoom level"
270
271    itk_component add zoomin {
272        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
273            -highlightthickness 0 \
274            -image [Rappture::icon zoom-in] \
275            -command [itcl::code $this Zoom in]
276    } {
277        usual
278        ignore -highlightthickness
279    }
280    pack $itk_component(zoomin) -side top -padx 2 -pady 2
281    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
282
283    itk_component add zoomout {
284        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
285            -highlightthickness 0 \
286            -image [Rappture::icon zoom-out] \
287            -command [itcl::code $this Zoom out]
288    } {
289        usual
290        ignore -highlightthickness
291    }
292    pack $itk_component(zoomout) -side top -padx 2 -pady 2
293    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
294
295    itk_component add volume {
296        Rappture::PushButton $f.volume \
297            -onimage [Rappture::icon volume-on] \
298            -offimage [Rappture::icon volume-off] \
299            -command [itcl::code $this AdjustSetting -volume] \
300            -variable [itcl::scope _settings(-volume)]
301    }
302    $itk_component(volume) select
303    Rappture::Tooltip::for $itk_component(volume) \
304        "Toggle the volume cloud on/off"
305    pack $itk_component(volume) -padx 2 -pady 2
306
307    itk_component add cutplane {
308        Rappture::PushButton $f.cutplane \
309            -onimage [Rappture::icon cutbutton] \
310            -offimage [Rappture::icon cutbutton] \
311            -variable [itcl::scope _settings(-cutplanesvisible)] \
312            -command [itcl::code $this AdjustSetting -cutplanesvisible]
313    }
314    Rappture::Tooltip::for $itk_component(cutplane) \
315        "Show/Hide cutplanes"
316    pack $itk_component(cutplane) -padx 2 -pady 2
317
318    if { [catch {
319        BuildViewTab
320        BuildVolumeTab
321        BuildCutplanesTab
322        BuildCameraTab
323    } errs] != 0 } {
324        global errorInfo
325        puts stderr "errs=$errs errorInfo=$errorInfo"
326    }
327
328    # Legend
329    set _image(legend) [image create photo]
330    itk_component add legend {
331        canvas $itk_component(plotarea).legend -height 50 -highlightthickness 0
332    } {
333        usual
334        ignore -highlightthickness
335        rename -background -plotbackground plotBackground Background
336    }
337    bind $itk_component(legend) <Configure> \
338        [itcl::code $this EventuallyRedrawLegend]
339    bind $itk_component(legend) <KeyPress-Delete> \
340        [itcl::code $this RemoveMarker %x %y]
341    bind $itk_component(legend) <Enter> \
342        [list focus $itk_component(legend)]
343
344    # Hack around the Tk panewindow.  The problem is that the requested
345    # size of the 3d view isn't set until an image is retrieved from
346    # the server.  So the panewindow uses the tiny size.
347    set w 10000
348    pack forget $itk_component(3dview)
349    blt::table $itk_component(plotarea) \
350        0,0 $itk_component(3dview) -fill both -reqwidth $w \
351        1,0 $itk_component(legend) -fill x
352    blt::table configure $itk_component(plotarea) r1 -resize none
353
354    # Bindings for rotation via mouse
355    bind $itk_component(3dview) <ButtonPress-1> \
356        [itcl::code $this Rotate click %x %y]
357    bind $itk_component(3dview) <B1-Motion> \
358        [itcl::code $this Rotate drag %x %y]
359    bind $itk_component(3dview) <ButtonRelease-1> \
360        [itcl::code $this Rotate release %x %y]
361    bind $itk_component(3dview) <Configure> \
362        [itcl::code $this EventuallyResize %w %h]
363
364    # Bindings for panning via mouse
365    bind $itk_component(3dview) <ButtonPress-2> \
366        [itcl::code $this Pan click %x %y]
367    bind $itk_component(3dview) <B2-Motion> \
368        [itcl::code $this Pan drag %x %y]
369    bind $itk_component(3dview) <ButtonRelease-2> \
370        [itcl::code $this Pan release %x %y]
371
372    # Bindings for panning via keyboard
373    bind $itk_component(3dview) <KeyPress-Left> \
374        [itcl::code $this Pan set -10 0]
375    bind $itk_component(3dview) <KeyPress-Right> \
376        [itcl::code $this Pan set 10 0]
377    bind $itk_component(3dview) <KeyPress-Up> \
378        [itcl::code $this Pan set 0 -10]
379    bind $itk_component(3dview) <KeyPress-Down> \
380        [itcl::code $this Pan set 0 10]
381    bind $itk_component(3dview) <Shift-KeyPress-Left> \
382        [itcl::code $this Pan set -2 0]
383    bind $itk_component(3dview) <Shift-KeyPress-Right> \
384        [itcl::code $this Pan set 2 0]
385    bind $itk_component(3dview) <Shift-KeyPress-Up> \
386        [itcl::code $this Pan set 0 -2]
387    bind $itk_component(3dview) <Shift-KeyPress-Down> \
388        [itcl::code $this Pan set 0 2]
389
390    # Bindings for zoom via keyboard
391    bind $itk_component(3dview) <KeyPress-Prior> \
392        [itcl::code $this Zoom out]
393    bind $itk_component(3dview) <KeyPress-Next> \
394        [itcl::code $this Zoom in]
395
396    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
397
398    if {[string equal "x11" [tk windowingsystem]]} {
399        # Bindings for zoom via mouse
400        bind $itk_component(3dview) <4> [itcl::code $this Zoom out]
401        bind $itk_component(3dview) <5> [itcl::code $this Zoom in]
402    }
403
404    set _image(download) [image create photo]
405
406    eval itk_initialize $args
407
408    EnableWaitDialog 900
409    Connect
410}
411
412# ----------------------------------------------------------------------
413# DESTRUCTOR
414# ----------------------------------------------------------------------
415itcl::body Rappture::NanovisViewer::destructor {} {
416    $_dispatcher cancel !rebuild
417    $_dispatcher cancel !send_transfunc
418    $_dispatcher cancel !resize
419    image delete $_image(plot)
420    image delete $_image(legend)
421    image delete $_image(download)
422    foreach cname [array names _transferFunctionEditors] {
423        itcl::delete object $_transferFunctionEditors($cname)
424    }
425    catch { blt::arcball destroy $_arcball }
426    array unset _settings
427}
428
429# ----------------------------------------------------------------------
430# USAGE: add <dataobj> ?<settings>?
431#
432# Clients use this to add a data object to the plot.  The optional
433# <settings> are used to configure the plot.  Allowed settings are
434# -color, -brightness, -width, -linestyle, and -raise.
435# ----------------------------------------------------------------------
436itcl::body Rappture::NanovisViewer::add {dataobj {settings ""}} {
437    if { ![$dataobj isvalid] } {
438        return;                         # Object doesn't contain valid data.
439    }
440    array set params {
441        -color auto
442        -width 1
443        -linestyle solid
444        -brightness 0
445        -raise 0
446        -description ""
447        -param ""
448    }
449    array set params $settings
450
451    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
452        # can't handle -autocolors yet
453        set params(-color) black
454    }
455    set pos [lsearch -exact $_dlist $dataobj]
456    if {$pos < 0} {
457        lappend _dlist $dataobj
458        set _obj2ovride($dataobj-color) $params(-color)
459        set _obj2ovride($dataobj-width) $params(-width)
460        set _obj2ovride($dataobj-raise) $params(-raise)
461        $_dispatcher event -idle !rebuild
462    }
463}
464
465# ----------------------------------------------------------------------
466# USAGE: get ?-objects?
467# USAGE: get ?-image 3dview|legend?
468#
469# Clients use this to query the list of objects being plotted, in
470# order from bottom to top of this result.  The optional "-image"
471# flag can also request the internal images being shown.
472# ----------------------------------------------------------------------
473itcl::body Rappture::NanovisViewer::get {args} {
474    if {[llength $args] == 0} {
475        set args "-objects"
476    }
477
478    set op [lindex $args 0]
479    switch -- $op {
480        -objects {
481            # put the dataobj list in order according to -raise options
482            set dlist $_dlist
483            foreach obj $dlist {
484                if {[info exists _obj2ovride($obj-raise)] &&
485                    $_obj2ovride($obj-raise)} {
486                    set i [lsearch -exact $dlist $obj]
487                    if {$i >= 0} {
488                        set dlist [lreplace $dlist $i $i]
489                        lappend dlist $obj
490                    }
491                }
492            }
493            return $dlist
494        }
495        -image {
496            if {[llength $args] != 2} {
497                error "wrong # args: should be \"get -image 3dview|legend\""
498            }
499            switch -- [lindex $args end] {
500                3dview {
501                    return $_image(plot)
502                }
503                legend {
504                    return $_image(legend)
505                }
506                default {
507                    error "bad image name \"[lindex $args end]\": should be 3dview or legend"
508                }
509            }
510        }
511        default {
512            error "bad option \"$op\": should be -objects or -image"
513        }
514    }
515}
516
517# ----------------------------------------------------------------------
518# USAGE: delete ?<dataobj1> <dataobj2> ...?
519#
520#       Clients use this to delete a dataobj from the plot.  If no dataobjs
521#       are specified, then all dataobjs are deleted.  No data objects are
522#       deleted.  They are only removed from the display list.
523#
524# ----------------------------------------------------------------------
525itcl::body Rappture::NanovisViewer::delete {args} {
526    if {[llength $args] == 0} {
527        set args $_dlist
528    }
529    # Delete all specified dataobjs
530    set changed 0
531    foreach dataobj $args {
532        set pos [lsearch -exact $_dlist $dataobj]
533        if { $pos >= 0 } {
534            set _dlist [lreplace $_dlist $pos $pos]
535            array unset _obj2ovride $dataobj-*
536            set changed 1
537        }
538    }
539    # If anything changed, then rebuild the plot
540    if {$changed} {
541        $_dispatcher event -idle !rebuild
542    }
543}
544
545# ----------------------------------------------------------------------
546# USAGE: scale ?<data1> <data2> ...?
547#
548# Sets the default limits for the overall plot according to the
549# limits of the data for all of the given <data> objects.  This
550# accounts for all objects--even those not showing on the screen.
551# Because of this, the limits are appropriate for all objects as
552# the user scans through data in the ResultSet viewer.
553# ----------------------------------------------------------------------
554itcl::body Rappture::NanovisViewer::scale {args} {
555    array set style {
556        -color    BCGYR
557        -levels   6
558        -markers  ""
559    }
560    array unset _limits
561    array unset _volcomponents
562    foreach dataobj $args {
563        if { ![$dataobj isvalid] } {
564            continue;                     # Object doesn't contain valid data.
565        }
566        foreach cname [$dataobj components] {
567            if { ![info exists _volcomponents($cname)] } {
568                lappend _componentsList $cname
569                array set style [lindex [$dataobj components -style $cname] 0]
570                set cmap [ColorsToColormap $style(-color)]
571                set _cname2defaultcolormap($cname) $cmap
572                set _settings($cname-colormap) $style(-color)
573            }
574            lappend _volcomponents($cname) $dataobj-$cname
575            array unset limits
576            array set limits [$dataobj valueLimits $cname]
577            set _limits($cname) $limits(v)
578        }
579        foreach axis {x y z v} {
580            foreach { min max } [$dataobj limits $axis] break
581            if {"" != $min && "" != $max} {
582                if { ![info exists _limits($axis)] } {
583                    set _limits($axis) [list $min $max]
584                    continue
585                }
586                foreach {amin amax} $_limits($axis) break
587                if {$min < $amin} {
588                    set amin $min
589                }
590                if {$max > $amax} {
591                    set amax $max
592                }
593                set _limits($axis) [list $amin $amax]
594            }
595        }
596    }
597    BuildVolumeComponents
598}
599
600# ----------------------------------------------------------------------
601# USAGE: download coming
602# USAGE: download controls <downloadCommand>
603# USAGE: download now
604#
605# Clients use this method to create a downloadable representation
606# of the plot.  Returns a list of the form {ext string}, where
607# "ext" is the file extension (indicating the type of data) and
608# "string" is the data itself.
609# ----------------------------------------------------------------------
610itcl::body Rappture::NanovisViewer::download {option args} {
611    switch $option {
612        coming {
613            if {[catch {
614                blt::winop snap $itk_component(plotarea) $_image(download)
615            }]} {
616                $_image(download) configure -width 1 -height 1
617                $_image(download) put #000000
618            }
619        }
620        controls {
621            # no controls for this download yet
622            return ""
623        }
624        now {
625            # Get the image data (as base64) and decode it back to binary.
626            # This is better than writing to temporary files.  When we switch
627            # to the BLT picture image it won't be necessary to decode the
628            # image data.
629            if { [image width $_image(plot)] > 0 &&
630                 [image height $_image(plot)] > 0 } {
631                set bytes [$_image(plot) data -format "jpeg -quality 100"]
632                set bytes [Rappture::encoding::decode -as b64 $bytes]
633                return [list .jpg $bytes]
634            }
635            return ""
636        }
637        default {
638            error "bad option \"$option\": should be coming, controls, now"
639        }
640    }
641}
642
643# ----------------------------------------------------------------------
644# USAGE: Connect ?<host:port>,<host:port>...?
645#
646# Clients use this method to establish a connection to a new
647# server, or to reestablish a connection to the previous server.
648# Any existing connection is automatically closed.
649# ----------------------------------------------------------------------
650itcl::body Rappture::NanovisViewer::Connect {} {
651    set _hosts [GetServerList "nanovis"]
652    if { "" == $_hosts } {
653        return 0
654    }
655    set _reset 1
656    set result [VisViewer::Connect $_hosts]
657    if { $result } {
658        if { $_reportClientInfo }  {
659            # Tell the server the viewer, hub, user and session.
660            # Do this immediately on connect before buffering any commands
661            global env
662
663            set info {}
664            set user "???"
665            if { [info exists env(USER)] } {
666                set user $env(USER)
667            }
668            set session "???"
669            if { [info exists env(SESSION)] } {
670                set session $env(SESSION)
671            }
672            lappend info "version" "$Rappture::version"
673            lappend info "build" "$Rappture::build"
674            lappend info "svnurl" "$Rappture::svnurl"
675            lappend info "installdir" "$Rappture::installdir"
676            lappend info "hub" [exec hostname]
677            lappend info "client" "nanovisviewer"
678            lappend info "user" $user
679            lappend info "session" $session
680            SendCmd "clientinfo [list $info]"
681        }
682
683        set w [winfo width $itk_component(3dview)]
684        set h [winfo height $itk_component(3dview)]
685        EventuallyResize $w $h
686    }
687    return $result
688}
689
690#
691# isconnected --
692#
693#       Indicates if we are currently connected to the visualization server.
694#
695itcl::body Rappture::NanovisViewer::isconnected {} {
696    return [VisViewer::IsConnected]
697}
698
699#
700# disconnect --
701#
702itcl::body Rappture::NanovisViewer::disconnect {} {
703    Disconnect
704}
705
706#
707# Disconnect --
708#
709#       Clients use this method to disconnect from the current rendering
710#       server.
711#
712itcl::body Rappture::NanovisViewer::Disconnect {} {
713    VisViewer::Disconnect
714
715    # disconnected -- no more data sitting on server
716    array unset _serverDatasets
717}
718
719# ----------------------------------------------------------------------
720# USAGE: SendTransferFunctions
721# ----------------------------------------------------------------------
722itcl::body Rappture::NanovisViewer::SendTransferFunctions {} {
723    foreach cname [array names _volcomponents] {
724        ComputeTransferFunction $cname
725    }
726    FixLegend
727}
728
729# ----------------------------------------------------------------------
730# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
731#
732# Invoked automatically whenever the "image" command comes in from
733# the rendering server.  Indicates that binary image data with the
734# specified <size> will follow.
735# ----------------------------------------------------------------------
736itcl::body Rappture::NanovisViewer::ReceiveImage { args } {
737    array set info {
738        -token "???"
739        -bytes 0
740        -type image
741    }
742    array set info $args
743    set bytes [ReceiveBytes $info(-bytes)]
744    ReceiveEcho <<line "<read $info(-bytes) bytes"
745    if { $info(-type) == "image" } {
746        ReceiveEcho "for [image width $_image(plot)]x[image height $_image(plot)] image>"
747        $_image(plot) configure -data $bytes
748    } elseif { $info(-type) == "print" } {
749        set tag $this-print-$info(-token)
750        set _hardcopy($tag) $bytes
751    }
752}
753
754#
755# DrawLegend --
756#
757itcl::body Rappture::NanovisViewer::DrawLegend { cname } {
758    set c $itk_component(legend)
759    set w [winfo width $c]
760    set h [winfo height $c]
761    set lx 10
762    set ly [expr {$h - 1}]
763    if {"" == [$c find withtag colorbar]} {
764        $c create image 10 10 -anchor nw \
765            -image $_image(legend) -tags colorbar
766        $c create text $lx $ly -anchor sw \
767            -fill $itk_option(-plotforeground) -tags "limits text vmin"
768        $c create text [expr {$w-$lx}] $ly -anchor se \
769            -fill $itk_option(-plotforeground) -tags "limits text vmax"
770        $c create text [expr {$w/2}] $ly -anchor s \
771            -fill $itk_option(-plotforeground) -tags "limits text title"
772        $c lower colorbar
773        $c bind colorbar <ButtonRelease-1> [itcl::code $this AddNewMarker %x %y]
774    }
775
776    # Display the markers used by the current transfer function.
777    HideAllMarkers
778    $_transferFunctionEditors($cname) showMarkers $_limits($cname)
779
780    foreach {min max} $_limits($cname) break
781    $c itemconfigure vmin -text [format %g $min]
782    $c coords vmin $lx $ly
783
784    $c itemconfigure vmax -text [format %g $max]
785    $c coords vmax [expr {$w-$lx}] $ly
786
787    set title [$_first hints label]
788    set units [$_first hints units]
789    if { $units != "" } {
790        set title "$title ($units)"
791    }
792    $c itemconfigure title -text $title
793    $c coords title [expr {$w/2}] $ly
794
795    # The colormap may have changed. Resync the slicers with the colormap.
796    InitSettings -cutplanesvisible -xcutplanevisible -ycutplanevisible \
797        -zcutplanevisible
798}
799
800#
801#
802# ReceiveLegend --
803#
804#       The procedure is the response from the render server to each "legend"
805#       command.  The server sends back a "legend" command invoked our
806#       the slave interpreter.  The purpose is to collect data of the image
807#       representing the legend in the canvas.  In addition, the
808#       active transfer function is displayed.
809#
810#
811itcl::body Rappture::NanovisViewer::ReceiveLegend { cname vmin vmax size } {
812    if { ![isconnected] } {
813        return
814    }
815    set bytes [ReceiveBytes $size]
816    $_image(legend) configure -data $bytes
817    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
818
819    DrawLegend $_current
820}
821
822#
823# ReceiveData --
824#
825#       The procedure is the response from the render server to each "data
826#       follows" command.  The server sends back a "data" command invoked our
827#       the slave interpreter.  The purpose is to collect the min/max of the
828#       volume sent to the render server.  Since the client (nanovisviewer)
829#       doesn't parse 3D data formats, we rely on the server (nanovis) to
830#       tell us what the limits are.  Once we've received the limits to all
831#       the data we've sent (tracked by _recvdDatasets) we can then determine
832#       what the transfer functions are for these volumes.
833#
834#
835#       Note: There is a considerable tradeoff in having the server report
836#             back what the data limits are.  It means that much of the code
837#             having to do with transfer-functions has to wait for the data
838#             to come back, since the isomarkers are calculated based upon
839#             the data limits.  The client code is much messier because of
840#             this.  The alternative is to parse any of the 3D formats on the
841#             client side.
842#
843itcl::body Rappture::NanovisViewer::ReceiveData { args } {
844    if { ![isconnected] } {
845        return
846    }
847
848    # Arguments from server are name value pairs. Stuff them in an array.
849    array set info $args
850
851    set tag $info(tag)
852    set parts [split $tag -]
853
854    #
855    # Volumes don't exist until we're told about them.
856    #
857    set dataobj [lindex $parts 0]
858    set _serverDatasets($tag) 1
859    if { $_settings(-volumevisible) && $dataobj == $_first } {
860        SendCmd "volume state 1 $tag"
861    }
862    set _limits($tag) [list $info(min)  $info(max)]
863    set _limits(v)    [list $info(vmin) $info(vmax)]
864
865    unset _recvdDatasets($tag)
866    if { [array size _recvdDatasets] == 0 } {
867        updateTransferFunctions
868    }
869}
870
871# ----------------------------------------------------------------------
872# USAGE: Rebuild
873#
874# Called automatically whenever something changes that affects the
875# data in the widget.  Clears any existing data and rebuilds the
876# widget to display new data.
877# ----------------------------------------------------------------------
878itcl::body Rappture::NanovisViewer::Rebuild {} {
879    set w [winfo width $itk_component(3dview)]
880    set h [winfo height $itk_component(3dview)]
881    if { $w < 2 || $h < 2 } {
882        update
883        $_dispatcher event -idle !rebuild
884        return
885    }
886
887    # Turn on buffering of commands to the server.  We don't want to
888    # be preempted by a server disconnect/reconnect (which automatically
889    # generates a new call to Rebuild).
890    StartBufferingCommands
891
892    if { $_width != $w || $_height != $h || $_reset } {
893        set _width $w
894        set _height $h
895        $_arcball resize $w $h
896        DoResize
897    }
898
899    foreach dataobj [get] {
900        foreach cname [$dataobj components] {
901            set tag $dataobj-$cname
902            if { ![info exists _serverDatasets($tag)] } {
903                # Send the data as one huge base64-encoded mess -- yuck!
904                if { [$dataobj type] == "dx" } {
905                    if { ![$dataobj isvalid] } {
906                        puts stderr "??? $dataobj is invalid"
907                    }
908                    set data [$dataobj blob $cname]
909                } else {
910                    set data [$dataobj vtkdata $cname]
911                    if 0 {
912                        set f [open "/tmp/volume.vtk" "w"]
913                        fconfigure $f -translation binary -encoding binary
914                        puts -nonewline $f $data
915                        close $f
916                    }
917                }
918                set nbytes [string length $data]
919                if { $_reportClientInfo }  {
920                    set info {}
921                    lappend info "tool_id"       [$dataobj hints toolid]
922                    lappend info "tool_name"     [$dataobj hints toolname]
923                    lappend info "tool_title"    [$dataobj hints tooltitle]
924                    lappend info "tool_command"  [$dataobj hints toolcommand]
925                    lappend info "tool_revision" [$dataobj hints toolrevision]
926                    lappend info "dataset_label" [$dataobj hints label]
927                    lappend info "dataset_size"  $nbytes
928                    lappend info "dataset_tag"   $tag
929                    SendCmd "clientinfo [list $info]"
930                }
931                SendCmd "volume data follows $nbytes $tag"
932                SendData $data
933                set _recvdDatasets($tag) 1
934                set _serverDatasets($tag) 0
935            }
936            SetObjectStyle $dataobj $cname
937        }
938    }
939
940    # Outline seems to need to be reset every update.
941    InitSettings -outlinevisible -cutplanesvisible -current
942
943    set _first [lindex [get] 0]
944    if { $_reset } {
945        #
946        # Reset the camera and other view parameters
947        #
948        set _settings(-qw)    $_view(-qw)
949        set _settings(-qx)    $_view(-qx)
950        set _settings(-qy)    $_view(-qy)
951        set _settings(-qz)    $_view(-qz)
952        set _settings(-xpan)  $_view(-xpan)
953        set _settings(-ypan)  $_view(-ypan)
954        set _settings(-zoom)  $_view(-zoom)
955
956        set q [ViewToQuaternion]
957        $_arcball quaternion $q
958        SendCmd "camera orient $q"
959        SendCmd "camera reset"
960        PanCamera
961        SendCmd "camera zoom $_view(-zoom)"
962
963        # Turn off cutplanes for all volumes
964        foreach axis {x y z} {
965            SendCmd "cutplane state 0 $axis"
966        }
967
968        InitSettings -light2side -light -volumeopacity \
969            -isosurfaceshading -gridvisible -axesvisible \
970            -xcutplanevisible -ycutplanevisible -zcutplanevisible       
971
972        if {"" != $_first} {
973            set axis [$_first hints updir]
974            if { "" != $axis } {
975                SendCmd "up $axis"
976            }
977            set location [$_first hints camera]
978            if { $location != "" } {
979                array set _view $location
980            }
981        }
982    }
983
984    # nothing to send -- activate the proper ivol
985    SendCmd "volume state 0"
986    if {"" != $_first} {
987        set datasets [array names _serverDatasets $_first-*]
988        if { $datasets != "" } {
989            SendCmd "volume state 1 $datasets"
990        }
991        # If the first volume already exists on the server, then make sure
992        # we display the proper transfer function in the legend.
993        set cname [lindex [$_first components] 0]
994        if { [info exists _serverDatasets($_first-$cname)] } {
995            updateTransferFunctions
996        }
997    }
998    # Actually write the commands to the server socket.  If it fails, we don't
999    # care.  We're finished here.
1000    blt::busy hold $itk_component(hull)
1001    StopBufferingCommands
1002    blt::busy release $itk_component(hull)
1003    set _reset 0
1004}
1005
1006# ----------------------------------------------------------------------
1007# USAGE: CurrentDatasets ?-cutplanes?
1008#
1009# Returns a list of volume server IDs for the current volume being
1010# displayed.  This is normally a single ID, but it might be a list
1011# of IDs if the current data object has multiple components.
1012# ----------------------------------------------------------------------
1013itcl::body Rappture::NanovisViewer::CurrentDatasets {{what -all}} {
1014    set rlist ""
1015    if { $_first == "" } {
1016        return
1017    }
1018    foreach cname [$_first components] {
1019        set tag $_first-$cname
1020        if { [info exists _serverDatasets($tag)] && $_serverDatasets($tag) } {
1021            array set style {
1022                -cutplanes 1
1023            }
1024            array set style [lindex [$_first components -style $cname] 0]
1025            if { $what != "-cutplanes" || $style(-cutplanes) } {
1026                lappend rlist $tag
1027            }
1028        }
1029    }
1030    return $rlist
1031}
1032
1033# ----------------------------------------------------------------------
1034# USAGE: Zoom in
1035# USAGE: Zoom out
1036# USAGE: Zoom reset
1037#
1038# Called automatically when the user clicks on one of the zoom
1039# controls for this widget.  Changes the zoom for the current view.
1040# ----------------------------------------------------------------------
1041itcl::body Rappture::NanovisViewer::Zoom {option} {
1042    switch -- $option {
1043        "in" {
1044            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1045            set _settings(-zoom) $_view(-zoom)
1046            SendCmd "camera zoom $_view(-zoom)"
1047        }
1048        "out" {
1049            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1050            set _settings(-zoom) $_view(-zoom)
1051            SendCmd "camera zoom $_view(-zoom)"
1052        }
1053        "reset" {
1054            array set _view {
1055                -qw      0.853553
1056                -qx      -0.353553
1057                -qy      0.353553
1058                -qz      0.146447
1059                -xpan    0
1060                -ypan    0
1061                -zoom    1.0
1062            }
1063            if { $_first != "" } {
1064                set location [$_first hints camera]
1065                if { $location != "" } {
1066                    array set _view $location
1067                }
1068            }
1069            set q [ViewToQuaternion]
1070            $_arcball quaternion $q
1071            SendCmd "camera orient $q"
1072            SendCmd "camera reset"
1073            set _settings(-qw)    $_view(-qw)
1074            set _settings(-qx)    $_view(-qx)
1075            set _settings(-qy)    $_view(-qy)
1076            set _settings(-qz)    $_view(-qz)
1077            set _settings(-xpan)  $_view(-xpan)
1078            set _settings(-ypan)  $_view(-ypan)
1079            set _settings(-zoom)  $_view(-zoom)
1080        }
1081    }
1082}
1083
1084itcl::body Rappture::NanovisViewer::PanCamera {} {
1085    set x $_view(-xpan)
1086    set y $_view(-ypan)
1087    SendCmd "camera pan $x $y"
1088}
1089
1090
1091# ----------------------------------------------------------------------
1092# USAGE: Rotate click <x> <y>
1093# USAGE: Rotate drag <x> <y>
1094# USAGE: Rotate release <x> <y>
1095#
1096# Called automatically when the user clicks/drags/releases in the
1097# plot area.  Moves the plot according to the user's actions.
1098# ----------------------------------------------------------------------
1099itcl::body Rappture::NanovisViewer::Rotate {option x y} {
1100    switch -- $option {
1101        click {
1102            $itk_component(3dview) configure -cursor fleur
1103            set _click(x) $x
1104            set _click(y) $y
1105        }
1106        drag {
1107            if {[array size _click] == 0} {
1108                Rotate click $x $y
1109            } else {
1110                set w [winfo width $itk_component(3dview)]
1111                set h [winfo height $itk_component(3dview)]
1112                if {$w <= 0 || $h <= 0} {
1113                    return
1114                }
1115
1116                if {[catch {
1117                    # this fails sometimes for no apparent reason
1118                    set dx [expr {double($x-$_click(x))/$w}]
1119                    set dy [expr {double($y-$_click(y))/$h}]
1120                }]} {
1121                    return
1122                }
1123
1124                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1125                QuaternionToView $q
1126                set _settings(-qw) $_view(-qw)
1127                set _settings(-qx) $_view(-qx)
1128                set _settings(-qy) $_view(-qy)
1129                set _settings(-qz) $_view(-qz)
1130                SendCmd "camera orient $q"
1131
1132                set _click(x) $x
1133                set _click(y) $y
1134            }
1135        }
1136        release {
1137            Rotate drag $x $y
1138            $itk_component(3dview) configure -cursor ""
1139            catch {unset _click}
1140        }
1141        default {
1142            error "bad option \"$option\": should be click, drag, release"
1143        }
1144    }
1145}
1146
1147# ----------------------------------------------------------------------
1148# USAGE: $this Pan click x y
1149#        $this Pan drag x y
1150#        $this Pan release x y
1151#
1152# Called automatically when the user clicks on one of the zoom
1153# controls for this widget.  Changes the zoom for the current view.
1154# ----------------------------------------------------------------------
1155itcl::body Rappture::NanovisViewer::Pan {option x y} {
1156    # Experimental stuff
1157    set w [winfo width $itk_component(3dview)]
1158    set h [winfo height $itk_component(3dview)]
1159    if { $option == "set" } {
1160        set x [expr $x / double($w)]
1161        set y [expr $y / double($h)]
1162        set _view(-xpan) [expr $_view(-xpan) + $x]
1163        set _view(-ypan) [expr $_view(-ypan) + $y]
1164        PanCamera
1165        set _settings(-xpan) $_view(-xpan)
1166        set _settings(-ypan) $_view(-ypan)
1167        return
1168    }
1169    if { $option == "click" } {
1170        set _click(x) $x
1171        set _click(y) $y
1172        $itk_component(3dview) configure -cursor hand1
1173    }
1174    if { $option == "drag" || $option == "release" } {
1175        set dx [expr ($_click(x) - $x)/double($w)]
1176        set dy [expr ($_click(y) - $y)/double($h)]
1177        set _click(x) $x
1178        set _click(y) $y
1179        set _view(-xpan) [expr $_view(-xpan) - $dx]
1180        set _view(-ypan) [expr $_view(-ypan) - $dy]
1181        PanCamera
1182        set _settings(-xpan) $_view(-xpan)
1183        set _settings(-ypan) $_view(-ypan)
1184    }
1185    if { $option == "release" } {
1186        $itk_component(3dview) configure -cursor ""
1187    }
1188}
1189
1190# ----------------------------------------------------------------------
1191# USAGE: InitSettings <what> ?<value>?
1192#
1193# Used internally to update rendering settings whenever parameters
1194# change in the popup settings panel.  Sends the new settings off
1195# to the back end.
1196# ----------------------------------------------------------------------
1197itcl::body Rappture::NanovisViewer::InitSettings { args } {
1198    foreach arg $args {
1199        AdjustSetting $arg
1200    }
1201}
1202
1203# ----------------------------------------------------------------------
1204# USAGE: AdjustSetting <what> ?<value>?
1205#
1206# Used internally to update rendering settings whenever parameters
1207# change in the popup settings panel.  Sends the new settings off
1208# to the back end.
1209# ----------------------------------------------------------------------
1210itcl::body Rappture::NanovisViewer::AdjustSetting {what {value ""}} {
1211    if {![isconnected]} {
1212        return
1213    }
1214    switch -- $what {
1215        "-axesvisible" {
1216            SendCmd "axis visible $_settings($what)"
1217        }
1218        "-background" {
1219            set bgcolor [$itk_component(background) value]
1220            array set fgcolors {
1221                "black" "white"
1222                "white" "black"
1223                "grey"  "black"
1224            }
1225            configure -plotbackground $bgcolor \
1226                -plotforeground $fgcolors($bgcolor)
1227            DrawLegend $_current
1228        }
1229        "-colormap" {
1230            set color [$itk_component(colormap) value]
1231            set _settings($what) $color
1232            set _settings($_current${what}) $color
1233            ResetColormap $_current $color
1234        }
1235        "-current" {
1236            set cname [$itk_component(volcomponents) value]
1237            SwitchComponent $cname
1238        }
1239        "-cutplanesvisible" {
1240            set bool $_settings($what)
1241            # We only set cutplanes on the first dataset.
1242            set datasets [CurrentDatasets -cutplanes]
1243            set tag [lindex $datasets 0]
1244            SendCmd "cutplane visible $bool $tag"
1245        }
1246        "-gridvisible" {
1247            SendCmd "grid visible $_settings($what)"
1248        }
1249        "-isosurfaceshading" {
1250            SendCmd "volume shading isosurface $_settings($what)"
1251        }
1252        "-legendvisible" {
1253            if { $_settings($what) } {
1254                blt::table $itk_component(plotarea) \
1255                    0,0 $itk_component(3dview) -fill both \
1256                    1,0 $itk_component(legend) -fill x
1257                blt::table configure $itk_component(plotarea) r1 -resize none
1258            } else {
1259                blt::table forget $itk_component(legend)
1260            }
1261        }
1262        "-light" {
1263            set _settings($_current${what}) $_settings($what)
1264            set val $_settings($what)
1265            set diffuse [expr {0.01*$val}]
1266            set ambient [expr {1.0-$diffuse}]
1267            set specularLevel 0.3
1268            set specularExp 90.0
1269            foreach tag [GetDatasetsWithComponent $_current] {
1270                SendCmd "volume shading ambient $ambient $tag"
1271                SendCmd "volume shading diffuse $diffuse $tag"
1272                SendCmd "volume shading specularLevel $specularLevel $tag"
1273                SendCmd "volume shading specularExp $specularExp $tag"
1274            }
1275        }
1276        "-light2side" {
1277            set _settings($_current${what}) $_settings($what)
1278            set val $_settings($what)
1279            foreach tag [GetDatasetsWithComponent $_current] {
1280                SendCmd "volume shading light2side $val $tag"
1281            }
1282        }
1283        "-outlinevisible" {
1284            SendCmd "volume outline state $_settings($what)"
1285        }
1286        "-thickness" {
1287            set val $_settings($what)
1288            set _settings($_current${what}) $val
1289            updateTransferFunctions
1290        }
1291        "-volume" {
1292            # This is the global volume visibility control.  It controls the
1293            # visibility of all the all volumes.  Whenever it's changed, you
1294            # have to synchronize each of the local controls (see below) with
1295            # this.
1296            set datasets [CurrentDatasets]
1297            set bool $_settings($what)
1298            SendCmd "volume data state $bool $datasets"
1299            foreach cname $_componentsList {
1300                set _settings($cname-volumevisible) $bool
1301            }
1302            set _settings(-volumevisible) $bool
1303        }
1304        "-volumeopacity" {
1305            set _settings($what) [expr $_widget($what) * 0.01]
1306            set _settings($_current${what}) $_settings($what)
1307            foreach tag [GetDatasetsWithComponent $_current] {
1308                SendCmd "volume shading opacity $_settings($what) $tag"
1309            }
1310        }
1311        "-volumevisible" {
1312            # This is the component specific control.  It changes the
1313            # visibility of only the current component.
1314            set _settings($_current${what}) $_settings($what)
1315            foreach tag [GetDatasetsWithComponent $_current] {
1316                SendCmd "volume data state $_settings($what) $tag"
1317            }
1318        }
1319        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1320            set axis [string range $what 1 1]
1321            set bool $_settings($what)
1322            # We only set cutplanes on the first dataset.
1323            set datasets [CurrentDatasets -cutplanes]
1324            set tag [lindex $datasets 0]
1325            SendCmd "cutplane state $bool $axis $tag"
1326            if { $bool } {
1327                $itk_component(${axis}CutScale) configure -state normal \
1328                    -troughcolor white
1329            } else {
1330                $itk_component(${axis}CutScale) configure -state disabled \
1331                    -troughcolor grey82
1332            }
1333        }
1334        default {
1335            error "don't know how to fix $what"
1336        }
1337    }
1338}
1339
1340# ----------------------------------------------------------------------
1341# USAGE: FixLegend
1342#
1343# Used internally to update the legend area whenever it changes size
1344# or when the field changes.  Asks the server to send a new legend
1345# for the current field.
1346# ----------------------------------------------------------------------
1347itcl::body Rappture::NanovisViewer::FixLegend {} {
1348    set _resizeLegendPending 0
1349    set lineht [font metrics $itk_option(-font) -linespace]
1350    set w [expr {$_width-20}]
1351    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1352    if {$w > 0 && $h > 0 && $_first != "" } {
1353        if { [info exists _cname2transferFunction($_current)] } {
1354            SendCmd "legend $_current $w $h"
1355        }
1356    }
1357}
1358
1359#
1360# NameTransferFunction --
1361#
1362#       Creates a transfer function name based on the <style> settings in the
1363#       library run.xml file. This placeholder will be used later to create
1364#       and send the actual transfer function once the data info has been sent
1365#       to us by the render server. [We won't know the volume limits until the
1366#       server parses the 3D data and sends back the limits via ReceiveData.]
1367#
1368itcl::body Rappture::NanovisViewer::NameTransferFunction { dataobj cname } {
1369    array set style {
1370        -color BCGYR
1371        -levels 6
1372        -markers ""
1373    }
1374    set tag $dataobj-$cname
1375    array set style [lindex [$dataobj components -style $cname] 0]
1376    if { ![info exists _cname2transferFunction($cname)] } {
1377        # Get the colormap right now, since it doesn't change with marker
1378        # changes.
1379        set cmap [ColorsToColormap $style(-color)]
1380        set amap [list 0.0 0.0 1.0 1.0]
1381        set _cname2transferFunction($cname) [list $cmap $amap]
1382        SendCmd [list transfunc define $cname $cmap $amap]
1383    }
1384    SendCmd "volume shading transfunc $cname $tag"
1385    if { ![info exists _transferFunctionEditors($cname)] } {
1386        set _transferFunctionEditors($cname) \
1387            [Rappture::TransferFunctionEditor ::\#auto $itk_component(legend) \
1388                 $cname \
1389                 -command [itcl::code $this updateTransferFunctions]]
1390    }
1391    return $cname
1392}
1393
1394#
1395# ComputeTransferFunction --
1396#
1397#       Computes and sends the transfer function to the render server.  It's
1398#       assumed that the volume data limits are known and that the global
1399#       transfer-functions slider values have been set up.  Both parts are
1400#       needed to compute the relative value (location) of the marker, and
1401#       the alpha map of the transfer function.
1402#
1403itcl::body Rappture::NanovisViewer::ComputeTransferFunction { cname } {
1404    foreach {cmap amap} $_cname2transferFunction($cname) break
1405
1406    # We have to parse the style attributes for a volume using this
1407    # transfer-function *once*.  This sets up the initial isomarkers for the
1408    # transfer function.  The user may add/delete markers, so we have to
1409    # maintain a list of markers for each transfer-function.  We use the one
1410    # of the volumes (the first in the list) using the transfer-function as a
1411    # reference.
1412    if { ![info exists _parsedFunction($cname)] } {
1413        array set style {
1414            -color BCGYR
1415            -levels 6
1416            -markers ""
1417        }
1418        # Accumulate the style from all the datasets using it.
1419        foreach tag [GetDatasetsWithComponent $cname] {
1420            foreach {dataobj cname} [split [lindex $tag 0] -] break
1421            array set style [lindex [$dataobj components -style $cname] 0]
1422        }
1423        eval $_transferFunctionEditors($cname) limits $_limits($cname)
1424        # Have to defer creation of isomarkers until we have data limits
1425        if { [info exists style(-markers)] &&
1426             [llength $style(-markers)] > 0 } {
1427            ParseMarkersOption $cname $style(-markers)
1428        } else {
1429            ParseLevelsOption $cname $style(-levels)
1430        }
1431
1432    }
1433    set amap [ComputeAlphamap $cname]
1434    set _cname2transferFunction($cname) [list $cmap $amap]
1435    SendCmd [list transfunc define $cname $cmap $amap]
1436}
1437
1438itcl::body Rappture::NanovisViewer::AddNewMarker { x y } {
1439    if { ![info exists _transferFunctionEditors($_current)] } {
1440        continue
1441    }
1442    # Add a new marker to the current transfer function
1443    $_transferFunctionEditors($_current) newMarker $x $y normal
1444    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1445}
1446
1447itcl::body Rappture::NanovisViewer::RemoveMarker { x y } {
1448    if { ![info exists _transferFunctionEditors($_current)] } {
1449        continue
1450    }
1451    # Add a new marker to the current transfer function
1452    $_transferFunctionEditors($_current) deleteMarker $x $y
1453}
1454
1455# ----------------------------------------------------------------------
1456# CONFIGURATION OPTION: -plotbackground
1457# ----------------------------------------------------------------------
1458itcl::configbody Rappture::NanovisViewer::plotbackground {
1459    if { [isconnected] } {
1460        set color $itk_option(-plotbackground)
1461        set rgb [Color2RGB $color]
1462        SendCmd "screen bgcolor $rgb"
1463        $itk_component(legend) configure -background $color
1464    }
1465}
1466
1467# ----------------------------------------------------------------------
1468# CONFIGURATION OPTION: -plotforeground
1469# ----------------------------------------------------------------------
1470itcl::configbody Rappture::NanovisViewer::plotforeground {
1471    if { [isconnected] } {
1472        set color $itk_option(-plotforeground)
1473        set rgb [Color2RGB $color]
1474        SendCmd "volume outline color $rgb"
1475        SendCmd "grid axiscolor $rgb"
1476        SendCmd "grid linecolor $rgb"
1477        $itk_component(legend) itemconfigure labels -fill $color
1478        $itk_component(legend) itemconfigure limits -fill $color
1479    }
1480}
1481
1482# ----------------------------------------------------------------------
1483# CONFIGURATION OPTION: -plotoutline
1484# ----------------------------------------------------------------------
1485itcl::configbody Rappture::NanovisViewer::plotoutline {
1486    # Must check if we are connected because this routine is called from the
1487    # class body when the -plotoutline itk_option is defined.  At that point
1488    # the NanovisViewer class constructor hasn't been called, so we can't
1489    # start sending commands to visualization server.
1490    if { [isconnected] } {
1491        if {"" == $itk_option(-plotoutline)} {
1492            SendCmd "volume outline state off"
1493        } else {
1494            SendCmd "volume outline state on"
1495            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1496        }
1497    }
1498}
1499
1500#
1501# The -levels option takes a single value that represents the number
1502# of evenly distributed markers based on the current data range. Each
1503# marker is a relative value from 0.0 to 1.0.
1504#
1505itcl::body Rappture::NanovisViewer::ParseLevelsOption { cname levels } {
1506    set c $itk_component(legend)
1507    set list {}
1508    regsub -all "," $levels " " levels
1509    if {[string is int $levels]} {
1510        for {set i 1} { $i <= $levels } {incr i} {
1511            lappend list [expr {double($i)/($levels+1)}]
1512        }
1513    } else {
1514        foreach x $levels {
1515            lappend list $x
1516        }
1517    }
1518    set _parsedFunction($cname) 1
1519    $_transferFunctionEditors($cname) addMarkers $list
1520    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1521}
1522
1523#
1524# The -markers option takes a list of zero or more values (the values
1525# may be separated either by spaces or commas) that have the following
1526# format:
1527#
1528#   N%  Percent of current total data range.  Converted to
1529#       to a relative value between 0.0 and 1.0.
1530#   N   Absolute value of marker.  If the marker is outside of
1531#       the current range, it will be displayed on the outer
1532#       edge of the legends, but it range it represents will
1533#       not be seen.
1534#
1535itcl::body Rappture::NanovisViewer::ParseMarkersOption { cname markers } {
1536    set c $itk_component(legend)
1537    set list {}
1538    foreach { min max } $_limits($cname) break
1539    regsub -all "," $markers " " markers
1540    foreach marker $markers {
1541        set n [scan $marker "%g%s" value suffix]
1542        if { $n == 2 && $suffix == "%" } {
1543            # $n% : Set relative value (0..1).
1544            lappend list [expr {$value * 0.01}]
1545        } else {
1546            # $n : absolute value, compute relative
1547            lappend list  [expr {(double($value)-$min)/($max-$min)]}
1548        }
1549    }
1550    set _parsedFunction($cname) 1
1551    $_transferFunctionEditors($cname) addMarkers $list
1552    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1553}
1554
1555# ----------------------------------------------------------------------
1556# USAGE: UpdateTransferFuncs
1557# ----------------------------------------------------------------------
1558itcl::body Rappture::NanovisViewer::updateTransferFunctions {} {
1559    $_dispatcher event -idle !send_transfunc
1560}
1561
1562itcl::body Rappture::NanovisViewer::BuildViewTab {} {
1563    set fg [option get $itk_component(hull) font Font]
1564    #set bfg [option get $itk_component(hull) boldFont Font]
1565
1566    set inner [$itk_component(main) insert end \
1567        -title "View Settings" \
1568        -icon [Rappture::icon wrench]]
1569    $inner configure -borderwidth 4
1570
1571    set ::Rappture::NanovisViewer::_settings(-isosurfaceshading) 0
1572    checkbutton $inner.isosurface \
1573        -text "Isosurface shading" \
1574        -variable [itcl::scope _settings(-isosurfaceshading)] \
1575        -command [itcl::code $this AdjustSetting -isosurfaceshading] \
1576        -font "Arial 9"
1577
1578    checkbutton $inner.axes \
1579        -text "Axes" \
1580        -variable [itcl::scope _settings(-axesvisible)] \
1581        -command [itcl::code $this AdjustSetting -axesvisible] \
1582        -font "Arial 9"
1583
1584    checkbutton $inner.grid \
1585        -text "Grid" \
1586        -variable [itcl::scope _settings(-gridvisible)] \
1587        -command [itcl::code $this AdjustSetting -gridvisible] \
1588        -font "Arial 9"
1589
1590    checkbutton $inner.outline \
1591        -text "Outline" \
1592        -variable [itcl::scope _settings(-outlinevisible)] \
1593        -command [itcl::code $this AdjustSetting -outlinevisible] \
1594        -font "Arial 9"
1595
1596    checkbutton $inner.legend \
1597        -text "Legend" \
1598        -variable [itcl::scope _settings(-legendvisible)] \
1599        -command [itcl::code $this AdjustSetting -legendvisible] \
1600        -font "Arial 9"
1601
1602    checkbutton $inner.volume \
1603        -text "Volume" \
1604        -variable [itcl::scope _settings(-volume)] \
1605        -command [itcl::code $this AdjustSetting -volume] \
1606        -font "Arial 9"
1607
1608    label $inner.background_l -text "Background" -font "Arial 9"
1609    itk_component add background {
1610        Rappture::Combobox $inner.background -width 10 -editable no
1611    }
1612    $inner.background choices insert end \
1613        "black"              "black"            \
1614        "white"              "white"            \
1615        "grey"               "grey"
1616
1617    $itk_component(background) value $_settings(-background)
1618    bind $inner.background <<Value>> \
1619        [itcl::code $this AdjustSetting -background]
1620
1621    blt::table $inner \
1622        0,0 $inner.axes  -cspan 2 -anchor w \
1623        1,0 $inner.grid  -cspan 2 -anchor w \
1624        2,0 $inner.outline  -cspan 2 -anchor w \
1625        3,0 $inner.volume  -cspan 2 -anchor w \
1626        4,0 $inner.legend  -cspan 2 -anchor w \
1627        5,0 $inner.background_l       -anchor e -pady 2 \
1628        5,1 $inner.background                   -fill x \
1629
1630    if 0 {
1631    bind $inner <Map> [itcl::code $this GetVolumeInfo $inner]
1632    }
1633    blt::table configure $inner r* -resize none
1634    blt::table configure $inner r6 -resize expand
1635}
1636
1637itcl::body Rappture::NanovisViewer::BuildVolumeTab {} {
1638    set inner [$itk_component(main) insert end \
1639        -title "Volume Settings" \
1640        -icon [Rappture::icon volume-on]]
1641    $inner configure -borderwidth 4
1642
1643    set fg [option get $itk_component(hull) font Font]
1644    #set bfg [option get $itk_component(hull) boldFont Font]
1645
1646    label $inner.lighting_l \
1647        -text "Lighting / Material Properties" \
1648        -font "Arial 9 bold"
1649
1650    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
1651        -variable [itcl::scope _settings(-light2side)] \
1652        -command [itcl::code $this AdjustSetting -light2side]
1653
1654    checkbutton $inner.visibility -text "Visible" -font $fg \
1655        -variable [itcl::scope _settings(-volumevisible)] \
1656        -command [itcl::code $this AdjustSetting -volumevisible]
1657
1658    label $inner.dim -text "Glow" -font $fg
1659    ::scale $inner.light -from 0 -to 100 -orient horizontal \
1660        -variable [itcl::scope _settings(-light)] \
1661        -showvalue off -command [itcl::code $this AdjustSetting -light] \
1662        -troughcolor grey92
1663    label $inner.bright -text "Surface" -font $fg
1664
1665    # Opacity
1666    label $inner.opacity_l -text "Opacity" -font $fg
1667    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1668        -variable [itcl::scope _widget(-volumeopacity)] \
1669        -showvalue off \
1670        -command [itcl::code $this AdjustSetting -volumeopacity] \
1671        -troughcolor grey92
1672
1673    label $inner.transferfunction_l \
1674        -text "Transfer Function" -font "Arial 9 bold"
1675
1676    # Tooth thickness
1677    label $inner.thin -text "Thin" -font $fg
1678    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
1679        -variable [itcl::scope _settings(-thickness)] \
1680        -showvalue off -command [itcl::code $this AdjustSetting -thickness] \
1681        -troughcolor grey92
1682    label $inner.thick -text "Thick" -font $fg
1683
1684    # Colormap
1685    label $inner.colormap_l -text "Colormap" -font $fg
1686    itk_component add colormap {
1687        Rappture::Combobox $inner.colormap -width 10 -editable no
1688    }
1689
1690    $inner.colormap choices insert end [GetColormapList -includeDefault -includeNone]
1691    bind $inner.colormap <<Value>> \
1692        [itcl::code $this AdjustSetting -colormap]
1693    $itk_component(colormap) value "default"
1694    set _settings(-colormap) "default"
1695
1696    # Component
1697    label $inner.volcomponents_l -text "Component" -font $fg
1698    itk_component add volcomponents {
1699        Rappture::Combobox $inner.volcomponents -editable no
1700    }
1701    bind $inner.volcomponents <<Value>> \
1702        [itcl::code $this AdjustSetting -current]
1703
1704    blt::table $inner \
1705        0,0 $inner.volcomponents_l -anchor e -cspan 2 \
1706        0,2 $inner.volcomponents             -cspan 3 -fill x \
1707        1,1 $inner.lighting_l -anchor w -cspan 4 \
1708        2,1 $inner.dim -anchor e \
1709        2,2 $inner.light -cspan 2 -fill x \
1710        2,4 $inner.bright -anchor w \
1711        3,1 $inner.light2side -cspan 3 -anchor w \
1712        4,1 $inner.visibility -cspan 3 -anchor w \
1713        5,1 $inner.transferfunction_l -cspan 4 -anchor w \
1714        6,1 $inner.opacity_l -anchor e -pady 2 \
1715        6,2 $inner.opacity -cspan 3 -fill x \
1716        7,1 $inner.colormap_l -anchor e \
1717        7,2 $inner.colormap -padx 2 -cspan 3 -fill x \
1718        8,1 $inner.thin -anchor e \
1719        8,2 $inner.thickness -cspan 2 -fill x \
1720        8,4 $inner.thick -anchor w
1721
1722    blt::table configure $inner c* r* -resize none
1723    blt::table configure $inner r* -pady { 2 0 }
1724    blt::table configure $inner c2 c3 r9 -resize expand
1725    blt::table configure $inner c0 -width .1i
1726}
1727
1728itcl::body Rappture::NanovisViewer::BuildCutplanesTab {} {
1729    set inner [$itk_component(main) insert end \
1730        -title "Cutplane Settings" \
1731        -icon [Rappture::icon cutbutton]]
1732    $inner configure -borderwidth 4
1733
1734    checkbutton $inner.visible \
1735        -text "Show Cutplanes" \
1736        -variable [itcl::scope _settings(-cutplanesvisible)] \
1737        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1738        -font "Arial 9"
1739
1740    # X-value slicer...
1741    itk_component add xCutButton {
1742        Rappture::PushButton $inner.xbutton \
1743            -onimage [Rappture::icon x-cutplane] \
1744            -offimage [Rappture::icon x-cutplane] \
1745            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1746            -variable [itcl::scope _settings(-xcutplanevisible)]
1747    }
1748    Rappture::Tooltip::for $itk_component(xCutButton) \
1749        "Toggle the X cut plane on/off"
1750    $itk_component(xCutButton) select
1751
1752    itk_component add xCutScale {
1753        ::scale $inner.xval -from 100 -to 0 \
1754            -width 10 -orient vertical -showvalue off \
1755            -borderwidth 1 -highlightthickness 0 \
1756            -command [itcl::code $this Slice move x] \
1757            -variable [itcl::scope _settings(-xcutplaneposition)]
1758    } {
1759        usual
1760        ignore -borderwidth -highlightthickness
1761    }
1762    # Set the default cutplane value before disabling the scale.
1763    $itk_component(xCutScale) set 50
1764    $itk_component(xCutScale) configure -state disabled
1765    Rappture::Tooltip::for $itk_component(xCutScale) \
1766        "@[itcl::code $this SlicerTip x]"
1767
1768    # Y-value slicer...
1769    itk_component add yCutButton {
1770        Rappture::PushButton $inner.ybutton \
1771            -onimage [Rappture::icon y-cutplane] \
1772            -offimage [Rappture::icon y-cutplane] \
1773            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1774            -variable [itcl::scope _settings(-ycutplanevisible)]
1775    }
1776    Rappture::Tooltip::for $itk_component(yCutButton) \
1777        "Toggle the Y cut plane on/off"
1778    $itk_component(yCutButton) select
1779
1780    itk_component add yCutScale {
1781        ::scale $inner.yval -from 100 -to 0 \
1782            -width 10 -orient vertical -showvalue off \
1783            -borderwidth 1 -highlightthickness 0 \
1784            -command [itcl::code $this Slice move y] \
1785            -variable [itcl::scope _settings(-ycutplaneposition)]
1786    } {
1787        usual
1788        ignore -borderwidth -highlightthickness
1789    }
1790    Rappture::Tooltip::for $itk_component(yCutScale) \
1791        "@[itcl::code $this SlicerTip y]"
1792    # Set the default cutplane value before disabling the scale.
1793    $itk_component(yCutScale) set 50
1794    $itk_component(yCutScale) configure -state disabled
1795
1796    # Z-value slicer...
1797    itk_component add zCutButton {
1798        Rappture::PushButton $inner.zbutton \
1799            -onimage [Rappture::icon z-cutplane] \
1800            -offimage [Rappture::icon z-cutplane] \
1801            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1802            -variable [itcl::scope _settings(-zcutplanevisible)]
1803    }
1804    Rappture::Tooltip::for $itk_component(zCutButton) \
1805        "Toggle the Z cut plane on/off"
1806    $itk_component(zCutButton) select
1807
1808    itk_component add zCutScale {
1809        ::scale $inner.zval -from 100 -to 0 \
1810            -width 10 -orient vertical -showvalue off \
1811            -borderwidth 1 -highlightthickness 0 \
1812            -command [itcl::code $this Slice move z] \
1813            -variable [itcl::scope _settings(-zcutplaneposition)]
1814    } {
1815        usual
1816        ignore -borderwidth -highlightthickness
1817    }
1818    $itk_component(zCutScale) set 50
1819    $itk_component(zCutScale) configure -state disabled
1820    Rappture::Tooltip::for $itk_component(zCutScale) \
1821        "@[itcl::code $this SlicerTip z]"
1822
1823    blt::table $inner \
1824        0,1 $inner.visible              -anchor w -pady 2 -cspan 4 \
1825        1,1 $itk_component(xCutScale) \
1826        1,2 $itk_component(yCutScale) \
1827        1,3 $itk_component(zCutScale) \
1828        2,1 $itk_component(xCutButton) \
1829        2,2 $itk_component(yCutButton) \
1830        2,3 $itk_component(zCutButton)
1831
1832    blt::table configure $inner r0 r1 r2 c* -resize none
1833    blt::table configure $inner r3 c4 -resize expand
1834    blt::table configure $inner c0 -width 2
1835    blt::table configure $inner c1 c2 c3 -padx 2
1836}
1837
1838itcl::body Rappture::NanovisViewer::BuildCameraTab {} {
1839    set inner [$itk_component(main) insert end \
1840        -title "Camera Settings" \
1841        -icon [Rappture::icon camera]]
1842    $inner configure -borderwidth 4
1843
1844    label $inner.view_l -text "view" -font "Arial 9"
1845    set f [frame $inner.view]
1846    foreach side { front back left right top bottom } {
1847        button $f.$side  -image [Rappture::icon view$side] \
1848            -command [itcl::code $this SetOrientation $side]
1849        Rappture::Tooltip::for $f.$side "Change the view to $side"
1850        pack $f.$side -side left
1851    }
1852
1853    blt::table $inner \
1854        0,0 $inner.view_l -anchor e -pady 2 \
1855        0,1 $inner.view -anchor w -pady 2
1856    blt::table configure $inner r0 -resize none
1857
1858    set row 1
1859    set labels { qw qx qy qz xpan ypan zoom }
1860    foreach tag $labels {
1861        label $inner.${tag}label -text $tag -font "Arial 9"
1862        entry $inner.${tag} -font "Arial 9"  -bg white \
1863            -textvariable [itcl::scope _settings(-$tag)]
1864        bind $inner.${tag} <Return> \
1865            [itcl::code $this camera set -${tag}]
1866        bind $inner.${tag} <KP_Enter> \
1867            [itcl::code $this camera set -${tag}]
1868        blt::table $inner \
1869            $row,0 $inner.${tag}label -anchor e -pady 2 \
1870            $row,1 $inner.${tag} -anchor w -pady 2
1871        blt::table configure $inner r$row -resize none
1872        incr row
1873    }
1874
1875    blt::table configure $inner c* -resize none
1876    blt::table configure $inner c2 -resize expand
1877    blt::table configure $inner r$row -resize expand
1878}
1879
1880# ----------------------------------------------------------------------
1881# USAGE: Slice move x|y|z <newval>
1882#
1883# Called automatically when the user drags the slider to move the
1884# cut plane that slices 3D data.  Gets the current value from the
1885# slider and moves the cut plane to the appropriate point in the
1886# data set.
1887# ----------------------------------------------------------------------
1888itcl::body Rappture::NanovisViewer::Slice {option args} {
1889    switch -- $option {
1890        move {
1891            if {[llength $args] != 2} {
1892                error "wrong # args: should be \"Slice move x|y|z newval\""
1893            }
1894            set axis [lindex $args 0]
1895            set newval [lindex $args 1]
1896
1897            set newpos [expr {0.01*$newval}]
1898            set datasets [CurrentDatasets -cutplanes]
1899            set tag [lindex $datasets 0]
1900            SendCmd "cutplane position $newpos $axis $tag"
1901        }
1902        default {
1903            error "bad option \"$option\": should be axis, move, or volume"
1904        }
1905    }
1906}
1907
1908# ----------------------------------------------------------------------
1909# USAGE: SlicerTip <axis>
1910#
1911# Used internally to generate a tooltip for the x/y/z slicer controls.
1912# Returns a message that includes the current slicer value.
1913# ----------------------------------------------------------------------
1914itcl::body Rappture::NanovisViewer::SlicerTip {axis} {
1915    set val [$itk_component(${axis}CutScale) get]
1916    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
1917}
1918
1919
1920itcl::body Rappture::NanovisViewer::DoResize {} {
1921    $_arcball resize $_width $_height
1922    SendCmd "screen size $_width $_height"
1923    set _resizePending 0
1924}
1925
1926itcl::body Rappture::NanovisViewer::EventuallyResize { w h } {
1927    set _width $w
1928    set _height $h
1929    $_arcball resize $w $h
1930    if { !$_resizePending } {
1931        $_dispatcher event -idle !resize
1932        set _resizePending 1
1933    }
1934}
1935
1936itcl::body Rappture::NanovisViewer::EventuallyRedrawLegend {} {
1937    if { !$_resizeLegendPending } {
1938        $_dispatcher event -idle !legend
1939        set _resizeLegendPending 1
1940    }
1941}
1942
1943#  camera --
1944#
1945itcl::body Rappture::NanovisViewer::camera {option args} {
1946    switch -- $option {
1947        "show" {
1948            puts [array get _view]
1949        }
1950        "set" {
1951            set what [lindex $args 0]
1952            set x $_settings($what)
1953            set code [catch { string is double $x } result]
1954            if { $code != 0 || !$result } {
1955                set _settings($what) $_view($what)
1956                return
1957            }
1958            switch -- $what {
1959                "-xpan" - "-ypan" {
1960                    set _view($what) $_settings($what)
1961                    PanCamera
1962                }
1963                "-qx" - "-qy" - "-qz" - "-qw" {
1964                    set _view($what) $_settings($what)
1965                    set q [ViewToQuaternion]
1966                    $_arcball quaternion $q
1967                    SendCmd "camera orient $q"
1968                }
1969                "-zoom" {
1970                    set _view($what) $_settings($what)
1971                    SendCmd "camera zoom $_view($what)"
1972                }
1973            }
1974        }
1975    }
1976}
1977
1978itcl::body Rappture::NanovisViewer::GetVolumeInfo { w } {
1979    set flowobj ""
1980    foreach key [array names _obj2flow] {
1981        set flowobj $_obj2flow($key)
1982        break
1983    }
1984    if { $flowobj == "" } {
1985        return
1986    }
1987    if { [winfo exists $w.frame] } {
1988        destroy $w.frame
1989    }
1990    set inner [frame $w.frame]
1991    blt::table $w \
1992        5,0 $inner -fill both -cspan 2 -anchor nw
1993    array set hints [$dataobj hints]
1994
1995    label $inner.volumes -text "Volumes" -font "Arial 9 bold"
1996    blt::table $inner \
1997        1,0 $inner.volumes  -anchor w \
1998    blt::table configure $inner c0 c1 -resize none
1999    blt::table configure $inner c2 -resize expand
2000
2001    set row 3
2002    set volumes [get]
2003    if { [llength $volumes] > 0 } {
2004        blt::table $inner $row,0 $inner.volumes  -anchor w
2005        incr row
2006    }
2007    foreach vol $volumes {
2008        array unset info
2009        array set info $vol
2010        set name $info(name)
2011        if { ![info exists _settings(-volumevisible-$name)] } {
2012            set _settings(-volumevisible-$name) $info(hide)
2013        }
2014        checkbutton $inner.vol$row -text $info(label) \
2015            -variable [itcl::scope _settings(-volumevisible-$name)] \
2016            -onvalue 0 -offvalue 1 \
2017            -command [itcl::code $this ToggleVolume $key $name] \
2018            -font "Arial 9"
2019        Rappture::Tooltip::for $inner.vol$row $info(description)
2020        blt::table $inner $row,0 $inner.vol$row -anchor w
2021        if { !$_settings(-volume-$name) } {
2022            $inner.vol$row select
2023        }
2024        incr row
2025    }
2026    blt::table configure $inner r* -resize none
2027    blt::table configure $inner r$row -resize expand
2028    blt::table configure $inner c3 -resize expand
2029    event generate [winfo parent [winfo parent $w]] <Configure>
2030}
2031
2032itcl::body Rappture::NanovisViewer::ToggleVolume { tag name } {
2033    set bool $_settings(-volumevisible-$name)
2034    SendCmd "volume state $bool $name"
2035}
2036
2037itcl::body Rappture::NanovisViewer::SetOrientation { side } {
2038    array set positions {
2039        front "1 0 0 0"
2040        back  "0 0 1 0"
2041        left  "0.707107 0 -0.707107 0"
2042        right "0.707107 0 0.707107 0"
2043        top   "0.707107 -0.707107 0 0"
2044        bottom "0.707107 0.707107 0 0"
2045    }
2046    foreach name { -qw -qx -qy -qz } value $positions($side) {
2047        set _view($name) $value
2048    }
2049    set q [ViewToQuaternion]
2050    $_arcball quaternion $q
2051    SendCmd "camera orient $q"
2052    SendCmd "camera reset"
2053    set _view(-xpan) 0
2054    set _view(-ypan) 0
2055    set _view(-zoom) 1.0
2056    set _settings(-xpan) $_view(-xpan)
2057    set _settings(-ypan) $_view(-ypan)
2058    set _settings(-zoom) $_view(-zoom)
2059}
2060
2061
2062#
2063# InitComponentSettings --
2064#
2065#    Initializes the volume settings for a specific component. This should
2066#    match what's used as global settings above. This is called the first
2067#    time we try to switch to a given component in SwitchComponent below.
2068#
2069itcl::body Rappture::NanovisViewer::InitComponentSettings { cname } {
2070    foreach {key value} {
2071        -colormap          "default"
2072        -light             40
2073        -light2side        1
2074        -thickness         350
2075        -volumeopacity     1.0
2076        -volumevisible     1
2077    } {
2078        if { ![info exists _settings($cname${key})] } {
2079            # Don't override existing component settings
2080            set _settings($cname${key}) $value
2081        }
2082    }
2083}
2084
2085#
2086# SwitchComponent --
2087#
2088#    This is called when the current component is changed by the dropdown
2089#    menu in the volume tab.  It synchronizes the global volume settings
2090#    with the settings of the new current component.
2091#
2092itcl::body Rappture::NanovisViewer::SwitchComponent { cname } {
2093    if { ![info exists _settings($cname-light)] } {
2094        InitComponentSettings $cname
2095    }
2096    if { $_settings(-colormap) != $_settings($cname-colormap) } {
2097        set _settings(-colormap)         $_settings($cname-colormap)
2098        EventuallyRedrawLegend
2099    }
2100    # _settings variables change widgets, except for colormap
2101    set _settings(-light)            $_settings($cname-light)
2102    set _settings(-light2side)       $_settings($cname-light2side)
2103    set _settings(-volumeopacity)    $_settings($cname-volumeopacity)
2104    set _settings(-thickness)        $_settings($cname-thickness)
2105    set _settings(-volumevisible)    $_settings($cname-volumevisible)
2106    $itk_component(colormap) value   $_settings($cname-colormap)
2107
2108    set _widget(-volumeopacity) [expr $_settings(-volumeopacity) * 100.0]
2109
2110    set _current $cname;                # Reset the current component
2111}
2112
2113#
2114# BuildVolumeComponents --
2115#
2116#    This is called from the "scale" method which is called when a new
2117#    dataset is added or deleted.  It repopulates the dropdown menu of
2118#    volume component names.  It sets the current component to the first
2119#    component in the list (of components found).  Finally, if there is
2120#    only one component, don't display the label or the combobox in the
2121#    volume settings tab.
2122#
2123itcl::body Rappture::NanovisViewer::BuildVolumeComponents {} {
2124    $itk_component(volcomponents) choices delete 0 end
2125    foreach name $_componentsList {
2126        $itk_component(volcomponents) choices insert end $name $name
2127    }
2128    set _current [lindex $_componentsList 0]
2129    $itk_component(volcomponents) value $_current
2130    set parent [winfo parent $itk_component(volcomponents)]
2131    if { [llength $_componentsList] <= 1 } {
2132        # Unpack the components label and dropdown if there's only one
2133        # component.
2134        blt::table forget $parent.volcomponents_l $parent.volcomponents
2135    } else {
2136        # Pack the components label and dropdown into the table there's
2137        # more than one component to select.
2138        blt::table $parent \
2139            0,0 $parent.volcomponents_l -anchor e -cspan 2 \
2140            0,2 $parent.volcomponents -cspan 3 -fill x
2141    }
2142}
2143
2144#
2145# GetDatasetsWithComponents --
2146#
2147#    Returns a list of all the datasets (known by the combination of their
2148#    data object and component name) that match the given component name.
2149#    For example, this is used where we want to change the settings of
2150#    volumes that have the current component.
2151#
2152itcl::body Rappture::NanovisViewer::GetDatasetsWithComponent { cname } {
2153    if { ![info exists _volcomponents($cname)] } {
2154        return ""
2155    }
2156    set list ""
2157    foreach tag $_volcomponents($cname) {
2158        if { ![info exists _serverDatasets($tag)] } {
2159            continue
2160        }
2161        lappend list $tag
2162    }
2163    return $list
2164}
2165
2166#
2167# HideAllMarkers --
2168#
2169#    Hide all the markers in all the transfer functions.  Can't simply
2170#    delete and recreate markers from the <style> since the user may have
2171#    created, deleted, or moved markers.
2172#
2173itcl::body Rappture::NanovisViewer::HideAllMarkers {} {
2174    foreach cname [array names _transferFunctionEditors] {
2175        $_transferFunctionEditors($cname) hideMarkers
2176    }
2177}
2178
2179itcl::body Rappture::NanovisViewer::GetColormap { cname color } {
2180    if { $color == "default" } {
2181        return $_cname2defaultcolormap($cname)
2182    }
2183    return [ColorsToColormap $color]
2184}
2185
2186itcl::body Rappture::NanovisViewer::ResetColormap { cname color } {
2187    # Get the current transfer function
2188    if { ![info exists _cname2transferFunction($cname)] } {
2189        return
2190    }
2191    foreach { cmap amap } $_cname2transferFunction($cname) break
2192    set cmap [GetColormap $cname $color]
2193    set _cname2transferFunction($cname) [list $cmap $amap]
2194    SendCmd [list transfunc define $cname $cmap $amap]
2195    EventuallyRedrawLegend
2196}
2197
2198itcl::body Rappture::NanovisViewer::ComputeAlphamap { cname } {
2199    if { ![info exists _transferFunctionEditors($cname)] } {
2200        return [list 0.0 0.0 1.0 1.0]
2201    }
2202    if { ![info exists _settings($cname-light)] } {
2203        InitComponentSettings $cname
2204    }
2205
2206    set isovalues [$_transferFunctionEditors($cname) values]
2207
2208    # Transfer function should be normalized with [0,1] range
2209    # The volume shading opacity setting is used to scale opacity
2210    # in the volume shader.
2211    set max 1.0
2212
2213    # Use the component-wise thickness setting from the slider
2214    # settings widget
2215    # Scale values between 0.00001 and 0.01000
2216    set delta [expr {double($_settings($cname-thickness)) * 0.0001}]
2217
2218    set first [lindex $isovalues 0]
2219    set last [lindex $isovalues end]
2220    set amap ""
2221    if { $first == "" || $first != 0.0 } {
2222        lappend amap 0.0 0.0
2223    }
2224    foreach x $isovalues {
2225        set x1 [expr {$x-$delta-0.00001}]
2226        set x2 [expr {$x-$delta}]
2227        set x3 [expr {$x+$delta}]
2228        set x4 [expr {$x+$delta+0.00001}]
2229        if { $x1 < 0.0 } {
2230            set x1 0.0
2231        } elseif { $x1 > 1.0 } {
2232            set x1 1.0
2233        }
2234        if { $x2 < 0.0 } {
2235            set x2 0.0
2236        } elseif { $x2 > 1.0 } {
2237            set x2 1.0
2238        }
2239        if { $x3 < 0.0 } {
2240            set x3 0.0
2241        } elseif { $x3 > 1.0 } {
2242            set x3 1.0
2243        }
2244        if { $x4 < 0.0 } {
2245            set x4 0.0
2246        } elseif { $x4 > 1.0 } {
2247            set x4 1.0
2248        }
2249        # add spikes in the middle
2250        lappend amap $x1 0.0
2251        lappend amap $x2 $max
2252        lappend amap $x3 $max
2253        lappend amap $x4 0.0
2254    }
2255    if { $last == "" || $last != 1.0 } {
2256        lappend amap 1.0 0.0
2257    }
2258    return $amap
2259}
2260
2261itcl::body Rappture::NanovisViewer::SetObjectStyle { dataobj cname } {
2262    array set style {
2263        -opacity  0.5
2264    }
2265    array set style [lindex [$dataobj components -style $cname] 0]
2266    # Some tools erroneously set -opacity to 1 in style, so
2267    # override the requested opacity for now
2268    set style(-opacity) 0.5
2269    set _settings($cname-volumeopacity) $style(-opacity)
2270    set tag $dataobj-$cname
2271    SendCmd "volume shading opacity $_settings($cname-volumeopacity) $tag"
2272    NameTransferFunction $dataobj $cname
2273}
Note: See TracBrowser for help on using the repository browser.