source: tags/1.3.5/gui/scripts/vtkheightmapviewer.tcl @ 4754

Last change on this file since 4754 was 4754, checked in by ldelgass, 7 years ago

merge r4668:4669 from trunk

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