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

Last change on this file since 3405 was 3405, checked in by gah, 10 years ago

fix to streamlines to (again) display mulitple fields from a single VTK file

File size: 80.4 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        if 1 {
913            # Tell the server the name of the tool, the version, and dataset
914            # that we are rendering.  Have to do it here because we don't know
915            # what data objects are using the renderer until be get here.
916            global env
917
918            set info {}
919            set user "???"
920            if { [info exists env(USER)] } {
921                set user $env(USER)
922            }
923            set session "???"
924            if { [info exists env(SESSION)] } {
925                set session $env(SESSION)
926            }
927            lappend info "hub" [exec hostname]
928            lappend info "client" "vtkheightmapviewer"
929            lappend info "user" $user
930            lappend info "session" $session
931            SendCmd "clientinfo [list $info]"
932        }
933        InitSettings isHeightmap background
934        #
935        # Reset the camera and other view parameters
936        #
937        SendCmd "axis color all [Color2RGB $itk_option(-plotforeground)]"
938        SendCmd "axis lrot z 90"
939        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
940        $_arcball quaternion $q
941        if {$_settings(isHeightmap) } {
942            SendCmd "camera reset"
943            if { $_view(ortho)} {
944                SendCmd "camera mode ortho"
945            } else {
946                SendCmd "camera mode persp"
947            }
948        }           
949        DoRotate
950        PanCamera
951    }
952    set _first ""
953
954    #SendCmd "imgflush"
955
956    set _first ""
957    # Start off with no datasets are visible.
958    SendCmd "dataset visible 0"
959    set scale [GetHeightmapScale]
960    foreach dataobj [get -objects] {
961        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
962            set _first $dataobj
963        }
964        scale $dataobj
965        set _obj2datasets($dataobj) ""
966        foreach comp [$dataobj components] {
967            set tag $dataobj-$comp
968            if { ![info exists _datasets($tag)] } {
969                set bytes [$dataobj vtkdata $comp]
970                if 1 {
971                    set f [open /tmp/vtkheightmap.vtk "w"]
972                    puts $f $bytes
973                    close $f
974                }
975                set length [string length $bytes]
976                if 1 {
977                    set info {}
978                    lappend info "tool_id"       [$dataobj hints toolId]
979                    lappend info "tool_name"     [$dataobj hints toolName]
980                    lappend info "tool_version"  [$dataobj hints toolRevision]
981                    lappend info "tool_title"    [$dataobj hints toolTitle]
982                    lappend info "dataset_label" [$dataobj hints label]
983                    lappend info "dataset_size"  $length
984                    lappend info "dataset_tag"   $tag
985                    SendCmd [list "clientinfo" $info]
986                }
987                append _outbuf "dataset add $tag data follows $length\n"
988                append _outbuf $bytes
989                set _datasets($tag) 1
990                SetObjectStyle $dataobj $comp
991            }
992            lappend _obj2datasets($dataobj) $tag
993            if { [info exists _obj2ovride($dataobj-raise)] } {
994                SendCmd "heightmap visible 1 $tag"
995            }
996            if { ![info exists _comp2scale($tag)] ||
997                 $_comp2scale($tag) != $scale } {
998                SendCmd "heightmap heightscale $scale $tag"
999                set _comp2scale($tag) $scale
1000            }
1001        }
1002    }
1003    if { $_first != ""  } {
1004        $itk_component(field) choices delete 0 end
1005        $itk_component(fieldmenu) delete 0 end
1006        array unset _fields
1007        foreach cname [$_first components] {
1008            foreach fname [$_first fieldnames $cname] {
1009                if { [info exists _fields($fname)] } {
1010                    continue
1011                }
1012                foreach { label units components } \
1013                    [$_first fieldinfo $fname] break
1014                SendCmd "dataset maprange explicit $_limits(v) $fname"
1015                $itk_component(field) choices insert end "$fname" "$label"
1016                $itk_component(fieldmenu) add radiobutton -label "$label" \
1017                    -value $label -variable [itcl::scope _curFldName] \
1018                    -selectcolor red \
1019                    -activebackground $itk_option(-plotbackground) \
1020                    -activeforeground $itk_option(-plotforeground) \
1021                    -font "Arial 8" \
1022                    -command [itcl::code $this Combo invoke]
1023                set _fields($fname) [list $label $units $components]
1024                set _curFldName $fname
1025            }
1026        }
1027        if { [array size _fields] == 1 } {
1028            set _curFldName [array names _fields]
1029            if { $_curFldName == "" } {
1030                puts stderr "no default name from field"
1031                set _curFldName "Default"
1032            }
1033        }
1034        $itk_component(field) value $_curFldName
1035    }
1036    InitSettings stretchToFit
1037
1038    if { $_reset } {
1039        SendCmd "axis tickpos outside"
1040        foreach axis { x y z } {
1041            SendCmd "axis lformat $axis %g"
1042        }
1043        foreach axis { x y z } {
1044            set label [$_first hints ${axis}label]
1045            if { $label == "" } {
1046                if {$axis == "z"} {
1047                    if { $_curFldName == "component" } {
1048                        set label [string toupper $axis]
1049                    } else {
1050                        set label [lindex $_fields($_curFldName) 0]
1051                    }
1052                } else {
1053                    set label [string toupper $axis]
1054                }
1055            }
1056            # May be a space in the axis label.
1057            SendCmd [list axis name $axis $label]
1058
1059            if {$axis == "z" && [$_first hints ${axis}units] == ""} {
1060                set units [lindex $_fields($_curFldName) 1]
1061            } else {
1062                set units [$_first hints ${axis}units]
1063            }
1064            if { $units != "" } {
1065                # May be a space in the axis units.
1066                SendCmd [list axis units $axis $units]
1067            }
1068        }
1069        #
1070        # Reset the camera and other view parameters
1071        #
1072        SendCmd "axis color all [Color2RGB $itk_option(-plotforeground)]"
1073        ResetAxes
1074        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1075        $_arcball quaternion $q
1076        if {$_settings(isHeightmap) } {
1077            SendCmd "camera reset"
1078            if { $_view(ortho)} {
1079                SendCmd "camera mode ortho"
1080            } else {
1081                SendCmd "camera mode persp"
1082            }
1083        }
1084        DoRotate
1085        PanCamera
1086        InitSettings axisXGrid axisYGrid axisZGrid \
1087            axisVisible axisLabels
1088        InitSettings heightmapOpacity \
1089            heightmapScale lighting \
1090            colormap field outline \
1091            edges heightmapOpacity wireframe
1092        set _reset 0
1093    }
1094    global readyForNextFrame
1095    set readyForNextFrame 0;            # Don't advance to the next frame
1096    set _buffering 0;                   # Turn off buffering.
1097
1098    # Actually write the commands to the server socket.  If it fails, we don't
1099    # care.  We're finished here.
1100    blt::busy hold $itk_component(hull)
1101    sendto $_outbuf;                       
1102    blt::busy release $itk_component(hull)
1103    set _outbuf "";                        # Clear the buffer.               
1104}
1105
1106# ----------------------------------------------------------------------
1107# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1108#
1109# Returns a list of server IDs for the current datasets being displayed.  This
1110# is normally a single ID, but it might be a list of IDs if the current data
1111# object has multiple components.
1112# ----------------------------------------------------------------------
1113itcl::body Rappture::VtkHeightmapViewer::CurrentDatasets {args} {
1114    set flag [lindex $args 0]
1115    switch -- $flag {
1116        "-all" {
1117            if { [llength $args] > 1 } {
1118                error "CurrentDatasets: can't specify dataobj after \"-all\""
1119            }
1120            set dlist [get -objects]
1121        }
1122        "-visible" {
1123            if { [llength $args] > 1 } {
1124                set dlist {}
1125                set args [lrange $args 1 end]
1126                foreach dataobj $args {
1127                    if { [info exists _obj2ovride($dataobj-raise)] } {
1128                        lappend dlist $dataobj
1129                    }
1130                }
1131            } else {
1132                set dlist [get -visible]
1133            }
1134        }           
1135        default {
1136            set dlist $args
1137        }
1138    }
1139    set rlist ""
1140    foreach dataobj $dlist {
1141        foreach comp [$dataobj components] {
1142            set tag $dataobj-$comp
1143            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1144                lappend rlist $tag
1145            }
1146        }
1147    }
1148    return $rlist
1149}
1150
1151# ----------------------------------------------------------------------
1152# USAGE: Zoom in
1153# USAGE: Zoom out
1154# USAGE: Zoom reset
1155#
1156# Called automatically when the user clicks on one of the zoom
1157# controls for this widget.  Changes the zoom for the current view.
1158# ----------------------------------------------------------------------
1159itcl::body Rappture::VtkHeightmapViewer::Zoom {option} {
1160    switch -- $option {
1161        "in" {
1162            set _view(zoom) [expr {$_view(zoom)*1.25}]
1163            SendCmd "camera zoom $_view(zoom)"
1164        }
1165        "out" {
1166            set _view(zoom) [expr {$_view(zoom)*0.8}]
1167            SendCmd "camera zoom $_view(zoom)"
1168        }
1169        "reset" {
1170            array set _view {
1171                qw      0.36
1172                qx      0.25
1173                qy      0.50
1174                qz      0.70
1175                zoom    1.0
1176                xpan    0
1177                ypan    0
1178            }
1179            SendCmd "camera reset all"
1180            if { $_first != "" } {
1181                set location [$_first hints camera]
1182                if { $location != "" } {
1183                    array set _view $location
1184                }
1185            }
1186            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1187            $_arcball quaternion $q
1188            DoRotate
1189        }
1190    }
1191}
1192
1193itcl::body Rappture::VtkHeightmapViewer::PanCamera {} {
1194    set x $_view(xpan)
1195    set y $_view(ypan)
1196    SendCmd "camera pan $x $y"
1197}
1198
1199
1200# ----------------------------------------------------------------------
1201# USAGE: Rotate click <x> <y>
1202# USAGE: Rotate drag <x> <y>
1203# USAGE: Rotate release <x> <y>
1204#
1205# Called automatically when the user clicks/drags/releases in the
1206# plot area.  Moves the plot according to the user's actions.
1207# ----------------------------------------------------------------------
1208itcl::body Rappture::VtkHeightmapViewer::Rotate {option x y} {
1209    switch -- $option {
1210        "click" {
1211            $itk_component(view) configure -cursor fleur
1212            set _click(x) $x
1213            set _click(y) $y
1214        }
1215        "drag" {
1216            if {[array size _click] == 0} {
1217                Rotate click $x $y
1218            } else {
1219                set w [winfo width $itk_component(view)]
1220                set h [winfo height $itk_component(view)]
1221                if {$w <= 0 || $h <= 0} {
1222                    return
1223                }
1224
1225                if {[catch {
1226                    # this fails sometimes for no apparent reason
1227                    set dx [expr {double($x-$_click(x))/$w}]
1228                    set dy [expr {double($y-$_click(y))/$h}]
1229                }]} {
1230                    return
1231                }
1232                if { $dx == 0 && $dy == 0 } {
1233                    return
1234                }
1235                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1236                EventuallyRotate $q
1237                set _click(x) $x
1238                set _click(y) $y
1239            }
1240        }
1241        "release" {
1242            Rotate drag $x $y
1243            $itk_component(view) configure -cursor ""
1244            catch {unset _click}
1245        }
1246        default {
1247            error "bad option \"$option\": should be click, drag, release"
1248        }
1249    }
1250}
1251
1252itcl::body Rappture::VtkHeightmapViewer::Pick {x y} {
1253    foreach tag [CurrentDatasets -visible] {
1254        SendCmd "dataset getscalar pixel $x $y $tag"
1255    }
1256}
1257
1258# ----------------------------------------------------------------------
1259# USAGE: $this Pan click x y
1260#        $this Pan drag x y
1261#        $this Pan release x y
1262#
1263# Called automatically when the user clicks on one of the zoom
1264# controls for this widget.  Changes the zoom for the current view.
1265# ----------------------------------------------------------------------
1266itcl::body Rappture::VtkHeightmapViewer::Pan {option x y} {
1267    switch -- $option {
1268        "set" {
1269            set w [winfo width $itk_component(view)]
1270            set h [winfo height $itk_component(view)]
1271            set x [expr $x / double($w)]
1272            set y [expr $y / double($h)]
1273            set _view(xpan) [expr $_view(xpan) + $x]
1274            set _view(ypan) [expr $_view(ypan) + $y]
1275            PanCamera
1276            return
1277        }
1278        "click" {
1279            set _click(x) $x
1280            set _click(y) $y
1281            $itk_component(view) configure -cursor hand1
1282        }
1283        "drag" {
1284            if { ![info exists _click(x)] } {
1285                set _click(x) $x
1286            }
1287            if { ![info exists _click(y)] } {
1288                set _click(y) $y
1289            }
1290            set w [winfo width $itk_component(view)]
1291            set h [winfo height $itk_component(view)]
1292            set dx [expr ($_click(x) - $x)/double($w)]
1293            set dy [expr ($_click(y) - $y)/double($h)]
1294            set _click(x) $x
1295            set _click(y) $y
1296            set _view(xpan) [expr $_view(xpan) - $dx]
1297            set _view(ypan) [expr $_view(ypan) - $dy]
1298            PanCamera
1299        }
1300        "release" {
1301            Pan drag $x $y
1302            $itk_component(view) configure -cursor ""
1303        }
1304        default {
1305            error "unknown option \"$option\": should set, click, drag, or release"
1306        }
1307    }
1308}
1309
1310# ----------------------------------------------------------------------
1311# USAGE: InitSettings <what> ?<value>?
1312#
1313# Used internally to update rendering settings whenever parameters
1314# change in the popup settings panel.  Sends the new settings off
1315# to the back end.
1316# ----------------------------------------------------------------------
1317itcl::body Rappture::VtkHeightmapViewer::InitSettings { args } {
1318    foreach spec $args {
1319        if { [info exists _settings($_first-$spec)] } {
1320            # Reset global setting with dataobj specific setting
1321            set _settings($spec) $_settings($_first-$spec)
1322        }
1323        AdjustSetting $spec
1324    }
1325}
1326
1327#
1328# AdjustSetting --
1329#
1330#       Changes/updates a specific setting in the widget.  There are
1331#       usually user-setable option.  Commands are sent to the render
1332#       server.
1333#
1334itcl::body Rappture::VtkHeightmapViewer::AdjustSetting {what {value ""}} {
1335    if { $_beforeConnect } {
1336        return
1337    }
1338    switch -- $what {
1339        "heightmapOpacity" {
1340            set val $_settings(heightmapOpacity)
1341            set sval [expr { 0.01 * double($val) }]
1342            foreach dataset [CurrentDatasets -all] {
1343                SendCmd "heightmap opacity $sval $dataset"
1344            }
1345        }
1346        "wireframe" {
1347            set bool $_settings(wireframe)
1348            foreach dataset [CurrentDatasets -all] {
1349                SendCmd "heightmap wireframe $bool $dataset"
1350            }
1351        }
1352        "colormapVisible" {
1353            set bool $_settings(colormapVisible)
1354            foreach dataset [CurrentDatasets -all] {
1355                SendCmd "heightmap surface $bool $dataset"
1356            }
1357        }
1358        "isolinesVisible" {
1359            set bool $_settings(isolinesVisible)
1360            foreach dataset [CurrentDatasets -all] {
1361                SendCmd "heightmap isolines $bool $dataset"
1362            }
1363        }
1364        "lighting" {
1365            if { $_settings(isHeightmap) } {
1366                set bool $_settings(lighting)
1367                SendCmd "heightmap lighting $bool"
1368            } else {
1369                SendCmd "heightmap lighting 0"
1370            }
1371        }
1372        "edges" {
1373            set bool $_settings(edges)
1374            foreach dataset [CurrentDatasets -all] {
1375                SendCmd "heightmap edges $bool $dataset"
1376            }
1377        }
1378        "axisVisible" {
1379            set bool $_settings(axisVisible)
1380            SendCmd "axis visible all $bool"
1381        }
1382        "axisLabels" {
1383            set bool $_settings(axisLabels)
1384            SendCmd "axis labels all $bool"
1385        }
1386        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1387            set axis [string tolower [string range $what 4 4]]
1388            set bool $_settings($what)
1389            SendCmd "axis grid $axis $bool"
1390        }
1391        "axisFlymode" {
1392            set mode [$itk_component(axisflymode) value]
1393            set mode [$itk_component(axisflymode) translate $mode]
1394            set _settings($what) $mode
1395            SendCmd "axis flymode $mode"
1396        }
1397        "axisMinorTicks" {
1398            set bool $_settings(axisMinorTicks)
1399            foreach axis { x y z } {
1400                SendCmd "axis minticks ${axis} $bool"
1401            }
1402        }
1403        "isolines" {
1404            set n $_settings($what)
1405            EventuallyContour $n
1406        }
1407        "isolinesVisible" {
1408            set bool $_settings($what)
1409            foreach dataset [CurrentDatasets -all] {
1410                SendCmd "heightmap isolines $bool $dataset"
1411            }
1412        }
1413        "colormapVisible" {
1414            set bool $_settings($what)
1415            foreach dataset [CurrentDatasets -all] {
1416                SendCmd "heightmap surface $bool $dataset"
1417            }
1418        }
1419        "background" {
1420            set bgcolor [$itk_component(background) value]
1421            array set fgcolors {
1422                "black" "white"
1423                "white" "black"
1424                "grey"  "black"
1425            }
1426            configure -plotbackground $bgcolor \
1427                -plotforeground $fgcolors($bgcolor)
1428            $itk_component(view) delete "legend"
1429            DrawLegend $_curFldName
1430        }
1431        "isolineColor" {
1432            set color [$itk_component(isolinecolor) value]
1433            if { $color == "none" } {
1434                if { $_settings(isolinesVisible) } {
1435                    SendCmd "heightmap isolines 0"
1436                    set _settings(isolinesVisible) 0
1437                }
1438            } else {
1439                if { !$_settings(isolinesVisible) } {
1440                    SendCmd "heightmap isolines 1"
1441                    set _settings(isolinesVisible) 1
1442                }
1443                SendCmd "heightmap isolinecolor [Color2RGB $color]"
1444            }
1445            DrawLegend $_curFldName
1446        }
1447        "colormap" {
1448            set color [$itk_component(colormap) value]
1449            set _settings(colormap) $color
1450            if { $color == "none" } {
1451                if { $_settings(colormapVisible) } {
1452                    SendCmd "heightmap surface 0"
1453                    set _settings(colormapVisible) 0
1454                }
1455            } else {
1456                if { !$_settings(colormapVisible) } {
1457                    SendCmd "heightmap surface 1"
1458                    set _settings(colormapVisible) 1
1459                }
1460                ResetColormap $color
1461                SendCmd "heightmap colormap $_currentColormap"
1462            }
1463            SendCmdNoWait "heightmap colormode scalar $_curFldName"
1464            SendCmdNoWait "dataset scalar $_curFldName"
1465            EventuallyRequestLegend
1466        }
1467        "heightmapOpacity" {
1468            set val $_settings(heightmapOpacity)
1469            set sval [expr { 0.01 * double($val) }]
1470            foreach dataset [CurrentDatasets -all] {
1471                SendCmd "heightmap opacity $sval $dataset"
1472            }
1473        }
1474        "heightmapScale" {
1475            if { $_settings(isHeightmap) } {
1476                set scale [GetHeightmapScale]
1477                foreach dataset [CurrentDatasets -all] {
1478                    SendCmd "heightmap heightscale $scale $dataset"
1479                    set _comp2scale($dataset) $scale
1480                }
1481                ResetAxes
1482            }
1483        }
1484        "lighting" {
1485            if { $_settings(isHeightmap) } {
1486                set bool $_settings(lighting)
1487                SendCmd "heightmap lighting $bool"
1488            } else {
1489                SendCmd "heightmap lighting 0"
1490            }
1491        }
1492        "field" {
1493            set new   [$itk_component(field) value]
1494            set value [$itk_component(field) translate $new]
1495            set _settings(field) $value
1496            if { [info exists _fields($new)] } {
1497                set _colorMode scalar
1498                set _curFldName $new
1499            } else {
1500                puts stderr "unknown field \"$new\""
1501                return
1502            }
1503            EventuallyRequestLegend
1504        }
1505        "stretchToFit" {
1506            set bool $_settings(stretchToFit)
1507            if { $bool } {
1508                set heightScale [GetHeightmapScale]
1509                if {$heightScale == 0} {
1510                    SendCmd "camera aspect window"
1511                } else {
1512                    SendCmd "camera aspect square"
1513                }
1514            } else {
1515                SendCmd "camera aspect native"
1516            }
1517        }
1518        "outline" {
1519            set bool $_settings(outline)
1520            SendCmd "dataset outline $bool"
1521        }
1522        "isHeightmap" {
1523            set bool $_settings(isHeightmap)
1524            if { $bool } {
1525                $itk_component(lighting) configure -state normal
1526            } else {
1527                $itk_component(lighting) configure -state disabled
1528            }
1529            set _settings(lighting) $bool
1530            # Fix heightmap scale: 0 for contours, 1 for heightmaps.
1531            if { $bool } {
1532                set _settings(heightmapScale) 50
1533            } else {
1534                set _settings(heightmapScale) 50
1535            }
1536            SendCmd "heightmap lighting $bool"
1537            set scale [GetHeightmapScale]
1538            foreach dataset [CurrentDatasets -all] {
1539                SendCmd "heightmap heightscale $scale $dataset"
1540                set _comp2scale($dataset) $scale
1541            }
1542            if {$_settings(stretchToFit)} {
1543                if {$scale == 0} {
1544                    SendCmd "camera aspect window"
1545                } else {
1546                    SendCmd "camera aspect square"
1547                }
1548            }
1549            ResetAxes
1550            # Fix the mouse bindings for rotation/panning and the
1551            # camera mode. Ideally we'd create a bindtag for these.
1552            set c $itk_component(view)
1553            if { $bool } {
1554                # Bindings for rotation via mouse
1555                bind $c <ButtonPress-1> \
1556                    [itcl::code $this Rotate click %x %y]
1557                bind $c <B1-Motion> \
1558                    [itcl::code $this Rotate drag %x %y]
1559                bind $c <ButtonRelease-1> \
1560                    [itcl::code $this Rotate release %x %y]
1561                set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1562                $_arcball quaternion $q
1563                if {$_view(ortho)} {
1564                    SendCmd "camera mode ortho"
1565                } else {
1566                    SendCmd "camera mode persp"
1567                }
1568                SendCmd "camera orient $q"
1569            } else {
1570                set _settings(heightmapScale) 0
1571                bind $c <ButtonPress-1> {}
1572                bind $c <B1-Motion> {}
1573                bind $c <ButtonRelease-1> {}
1574                SendCmd "camera mode image"
1575            }
1576        }
1577        "legendVisible" {
1578            if { !$_settings(legendVisible) } {
1579                $itk_component(view) delete legend
1580            }
1581            DrawLegend $_curFldName
1582        }
1583        default {
1584            error "don't know how to fix $what"
1585        }
1586    }
1587}
1588
1589#
1590# RequestLegend --
1591#
1592#       Request a new legend from the server.  The size of the legend
1593#       is determined from the height of the canvas. 
1594#
1595# This should be called when
1596#       1.  A new current colormap is set.
1597#       2.  Window is resized.
1598#       3.  The limits of the data have changed.  (Just need a redraw).
1599#       4.  Number of isolines have changed. (Just need a redraw).
1600#       5.  Legend becomes visible (Just need a redraw).
1601#
1602itcl::body Rappture::VtkHeightmapViewer::RequestLegend {} {
1603    set _legendPending 0
1604    set font "Arial 8"
1605    set lineht [font metrics $font -linespace]
1606    set c $itk_component(view)
1607    set w 12
1608    set h [expr {$_height - 2 * ($lineht + 2)}]
1609    if { $h < 1} {
1610        return
1611    }
1612    if { [info exists _fields($_curFldName)] } {
1613        set title [lindex $_fields($_curFldName) 0]
1614        if { $title != "component" } {
1615            set h [expr $h - ($lineht + 2)]
1616        }
1617    } else {
1618        return
1619    }
1620    # Set the legend on the first heightmap dataset.
1621    if { $_currentColormap != ""  } {
1622        set cmap $_currentColormap
1623        SendCmdNoWait "legend $cmap scalar $_curFldName {} $w $h 0"
1624        SendCmdNoWait "heightmap colormode scalar $_curFldName"
1625        SendCmdNoWait "dataset scalar $_curFldName"
1626    }
1627}
1628
1629#
1630# ResetAxes --
1631#
1632#       Set axis z bounds and range
1633#
1634itcl::body Rappture::VtkHeightmapViewer::ResetAxes {} {
1635    if { ![info exists _limits(v)] || ![info exists _fields($_curFldName)]} {
1636        SendCmd "dataset maprange all"
1637        SendCmd "axis autorange z on"
1638        SendCmd "axis autobounds z on"
1639        return
1640    }
1641    foreach { vmin vmax } $_limits(v) break
1642    foreach { xmin xmax } $_limits(x) break
1643    foreach { ymin ymax } $_limits(y) break
1644    set dataRange   [expr $vmax - $vmin]
1645    set boundsRange [expr $xmax - $xmin]
1646    set r [expr $ymax - $ymin]
1647    if {$r > $boundsRange} {
1648        set boundsRange $r
1649    }
1650    if {$dataRange < 1.0e-10} {
1651        set dataScale 1.0
1652    } else {
1653        set dataScale [expr $boundsRange / $dataRange]
1654    }
1655    set heightScale [GetHeightmapScale]
1656    set bMin [expr $heightScale * $dataScale * $vmin]
1657    set bMax [expr $heightScale * $dataScale * $vmax]
1658    set fieldName $_curFldName
1659    SendCmd "dataset maprange explicit $_limits(v) $fieldName"
1660    SendCmd "axis bounds z $bMin $bMax"
1661    SendCmd "axis range z $_limits(v)"
1662}
1663
1664#
1665# SetCurrentColormap --
1666#
1667itcl::body Rappture::VtkHeightmapViewer::SetCurrentColormap { stylelist } {
1668    array set style {
1669        -color BCGYR
1670        -levels 10
1671        -opacity 1.0
1672    }
1673    array set style $stylelist
1674
1675    set name "$style(-color):$style(-levels):$style(-opacity)"
1676    if { ![info exists _colormaps($name)] } {
1677        set stylelist [array get style]
1678        BuildColormap $name $stylelist
1679        set _colormaps($name) $stylelist
1680    }
1681    set _currentColormap $name
1682}
1683
1684
1685#
1686# BuildColormap --
1687#
1688itcl::body Rappture::VtkHeightmapViewer::BuildColormap { name stylelist } {
1689    array set style $stylelist
1690    set cmap [ColorsToColormap $style(-color)]
1691    if { [llength $cmap] == 0 } {
1692        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1693    }
1694    if { ![info exists _settings(heightmapOpacity)] } {
1695        set _settings(heightmapOpacity) $style(-opacity)
1696    }
1697    set max $_settings(heightmapOpacity)
1698
1699    set wmap "0.0 1.0 1.0 1.0"
1700    SendCmd "colormap add $name { $cmap } { $wmap }"
1701}
1702
1703# ----------------------------------------------------------------------
1704# CONFIGURATION OPTION: -mode
1705# ----------------------------------------------------------------------
1706itcl::configbody Rappture::VtkHeightmapViewer::mode {
1707    switch -- $itk_option(-mode) {
1708        "heightmap" {
1709            set _settings(isHeightmap) 1
1710        }
1711        "contour" {
1712            set _settings(isHeightmap) 0
1713        }
1714        default {
1715            error "unknown mode settings \"$itk_option(-mode)\""
1716        }
1717    }
1718    AdjustSetting isHeightmap
1719}
1720
1721# ----------------------------------------------------------------------
1722# CONFIGURATION OPTION: -plotbackground
1723# ----------------------------------------------------------------------
1724itcl::configbody Rappture::VtkHeightmapViewer::plotbackground {
1725    if { [isconnected] } {
1726        set rgb [Color2RGB $itk_option(-plotbackground)]
1727        SendCmd "screen bgcolor $rgb"
1728        $itk_component(view) configure -background $itk_option(-plotbackground)
1729    }
1730}
1731
1732# ----------------------------------------------------------------------
1733# CONFIGURATION OPTION: -plotforeground
1734# ----------------------------------------------------------------------
1735itcl::configbody Rappture::VtkHeightmapViewer::plotforeground {
1736    if { [isconnected] } {
1737        set rgb [Color2RGB $itk_option(-plotforeground)]
1738        SendCmd "dataset color $rgb"
1739        SendCmd "axis color all $rgb"
1740    }
1741}
1742
1743itcl::body Rappture::VtkHeightmapViewer::limits { dataobj } {
1744    lappend limits x [$dataobj limits x]
1745    lappend limits y [$dataobj limits y]
1746    lappend limits v [$dataobj limits v]
1747    return $limits
1748}
1749
1750itcl::body Rappture::VtkHeightmapViewer::BuildContourTab {} {
1751
1752    set fg [option get $itk_component(hull) font Font]
1753    #set bfg [option get $itk_component(hull) boldFont Font]
1754
1755    set inner [$itk_component(main) insert end \
1756        -title "Contour Settings" \
1757        -icon [Rappture::icon volume-on]]
1758    $inner configure -borderwidth 4
1759
1760    checkbutton $inner.legend \
1761        -text "Legend" \
1762        -variable [itcl::scope _settings(legendVisible)] \
1763        -command [itcl::code $this AdjustSetting legendVisible] \
1764        -font "Arial 9"
1765
1766    checkbutton $inner.wireframe \
1767        -text "Wireframe" \
1768        -variable [itcl::scope _settings(wireframe)] \
1769        -command [itcl::code $this AdjustSetting wireframe] \
1770        -font "Arial 9"
1771
1772    itk_component add lighting {
1773        checkbutton $inner.lighting \
1774            -text "Enable Lighting" \
1775            -variable [itcl::scope _settings(lighting)] \
1776            -command [itcl::code $this AdjustSetting lighting] \
1777            -font "Arial 9"
1778    } {
1779        ignore -font
1780    }
1781
1782    checkbutton $inner.edges \
1783        -text "Edges" \
1784        -variable [itcl::scope _settings(edges)] \
1785        -command [itcl::code $this AdjustSetting edges] \
1786        -font "Arial 9"
1787
1788    checkbutton $inner.outline \
1789        -text "Outline" \
1790        -variable [itcl::scope _settings(outline)] \
1791        -command [itcl::code $this AdjustSetting outline] \
1792        -font "Arial 9"
1793
1794    checkbutton $inner.stretch \
1795        -text "Stretch to fit" \
1796        -variable [itcl::scope _settings(stretchToFit)] \
1797        -command [itcl::code $this AdjustSetting stretchToFit] \
1798        -font "Arial 9"
1799
1800    label $inner.field_l -text "Field" -font "Arial 9"
1801    itk_component add field {
1802        Rappture::Combobox $inner.field -width 10 -editable no
1803    }
1804    bind $inner.field <<Value>> \
1805        [itcl::code $this AdjustSetting field]
1806
1807    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1808    itk_component add colormap {
1809        Rappture::Combobox $inner.colormap -width 10 -editable no
1810    }
1811    $inner.colormap choices insert end \
1812        "BCGYR"              "BCGYR"            \
1813        "BGYOR"              "BGYOR"            \
1814        "blue"               "blue"             \
1815        "blue-to-brown"      "blue-to-brown"    \
1816        "blue-to-orange"     "blue-to-orange"   \
1817        "blue-to-grey"       "blue-to-grey"     \
1818        "green-to-magenta"   "green-to-magenta" \
1819        "greyscale"          "greyscale"        \
1820        "nanohub"            "nanohub"          \
1821        "rainbow"            "rainbow"          \
1822        "spectral"           "spectral"         \
1823        "ROYGB"              "ROYGB"            \
1824        "RYGCB"              "RYGCB"            \
1825        "brown-to-blue"      "brown-to-blue"    \
1826        "grey-to-blue"       "grey-to-blue"     \
1827        "orange-to-blue"     "orange-to-blue"   \
1828        "none"               "none"
1829
1830    $itk_component(colormap) value "BCGYR"
1831    bind $inner.colormap <<Value>> \
1832        [itcl::code $this AdjustSetting colormap]
1833
1834    label $inner.isolinecolor_l -text "Isolines" -font "Arial 9"
1835    itk_component add isolinecolor {
1836        Rappture::Combobox $inner.isolinecolor -width 10 -editable no
1837    }
1838    $inner.isolinecolor choices insert end \
1839        "black"              "black"            \
1840        "blue"               "blue"             \
1841        "cyan"               "cyan"             \
1842        "green"              "green"            \
1843        "grey"               "grey"             \
1844        "magenta"            "magenta"          \
1845        "orange"             "orange"           \
1846        "red"                "red"              \
1847        "white"              "white"            \
1848        "none"               "none"
1849
1850    $itk_component(isolinecolor) value "black"
1851    bind $inner.isolinecolor <<Value>> \
1852        [itcl::code $this AdjustSetting isolineColor]
1853
1854    label $inner.background_l -text "Background" -font "Arial 9"
1855    itk_component add background {
1856        Rappture::Combobox $inner.background -width 10 -editable no
1857    }
1858    $inner.background choices insert end \
1859        "black"              "black"            \
1860        "white"              "white"            \
1861        "grey"               "grey"             
1862
1863    $itk_component(background) value "white"
1864    bind $inner.background <<Value>> [itcl::code $this AdjustSetting background]
1865
1866    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1867    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1868        -variable [itcl::scope _settings(heightmapOpacity)] \
1869        -width 10 \
1870        -showvalue off \
1871        -command [itcl::code $this AdjustSetting heightmapOpacity]
1872
1873    label $inner.scale_l -text "Scale" -font "Arial 9"
1874    ::scale $inner.scale -from 0 -to 100 -orient horizontal \
1875        -variable [itcl::scope _settings(heightmapScale)] \
1876        -width 10 \
1877        -showvalue off \
1878        -command [itcl::code $this AdjustSetting heightmapScale]
1879
1880    blt::table $inner \
1881        0,0 $inner.colormap_l -anchor w -pady 2  \
1882        0,1 $inner.colormap   -anchor w -pady 2 -fill x  \
1883        1,0 $inner.isolinecolor_l  -anchor w -pady 2  \
1884        1,1 $inner.isolinecolor    -anchor w -pady 2 -fill x  \
1885        2,0 $inner.background_l -anchor w -pady 2 \
1886        2,1 $inner.background -anchor w -pady 2  -fill x \
1887        4,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1888        5,0 $inner.wireframe  -anchor w -pady 2 -cspan 2\
1889        6,0 $inner.lighting   -anchor w -pady 2 -cspan 2 \
1890        7,0 $inner.edges      -anchor w -pady 2 -cspan 2 \
1891        8,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1892        9,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
1893        10,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
1894        11,0 $inner.opacity_l -anchor w -pady 2 \
1895        11,1 $inner.opacity   -fill x   -pady 2 \
1896        12,0 $inner.scale_l   -anchor w -pady 2 -cspan 2 \
1897        12,1 $inner.scale     -fill x   -pady 2 -cspan 2 \
1898
1899    if { [array size _fields] > 1 } {
1900        blt::table $inner \
1901            3,0 $inner.field_l   -anchor w -pady 2 \
1902            3,1 $inner.field     -anchor w -pady 2 -fill x
1903    }
1904    blt::table configure $inner r* c* -resize none
1905    blt::table configure $inner r13 c1 -resize expand
1906}
1907
1908itcl::body Rappture::VtkHeightmapViewer::BuildAxisTab {} {
1909
1910    set fg [option get $itk_component(hull) font Font]
1911    #set bfg [option get $itk_component(hull) boldFont Font]
1912
1913    set inner [$itk_component(main) insert end \
1914        -title "Axis Settings" \
1915        -icon [Rappture::icon axis1]]
1916    $inner configure -borderwidth 4
1917
1918    checkbutton $inner.visible \
1919        -text "Axes" \
1920        -variable [itcl::scope _settings(axisVisible)] \
1921        -command [itcl::code $this AdjustSetting axisVisible] \
1922        -font "Arial 9"
1923    checkbutton $inner.labels \
1924        -text "Axis Labels" \
1925        -variable [itcl::scope _settings(axisLabels)] \
1926        -command [itcl::code $this AdjustSetting axisLabels] \
1927        -font "Arial 9"
1928    label $inner.grid_l -text "Grid" -font "Arial 9"
1929    checkbutton $inner.xgrid \
1930        -text "X" \
1931        -variable [itcl::scope _settings(axisXGrid)] \
1932        -command [itcl::code $this AdjustSetting axisXGrid] \
1933        -font "Arial 9"
1934    checkbutton $inner.ygrid \
1935        -text "Y" \
1936        -variable [itcl::scope _settings(axisYGrid)] \
1937        -command [itcl::code $this AdjustSetting axisYGrid] \
1938        -font "Arial 9"
1939    checkbutton $inner.zgrid \
1940        -text "Z" \
1941        -variable [itcl::scope _settings(axisZGrid)] \
1942        -command [itcl::code $this AdjustSetting axisZGrid] \
1943        -font "Arial 9"
1944    checkbutton $inner.minorticks \
1945        -text "Minor Ticks" \
1946        -variable [itcl::scope _settings(axisMinorTicks)] \
1947        -command [itcl::code $this AdjustSetting axisMinorTicks] \
1948        -font "Arial 9"
1949
1950
1951    label $inner.mode_l -text "Mode" -font "Arial 9"
1952
1953    itk_component add axisflymode {
1954        Rappture::Combobox $inner.mode -width 10 -editable no
1955    }
1956    $inner.mode choices insert end \
1957        "static_triad"    "static" \
1958        "closest_triad"   "closest" \
1959        "furthest_triad"  "furthest" \
1960        "outer_edges"     "outer"         
1961    $itk_component(axisflymode) value "static"
1962    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisFlymode]
1963
1964    blt::table $inner \
1965        0,0 $inner.visible -anchor w -cspan 4 \
1966        1,0 $inner.labels  -anchor w -cspan 4 \
1967        2,0 $inner.minorticks  -anchor w -cspan 4 \
1968        4,0 $inner.grid_l  -anchor w \
1969        4,1 $inner.xgrid   -anchor w \
1970        4,2 $inner.ygrid   -anchor w \
1971        4,3 $inner.zgrid   -anchor w \
1972        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1973        5,1 $inner.mode    -fill x -cspan 3
1974
1975    blt::table configure $inner r* c* -resize none
1976    blt::table configure $inner r7 c6 -resize expand
1977    blt::table configure $inner r3 -height 0.125i
1978}
1979
1980
1981itcl::body Rappture::VtkHeightmapViewer::BuildCameraTab {} {
1982    set inner [$itk_component(main) insert end \
1983        -title "Camera Settings" \
1984        -icon [Rappture::icon camera]]
1985    $inner configure -borderwidth 4
1986
1987    set labels { qx qy qz qw xpan ypan zoom }
1988    set row 0
1989    foreach tag $labels {
1990        label $inner.${tag}label -text $tag -font "Arial 9"
1991        entry $inner.${tag} -font "Arial 9"  -bg white \
1992            -textvariable [itcl::scope _view($tag)]
1993        bind $inner.${tag} <KeyPress-Return> \
1994            [itcl::code $this camera set ${tag}]
1995        blt::table $inner \
1996            $row,0 $inner.${tag}label -anchor e -pady 2 \
1997            $row,1 $inner.${tag} -anchor w -pady 2
1998        blt::table configure $inner r$row -resize none
1999        incr row
2000    }
2001    checkbutton $inner.ortho \
2002        -text "Orthographic Projection" \
2003        -variable [itcl::scope _view(ortho)] \
2004        -command [itcl::code $this camera set ortho] \
2005        -font "Arial 9"
2006    blt::table $inner \
2007            $row,0 $inner.ortho -columnspan 2 -anchor w -pady 2
2008    blt::table configure $inner r$row -resize none
2009    incr row
2010
2011    blt::table configure $inner c0 c1 -resize none
2012    blt::table configure $inner c2 -resize expand
2013    blt::table configure $inner r$row -resize expand
2014}
2015
2016#
2017#  camera --
2018#
2019itcl::body Rappture::VtkHeightmapViewer::camera {option args} {
2020    switch -- $option {
2021        "show" {
2022            puts [array get _view]
2023        }
2024        "set" {
2025            set who [lindex $args 0]
2026            set x $_view($who)
2027            set code [catch { string is double $x } result]
2028            if { $code != 0 || !$result } {
2029                return
2030            }
2031            switch -- $who {
2032                "ortho" {
2033                    if {$_view(ortho)} {
2034                        SendCmd "camera mode ortho"
2035                    } else {
2036                        SendCmd "camera mode persp"
2037                    }
2038                }
2039                "xpan" - "ypan" {
2040                    PanCamera
2041                }
2042                "qx" - "qy" - "qz" - "qw" {
2043                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2044                    $_arcball quaternion $q
2045                    EventuallyRotate $q
2046                }
2047                "zoom" {
2048                    SendCmd "camera zoom $_view(zoom)"
2049                }
2050            }
2051        }
2052    }
2053}
2054
2055itcl::body Rappture::VtkHeightmapViewer::GetVtkData { args } {
2056    set bytes ""
2057    foreach dataobj [get] {
2058        foreach comp [$dataobj components] {
2059            set tag $dataobj-$comp
2060            set contents [ConvertToVtkData $dataobj $comp]
2061            #set contents [$dataobj vtkdata $comp]
2062            append bytes "$contents\n\n"
2063        }
2064    }
2065    return [list .vtk $bytes]
2066}
2067
2068itcl::body Rappture::VtkHeightmapViewer::GetImage { args } {
2069    if { [image width $_image(download)] > 0 &&
2070         [image height $_image(download)] > 0 } {
2071        set bytes [$_image(download) data -format "jpeg -quality 100"]
2072        set bytes [Rappture::encoding::decode -as b64 $bytes]
2073        return [list .jpg $bytes]
2074    }
2075    return ""
2076}
2077
2078itcl::body Rappture::VtkHeightmapViewer::BuildDownloadPopup { popup command } {
2079    Rappture::Balloon $popup \
2080        -title "[Rappture::filexfer::label downloadWord] as..."
2081    set inner [$popup component inner]
2082    label $inner.summary -text "" -anchor w
2083    radiobutton $inner.vtk_button -text "VTK data file" \
2084        -variable [itcl::scope _downloadPopup(format)] \
2085        -font "Arial 9 " \
2086        -value vtk 
2087    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2088    radiobutton $inner.image_button -text "Image File" \
2089        -variable [itcl::scope _downloadPopup(format)] \
2090        -font "Arial 9 " \
2091        -value image
2092    Rappture::Tooltip::for $inner.image_button \
2093        "Save as digital image."
2094
2095    button $inner.ok -text "Save" \
2096        -highlightthickness 0 -pady 2 -padx 3 \
2097        -command $command \
2098        -compound left \
2099        -image [Rappture::icon download]
2100
2101    button $inner.cancel -text "Cancel" \
2102        -highlightthickness 0 -pady 2 -padx 3 \
2103        -command [list $popup deactivate] \
2104        -compound left \
2105        -image [Rappture::icon cancel]
2106
2107    blt::table $inner \
2108        0,0 $inner.summary -cspan 2  \
2109        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2110        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2111        4,1 $inner.cancel -width .9i -fill y \
2112        4,0 $inner.ok -padx 2 -width .9i -fill y
2113    blt::table configure $inner r3 -height 4
2114    blt::table configure $inner r4 -pady 4
2115    raise $inner.image_button
2116    $inner.vtk_button invoke
2117    return $inner
2118}
2119
2120itcl::body Rappture::VtkHeightmapViewer::SetObjectStyle { dataobj comp } {
2121    # Parse style string.
2122    set tag $dataobj-$comp
2123    array set style {
2124        -color BCGYR
2125        -edges 0
2126        -edgecolor black
2127        -lighting 1
2128        -linewidth 1.0
2129        -levels 10
2130        -visible 1
2131    }
2132    if { $_currentColormap == "" } {
2133        set stylelist [$dataobj style $comp]
2134        if { $stylelist != "" } {
2135            array set style $stylelist
2136            set stylelist [array get style]
2137            SetCurrentColormap $stylelist
2138        }
2139        $itk_component(colormap) value $style(-color)
2140    }
2141    set _numContours $style(-levels)
2142    set scale [GetHeightmapScale]
2143    SendCmd "heightmap add numcontours $_numContours $scale $tag"
2144    set _comp2scale($tag) $_settings(heightmapScale)
2145    SendCmd "heightmap edges $_settings(edges) $tag"
2146    SendCmd "heightmap wireframe $_settings(wireframe) $tag"
2147    SendCmd "heightmap colormap $_currentColormap $tag"
2148}
2149
2150itcl::body Rappture::VtkHeightmapViewer::IsValidObject { dataobj } {
2151    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2152        return 0
2153    }
2154    return 1
2155}
2156
2157# ----------------------------------------------------------------------
2158# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2159#
2160# Invoked automatically whenever the "legend" command comes in from
2161# the rendering server.  Indicates that binary image data with the
2162# specified <size> will follow.
2163# ----------------------------------------------------------------------
2164itcl::body Rappture::VtkHeightmapViewer::ReceiveLegend { colormap title min max size } {
2165    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2166    set _title $title
2167    regsub {\(mag\)} $title "" _title
2168    if { [isconnected] } {
2169        set bytes [ReceiveBytes $size]
2170        if { ![info exists _image(legend)] } {
2171            set _image(legend) [image create photo]
2172        }
2173        $_image(legend) configure -data $bytes
2174        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2175        if { [catch {DrawLegend $_title} errs] != 0 } {
2176            global errorInfo
2177            puts stderr "errs=$errs errorInfo=$errorInfo"
2178        }
2179    }
2180}
2181
2182#
2183# DrawLegend --
2184#
2185#       Draws the legend in it's own canvas which resides to the right
2186#       of the contour plot area.
2187#
2188itcl::body Rappture::VtkHeightmapViewer::DrawLegend { name } {
2189    set c $itk_component(view)
2190    set w [winfo width $c]
2191    set h [winfo height $c]
2192    set font "Arial 8"
2193    set lineht [font metrics $font -linespace]
2194   
2195    if { $name == "component" } {
2196        set title ""
2197    } else {
2198        if { [info exists _fields($name)] } {
2199            foreach { title units } $_fields($name) break
2200            if { $units != "" } {
2201                set title [format "%s (%s)" $title $units]
2202            }
2203        } else {
2204            set title $name
2205        }
2206    }
2207    set x [expr $w - 2]
2208    if { !$_settings(legendVisible) } {
2209        $c delete legend
2210        return
2211    }
2212    if { [$c find withtag "legend"] == "" } {
2213        set y 2
2214        # If there's a legend title, create a text item for the title.
2215        if { $title != "" } {
2216            $c create text $x $y \
2217                -anchor ne \
2218                -fill $itk_option(-plotforeground) -tags "title legend" \
2219                -font $font
2220            incr y $lineht
2221        }
2222        $c create text $x $y \
2223            -anchor ne \
2224            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2225            -font $font
2226        incr y $lineht
2227        $c create image $x $y \
2228            -anchor ne \
2229            -image $_image(legend) -tags "colormap legend"
2230        $c create text $x [expr {$h-2}] \
2231            -anchor se \
2232            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2233            -font $font
2234        #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2235        $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2236        $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2237    }
2238    $c delete isoline
2239    set x2 $x
2240    set iw [image width $_image(legend)]
2241    set ih [image height $_image(legend)]
2242    set x1 [expr $x2 - ($iw*12)/10]
2243    set color [$itk_component(isolinecolor) value]
2244    # Draw the isolines on the legend.
2245    if { $color != "none"  && $_numContours > 0 } {
2246        set pixels [blt::vector create \#auto]
2247        set values [blt::vector create \#auto]
2248        set range [image height $_image(legend)]
2249        # Order of pixels is max to min (max is at top of legend).
2250        $pixels seq $ih 0 $_numContours
2251        set offset [expr 2 + $lineht]
2252        # If there's a legend title, increase the offset by the line height.
2253        if { $title != "" } {
2254            incr offset $lineht
2255        }
2256        $pixels expr {round($pixels + $offset)}
2257        # Order of values is min to max.
2258        foreach { vmin vmax } $_limits(v) break
2259        $values seq $vmin $vmax $_numContours
2260        set tags "isoline legend"
2261        foreach pos [$pixels range 0 end] value [$values range end 0] {
2262            set y1 [expr int($pos)]
2263            set id [$c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags]
2264            $c bind $id <Enter> [itcl::code $this EnterIsoline %x %y $value]
2265            $c bind $id <Leave> [itcl::code $this LeaveIsoline]
2266        }
2267        blt::vector destroy $pixels $values
2268    }
2269
2270    $c bind title <ButtonPress> [itcl::code $this Combo post]
2271    $c bind title <Enter> [itcl::code $this Combo activate]
2272    $c bind title <Leave> [itcl::code $this Combo deactivate]
2273    # Reset the item coordinates according the current size of the plot.
2274    $c itemconfigure title -text $title
2275    if { [info exists _limits(v)] } {
2276        foreach { vmin vmax } $_limits(v) break
2277        $c itemconfigure vmin -text [format %g $vmin]
2278        $c itemconfigure vmax -text [format %g $vmax]
2279    }
2280    set y 2
2281    # If there's a legend title, move the title to the correct position
2282    if { $title != "" } {
2283        $c coords title $x $y
2284        incr y $lineht
2285    }
2286    $c coords vmax $x $y
2287    incr y $lineht
2288    $c coords colormap $x $y
2289    $c coords vmin $x [expr {$h - 2}]
2290}
2291
2292#
2293# EnterIsoline --
2294#
2295itcl::body Rappture::VtkHeightmapViewer::EnterIsoline { x y value } {
2296    SetIsolineTip $x $y $value
2297}
2298
2299#
2300# LeaveIsoline --
2301#
2302itcl::body Rappture::VtkHeightmapViewer::LeaveIsoline { } {
2303    Rappture::Tooltip::tooltip cancel
2304    .rappturetooltip configure -icon ""
2305}
2306
2307#
2308# SetIsolineTip --
2309#
2310itcl::body Rappture::VtkHeightmapViewer::SetIsolineTip { x y value } {
2311    set c $itk_component(view)
2312    set w [winfo width $c]
2313    set h [winfo height $c]
2314    set font "Arial 8"
2315    set lineht [font metrics $font -linespace]
2316   
2317    if { [info exists _fields($_title)] } {
2318        foreach { title units } $_fields($_title) break
2319        if { $units != "" } {
2320            set title [format "%s (%s)" $title $units]
2321        }
2322    } else {
2323        set title $_title
2324    }
2325    set imgHeight [image height $_image(legend)]
2326    set coords [$c coords colormap]
2327    set imgX [expr $w - [image width $_image(legend)] - 2]
2328    set imgY [expr $y - 2 * ($lineht + 2)]
2329
2330    .rappturetooltip configure -icon ""
2331
2332    # Compute the value of the point
2333    set tipx [expr $x + 15]
2334    set tipy [expr $y - 5]
2335    Rappture::Tooltip::text $c "Isoline $value"
2336    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2337}
2338
2339
2340#
2341# EnterLegend --
2342#
2343itcl::body Rappture::VtkHeightmapViewer::EnterLegend { x y } {
2344    SetLegendTip $x $y
2345}
2346
2347#
2348# MotionLegend --
2349#
2350itcl::body Rappture::VtkHeightmapViewer::MotionLegend { x y } {
2351    Rappture::Tooltip::tooltip cancel
2352    set c $itk_component(view)
2353    SetLegendTip $x $y
2354}
2355
2356#
2357# LeaveLegend --
2358#
2359itcl::body Rappture::VtkHeightmapViewer::LeaveLegend { } {
2360    Rappture::Tooltip::tooltip cancel
2361    .rappturetooltip configure -icon ""
2362}
2363
2364#
2365# SetLegendTip --
2366#
2367itcl::body Rappture::VtkHeightmapViewer::SetLegendTip { x y } {
2368    set c $itk_component(view)
2369    set w [winfo width $c]
2370    set h [winfo height $c]
2371    set font "Arial 8"
2372    set lineht [font metrics $font -linespace]
2373   
2374    set imgHeight [image height $_image(legend)]
2375    set coords [$c coords colormap]
2376    set imgX [expr $w - [image width $_image(legend)] - 2]
2377    set imgY [expr $y - 2 * ($lineht + 2)]
2378
2379    if { [info exists _fields($_title)] } {
2380        foreach { title units } $_fields($_title) break
2381        if { $units != "" } {
2382            set title [format "%s (%s)" $title $units]
2383        }
2384    } else {
2385        set title $_title
2386    }
2387    # Make a swatch of the selected color
2388    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2389        #puts stderr "out of range: $imgY"
2390        return
2391    }
2392    if { ![info exists _image(swatch)] } {
2393        set _image(swatch) [image create photo -width 24 -height 24]
2394    }
2395    set color [eval format "\#%02x%02x%02x" $pixel]
2396    $_image(swatch) put black  -to 0 0 23 23
2397    $_image(swatch) put $color -to 1 1 22 22
2398    .rappturetooltip configure -icon $_image(swatch)
2399
2400    # Compute the value of the point
2401    if { [info exists _limits(v)] } {
2402        foreach { vmin vmax } $_limits(v) break
2403        set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2404        set value [expr $t * ($vmax - $vmin) + $vmin]
2405    } else {
2406        set value 0.0
2407    }
2408    set tipx [expr $x + 15]
2409    set tipy [expr $y - 5]
2410    Rappture::Tooltip::text $c "$title $value"
2411    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2412}
2413
2414# ----------------------------------------------------------------------
2415# USAGE: _dropdown post
2416# USAGE: _dropdown unpost
2417# USAGE: _dropdown select
2418#
2419# Used internally to handle the dropdown list for this combobox.  The
2420# post/unpost options are invoked when the list is posted or unposted
2421# to manage the relief of the controlling button.  The select option
2422# is invoked whenever there is a selection from the list, to assign
2423# the value back to the gauge.
2424# ----------------------------------------------------------------------
2425itcl::body Rappture::VtkHeightmapViewer::Combo {option} {
2426    set c $itk_component(view)
2427    switch -- $option {
2428        post {
2429            foreach { x1 y1 x2 y2 } [$c bbox title] break
2430            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2431            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2432            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2433            tk_popup $itk_component(fieldmenu) $x $y
2434        }
2435        activate {
2436            $c itemconfigure title -fill red
2437        }
2438        deactivate {
2439            $c itemconfigure title -fill $itk_option(-plotforeground)
2440        }
2441        invoke {
2442            $itk_component(field) value $_curFldName
2443            AdjustSetting field
2444        }
2445        default {
2446            error "bad option \"$option\": should be post, unpost, select"
2447        }
2448    }
2449}
2450
2451itcl::body Rappture::VtkHeightmapViewer::GetHeightmapScale {} {
2452    if {  $_settings(isHeightmap) } {
2453        set val $_settings(heightmapScale)
2454        set sval [expr { $val >= 50 ? double($val)/50.0 : 1.0/(2.0-(double($val)/50.0)) }]
2455        return $sval
2456    }
2457    set sval 0
2458}
2459
2460itcl::body Rappture::VtkHeightmapViewer::ResetColormap { color } {
2461    array set style {
2462        -color BCGYR
2463        -levels 10
2464        -opacity 1.0
2465    }
2466    if { [info exists _colormap($_currentColormap)] } {
2467        array set style $_colormap($_currentColormap)
2468    }
2469    set style(-color) $color
2470    SetCurrentColormap [array get style]
2471}
2472
Note: See TracBrowser for help on using the repository browser.