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

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

set _downloadPopup to private access

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