source: branches/1.3/gui/scripts/vtkheightmapviewer.tcl @ 4706

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

merge r4699 from trunk

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