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

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

Camera setting fixes

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