source: branches/1.6/gui/scripts/vtkvolumeviewer.tcl @ 6363

Last change on this file since 6363 was 6363, checked in by ldelgass, 8 years ago

merge viewer fixes from trunk

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