source: trunk/gui/scripts/vtkheightmapviewer.tcl @ 4685

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

I think this should help with nanohub ticket #267036. See the comment in the
source for a brief explanation. Basically, I don't think the manual settings
are well tested and the CubeAxes? will work best if we let the automatic
formatting do its thing.

File size: 87.9 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-2014  HUBzero Foundation, LLC
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16#package require Img
17
18option add *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
126    private variable _maxScale 100;     # This is the # of times the x-axis
127                                        # and y-axis ranges can differ before
128                                        # automatically turning on
129                                        # -stretchtofit
130
131    private variable _click        ;    # info used for rotate operations
132    private variable _limits       ;    # Holds overall limits for all dataobjs
133                                        # using the viewer.
134    private variable _view         ;    # view params for 3D view
135    private variable _settings
136    private variable _changed
137    private variable _initialStyle "";  # First found style in dataobjects.
138    private variable _reset 1;          # Indicates if camera needs to be reset
139                                        # to starting position.
140    private variable _beforeConnect 1;  # Indicates if camera needs to be reset
141                                        # to starting position.
142
143    private variable _first ""     ;    # This is the topmost dataset.
144    private variable _start 0
145    private variable _isolines
146    private variable _contourList ""
147
148    common _downloadPopup;              # download options from popup
149    private common _hardcopy
150    private variable _width 0
151    private variable _height 0
152    private variable _legendWidth 0
153    private variable _legendHeight 0
154    private variable _resizePending 0
155    private variable _rotatePending 0
156    private variable _legendPending 0
157    private variable _fieldNames {}
158    private variable _fields
159    private variable _curFldName ""
160    private variable _curFldLabel ""
161    private variable _colorMode "scalar";#  Mode of colormap (vmag or scalar)
162}
163
164itk::usual VtkHeightmapViewer {
165    keep -background -foreground -cursor -font
166    keep -plotbackground -plotforeground -mode
167}
168
169# ----------------------------------------------------------------------
170# CONSTRUCTOR
171# ----------------------------------------------------------------------
172itcl::body Rappture::VtkHeightmapViewer::constructor {hostlist args} {
173    set _serverType "vtkvis"
174
175    EnableWaitDialog 900
176    # Rebuild event
177    $_dispatcher register !rebuild
178    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
179
180    # Resize event
181    $_dispatcher register !resize
182    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
183
184    # Rotate event
185    $_dispatcher register !rotate
186    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
187
188    # Legend event
189    $_dispatcher register !legend
190    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
191
192    #
193    # Populate parser with commands handle incoming requests
194    #
195    $_parser alias image [itcl::code $this ReceiveImage]
196    $_parser alias dataset [itcl::code $this ReceiveDataset]
197    $_parser alias legend [itcl::code $this ReceiveLegend]
198
199    # Create image for legend colorbar.
200    set _image(legend) [image create photo]
201
202    # Initialize the view to some default parameters.
203    array set _view {
204        qw      0.36
205        qx      0.25
206        qy      0.50
207        qz      0.70
208        zoom    1.0
209        xpan    0
210        ypan    0
211        ortho   0
212    }
213    set _arcball [blt::arcball create 100 100]
214    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
215    $_arcball quaternion $q
216
217    array set _settings {
218        -axisflymode            "static"
219        -axislabels             1
220        -axisminorticks         1
221        -axisvisible            1
222        -colormap               BCGYR
223        -colormapdiscrete       0
224        -colormapvisible        1
225        -edges                  0
226        -field                  "Default"
227        -heightmapscale         50
228        -isheightmap            0
229        -isolinecolor           black
230        -isolinesvisible        1
231        -legendvisible          1
232        -lighting               1
233        -numisolines            10
234        -opacity                100
235        -outline                0
236        -savelighting           1
237        -saveopacity            100
238        -saveoutline            0
239        -stretchtofit           0
240        -wireframe              0
241        -xgrid                  0
242        -ygrid                  0
243        -zgrid                  0
244    }
245    array set _changed {
246        -colormap               0
247        -numisolines            0
248        -opacity                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        # Setting a custom exponent and label format for axes is causing
941        # a problem with rounding.  Near zero ticks aren't rounded by
942        # the %g format.  The VTK CubeAxes seem to currently work best
943        # when allowed to automatically set the exponent and precision
944        # based on the axis ranges.  This does tend to result in less
945        # visual clutter, so I think it is best to use the automatic
946        # settings by default.  We can test more fine-grained
947        # controls on the axis settings tab if necessary.
948        # -Leif
949        #SendCmd "axis exp 0 0 0 1"
950
951        SendCmd "axis lrot z 90"
952        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
953        $_arcball quaternion $q
954        if {$_settings(-isheightmap) } {
955            if { $_view(ortho)} {
956                SendCmd "camera mode ortho"
957            } else {
958                SendCmd "camera mode persp"
959            }
960            DoRotate
961            SendCmd "camera reset"
962        }
963        PanCamera
964        StopBufferingCommands
965        SendCmd "imgflush"
966        StartBufferingCommands
967    }
968
969    set _first ""
970    # Start off with no datasets are visible.
971    SendCmd "dataset visible 0"
972    set scale [GetHeightmapScale]
973    foreach dataobj [get -objects] {
974        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
975            set _first $dataobj
976        }
977        set _obj2datasets($dataobj) ""
978        foreach comp [$dataobj components] {
979            set tag $dataobj-$comp
980            if { ![info exists _datasets($tag)] } {
981                set bytes [$dataobj vtkdata $comp]
982                if 0 {
983                    set f [open /tmp/vtkheightmap.vtk "w"]
984                    puts $f $bytes
985                    close $f
986                }
987                set length [string length $bytes]
988                if { $_reportClientInfo }  {
989                    set info {}
990                    lappend info "tool_id"       [$dataobj hints toolId]
991                    lappend info "tool_name"     [$dataobj hints toolName]
992                    lappend info "tool_version"  [$dataobj hints toolRevision]
993                    lappend info "tool_title"    [$dataobj hints toolTitle]
994                    lappend info "dataset_label" [$dataobj hints label]
995                    lappend info "dataset_size"  $length
996                    lappend info "dataset_tag"   $tag
997                    SendCmd [list "clientinfo" $info]
998                }
999                SendCmd "dataset add $tag data follows $length"
1000                append _outbuf $bytes
1001                set _datasets($tag) 1
1002                SetObjectStyle $dataobj $comp
1003            }
1004            lappend _obj2datasets($dataobj) $tag
1005            if { [info exists _obj2ovride($dataobj-raise)] } {
1006                # Setting dataset visible enables outline
1007                # and heightmap
1008                SendCmd "dataset visible 1 $tag"
1009            }
1010            if { ![info exists _comp2scale($tag)] ||
1011                 $_comp2scale($tag) != $scale } {
1012                SendCmd "heightmap heightscale $scale $tag"
1013                set _comp2scale($tag) $scale
1014            }
1015        }
1016    }
1017    if { $_first != ""  } {
1018        $itk_component(field) choices delete 0 end
1019        $itk_component(fieldmenu) delete 0 end
1020        array unset _fields
1021        set _curFldName ""
1022        foreach cname [$_first components] {
1023            foreach fname [$_first fieldnames $cname] {
1024                if { [info exists _fields($fname)] } {
1025                    continue
1026                }
1027                foreach { label units components } \
1028                    [$_first fieldinfo $fname] break
1029                $itk_component(field) choices insert end "$fname" "$label"
1030                $itk_component(fieldmenu) add radiobutton -label "$label" \
1031                    -value $label -variable [itcl::scope _curFldLabel] \
1032                    -selectcolor red \
1033                    -activebackground $itk_option(-plotbackground) \
1034                    -activeforeground $itk_option(-plotforeground) \
1035                    -font "Arial 8" \
1036                    -command [itcl::code $this Combo invoke]
1037                set _fields($fname) [list $label $units $components]
1038                if { $_curFldName == "" } {
1039                    set _curFldName $fname
1040                    set _curFldLabel $label
1041                }
1042            }
1043        }
1044        $itk_component(field) value $_curFldLabel
1045    }
1046    InitSettings -stretchtofit -outline
1047
1048    if { $_reset } {
1049        SendCmd "axis tickpos outside"
1050        #SendCmd "axis lformat all %g"
1051       
1052        foreach axis { x y z } {
1053            if { $axis == "z" } {
1054                set label [$_first hints label]
1055            } else {
1056                set label [$_first hints ${axis}label]
1057            }
1058            if { $label == "" } {
1059                if {$axis == "z"} {
1060                    if { [string match "component*" $_curFldName] } {
1061                        set label [string toupper $axis]
1062                    } else {
1063                        set label $_curFldLabel
1064                    }
1065                } else {
1066                    set label [string toupper $axis]
1067                }
1068            }
1069            # May be a space in the axis label.
1070            SendCmd [list axis name $axis $label]
1071
1072            if {$axis == "z" && [$_first hints ${axis}units] == ""} {
1073                set units [lindex $_fields($_curFldName) 1]
1074            } else {
1075                set units [$_first hints ${axis}units]
1076            }
1077            if { $units != "" } {
1078                # May be a space in the axis units.
1079                SendCmd [list axis units $axis $units]
1080            }
1081        }
1082        #
1083        # Reset the camera and other view parameters
1084        #
1085        ResetAxes
1086        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1087        $_arcball quaternion $q
1088        if {$_settings(-isheightmap) } {
1089            if { $_view(ortho)} {
1090                SendCmd "camera mode ortho"
1091            } else {
1092                SendCmd "camera mode persp"
1093            }
1094            DoRotate
1095            SendCmd "camera reset"
1096        }
1097        PanCamera
1098        InitSettings -xgrid -ygrid -zgrid \
1099            -axisvisible -axislabels -heightmapscale -field -isheightmap \
1100            -numisolines
1101        if { [array size _fields] < 2 } {
1102            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1103        }
1104        RequestLegend
1105        set _reset 0
1106    }
1107    global readyForNextFrame
1108    set readyForNextFrame 0;            # Don't advance to the next frame
1109
1110    # Actually write the commands to the server socket.  If it fails, we don't
1111    # care.  We're finished here.
1112    blt::busy hold $itk_component(hull)
1113    StopBufferingCommands
1114    blt::busy release $itk_component(hull)
1115}
1116
1117# ----------------------------------------------------------------------
1118# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1119#
1120# Returns a list of server IDs for the current datasets being displayed.  This
1121# is normally a single ID, but it might be a list of IDs if the current data
1122# object has multiple components.
1123# ----------------------------------------------------------------------
1124itcl::body Rappture::VtkHeightmapViewer::CurrentDatasets {args} {
1125    set flag [lindex $args 0]
1126    switch -- $flag {
1127        "-all" {
1128            if { [llength $args] > 1 } {
1129                error "CurrentDatasets: can't specify dataobj after \"-all\""
1130            }
1131            set dlist [get -objects]
1132        }
1133        "-visible" {
1134            if { [llength $args] > 1 } {
1135                set dlist {}
1136                set args [lrange $args 1 end]
1137                foreach dataobj $args {
1138                    if { [info exists _obj2ovride($dataobj-raise)] } {
1139                        lappend dlist $dataobj
1140                    }
1141                }
1142            } else {
1143                set dlist [get -visible]
1144            }
1145        }           
1146        default {
1147            set dlist $args
1148        }
1149    }
1150    set rlist ""
1151    foreach dataobj $dlist {
1152        foreach comp [$dataobj components] {
1153            set tag $dataobj-$comp
1154            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1155                lappend rlist $tag
1156            }
1157        }
1158    }
1159    return $rlist
1160}
1161
1162itcl::body Rappture::VtkHeightmapViewer::CameraReset {} {
1163    array set _view {
1164        qw      0.36
1165        qx      0.25
1166        qy      0.50
1167        qz      0.70
1168        zoom    1.0
1169        xpan    0
1170        ypan    0
1171    }
1172    if { $_first != "" } {
1173        set location [$_first hints camera]
1174        if { $location != "" } {
1175            array set _view $location
1176        }
1177    }
1178    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1179    $_arcball quaternion $q
1180    if {$_settings(-isheightmap) } {
1181        DoRotate
1182    }
1183    SendCmd "camera reset"
1184}
1185
1186# ----------------------------------------------------------------------
1187# USAGE: Zoom in
1188# USAGE: Zoom out
1189# USAGE: Zoom reset
1190#
1191# Called automatically when the user clicks on one of the zoom
1192# controls for this widget.  Changes the zoom for the current view.
1193# ----------------------------------------------------------------------
1194itcl::body Rappture::VtkHeightmapViewer::Zoom {option} {
1195    switch -- $option {
1196        "in" {
1197            set _view(zoom) [expr {$_view(zoom)*1.25}]
1198            SendCmd "camera zoom $_view(zoom)"
1199        }
1200        "out" {
1201            set _view(zoom) [expr {$_view(zoom)*0.8}]
1202            SendCmd "camera zoom $_view(zoom)"
1203        }
1204        "reset" {
1205            array set _view {
1206                zoom    1.0
1207                xpan    0
1208                ypan    0
1209            }
1210            SendCmd "camera reset"
1211        }
1212    }
1213}
1214
1215itcl::body Rappture::VtkHeightmapViewer::PanCamera {} {
1216    set x $_view(xpan)
1217    set y $_view(ypan)
1218    SendCmd "camera pan $x $y"
1219}
1220
1221
1222# ----------------------------------------------------------------------
1223# USAGE: Rotate click <x> <y>
1224# USAGE: Rotate drag <x> <y>
1225# USAGE: Rotate release <x> <y>
1226#
1227# Called automatically when the user clicks/drags/releases in the
1228# plot area.  Moves the plot according to the user's actions.
1229# ----------------------------------------------------------------------
1230itcl::body Rappture::VtkHeightmapViewer::Rotate {option x y} {
1231    switch -- $option {
1232        "click" {
1233            $itk_component(view) configure -cursor fleur
1234            set _click(x) $x
1235            set _click(y) $y
1236        }
1237        "drag" {
1238            if {[array size _click] == 0} {
1239                Rotate click $x $y
1240            } else {
1241                set w [winfo width $itk_component(view)]
1242                set h [winfo height $itk_component(view)]
1243                if {$w <= 0 || $h <= 0} {
1244                    return
1245                }
1246
1247                if {[catch {
1248                    # this fails sometimes for no apparent reason
1249                    set dx [expr {double($x-$_click(x))/$w}]
1250                    set dy [expr {double($y-$_click(y))/$h}]
1251                }]} {
1252                    return
1253                }
1254                if { $dx == 0 && $dy == 0 } {
1255                    return
1256                }
1257                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1258                EventuallyRotate $q
1259                set _click(x) $x
1260                set _click(y) $y
1261            }
1262        }
1263        "release" {
1264            Rotate drag $x $y
1265            $itk_component(view) configure -cursor ""
1266            catch {unset _click}
1267        }
1268        default {
1269            error "bad option \"$option\": should be click, drag, release"
1270        }
1271    }
1272}
1273
1274itcl::body Rappture::VtkHeightmapViewer::Pick {x y} {
1275    foreach tag [CurrentDatasets -visible] {
1276        SendCmd "dataset getscalar pixel $x $y $tag"
1277    }
1278}
1279
1280# ----------------------------------------------------------------------
1281# USAGE: $this Pan click x y
1282#        $this Pan drag x y
1283#        $this Pan release x y
1284#
1285# Called automatically when the user clicks on one of the zoom
1286# controls for this widget.  Changes the zoom for the current view.
1287# ----------------------------------------------------------------------
1288itcl::body Rappture::VtkHeightmapViewer::Pan {option x y} {
1289    switch -- $option {
1290        "set" {
1291            set w [winfo width $itk_component(view)]
1292            set h [winfo height $itk_component(view)]
1293            set x [expr $x / double($w)]
1294            set y [expr $y / double($h)]
1295            set _view(xpan) [expr $_view(xpan) + $x]
1296            set _view(ypan) [expr $_view(ypan) + $y]
1297            PanCamera
1298            return
1299        }
1300        "click" {
1301            set _click(x) $x
1302            set _click(y) $y
1303            $itk_component(view) configure -cursor hand1
1304        }
1305        "drag" {
1306            if { ![info exists _click(x)] } {
1307                set _click(x) $x
1308            }
1309            if { ![info exists _click(y)] } {
1310                set _click(y) $y
1311            }
1312            set w [winfo width $itk_component(view)]
1313            set h [winfo height $itk_component(view)]
1314            set dx [expr ($_click(x) - $x)/double($w)]
1315            set dy [expr ($_click(y) - $y)/double($h)]
1316            set _click(x) $x
1317            set _click(y) $y
1318            set _view(xpan) [expr $_view(xpan) - $dx]
1319            set _view(ypan) [expr $_view(ypan) - $dy]
1320            PanCamera
1321        }
1322        "release" {
1323            Pan drag $x $y
1324            $itk_component(view) configure -cursor ""
1325        }
1326        default {
1327            error "unknown option \"$option\": should set, click, drag, or release"
1328        }
1329    }
1330}
1331
1332# ----------------------------------------------------------------------
1333# USAGE: InitSettings <what> ?<value>?
1334#
1335# Used internally to update rendering settings whenever parameters
1336# change in the popup settings panel.  Sends the new settings off
1337# to the back end.
1338# ----------------------------------------------------------------------
1339itcl::body Rappture::VtkHeightmapViewer::InitSettings { args } {
1340    foreach spec $args {
1341        if { [info exists _settings($_first${spec})] } {
1342            # Reset global setting with dataobj specific setting
1343            set _settings($spec) $_settings($_first${spec})
1344        }
1345        AdjustSetting $spec
1346    }
1347}
1348
1349#
1350# AdjustSetting --
1351#
1352#       Changes/updates a specific setting in the widget.  There are
1353#       usually user-setable option.  Commands are sent to the render
1354#       server.
1355#
1356itcl::body Rappture::VtkHeightmapViewer::AdjustSetting {what {value ""}} {
1357    if { $_beforeConnect } {
1358        return
1359    }
1360    switch -- $what {
1361        "-axisflymode" {
1362            set mode [$itk_component(axisflymode) value]
1363            set mode [$itk_component(axisflymode) translate $mode]
1364            set _settings($what) $mode
1365            SendCmd "axis flymode $mode"
1366        }
1367        "-axislabels" {
1368            set bool $_settings($what)
1369            SendCmd "axis labels all $bool"
1370        }
1371        "-axisminorticks" {
1372            set bool $_settings($what)
1373            SendCmd "axis minticks all $bool"
1374        }
1375        "-axisvisible" {
1376            set bool $_settings($what)
1377            SendCmd "axis visible all $bool"
1378        }
1379        "-xgrid" - "-ygrid" - "-zgrid" {
1380            set axis [string tolower [string range $what 1 1]]
1381            set bool $_settings($what)
1382            SendCmd "axis grid $axis $bool"
1383        }
1384        "-background" {
1385            set bg [$itk_component(background) value]
1386            array set fgcolors {
1387                "black" "white"
1388                "white" "black"
1389                "grey"  "black"
1390            }
1391            set fg $fgcolors($bg)
1392            configure -plotbackground $bg -plotforeground $fg
1393            $itk_component(view) delete "legend"
1394            SendCmd "screen bgcolor [Color2RGB $bg]"
1395            SendCmd "outline color [Color2RGB $fg]"
1396            SendCmd "axis color all [Color2RGB $fg]"
1397            DrawLegend
1398        }
1399        "-colormap" {
1400            set _changed($what) 1
1401            StartBufferingCommands
1402            set color [$itk_component(colormap) value]
1403            set _settings($what) $color
1404            if { $color == "none" } {
1405                if { $_settings(-colormapvisible) } {
1406                    SendCmd "heightmap surface 0"
1407                    set _settings(-colormapvisible) 0
1408                }
1409            } else {
1410                if { !$_settings(-colormapvisible) } {
1411                    SendCmd "heightmap surface 1"
1412                    set _settings(-colormapvisible) 1
1413                }
1414                SetCurrentColormap $color
1415                if {$_settings(-colormapdiscrete)} {
1416                    set numColors [expr $_settings(-numisolines) + 1]
1417                    SendCmd "colormap res $numColors $color"
1418                }
1419            }
1420            StopBufferingCommands
1421            EventuallyRequestLegend
1422        }
1423        "-colormapvisible" {
1424            set bool $_settings($what)
1425            SendCmd "heightmap surface $bool"
1426        }
1427        "-colormapdiscrete" {
1428            set bool $_settings($what)
1429            set numColors [expr $_settings(-numisolines) + 1]
1430            StartBufferingCommands
1431            if {$bool} {
1432                SendCmd "colormap res $numColors"
1433                # Discrete colormap requires preinterp on
1434                SendCmd "heightmap preinterp on"
1435            } else {
1436                SendCmd "colormap res default"
1437                # FIXME: add setting for preinterp (default on)
1438                SendCmd "heightmap preinterp on"
1439            }
1440            StopBufferingCommands
1441            EventuallyRequestLegend
1442        }
1443        "-edges" {
1444            set bool $_settings($what)
1445            SendCmd "heightmap edges $bool"
1446        }
1447        "-field" {
1448            set label [$itk_component(field) value]
1449            set fname [$itk_component(field) translate $label]
1450            set _settings($what) $fname
1451            if { [info exists _fields($fname)] } {
1452                foreach { label units components } $_fields($fname) break
1453                if { $components > 1 } {
1454                    set _colorMode vmag
1455                } else {
1456                    set _colorMode scalar
1457                }
1458                set _curFldName $fname
1459                set _curFldLabel $label
1460            } else {
1461                puts stderr "unknown field \"$fname\""
1462                return
1463            }
1464            set label [$_first hints label]
1465            if { $label == "" } {
1466                if { [string match "component*" $_curFldName] } {
1467                    set label Z
1468                } else {
1469                    set label $_curFldLabel
1470                }
1471            }
1472            # May be a space in the axis label.
1473            SendCmd [list axis name z $label]
1474
1475            if { [$_first hints zunits] == "" } {
1476                set units [lindex $_fields($_curFldName) 1]
1477            } else {
1478                set units [$_first hints zunits]
1479            }
1480            if { $units != "" } {
1481                # May be a space in the axis units.
1482                SendCmd [list axis units z $units]
1483            }
1484            # Get the new limits because the field changed.
1485            ResetAxes
1486            SendCmd "dataset scalar $_curFldName"
1487            SendCmd "heightmap colormode scalar $_curFldName"
1488            Zoom reset
1489            UpdateContourList
1490            DrawLegend
1491        }
1492        "-heightmapscale" {
1493            if { $_settings(-isheightmap) } {
1494                set scale [GetHeightmapScale]
1495                # Have to set the datasets individually because we are
1496                # tracking them in _comp2scale.
1497                foreach dataset [CurrentDatasets -all] {
1498                    SendCmd "heightmap heightscale $scale $dataset"
1499                    set _comp2scale($dataset) $scale
1500                }
1501                ResetAxes
1502            }
1503        }
1504        "-isheightmap" {
1505            set bool $_settings($what)
1506            set c $itk_component(view)
1507            StartBufferingCommands
1508            # Fix heightmap scale: 0 for contours, 1 for heightmaps.
1509            if { $bool } {
1510                set _settings(-heightmapscale) 50
1511                set _settings(-opacity) $_settings(-saveopacity)
1512                set _settings(-lighting) $_settings(-savelighting)
1513                set _settings(-outline) 0
1514            } else {
1515                set _settings(-heightmapscale) 0
1516                set _settings(-lighting) 0
1517                set _settings(-opacity) 100
1518                set _settings(-outline)  $_settings(-saveoutline)
1519            }
1520            InitSettings -lighting -opacity -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($what)
1610                set bool $_settings($what)
1611                SendCmd "heightmap lighting $bool"
1612            } else {
1613                SendCmd "heightmap lighting 0"
1614            }
1615        }
1616        "-numisolines" {
1617            set _settings($what) [$itk_component(numisolines) value]
1618            set _currentNumIsolines $_settings($what)
1619            UpdateContourList
1620            set _changed($what) 1
1621            SendCmd "heightmap contourlist [list $_contourList]"
1622            if {$_settings(-colormapdiscrete)} {
1623                set numColors [expr $_settings($what) + 1]
1624                SendCmd "colormap res $numColors"
1625                EventuallyRequestLegend
1626            } else {
1627                DrawLegend
1628            }
1629        }
1630        "-opacity" {
1631            set _changed($what) 1
1632            set val [expr $_settings($what) * 0.01]
1633            if { $_settings(-isheightmap) } {
1634                set _settings(-saveopacity) $_settings($what)
1635                SendCmd "heightmap opacity $val"
1636            } else {
1637                SendCmd "heightmap opacity 1.0"
1638            }
1639        }
1640        "-outline" {
1641            if { $_settings(-isheightmap) } {
1642                SendCmd "outline visible 0"
1643            } else {
1644                set _settings(-saveoutline) $_settings($what)
1645                set bool $_settings($what)
1646                SendCmd "outline visible $bool"
1647            }
1648        }
1649        "-stretchtofit" {
1650            set bool $_settings($what)
1651            if { $bool } {
1652                set heightScale [GetHeightmapScale]
1653                if {$heightScale == 0} {
1654                    SendCmd "camera aspect window"
1655                } else {
1656                    SendCmd "camera aspect square"
1657                }
1658            } else {
1659                SendCmd "camera aspect native"
1660            }
1661            Zoom reset
1662        }
1663        "-wireframe" {
1664            set bool $_settings($what)
1665            SendCmd "heightmap wireframe $bool"
1666        }
1667        default {
1668            error "don't know how to fix $what"
1669        }
1670    }
1671}
1672
1673#
1674# RequestLegend --
1675#
1676#       Request a new legend from the server.  The size of the legend
1677#       is determined from the height of the canvas. 
1678#
1679# This should be called when
1680#       1.  A new current colormap is set.
1681#       2.  Window is resized.
1682#       3.  The limits of the data have changed.  (Just need a redraw).
1683#       4.  Number of isolines have changed. (Just need a redraw).
1684#       5.  Legend becomes visible (Just need a redraw).
1685#
1686itcl::body Rappture::VtkHeightmapViewer::RequestLegend {} {
1687    set _legendPending 0
1688    set font "Arial 8"
1689    set w 12
1690    set lineht [font metrics $font -linespace]
1691    # color ramp height = (canvas height) - (min and max value lines) - 2
1692    set h [expr {$_height - 2 * ($lineht + 2)}]
1693    set _legendHeight $h
1694
1695    set fname $_curFldName
1696    if { [string match "component*" $fname] } {
1697        set title ""
1698    } else {
1699        if { [info exists _fields($fname)] } {
1700            foreach { title units } $_fields($fname) break
1701            if { $units != "" } {
1702                set title [format "%s (%s)" $title $units]
1703            }
1704        } else {
1705            set title $fname
1706        }
1707    }
1708    # If there's a title too, substract one more line
1709    if { $title != "" } {
1710        incr h -$lineht
1711    }
1712    if { $h < 1 } {
1713        return
1714    }
1715    # Set the legend on the first heightmap dataset.
1716    if { $_currentColormap != ""  } {
1717        set cmap $_currentColormap
1718        SendCmd "legend $cmap scalar $_curFldName {} $w $h 0"
1719    }
1720}
1721
1722#
1723# ResetAxes --
1724#
1725#       Set axis z bounds and range
1726#
1727itcl::body Rappture::VtkHeightmapViewer::ResetAxes {} {
1728    if { ![info exists _limits($_curFldName)]} {
1729        SendCmd "dataset maprange all"
1730        SendCmd "axis autorange z on"
1731        SendCmd "axis autobounds z on"
1732        return
1733    }
1734    foreach { xmin xmax } $_limits(x) break
1735    foreach { ymin ymax } $_limits(y) break
1736    foreach { vmin vmax } $_limits($_curFldName) break
1737
1738    global tcl_precision
1739    set tcl_precision 17
1740    set xr [expr $xmax - $xmin]
1741    set yr [expr $ymax - $ymin]
1742    set vr [expr $vmax - $vmin]
1743    set r  [expr ($yr > $xr) ? $yr : $xr]
1744    if { $vr < 1.0e-17 } {
1745        set dataScale 1.0
1746    } else {
1747        set dataScale [expr $r / $vr]
1748    }
1749    set heightScale [GetHeightmapScale]
1750    set bmin [expr $heightScale * $dataScale * $vmin]
1751    set bmax [expr $heightScale * $dataScale * $vmax]
1752    if {$heightScale > 0} {
1753        set zpos [expr - $bmin]
1754        SendCmd "heightmap pos 0 0 $zpos"
1755    } else {
1756        SendCmd "heightmap pos 0 0 0"
1757    }
1758    set bmax [expr $bmax - $bmin]
1759    set bmin 0
1760    SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
1761    SendCmd "axis bounds z $bmin $bmax"
1762    SendCmd "axis range z $_limits($_curFldName)"
1763}
1764
1765#
1766# SetCurrentColormap --
1767#
1768itcl::body Rappture::VtkHeightmapViewer::SetCurrentColormap { name } {
1769    # Keep track of the colormaps that we build.
1770    if { $name != "none" && ![info exists _colormaps($name)] } {
1771        BuildColormap $name
1772        set _colormaps($name) 1
1773    }
1774    set _currentColormap $name
1775    SendCmd "heightmap colormap $_currentColormap"
1776}
1777
1778
1779#
1780# BuildColormap --
1781#
1782#       Build the designated colormap on the server.
1783#
1784itcl::body Rappture::VtkHeightmapViewer::BuildColormap { name } {
1785    set cmap [ColorsToColormap $name]
1786    if { [llength $cmap] == 0 } {
1787        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1788    }
1789    set wmap "0.0 1.0 1.0 1.0"
1790    SendCmd "colormap add $name { $cmap } { $wmap }"
1791}
1792
1793# ----------------------------------------------------------------------
1794# CONFIGURATION OPTION: -mode
1795# ----------------------------------------------------------------------
1796itcl::configbody Rappture::VtkHeightmapViewer::mode {
1797    switch -- $itk_option(-mode) {
1798        "heightmap" {
1799            set _settings(-isheightmap) 1
1800        }
1801        "contour" {
1802            set _settings(-isheightmap) 0
1803        }
1804        default {
1805            error "unknown mode settings \"$itk_option(-mode)\""
1806        }
1807    }
1808    if { !$_reset } {
1809        AdjustSetting -isheightmap
1810    }
1811}
1812
1813# ----------------------------------------------------------------------
1814# CONFIGURATION OPTION: -plotbackground
1815# ----------------------------------------------------------------------
1816itcl::configbody Rappture::VtkHeightmapViewer::plotbackground {
1817    if { [isconnected] } {
1818        set rgb [Color2RGB $itk_option(-plotbackground)]
1819        if { !$_reset } {
1820            SendCmd "screen bgcolor $rgb"
1821        }
1822        $itk_component(view) configure -background $itk_option(-plotbackground)
1823    }
1824}
1825
1826# ----------------------------------------------------------------------
1827# CONFIGURATION OPTION: -plotforeground
1828# ----------------------------------------------------------------------
1829itcl::configbody Rappture::VtkHeightmapViewer::plotforeground {
1830    if { [isconnected] } {
1831        set rgb [Color2RGB $itk_option(-plotforeground)]
1832        if { !$_reset } {
1833            SendCmd "outline color $rgb"
1834            SendCmd "axis color all $rgb"
1835        }
1836    }
1837}
1838
1839itcl::body Rappture::VtkHeightmapViewer::limits3 { dataobj } {
1840    lappend limits x [$dataobj limits x]
1841    lappend limits y [$dataobj limits y]
1842    if { [catch { $dataobj limits $_curFldName } vlim] != 0 } {
1843        set vlim [$dataobj limits v]
1844    }
1845    lappend limits v $vlim
1846    return $limits
1847}
1848
1849itcl::body Rappture::VtkHeightmapViewer::BuildContourTab {} {
1850
1851    set fg [option get $itk_component(hull) font Font]
1852    #set bfg [option get $itk_component(hull) boldFont Font]
1853
1854    set inner [$itk_component(main) insert end \
1855        -title "Contour/Surface Settings" \
1856        -icon [Rappture::icon contour2]]
1857    $inner configure -borderwidth 4
1858
1859    checkbutton $inner.legend \
1860        -text "Legend" \
1861        -variable [itcl::scope _settings(-legendvisible)] \
1862        -command [itcl::code $this AdjustSetting -legendvisible] \
1863        -font "Arial 9"
1864
1865    checkbutton $inner.wireframe \
1866        -text "Wireframe" \
1867        -variable [itcl::scope _settings(-wireframe)] \
1868        -command [itcl::code $this AdjustSetting -wireframe] \
1869        -font "Arial 9"
1870
1871    itk_component add lighting {
1872        checkbutton $inner.lighting \
1873            -text "Enable Lighting" \
1874            -variable [itcl::scope _settings(-lighting)] \
1875            -command [itcl::code $this AdjustSetting -lighting] \
1876            -font "Arial 9"
1877    } {
1878        ignore -font
1879    }
1880    checkbutton $inner.edges \
1881        -text "Edges" \
1882        -variable [itcl::scope _settings(-edges)] \
1883        -command [itcl::code $this AdjustSetting -edges] \
1884        -font "Arial 9"
1885
1886    itk_component add outline {
1887        checkbutton $inner.outline \
1888            -text "Outline" \
1889            -variable [itcl::scope _settings(-outline)] \
1890            -command [itcl::code $this AdjustSetting -outline] \
1891            -font "Arial 9"
1892    } {
1893        ignore -font
1894    }
1895    checkbutton $inner.stretch \
1896        -text "Stretch to fit" \
1897        -variable [itcl::scope _settings(-stretchtofit)] \
1898        -command [itcl::code $this AdjustSetting -stretchtofit] \
1899        -font "Arial 9"
1900
1901    checkbutton $inner.isolines \
1902        -text "Isolines" \
1903        -variable [itcl::scope _settings(-isolinesvisible)] \
1904        -command [itcl::code $this AdjustSetting -isolinesvisible] \
1905        -font "Arial 9"
1906
1907    checkbutton $inner.colormapDiscrete \
1908        -text "Discrete Colormap" \
1909        -variable [itcl::scope _settings(-colormapdiscrete)] \
1910        -command [itcl::code $this AdjustSetting -colormapdiscrete] \
1911        -font "Arial 9"
1912
1913    itk_component add field_l {
1914        label $inner.field_l -text "Field" -font "Arial 9"
1915    } {
1916        ignore -font
1917    }
1918    itk_component add field {
1919        Rappture::Combobox $inner.field -width 10 -editable no
1920    }
1921    bind $inner.field <<Value>> \
1922        [itcl::code $this AdjustSetting -field]
1923
1924    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1925    itk_component add colormap {
1926        Rappture::Combobox $inner.colormap -width 10 -editable no
1927    }
1928    $inner.colormap choices insert end [GetColormapList -includeNone]
1929    $itk_component(colormap) value $_settings(-colormap)
1930    bind $inner.colormap <<Value>> \
1931        [itcl::code $this AdjustSetting -colormap]
1932
1933    label $inner.isolinecolor_l -text "Isolines Color" -font "Arial 9"
1934    itk_component add isolinecolor {
1935        Rappture::Combobox $inner.isolinecolor -width 10 -editable no
1936    }
1937    $inner.isolinecolor choices insert end \
1938        "black"              "black"            \
1939        "blue"               "blue"             \
1940        "cyan"               "cyan"             \
1941        "green"              "green"            \
1942        "grey"               "grey"             \
1943        "magenta"            "magenta"          \
1944        "orange"             "orange"           \
1945        "red"                "red"              \
1946        "white"              "white"            \
1947        "none"               "none"
1948
1949    $itk_component(isolinecolor) value $_settings(-isolinecolor)
1950    bind $inner.isolinecolor <<Value>> \
1951        [itcl::code $this AdjustSetting -isolinecolor]
1952
1953    label $inner.background_l -text "Background Color" -font "Arial 9"
1954    itk_component add background {
1955        Rappture::Combobox $inner.background -width 10 -editable no
1956    }
1957    $inner.background choices insert end \
1958        "black"              "black"            \
1959        "white"              "white"            \
1960        "grey"               "grey"             
1961
1962    $itk_component(background) value "white"
1963    bind $inner.background <<Value>> \
1964        [itcl::code $this AdjustSetting -background]
1965
1966    itk_component add opacity_l {
1967        label $inner.opacity_l -text "Opacity" -font "Arial 9"
1968    } {
1969        ignore -font
1970    }
1971    itk_component add opacity {
1972        ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1973            -variable [itcl::scope _settings(-opacity)] \
1974            -showvalue off \
1975            -command [itcl::code $this AdjustSetting -opacity]
1976    }
1977    itk_component add scale_l {
1978        label $inner.scale_l -text "Scale" -font "Arial 9"
1979    } {
1980        ignore -font
1981    }
1982    itk_component add scale {
1983        ::scale $inner.scale -from 0 -to 100 -orient horizontal \
1984            -variable [itcl::scope _settings(-heightmapscale)] \
1985            -showvalue off \
1986            -command [itcl::code $this AdjustSetting -heightmapscale]
1987    }
1988    label $inner.numisolines_l -text "Number of Isolines" -font "Arial 9"
1989    itk_component add numisolines {
1990        Rappture::Spinint $inner.numisolines \
1991            -min 0 -max 50 -font "arial 9"
1992    }
1993    $itk_component(numisolines) value $_settings(-numisolines)
1994    bind $itk_component(numisolines) <<Value>> \
1995        [itcl::code $this AdjustSetting -numisolines]
1996
1997    frame $inner.separator1 -height 2 -relief sunken -bd 1
1998    frame $inner.separator2 -height 2 -relief sunken -bd 1
1999
2000    blt::table $inner \
2001        0,0 $inner.field_l -anchor w -pady 2 \
2002        0,1 $inner.field -anchor w -pady 2 -fill x \
2003        1,0 $inner.colormap_l -anchor w -pady 2  \
2004        1,1 $inner.colormap   -anchor w -pady 2 -fill x  \
2005        2,0 $inner.isolinecolor_l  -anchor w -pady 2  \
2006        2,1 $inner.isolinecolor    -anchor w -pady 2 -fill x  \
2007        3,0 $inner.background_l -anchor w -pady 2 \
2008        3,1 $inner.background -anchor w -pady 2  -fill x \
2009        4,0 $inner.numisolines_l -anchor w -pady 2 \
2010        4,1 $inner.numisolines -anchor w -pady 2 \
2011        5,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
2012        6,0 $inner.edges      -anchor w -pady 2 -cspan 2 \
2013        7,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
2014        8,0 $inner.colormapDiscrete -anchor w -pady 2 -cspan 2 \
2015        9,0 $inner.wireframe  -anchor w -pady 2 -cspan 2\
2016        10,0 $inner.isolines   -anchor w -pady 2 -cspan 2 \
2017        11,0 $inner.separator1 -padx 2 -fill x -cspan 2 \
2018        12,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
2019        13,0 $inner.separator2 -padx 2 -fill x -cspan 2 \
2020        14,0 $inner.lighting   -anchor w -pady 2 -cspan 2 \
2021        15,0 $inner.opacity_l -anchor w -pady 2 \
2022        15,1 $inner.opacity   -fill x   -pady 2 \
2023        16,0 $inner.scale_l   -anchor w -pady 2 -cspan 2 \
2024        16,1 $inner.scale     -fill x   -pady 2 -cspan 2 \
2025
2026    blt::table configure $inner r* c* -resize none
2027    blt::table configure $inner r17 c1 -resize expand
2028}
2029
2030itcl::body Rappture::VtkHeightmapViewer::BuildAxisTab {} {
2031
2032    set fg [option get $itk_component(hull) font Font]
2033    #set bfg [option get $itk_component(hull) boldFont Font]
2034
2035    set inner [$itk_component(main) insert end \
2036        -title "Axis Settings" \
2037        -icon [Rappture::icon axis2]]
2038    $inner configure -borderwidth 4
2039
2040    checkbutton $inner.visible \
2041        -text "Axes" \
2042        -variable [itcl::scope _settings(-axisvisible)] \
2043        -command [itcl::code $this AdjustSetting -axisvisible] \
2044        -font "Arial 9"
2045    checkbutton $inner.labels \
2046        -text "Axis Labels" \
2047        -variable [itcl::scope _settings(-axislabels)] \
2048        -command [itcl::code $this AdjustSetting -axislabels] \
2049        -font "Arial 9"
2050    label $inner.grid_l -text "Grid" -font "Arial 9"
2051    checkbutton $inner.xgrid \
2052        -text "X" \
2053        -variable [itcl::scope _settings(-xgrid)] \
2054        -command [itcl::code $this AdjustSetting -xgrid] \
2055        -font "Arial 9"
2056    checkbutton $inner.ygrid \
2057        -text "Y" \
2058        -variable [itcl::scope _settings(-ygrid)] \
2059        -command [itcl::code $this AdjustSetting -ygrid] \
2060        -font "Arial 9"
2061    checkbutton $inner.zgrid \
2062        -text "Z" \
2063        -variable [itcl::scope _settings(-zgrid)] \
2064        -command [itcl::code $this AdjustSetting -zgrid] \
2065        -font "Arial 9"
2066    checkbutton $inner.minorticks \
2067        -text "Minor Ticks" \
2068        -variable [itcl::scope _settings(-axisminorticks)] \
2069        -command [itcl::code $this AdjustSetting -axisminorticks] \
2070        -font "Arial 9"
2071
2072    label $inner.mode_l -text "Mode" -font "Arial 9"
2073
2074    itk_component add axisflymode {
2075        Rappture::Combobox $inner.mode -width 10 -editable no
2076    }
2077    $inner.mode choices insert end \
2078        "static_triad"    "static" \
2079        "closest_triad"   "closest" \
2080        "furthest_triad"  "farthest" \
2081        "outer_edges"     "outer"         
2082    $itk_component(axisflymode) value $_settings(-axisflymode)
2083    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axisflymode]
2084
2085    blt::table $inner \
2086        0,0 $inner.visible -anchor w -cspan 4 \
2087        1,0 $inner.labels  -anchor w -cspan 4 \
2088        2,0 $inner.minorticks  -anchor w -cspan 4 \
2089        4,0 $inner.grid_l  -anchor w \
2090        4,1 $inner.xgrid   -anchor w \
2091        4,2 $inner.ygrid   -anchor w \
2092        4,3 $inner.zgrid   -anchor w \
2093        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
2094        5,1 $inner.mode    -fill x -cspan 3
2095
2096    blt::table configure $inner r* c* -resize none
2097    blt::table configure $inner r7 c6 -resize expand
2098    blt::table configure $inner r3 -height 0.125i
2099}
2100
2101
2102itcl::body Rappture::VtkHeightmapViewer::BuildCameraTab {} {
2103    set inner [$itk_component(main) insert end \
2104        -title "Camera Settings" \
2105        -icon [Rappture::icon camera]]
2106    $inner configure -borderwidth 4
2107
2108    label $inner.view_l -text "view" -font "Arial 9"
2109    set f [frame $inner.view]
2110    foreach side { front back left right top bottom } {
2111        button $f.$side  -image [Rappture::icon view$side] \
2112            -command [itcl::code $this SetOrientation $side]
2113        Rappture::Tooltip::for $f.$side "Change the view to $side"
2114        pack $f.$side -side left
2115    }
2116
2117    blt::table $inner \
2118        0,0 $inner.view_l -anchor e -pady 2 \
2119        0,1 $inner.view -anchor w -pady 2
2120
2121    set labels { qx qy qz qw xpan ypan zoom }
2122    set row 1
2123    foreach tag $labels {
2124        label $inner.${tag}label -text $tag -font "Arial 9"
2125        entry $inner.${tag} -font "Arial 9"  -bg white \
2126            -textvariable [itcl::scope _view($tag)]
2127        bind $inner.${tag} <Return> \
2128            [itcl::code $this camera set ${tag}]
2129        bind $inner.${tag} <KP_Enter> \
2130            [itcl::code $this camera set ${tag}]
2131        blt::table $inner \
2132            $row,0 $inner.${tag}label -anchor e -pady 2 \
2133            $row,1 $inner.${tag} -anchor w -pady 2
2134        blt::table configure $inner r$row -resize none
2135        incr row
2136    }
2137    checkbutton $inner.ortho \
2138        -text "Orthographic Projection" \
2139        -variable [itcl::scope _view(ortho)] \
2140        -command [itcl::code $this camera set ortho] \
2141        -font "Arial 9"
2142    blt::table $inner \
2143            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
2144    blt::table configure $inner r$row -resize none
2145    incr row
2146
2147    blt::table configure $inner c* r* -resize none
2148    blt::table configure $inner c2 -resize expand
2149    blt::table configure $inner r$row -resize expand
2150}
2151
2152#
2153#  camera --
2154#
2155itcl::body Rappture::VtkHeightmapViewer::camera {option args} {
2156    switch -- $option {
2157        "show" {
2158            puts [array get _view]
2159        }
2160        "set" {
2161            set who [lindex $args 0]
2162            set x $_view($who)
2163            set code [catch { string is double $x } result]
2164            if { $code != 0 || !$result } {
2165                return
2166            }
2167            switch -- $who {
2168                "ortho" {
2169                    if {$_view(ortho)} {
2170                        SendCmd "camera mode ortho"
2171                    } else {
2172                        SendCmd "camera mode persp"
2173                    }
2174                }
2175                "xpan" - "ypan" {
2176                    PanCamera
2177                }
2178                "qx" - "qy" - "qz" - "qw" {
2179                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2180                    $_arcball quaternion $q
2181                    EventuallyRotate $q
2182                }
2183                "zoom" {
2184                    SendCmd "camera zoom $_view(zoom)"
2185                }
2186            }
2187        }
2188    }
2189}
2190
2191itcl::body Rappture::VtkHeightmapViewer::GetVtkData { args } {
2192    set bytes ""
2193    foreach dataobj [get] {
2194        foreach comp [$dataobj components] {
2195            set tag $dataobj-$comp
2196            set contents [$dataobj vtkdata $comp]
2197            append bytes "$contents\n"
2198        }
2199    }
2200    return [list .vtk $bytes]
2201}
2202
2203itcl::body Rappture::VtkHeightmapViewer::GetImage { args } {
2204    if { [image width $_image(download)] > 0 &&
2205         [image height $_image(download)] > 0 } {
2206        set bytes [$_image(download) data -format "jpeg -quality 100"]
2207        set bytes [Rappture::encoding::decode -as b64 $bytes]
2208        return [list .jpg $bytes]
2209    }
2210    return ""
2211}
2212
2213itcl::body Rappture::VtkHeightmapViewer::BuildDownloadPopup { popup command } {
2214    Rappture::Balloon $popup \
2215        -title "[Rappture::filexfer::label downloadWord] as..."
2216    set inner [$popup component inner]
2217    label $inner.summary -text "" -anchor w
2218    radiobutton $inner.vtk_button -text "VTK data file" \
2219        -variable [itcl::scope _downloadPopup(format)] \
2220        -font "Arial 9 " \
2221        -value vtk 
2222    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2223    radiobutton $inner.image_button -text "Image File" \
2224        -variable [itcl::scope _downloadPopup(format)] \
2225        -font "Arial 9 " \
2226        -value image
2227    Rappture::Tooltip::for $inner.image_button \
2228        "Save as digital image."
2229
2230    button $inner.ok -text "Save" \
2231        -highlightthickness 0 -pady 2 -padx 3 \
2232        -command $command \
2233        -compound left \
2234        -image [Rappture::icon download]
2235
2236    button $inner.cancel -text "Cancel" \
2237        -highlightthickness 0 -pady 2 -padx 3 \
2238        -command [list $popup deactivate] \
2239        -compound left \
2240        -image [Rappture::icon cancel]
2241
2242    blt::table $inner \
2243        0,0 $inner.summary -cspan 2  \
2244        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2245        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2246        4,1 $inner.cancel -width .9i -fill y \
2247        4,0 $inner.ok -padx 2 -width .9i -fill y
2248    blt::table configure $inner r3 -height 4
2249    blt::table configure $inner r4 -pady 4
2250    raise $inner.image_button
2251    $inner.vtk_button invoke
2252    return $inner
2253}
2254
2255#
2256# SetObjectStyle --
2257#
2258#       Set the style of the heightmap/contour object.  This gets calls
2259#       for each dataset once as it is loaded.  It can overridden by
2260#       the user controls.
2261#
2262#
2263itcl::body Rappture::VtkHeightmapViewer::SetObjectStyle { dataobj comp } {
2264    # Parse style string.
2265    set tag $dataobj-$comp
2266    array set style {
2267        -color BCGYR
2268        -levels 10
2269        -opacity 1.0
2270    }
2271    set stylelist [$dataobj style $comp]
2272    if { $stylelist != "" } {
2273        array set style $stylelist
2274    }
2275    # This is too complicated.  We want to set the colormap, number of
2276    # isolines and opacity for the dataset.  They can be the default values,
2277    # the style hints loaded with the dataset, or set by user controls.  As
2278    # datasets get loaded, they first use the defaults that are overidden
2279    # by the style hints.  If the user changes the global controls, then that
2280    # overrides everything else.  I don't know what it means when global
2281    # controls are specified as style hints by each dataset.  It complicates
2282    # the code to handle aberrant cases.
2283
2284    if { $_changed(-opacity) } {
2285        set style(-opacity) [expr $_settings(-opacity) * 0.01]
2286    }
2287    if { $_changed(-numisolines) } {
2288        set style(-levels) $_settings(-numisolines)
2289    }
2290    if { $_changed(-colormap) } {
2291        set style(-color) $_settings(-colormap)
2292    }
2293    if { $_currentColormap == "" } {
2294        $itk_component(colormap) value $style(-color)
2295    }
2296    if { [info exists style(-stretchtofit)] } {
2297        set _settings(-stretchtofit) $style(-stretchtofit)
2298        AdjustSetting -stretchtofit
2299    }
2300    if { $_currentNumIsolines != $style(-levels) } {
2301        set _currentNumIsolines $style(-levels)
2302        set _settings(-numisolines) $_currentNumIsolines
2303        $itk_component(numisolines) value $_currentNumIsolines
2304        UpdateContourList
2305        DrawLegend
2306    }
2307    SendCmd "outline add $tag"
2308    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2309    SendCmd "outline visible $_settings(-outline) $tag"
2310    set scale [GetHeightmapScale]
2311    SendCmd "[list heightmap add contourlist $_contourList $scale $tag]"
2312    set _comp2scale($tag) $_settings(-heightmapscale)
2313    SendCmd "heightmap edges $_settings(-edges) $tag"
2314    SendCmd "heightmap wireframe $_settings(-wireframe) $tag"
2315    SetCurrentColormap $style(-color)
2316    set color [$itk_component(isolinecolor) value]
2317    SendCmd "heightmap isolinecolor [Color2RGB $color] $tag"
2318    SendCmd "heightmap lighting $_settings(-isheightmap) $tag"
2319    SendCmd "heightmap isolines $_settings(-isolinesvisible) $tag"
2320    SendCmd "heightmap surface $_settings(-colormapvisible) $tag"
2321    SendCmd "heightmap opacity $style(-opacity) $tag"
2322    set _settings(-opacity) [expr $style(-opacity) * 100.0]
2323}
2324
2325itcl::body Rappture::VtkHeightmapViewer::IsValidObject { dataobj } {
2326    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2327        return 0
2328    }
2329    return 1
2330}
2331
2332# ----------------------------------------------------------------------
2333# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2334#
2335# Invoked automatically whenever the "legend" command comes in from
2336# the rendering server.  Indicates that binary image data with the
2337# specified <size> will follow.
2338# ----------------------------------------------------------------------
2339itcl::body Rappture::VtkHeightmapViewer::ReceiveLegend { colormap title min max size } {
2340    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2341    if { [isconnected] } {
2342        set bytes [ReceiveBytes $size]
2343        if { ![info exists _image(legend)] } {
2344            set _image(legend) [image create photo]
2345        }
2346        $_image(legend) configure -data $bytes
2347        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2348        if { [catch {DrawLegend} errs] != 0 } {
2349            global errorInfo
2350            puts stderr "errs=$errs errorInfo=$errorInfo"
2351        }
2352    }
2353}
2354
2355#
2356# DrawLegend --
2357#
2358#       Draws the legend in the own canvas on the right side of the plot area.
2359#
2360itcl::body Rappture::VtkHeightmapViewer::DrawLegend {} {
2361    set fname $_curFldName
2362    set c $itk_component(view)
2363    set w [winfo width $c]
2364    set h [winfo height $c]
2365    set font "Arial 8"
2366    set lineht [font metrics $font -linespace]
2367   
2368    if { [string match "component*" $fname] } {
2369        set title ""
2370    } else {
2371        if { [info exists _fields($fname)] } {
2372            foreach { title units } $_fields($fname) break
2373            if { $units != "" } {
2374                set title [format "%s (%s)" $title $units]
2375            }
2376        } else {
2377            set title $fname
2378        }
2379    }
2380    set x [expr $w - 2]
2381    if { !$_settings(-legendvisible) } {
2382        $c delete legend
2383        return
2384    }
2385    if { [$c find withtag "legend"] == "" } {
2386        set y 2
2387        # If there's a legend title, create a text item for the title.
2388        $c create text $x $y \
2389            -anchor ne \
2390            -fill $itk_option(-plotforeground) -tags "title legend" \
2391            -font $font
2392        if { $title != "" } {
2393            incr y $lineht
2394        }
2395        $c create text $x $y \
2396            -anchor ne \
2397            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2398            -font $font
2399        incr y $lineht
2400        $c create image $x $y \
2401            -anchor ne \
2402            -image $_image(legend) -tags "colormap legend"
2403        $c create rectangle $x $y 1 1 \
2404            -fill "" -outline "" -tags "sensor legend"
2405        $c create text $x [expr {$h-2}] \
2406            -anchor se \
2407            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2408            -font $font
2409        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2410        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2411        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2412    }
2413    $c delete isoline
2414    set x2 $x
2415    set iw [image width $_image(legend)]
2416    set ih [image height $_image(legend)]
2417    set x1 [expr $x2 - ($iw*12)/10]
2418    set color [$itk_component(isolinecolor) value]
2419
2420    # Draw the isolines on the legend.
2421    array unset _isolines
2422    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2423         $_settings(-isolinesvisible) && $_currentNumIsolines > 0 } {
2424
2425        foreach { vmin vmax } $_limits($_curFldName) break
2426        set range [expr double($vmax - $vmin)]
2427        if { $range <= 0.0 } {
2428            set range 1.0;              # Min is greater or equal to max.
2429        }
2430        set tags "isoline legend"
2431        set offset [expr 2 + $lineht]
2432        if { $title != "" } {
2433            incr offset $lineht
2434        }
2435        foreach value $_contourList {
2436            set norm [expr 1.0 - (($value - $vmin) / $range)]
2437            set y1 [expr int(round(($norm * $ih) + $offset))]
2438            for { set off 0 } { $off < 3 } { incr off } {
2439                set _isolines([expr $y1 + $off]) $value
2440                set _isolines([expr $y1 - $off]) $value
2441            }
2442            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2443        }
2444    }
2445
2446    $c bind title <ButtonPress> [itcl::code $this Combo post]
2447    $c bind title <Enter> [itcl::code $this Combo activate]
2448    $c bind title <Leave> [itcl::code $this Combo deactivate]
2449    # Reset the item coordinates according the current size of the plot.
2450    if { [info exists _limits($_curFldName)] } {
2451        foreach { vmin vmax } $_limits($_curFldName) break
2452        $c itemconfigure vmin -text [format %g $vmin]
2453        $c itemconfigure vmax -text [format %g $vmax]
2454    }
2455    set y 2
2456    # If there's a legend title, move the title to the correct position
2457    if { $title != "" } {
2458        $c itemconfigure title -text $title
2459        $c coords title $x $y
2460        incr y $lineht
2461    }
2462    $c coords vmax $x $y
2463    incr y $lineht
2464    $c coords colormap $x $y
2465    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2466    $c raise sensor
2467    $c coords vmin $x [expr {$h - 2}]
2468}
2469
2470#
2471# EnterLegend --
2472#
2473itcl::body Rappture::VtkHeightmapViewer::EnterLegend { x y } {
2474    SetLegendTip $x $y
2475}
2476
2477#
2478# MotionLegend --
2479#
2480itcl::body Rappture::VtkHeightmapViewer::MotionLegend { x y } {
2481    Rappture::Tooltip::tooltip cancel
2482    set c $itk_component(view)
2483    set cw [winfo width $c]
2484    set ch [winfo height $c]
2485    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2486        SetLegendTip $x $y
2487    }
2488}
2489
2490#
2491# LeaveLegend --
2492#
2493itcl::body Rappture::VtkHeightmapViewer::LeaveLegend { } {
2494    Rappture::Tooltip::tooltip cancel
2495    .rappturetooltip configure -icon ""
2496}
2497
2498#
2499# SetLegendTip --
2500#
2501itcl::body Rappture::VtkHeightmapViewer::SetLegendTip { x y } {
2502    set fname $_curFldName
2503    set c $itk_component(view)
2504    set w [winfo width $c]
2505    set h [winfo height $c]
2506    set font "Arial 8"
2507    set lineht [font metrics $font -linespace]
2508   
2509    set ih [image height $_image(legend)]
2510    # Subtract off the offset of the color ramp from the top of the canvas
2511    set iy [expr $y - ($lineht + 2)]
2512
2513    if { [string match "component*" $fname] } {
2514        set title ""
2515    } else {
2516        if { [info exists _fields($fname)] } {
2517            foreach { title units } $_fields($fname) break
2518            if { $units != "" } {
2519                set title [format "%s (%s)" $title $units]
2520            }
2521        } else {
2522            set title $fname
2523        }
2524    }
2525    # If there's a legend title, increase the offset by the line height.
2526    if { $title != "" } {
2527        incr iy -$lineht
2528    }
2529
2530    # Make a swatch of the selected color
2531    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2532        return
2533    }
2534
2535    if { ![info exists _image(swatch)] } {
2536        set _image(swatch) [image create photo -width 24 -height 24]
2537    }
2538    set color [eval format "\#%02x%02x%02x" $pixel]
2539    $_image(swatch) put black  -to 0 0 23 23
2540    $_image(swatch) put $color -to 1 1 22 22
2541
2542    # Compute the value of the point
2543    if { [info exists _limits($fname)] } {
2544        foreach { vmin vmax } $_limits($fname) break
2545        set t [expr 1.0 - (double($iy) / double($ih-1))]
2546        set value [expr $t * ($vmax - $vmin) + $vmin]
2547    } else {
2548        set value 0.0
2549    }
2550    set tipx [expr $x + 15]
2551    set tipy [expr $y - 5]
2552    .rappturetooltip configure -icon $_image(swatch)
2553    if { [info exists _isolines($y)] } {
2554        Rappture::Tooltip::text $c [format "$title %g (isoline)" $_isolines($y)]
2555    } else {
2556        Rappture::Tooltip::text $c [format "$title %g" $value]
2557    }
2558    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2559}
2560
2561# ----------------------------------------------------------------------
2562# USAGE: _dropdown post
2563# USAGE: _dropdown unpost
2564# USAGE: _dropdown select
2565#
2566# Used internally to handle the dropdown list for this combobox.  The
2567# post/unpost options are invoked when the list is posted or unposted
2568# to manage the relief of the controlling button.  The select option
2569# is invoked whenever there is a selection from the list, to assign
2570# the value back to the gauge.
2571# ----------------------------------------------------------------------
2572itcl::body Rappture::VtkHeightmapViewer::Combo {option} {
2573    set c $itk_component(view)
2574    switch -- $option {
2575        post {
2576            foreach { x1 y1 x2 y2 } [$c bbox title] break
2577            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2578            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2579            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2580            tk_popup $itk_component(fieldmenu) $x $y
2581        }
2582        activate {
2583            $c itemconfigure title -fill red
2584        }
2585        deactivate {
2586            $c itemconfigure title -fill $itk_option(-plotforeground)
2587        }
2588        invoke {
2589            $itk_component(field) value $_curFldLabel
2590            AdjustSetting -field
2591        }
2592        default {
2593            error "bad option \"$option\": should be post, unpost, select"
2594        }
2595    }
2596}
2597
2598itcl::body Rappture::VtkHeightmapViewer::GetHeightmapScale {} {
2599    if {  $_settings(-isheightmap) } {
2600        set val $_settings(-heightmapscale)
2601        set sval [expr { $val >= 50 ? double($val)/50.0 : 1.0/(2.0-(double($val)/50.0)) }]
2602        return $sval
2603    }
2604    return 0
2605}
2606
2607itcl::body Rappture::VtkHeightmapViewer::SetOrientation { side } {
2608    array set positions {
2609        front  "0.707107 0.707107 0 0"
2610        back   "0 0 0.707107 0.707107"
2611        left   "0.5 0.5 -0.5 -0.5"
2612        right  "0.5 0.5 0.5 0.5"
2613        top    "1 0 0 0"
2614        bottom "0 1 0 0"
2615    }
2616    foreach name { qw qx qy qz } value $positions($side) {
2617        set _view($name) $value
2618    }
2619    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2620    $_arcball quaternion $q
2621    SendCmd "camera orient $q"
2622    SendCmd "camera reset"
2623    set _view(xpan) 0
2624    set _view(ypan) 0
2625    set _view(zoom) 1.0
2626}
2627
2628itcl::body Rappture::VtkHeightmapViewer::UpdateContourList {} {
2629    if {$_currentNumIsolines == 0} {
2630        set _contourList ""
2631        return
2632    }
2633    if { ![info exists _limits($_curFldName)] } {
2634        return
2635    }
2636    foreach { vmin vmax } $_limits($_curFldName) break
2637    set v [blt::vector create \#auto]
2638    $v seq $vmin $vmax [expr $_currentNumIsolines+2]
2639    $v delete end 0
2640    set _contourList [$v range 0 end]
2641    blt::vector destroy $v
2642}
Note: See TracBrowser for help on using the repository browser.