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

Last change on this file since 4197 was 4197, checked in by ldelgass, 10 years ago

Add "default" to colormap dropdown: needed for user-specified -color styles
(which may not have a named entry). Still needs some work (see e.g. the volume1
test).

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