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

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

Axis setting fixes for vtkvolumeviewer

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