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

Last change on this file since 3416 was 3416, checked in by gah, 11 years ago

fix switching between heightmap/contour modes

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