source: branches/1.3/gui/scripts/nanovisviewer.tcl @ 5565

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

Merge r5526:5527 from trunk (vtk download for flow/nanovis viewers)

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