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

Last change on this file since 3441 was 3441, checked in by gah, 12 years ago

misc cleanup vtkvolumeviewer

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