source: branches/1.6/gui/scripts/vtkheightmapviewer.tcl @ 6212

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

merge viewer cleanups from trunk

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