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

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

Use SendData? method to send binary data in viewers, make _outbuf private in
superclass.

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