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

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

whitespace

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