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

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

merge r5289 from trunk

File size: 80.5 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            set val $_settings($what)
1251            foreach tag [GetDatasetsWithComponent $_current] {
1252                SendCmd "volume shading isosurface $val $tag"
1253            }
1254        }
1255        "-legendvisible" {
1256            if { $_settings($what) } {
1257                blt::table $itk_component(plotarea) \
1258                    0,0 $itk_component(3dview) -fill both \
1259                    1,0 $itk_component(legend) -fill x
1260                blt::table configure $itk_component(plotarea) r1 -resize none
1261            } else {
1262                blt::table forget $itk_component(legend)
1263            }
1264        }
1265        "-light" {
1266            set _settings($_current${what}) $_settings($what)
1267            set val $_settings($what)
1268            set diffuse [expr {0.01*$val}]
1269            set ambient [expr {1.0-$diffuse}]
1270            set specularLevel 0.3
1271            set specularExp 90.0
1272            foreach tag [GetDatasetsWithComponent $_current] {
1273                SendCmd "volume shading ambient $ambient $tag"
1274                SendCmd "volume shading diffuse $diffuse $tag"
1275                SendCmd "volume shading specularLevel $specularLevel $tag"
1276                SendCmd "volume shading specularExp $specularExp $tag"
1277            }
1278        }
1279        "-light2side" {
1280            set _settings($_current${what}) $_settings($what)
1281            set val $_settings($what)
1282            foreach tag [GetDatasetsWithComponent $_current] {
1283                SendCmd "volume shading light2side $val $tag"
1284            }
1285        }
1286        "-outlinevisible" {
1287            SendCmd "volume outline state $_settings($what)"
1288        }
1289        "-thickness" {
1290            set val $_settings($what)
1291            set _settings($_current${what}) $val
1292            updateTransferFunctions
1293        }
1294        "-volume" {
1295            # This is the global volume visibility control.  It controls the
1296            # visibility of all the all volumes.  Whenever it's changed, you
1297            # have to synchronize each of the local controls (see below) with
1298            # this.
1299            set datasets [CurrentDatasets]
1300            set bool $_settings($what)
1301            SendCmd "volume data state $bool $datasets"
1302            foreach cname $_componentsList {
1303                set _settings($cname-volumevisible) $bool
1304            }
1305            set _settings(-volumevisible) $bool
1306        }
1307        "-volumeopacity" {
1308            set _settings($what) [expr $_widget($what) * 0.01]
1309            set _settings($_current${what}) $_settings($what)
1310            foreach tag [GetDatasetsWithComponent $_current] {
1311                SendCmd "volume shading opacity $_settings($what) $tag"
1312            }
1313        }
1314        "-volumevisible" {
1315            # This is the component specific control.  It changes the
1316            # visibility of only the current component.
1317            set _settings($_current${what}) $_settings($what)
1318            foreach tag [GetDatasetsWithComponent $_current] {
1319                SendCmd "volume data state $_settings($what) $tag"
1320            }
1321        }
1322        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1323            set axis [string range $what 1 1]
1324            set bool $_settings($what)
1325            # We only set cutplanes on the first dataset.
1326            set datasets [CurrentDatasets -cutplanes]
1327            set tag [lindex $datasets 0]
1328            SendCmd "cutplane state $bool $axis $tag"
1329            if { $bool } {
1330                $itk_component(${axis}CutScale) configure -state normal \
1331                    -troughcolor white
1332            } else {
1333                $itk_component(${axis}CutScale) configure -state disabled \
1334                    -troughcolor grey82
1335            }
1336        }
1337        default {
1338            error "don't know how to fix $what"
1339        }
1340    }
1341}
1342
1343# ----------------------------------------------------------------------
1344# USAGE: FixLegend
1345#
1346# Used internally to update the legend area whenever it changes size
1347# or when the field changes.  Asks the server to send a new legend
1348# for the current field.
1349# ----------------------------------------------------------------------
1350itcl::body Rappture::NanovisViewer::FixLegend {} {
1351    set _resizeLegendPending 0
1352    set lineht [font metrics $itk_option(-font) -linespace]
1353    set w [expr {$_width-20}]
1354    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1355    if {$w > 0 && $h > 0 && $_first != "" } {
1356        if { [info exists _cname2transferFunction($_current)] } {
1357            SendCmd "legend $_current $w $h"
1358        }
1359    }
1360}
1361
1362#
1363# NameTransferFunction --
1364#
1365#       Creates a transfer function name based on the <style> settings in the
1366#       library run.xml file. This placeholder will be used later to create
1367#       and send the actual transfer function once the data info has been sent
1368#       to us by the render server. [We won't know the volume limits until the
1369#       server parses the 3D data and sends back the limits via ReceiveData.]
1370#
1371itcl::body Rappture::NanovisViewer::NameTransferFunction { dataobj cname } {
1372    array set style {
1373        -color BCGYR
1374        -levels 6
1375        -markers ""
1376    }
1377    set tag $dataobj-$cname
1378    array set style [lindex [$dataobj components -style $cname] 0]
1379    if { ![info exists _cname2transferFunction($cname)] } {
1380        # Get the colormap right now, since it doesn't change with marker
1381        # changes.
1382        set cmap [ColorsToColormap $style(-color)]
1383        set amap [list 0.0 0.0 1.0 1.0]
1384        set _cname2transferFunction($cname) [list $cmap $amap]
1385        SendCmd [list transfunc define $cname $cmap $amap]
1386    }
1387    SendCmd "volume shading transfunc $cname $tag"
1388    if { ![info exists _transferFunctionEditors($cname)] } {
1389        set _transferFunctionEditors($cname) \
1390            [Rappture::TransferFunctionEditor ::\#auto $itk_component(legend) \
1391                 $cname \
1392                 -command [itcl::code $this updateTransferFunctions]]
1393    }
1394    return $cname
1395}
1396
1397#
1398# ComputeTransferFunction --
1399#
1400#       Computes and sends the transfer function to the render server.  It's
1401#       assumed that the volume data limits are known and that the global
1402#       transfer-functions slider values have been set up.  Both parts are
1403#       needed to compute the relative value (location) of the marker, and
1404#       the alpha map of the transfer function.
1405#
1406itcl::body Rappture::NanovisViewer::ComputeTransferFunction { cname } {
1407    foreach {cmap amap} $_cname2transferFunction($cname) break
1408
1409    # We have to parse the style attributes for a volume using this
1410    # transfer-function *once*.  This sets up the initial isomarkers for the
1411    # transfer function.  The user may add/delete markers, so we have to
1412    # maintain a list of markers for each transfer-function.  We use the one
1413    # of the volumes (the first in the list) using the transfer-function as a
1414    # reference.
1415    if { ![info exists _parsedFunction($cname)] } {
1416        array set style {
1417            -color BCGYR
1418            -levels 6
1419            -markers ""
1420        }
1421        # Accumulate the style from all the datasets using it.
1422        foreach tag [GetDatasetsWithComponent $cname] {
1423            foreach {dataobj cname} [split [lindex $tag 0] -] break
1424            array set style [lindex [$dataobj components -style $cname] 0]
1425        }
1426        eval $_transferFunctionEditors($cname) limits $_limits($cname)
1427        # Have to defer creation of isomarkers until we have data limits
1428        if { [info exists style(-markers)] &&
1429             [llength $style(-markers)] > 0 } {
1430            ParseMarkersOption $cname $style(-markers)
1431        } else {
1432            ParseLevelsOption $cname $style(-levels)
1433        }
1434
1435    }
1436    set amap [ComputeAlphamap $cname]
1437    set _cname2transferFunction($cname) [list $cmap $amap]
1438    SendCmd [list transfunc define $cname $cmap $amap]
1439}
1440
1441itcl::body Rappture::NanovisViewer::AddNewMarker { x y } {
1442    if { ![info exists _transferFunctionEditors($_current)] } {
1443        continue
1444    }
1445    # Add a new marker to the current transfer function
1446    $_transferFunctionEditors($_current) newMarker $x $y normal
1447    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1448}
1449
1450itcl::body Rappture::NanovisViewer::RemoveMarker { x y } {
1451    if { ![info exists _transferFunctionEditors($_current)] } {
1452        continue
1453    }
1454    # Add a new marker to the current transfer function
1455    $_transferFunctionEditors($_current) deleteMarker $x $y
1456}
1457
1458# ----------------------------------------------------------------------
1459# CONFIGURATION OPTION: -plotbackground
1460# ----------------------------------------------------------------------
1461itcl::configbody Rappture::NanovisViewer::plotbackground {
1462    if { [isconnected] } {
1463        set color $itk_option(-plotbackground)
1464        set rgb [Color2RGB $color]
1465        SendCmd "screen bgcolor $rgb"
1466        $itk_component(legend) configure -background $color
1467    }
1468}
1469
1470# ----------------------------------------------------------------------
1471# CONFIGURATION OPTION: -plotforeground
1472# ----------------------------------------------------------------------
1473itcl::configbody Rappture::NanovisViewer::plotforeground {
1474    if { [isconnected] } {
1475        set color $itk_option(-plotforeground)
1476        set rgb [Color2RGB $color]
1477        SendCmd "volume outline color $rgb"
1478        SendCmd "grid axiscolor $rgb"
1479        SendCmd "grid linecolor $rgb"
1480        $itk_component(legend) itemconfigure labels -fill $color
1481        $itk_component(legend) itemconfigure limits -fill $color
1482    }
1483}
1484
1485# ----------------------------------------------------------------------
1486# CONFIGURATION OPTION: -plotoutline
1487# ----------------------------------------------------------------------
1488itcl::configbody Rappture::NanovisViewer::plotoutline {
1489    # Must check if we are connected because this routine is called from the
1490    # class body when the -plotoutline itk_option is defined.  At that point
1491    # the NanovisViewer class constructor hasn't been called, so we can't
1492    # start sending commands to visualization server.
1493    if { [isconnected] } {
1494        if {"" == $itk_option(-plotoutline)} {
1495            SendCmd "volume outline state off"
1496        } else {
1497            SendCmd "volume outline state on"
1498            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1499        }
1500    }
1501}
1502
1503#
1504# The -levels option takes a single value that represents the number
1505# of evenly distributed markers based on the current data range. Each
1506# marker is a relative value from 0.0 to 1.0.
1507#
1508itcl::body Rappture::NanovisViewer::ParseLevelsOption { cname levels } {
1509    set c $itk_component(legend)
1510    set list {}
1511    regsub -all "," $levels " " levels
1512    if {[string is int $levels]} {
1513        for {set i 1} { $i <= $levels } {incr i} {
1514            lappend list [expr {double($i)/($levels+1)}]
1515        }
1516    } else {
1517        foreach x $levels {
1518            lappend list $x
1519        }
1520    }
1521    set _parsedFunction($cname) 1
1522    $_transferFunctionEditors($cname) addMarkers $list
1523    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1524}
1525
1526#
1527# The -markers option takes a list of zero or more values (the values
1528# may be separated either by spaces or commas) that have the following
1529# format:
1530#
1531#   N%  Percent of current total data range.  Converted to
1532#       to a relative value between 0.0 and 1.0.
1533#   N   Absolute value of marker.  If the marker is outside of
1534#       the current range, it will be displayed on the outer
1535#       edge of the legends, but it range it represents will
1536#       not be seen.
1537#
1538itcl::body Rappture::NanovisViewer::ParseMarkersOption { cname markers } {
1539    set c $itk_component(legend)
1540    set list {}
1541    foreach { min max } $_limits($cname) break
1542    regsub -all "," $markers " " markers
1543    foreach marker $markers {
1544        set n [scan $marker "%g%s" value suffix]
1545        if { $n == 2 && $suffix == "%" } {
1546            # $n% : Set relative value (0..1).
1547            lappend list [expr {$value * 0.01}]
1548        } else {
1549            # $n : absolute value, compute relative
1550            lappend list  [expr {(double($value)-$min)/($max-$min)]}
1551        }
1552    }
1553    set _parsedFunction($cname) 1
1554    $_transferFunctionEditors($cname) addMarkers $list
1555    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1556}
1557
1558# ----------------------------------------------------------------------
1559# USAGE: UpdateTransferFuncs
1560# ----------------------------------------------------------------------
1561itcl::body Rappture::NanovisViewer::updateTransferFunctions {} {
1562    $_dispatcher event -idle !send_transfunc
1563}
1564
1565itcl::body Rappture::NanovisViewer::BuildViewTab {} {
1566    set fg [option get $itk_component(hull) font Font]
1567    #set bfg [option get $itk_component(hull) boldFont Font]
1568
1569    set inner [$itk_component(main) insert end \
1570        -title "View Settings" \
1571        -icon [Rappture::icon wrench]]
1572    $inner configure -borderwidth 4
1573
1574    set ::Rappture::NanovisViewer::_settings(-isosurfaceshading) 0
1575    checkbutton $inner.isosurface \
1576        -text "Isosurface shading" \
1577        -variable [itcl::scope _settings(-isosurfaceshading)] \
1578        -command [itcl::code $this AdjustSetting -isosurfaceshading] \
1579        -font "Arial 9"
1580
1581    checkbutton $inner.axes \
1582        -text "Axes" \
1583        -variable [itcl::scope _settings(-axesvisible)] \
1584        -command [itcl::code $this AdjustSetting -axesvisible] \
1585        -font "Arial 9"
1586
1587    checkbutton $inner.grid \
1588        -text "Grid" \
1589        -variable [itcl::scope _settings(-gridvisible)] \
1590        -command [itcl::code $this AdjustSetting -gridvisible] \
1591        -font "Arial 9"
1592
1593    checkbutton $inner.outline \
1594        -text "Outline" \
1595        -variable [itcl::scope _settings(-outlinevisible)] \
1596        -command [itcl::code $this AdjustSetting -outlinevisible] \
1597        -font "Arial 9"
1598
1599    checkbutton $inner.legend \
1600        -text "Legend" \
1601        -variable [itcl::scope _settings(-legendvisible)] \
1602        -command [itcl::code $this AdjustSetting -legendvisible] \
1603        -font "Arial 9"
1604
1605    checkbutton $inner.volume \
1606        -text "Volume" \
1607        -variable [itcl::scope _settings(-volume)] \
1608        -command [itcl::code $this AdjustSetting -volume] \
1609        -font "Arial 9"
1610
1611    label $inner.background_l -text "Background" -font "Arial 9"
1612    itk_component add background {
1613        Rappture::Combobox $inner.background -width 10 -editable no
1614    }
1615    $inner.background choices insert end \
1616        "black"              "black"            \
1617        "white"              "white"            \
1618        "grey"               "grey"
1619
1620    $itk_component(background) value $_settings(-background)
1621    bind $inner.background <<Value>> \
1622        [itcl::code $this AdjustSetting -background]
1623
1624    blt::table $inner \
1625        0,0 $inner.axes  -cspan 2 -anchor w \
1626        1,0 $inner.grid  -cspan 2 -anchor w \
1627        2,0 $inner.outline  -cspan 2 -anchor w \
1628        3,0 $inner.volume  -cspan 2 -anchor w \
1629        4,0 $inner.legend  -cspan 2 -anchor w \
1630        5,0 $inner.background_l       -anchor e -pady 2 \
1631        5,1 $inner.background                   -fill x \
1632
1633    if 0 {
1634    bind $inner <Map> [itcl::code $this GetVolumeInfo $inner]
1635    }
1636    blt::table configure $inner r* -resize none
1637    blt::table configure $inner r6 -resize expand
1638}
1639
1640itcl::body Rappture::NanovisViewer::BuildVolumeTab {} {
1641    set inner [$itk_component(main) insert end \
1642        -title "Volume Settings" \
1643        -icon [Rappture::icon volume-on]]
1644    $inner configure -borderwidth 4
1645
1646    set fg [option get $itk_component(hull) font Font]
1647    #set bfg [option get $itk_component(hull) boldFont Font]
1648
1649    label $inner.lighting_l \
1650        -text "Lighting / Material Properties" \
1651        -font "Arial 9 bold"
1652
1653    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
1654        -variable [itcl::scope _settings(-light2side)] \
1655        -command [itcl::code $this AdjustSetting -light2side]
1656
1657    checkbutton $inner.visibility -text "Visible" -font $fg \
1658        -variable [itcl::scope _settings(-volumevisible)] \
1659        -command [itcl::code $this AdjustSetting -volumevisible]
1660
1661    label $inner.dim -text "Glow" -font $fg
1662    ::scale $inner.light -from 0 -to 100 -orient horizontal \
1663        -variable [itcl::scope _settings(-light)] \
1664        -showvalue off -command [itcl::code $this AdjustSetting -light] \
1665        -troughcolor grey92
1666    label $inner.bright -text "Surface" -font $fg
1667
1668    # Opacity
1669    label $inner.opacity_l -text "Opacity" -font $fg
1670    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1671        -variable [itcl::scope _widget(-volumeopacity)] \
1672        -showvalue off \
1673        -command [itcl::code $this AdjustSetting -volumeopacity] \
1674        -troughcolor grey92
1675
1676    label $inner.transferfunction_l \
1677        -text "Transfer Function" -font "Arial 9 bold"
1678
1679    # Tooth thickness
1680    label $inner.thin -text "Thin" -font $fg
1681    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
1682        -variable [itcl::scope _settings(-thickness)] \
1683        -showvalue off -command [itcl::code $this AdjustSetting -thickness] \
1684        -troughcolor grey92
1685    label $inner.thick -text "Thick" -font $fg
1686
1687    # Colormap
1688    label $inner.colormap_l -text "Colormap" -font $fg
1689    itk_component add colormap {
1690        Rappture::Combobox $inner.colormap -width 10 -editable no
1691    }
1692
1693    $inner.colormap choices insert end [GetColormapList -includeDefault -includeNone]
1694    bind $inner.colormap <<Value>> \
1695        [itcl::code $this AdjustSetting -colormap]
1696    $itk_component(colormap) value "default"
1697    set _settings(-colormap) "default"
1698
1699    # Component
1700    label $inner.volcomponents_l -text "Component" -font $fg
1701    itk_component add volcomponents {
1702        Rappture::Combobox $inner.volcomponents -editable no
1703    }
1704    bind $inner.volcomponents <<Value>> \
1705        [itcl::code $this AdjustSetting -current]
1706
1707    blt::table $inner \
1708        0,0 $inner.volcomponents_l -anchor e -cspan 2 \
1709        0,2 $inner.volcomponents             -cspan 3 -fill x \
1710        1,1 $inner.lighting_l -anchor w -cspan 4 \
1711        2,1 $inner.dim -anchor e \
1712        2,2 $inner.light -cspan 2 -fill x \
1713        2,4 $inner.bright -anchor w \
1714        3,1 $inner.light2side -cspan 3 -anchor w \
1715        4,1 $inner.visibility -cspan 3 -anchor w \
1716        5,1 $inner.transferfunction_l -cspan 4 -anchor w \
1717        6,1 $inner.opacity_l -anchor e -pady 2 \
1718        6,2 $inner.opacity -cspan 3 -fill x \
1719        7,1 $inner.colormap_l -anchor e \
1720        7,2 $inner.colormap -padx 2 -cspan 3 -fill x \
1721        8,1 $inner.thin -anchor e \
1722        8,2 $inner.thickness -cspan 2 -fill x \
1723        8,4 $inner.thick -anchor w
1724
1725    blt::table configure $inner c* r* -resize none
1726    blt::table configure $inner r* -pady { 2 0 }
1727    blt::table configure $inner c2 c3 r9 -resize expand
1728    blt::table configure $inner c0 -width .1i
1729}
1730
1731itcl::body Rappture::NanovisViewer::BuildCutplanesTab {} {
1732    set inner [$itk_component(main) insert end \
1733        -title "Cutplane Settings" \
1734        -icon [Rappture::icon cutbutton]]
1735    $inner configure -borderwidth 4
1736
1737    checkbutton $inner.visible \
1738        -text "Show Cutplanes" \
1739        -variable [itcl::scope _settings(-cutplanesvisible)] \
1740        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1741        -font "Arial 9"
1742
1743    # X-value slicer...
1744    itk_component add xCutButton {
1745        Rappture::PushButton $inner.xbutton \
1746            -onimage [Rappture::icon x-cutplane] \
1747            -offimage [Rappture::icon x-cutplane] \
1748            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1749            -variable [itcl::scope _settings(-xcutplanevisible)]
1750    }
1751    Rappture::Tooltip::for $itk_component(xCutButton) \
1752        "Toggle the X cut plane on/off"
1753    $itk_component(xCutButton) select
1754
1755    itk_component add xCutScale {
1756        ::scale $inner.xval -from 100 -to 0 \
1757            -width 10 -orient vertical -showvalue off \
1758            -borderwidth 1 -highlightthickness 0 \
1759            -command [itcl::code $this Slice move x] \
1760            -variable [itcl::scope _settings(-xcutplaneposition)]
1761    } {
1762        usual
1763        ignore -borderwidth -highlightthickness
1764    }
1765    # Set the default cutplane value before disabling the scale.
1766    $itk_component(xCutScale) set 50
1767    $itk_component(xCutScale) configure -state disabled
1768    Rappture::Tooltip::for $itk_component(xCutScale) \
1769        "@[itcl::code $this SlicerTip x]"
1770
1771    # Y-value slicer...
1772    itk_component add yCutButton {
1773        Rappture::PushButton $inner.ybutton \
1774            -onimage [Rappture::icon y-cutplane] \
1775            -offimage [Rappture::icon y-cutplane] \
1776            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1777            -variable [itcl::scope _settings(-ycutplanevisible)]
1778    }
1779    Rappture::Tooltip::for $itk_component(yCutButton) \
1780        "Toggle the Y cut plane on/off"
1781    $itk_component(yCutButton) select
1782
1783    itk_component add yCutScale {
1784        ::scale $inner.yval -from 100 -to 0 \
1785            -width 10 -orient vertical -showvalue off \
1786            -borderwidth 1 -highlightthickness 0 \
1787            -command [itcl::code $this Slice move y] \
1788            -variable [itcl::scope _settings(-ycutplaneposition)]
1789    } {
1790        usual
1791        ignore -borderwidth -highlightthickness
1792    }
1793    Rappture::Tooltip::for $itk_component(yCutScale) \
1794        "@[itcl::code $this SlicerTip y]"
1795    # Set the default cutplane value before disabling the scale.
1796    $itk_component(yCutScale) set 50
1797    $itk_component(yCutScale) configure -state disabled
1798
1799    # Z-value slicer...
1800    itk_component add zCutButton {
1801        Rappture::PushButton $inner.zbutton \
1802            -onimage [Rappture::icon z-cutplane] \
1803            -offimage [Rappture::icon z-cutplane] \
1804            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1805            -variable [itcl::scope _settings(-zcutplanevisible)]
1806    }
1807    Rappture::Tooltip::for $itk_component(zCutButton) \
1808        "Toggle the Z cut plane on/off"
1809    $itk_component(zCutButton) select
1810
1811    itk_component add zCutScale {
1812        ::scale $inner.zval -from 100 -to 0 \
1813            -width 10 -orient vertical -showvalue off \
1814            -borderwidth 1 -highlightthickness 0 \
1815            -command [itcl::code $this Slice move z] \
1816            -variable [itcl::scope _settings(-zcutplaneposition)]
1817    } {
1818        usual
1819        ignore -borderwidth -highlightthickness
1820    }
1821    $itk_component(zCutScale) set 50
1822    $itk_component(zCutScale) configure -state disabled
1823    Rappture::Tooltip::for $itk_component(zCutScale) \
1824        "@[itcl::code $this SlicerTip z]"
1825
1826    blt::table $inner \
1827        0,1 $inner.visible              -anchor w -pady 2 -cspan 4 \
1828        1,1 $itk_component(xCutScale) \
1829        1,2 $itk_component(yCutScale) \
1830        1,3 $itk_component(zCutScale) \
1831        2,1 $itk_component(xCutButton) \
1832        2,2 $itk_component(yCutButton) \
1833        2,3 $itk_component(zCutButton)
1834
1835    blt::table configure $inner r0 r1 r2 c* -resize none
1836    blt::table configure $inner r3 c4 -resize expand
1837    blt::table configure $inner c0 -width 2
1838    blt::table configure $inner c1 c2 c3 -padx 2
1839}
1840
1841itcl::body Rappture::NanovisViewer::BuildCameraTab {} {
1842    set inner [$itk_component(main) insert end \
1843        -title "Camera Settings" \
1844        -icon [Rappture::icon camera]]
1845    $inner configure -borderwidth 4
1846
1847    label $inner.view_l -text "view" -font "Arial 9"
1848    set f [frame $inner.view]
1849    foreach side { front back left right top bottom } {
1850        button $f.$side  -image [Rappture::icon view$side] \
1851            -command [itcl::code $this SetOrientation $side]
1852        Rappture::Tooltip::for $f.$side "Change the view to $side"
1853        pack $f.$side -side left
1854    }
1855
1856    blt::table $inner \
1857        0,0 $inner.view_l -anchor e -pady 2 \
1858        0,1 $inner.view -anchor w -pady 2
1859    blt::table configure $inner r0 -resize none
1860
1861    set row 1
1862    set labels { qw qx qy qz xpan ypan zoom }
1863    foreach tag $labels {
1864        label $inner.${tag}label -text $tag -font "Arial 9"
1865        entry $inner.${tag} -font "Arial 9"  -bg white \
1866            -textvariable [itcl::scope _settings(-$tag)]
1867        bind $inner.${tag} <Return> \
1868            [itcl::code $this camera set -${tag}]
1869        bind $inner.${tag} <KP_Enter> \
1870            [itcl::code $this camera set -${tag}]
1871        blt::table $inner \
1872            $row,0 $inner.${tag}label -anchor e -pady 2 \
1873            $row,1 $inner.${tag} -anchor w -pady 2
1874        blt::table configure $inner r$row -resize none
1875        incr row
1876    }
1877
1878    blt::table configure $inner c* -resize none
1879    blt::table configure $inner c2 -resize expand
1880    blt::table configure $inner r$row -resize expand
1881}
1882
1883# ----------------------------------------------------------------------
1884# USAGE: Slice move x|y|z <newval>
1885#
1886# Called automatically when the user drags the slider to move the
1887# cut plane that slices 3D data.  Gets the current value from the
1888# slider and moves the cut plane to the appropriate point in the
1889# data set.
1890# ----------------------------------------------------------------------
1891itcl::body Rappture::NanovisViewer::Slice {option args} {
1892    switch -- $option {
1893        move {
1894            if {[llength $args] != 2} {
1895                error "wrong # args: should be \"Slice move x|y|z newval\""
1896            }
1897            set axis [lindex $args 0]
1898            set newval [lindex $args 1]
1899
1900            set newpos [expr {0.01*$newval}]
1901            set datasets [CurrentDatasets -cutplanes]
1902            set tag [lindex $datasets 0]
1903            SendCmd "cutplane position $newpos $axis $tag"
1904        }
1905        default {
1906            error "bad option \"$option\": should be axis, move, or volume"
1907        }
1908    }
1909}
1910
1911# ----------------------------------------------------------------------
1912# USAGE: SlicerTip <axis>
1913#
1914# Used internally to generate a tooltip for the x/y/z slicer controls.
1915# Returns a message that includes the current slicer value.
1916# ----------------------------------------------------------------------
1917itcl::body Rappture::NanovisViewer::SlicerTip {axis} {
1918    set val [$itk_component(${axis}CutScale) get]
1919    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
1920}
1921
1922
1923itcl::body Rappture::NanovisViewer::DoResize {} {
1924    $_arcball resize $_width $_height
1925    SendCmd "screen size $_width $_height"
1926    set _resizePending 0
1927}
1928
1929itcl::body Rappture::NanovisViewer::EventuallyResize { w h } {
1930    set _width $w
1931    set _height $h
1932    $_arcball resize $w $h
1933    if { !$_resizePending } {
1934        $_dispatcher event -idle !resize
1935        set _resizePending 1
1936    }
1937}
1938
1939itcl::body Rappture::NanovisViewer::EventuallyRedrawLegend {} {
1940    if { !$_resizeLegendPending } {
1941        $_dispatcher event -idle !legend
1942        set _resizeLegendPending 1
1943    }
1944}
1945
1946#  camera --
1947#
1948itcl::body Rappture::NanovisViewer::camera {option args} {
1949    switch -- $option {
1950        "show" {
1951            puts [array get _view]
1952        }
1953        "set" {
1954            set what [lindex $args 0]
1955            set x $_settings($what)
1956            set code [catch { string is double $x } result]
1957            if { $code != 0 || !$result } {
1958                set _settings($what) $_view($what)
1959                return
1960            }
1961            switch -- $what {
1962                "-xpan" - "-ypan" {
1963                    set _view($what) $_settings($what)
1964                    PanCamera
1965                }
1966                "-qx" - "-qy" - "-qz" - "-qw" {
1967                    set _view($what) $_settings($what)
1968                    set q [ViewToQuaternion]
1969                    $_arcball quaternion $q
1970                    SendCmd "camera orient $q"
1971                }
1972                "-zoom" {
1973                    set _view($what) $_settings($what)
1974                    SendCmd "camera zoom $_view($what)"
1975                }
1976            }
1977        }
1978    }
1979}
1980
1981itcl::body Rappture::NanovisViewer::GetVolumeInfo { w } {
1982    set flowobj ""
1983    foreach key [array names _obj2flow] {
1984        set flowobj $_obj2flow($key)
1985        break
1986    }
1987    if { $flowobj == "" } {
1988        return
1989    }
1990    if { [winfo exists $w.frame] } {
1991        destroy $w.frame
1992    }
1993    set inner [frame $w.frame]
1994    blt::table $w \
1995        5,0 $inner -fill both -cspan 2 -anchor nw
1996    array set hints [$dataobj hints]
1997
1998    label $inner.volumes -text "Volumes" -font "Arial 9 bold"
1999    blt::table $inner \
2000        1,0 $inner.volumes  -anchor w \
2001    blt::table configure $inner c0 c1 -resize none
2002    blt::table configure $inner c2 -resize expand
2003
2004    set row 3
2005    set volumes [get]
2006    if { [llength $volumes] > 0 } {
2007        blt::table $inner $row,0 $inner.volumes  -anchor w
2008        incr row
2009    }
2010    foreach vol $volumes {
2011        array unset info
2012        array set info $vol
2013        set name $info(name)
2014        if { ![info exists _settings(-volumevisible-$name)] } {
2015            set _settings(-volumevisible-$name) $info(hide)
2016        }
2017        checkbutton $inner.vol$row -text $info(label) \
2018            -variable [itcl::scope _settings(-volumevisible-$name)] \
2019            -onvalue 0 -offvalue 1 \
2020            -command [itcl::code $this ToggleVolume $key $name] \
2021            -font "Arial 9"
2022        Rappture::Tooltip::for $inner.vol$row $info(description)
2023        blt::table $inner $row,0 $inner.vol$row -anchor w
2024        if { !$_settings(-volume-$name) } {
2025            $inner.vol$row select
2026        }
2027        incr row
2028    }
2029    blt::table configure $inner r* -resize none
2030    blt::table configure $inner r$row -resize expand
2031    blt::table configure $inner c3 -resize expand
2032    event generate [winfo parent [winfo parent $w]] <Configure>
2033}
2034
2035itcl::body Rappture::NanovisViewer::ToggleVolume { tag name } {
2036    set bool $_settings(-volumevisible-$name)
2037    SendCmd "volume state $bool $name"
2038}
2039
2040itcl::body Rappture::NanovisViewer::SetOrientation { side } {
2041    array set positions {
2042        front "1 0 0 0"
2043        back  "0 0 1 0"
2044        left  "0.707107 0 -0.707107 0"
2045        right "0.707107 0 0.707107 0"
2046        top   "0.707107 -0.707107 0 0"
2047        bottom "0.707107 0.707107 0 0"
2048    }
2049    foreach name { -qw -qx -qy -qz } value $positions($side) {
2050        set _view($name) $value
2051    }
2052    set q [ViewToQuaternion]
2053    $_arcball quaternion $q
2054    SendCmd "camera orient $q"
2055    SendCmd "camera reset"
2056    set _view(-xpan) 0
2057    set _view(-ypan) 0
2058    set _view(-zoom) 1.0
2059    set _settings(-xpan) $_view(-xpan)
2060    set _settings(-ypan) $_view(-ypan)
2061    set _settings(-zoom) $_view(-zoom)
2062}
2063
2064
2065#
2066# InitComponentSettings --
2067#
2068#    Initializes the volume settings for a specific component. This should
2069#    match what's used as global settings above. This is called the first
2070#    time we try to switch to a given component in SwitchComponent below.
2071#
2072itcl::body Rappture::NanovisViewer::InitComponentSettings { cname } {
2073    foreach {key value} {
2074        -colormap          "default"
2075        -light             40
2076        -light2side        1
2077        -thickness         350
2078        -volumeopacity     1.0
2079        -volumevisible     1
2080    } {
2081        if { ![info exists _settings($cname${key})] } {
2082            # Don't override existing component settings
2083            set _settings($cname${key}) $value
2084        }
2085    }
2086}
2087
2088#
2089# SwitchComponent --
2090#
2091#    This is called when the current component is changed by the dropdown
2092#    menu in the volume tab.  It synchronizes the global volume settings
2093#    with the settings of the new current component.
2094#
2095itcl::body Rappture::NanovisViewer::SwitchComponent { cname } {
2096    if { ![info exists _settings($cname-light)] } {
2097        InitComponentSettings $cname
2098    }
2099    if { $_settings(-colormap) != $_settings($cname-colormap) } {
2100        set _settings(-colormap)         $_settings($cname-colormap)
2101        EventuallyRedrawLegend
2102    }
2103    # _settings variables change widgets, except for colormap
2104    set _settings(-light)            $_settings($cname-light)
2105    set _settings(-light2side)       $_settings($cname-light2side)
2106    set _settings(-volumeopacity)    $_settings($cname-volumeopacity)
2107    set _settings(-thickness)        $_settings($cname-thickness)
2108    set _settings(-volumevisible)    $_settings($cname-volumevisible)
2109    $itk_component(colormap) value   $_settings($cname-colormap)
2110
2111    set _widget(-volumeopacity) [expr $_settings(-volumeopacity) * 100.0]
2112
2113    set _current $cname;                # Reset the current component
2114}
2115
2116#
2117# BuildVolumeComponents --
2118#
2119#    This is called from the "scale" method which is called when a new
2120#    dataset is added or deleted.  It repopulates the dropdown menu of
2121#    volume component names.  It sets the current component to the first
2122#    component in the list (of components found).  Finally, if there is
2123#    only one component, don't display the label or the combobox in the
2124#    volume settings tab.
2125#
2126itcl::body Rappture::NanovisViewer::BuildVolumeComponents {} {
2127    $itk_component(volcomponents) choices delete 0 end
2128    foreach name $_componentsList {
2129        $itk_component(volcomponents) choices insert end $name $name
2130    }
2131    set _current [lindex $_componentsList 0]
2132    $itk_component(volcomponents) value $_current
2133    set parent [winfo parent $itk_component(volcomponents)]
2134    if { [llength $_componentsList] <= 1 } {
2135        # Unpack the components label and dropdown if there's only one
2136        # component.
2137        blt::table forget $parent.volcomponents_l $parent.volcomponents
2138    } else {
2139        # Pack the components label and dropdown into the table there's
2140        # more than one component to select.
2141        blt::table $parent \
2142            0,0 $parent.volcomponents_l -anchor e -cspan 2 \
2143            0,2 $parent.volcomponents -cspan 3 -fill x
2144    }
2145}
2146
2147#
2148# GetDatasetsWithComponents --
2149#
2150#    Returns a list of all the datasets (known by the combination of their
2151#    data object and component name) that match the given component name.
2152#    For example, this is used where we want to change the settings of
2153#    volumes that have the current component.
2154#
2155itcl::body Rappture::NanovisViewer::GetDatasetsWithComponent { cname } {
2156    if { ![info exists _volcomponents($cname)] } {
2157        return ""
2158    }
2159    set list ""
2160    foreach tag $_volcomponents($cname) {
2161        if { ![info exists _serverDatasets($tag)] } {
2162            continue
2163        }
2164        lappend list $tag
2165    }
2166    return $list
2167}
2168
2169#
2170# HideAllMarkers --
2171#
2172#    Hide all the markers in all the transfer functions.  Can't simply
2173#    delete and recreate markers from the <style> since the user may have
2174#    created, deleted, or moved markers.
2175#
2176itcl::body Rappture::NanovisViewer::HideAllMarkers {} {
2177    foreach cname [array names _transferFunctionEditors] {
2178        $_transferFunctionEditors($cname) hideMarkers
2179    }
2180}
2181
2182itcl::body Rappture::NanovisViewer::GetColormap { cname color } {
2183    if { $color == "default" } {
2184        return $_cname2defaultcolormap($cname)
2185    }
2186    return [ColorsToColormap $color]
2187}
2188
2189itcl::body Rappture::NanovisViewer::ResetColormap { cname color } {
2190    # Get the current transfer function
2191    if { ![info exists _cname2transferFunction($cname)] } {
2192        return
2193    }
2194    foreach { cmap amap } $_cname2transferFunction($cname) break
2195    set cmap [GetColormap $cname $color]
2196    set _cname2transferFunction($cname) [list $cmap $amap]
2197    SendCmd [list transfunc define $cname $cmap $amap]
2198    EventuallyRedrawLegend
2199}
2200
2201itcl::body Rappture::NanovisViewer::ComputeAlphamap { cname } {
2202    if { ![info exists _transferFunctionEditors($cname)] } {
2203        return [list 0.0 0.0 1.0 1.0]
2204    }
2205    if { ![info exists _settings($cname-light)] } {
2206        InitComponentSettings $cname
2207    }
2208
2209    set isovalues [$_transferFunctionEditors($cname) values]
2210
2211    # Transfer function should be normalized with [0,1] range
2212    # The volume shading opacity setting is used to scale opacity
2213    # in the volume shader.
2214    set max 1.0
2215
2216    # Use the component-wise thickness setting from the slider
2217    # settings widget
2218    # Scale values between 0.00001 and 0.01000
2219    set delta [expr {double($_settings($cname-thickness)) * 0.0001}]
2220
2221    set first [lindex $isovalues 0]
2222    set last [lindex $isovalues end]
2223    set amap ""
2224    if { $first == "" || $first != 0.0 } {
2225        lappend amap 0.0 0.0
2226    }
2227    foreach x $isovalues {
2228        set x1 [expr {$x-$delta-0.00001}]
2229        set x2 [expr {$x-$delta}]
2230        set x3 [expr {$x+$delta}]
2231        set x4 [expr {$x+$delta+0.00001}]
2232        if { $x1 < 0.0 } {
2233            set x1 0.0
2234        } elseif { $x1 > 1.0 } {
2235            set x1 1.0
2236        }
2237        if { $x2 < 0.0 } {
2238            set x2 0.0
2239        } elseif { $x2 > 1.0 } {
2240            set x2 1.0
2241        }
2242        if { $x3 < 0.0 } {
2243            set x3 0.0
2244        } elseif { $x3 > 1.0 } {
2245            set x3 1.0
2246        }
2247        if { $x4 < 0.0 } {
2248            set x4 0.0
2249        } elseif { $x4 > 1.0 } {
2250            set x4 1.0
2251        }
2252        # add spikes in the middle
2253        lappend amap $x1 0.0
2254        lappend amap $x2 $max
2255        lappend amap $x3 $max
2256        lappend amap $x4 0.0
2257    }
2258    if { $last == "" || $last != 1.0 } {
2259        lappend amap 1.0 0.0
2260    }
2261    return $amap
2262}
2263
2264itcl::body Rappture::NanovisViewer::SetObjectStyle { dataobj cname } {
2265    array set style {
2266        -opacity  0.5
2267    }
2268    array set style [lindex [$dataobj components -style $cname] 0]
2269    # Some tools erroneously set -opacity to 1 in style, so
2270    # override the requested opacity for now
2271    set style(-opacity) 0.5
2272    set _settings($cname-volumeopacity) $style(-opacity)
2273    set tag $dataobj-$cname
2274    SendCmd "volume shading opacity $_settings($cname-volumeopacity) $tag"
2275    NameTransferFunction $dataobj $cname
2276}
Note: See TracBrowser for help on using the repository browser.