source: branches/1.6/gui/scripts/vtkvolumeviewer.tcl @ 6155

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

merge viewer cleanups from trunk

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