source: branches/1.4/gui/scripts/vtkheightmapviewer.tcl @ 5187

Last change on this file since 5187 was 5187, checked in by ldelgass, 9 years ago

s/styles/style/ (for code consistency), remove unused member variables

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