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

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

Remove redundant settings initialization

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