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

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

Disable right-click binding for "Picking." This was only there for testing.

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