source: trunk/gui/scripts/nanovisviewer.tcl @ 3498

Last change on this file since 3498 was 3498, checked in by ldelgass, 12 years ago

Delay Rebuild until window size larger than 1x1 - copying this code from
VTK viewers to nanovis viewers. Helps get proper aspect for initial camera
reset. There is still a problem with the updir coming too late (needs to come
before camera reset).

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