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

Last change on this file since 3374 was 3374, checked in by ldelgass, 12 years ago

VTK heightmap viewer doesn\'t use cutplanes

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