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

Last change on this file since 3413 was 3413, checked in by ldelgass, 11 years ago

Fix typo

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