source: branches/1.6/gui/scripts/nanovisviewer.tcl @ 6309

Last change on this file since 6309 was 6309, checked in by gah, 8 years ago

fixes -load causing simulation

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