source: branches/1.3/gui/scripts/vtksurfaceviewer.tcl @ 4766

Last change on this file since 4766 was 4766, checked in by ldelgass, 6 years ago

merge r4765 from trunk

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