source: branches/1.4/gui/scripts/vtkvolumeviewer.tcl @ 5733

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

Merge in vtkvolume viewer updates from trunk

File size: 82.8 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-2015  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 { hostlist args } {
43        Rappture::VisViewer::constructor $hostlist
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 EventuallyResize { w h }
84    private method EventuallyRequestLegend {}
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 {hostlist 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 no
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        set location [$_first hints camera]
1038        if { $location != "" } {
1039            array set view $location
1040        }
1041
1042        foreach axis { x y z } {
1043            set label [$_first hints ${axis}label]
1044            if { $label != "" } {
1045                SendCmd [list axis name $axis $label]
1046            }
1047            set units [$_first hints ${axis}units]
1048            if { $units != "" } {
1049                SendCmd [list axis units $axis $units]
1050            }
1051        }
1052        $itk_component(field) choices delete 0 end
1053        $itk_component(fieldmenu) delete 0 end
1054        array unset _fields
1055        set _curFldName ""
1056        foreach cname [$_first components] {
1057            foreach fname [$_first fieldnames $cname] {
1058                if { [info exists _fields($fname)] } {
1059                    continue
1060                }
1061                foreach { label units components } \
1062                    [$_first fieldinfo $fname] break
1063                # Only scalar fields are valid
1064                if {$_allowMultiComponent || $components == 1} {
1065                    $itk_component(field) choices insert end "$fname" "$label"
1066                    $itk_component(fieldmenu) add radiobutton -label "$label" \
1067                        -value $label -variable [itcl::scope _curFldLabel] \
1068                        -selectcolor red \
1069                        -activebackground $itk_option(-plotbackground) \
1070                        -activeforeground $itk_option(-plotforeground) \
1071                        -font "Arial 8" \
1072                        -command [itcl::code $this Combo invoke]
1073                    set _fields($fname) [list $label $units $components]
1074                    if { $_curFldName == "" } {
1075                        set _curFldName $fname
1076                        set _curFldLabel $label
1077                    }
1078                }
1079            }
1080        }
1081        $itk_component(field) value $_curFldLabel
1082    }
1083
1084    InitSettings -color \
1085        -volumevisible \
1086        -volumematerial \
1087        -volumelighting -volumeopacity -volumequality -volumeoutline \
1088        -cutplanesvisible \
1089        -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1090        -xcutplanevisible -ycutplanevisible -zcutplanevisible
1091
1092    if { $_reset } {
1093        SendCmd "camera reset"
1094        SendCmd "camera zoom $_view(-zoom)"
1095        RequestLegend
1096        set _reset 0
1097    }
1098    # Actually write the commands to the server socket.  If it fails, we don't
1099    # care.  We're finished here.
1100    blt::busy hold $itk_component(hull)
1101    StopBufferingCommands
1102    blt::busy release $itk_component(hull)
1103}
1104
1105# ----------------------------------------------------------------------
1106# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1107#
1108# Returns a list of server IDs for the current datasets being displayed.  This
1109# is normally a single ID, but it might be a list of IDs if the current data
1110# object has multiple components.
1111# ----------------------------------------------------------------------
1112itcl::body Rappture::VtkVolumeViewer::CurrentDatasets {args} {
1113    set flag [lindex $args 0]
1114    switch -- $flag {
1115        "-all" {
1116            if { [llength $args] > 1 } {
1117                error "CurrentDatasets: can't specify dataobj after \"-all\""
1118            }
1119            set dlist [get -objects]
1120        }
1121        "-visible" {
1122            if { [llength $args] > 1 } {
1123                set dlist {}
1124                set args [lrange $args 1 end]
1125                foreach dataobj $args {
1126                    if { [info exists _obj2ovride($dataobj-raise)] } {
1127                        lappend dlist $dataobj
1128                    }
1129                }
1130            } else {
1131                set dlist [get -visible]
1132            }
1133        }
1134        default {
1135            set dlist $args
1136        }
1137    }
1138    set rlist ""
1139    foreach dataobj $dlist {
1140        foreach comp [$dataobj components] {
1141            set tag $dataobj-$comp
1142            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1143                lappend rlist $tag
1144            }
1145        }
1146    }
1147    return $rlist
1148}
1149
1150# ----------------------------------------------------------------------
1151# USAGE: Zoom in
1152# USAGE: Zoom out
1153# USAGE: Zoom reset
1154#
1155# Called automatically when the user clicks on one of the zoom
1156# controls for this widget.  Changes the zoom for the current view.
1157# ----------------------------------------------------------------------
1158itcl::body Rappture::VtkVolumeViewer::Zoom {option} {
1159    switch -- $option {
1160        "in" {
1161            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1162            SendCmd "camera zoom $_view(-zoom)"
1163        }
1164        "out" {
1165            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1166            SendCmd "camera zoom $_view(-zoom)"
1167        }
1168        "reset" {
1169            array set _view {
1170                -qw      0.853553
1171                -qx      -0.353553
1172                -qy      0.353553
1173                -qz      0.146447
1174                -xpan    0
1175                -ypan    0
1176                -zoom    1.0
1177            }
1178            if { $_first != "" } {
1179                set location [$_first hints camera]
1180                if { $location != "" } {
1181                    array set _view $location
1182                }
1183            }
1184            $_arcball quaternion [ViewToQuaternion]
1185            DoRotate
1186            SendCmd "camera reset"
1187        }
1188    }
1189}
1190
1191itcl::body Rappture::VtkVolumeViewer::PanCamera {} {
1192    set x $_view(-xpan)
1193    set y $_view(-ypan)
1194    SendCmd "camera pan $x $y"
1195}
1196
1197# ----------------------------------------------------------------------
1198# USAGE: Rotate click <x> <y>
1199# USAGE: Rotate drag <x> <y>
1200# USAGE: Rotate release <x> <y>
1201#
1202# Called automatically when the user clicks/drags/releases in the
1203# plot area.  Moves the plot according to the user's actions.
1204# ----------------------------------------------------------------------
1205itcl::body Rappture::VtkVolumeViewer::Rotate {option x y} {
1206    switch -- $option {
1207        "click" {
1208            $itk_component(view) configure -cursor fleur
1209            set _click(x) $x
1210            set _click(y) $y
1211        }
1212        "drag" {
1213            if {[array size _click] == 0} {
1214                Rotate click $x $y
1215            } else {
1216                set w [winfo width $itk_component(view)]
1217                set h [winfo height $itk_component(view)]
1218                if {$w <= 0 || $h <= 0} {
1219                    return
1220                }
1221
1222                if {[catch {
1223                    # this fails sometimes for no apparent reason
1224                    set dx [expr {double($x-$_click(x))/$w}]
1225                    set dy [expr {double($y-$_click(y))/$h}]
1226                }]} {
1227                    return
1228                }
1229                if { $dx == 0 && $dy == 0 } {
1230                    return
1231                }
1232                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1233                EventuallyRotate $q
1234                set _click(x) $x
1235                set _click(y) $y
1236            }
1237        }
1238        "release" {
1239            Rotate drag $x $y
1240            $itk_component(view) configure -cursor ""
1241            catch {unset _click}
1242        }
1243        default {
1244            error "bad option \"$option\": should be click, drag, release"
1245        }
1246    }
1247}
1248
1249itcl::body Rappture::VtkVolumeViewer::Pick {x y} {
1250    foreach tag [CurrentDatasets -visible] {
1251        SendCmd "dataset getscalar pixel $x $y $tag"
1252    }
1253}
1254
1255# ----------------------------------------------------------------------
1256# USAGE: $this Pan click x y
1257#        $this Pan drag x y
1258#        $this Pan release x y
1259#
1260# Called automatically when the user clicks on one of the zoom
1261# controls for this widget.  Changes the zoom for the current view.
1262# ----------------------------------------------------------------------
1263itcl::body Rappture::VtkVolumeViewer::Pan {option x y} {
1264    switch -- $option {
1265        "set" {
1266            set w [winfo width $itk_component(view)]
1267            set h [winfo height $itk_component(view)]
1268            set x [expr $x / double($w)]
1269            set y [expr $y / double($h)]
1270            set _view(-xpan) [expr $_view(-xpan) + $x]
1271            set _view(-ypan) [expr $_view(-ypan) + $y]
1272            PanCamera
1273            return
1274        }
1275        "click" {
1276            set _click(x) $x
1277            set _click(y) $y
1278            $itk_component(view) configure -cursor hand1
1279        }
1280        "drag" {
1281            if { ![info exists _click(x)] } {
1282                set _click(x) $x
1283            }
1284            if { ![info exists _click(y)] } {
1285                set _click(y) $y
1286            }
1287            set w [winfo width $itk_component(view)]
1288            set h [winfo height $itk_component(view)]
1289            set dx [expr ($_click(x) - $x)/double($w)]
1290            set dy [expr ($_click(y) - $y)/double($h)]
1291            set _click(x) $x
1292            set _click(y) $y
1293            set _view(-xpan) [expr $_view(-xpan) - $dx]
1294            set _view(-ypan) [expr $_view(-ypan) - $dy]
1295            PanCamera
1296        }
1297        "release" {
1298            Pan drag $x $y
1299            $itk_component(view) configure -cursor ""
1300        }
1301        default {
1302            error "unknown option \"$option\": should set, click, drag, or release"
1303        }
1304    }
1305}
1306
1307# ----------------------------------------------------------------------
1308# USAGE: InitSettings <what> ?<value>?
1309#
1310# Used internally to update rendering settings whenever parameters
1311# change in the popup settings panel.  Sends the new settings off
1312# to the back end.
1313# ----------------------------------------------------------------------
1314itcl::body Rappture::VtkVolumeViewer::InitSettings { args } {
1315    foreach spec $args {
1316        if { [info exists _settings($_first${spec})] } {
1317            # Reset global setting with dataobj specific setting
1318            set _settings($spec) $_settings($_first${spec})
1319        }
1320        AdjustSetting $spec
1321    }
1322}
1323
1324#
1325# AdjustSetting --
1326#
1327# Changes/updates a specific setting in the widget.  There are
1328# usually user-setable option.  Commands are sent to the render
1329# server.
1330#
1331itcl::body Rappture::VtkVolumeViewer::AdjustSetting {what {value ""}} {
1332    if { ![isconnected] } {
1333        return
1334    }
1335    switch -- $what {
1336        "-background" {
1337            set bgcolor [$itk_component(background) value]
1338            set _settings($what) $bgcolor
1339            array set fgcolors {
1340                "black" "white"
1341                "white" "black"
1342                "grey"  "black"
1343            }
1344            configure -plotbackground $bgcolor \
1345                -plotforeground $fgcolors($bgcolor)
1346            $itk_component(view) delete "legend"
1347            DrawLegend
1348        }
1349        "-volumeoutline" {
1350            set bool $_settings($what)
1351            SendCmd "outline visible 0"
1352            foreach tag [CurrentDatasets -visible] {
1353                SendCmd "outline visible $bool $tag"
1354            }
1355        }
1356        "-legendvisible" {
1357            DrawLegend
1358        }
1359        "-volumevisible" {
1360            set bool $_settings($what)
1361            foreach tag [CurrentDatasets -visible] {
1362                SendCmd "volume visible $bool $tag"
1363            }
1364            if { $bool } {
1365                Rappture::Tooltip::for $itk_component(volume) \
1366                    "Hide the volume"
1367            } else {
1368                Rappture::Tooltip::for $itk_component(volume) \
1369                    "Show the volume"
1370            }
1371        }
1372        "-volumematerial" {
1373            set val $_settings($what)
1374            set diffuse [expr {0.01*$val}]
1375            set specular [expr {0.01*$val}]
1376            #set power [expr {sqrt(160*$val+1.0)}]
1377            set power [expr {$val+1.0}]
1378            foreach tag [CurrentDatasets -visible] {
1379                SendCmd "volume shading diffuse $diffuse $tag"
1380                SendCmd "volume shading specular $specular $power $tag"
1381            }
1382        }
1383        "-volumelighting" {
1384            set bool $_settings($what)
1385            foreach tag [CurrentDatasets -visible] {
1386                SendCmd "volume lighting $bool $tag"
1387            }
1388        }
1389        "-volumeopacity" {
1390            set val $_settings($what)
1391            set val [expr {0.01*$val}]
1392            foreach tag [CurrentDatasets -visible] {
1393                SendCmd "volume opacity $val $tag"
1394            }
1395        }
1396        "-volumequality" {
1397            set val $_settings($what)
1398            set val [expr {0.01*$val}]
1399            foreach tag [CurrentDatasets -visible] {
1400                SendCmd "volume quality $val $tag"
1401            }
1402        }
1403        "-axesvisible" {
1404            set bool $_settings($what)
1405            SendCmd "axis visible all $bool"
1406        }
1407        "-axislabels" {
1408            set bool $_settings($what)
1409            SendCmd "axis labels all $bool"
1410        }
1411        "-axisminorticks" {
1412            set bool $_settings($what)
1413            SendCmd "axis minticks all $bool"
1414        }
1415        "-xgrid" - "-ygrid" - "-zgrid" {
1416            set axis [string range $what 1 1]
1417            set bool $_settings($what)
1418            SendCmd "axis grid $axis $bool"
1419        }
1420        "-axisflymode" {
1421            set mode [$itk_component(axismode) value]
1422            set mode [$itk_component(axismode) translate $mode]
1423            set _settings($what) $mode
1424            SendCmd "axis flymode $mode"
1425        }
1426        "-cutplanesvisible" {
1427            set bool $_settings($what)
1428            foreach dataset [CurrentDatasets -visible] {
1429                SendCmd "$_cutplaneCmd visible $bool $dataset"
1430            }
1431        }
1432        "-cutplanelighting" {
1433            set bool $_settings($what)
1434            foreach dataset [CurrentDatasets -visible] {
1435                if {$_cutplaneCmd != "imgcutplane"} {
1436                    SendCmd "$_cutplaneCmd lighting $bool $dataset"
1437                } else {
1438                    if {$bool} {
1439                        set ambient 0.0
1440                        set diffuse 1.0
1441                    } else {
1442                        set ambient 1.0
1443                        set diffuse 0.0
1444                    }
1445                    SendCmd "imgcutplane material $ambient $diffuse $dataset"
1446                }
1447            }
1448        }
1449        "-cutplaneopacity" {
1450            set val $_settings($what)
1451            set sval [expr { 0.01 * double($val) }]
1452            foreach dataset [CurrentDatasets -visible] {
1453                SendCmd "$_cutplaneCmd opacity $sval $dataset"
1454            }
1455        }
1456        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1457            set axis [string range $what 1 1]
1458            set bool $_settings($what)
1459            if { $bool } {
1460                $itk_component(${axis}CutScale) configure -state normal \
1461                    -troughcolor white
1462            } else {
1463                $itk_component(${axis}CutScale) configure -state disabled \
1464                    -troughcolor grey82
1465            }
1466            foreach dataset [CurrentDatasets -visible] {
1467                SendCmd "$_cutplaneCmd axis $axis $bool $dataset"
1468            }
1469        }
1470        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1471            set axis [string range $what 1 1]
1472            set pos [expr $_settings($what) * 0.01]
1473            foreach dataset [CurrentDatasets -visible] {
1474                SendCmd "$_cutplaneCmd slice ${axis} ${pos} $dataset"
1475            }
1476            set _cutplanePending 0
1477        }
1478        "-color" {
1479            set color [$itk_component(colormap) value]
1480            set _settings($what) $color
1481            foreach dataset [CurrentDatasets -visible $_first] {
1482                foreach {dataobj comp} [split $dataset -] break
1483                ChangeColormap $dataobj $comp $color
1484            }
1485            EventuallyRequestLegend
1486        }
1487        "-field" {
1488            set label [$itk_component(field) value]
1489            set fname [$itk_component(field) translate $label]
1490            set _settings($what) $fname
1491            if { [info exists _fields($fname)] } {
1492                foreach { label units components } $_fields($fname) break
1493                if { !$_allowMultiComponent && $components > 1 } {
1494                    puts stderr "Can't use a vector field in a volume"
1495                    return
1496                } else {
1497                    if { $components > 1 } {
1498                        set _colorMode vmag
1499                    } else {
1500                        set _colorMode scalar
1501                    }
1502                }
1503                set _curFldName $fname
1504                set _curFldLabel $label
1505            } else {
1506                puts stderr "unknown field \"$fname\""
1507                return
1508            }
1509            foreach dataset [CurrentDatasets -visible $_first] {
1510                #SendCmd "$_cutplaneCmd colormode $_colorMode $_curFldName $dataset"
1511                SendCmd "dataset scalar $_curFldName $dataset"
1512            }
1513            SendCmd "camera reset"
1514            DrawLegend
1515        }
1516        default {
1517            error "don't know how to fix $what"
1518        }
1519    }
1520}
1521
1522#
1523# RequestLegend --
1524#
1525# Request a new legend from the server.  The size of the legend
1526# is determined from the height of the canvas.
1527#
1528itcl::body Rappture::VtkVolumeViewer::RequestLegend {} {
1529    set _legendPending 0
1530    set font "Arial 8"
1531    set lineht [font metrics $font -linespace]
1532    set w 12
1533    set h [expr {$_height - 3 * ($lineht + 2)}]
1534    if { $h < 1 } {
1535        return
1536    }
1537    # Set the legend on the first volume dataset.
1538    foreach dataset [CurrentDatasets -visible $_first] {
1539        foreach {dataobj comp} [split $dataset -] break
1540        if { [info exists _dataset2style($dataset)] } {
1541            #SendCmd "legend $_dataset2style($dataset) $_colorMode $_curFldName {} $w $h 0"
1542            SendCmd "legend2 $_dataset2style($dataset) $w $h"
1543            break;
1544        }
1545    }
1546}
1547
1548#
1549# ChangeColormap --
1550#
1551itcl::body Rappture::VtkVolumeViewer::ChangeColormap {dataobj comp color} {
1552    set tag $dataobj-$comp
1553    if { ![info exist _style($tag)] } {
1554        error "no initial colormap"
1555    }
1556    array set style $_style($tag)
1557    set style(-color) $color
1558    set _style($tag) [array get style]
1559    SetColormap $dataobj $comp
1560}
1561
1562#
1563# SetColormap --
1564#
1565itcl::body Rappture::VtkVolumeViewer::SetColormap { dataobj comp } {
1566    array set style {
1567        -color BCGYR
1568        -levels 6
1569    }
1570    set tag $dataobj-$comp
1571    if { ![info exists _initialStyle($tag)] } {
1572        # Save the initial component style.
1573        set _initialStyle($tag) [$dataobj style $comp]
1574    }
1575
1576    # Override defaults with initial style defined in xml.
1577    array set style $_initialStyle($tag)
1578
1579    if { ![info exists _style($tag)] } {
1580        set _style($tag) [array get style]
1581    }
1582    # Override initial style with current style.
1583    array set style $_style($tag)
1584
1585    set name "$style(-color):$style(-levels)"
1586    if { ![info exists _colormaps($name)] } {
1587        BuildColormap $name [array get style]
1588        set _colormaps($name) 1
1589    }
1590    if { ![info exists _dataset2style($tag)] ||
1591         $_dataset2style($tag) != $name } {
1592        SendCmd "volume colormap $name $tag"
1593        SendCmd "$_cutplaneCmd colormap $name-opaque $tag"
1594        set _dataset2style($tag) $name
1595    }
1596}
1597
1598#
1599# BuildColormap --
1600#
1601# Alpha map is in the format: normalized_value opacity midpoint sharpness
1602#
1603itcl::body Rappture::VtkVolumeViewer::BuildColormap { name styles } {
1604    array set style $styles
1605    set cmap [ColorsToColormap $style(-color)]
1606    if { [llength $cmap] == 0 } {
1607        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1608    }
1609
1610    set amap "0.0 0.0 0.5 0.0 1.0 1.0 0.5 0.0"
1611    set opaqueAmap "0.0 1.0 1.0 1.0"
1612    SendCmd [list colormap define $name $cmap -spline $amap]
1613    SendCmd [list colormap define $name-opaque $cmap $opaqueAmap]
1614}
1615
1616# ----------------------------------------------------------------------
1617# CONFIGURATION OPTION: -plotbackground
1618# ----------------------------------------------------------------------
1619itcl::configbody Rappture::VtkVolumeViewer::plotbackground {
1620    if { [isconnected] } {
1621        set color $itk_option(-plotbackground)
1622        set rgb [Color2RGB $color]
1623        SendCmd "screen bgcolor $rgb"
1624        $itk_component(legend) configure -background $color
1625    }
1626}
1627
1628# ----------------------------------------------------------------------
1629# CONFIGURATION OPTION: -plotforeground
1630# ----------------------------------------------------------------------
1631itcl::configbody Rappture::VtkVolumeViewer::plotforeground {
1632    if { [isconnected] } {
1633        set color $itk_option(-plotforeground)
1634        set rgb [Color2RGB $color]
1635        SendCmd "axis color all $rgb"
1636        SendCmd "outline color $rgb"
1637        SendCmd "$_cutplaneCmd color $rgb"
1638        $itk_component(legend) itemconfigure labels -fill $color
1639        $itk_component(legend) itemconfigure limits -fill $color
1640    }
1641}
1642
1643itcl::body Rappture::VtkVolumeViewer::BuildViewTab {} {
1644    set font [option get $itk_component(hull) font Font]
1645
1646    set inner [$itk_component(main) insert end \
1647        -title "View Settings" \
1648        -icon [Rappture::icon wrench]]
1649    $inner configure -borderwidth 4
1650
1651    checkbutton $inner.axes \
1652        -text "Axes" \
1653        -variable [itcl::scope _settings(-axesvisible)] \
1654        -command [itcl::code $this AdjustSetting -axesvisible] \
1655        -font $font
1656
1657    checkbutton $inner.outline \
1658        -text "Outline" \
1659        -variable [itcl::scope _settings(-volumeoutline)] \
1660        -command [itcl::code $this AdjustSetting -volumeoutline] \
1661        -font $font
1662
1663    checkbutton $inner.legend \
1664        -text "Legend" \
1665        -variable [itcl::scope _settings(-legendvisible)] \
1666        -command [itcl::code $this AdjustSetting -legendvisible] \
1667        -font $font
1668
1669    checkbutton $inner.volume \
1670        -text "Volume" \
1671        -variable [itcl::scope _settings(-volumevisible)] \
1672        -command [itcl::code $this AdjustSetting -volumevisible] \
1673        -font $font
1674
1675    label $inner.background_l -text "Background" -font $font
1676    itk_component add background {
1677        Rappture::Combobox $inner.background -width 10 -editable no
1678    }
1679    $inner.background choices insert end \
1680        "black" "black" \
1681        "white" "white" \
1682        "grey"  "grey"
1683
1684    $itk_component(background) value $_settings(-background)
1685    bind $inner.background <<Value>> \
1686        [itcl::code $this AdjustSetting -background]
1687
1688    blt::table $inner \
1689        0,0 $inner.axes -cspan 2 -anchor w \
1690        1,0 $inner.outline -cspan 2 -anchor w \
1691        2,0 $inner.volume -cspan 2 -anchor w \
1692        3,0 $inner.legend -cspan 2 -anchor w \
1693        4,0 $inner.background_l -anchor e -pady 2 \
1694        4,1 $inner.background -fill x
1695
1696    blt::table configure $inner r* -resize none
1697    blt::table configure $inner r5 -resize expand
1698}
1699
1700itcl::body Rappture::VtkVolumeViewer::BuildVolumeTab {} {
1701    set font [option get $itk_component(hull) font Font]
1702    #set bfont [option get $itk_component(hull) boldFont Font]
1703    set bfont "Arial 9 bold"
1704
1705    set inner [$itk_component(main) insert end \
1706        -title "Volume Settings" \
1707        -icon [Rappture::icon volume-on]]
1708    $inner configure -borderwidth 4
1709
1710    checkbutton $inner.visibility \
1711        -text "Visible" \
1712        -font $font \
1713        -variable [itcl::scope _settings(-volumevisible)] \
1714        -command [itcl::code $this AdjustSetting -volumevisible]
1715
1716    checkbutton $inner.lighting \
1717        -text "Enable Lighting" \
1718        -font $font \
1719        -variable [itcl::scope _settings(-volumelighting)] \
1720        -command [itcl::code $this AdjustSetting -volumelighting]
1721
1722    label $inner.dim_l -text "Dim" -font $font
1723    ::scale $inner.material -from 0 -to 100 -orient horizontal \
1724        -variable [itcl::scope _settings(-volumematerial)] \
1725        -showvalue off \
1726        -command [itcl::code $this AdjustSetting -volumematerial]
1727    label $inner.bright_l -text "Bright" -font $font
1728
1729    label $inner.opacity_l -text "Opacity" -font $font
1730    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1731        -variable [itcl::scope _settings(-volumeopacity)] \
1732        -showvalue off \
1733        -command [itcl::code $this AdjustSetting -volumeopacity]
1734
1735    label $inner.quality_l -text "Quality" -font $font
1736    ::scale $inner.quality -from 0 -to 100 -orient horizontal \
1737        -variable [itcl::scope _settings(-volumequality)] \
1738        -showvalue off \
1739        -command [itcl::code $this AdjustSetting -volumequality]
1740
1741    label $inner.field_l -text "Field" -font $font
1742    itk_component add field {
1743        Rappture::Combobox $inner.field -editable no
1744    }
1745    bind $inner.field <<Value>> \
1746        [itcl::code $this AdjustSetting -field]
1747
1748    label $inner.colormap_l -text "Colormap" -font $font
1749    itk_component add colormap {
1750        Rappture::Combobox $inner.colormap -editable no
1751    }
1752    $inner.colormap choices insert end [GetColormapList]
1753    bind $inner.colormap <<Value>> \
1754        [itcl::code $this AdjustSetting -color]
1755    $itk_component(colormap) value $_settings(-color)
1756
1757    blt::table $inner \
1758        0,0 $inner.field_l -anchor w -pady 2 \
1759        0,1 $inner.field -fill x -pady 2 -cspan 3 \
1760        1,0 $inner.visibility -anchor w -pady 2 -cspan 4 \
1761        2,0 $inner.lighting -anchor w -pady 2 -cspan 4 \
1762        3,0 $inner.dim_l -anchor e -pady 2 \
1763        3,1 $inner.material -fill x -pady 2 -cspan 2 \
1764        3,3 $inner.bright_l -anchor w -pady 2 \
1765        4,0 $inner.opacity_l -anchor w -pady 2 -cspan 4 \
1766        5,0 $inner.opacity -fill x -pady 2 -cspan 4 \
1767        6,0 $inner.quality_l -anchor w -pady 2 -cspan 4 \
1768        7,0 $inner.quality -fill x -pady 2 -cspan 4 \
1769        8,0 $inner.colormap_l -anchor w -pady 2 \
1770        8,1 $inner.colormap -fill x -pady 2 -cspan 3
1771
1772    blt::table configure $inner r* c0 c1 c3 -resize none
1773    blt::table configure $inner r9 c2 -resize expand
1774}
1775
1776itcl::body Rappture::VtkVolumeViewer::BuildAxisTab {} {
1777    set font [option get $itk_component(hull) font Font]
1778
1779    set inner [$itk_component(main) insert end \
1780        -title "Axis Settings" \
1781        -icon [Rappture::icon axis2]]
1782    $inner configure -borderwidth 4
1783
1784    checkbutton $inner.visible \
1785        -text "Axes" \
1786        -variable [itcl::scope _settings(-axesvisible)] \
1787        -command [itcl::code $this AdjustSetting -axesvisible] \
1788        -font $font
1789
1790    checkbutton $inner.labels \
1791        -text "Axis Labels" \
1792        -variable [itcl::scope _settings(-axislabels)] \
1793        -command [itcl::code $this AdjustSetting -axislabels] \
1794        -font $font
1795    label $inner.grid_l -text "Grid" -font $font
1796    checkbutton $inner.xgrid \
1797        -text "X" \
1798        -variable [itcl::scope _settings(-xgrid)] \
1799        -command [itcl::code $this AdjustSetting -xgrid] \
1800        -font $font
1801    checkbutton $inner.ygrid \
1802        -text "Y" \
1803        -variable [itcl::scope _settings(-ygrid)] \
1804        -command [itcl::code $this AdjustSetting -ygrid] \
1805        -font $font
1806    checkbutton $inner.zgrid \
1807        -text "Z" \
1808        -variable [itcl::scope _settings(-zgrid)] \
1809        -command [itcl::code $this AdjustSetting -zgrid] \
1810        -font $font
1811    checkbutton $inner.minorticks \
1812        -text "Minor Ticks" \
1813        -variable [itcl::scope _settings(-axisminorticks)] \
1814        -command [itcl::code $this AdjustSetting -axisminorticks] \
1815        -font $font
1816
1817    label $inner.mode_l -text "Mode" -font $font
1818
1819    itk_component add axismode {
1820        Rappture::Combobox $inner.mode -width 10 -editable no
1821    }
1822    $inner.mode choices insert end \
1823        "static_triad"    "static" \
1824        "closest_triad"   "closest" \
1825        "furthest_triad"  "farthest" \
1826        "outer_edges"     "outer"
1827    $itk_component(axismode) value $_settings(-axisflymode)
1828    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axisflymode]
1829
1830    blt::table $inner \
1831        0,0 $inner.visible -anchor w -cspan 4 \
1832        1,0 $inner.labels -anchor w -cspan 4 \
1833        2,0 $inner.minorticks -anchor w -cspan 4 \
1834        4,0 $inner.grid_l -anchor w \
1835        4,1 $inner.xgrid -anchor w \
1836        4,2 $inner.ygrid -anchor w \
1837        4,3 $inner.zgrid -anchor w \
1838        5,0 $inner.mode_l -anchor w -padx { 2 0 } \
1839        5,1 $inner.mode -fill x -cspan 3
1840
1841    blt::table configure $inner r* c* -resize none
1842    blt::table configure $inner r7 c6 -resize expand
1843    blt::table configure $inner r3 -height 0.125i
1844}
1845
1846itcl::body Rappture::VtkVolumeViewer::BuildCameraTab {} {
1847    set font [option get $itk_component(hull) font Font]
1848    set inner [$itk_component(main) insert end \
1849        -title "Camera Settings" \
1850        -icon [Rappture::icon camera]]
1851    $inner configure -borderwidth 4
1852
1853    label $inner.view_l -text "view" -font $font
1854    set f [frame $inner.view]
1855    foreach side { front back left right top bottom } {
1856        button $f.$side  -image [Rappture::icon view$side] \
1857            -command [itcl::code $this SetOrientation $side]
1858        Rappture::Tooltip::for $f.$side "Change the view to $side"
1859        pack $f.$side -side left
1860    }
1861    blt::table $inner \
1862        0,0 $inner.view_l -anchor e -pady 2 \
1863        0,1 $inner.view -anchor w -pady 2
1864    blt::table configure $inner r0 -resize none
1865
1866    set row 1
1867    set labels { qx qy qz qw xpan ypan zoom }
1868    foreach tag $labels {
1869        label $inner.${tag}label -text $tag -font $font
1870        entry $inner.${tag} -font $font  -bg white \
1871            -textvariable [itcl::scope _view(-$tag)]
1872        bind $inner.${tag} <Return> \
1873            [itcl::code $this camera set -${tag}]
1874        bind $inner.${tag} <KP_Enter> \
1875            [itcl::code $this camera set -${tag}]
1876        blt::table $inner \
1877            $row,0 $inner.${tag}label -anchor e -pady 2 \
1878            $row,1 $inner.${tag} -anchor w -pady 2
1879        blt::table configure $inner r$row -resize none
1880        incr row
1881    }
1882    checkbutton $inner.ortho \
1883        -text "Orthographic Projection" \
1884        -variable [itcl::scope _view(-ortho)] \
1885        -command [itcl::code $this camera set -ortho] \
1886        -font $font
1887    blt::table $inner \
1888            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1889    blt::table configure $inner r$row -resize none
1890    incr row
1891
1892    blt::table configure $inner c0 c1 -resize none
1893    blt::table configure $inner c2 -resize expand
1894    blt::table configure $inner r$row -resize expand
1895}
1896
1897itcl::body Rappture::VtkVolumeViewer::BuildCutplanesTab {} {
1898    set font [option get $itk_component(hull) font Font]
1899
1900    set inner [$itk_component(main) insert end \
1901        -title "Cutplane Settings" \
1902        -icon [Rappture::icon cutbutton]]
1903
1904    $inner configure -borderwidth 4
1905
1906    checkbutton $inner.visible \
1907        -text "Show Cutplanes" \
1908        -variable [itcl::scope _settings(-cutplanesvisible)] \
1909        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1910        -font $font
1911
1912    checkbutton $inner.lighting \
1913        -text "Enable Lighting" \
1914        -variable [itcl::scope _settings(-cutplanelighting)] \
1915        -command [itcl::code $this AdjustSetting -cutplanelighting] \
1916        -font $font
1917
1918    label $inner.opacity_l -text "Opacity" -font $font
1919    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1920        -variable [itcl::scope _settings(-cutplaneopacity)] \
1921        -width 10 \
1922        -showvalue off \
1923        -command [itcl::code $this AdjustSetting -cutplaneopacity]
1924    $inner.opacity set $_settings(-cutplaneopacity)
1925
1926    # X-value slicer...
1927    itk_component add xCutButton {
1928        Rappture::PushButton $inner.xbutton \
1929            -onimage [Rappture::icon x-cutplane] \
1930            -offimage [Rappture::icon x-cutplane] \
1931            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1932            -variable [itcl::scope _settings(-xcutplanevisible)]
1933    }
1934    Rappture::Tooltip::for $itk_component(xCutButton) \
1935        "Toggle the X-axis cutplane on/off"
1936    $itk_component(xCutButton) select
1937
1938    itk_component add xCutScale {
1939        ::scale $inner.xval -from 100 -to 0 \
1940            -width 10 -orient vertical -showvalue yes \
1941            -borderwidth 1 -highlightthickness 0 \
1942            -command [itcl::code $this EventuallySetCutplane x] \
1943            -variable [itcl::scope _settings(-xcutplaneposition)]
1944    } {
1945        usual
1946        ignore -borderwidth -highlightthickness
1947    }
1948    # Set the default cutplane value before disabling the scale.
1949    $itk_component(xCutScale) set 50
1950    $itk_component(xCutScale) configure -state disabled
1951    Rappture::Tooltip::for $itk_component(xCutScale) \
1952        "@[itcl::code $this Slice tooltip x]"
1953
1954    # Y-value slicer...
1955    itk_component add yCutButton {
1956        Rappture::PushButton $inner.ybutton \
1957            -onimage [Rappture::icon y-cutplane] \
1958            -offimage [Rappture::icon y-cutplane] \
1959            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1960            -variable [itcl::scope _settings(-ycutplanevisible)]
1961    }
1962    Rappture::Tooltip::for $itk_component(yCutButton) \
1963        "Toggle the Y-axis cutplane on/off"
1964    $itk_component(yCutButton) select
1965
1966    itk_component add yCutScale {
1967        ::scale $inner.yval -from 100 -to 0 \
1968            -width 10 -orient vertical -showvalue yes \
1969            -borderwidth 1 -highlightthickness 0 \
1970            -command [itcl::code $this EventuallySetCutplane y] \
1971            -variable [itcl::scope _settings(-ycutplaneposition)]
1972    } {
1973        usual
1974        ignore -borderwidth -highlightthickness
1975    }
1976    Rappture::Tooltip::for $itk_component(yCutScale) \
1977        "@[itcl::code $this Slice tooltip y]"
1978    # Set the default cutplane value before disabling the scale.
1979    $itk_component(yCutScale) set 50
1980    $itk_component(yCutScale) configure -state disabled
1981
1982    # Z-value slicer...
1983    itk_component add zCutButton {
1984        Rappture::PushButton $inner.zbutton \
1985            -onimage [Rappture::icon z-cutplane] \
1986            -offimage [Rappture::icon z-cutplane] \
1987            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1988            -variable [itcl::scope _settings(-zcutplanevisible)]
1989    }
1990    Rappture::Tooltip::for $itk_component(zCutButton) \
1991        "Toggle the Z-axis cutplane on/off"
1992    $itk_component(zCutButton) select
1993
1994    itk_component add zCutScale {
1995        ::scale $inner.zval -from 100 -to 0 \
1996            -width 10 -orient vertical -showvalue yes \
1997            -borderwidth 1 -highlightthickness 0 \
1998            -command [itcl::code $this EventuallySetCutplane z] \
1999            -variable [itcl::scope _settings(-zcutplaneposition)]
2000    } {
2001        usual
2002        ignore -borderwidth -highlightthickness
2003    }
2004    $itk_component(zCutScale) set 50
2005    $itk_component(zCutScale) configure -state disabled
2006    Rappture::Tooltip::for $itk_component(zCutScale) \
2007        "@[itcl::code $this Slice tooltip z]"
2008
2009    blt::table $inner \
2010        0,0 $inner.visible              -anchor w -pady 2 -cspan 4 \
2011        1,0 $inner.lighting             -anchor w -pady 2 -cspan 4 \
2012        2,0 $inner.opacity_l            -anchor w -pady 2 -cspan 3 \
2013        3,0 $inner.opacity              -fill x   -pady 2 -cspan 3 \
2014        4,0 $itk_component(xCutButton)  -anchor e -padx 2 -pady 2 \
2015        5,0 $itk_component(xCutScale)   -fill y \
2016        4,1 $itk_component(yCutButton)  -anchor e -padx 2 -pady 2 \
2017        5,1 $itk_component(yCutScale)   -fill y \
2018        4,2 $itk_component(zCutButton)  -anchor e -padx 2 -pady 2 \
2019        5,2 $itk_component(zCutScale)   -fill y
2020
2021    blt::table configure $inner r* c* -resize none
2022    blt::table configure $inner r5 c3 -resize expand
2023}
2024
2025#
2026#  camera --
2027#
2028itcl::body Rappture::VtkVolumeViewer::camera {option args} {
2029    switch -- $option {
2030        "show" {
2031            puts [array get _view]
2032        }
2033        "set" {
2034            set what [lindex $args 0]
2035            set x $_view($what)
2036            set code [catch { string is double $x } result]
2037            if { $code != 0 || !$result } {
2038                return
2039            }
2040            switch -- $what {
2041                "-ortho" {
2042                    if {$_view($what)} {
2043                        SendCmd "camera mode ortho"
2044                    } else {
2045                        SendCmd "camera mode persp"
2046                    }
2047                }
2048                "-xpan" - "-ypan" {
2049                    PanCamera
2050                }
2051                "-qx" - "-qy" - "-qz" - "-qw" {
2052                    set q [ViewToQuaternion]
2053                    $_arcball quaternion $q
2054                    EventuallyRotate $q
2055                }
2056                "-zoom" {
2057                    SendCmd "camera zoom $_view($what)"
2058                }
2059            }
2060        }
2061    }
2062}
2063
2064itcl::body Rappture::VtkVolumeViewer::GetVtkData { args } {
2065    set bytes ""
2066    foreach dataobj [get] {
2067        foreach comp [$dataobj components] {
2068            set tag $dataobj-$comp
2069            set contents [$dataobj vtkdata $comp]
2070            append bytes "$contents\n"
2071        }
2072    }
2073    return [list .vtk $bytes]
2074}
2075
2076itcl::body Rappture::VtkVolumeViewer::GetImage { args } {
2077    if { [image width $_image(download)] > 0 &&
2078         [image height $_image(download)] > 0 } {
2079        set bytes [$_image(download) data -format "jpeg -quality 100"]
2080        set bytes [Rappture::encoding::decode -as b64 $bytes]
2081        return [list .jpg $bytes]
2082    }
2083    return ""
2084}
2085
2086itcl::body Rappture::VtkVolumeViewer::BuildDownloadPopup { popup command } {
2087    Rappture::Balloon $popup \
2088        -title "[Rappture::filexfer::label downloadWord] as..."
2089    set inner [$popup component inner]
2090    label $inner.summary -text "" -anchor w
2091    radiobutton $inner.vtk_button -text "VTK data file" \
2092        -variable [itcl::scope _downloadPopup(format)] \
2093        -font "Helvetica 9 " \
2094        -value vtk
2095    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2096    radiobutton $inner.image_button -text "Image File" \
2097        -variable [itcl::scope _downloadPopup(format)] \
2098        -value image
2099    Rappture::Tooltip::for $inner.image_button \
2100        "Save as digital image."
2101
2102    button $inner.ok -text "Save" \
2103        -highlightthickness 0 -pady 2 -padx 3 \
2104        -command $command \
2105        -compound left \
2106        -image [Rappture::icon download]
2107
2108    button $inner.cancel -text "Cancel" \
2109        -highlightthickness 0 -pady 2 -padx 3 \
2110        -command [list $popup deactivate] \
2111        -compound left \
2112        -image [Rappture::icon cancel]
2113
2114    blt::table $inner \
2115        0,0 $inner.summary -cspan 2  \
2116        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2117        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2118        4,1 $inner.cancel -width .9i -fill y \
2119        4,0 $inner.ok -padx 2 -width .9i -fill y
2120    blt::table configure $inner r3 -height 4
2121    blt::table configure $inner r4 -pady 4
2122    raise $inner.image_button
2123    $inner.vtk_button invoke
2124    return $inner
2125}
2126
2127itcl::body Rappture::VtkVolumeViewer::SetObjectStyle { dataobj cname } {
2128    # Parse style string.
2129    set tag $dataobj-$cname
2130    array set style {
2131        -color      BCGYR
2132        -lighting   1
2133        -opacity    0.5
2134        -outline    0
2135        -visible    1
2136    }
2137    array set style [$dataobj style $cname]
2138    set _settings(-volumelighting) $style(-lighting)
2139    set _settings(-volumeopacity) [expr $style(-opacity) * 100.0]
2140    set _settings(-volumeoutline) $style(-outline)
2141    set _settings(-volumevisible) $style(-visible)
2142
2143    $itk_component(colormap) value $style(-color)
2144
2145    SendCmd "outline add $tag"
2146    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2147    SendCmd "outline visible $style(-outline) $tag"
2148
2149    SendCmd "$_cutplaneCmd add $tag"
2150    SendCmd "$_cutplaneCmd color [Color2RGB $itk_option(-plotforeground)] $tag"
2151    SendCmd "$_cutplaneCmd visible 0 $tag"
2152
2153    SendCmd "volume add $tag"
2154    SendCmd "volume lighting $style(-lighting) $tag"
2155    SendCmd "volume opacity $style(-opacity) $tag"
2156    SendCmd "volume visible $style(-visible) $tag"
2157    SetColormap $dataobj $cname
2158}
2159
2160itcl::body Rappture::VtkVolumeViewer::IsValidObject { dataobj } {
2161    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2162        return 0
2163    }
2164    return 1
2165}
2166
2167# ----------------------------------------------------------------------
2168# USAGE: ReceiveLegend <colormap> <title> <vmin> <vmax> <size>
2169#
2170# Invoked automatically whenever the "legend" command comes in from
2171# the rendering server.  Indicates that binary image data with the
2172# specified <size> will follow.
2173# ----------------------------------------------------------------------
2174itcl::body Rappture::VtkVolumeViewer::ReceiveLegend { colormap title vmin vmax size } {
2175    if { [isconnected] } {
2176        set bytes [ReceiveBytes $size]
2177        if { ![info exists _image(legend)] } {
2178            set _image(legend) [image create photo]
2179        }
2180        $_image(legend) configure -data $bytes
2181        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2182        if { [catch {DrawLegend} errs] != 0 } {
2183            puts stderr errs=$errs
2184        }
2185    }
2186}
2187
2188#
2189# DrawLegend --
2190#
2191itcl::body Rappture::VtkVolumeViewer::DrawLegend {} {
2192    set fname $_curFldName
2193    set c $itk_component(view)
2194    set w [winfo width $c]
2195    set h [winfo height $c]
2196    set font "Arial 8"
2197    set lineht [font metrics $font -linespace]
2198
2199    if { !$_settings(-legendvisible) } {
2200        $c delete legend
2201        return
2202    }
2203
2204    if { [info exists _fields($fname)] } {
2205        foreach { title units } $_fields($fname) break
2206        if { $units != "" } {
2207            set title [format "%s (%s)" $title $units]
2208        }
2209    } else {
2210        set title $fname
2211    }
2212
2213    set x [expr $w - 2]
2214    if { [$c find withtag "legend"] == "" } {
2215        set y 2
2216        $c create text $x $y \
2217            -anchor ne \
2218            -fill $itk_option(-plotforeground) -tags "title legend" \
2219            -font $font
2220        incr y $lineht
2221        $c create text $x $y \
2222            -anchor ne \
2223            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2224            -font $font
2225        incr y $lineht
2226        $c create image $x $y \
2227            -anchor ne \
2228            -image $_image(legend) -tags "colormap legend"
2229        $c create text $x [expr {$h-2}] \
2230            -anchor se \
2231            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2232            -font $font
2233        #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2234        $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2235        $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2236    }
2237    $c bind title <ButtonPress> [itcl::code $this Combo post]
2238    $c bind title <Enter> [itcl::code $this Combo activate]
2239    $c bind title <Leave> [itcl::code $this Combo deactivate]
2240    # Reset the item coordinates according the current size of the plot.
2241    $c itemconfigure title -text $title
2242    if { [info exists _limits($_curFldName)] } {
2243        foreach { vmin vmax } $_limits($_curFldName) break
2244        $c itemconfigure vmin -text [format %g $vmin]
2245        $c itemconfigure vmax -text [format %g $vmax]
2246    }
2247    set y 2
2248    $c coords title $x $y
2249    incr y $lineht
2250    $c coords vmax $x $y
2251    incr y $lineht
2252    $c coords colormap $x $y
2253    $c coords vmin $x [expr {$h - 2}]
2254}
2255
2256#
2257# EnterLegend --
2258#
2259itcl::body Rappture::VtkVolumeViewer::EnterLegend { x y } {
2260    SetLegendTip $x $y
2261}
2262
2263#
2264# MotionLegend --
2265#
2266itcl::body Rappture::VtkVolumeViewer::MotionLegend { x y } {
2267    Rappture::Tooltip::tooltip cancel
2268    set c $itk_component(view)
2269    SetLegendTip $x $y
2270}
2271
2272#
2273# LeaveLegend --
2274#
2275itcl::body Rappture::VtkVolumeViewer::LeaveLegend { } {
2276    Rappture::Tooltip::tooltip cancel
2277    .rappturetooltip configure -icon ""
2278}
2279
2280#
2281# SetLegendTip --
2282#
2283itcl::body Rappture::VtkVolumeViewer::SetLegendTip { x y } {
2284    set c $itk_component(view)
2285    set w [winfo width $c]
2286    set h [winfo height $c]
2287    set font "Arial 8"
2288    set lineht [font metrics $font -linespace]
2289
2290    set imgHeight [image height $_image(legend)]
2291    set coords [$c coords colormap]
2292    set imgX [expr $w - [image width $_image(legend)] - 2]
2293    set imgY [expr $y - 2 * ($lineht + 2)]
2294
2295    if { [info exists _fields($_title)] } {
2296        foreach { title units } $_fields($_title) break
2297        if { $units != "" } {
2298            set title [format "%s (%s)" $title $units]
2299        }
2300    } else {
2301        set title $_title
2302    }
2303    # Make a swatch of the selected color
2304    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2305        #puts stderr "out of range: $imgY"
2306        return
2307    }
2308    if { ![info exists _image(swatch)] } {
2309        set _image(swatch) [image create photo -width 24 -height 24]
2310    }
2311    set color [eval format "\#%02x%02x%02x" $pixel]
2312    $_image(swatch) put black  -to 0 0 23 23
2313    $_image(swatch) put $color -to 1 1 22 22
2314    .rappturetooltip configure -icon $_image(swatch)
2315
2316    # Compute the value of the point
2317    if { [info exists _limits($_curFldName)] } {
2318        foreach { vmin vmax } $_limits($_curFldName) break
2319        set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2320        set value [expr $t * ($vmax - $vmin) + $vmin]
2321    } else {
2322        set value 0.0
2323    }
2324    set tipx [expr $x + 15]
2325    set tipy [expr $y - 5]
2326    Rappture::Tooltip::text $c "$title $value"
2327    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy
2328}
2329
2330# ----------------------------------------------------------------------
2331# USAGE: Slice move x|y|z <newval>
2332#
2333# Called automatically when the user drags the slider to move the
2334# cut plane that slices 3D data.  Gets the current value from the
2335# slider and moves the cut plane to the appropriate point in the
2336# data set.
2337# ----------------------------------------------------------------------
2338itcl::body Rappture::VtkVolumeViewer::Slice {option args} {
2339    switch -- $option {
2340        "move" {
2341            set axis [lindex $args 0]
2342            set newval [lindex $args 1]
2343            if {[llength $args] != 2} {
2344                error "wrong # args: should be \"Slice move x|y|z newval\""
2345            }
2346            set newpos [expr {0.01*$newval}]
2347            SendCmd "$_cutplaneCmd slice $axis $newpos"
2348        }
2349        "tooltip" {
2350            set axis [lindex $args 0]
2351            set val [$itk_component(${axis}CutScale) get]
2352            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2353        }
2354        default {
2355            error "bad option \"$option\": should be axis, move, or tooltip"
2356        }
2357    }
2358}
2359
2360# ----------------------------------------------------------------------
2361# USAGE: _dropdown post
2362# USAGE: _dropdown unpost
2363# USAGE: _dropdown select
2364#
2365# Used internally to handle the dropdown list for this combobox.  The
2366# post/unpost options are invoked when the list is posted or unposted
2367# to manage the relief of the controlling button.  The select option
2368# is invoked whenever there is a selection from the list, to assign
2369# the value back to the gauge.
2370# ----------------------------------------------------------------------
2371itcl::body Rappture::VtkVolumeViewer::Combo {option} {
2372    set c $itk_component(view)
2373    switch -- $option {
2374        post {
2375            foreach { x1 y1 x2 y2 } [$c bbox title] break
2376            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2377            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2378            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2379            tk_popup $itk_component(fieldmenu) $x $y
2380        }
2381        activate {
2382            $c itemconfigure title -fill red
2383        }
2384        deactivate {
2385            $c itemconfigure title -fill $itk_option(-plotforeground)
2386        }
2387        invoke {
2388            $itk_component(field) value $_curFldLabel
2389            AdjustSetting -field
2390        }
2391        default {
2392            error "bad option \"$option\": should be post, unpost, select"
2393        }
2394    }
2395}
2396
2397itcl::body Rappture::VtkVolumeViewer::SetOrientation { side } {
2398    array set positions {
2399        front "1 0 0 0"
2400        back  "0 0 1 0"
2401        left  "0.707107 0 -0.707107 0"
2402        right "0.707107 0 0.707107 0"
2403        top   "0.707107 -0.707107 0 0"
2404        bottom "0.707107 0.707107 0 0"
2405    }
2406    foreach name { -qw -qx -qy -qz } value $positions($side) {
2407        set _view($name) $value
2408    }
2409    set q [ViewToQuaternion]
2410    $_arcball quaternion $q
2411    SendCmd "camera orient $q"
2412    SendCmd "camera reset"
2413    set _view(-xpan) 0
2414    set _view(-ypan) 0
2415    set _view(-zoom) 1.0
2416}
2417
2418#
2419# GetDatasetsWithComponent --
2420#
2421# Returns a list of all the datasets (known by the combination of
2422# their data object and component name) that match the given
2423# component name.  For example, this is used where we want to change
2424# the settings of volumes that have the current component.
2425#
2426itcl::body Rappture::VtkVolumeViewer::GetDatasetsWithComponent { cname } {
2427    if { ![info exists _volcomponents($cname)] } {
2428        return ""
2429    }
2430    return $_volcomponents($cname)
2431}
Note: See TracBrowser for help on using the repository browser.