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

Last change on this file since 5181 was 5181, checked in by ldelgass, 5 years ago

merge r5157:5158 from trunk (surfaceviewer)

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