source: trunk/gui/scripts/vtkvolumeviewer.tcl @ 6359

Last change on this file since 6359 was 6355, checked in by ldelgass, 8 years ago

Add SetCurrentFieldName? method to more vtk viewers

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