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

Last change on this file since 4735 was 4735, checked in by ldelgass, 6 years ago

Try to keep style names more consistent.

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