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

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

sync fixes

File size: 102.8 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 } {
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        PanCamera
1022        set _first ""
1023        InitSettings -background \
1024            -xgrid -ygrid -zgrid -axisflymode \
1025            -axesvisible -axislabels -axisminorticks
1026        StopBufferingCommands
1027        SendCmd "imgflush"
1028        StartBufferingCommands
1029     }
1030    set _first ""
1031
1032    SendCmd "dataset visible 0"
1033
1034    # No volumes are active (i.e. in the working set of displayed volumes).
1035    # A volume is always invisible if it's not in the working set.  A
1036    # volume in the working set may be visible/invisible depending upon the
1037    # global visibility value.
1038    array unset _activeVolumes
1039    foreach dataobj [get -objects] {
1040        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
1041            set _first $dataobj
1042        }
1043        set _obj2datasets($dataobj) ""
1044        foreach comp [$dataobj components] {
1045            set tag $dataobj-$comp
1046            if { ![info exists _datasets($tag)] } {
1047                set bytes [$dataobj vtkdata $comp]
1048                set length [string length $bytes]
1049                if { $_reportClientInfo }  {
1050                    set info {}
1051                    lappend info "tool_id"       [$dataobj hints toolId]
1052                    lappend info "tool_name"     [$dataobj hints toolName]
1053                    lappend info "tool_version"  [$dataobj hints toolRevision]
1054                    lappend info "tool_title"    [$dataobj hints toolTitle]
1055                    lappend info "dataset_label" [$dataobj hints label]
1056                    lappend info "dataset_size"  $length
1057                    lappend info "dataset_tag"   $tag
1058                    SendCmd [list "clientinfo" $info]
1059                }
1060                append _outbuf "dataset add $tag data follows $length\n"
1061                append _outbuf $bytes
1062                set _datasets($tag) 1
1063                SetObjectStyle $dataobj $comp
1064            }
1065            lappend _obj2datasets($dataobj) $tag
1066            if { [info exists _obj2ovride($dataobj-raise)] } {
1067                SendCmd "volume visible 1 $tag"
1068            }
1069            break
1070        }
1071    }
1072    if {"" != $_first} {
1073        set location [$_first hints camera]
1074        if { $location != "" } {
1075            array set view $location
1076        }
1077
1078        foreach axis { x y z } {
1079            set label [$_first hints ${axis}label]
1080            if { $label != "" } {
1081                SendCmd [list axis name $axis $label]
1082            }
1083            set units [$_first hints ${axis}units]
1084            if { $units != "" } {
1085                SendCmd [list axis units $axis $units]
1086            }
1087        }
1088        $itk_component(field) choices delete 0 end
1089        $itk_component(fieldmenu) delete 0 end
1090        array unset _fields
1091        set _curFldName ""
1092        foreach cname [$_first components] {
1093            foreach fname [$_first fieldnames $cname] {
1094                if { [info exists _fields($fname)] } {
1095                    continue
1096                }
1097                foreach { label units components } \
1098                    [$_first fieldinfo $fname] break
1099                # Only scalar fields are valid
1100                if {$_allowMultiComponent || $components == 1} {
1101                    $itk_component(field) choices insert end "$fname" "$label"
1102                    $itk_component(fieldmenu) add radiobutton -label "$label" \
1103                        -value $label -variable [itcl::scope _curFldLabel] \
1104                        -selectcolor red \
1105                        -activebackground $itk_option(-plotbackground) \
1106                        -activeforeground $itk_option(-plotforeground) \
1107                        -font "Arial 8" \
1108                        -command [itcl::code $this Combo invoke]
1109                    set _fields($fname) [list $label $units $components]
1110                    if { $_curFldName == "" } {
1111                        set _curFldName $fname
1112                        set _curFldLabel $label
1113                    }
1114                }
1115            }
1116        }
1117        $itk_component(field) value $_curFldLabel
1118    }
1119
1120    InitSettings -color \
1121        -volumeambient -volumediffuse -volumespecularlevel \
1122        -volumespecularexponent -volumeblendmode -volumethickness \
1123        -volumelighting -volumeopacity -volumequality -volumeoutline -volumevisible \
1124        -cutplanesvisible \
1125        -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1126        -xcutplanevisible -ycutplanevisible -zcutplanevisible
1127
1128    if { $_reset } {
1129        SendCmd "camera reset"
1130        SendCmd "camera zoom $_view(-zoom)"
1131        RequestLegend
1132        set _reset 0
1133    }
1134    # Actually write the commands to the server socket.  If it fails, we don't
1135    # care.  We're finished here.
1136    blt::busy hold $itk_component(hull)
1137    StopBufferingCommands
1138    blt::busy release $itk_component(hull)
1139}
1140
1141# ----------------------------------------------------------------------
1142# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1143#
1144# Returns a list of server IDs for the current datasets being displayed.  This
1145# is normally a single ID, but it might be a list of IDs if the current data
1146# object has multiple components.
1147# ----------------------------------------------------------------------
1148itcl::body Rappture::VtkVolumeViewer::CurrentDatasets {args} {
1149    set flag [lindex $args 0]
1150    switch -- $flag {
1151        "-all" {
1152            if { [llength $args] > 1 } {
1153                error "CurrentDatasets: can't specify dataobj after \"-all\""
1154            }
1155            set dlist [get -objects]
1156        }
1157        "-visible" {
1158            if { [llength $args] > 1 } {
1159                set dlist {}
1160                set args [lrange $args 1 end]
1161                foreach dataobj $args {
1162                    if { [info exists _obj2ovride($dataobj-raise)] } {
1163                        lappend dlist $dataobj
1164                    }
1165                }
1166            } else {
1167                set dlist [get -visible]
1168            }
1169        }           
1170        default {
1171            set dlist $args
1172        }
1173    }
1174    set rlist ""
1175    foreach dataobj $dlist {
1176        foreach comp [$dataobj components] {
1177            set tag $dataobj-$comp
1178            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1179                lappend rlist $tag
1180            }
1181        }
1182    }
1183    return $rlist
1184}
1185
1186# ----------------------------------------------------------------------
1187# USAGE: Zoom in
1188# USAGE: Zoom out
1189# USAGE: Zoom reset
1190#
1191# Called automatically when the user clicks on one of the zoom
1192# controls for this widget.  Changes the zoom for the current view.
1193# ----------------------------------------------------------------------
1194itcl::body Rappture::VtkVolumeViewer::Zoom {option} {
1195    switch -- $option {
1196        "in" {
1197            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1198            SendCmd "camera zoom $_view(-zoom)"
1199        }
1200        "out" {
1201            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1202            SendCmd "camera zoom $_view(-zoom)"
1203        }
1204        "reset" {
1205            array set _view {
1206                -qw      0.853553
1207                -qx      -0.353553
1208                -qy      0.353553
1209                -qz      0.146447
1210                -zoom    1.0
1211                -xpan   0
1212                -ypan   0
1213            }
1214            if { $_first != "" } {
1215                set location [$_first hints camera]
1216                if { $location != "" } {
1217                    array set _view $location
1218                }
1219            }
1220            $_arcball quaternion [ViewToQuaternion]
1221            DoRotate
1222            SendCmd "camera reset"
1223        }
1224    }
1225}
1226
1227itcl::body Rappture::VtkVolumeViewer::PanCamera {} {
1228    set x $_view(-xpan)
1229    set y $_view(-ypan)
1230    SendCmd "camera pan $x $y"
1231}
1232
1233
1234# ----------------------------------------------------------------------
1235# USAGE: Rotate click <x> <y>
1236# USAGE: Rotate drag <x> <y>
1237# USAGE: Rotate release <x> <y>
1238#
1239# Called automatically when the user clicks/drags/releases in the
1240# plot area.  Moves the plot according to the user's actions.
1241# ----------------------------------------------------------------------
1242itcl::body Rappture::VtkVolumeViewer::Rotate {option x y} {
1243    switch -- $option {
1244        "click" {
1245            $itk_component(view) configure -cursor fleur
1246            set _click(x) $x
1247            set _click(y) $y
1248        }
1249        "drag" {
1250            if {[array size _click] == 0} {
1251                Rotate click $x $y
1252            } else {
1253                set w [winfo width $itk_component(view)]
1254                set h [winfo height $itk_component(view)]
1255                if {$w <= 0 || $h <= 0} {
1256                    return
1257                }
1258
1259                if {[catch {
1260                    # this fails sometimes for no apparent reason
1261                    set dx [expr {double($x-$_click(x))/$w}]
1262                    set dy [expr {double($y-$_click(y))/$h}]
1263                }]} {
1264                    return
1265                }
1266                if { $dx == 0 && $dy == 0 } {
1267                    return
1268                }
1269                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1270                EventuallyRotate $q
1271                set _click(x) $x
1272                set _click(y) $y
1273            }
1274        }
1275        "release" {
1276            Rotate drag $x $y
1277            $itk_component(view) configure -cursor ""
1278            catch {unset _click}
1279        }
1280        default {
1281            error "bad option \"$option\": should be click, drag, release"
1282        }
1283    }
1284}
1285
1286itcl::body Rappture::VtkVolumeViewer::Pick {x y} {
1287    foreach tag [CurrentDatasets -visible] {
1288        SendCmd "dataset getscalar pixel $x $y $tag"
1289    }
1290}
1291
1292# ----------------------------------------------------------------------
1293# USAGE: $this Pan click x y
1294#        $this Pan drag x y
1295#        $this Pan release x y
1296#
1297# Called automatically when the user clicks on one of the zoom
1298# controls for this widget.  Changes the zoom for the current view.
1299# ----------------------------------------------------------------------
1300itcl::body Rappture::VtkVolumeViewer::Pan {option x y} {
1301    switch -- $option {
1302        "set" {
1303            set w [winfo width $itk_component(view)]
1304            set h [winfo height $itk_component(view)]
1305            set x [expr $x / double($w)]
1306            set y [expr $y / double($h)]
1307            set _view(-xpan) [expr $_view(-xpan) + $x]
1308            set _view(-ypan) [expr $_view(-ypan) + $y]
1309            PanCamera
1310            return
1311        }
1312        "click" {
1313            set _click(x) $x
1314            set _click(y) $y
1315            $itk_component(view) configure -cursor hand1
1316        }
1317        "drag" {
1318            if { ![info exists _click(x)] } {
1319                set _click(x) $x
1320            }
1321            if { ![info exists _click(y)] } {
1322                set _click(y) $y
1323            }
1324            set w [winfo width $itk_component(view)]
1325            set h [winfo height $itk_component(view)]
1326            set dx [expr ($_click(x) - $x)/double($w)]
1327            set dy [expr ($_click(y) - $y)/double($h)]
1328            set _click(x) $x
1329            set _click(y) $y
1330            set _view(-xpan) [expr $_view(-xpan) - $dx]
1331            set _view(-ypan) [expr $_view(-ypan) - $dy]
1332            PanCamera
1333        }
1334        "release" {
1335            Pan drag $x $y
1336            $itk_component(view) configure -cursor ""
1337        }
1338        default {
1339            error "unknown option \"$option\": should set, click, drag, or release"
1340        }
1341    }
1342}
1343
1344# ----------------------------------------------------------------------
1345# USAGE: InitSettings <what> ?<value>?
1346#
1347# Used internally to update rendering settings whenever parameters
1348# change in the popup settings panel.  Sends the new settings off
1349# to the back end.
1350# ----------------------------------------------------------------------
1351itcl::body Rappture::VtkVolumeViewer::InitSettings { args } {
1352    foreach spec $args {
1353        if { [info exists _settings($_first${spec})] } {
1354            # Reset global setting with dataobj specific setting
1355            set _settings($spec) $_settings($_first${spec})
1356        }
1357        AdjustSetting $spec
1358    }
1359}
1360
1361#
1362# AdjustSetting --
1363#
1364#       Changes/updates a specific setting in the widget.  There are
1365#       usually user-setable option.  Commands are sent to the render
1366#       server.
1367#
1368itcl::body Rappture::VtkVolumeViewer::AdjustSetting {what {value ""}} {
1369    if { ![isconnected] } {
1370        if { $_reset } {
1371            # Just reconnect if we've been reset.
1372            Connect
1373        }
1374        return
1375    }
1376    switch -- $what {
1377        "-current" {
1378            set cname [$itk_component(volcomponents) value]
1379            SwitchComponent $cname
1380        }
1381        "-background" {
1382            set bgcolor [$itk_component(background) value]
1383            set _settings($what) $bgcolor
1384            array set fgcolors {
1385                "black" "white"
1386                "white" "black"
1387                "grey"  "black"
1388            }
1389            configure -plotbackground $bgcolor \
1390                -plotforeground $fgcolors($bgcolor)
1391            $itk_component(view) delete "legend"
1392            DrawLegend
1393        }
1394        "-volumeoutline" {
1395            set bool $_settings($what)
1396            SendCmd "outline visible 0"
1397            foreach tag [GetDatasetsWithComponent $_current] {
1398                SendCmd "outline visible $bool $tag"
1399            }
1400        }
1401        "-legendvisible" {
1402            set bool $_settings($what)
1403            set _settings($_current${what}) $bool
1404            if { $bool } {
1405                blt::table $itk_component(plotarea) \
1406                    1,0 $itk_component(legend) -fill x
1407            } else {
1408                blt::table forget $itk_component(legend)
1409            }
1410        }
1411        "-volumevisible" {
1412            set bool $_settings($what)
1413            set _settings($_current${what}) $bool
1414            # Only the data objects in the array _obj2ovride(*-raise) are
1415            # in the working set and can be displayed on screen. The global
1416            # volume control determines whether they are visible.
1417            #
1418            # Note: The use of the current component is a hold over from
1419            #       nanovis.  If we can't display more than one volume,
1420            #       we don't have to limit the effects to a specific
1421            #       component.
1422            foreach tag [GetDatasetsWithComponent $_current] {
1423                foreach {dataobj cname} [split $tag -] break
1424                if { [info exists _obj2ovride($dataobj-raise)] } {
1425                    SendCmd "volume visible $bool $tag"
1426                }
1427            }
1428            if { $bool } {
1429                Rappture::Tooltip::for $itk_component(volume) \
1430                    "Hide the volume"
1431            } else {
1432                Rappture::Tooltip::for $itk_component(volume) \
1433                    "Show the volume"
1434            }
1435        }
1436        "-volumeblendmode" {
1437            set val [$itk_component(blendmode) value]
1438            set mode [$itk_component(blendmode) translate $val]
1439            set _settings($what) $mode
1440            set _settings($_current${what}) $mode
1441            foreach tag [GetDatasetsWithComponent $_current] {
1442                SendCmd "volume blendmode $mode $tag"
1443            }
1444        }
1445        "-volumeambient" {
1446            # Other parts of the code use the -volumeambient setting to
1447            # tell if the component settings have been initialized
1448            if { ![info exists _settings($_current${what})] } {
1449                InitComponentSettings $_current
1450            }
1451            set val $_settings($what)
1452            set _settings($_current${what}) $val
1453            set ambient [expr {0.01*$val}]
1454            foreach tag [GetDatasetsWithComponent $_current] {
1455                SendCmd "volume shading ambient $ambient $tag"
1456            }
1457        }
1458        "-volumediffuse" {
1459            set val $_settings($what)
1460            set _settings($_current${what}) $val
1461            set diffuse [expr {0.01*$val}]
1462            foreach tag [GetDatasetsWithComponent $_current] {
1463                SendCmd "volume shading diffuse $diffuse $tag"
1464            }
1465        }
1466        "-volumespecularlevel" - "-volumespecularexponent" {
1467            set val $_settings($what)
1468            set _settings($_current${what}) $val
1469            set level [expr {0.01*$val}]
1470            set exp $_settings($what)
1471            foreach tag [GetDatasetsWithComponent $_current] {
1472                SendCmd "volume shading specular $level $exp $tag"
1473            }
1474        }
1475        "-volumelighting" {
1476            set bool $_settings($what)
1477            set _settings($_current{$what}) $bool
1478            foreach tag [GetDatasetsWithComponent $_current] {
1479                SendCmd "volume lighting $bool $tag"
1480            }
1481        }
1482        "-volumeopacity" {
1483            set val $_settings($what)
1484            set _settings($_current${what}) $val
1485            set val [expr {0.01*$val}]
1486            foreach tag [GetDatasetsWithComponent $_current] {
1487                SendCmd "volume opacity $val $tag"
1488            }
1489        }
1490        "-volumequality" {
1491            set val $_settings($what)
1492            set _settings($_current${what}) $val
1493            set val [expr {0.01*$val}]
1494            foreach tag [GetDatasetsWithComponent $_current] {
1495                SendCmd "volume quality $val $tag"
1496            }
1497        }
1498        "-axesvisible" {
1499            set bool $_settings($what)
1500            SendCmd "axis visible all $bool"
1501        }
1502        "-axislabels" {
1503            set bool $_settings($what)
1504            SendCmd "axis labels all $bool"
1505        }
1506        "-axisminorticks" {
1507            set bool $_settings($what)
1508            SendCmd "axis minticks all $bool"
1509        }
1510        "-xgrid" - "-ygrid" - "-zgrid" {
1511            set axis [string range $what 1 1]
1512            set bool $_settings($what)
1513            SendCmd "axis grid $axis $bool"
1514        }
1515        "-axisflymode" {
1516            set mode [$itk_component(axismode) value]
1517            set mode [$itk_component(axismode) translate $mode]
1518            set _settings($what) $mode
1519            SendCmd "axis flymode $mode"
1520        }
1521        "-cutplanesvisible" {
1522            set bool $_settings($what)
1523            foreach dataset [CurrentDatasets -visible] {
1524                SendCmd "$_cutplaneCmd visible $bool $dataset"
1525            }
1526        }
1527        "-cutplanelighting" {
1528            set bool $_settings($what)
1529            foreach dataset [CurrentDatasets -visible] {
1530                if {$_cutplaneCmd != "imgcutplane"} {
1531                    SendCmd "$_cutplaneCmd lighting $bool $dataset"
1532                } else {
1533                    if {$bool} {
1534                        set ambient 0.0
1535                        set diffuse 1.0
1536                    } else {
1537                        set ambient 1.0
1538                        set diffuse 0.0
1539                    }
1540                    SendCmd "imgcutplane material $ambient $diffuse $dataset"
1541                }
1542            }
1543        }
1544        "-cutplaneopacity" {
1545            set val $_settings($what)
1546            set sval [expr { 0.01 * double($val) }]
1547            foreach dataset [CurrentDatasets -visible] {
1548                SendCmd "$_cutplaneCmd opacity $sval $dataset"
1549            }
1550        }
1551        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1552            set axis [string range $what 1 1]
1553            set bool $_settings($what)
1554            if { $bool } {
1555                $itk_component(${axis}CutScale) configure -state normal \
1556                    -troughcolor white
1557            } else {
1558                $itk_component(${axis}CutScale) configure -state disabled \
1559                    -troughcolor grey82
1560            }
1561            foreach dataset [CurrentDatasets -visible] {
1562                SendCmd "$_cutplaneCmd axis $axis $bool $dataset"
1563            }
1564        }
1565        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1566            set axis [string range $what 1 1]
1567            set pos [expr $_settings($what) * 0.01]
1568            foreach dataset [CurrentDatasets -visible] {
1569                SendCmd "$_cutplaneCmd slice ${axis} ${pos} $dataset"
1570            }
1571            set _cutplanePending 0
1572        }
1573        "-volumethickness" {
1574            set _settings($_current${what}) $_settings($what)
1575            updateTransferFunctions
1576        }
1577        "-color" {
1578            set color [$itk_component(colormap) value]
1579            set _settings($what) $color
1580            set _settings($_current${what}) $color
1581            ResetColormap $_current $color
1582        }
1583        "-field" {
1584            set label [$itk_component(field) value]
1585            set fname [$itk_component(field) translate $label]
1586            set _settings($what) $fname
1587            if { [info exists _fields($fname)] } {
1588                foreach { label units components } $_fields($fname) break
1589                if { !$_allowMultiComponent && $components > 1 } {
1590                    puts stderr "Can't use a vector field in a volume"
1591                    return
1592                }
1593                set _curFldName $fname
1594                set _curFldLabel $label
1595            } else {
1596                puts stderr "unknown field \"$fname\""
1597                return
1598            }
1599            foreach dataset [CurrentDatasets -visible $_first] {
1600                SendCmd "dataset scalar $_curFldName $dataset"
1601            }
1602            SendCmd "camera reset"
1603            DrawLegend
1604        }
1605        default {
1606            error "don't know how to fix $what"
1607        }
1608    }
1609}
1610
1611#
1612# RequestLegend --
1613#
1614#       Request a new legend from the server.  The size of the legend
1615#       is determined from the height of the canvas.
1616#
1617itcl::body Rappture::VtkVolumeViewer::RequestLegend {} {
1618    set _legendPending 0
1619    set font "Arial 8"
1620    set lineht [font metrics $itk_option(-font) -linespace]
1621    set c $itk_component(legend)
1622    set w [winfo width $c]
1623    set h [winfo height $c]
1624    set h [expr {$h-$lineht-20}]
1625    set w [expr {$w-20}]
1626    # Set the legend on the first volume dataset.
1627    foreach dataset [CurrentDatasets -visible $_first] {
1628        foreach {dataobj comp} [split $dataset -] break
1629        if { [info exists _dataset2style($dataset)] } {
1630            SendCmdNoWait \
1631                "legend2 $_dataset2style($dataset) $w $h"
1632                #"legend $_dataset2style($dataset) scalar $_curFldName {} $w $h 0"
1633            break;
1634        }
1635    }
1636}
1637
1638# ----------------------------------------------------------------------
1639# CONFIGURATION OPTION: -plotbackground
1640# ----------------------------------------------------------------------
1641itcl::configbody Rappture::VtkVolumeViewer::plotbackground {
1642    if { [isconnected] } {
1643        set color $itk_option(-plotbackground)
1644        set rgb [Color2RGB $color]
1645        SendCmd "screen bgcolor $rgb"
1646        $itk_component(legend) configure -background $color
1647    }
1648}
1649
1650# ----------------------------------------------------------------------
1651# CONFIGURATION OPTION: -plotforeground
1652# ----------------------------------------------------------------------
1653itcl::configbody Rappture::VtkVolumeViewer::plotforeground {
1654    if { [isconnected] } {
1655        set color $itk_option(-plotforeground)
1656        set rgb [Color2RGB $color]
1657        SendCmd "axis color all $rgb"
1658        SendCmd "outline color $rgb"
1659        SendCmd "$_cutplaneCmd color $rgb"
1660        $itk_component(legend) itemconfigure labels -fill $color
1661        $itk_component(legend) itemconfigure limits -fill $color
1662    }
1663}
1664
1665itcl::body Rappture::VtkVolumeViewer::BuildViewTab {} {
1666    set fg [option get $itk_component(hull) font Font]
1667    #set bfg [option get $itk_component(hull) boldFont Font]
1668
1669    set inner [$itk_component(main) insert end \
1670        -title "View Settings" \
1671        -icon [Rappture::icon wrench]]
1672    $inner configure -borderwidth 4
1673
1674    checkbutton $inner.axes \
1675        -text "Axes" \
1676        -variable [itcl::scope _settings(-axesvisible)] \
1677        -command [itcl::code $this AdjustSetting -axesvisible] \
1678        -font "Arial 9"
1679
1680    checkbutton $inner.outline \
1681        -text "Outline" \
1682        -variable [itcl::scope _settings(-volumeoutline)] \
1683        -command [itcl::code $this AdjustSetting -volumeoutline] \
1684        -font "Arial 9"
1685
1686    checkbutton $inner.legend \
1687        -text "Legend" \
1688        -variable [itcl::scope _settings(-legendvisible)] \
1689        -command [itcl::code $this AdjustSetting -legendvisible] \
1690        -font "Arial 9"
1691
1692    checkbutton $inner.volume \
1693        -text "Volume" \
1694        -variable [itcl::scope _settings(-volumevisible)] \
1695        -command [itcl::code $this AdjustSetting -volumevisible] \
1696        -font "Arial 9"
1697
1698    label $inner.background_l -text "Background" -font "Arial 9"
1699    itk_component add background {
1700        Rappture::Combobox $inner.background -width 10 -editable no
1701    }
1702    $inner.background choices insert end \
1703        "black"              "black"            \
1704        "white"              "white"            \
1705        "grey"               "grey"             
1706
1707    $itk_component(background) value $_settings(-background)
1708    bind $inner.background <<Value>> \
1709        [itcl::code $this AdjustSetting -background]
1710
1711    blt::table $inner \
1712        0,0 $inner.axes  -cspan 2 -anchor w \
1713        1,0 $inner.outline  -cspan 2 -anchor w \
1714        2,0 $inner.volume  -cspan 2 -anchor w \
1715        3,0 $inner.legend  -cspan 2 -anchor w \
1716        4,0 $inner.background_l       -anchor e -pady 2 \
1717        4,1 $inner.background                   -fill x \
1718
1719    blt::table configure $inner r* -resize none
1720    blt::table configure $inner r5 -resize expand
1721}
1722
1723itcl::body Rappture::VtkVolumeViewer::BuildVolumeTab {} {
1724    set font [option get $itk_component(hull) font Font]
1725    #set bfont [option get $itk_component(hull) boldFont Font]
1726
1727    set inner [$itk_component(main) insert end \
1728        -title "Volume Settings" \
1729        -icon [Rappture::icon volume-on]]
1730    $inner configure -borderwidth 4
1731
1732    label $inner.volcomponents_l -text "Component" -font $font
1733    itk_component add volcomponents {
1734        Rappture::Combobox $inner.volcomponents -editable no
1735    }
1736    bind $inner.volcomponents <<Value>> \
1737        [itcl::code $this AdjustSetting -current]
1738
1739    checkbutton $inner.visibility \
1740        -text "Visible" \
1741        -font $font \
1742        -variable [itcl::scope _settings(-volumevisible)] \
1743        -command [itcl::code $this AdjustSetting -volumevisible]
1744
1745    label $inner.lighting_l \
1746        -text "Lighting / Material Properties" \
1747        -font "Arial 9 bold"
1748
1749    checkbutton $inner.lighting \
1750        -text "Enable Lighting" \
1751        -font $font \
1752        -variable [itcl::scope _settings(-volumelighting)] \
1753        -command [itcl::code $this AdjustSetting -volumelighting]
1754
1755    label $inner.ambient_l \
1756        -text "Ambient" \
1757        -font $font
1758    ::scale $inner.ambient -from 0 -to 100 -orient horizontal \
1759        -variable [itcl::scope _settings(-volumeambient)] \
1760        -showvalue off \
1761        -command [itcl::code $this AdjustSetting -volumeambient] \
1762        -troughcolor grey92
1763
1764    label $inner.diffuse_l -text "Diffuse" -font $font
1765    ::scale $inner.diffuse -from 0 -to 100 -orient horizontal \
1766        -variable [itcl::scope _settings(-volumediffuse)] \
1767        -showvalue off \
1768        -command [itcl::code $this AdjustSetting -volumediffuse] \
1769        -troughcolor grey92
1770
1771    label $inner.specularLevel_l -text "Specular" -font $font
1772    ::scale $inner.specularLevel -from 0 -to 100 -orient horizontal \
1773        -variable [itcl::scope _settings(-volumespecularlevel)] \
1774        -showvalue off \
1775        -command [itcl::code $this AdjustSetting -volumespecularlevel] \
1776        -troughcolor grey92
1777
1778    label $inner.specularExponent_l -text "Shininess" -font $font
1779    ::scale $inner.specularExponent -from 10 -to 128 -orient horizontal \
1780        -variable [itcl::scope _settings(-volumespecularexponent)] \
1781        -showvalue off \
1782        -command [itcl::code $this AdjustSetting -volumespecularexponent] \
1783        -troughcolor grey92
1784
1785    label $inner.opacity_l -text "Opacity" -font $font
1786    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1787        -variable [itcl::scope _settings(-volumeopacity)] \
1788        -showvalue off \
1789        -command [itcl::code $this AdjustSetting -volumeopacity] \
1790        -troughcolor grey92
1791
1792    label $inner.quality_l -text "Quality" -font $font
1793    ::scale $inner.quality -from 0 -to 100 -orient horizontal \
1794        -variable [itcl::scope _settings(-volumequality)] \
1795        -showvalue off \
1796        -command [itcl::code $this AdjustSetting -volumequality] \
1797        -troughcolor grey92
1798
1799    label $inner.field_l -text "Field" -font $font
1800    itk_component add field {
1801        Rappture::Combobox $inner.field -editable no
1802    }
1803    bind $inner.field <<Value>> \
1804        [itcl::code $this AdjustSetting -field]
1805
1806    label $inner.transferfunction_l \
1807        -text "Transfer Function" -font "Arial 9 bold"
1808
1809    label $inner.thin -text "Thin" -font $font
1810    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
1811        -variable [itcl::scope _settings(-volumethickness)] \
1812        -showvalue off \
1813        -command [itcl::code $this AdjustSetting -volumethickness] \
1814        -troughcolor grey92
1815
1816    label $inner.thick -text "Thick" -font $font
1817    $inner.thickness set $_settings(-volumethickness)
1818
1819    label $inner.colormap_l -text "Colormap" -font $font
1820    itk_component add colormap {
1821        Rappture::Combobox $inner.colormap -width 10 -editable no
1822    }
1823    $inner.colormap choices insert end [GetColormapList -includeDefault]
1824
1825    bind $inner.colormap <<Value>> \
1826        [itcl::code $this AdjustSetting -color]
1827    $itk_component(colormap) value "default"
1828    set _settings(-color) "default"
1829
1830    label $inner.blendmode_l -text "Blend Mode" -font $font
1831    itk_component add blendmode {
1832        Rappture::Combobox $inner.blendmode -editable no
1833    }
1834    $inner.blendmode choices insert end \
1835        "composite"          "Composite"         \
1836        "max_intensity"      "Maximum Intensity" \
1837        "additive"           "Additive"
1838
1839    $itk_component(blendmode) value \
1840        "[$itk_component(blendmode) label $_settings(-volumeblendmode)]"
1841    bind $inner.blendmode <<Value>> \
1842        [itcl::code $this AdjustSetting -volumeblendmode]
1843
1844    blt::table $inner \
1845        0,0 $inner.volcomponents_l -anchor e -cspan 2 \
1846        0,2 $inner.volcomponents             -cspan 3 -fill x \
1847        1,0 $inner.field_l   -anchor e -cspan 2  \
1848        1,2 $inner.field               -cspan 3 -fill x \
1849        2,0 $inner.lighting_l -anchor w -cspan 4 \
1850        3,1 $inner.lighting   -anchor w -cspan 3 \
1851        4,1 $inner.ambient_l       -anchor e -pady 2 \
1852        4,2 $inner.ambient                   -cspan 3 -fill x \
1853        5,1 $inner.diffuse_l       -anchor e -pady 2 \
1854        5,2 $inner.diffuse                   -cspan 3 -fill x \
1855        6,1 $inner.specularLevel_l -anchor e -pady 2 \
1856        6,2 $inner.specularLevel             -cspan 3 -fill x \
1857        7,1 $inner.specularExponent_l -anchor e -pady 2 \
1858        7,2 $inner.specularExponent          -cspan 3 -fill x \
1859        8,1 $inner.visibility    -anchor w -cspan 3 \
1860        9,1 $inner.quality_l -anchor e -pady 2 \
1861        9,2 $inner.quality                     -cspan 3 -fill x \
1862        10,0 $inner.transferfunction_l -anchor w              -cspan 4 \
1863        11,1 $inner.opacity_l -anchor e -pady 2 \
1864        11,2 $inner.opacity                    -cspan 3 -fill x \
1865        12,1 $inner.colormap_l -anchor e  \
1866        12,2 $inner.colormap                 -padx 2 -cspan 3 -fill x \
1867        13,1 $inner.blendmode_l -anchor e  \
1868        13,2 $inner.blendmode               -padx 2 -cspan 3 -fill x \
1869        14,1 $inner.thin             -anchor e \
1870        14,2 $inner.thickness                 -cspan 2 -fill x \
1871        14,4 $inner.thick -anchor w 
1872
1873    blt::table configure $inner r* c* -resize none
1874    blt::table configure $inner r* -pady { 2 0 }
1875    blt::table configure $inner c2 c3 r15 -resize expand
1876    blt::table configure $inner c0 -width .1i
1877}
1878
1879itcl::body Rappture::VtkVolumeViewer::BuildAxisTab {} {
1880    set fg [option get $itk_component(hull) font Font]
1881    #set bfg [option get $itk_component(hull) boldFont Font]
1882
1883    set inner [$itk_component(main) insert end \
1884        -title "Axis Settings" \
1885        -icon [Rappture::icon axis2]]
1886    $inner configure -borderwidth 4
1887
1888    checkbutton $inner.visible \
1889        -text "Axes" \
1890        -variable [itcl::scope _settings(-axesvisible)] \
1891        -command [itcl::code $this AdjustSetting -axesvisible] \
1892        -font "Arial 9"
1893
1894    checkbutton $inner.labels \
1895        -text "Axis Labels" \
1896        -variable [itcl::scope _settings(-axislabels)] \
1897        -command [itcl::code $this AdjustSetting -axislabels] \
1898        -font "Arial 9"
1899    label $inner.grid_l -text "Grid" -font "Arial 9"
1900    checkbutton $inner.xgrid \
1901        -text "X" \
1902        -variable [itcl::scope _settings(-xgrid)] \
1903        -command [itcl::code $this AdjustSetting -xgrid] \
1904        -font "Arial 9"
1905    checkbutton $inner.ygrid \
1906        -text "Y" \
1907        -variable [itcl::scope _settings(-ygrid)] \
1908        -command [itcl::code $this AdjustSetting -ygrid] \
1909        -font "Arial 9"
1910    checkbutton $inner.zgrid \
1911        -text "Z" \
1912        -variable [itcl::scope _settings(-zgrid)] \
1913        -command [itcl::code $this AdjustSetting -zgrid] \
1914        -font "Arial 9"
1915    checkbutton $inner.minorticks \
1916        -text "Minor Ticks" \
1917        -variable [itcl::scope _settings(-axisminorticks)] \
1918        -command [itcl::code $this AdjustSetting -axisminorticks] \
1919        -font "Arial 9"
1920
1921    label $inner.mode_l -text "Mode" -font "Arial 9"
1922
1923    itk_component add axismode {
1924        Rappture::Combobox $inner.mode -width 10 -editable no
1925    }
1926    $inner.mode choices insert end \
1927        "static_triad"    "static" \
1928        "closest_triad"   "closest" \
1929        "furthest_triad"  "farthest" \
1930        "outer_edges"     "outer"         
1931    $itk_component(axismode) value $_settings(-axisflymode)
1932    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axisflymode]
1933
1934    blt::table $inner \
1935        0,0 $inner.visible -anchor w -cspan 4 \
1936        1,0 $inner.labels  -anchor w -cspan 4 \
1937        2,0 $inner.minorticks  -anchor w -cspan 4 \
1938        4,0 $inner.grid_l  -anchor w \
1939        4,1 $inner.xgrid   -anchor w \
1940        4,2 $inner.ygrid   -anchor w \
1941        4,3 $inner.zgrid   -anchor w \
1942        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1943        5,1 $inner.mode    -fill x   -cspan 3
1944
1945    blt::table configure $inner r* c* -resize none
1946    blt::table configure $inner r7 c6 -resize expand
1947    blt::table configure $inner r3 -height 0.125i
1948}
1949
1950itcl::body Rappture::VtkVolumeViewer::BuildCameraTab {} {
1951    set inner [$itk_component(main) insert end \
1952        -title "Camera Settings" \
1953        -icon [Rappture::icon camera]]
1954    $inner configure -borderwidth 4
1955
1956    label $inner.view_l -text "view" -font "Arial 9"
1957    set f [frame $inner.view]
1958    foreach side { front back left right top bottom } {
1959        button $f.$side  -image [Rappture::icon view$side] \
1960            -command [itcl::code $this SetOrientation $side]
1961        Rappture::Tooltip::for $f.$side "Change the view to $side"
1962        pack $f.$side -side left
1963    }
1964    blt::table $inner \
1965        0,0 $inner.view_l -anchor e -pady 2 \
1966        0,1 $inner.view -anchor w -pady 2
1967    blt::table configure $inner r0 -resize none
1968
1969    set row 1
1970    set labels { qx qy qz qw xpan ypan zoom }
1971    foreach tag $labels {
1972        label $inner.${tag}-label -text $tag -font "Arial 9"
1973        entry $inner.${tag} -font "Arial 9"  -bg white \
1974            -textvariable [itcl::scope _view(-$tag)]
1975        bind $inner.${tag} <Return> \
1976            [itcl::code $this camera set -${tag}]
1977        bind $inner.${tag} <KP_Enter> \
1978            [itcl::code $this camera set -${tag}]
1979        blt::table $inner \
1980            $row,0 $inner.${tag}-label -anchor e -pady 2 \
1981            $row,1 $inner.${tag} -anchor w -pady 2
1982        blt::table configure $inner r$row -resize none
1983        incr row
1984    }
1985    checkbutton $inner.ortho \
1986        -text "Orthographic Projection" \
1987        -variable [itcl::scope _view(-ortho)] \
1988        -command [itcl::code $this camera set -ortho] \
1989        -font "Arial 9"
1990    blt::table $inner \
1991            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1992    blt::table configure $inner r$row -resize none
1993    incr row
1994
1995    blt::table configure $inner c0 c1 -resize none
1996    blt::table configure $inner c2 -resize expand
1997    blt::table configure $inner r$row -resize expand
1998}
1999
2000itcl::body Rappture::VtkVolumeViewer::BuildCutplaneTab {} {
2001
2002    set fg [option get $itk_component(hull) font Font]
2003   
2004    set inner [$itk_component(main) insert end \
2005        -title "Cutplane Settings" \
2006        -icon [Rappture::icon cutbutton]]
2007
2008    $inner configure -borderwidth 4
2009
2010    checkbutton $inner.visible \
2011        -text "Show Cutplanes" \
2012        -variable [itcl::scope _settings(-cutplanesvisible)] \
2013        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
2014        -font "Arial 9"
2015
2016    checkbutton $inner.lighting \
2017        -text "Enable Lighting" \
2018        -variable [itcl::scope _settings(-cutplanelighting)] \
2019        -command [itcl::code $this AdjustSetting -cutplanelighting] \
2020        -font "Arial 9"
2021
2022    label $inner.opacity_l -text "Opacity" -font "Arial 9"
2023    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2024        -variable [itcl::scope _settings(-cutplaneopacity)] \
2025        -width 10 \
2026        -showvalue off \
2027        -command [itcl::code $this AdjustSetting -cutplaneopacity]
2028    $inner.opacity set $_settings(-cutplaneopacity)
2029
2030    # X-value slicer...
2031    itk_component add xCutButton {
2032        Rappture::PushButton $inner.xbutton \
2033            -onimage [Rappture::icon x-cutplane] \
2034            -offimage [Rappture::icon x-cutplane] \
2035            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
2036            -variable [itcl::scope _settings(-xcutplanevisible)]
2037    }
2038    Rappture::Tooltip::for $itk_component(xCutButton) \
2039        "Toggle the X-axis cutplane on/off"
2040    $itk_component(xCutButton) select
2041
2042    itk_component add xCutScale {
2043        ::scale $inner.xval -from 100 -to 0 \
2044            -width 10 -orient vertical -showvalue yes \
2045            -borderwidth 1 -highlightthickness 0 \
2046            -command [itcl::code $this EventuallySetCutplane x] \
2047            -variable [itcl::scope _settings(-xcutplaneposition)]
2048    } {
2049        usual
2050        ignore -borderwidth -highlightthickness
2051    }
2052    # Set the default cutplane value before disabling the scale.
2053    $itk_component(xCutScale) set 50
2054    $itk_component(xCutScale) configure -state disabled
2055    Rappture::Tooltip::for $itk_component(xCutScale) \
2056        "@[itcl::code $this Slice tooltip x]"
2057
2058    # Y-value slicer...
2059    itk_component add yCutButton {
2060        Rappture::PushButton $inner.ybutton \
2061            -onimage [Rappture::icon y-cutplane] \
2062            -offimage [Rappture::icon y-cutplane] \
2063            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
2064            -variable [itcl::scope _settings(-ycutplanevisible)]
2065    }
2066    Rappture::Tooltip::for $itk_component(yCutButton) \
2067        "Toggle the Y-axis cutplane on/off"
2068    $itk_component(yCutButton) select
2069
2070    itk_component add yCutScale {
2071        ::scale $inner.yval -from 100 -to 0 \
2072            -width 10 -orient vertical -showvalue yes \
2073            -borderwidth 1 -highlightthickness 0 \
2074            -command [itcl::code $this EventuallySetCutplane y] \
2075            -variable [itcl::scope _settings(-ycutplaneposition)]
2076    } {
2077        usual
2078        ignore -borderwidth -highlightthickness
2079    }
2080    Rappture::Tooltip::for $itk_component(yCutScale) \
2081        "@[itcl::code $this Slice tooltip y]"
2082    # Set the default cutplane value before disabling the scale.
2083    $itk_component(yCutScale) set 50
2084    $itk_component(yCutScale) configure -state disabled
2085
2086    # Z-value slicer...
2087    itk_component add zCutButton {
2088        Rappture::PushButton $inner.zbutton \
2089            -onimage [Rappture::icon z-cutplane] \
2090            -offimage [Rappture::icon z-cutplane] \
2091            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
2092            -variable [itcl::scope _settings(-zcutplanevisible)]
2093    }
2094    Rappture::Tooltip::for $itk_component(zCutButton) \
2095        "Toggle the Z-axis cutplane on/off"
2096    $itk_component(zCutButton) select
2097
2098    itk_component add zCutScale {
2099        ::scale $inner.zval -from 100 -to 0 \
2100            -width 10 -orient vertical -showvalue yes \
2101            -borderwidth 1 -highlightthickness 0 \
2102            -command [itcl::code $this EventuallySetCutplane z] \
2103            -variable [itcl::scope _settings(-zcutplaneposition)]
2104    } {
2105        usual
2106        ignore -borderwidth -highlightthickness
2107    }
2108    $itk_component(zCutScale) set 50
2109    $itk_component(zCutScale) configure -state disabled
2110    Rappture::Tooltip::for $itk_component(zCutScale) \
2111        "@[itcl::code $this Slice tooltip z]"
2112
2113    blt::table $inner \
2114        0,0 $inner.visible              -anchor w -pady 2 -cspan 4 \
2115        1,0 $inner.lighting             -anchor w -pady 2 -cspan 4 \
2116        2,0 $inner.opacity_l            -anchor w -pady 2 -cspan 3 \
2117        3,0 $inner.opacity              -fill x   -pady 2 -cspan 3 \
2118        4,0 $itk_component(xCutButton)  -anchor e -padx 2 -pady 2 \
2119        5,0 $itk_component(xCutScale)   -fill y \
2120        4,1 $itk_component(yCutButton)  -anchor e -padx 2 -pady 2 \
2121        5,1 $itk_component(yCutScale)   -fill y \
2122        4,2 $itk_component(zCutButton)  -anchor e -padx 2 -pady 2 \
2123        5,2 $itk_component(zCutScale)   -fill y
2124
2125    blt::table configure $inner r* c* -resize none
2126    blt::table configure $inner r5 c3 -resize expand
2127}
2128
2129#
2130#  camera --
2131#
2132itcl::body Rappture::VtkVolumeViewer::camera {option args} {
2133    switch -- $option {
2134        "show" {
2135            puts [array get _view]
2136        }
2137        "set" {
2138            set who [lindex $args 0]
2139            set x $_view($who)
2140            set code [catch { string is double $x } result]
2141            if { $code != 0 || !$result } {
2142                return
2143            }
2144            switch -- $who {
2145                "-ortho" {
2146                    if {$_view(-ortho)} {
2147                        SendCmd "camera mode ortho"
2148                    } else {
2149                        SendCmd "camera mode persp"
2150                    }
2151                }
2152                "-xpan" - "-ypan" {
2153                    PanCamera
2154                }
2155                "-qx" - "-qy" - "-qz" - "-qw" {
2156                    set q [ViewToQuaternion]
2157                    $_arcball quaternion $q
2158                    EventuallyRotate $q
2159                }
2160                "-zoom" {
2161                    SendCmd "camera zoom $_view(-zoom)"
2162                }
2163            }
2164        }
2165    }
2166}
2167
2168itcl::body Rappture::VtkVolumeViewer::GetVtkData { args } {
2169    set bytes ""
2170    foreach dataobj [get] {
2171        foreach comp [$dataobj components] {
2172            set tag $dataobj-$comp
2173            set contents [$dataobj vtkdata $comp]
2174            append bytes "$contents\n"
2175        }
2176    }
2177    return [list .vtk $bytes]
2178}
2179
2180itcl::body Rappture::VtkVolumeViewer::GetImage { args } {
2181    if { [image width $_image(download)] > 0 &&
2182         [image height $_image(download)] > 0 } {
2183        set bytes [$_image(download) data -format "jpeg -quality 100"]
2184        set bytes [Rappture::encoding::decode -as b64 $bytes]
2185        return [list .jpg $bytes]
2186    }
2187    return ""
2188}
2189
2190itcl::body Rappture::VtkVolumeViewer::BuildDownloadPopup { popup command } {
2191    Rappture::Balloon $popup \
2192        -title "[Rappture::filexfer::label downloadWord] as..."
2193    set inner [$popup component inner]
2194    label $inner.summary -text "" -anchor w
2195    radiobutton $inner.vtk_button -text "VTK data file" \
2196        -variable [itcl::scope _downloadPopup(format)] \
2197        -font "Helvetica 9 " \
2198        -value vtk 
2199    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2200    radiobutton $inner.image_button -text "Image File" \
2201        -variable [itcl::scope _downloadPopup(format)] \
2202        -value image
2203    Rappture::Tooltip::for $inner.image_button \
2204        "Save as digital image."
2205
2206    button $inner.ok -text "Save" \
2207        -highlightthickness 0 -pady 2 -padx 3 \
2208        -command $command \
2209        -compound left \
2210        -image [Rappture::icon download]
2211
2212    button $inner.cancel -text "Cancel" \
2213        -highlightthickness 0 -pady 2 -padx 3 \
2214        -command [list $popup deactivate] \
2215        -compound left \
2216        -image [Rappture::icon cancel]
2217
2218    blt::table $inner \
2219        0,0 $inner.summary -cspan 2  \
2220        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2221        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2222        4,1 $inner.cancel -width .9i -fill y \
2223        4,0 $inner.ok -padx 2 -width .9i -fill y
2224    blt::table configure $inner r3 -height 4
2225    blt::table configure $inner r4 -pady 4
2226    raise $inner.image_button
2227    $inner.vtk_button invoke
2228    return $inner
2229}
2230
2231itcl::body Rappture::VtkVolumeViewer::SetObjectStyle { dataobj cname } {
2232    # Parse style string.
2233    set tag $dataobj-$cname
2234    array set styles {
2235        -color      BCGYR
2236        -lighting   1
2237        -opacity    0.5
2238        -outline    0
2239        -visible    1
2240    }
2241    array set styles [$dataobj style $cname]
2242    set _settings($cname-volumelighting)        $styles(-lighting)
2243    set _settings($cname-volumeopacity)         [expr $styles(-opacity) * 100]
2244    set _settings($cname-volumeoutline)         $styles(-outline)
2245    set _settings($cname-volumevisible)         $styles(-visible)
2246
2247    $itk_component(colormap) value $styles(-color)
2248
2249    SendCmd "outline add $tag"
2250    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2251    SendCmd "outline visible $styles(-outline) $tag"
2252
2253    SendCmd "$_cutplaneCmd add $tag"
2254    SendCmd "$_cutplaneCmd color [Color2RGB $itk_option(-plotforeground)] $tag"
2255    SendCmd "$_cutplaneCmd visible 0 $tag"
2256
2257    SendCmd "volume add $tag"
2258    SendCmd "volume lighting $styles(-lighting) $tag"
2259    SendCmd "volume opacity $styles(-opacity) $tag"
2260    SendCmd "volume visible $styles(-visible) $tag"
2261
2262    SetInitialTransferFunction $dataobj $cname
2263    SendCmd "volume colormap $cname $tag"
2264    SendCmd "$_cutplaneCmd colormap $cname-opaque $tag"
2265}
2266
2267itcl::body Rappture::VtkVolumeViewer::IsValidObject { dataobj } {
2268    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2269        return 0
2270    }
2271    return 1
2272}
2273
2274# ----------------------------------------------------------------------
2275# USAGE: ReceiveLegend <colormap> <title> <vmin> <vmax> <size>
2276#
2277# Invoked automatically whenever the "legend" command comes in from
2278# the rendering server.  Indicates that binary image data with the
2279# specified <size> will follow.
2280# ----------------------------------------------------------------------
2281itcl::body Rappture::VtkVolumeViewer::ReceiveLegend { colormap title vmin vmax size } {
2282    if { [isconnected] } {
2283        set bytes [ReceiveBytes $size]
2284        if { ![info exists _image(legend)] } {
2285            set _image(legend) [image create photo]
2286        }
2287        $_image(legend) configure -data $bytes
2288        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2289        if { [catch {DrawLegend} errs] != 0 } {
2290            puts stderr errs=$errs
2291        }
2292    }
2293}
2294
2295#
2296# DrawLegend --
2297#
2298itcl::body Rappture::VtkVolumeViewer::DrawLegend {} {
2299    if { $_current == "" } {
2300        set _current "component"
2301    }
2302    set cname $_current
2303    set c $itk_component(legend)
2304    set w [winfo width $c]
2305    set h [winfo height $c]
2306    set lx 10
2307    set ly [expr {$h - 1}]
2308    if {"" == [$c find withtag colorbar]} {
2309        $c create image 10 10 -anchor nw \
2310            -image $_image(legend) -tags colorbar
2311        $c create text $lx $ly -anchor sw \
2312            -fill $itk_option(-plotforeground) -tags "limits text vmin"
2313        $c create text [expr {$w-$lx}] $ly -anchor se \
2314            -fill $itk_option(-plotforeground) -tags "limits text vmax"
2315        $c create text [expr {$w/2}] $ly -anchor s \
2316            -fill $itk_option(-plotforeground) -tags "limits text title"
2317        $c lower colorbar
2318        $c bind colorbar <ButtonRelease-1> [itcl::code $this AddNewMarker %x %y]
2319    }
2320
2321    # Display the markers used by the current transfer function.
2322    HideAllMarkers
2323    if { [info exists _transferFunctionEditors($cname)] } {
2324        $_transferFunctionEditors($cname) showMarkers $_limits($cname)
2325    }
2326
2327    foreach {min max} $_limits($cname) break
2328    $c itemconfigure vmin -text [format %g $min]
2329    $c coords vmin $lx $ly
2330
2331    $c itemconfigure vmax -text [format %g $max]
2332    $c coords vmax [expr {$w-$lx}] $ly
2333
2334    set title ""
2335    if { $_first != "" } {
2336        set title [$_first hints label]
2337        set units [$_first hints units]
2338        if { $units != "" } {
2339            set title "$title ($units)"
2340        }
2341    }
2342    $c itemconfigure title -text $title
2343    $c coords title [expr {$w/2}] $ly
2344}
2345
2346#
2347# DrawLegendOld --
2348#
2349#       Draws the legend in it's own canvas which resides to the right
2350#       of the contour plot area.
2351#
2352itcl::body Rappture::VtkVolumeViewer::DrawLegendOld { } {
2353    set fname $_curFldName
2354    set c $itk_component(view)
2355    set w [winfo width $c]
2356    set h [winfo height $c]
2357    set font "Arial 8"
2358    set lineht [font metrics $font -linespace]
2359   
2360    if { [info exists _fields($fname)] } {
2361        foreach { title units } $_fields($fname) break
2362        if { $units != "" } {
2363            set title [format "%s (%s)" $title $units]
2364        }
2365    } else {
2366        set title $fname
2367    }
2368    if { $_settings(-legendvisible) } {
2369        set x [expr $w - 2]
2370        if { [$c find withtag "legend"] == "" } {
2371            set y 2
2372            $c create text $x $y \
2373                -anchor ne \
2374                -fill $itk_option(-plotforeground) -tags "title legend" \
2375                -font $font
2376            incr y $lineht
2377            $c create text $x $y \
2378                -anchor ne \
2379                -fill $itk_option(-plotforeground) -tags "vmax legend" \
2380                -font $font
2381            incr y $lineht
2382            $c create image $x $y \
2383                -anchor ne \
2384                -image $_image(legend) -tags "colormap legend"
2385            $c create text $x [expr {$h-2}] \
2386                -anchor se \
2387                -fill $itk_option(-plotforeground) -tags "vmin legend" \
2388                -font $font
2389            #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2390            $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2391            $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2392        }
2393        $c bind title <ButtonPress> [itcl::code $this Combo post]
2394        $c bind title <Enter> [itcl::code $this Combo activate]
2395        $c bind title <Leave> [itcl::code $this Combo deactivate]
2396        # Reset the item coordinates according the current size of the plot.
2397        $c itemconfigure title -text $title
2398        if { [info exists _limits($_curFldName)] } {
2399            foreach { vmin vmax } $_limits($_curFldName) break
2400            $c itemconfigure vmin -text [format %g $vmin]
2401            $c itemconfigure vmax -text [format %g $vmax]
2402        }
2403        set y 2
2404        $c coords title $x $y
2405        incr y $lineht
2406        $c coords vmax $x $y
2407        incr y $lineht
2408        $c coords colormap $x $y
2409        $c coords vmin $x [expr {$h - 2}]
2410    }
2411}
2412
2413#
2414# EnterLegend --
2415#
2416itcl::body Rappture::VtkVolumeViewer::EnterLegend { x y } {
2417    SetLegendTip $x $y
2418}
2419
2420#
2421# MotionLegend --
2422#
2423itcl::body Rappture::VtkVolumeViewer::MotionLegend { x y } {
2424    Rappture::Tooltip::tooltip cancel
2425    set c $itk_component(view)
2426    SetLegendTip $x $y
2427}
2428
2429#
2430# LeaveLegend --
2431#
2432itcl::body Rappture::VtkVolumeViewer::LeaveLegend { } {
2433    Rappture::Tooltip::tooltip cancel
2434    .rappturetooltip configure -icon ""
2435}
2436
2437#
2438# SetLegendTip --
2439#
2440itcl::body Rappture::VtkVolumeViewer::SetLegendTip { x y } {
2441    set c $itk_component(view)
2442    set w [winfo width $c]
2443    set h [winfo height $c]
2444    set font "Arial 8"
2445    set lineht [font metrics $font -linespace]
2446   
2447    set imgHeight [image height $_image(legend)]
2448    set coords [$c coords colormap]
2449    set imgX [expr $w - [image width $_image(legend)] - 2]
2450    set imgY [expr $y - 2 * ($lineht + 2)]
2451
2452    if { [info exists _fields($_title)] } {
2453        foreach { title units } $_fields($_title) break
2454        if { $units != "" } {
2455            set title [format "%s (%s)" $title $units]
2456        }
2457    } else {
2458        set title $_title
2459    }
2460    # Make a swatch of the selected color
2461    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2462        #puts stderr "out of range: $imgY"
2463        return
2464    }
2465    if { ![info exists _image(swatch)] } {
2466        set _image(swatch) [image create photo -width 24 -height 24]
2467    }
2468    set color [eval format "\#%02x%02x%02x" $pixel]
2469    $_image(swatch) put black  -to 0 0 23 23
2470    $_image(swatch) put $color -to 1 1 22 22
2471    .rappturetooltip configure -icon $_image(swatch)
2472
2473    # Compute the value of the point
2474    if { [info exists _limits($_curFldName)] } {
2475        foreach { vmin vmax } $_limits($_curFldName) break
2476        set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2477        set value [expr $t * ($vmax - $vmin) + $vmin]
2478    } else {
2479        set value 0.0
2480    }
2481    set tipx [expr $x + 15]
2482    set tipy [expr $y - 5]
2483    Rappture::Tooltip::text $c "$title $value"
2484    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2485}
2486
2487# ----------------------------------------------------------------------
2488# USAGE: Slice move x|y|z <newval>
2489#
2490# Called automatically when the user drags the slider to move the
2491# cut plane that slices 3D data.  Gets the current value from the
2492# slider and moves the cut plane to the appropriate point in the
2493# data set.
2494# ----------------------------------------------------------------------
2495itcl::body Rappture::VtkVolumeViewer::Slice {option args} {
2496    switch -- $option {
2497        "move" {
2498            set axis [lindex $args 0]
2499            set newval [lindex $args 1]
2500            if {[llength $args] != 2} {
2501                error "wrong # args: should be \"Slice move x|y|z newval\""
2502            }
2503            set newpos [expr {0.01*$newval}]
2504            SendCmd "$_cutplaneCmd slice $axis $newpos"
2505        }
2506        "tooltip" {
2507            set axis [lindex $args 0]
2508            set val [$itk_component(${axis}CutScale) get]
2509            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2510        }
2511        default {
2512            error "bad option \"$option\": should be axis, move, or tooltip"
2513        }
2514    }
2515}
2516
2517# ----------------------------------------------------------------------
2518# USAGE: _dropdown post
2519# USAGE: _dropdown unpost
2520# USAGE: _dropdown select
2521#
2522# Used internally to handle the dropdown list for this combobox.  The
2523# post/unpost options are invoked when the list is posted or unposted
2524# to manage the relief of the controlling button.  The select option
2525# is invoked whenever there is a selection from the list, to assign
2526# the value back to the gauge.
2527# ----------------------------------------------------------------------
2528itcl::body Rappture::VtkVolumeViewer::Combo {option} {
2529    set c $itk_component(view)
2530    switch -- $option {
2531        post {
2532            foreach { x1 y1 x2 y2 } [$c bbox title] break
2533            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2534            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2535            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2536            tk_popup $itk_component(fieldmenu) $x $y
2537        }
2538        activate {
2539            $c itemconfigure title -fill red
2540        }
2541        deactivate {
2542            $c itemconfigure title -fill white
2543        }
2544        invoke {
2545            $itk_component(field) value _curFldLabel
2546            AdjustSetting -field
2547        }
2548        default {
2549            error "bad option \"$option\": should be post, unpost, select"
2550        }
2551    }
2552}
2553
2554#
2555# The -levels option takes a single value that represents the number
2556# of evenly distributed markers based on the current data range. Each
2557# marker is a relative value from 0.0 to 1.0.
2558#
2559itcl::body Rappture::VtkVolumeViewer::ParseLevelsOption { cname levels } {
2560    set c $itk_component(legend)
2561    set list {}
2562    regsub -all "," $levels " " levels
2563    if {[string is int $levels]} {
2564        for {set i 1} { $i <= $levels } {incr i} {
2565            lappend list [expr {double($i)/($levels+1)}]
2566        }
2567    } else {
2568        foreach x $levels {
2569            lappend list $x
2570        }
2571    }
2572    set _parsedFunction($cname) 1
2573    $_transferFunctionEditors($cname) addMarkers $list
2574}
2575
2576#
2577# The -markers option takes a list of zero or more values (the values
2578# may be separated either by spaces or commas) that have the following
2579# format:
2580#
2581#   N%  Percent of current total data range.  Converted to
2582#       to a relative value between 0.0 and 1.0.
2583#   N   Absolute value of marker.  If the marker is outside of
2584#       the current range, it will be displayed on the outer
2585#       edge of the legends, but it range it represents will
2586#       not be seen.
2587#
2588itcl::body Rappture::VtkVolumeViewer::ParseMarkersOption { cname markers } {
2589    set c $itk_component(legend)
2590    set list {}
2591    foreach { min max } $_limits($cname) break
2592    regsub -all "," $markers " " markers
2593    foreach marker $markers {
2594        set n [scan $marker "%g%s" value suffix]
2595        if { $n == 2 && $suffix == "%" } {
2596            # $n% : Set relative value (0..1).
2597            lappend list [expr {$value * 0.01}]
2598        } else {
2599            # $n : absolute value, compute relative
2600            lappend list  [expr {(double($value)-$min)/($max-$min)]}
2601        }
2602    }
2603    set _parsedFunction($cname) 1
2604    $_transferFunctionEditors($cname) addMarkers $list
2605}
2606
2607#
2608# SetInitialTransferFunction --
2609#
2610#       Creates a transfer function name based on the <style> settings in the
2611#       library run.xml file. This placeholder will be used later to create
2612#       and send the actual transfer function once the data info has been sent
2613#       to us by the render server. [We won't know the volume limits until the
2614#       server parses the 3D data and sends back the limits via ReceiveData.]
2615#
2616itcl::body Rappture::VtkVolumeViewer::SetInitialTransferFunction { dataobj cname } {
2617    set tag $dataobj-$cname
2618    if { ![info exists _cname2transferFunction($cname)] } {
2619        ComputeTransferFunction $cname
2620    }
2621    set _dataset2style($tag) $cname
2622    lappend _style2datasets($cname) $tag
2623
2624    return $cname
2625}
2626
2627#
2628# ComputeTransferFunction --
2629#
2630#       Computes and sends the transfer function to the render server.  It's
2631#       assumed that the volume data limits are known and that the global
2632#       transfer-functions slider values have been set up.  Both parts are
2633#       needed to compute the relative value (location) of the marker, and
2634#       the alpha map of the transfer function.
2635#
2636itcl::body Rappture::VtkVolumeViewer::ComputeTransferFunction { cname } {
2637
2638    if { ![info exists _transferFunctionEditors($cname)] } {
2639        set _transferFunctionEditors($cname) \
2640            [Rappture::TransferFunctionEditor ::\#auto $itk_component(legend) \
2641                 $cname \
2642                 -command [itcl::code $this updateTransferFunctions]]
2643    }
2644
2645    # We have to parse the style attributes for a volume using this
2646    # transfer-function *once*.  This sets up the initial isomarkers for the
2647    # transfer function.  The user may add/delete markers, so we have to
2648    # maintain a list of markers for each transfer-function.  We use the one
2649    # of the volumes (the first in the list) using the transfer-function as a
2650    # reference.
2651
2652    if { ![info exists _parsedFunction($cname)] || ![info exists _cname2transferFunction($cname)] } {
2653        array set styles {
2654            -color BCGYR
2655            -alphamap ""
2656            -levels 6
2657            -markers ""
2658        }
2659        # Accumulate the style from all the datasets using it.
2660        foreach tag [GetDatasetsWithComponent $cname] {
2661            foreach {dataobj cname} [split [lindex $tag 0] -] break
2662            set option [lindex [$dataobj components -style $cname] 0]
2663            array set styles $option
2664        }
2665        set _settings($cname-color) $styles(-color)
2666        set cmap [ColorsToColormap $styles(-color)]
2667        set _cname2defaultcolormap($cname) $cmap
2668        if { [info exists _transferFunctionEditors($cname)] } {
2669            eval $_transferFunctionEditors($cname) limits $_limits($cname)
2670        }
2671        if { [info exists styles(-markers)] &&
2672             [llength $styles(-markers)] > 0 } {
2673            ParseMarkersOption $cname $styles(-markers)
2674        } else {
2675            ParseLevelsOption $cname $styles(-levels)
2676        }
2677        if { $styles(-alphamap) != "" } {
2678            set _alphamap($cname) $styles(-alphamap)
2679        }
2680    } else {
2681        foreach {cmap amap} $_cname2transferFunction($cname) break
2682    }
2683    if { ![info exists _alphamap($cname)] } {
2684        set amap [ComputeAlphamap $cname]
2685    } else {
2686        set amap $_alphamap($cname)
2687    }
2688    set opaqueAmap "0.0 1.0 1.0 1.0"
2689    set _cname2transferFunction($cname) [list $cmap $amap]
2690    SendCmd [list colormap define $cname $cmap $amap]
2691    SendCmd [list colormap define $cname-opaque $cmap $opaqueAmap]
2692}
2693
2694#
2695# ResetColormap --
2696#
2697#       Changes only the colormap portion of the transfer function.
2698#
2699itcl::body Rappture::VtkVolumeViewer::ResetColormap { cname color } {
2700    # Get the current transfer function
2701    if { ![info exists _cname2transferFunction($cname)] } {
2702        return
2703    }
2704    foreach { cmap amap } $_cname2transferFunction($cname) break
2705    set cmap [GetColormap $cname $color]
2706    set _cname2transferFunction($cname) [list $cmap $amap]
2707    set opaqueAmap "0.0 1.0 1.0 1.0"
2708    SendCmd [list colormap define $cname $cmap $amap]
2709    SendCmd [list colormap define $cname-opaque $cmap $opaqueAmap]
2710    EventuallyRequestLegend
2711}
2712
2713# ----------------------------------------------------------------------
2714# USAGE: updateTransferFunctions
2715#
2716#       This is called by the transfer function editor whenever the
2717#       transfer function definition changes.
2718#
2719# ----------------------------------------------------------------------
2720itcl::body Rappture::VtkVolumeViewer::updateTransferFunctions {} {
2721    foreach cname [array names _volcomponents] {
2722        ComputeTransferFunction $cname
2723    }
2724    EventuallyRequestLegend
2725}
2726
2727itcl::body Rappture::VtkVolumeViewer::AddNewMarker { x y } {
2728    if { ![info exists _transferFunctionEditors($_current)] } {
2729        continue
2730    }
2731    # Add a new marker to the current transfer function
2732    $_transferFunctionEditors($_current) newMarker $x $y normal
2733}
2734
2735itcl::body Rappture::VtkVolumeViewer::RemoveMarker { x y } {
2736    if { ![info exists _transferFunctionEditors($_current)] } {
2737        continue
2738    }
2739    # Add a new marker to the current transfer function
2740    $_transferFunctionEditors($_current) deleteMarker $x $y
2741}
2742
2743itcl::body Rappture::VtkVolumeViewer::SetOrientation { side } {
2744    array set positions {
2745        front "1 0 0 0"
2746        back  "0 0 1 0"
2747        left  "0.707107 0 -0.707107 0"
2748        right "0.707107 0 0.707107 0"
2749        top   "0.707107 -0.707107 0 0"
2750        bottom "0.707107 0.707107 0 0"
2751    }
2752    foreach name { -qw -qx -qy -qz } value $positions($side) {
2753        set _view($name) $value
2754    }
2755    set q [ViewToQuaternion]
2756    $_arcball quaternion $q
2757    SendCmd "camera orient $q"
2758    SendCmd "camera reset"
2759    set _view(-xpan) 0
2760    set _view(-ypan) 0
2761    set _view(-zoom) 1.0
2762}
2763
2764#
2765# InitComponentSettings --
2766#
2767#       Initializes the volume settings for a specific component. This
2768#       should match what's used as global settings above. This
2769#       is called the first time we try to switch to a given component
2770#       in SwitchComponent below.
2771#
2772itcl::body Rappture::VtkVolumeViewer::InitComponentSettings { cname } {
2773    array set _settings [subst {
2774        $cname-color                    default
2775        $cname-volumeambient            40
2776        $cname-volumeblendmode          composite
2777        $cname-volumediffuse            60
2778        $cname-volumelight2side         1
2779        $cname-volumelighting           1
2780        $cname-volumeopacity            50
2781        $cname-volumeoutline            0
2782        $cname-volumequality            80
2783        $cname-volumespecularexponent   90
2784        $cname-volumespecularlevel      30
2785        $cname-volumethickness          350
2786        $cname-volumevisible            1
2787    }]
2788}
2789
2790#
2791# SwitchComponent --
2792#
2793#       This is called when the current component is changed by the
2794#       dropdown menu in the volume tab.  It synchronizes the global
2795#       volume settings with the settings of the new current component.
2796#
2797itcl::body Rappture::VtkVolumeViewer::SwitchComponent { cname } {
2798    if { ![info exists _settings(${cname}-volumeambient)] } {
2799        InitComponentSettings $cname
2800    }
2801    # _settings variables change widgets, except for colormap
2802    foreach name {
2803        -volumeambient
2804        -volumeblendmode
2805        -volumediffuse
2806        -volumelight2side
2807        -volumelighting
2808        -volumeopacity
2809        -volumeoutline
2810        -volumequality
2811        -volumespecularexponent
2812        -volumespecularlevel
2813        -volumethickness
2814        -volumevisible
2815    } {
2816        set _settings($name) $_settings(${cname}${name})
2817    }
2818    $itk_component(colormap) value        $_settings($cname-color)
2819    set _current $cname;                # Reset the current component
2820}
2821
2822itcl::body Rappture::VtkVolumeViewer::ComputeAlphamap { cname } {
2823    if { ![info exists _transferFunctionEditors($cname)] } {
2824        return [list 0.0 0.0 1.0 1.0]
2825    }
2826    if { ![info exists _settings($cname-volumeambient)] } {
2827        InitComponentSettings $cname
2828    }
2829
2830    set isovalues [$_transferFunctionEditors($cname) values]
2831
2832    # Currently using volume opacity to scale opacity in
2833    # the volume shader. The transfer function always sets full
2834    # opacity
2835    set max 1.0;
2836
2837    # Use the component-wise thickness setting from the slider
2838    # settings widget
2839    # Scale values between 0.00001 and 0.01000
2840    set delta [expr {double($_settings($cname-volumethickness)) * 0.0001}]
2841    set first [lindex $isovalues 0]
2842    set last [lindex $isovalues end]
2843    set amap ""
2844    if { $first == "" || $first != 0.0 } {
2845        lappend amap 0.0 0.0
2846    }
2847    foreach x $isovalues {
2848        set x1 [expr {$x-$delta-0.00001}]
2849        set x2 [expr {$x-$delta}]
2850        set x3 [expr {$x+$delta}]
2851        set x4 [expr {$x+$delta+0.00001}]
2852        if { $x1 < 0.0 } {
2853            set x1 0.0
2854        } elseif { $x1 > 1.0 } {
2855            set x1 1.0
2856        }
2857        if { $x2 < 0.0 } {
2858            set x2 0.0
2859        } elseif { $x2 > 1.0 } {
2860            set x2 1.0
2861        }
2862        if { $x3 < 0.0 } {
2863            set x3 0.0
2864        } elseif { $x3 > 1.0 } {
2865            set x3 1.0
2866        }
2867        if { $x4 < 0.0 } {
2868            set x4 0.0
2869        } elseif { $x4 > 1.0 } {
2870            set x4 1.0
2871        }
2872        # add spikes in the middle
2873        lappend amap $x1 0.0
2874        lappend amap $x2 $max
2875        lappend amap $x3 $max
2876        lappend amap $x4 0.0
2877    }
2878    if { $last == "" || $last != 1.0 } {
2879        lappend amap 1.0 0.0
2880    }
2881    return $amap
2882}
2883
2884#
2885# HideAllMarkers --
2886#
2887#       Hide all the markers in all the transfer functions.  Can't simply
2888#       delete and recreate markers from the <style> since the user may
2889#       have create, deleted, or moved markers.
2890#
2891itcl::body Rappture::VtkVolumeViewer::HideAllMarkers {} {
2892    foreach cname [array names _transferFunctionEditors] {
2893        $_transferFunctionEditors($cname) hideMarkers
2894    }
2895}
2896
2897#
2898# GetDatasetsWithComponents --
2899#
2900#       Returns a list of all the datasets (known by the combination of
2901#       their data object and component name) that match the given
2902#       component name.  For example, this is used where we want to change
2903#       the settings of volumes that have the current component.
2904#
2905itcl::body Rappture::VtkVolumeViewer::GetDatasetsWithComponent { cname } {
2906    if { ![info exists _volcomponents($cname)] } {
2907        return ""
2908    }
2909    return $_volcomponents($cname)
2910}
2911
2912#
2913# BuildVolumeComponents --
2914#
2915#       This is called from the "scale" method which is called when a
2916#       new dataset is added or deleted.  It repopulates the dropdown
2917#       menu of volume component names.  It sets the current component
2918#       to the first component in the list (of components found).
2919#       Finally, if there is only one component, don't display the
2920#       label or the combobox in the volume settings tab.
2921#
2922itcl::body Rappture::VtkVolumeViewer::BuildVolumeComponents {} {
2923    $itk_component(volcomponents) choices delete 0 end
2924    foreach name $_componentsList {
2925        $itk_component(volcomponents) choices insert end $name $name
2926    }
2927    set _current [lindex $_componentsList 0]
2928    $itk_component(volcomponents) value $_current
2929    set parent [winfo parent $itk_component(volcomponents)]
2930    if { [llength $_componentsList] <= 1 } {
2931        # Unpack the components label and dropdown if there's only one
2932        # component.
2933        blt::table forget $parent.volcomponents_l $parent.volcomponents
2934    } else {
2935        # Pack the components label and dropdown into the table there's
2936        # more than one component to select.
2937        blt::table $parent \
2938            0,0 $parent.volcomponents_l -anchor e -cspan 2 \
2939            0,2 $parent.volcomponents -cspan 3 -fill x
2940    }
2941}
2942
2943itcl::body Rappture::VtkVolumeViewer::GetColormap { cname color } {
2944    if { $color == "default" } {
2945        return $_cname2defaultcolormap($cname)
2946    }
2947    return [ColorsToColormap $color]
2948}
Note: See TracBrowser for help on using the repository browser.